title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
How to call a SOAP webservice with a simple String (xml in string format)
<p>I have this string representing a XML: </p> <pre><code>String soapCall="&lt;soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"&gt; &lt;soap:Body xmlns:m="http://www.example.org/stock"&gt; &lt;m:addDownloadParams&gt; &lt;m:idApp&gt;"; soapCall+=idApp; soapCall+="&lt;m:versionApp&gt;"; soapCall+=versonApp; soapCall+="&lt;/m:versionApp&gt; &lt;m:os&gt;Android&lt;/m:os&gt; &lt;/m:addDownloadParams&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt;"; </code></pre> <p>And i have this soap webservice: </p> <pre><code>http://stats.mywebsite.com/ws/adddownload </code></pre> <p>Now, i need to pass that string to that soap webservice on android, but i dont know the way, i know i need to use httpcliente:</p> <pre><code>HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); </code></pre> <p>but i dont know how to call the soapwebservice with that string.</p> <p>Anyone haves a code example? i can't find it on google. I dont want to use a library, i need to do it by myself</p> <p>Thanks</p> <p><strong>EDIT: this is the code now, but it is not working, i get error 500 internal server error:</strong></p> <pre><code> public static byte[] addDownloadIntoServer(){ byte[] result = null; String SERVER_URL="http://stats.mywebsite.com/ws/server.php"; String SOAP_ACTION="addDownload"; String body="&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://stats.mobincube.com/\"&gt;&lt;SOAP-ENV:Body&gt;&lt;ns1:addDownloadParams&gt;"; body+="&lt;idApp&gt;" +SectionManager.instance.app_id+"&lt;/idApp&gt;"; body+="&lt;versionApp&gt;"+SectionManager.instance.app_version+"&lt;/versionApp&gt;"; body+="&lt;source&gt;android&lt;/source&gt; &lt;os&gt;Android&lt;/os&gt; &lt;/ns1:addDownloadParams&gt;&lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;"; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 15000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 35000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); /* * httpclient.getCredentialsProvider().setCredentials( new * AuthScope("os.icloud.com", 80, null, "Digest"), new * UsernamePasswordCredentials(username, password)); */ HttpPost httppost = new HttpPost(SERVER_URL ); httppost.setHeader("soapaction", SOAP_ACTION); httppost.setHeader("Content-Type", "text/xml; charset=utf-8"); System.out.println("executing request" + httppost.getRequestLine()); //now create a soap request message as follows: final StringBuffer soap = new StringBuffer(); soap.append("\n"); soap.append(""); // this is a sample data..you have create your own required data BEGIN soap.append(" \n"); soap.append(" \n"); soap.append("" + body); soap.append(" \n"); soap.append(" \n"); /* soap.append(body); */ // END of MEssage Body soap.append(""); Log.i("SOAP Request", ""+soap.toString()); // END of full SOAP request message try { HttpEntity entity = new StringEntity(soap.toString(),HTTP.UTF_8); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);// calling server HttpEntity r_entity = response.getEntity(); //get response Log.i("Reponse Header", "Begin..."); // response headers Log.i("Reponse Header", "StatusLine:"+response.getStatusLine()); Header[] headers = response.getAllHeaders(); for(Header h:headers) Log.i("Reponse Header",h.getName() + ": " + h.getValue()); Log.i("Reponse Header", "END..."); if (r_entity != null) { result = new byte[(int) r_entity.getContentLength()]; if (r_entity.isStreaming()) { DataInputStream is = new DataInputStream( r_entity.getContent()); is.readFully(result); } } }catch (Exception E) { Log.i("Exception While Connecting", ""+E.getMessage()); E.printStackTrace(); } httpclient.getConnectionManager().shutdown(); //shut down the connection return result; } </code></pre>
0
2,095
ExpressJS/Typescript - Unabe to Retrieve ZoneAwarePromise value?
<p><strong>UPDATE 1 STARTS</strong></p> <p>Issue is that I am not able to get all the cities and locations in sequence once I draw the FormArray again and this is becuase of the loop only. Anyways, I am new to TS, you might understand much better. Thanks again.</p> <pre><code>import { Component, OnInit, NgZone } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FormBuilder, FormGroup, FormArray, Validators, FormControl } from '@angular/forms'; import { CustomValidators } from 'ng2-validation'; import { SharedService } from '../../../layouts/shared-service'; import { MdSnackBar, MdSnackBarConfig, MdDialog, MdDialogRef, MdDialogConfig } from '@angular/material'; // Added employee services import { VehiclePlanService } from '../../../service/vehicle-plan.service'; import { PlanService } from '../../../service/plan.service'; import { LocationService } from '../../../service/location.service'; import { VehicleMakeService } from '../../../service/vehicle-make.service'; import { CommonService } from '../../../service/common.service'; // call the common services import { PlanInterface } from './plans.interface'; import 'rxjs/add/operator/toPromise'; declare var $: any; @Component({ selector: 'app-vehicle-plan', templateUrl: './vehicle-plan.component.html', styleUrls: ['./vehicle-plan.component.scss'] }) export class VehiclePlanComponent implements OnInit { pageTitle: "Vehicle Plan"; _id : string = this.route.snapshot.params['id']; public form: FormGroup; plansElement = {}; sessionData = {}; activePlans = {}; activeMake = {}; loc = {}; city = {}; locationNames = {}; activePlanKey = []; activeMakeKey = []; locKey = []; cityKey = []; value = []; planVals = []; securityDeposit : string ; fuleLevel : string; bookinH : string; bookingCycle : string; freeKm : string; grace : string; resVP: string; planDetails: string; vehicleDetails: string; vehicleID: string; planID: string; planName: string ; makeName : string; constructor( private fb: FormBuilder, private _sharedService: SharedService, private router: Router, private route: ActivatedRoute, public snackBar: MdSnackBar, public dialog: MdDialog, private vpService: VehiclePlanService, private plan: PlanService, private locationService: LocationService, private vmService: VehicleMakeService, private commonService : CommonService ) { this._sharedService.emitChange(this.pageTitle); this.commonService.getSession().then((res) =&gt; { this.sessionData = res['data']; }); } ngOnInit() { this.getActivePlans(); this.getActiveVehicleMake(); this.getCityForPlan(); this.getLocForPlan(); this.planName= '' ; this.makeName = ''; this.form = this.fb.group({ plan_name: [null, Validators.required], vehicle_make: [null, Validators.required], rate_per_additional_km: [null, Validators.required], rate_per_plan: [null, Validators.required], planArray: this.fb.array([ this.initPlans([]), ]) }) } // Operate vehiclemake to add / edit actionVP(model: PlanInterface) { let formData = model["value"]; var pa = model["value"].planArray; for(let i=0; i&lt;pa.length;i++) { if(pa[i].location_name != null) { let vp = { 'vehicle_make': [{ "id" : formData.vehicle_make, "make_name" : this.vehicleDetails }], 'plan_name': [{ "id" : formData.plan_name, "plan_name" : this.planDetails }], 'location': [{ "id" : "1", "location_name" : pa[i].location_name, "city" : pa[i].city, "lat" : "0.00", "long" : "0.00" }], 'plan_rate': (pa[i].rate_plan != null) ? pa[i].rate_plan : formData.rate_per_plan, 'total_free_km': (pa[i].total_free_km != null) ? pa[i].total_free_km : this.freeKm, 'additional_km_charges': (pa[i].additional_km_charges != null) ? pa[i].additional_km_charges : formData.rate_per_additional_km, 'minimum_hours': (pa[i].minimum_hours != null) ? pa[i].minimum_hours : this.bookinH, 'booking_cycle': (pa[i].booking_cycle != null) ? pa[i].booking_cycle : this.bookingCycle, 'rate_fuel_level': (pa[i].rate_fuel_level != null) ? pa[i].rate_fuel_level : this.fuleLevel, 'grace_period': (pa[i].grace_period != null) ? pa[i].grace_period : this.grace, 'security_deposit': (pa[i].security_deposit != null) ? pa[i].security_deposit : this.securityDeposit, "organization" : [{ "id" : "1", "name" : "Driven" }], 'modified_date': new Date() }; // SAVE DATA START if(this.route.snapshot.params['id']) { this.updateVP(this.route.snapshot.params['id'], vp); } else { this.saveVP(vp); } // SAVE DATA END } } } // Insert data to vehiclemake saveVP(vp) { // Build data JSON vp['created_date'] = new Date(); this.vpService.saveVehiclePlan(vp).then((result) =&gt; { let id = result['data']['_id']; this.openSnackBar("Saved vehicle plan successfully", ""); this.router.navigate(['/driven/vehicle-plan']); }, (err) =&gt; { this.openSnackBar("Something went wrong! vehicle plan not saved", ""); console.log(err); }); } // Update vehiclemake details updateVP(id, vp) { this.vpService.updateVehiclePlan(id, vp).then((result) =&gt; { let id = result['data']['_id']; this.openSnackBar("Updated vehicle plan successfully", ""); this.router.navigate(['/driven/vehicle-plan']); }, (err) =&gt; { this.openSnackBar("Something went wrong! vehicle plan not updated", ""); console.log(err); }); } // Get the all active plans getActivePlans() { this.plan.getActivePlans().then((res) =&gt; { if(res['status'] == 'success'){ this.activePlans = res['data']; this.activePlanKey = Object.keys(this.activePlans); }else{ this.openSnackBar(res['data']['message'], ""); } }, (err) =&gt; { console.log(err); }); } // Get the all active plans getActiveVehicleMake() { this.vmService.getActiveVehicleMake().then((res) =&gt; { if(res['status'] == 'success'){ this.activeMake = res['data']; this.activeMakeKey = Object.keys(this.activeMake); }else{ this.openSnackBar(res['data']['message'], ""); } }, (err) =&gt; { console.log(err); }); } // Get the all Locations for plans gruped by city getCityForPlan() { this.locationService.getCityForPlan().then((res) =&gt; { if(res['status'] == 'success'){ this.city = res['data']; this.cityKey = Object.keys(this.city); }else{ this.openSnackBar(res['data']['message'], ""); } }, (err) =&gt; { console.log(err); }); } async getLocForPlan() { let res = await this.locationService.getLocForPlan(); if(res['status'] == 'success') { this.loc = res['data']; this.locKey = Object.keys(this.loc); this.addEditValues(); } else { this.openSnackBar(res['data']['message'], ""); } } // used to display the alert message openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } initPlans(planVals) { //console.log(planVals); return this.fb.group({ city_name: [planVals['city_name']], city : [planVals['city']], is_active: [planVals['is_active']], location_name: [planVals['location_name']], rate_plan: [planVals['rate_plan']], total_free_km: [planVals['total_free_km']], additional_km_charges: [planVals['additional_km_charges']], minimum_hours: [planVals['minimum_hours']], booking_cycle: [planVals['booking_cycle']], rate_fuel_level: [planVals['rate_fuel_level']], grace_period: [planVals['grace_period']], security_deposit: [planVals['security_deposit']] }); } addEditValues() { let len = this.locKey.length; const control = &lt;FormArray&gt;this.form.controls['planArray']; if(len) { control.removeAt(0); } for(let i=0;i&lt;len;i++) { // DEFAULT NULL this.planVals['city'] = null; this.planVals['location_name'] = null; this.planVals['is_active'] = null; this.planVals['rate_plan'] = null; this.planVals['total_free_km'] = null; this.planVals['additional_km_charges'] = null; this.planVals['minimum_hours'] = null; this.planVals['booking_cycle'] = null; this.planVals['rate_fuel_level'] = null; this.planVals['grace_period'] = null; this.planVals['security_deposit'] = null; // DEFAULT NULL this.planVals['city_name'] = this.loc[i]._id[0]; let lenInner = this.loc[i].locations.length; for(let k=0;k&lt;lenInner;k++) { if(this.loc[i].locations[k].is_active) { // UPDATED DATA FROM DB if(this.planID &amp;&amp; this.vehicleID) { this.planVals['city'] = this.loc[i].locations[k].city[0]; this.planVals['location_name'] = this.loc[i].locations[k].location_name; this.getVPDetails(this.planID,this.vehicleID,this.planVals['location_name'],this.planVals['city']).then((res: any) =&gt; { console.log(res); if(res['status'] == 'success') { if(k==0) { this.planVals['city_name'] = this.loc[i]._id[0]; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } // FROM DB this.planVals['rate_plan'] = res['data'][0]['plan_rate']; this.planVals['total_free_km'] = res['data'][0]['total_free_km']; this.planVals['additional_km_charges'] = res['data'][0]['additional_km_charges']; this.planVals['minimum_hours'] = res['data'][0]['minimum_hours']; this.planVals['booking_cycle'] = res['data'][0]['booking_cycle']; this.planVals['rate_fuel_level'] = res['data'][0]['rate_fuel_level']; this.planVals['grace_period'] = res['data'][0]['grace_period']; this.planVals['security_deposit'] = res['data'][0]['security_deposit']; // FROM DB this.planVals['city_name'] = null; this.planVals['is_active'] = this.loc[i].locations[k].is_active; this.planVals['city'] = this.loc[i].locations[k].city[0]; this.planVals['location_name'] = this.loc[i].locations[k].location_name; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } else { if(k==0) { this.planVals['city_name'] = this.loc[i]._id[0]; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } // BLANK DATA AT FIRST this.planVals['rate_plan'] = null; this.planVals['total_free_km'] = null; this.planVals['additional_km_charges'] = null; this.planVals['minimum_hours'] = null; this.planVals['booking_cycle'] = null; this.planVals['rate_fuel_level'] = null; this.planVals['grace_period'] = null; this.planVals['security_deposit'] = null; // BLANK DATA AT FIRST this.planVals['city_name'] = null; this.planVals['city'] = this.loc[i].locations[k].city[0]; this.planVals['is_active'] = this.loc[i].locations[k].is_active; this.planVals['location_name'] = this.loc[i].locations[k].location_name; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } }); } else { if(k==0) { this.planVals['city_name'] = this.loc[i]._id[0]; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } // BLANK DATA AT FIRST this.planVals['rate_plan'] = null; this.planVals['total_free_km'] = null; this.planVals['additional_km_charges'] = null; this.planVals['minimum_hours'] = null; this.planVals['booking_cycle'] = null; this.planVals['rate_fuel_level'] = null; this.planVals['grace_period'] = null; this.planVals['security_deposit'] = null; // BLANK DATA AT FIRST this.planVals['city_name'] = null; this.planVals['city'] = this.loc[i].locations[k].city[0]; this.planVals['is_active'] = this.loc[i].locations[k].is_active; this.planVals['location_name'] = this.loc[i].locations[k].location_name; control.push(this.initPlans(this.planVals)); //#### PUSH INTO FORMARRAY #### } } } } } removeFormArray() { this.planVals = []; const control = &lt;FormArray&gt;this.form.controls['planArray']; for (var i = control.length - 1; i &gt; 0; i--) { this.removeInput(i); } } removeInput(i: number) { const control = &lt;FormArray&gt;this.form.controls['planArray']; control.removeAt(i); } async getVPDetails(pid, vid, locname, cityname): Promise&lt;any&gt; { return await this.vpService.getVehiclePlansInfo({plan_id: pid, make_id: vid, loc: locname, city: cityname}); } // used to populate the default security deposit &amp; fule level selectVM(value){ this.vmService.showVehicleMake(value['value']).then((res) =&gt; { this.securityDeposit = res['data']['base_security_deposit']; this.fuleLevel = res['data']['rate_per_fuel_level']; this.makeName = value['value']; this.vehicleID = res['data']['_id']; this.vehicleDetails = res['data']['brand_name'] + ' ' + res['data']['make_name'] + ' ' + res['data']['model_name']; this.getVehiclePlan(); return false; }, (err) =&gt; { console.log(err); }); } // used to prepopulate the default value min booking h, h/ booking cycle, free km, grace time //bookinH : string; bookingCycle : string; freeKm : string; grace : string; selectPlan(value) { this.plan.getPlansInfo(value['value']).then((res) =&gt; { this.bookinH = res['data']['min_booking_hours']; this.bookingCycle = res['data']['hours_per_booking_cycle']; this.freeKm = res['data']['free_km_per_booking_cycle']; this.grace = res['data']['grace_period_in_hours']; this.planName = value['value']; this.planDetails = res['data']['plan_name']; this.planID = res['data']['_id']; this.getVehiclePlan(); return false; }, (err) =&gt; { console.log(err); }); } // get the all plans on change of plans and vehicle make getVehiclePlan(){ if(this.planName != '' &amp;&amp; this.makeName != '' ) { //const control = &lt;FormArray&gt;this.form.controls['planArray']; //control.controls = []; this.removeFormArray(); this.addEditValues(); } } // update the plan screen with default values updateDefaultValue(){ var rate_plan = $('.rate_per_plan').val(); var additional_km_charges = $('.rate_per_additional_km').val(); var security_deposit = this.securityDeposit; var grace_period = this.grace; var rate_fuel_level = this.fuleLevel; var booking_cycle = this.bookingCycle; var minimum_hours = this.bookinH; var total_free_km = this.freeKm; $('.security_deposit, .grace_period, .rate_fuel_level, .booking_cycle, .minimum_hours, .additional_km_charges, .total_free_km, .rate_plan').each(function(){ $('.security_deposit').val(security_deposit); $('.grace_period').val(grace_period); $('.rate_fuel_level').val(rate_fuel_level); $('.booking_cycle').val(booking_cycle); $('.minimum_hours').val(minimum_hours); $('.additional_km_charges').val(additional_km_charges); $('.total_free_km').val(total_free_km); $('.rate_plan').val(rate_plan); }); return false; } checkAllLoc(value){ var val = $('#'+value).val(); if(val == "true"){ $('.'+value).prop('checked', true); $('#'+value).val("false"); } else { $('.'+value).prop('checked', false); $('#'+value).val("true"); } } uncheckParent(value){ $('#'+value).prop('checked', false); $('#'+value).val("true"); } } </code></pre> <h2><strong>UPDATE 1 ENDS</strong></h2> <p>I am using TypeScript in MeanStack and using a function with <strong>async</strong> because it was not working in sequential order</p> <pre><code>// Calling Function (In Main.ts file) let rs = getVPDetails("2132"); // Function Definition (In Main.ts file) async getVPDetails(pid) { let res = await this.vpService.getPlansInfo({plan_id: pid}); return res; } // Middle Ware (IN service.ts file) getPlansInfo(data) { return new Promise((resolve, reject) =&gt; { this.http.post('/vehicle-plan/plan-info', data) .map(res =&gt; res.json()) .subscribe(res =&gt; { resolve(res); }, (err) =&gt; { reject(err); }); }); } </code></pre> <p>I am getting the exact value while returning res (in "return res;") as I require. But in rs (Where I call), I am getting a value like this:</p> <p>ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}</p> <p>In __zone_symbol__value I am having my data as I require but by no means I am able to access it. I know that I am breaking the Promise object but how can I resolve it exactly when I dont want to use then() in getVPDetails();</p> <p>Please let me know what am I missing OR how can I get the data I require. </p> <p>Thanks in advance.</p>
0
10,844
How to use QThread correctly in pyqt with moveToThread()?
<p>i read this article <a href="http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/" rel="noreferrer">How To Really, Truly Use QThreads; The Full Explanation</a>, it says instead of subclass qthread, and reimplement run(), one should use moveToThread to push a QObject onto QThread instance using moveToThread(QThread*)</p> <p>here is the c++ example, but i don't know how to convert it to python code.</p> <pre class="lang-cpp prettyprint-override"><code>class Worker : public QObject { Q_OBJECT QThread workerThread; public slots: void doWork(const QString &amp;parameter) { // ... emit resultReady(result); } signals: void resultReady(const QString &amp;result); }; class Controller : public QObject { Q_OBJECT QThread workerThread; public: Controller() { Worker *worker = new Worker; worker-&gt;moveToThread(&amp;workerThread); connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(this, SIGNAL(operate(QString)), worker, SLOT(doWork(QString))); connect(worker, SIGNAL(resultReady(QString)), this, SLOT(handleResults(QString))); workerThread.start(); } ~Controller() { workerThread.quit(); workerThread.wait(); } public slots: void handleResults(const QString &amp;); signals: void operate(const QString &amp;); }; QThread* thread = new QThread; Worker* worker = new Worker(); worker-&gt;moveToThread(thread); connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString))); connect(thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(finished()), thread, SLOT(quit())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread-&gt;start(); </code></pre> <p>i've been using this method to generate a qthread , but as you can see, it's using the not recommended way. how can i re-write it to use the preferred method ?</p> <pre class="lang-py prettyprint-override"><code>class GenericThread(QThread): def __init__(self, function, *args, **kwargs): QThread.__init__(self) # super(GenericThread, self).__init__() self.function = function self.args = args self.kwargs = kwargs def __del__(self): self.wait() def run(self, *args): self.function(*self.args, **self.kwargs) </code></pre> <p>edit: two years later ... I tried qris' code, it works and in different thread </p> <pre class="lang-py prettyprint-override"><code>import sys import time from PyQt4 import QtCore, QtGui from PyQt4.QtCore import pyqtSignal, pyqtSlot import threading def logthread(caller): print('%-25s: %s, %s,' % (caller, threading.current_thread().name, threading.current_thread().ident)) class MyApp(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 280, 600) self.setWindowTitle('using threads') self.layout = QtGui.QVBoxLayout(self) self.testButton = QtGui.QPushButton("QThread") self.testButton.released.connect(self.test) self.listwidget = QtGui.QListWidget(self) self.layout.addWidget(self.testButton) self.layout.addWidget(self.listwidget) self.threadPool = [] logthread('mainwin.__init__') def add(self, text): """ Add item to list widget """ logthread('mainwin.add') self.listwidget.addItem(text) self.listwidget.sortItems() def addBatch(self, text="test", iters=6, delay=0.3): """ Add several items to list widget """ logthread('mainwin.addBatch') for i in range(iters): time.sleep(delay) # artificial time delay self.add(text+" "+str(i)) def test(self): my_thread = QtCore.QThread() my_thread.start() # This causes my_worker.run() to eventually execute in my_thread: my_worker = GenericWorker(self.addBatch) my_worker.moveToThread(my_thread) my_worker.start.emit("hello") # my_worker.finished.connect(self.xxx) self.threadPool.append(my_thread) self.my_worker = my_worker class GenericWorker(QtCore.QObject): start = pyqtSignal(str) finished = pyqtSignal() def __init__(self, function, *args, **kwargs): super(GenericWorker, self).__init__() logthread('GenericWorker.__init__') self.function = function self.args = args self.kwargs = kwargs self.start.connect(self.run) @pyqtSlot() def run(self, *args, **kwargs): logthread('GenericWorker.run') self.function(*self.args, **self.kwargs) self.finished.emit() # run app = QtGui.QApplication(sys.argv) test = MyApp() test.show() app.exec_() </code></pre> <p>the ouput is:</p> <pre><code>mainwin.__init__ : MainThread, 140221684574016, GenericWorker.__init__ : MainThread, 140221684574016, GenericWorker.run : Dummy-1, 140221265458944, mainwin.addBatch : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, mainwin.add : Dummy-1, 140221265458944, </code></pre>
0
2,340
What's the correct way to implement AsyncTask? static or non static nested class?
<p>The "Login" from Android examples implemented <code>AsyncTask</code> as a non-static inner class. However, according to Commonsguys, this class should be static and use weak-reference to the outside activity <a href="http://commonsware.com/blog/2010/09/10/asynctask-screen-rotation.html">see this</a>.</p> <p>So what is the correct way to implement <code>AsyncTask</code>? Static or non-static?</p> <p><strong>Commonsguy Implementation</strong><br> <a href="https://github.com/commonsguy/cw-android/tree/master/Rotation/RotationAsync/">https://github.com/commonsguy/cw-android/tree/master/Rotation/RotationAsync/</a></p> <p><strong>Log in example from Google</strong> </p> <pre><code>package com.example.asynctaskdemo; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.Activity; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; /** * Activity which displays a login screen to the user, offering registration as * well. */ public class LoginActivity extends Activity { /** * A dummy authentication store containing known user names and passwords. * TODO: remove after connecting to a real authentication system. */ private static final String[] DUMMY_CREDENTIALS = new String[] { "foo@example.com:hello", "bar@example.com:world" }; /** * The default email to populate the email field with. */ public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL"; /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // Values for email and password at the time of the login attempt. private String mEmail; private String mPassword; // UI references. private EditText mEmailView; private EditText mPasswordView; private View mLoginFormView; private View mLoginStatusView; private TextView mLoginStatusMessageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. mEmail = getIntent().getStringExtra(EXTRA_EMAIL); mEmailView = (EditText) findViewById(R.id.email); mEmailView.setText(mEmail); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); mLoginFormView = findViewById(R.id.login_form); mLoginStatusView = findViewById(R.id.login_status); mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message); findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.activity_login, menu); return true; } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ public void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. mEmailView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. mEmail = mEmailView.getText().toString(); mPassword = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password. if (TextUtils.isEmpty(mPassword)) { mPasswordView.setError(getString(R.string.error_field_required)); focusView = mPasswordView; cancel = true; } else if (mPassword.length() &lt; 4) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid email address. if (TextUtils.isEmpty(mEmail)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!mEmail.contains("@")) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. mLoginStatusMessageView.setText(R.string.login_progress_signing_in); showProgress(true); mAuthTask = new UserLoginTask(); mAuthTask.execute((Void) null); } } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginStatusView.setVisibility(View.VISIBLE); mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE); } }); mLoginFormView.setVisibility(View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask&lt;Void, Void, Boolean&gt; { @Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. try { // Simulate network access. Thread.sleep(2000); } catch (InterruptedException e) { return false; } for (String credential : DUMMY_CREDENTIALS) { String[] pieces = credential.split(":"); if (pieces[0].equals(mEmail)) { // Account exists, return true if the password matches. return pieces[1].equals(mPassword); } } // TODO: register the new account here. return true; } @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } } </code></pre> <p>If it depends on a specific situation, then with <code>ListView</code> items (text + plus Bitmap) loaded from the internet using <code>HttpClient</code>, how should I implement my AsyncTask? </p>
0
3,833
Mercurial for Beginners: The Definitive Practical Guide
<p><em>Inspired by <a href="https://stackoverflow.com/questions/315911/git-for-beginners-the-definitive-practical-guide">Git for beginners: The definitive practical guide</a>.</em></p> <p>This is a compilation of information on using Mercurial for <strong>beginners</strong> for <strong>practical</strong> use.</p> <p>Beginner - a programmer who has touched source control without understanding it very well.</p> <p>Practical - covering situations that the majority of users often encounter - creating a repository, branching, merging, pulling/pushing from/to a remote repository, etc.</p> <blockquote> <p><strong>Notes</strong>:</p> <ul> <li>Explain how to get something done rather than how something is implemented.</li> <li>Deal with one question per answer.</li> <li>Answer clearly and as concisely as possible.</li> <li>Edit/extend an existing answer rather than create a new answer on the same topic.</li> <li>Please provide a link to the the <a href="http://mercurial.selenic.com/wiki/" rel="nofollow noreferrer">Mercurial wiki</a> or the <a href="http://hgbook.red-bean.com/read/" rel="nofollow noreferrer">HG Book</a> for people who want to learn more.</li> </ul> </blockquote> <p>Questions:</p> <h2>Installation/Setup</h2> <ul> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1184108#1184108">How to install Mercurial?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1402038#1402038">How to set up Mercurial?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1170356#1170356">How do you create a new project/repository?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1170400#1170400">How do you configure it to ignore files?</a></li> </ul> <h2>Working with the code</h2> <ul> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1251593#1251593">How do you get the latest code?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1387214#1387214">How do you check out code?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1387249#1387249">How do you commit changes?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1174173#1174173">How do you see what's uncommitted, or the status of your current codebase?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/2652038#2652038">How do you remove files from the repository?</a></li> <li>How do you destroy unwanted commits?</li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1387288#1387288">How do you compare two revisions of a file, or your current file and a previous revision?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1688455#1688455">How do you see the history of revisions to a file or repository?</a></li> <li>How do you handle binary files (visio docs, for instance, or compiler environments)?</li> <li>How do you merge files changed at the "same time"?</li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/3353552#3353552">How do you revert a Changeset?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/3698654#3698654">How do you go back to a previous version of the code?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/3904935#3904935">How do you extract a patch from a specific changeset?</a></li> <li>How do you record that you renamed or deleted a file without using the Mercurial command?</li> </ul> <h2>Tagging, branching, releases, baselines</h2> <ul> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1170430#1170430">How do you 'mark' 'tag' or 'release' a particular set of revisions for a particular set of files so you can always pull that one later?</a></li> <li>How do you pull a particular 'release'?</li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1170368#1170368">How do you branch?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1170373#1170373">How do you merge branches?</a></li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/4264059#4264059">How do you merge parts of one branch into another branch?</a></li> </ul> <h2>Other</h2> <ul> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1551560#1551560">Good GUI/IDE plugin for Mercurial? Advantages/disadvantages?</a></li> <li>Any other common tasks a beginner should know?</li> <li><a href="https://stackoverflow.com/questions/1170338/mercurial-for-beginners-the-definitive-practical-guide/1297249#1297249">How do I interface with Subversion?</a></li> </ul> <h2>Other Mercurial references</h2> <ul> <li><a href="http://hgbook.red-bean.com/read/" rel="nofollow noreferrer">Mercurial: The Definitive Guide</a></li> <li><a href="https://www.mercurial-scm.org/wiki/" rel="nofollow noreferrer">Mercurial Wiki</a></li> <li><a href="http://peepcode.com/products/meet-mercurial" rel="nofollow noreferrer">Meet Mercurial | Peepcode Screencast</a></li> <li><a href="http://tekpub.com/production/hg" rel="nofollow noreferrer">Mastering Mercurial | TekPub Screencast</a></li> <li><a href="http://hginit.com" rel="nofollow noreferrer">Hg Init</a> - ground-up Mercurial tutorial</li> </ul>
0
2,179
ReferenceError: Parse is not defined
<p>I get this error with a Parse.com JS App:</p> <blockquote> <p>ReferenceError: Parse is not defined.</p> </blockquote> <p>I really don't know why. Everything looks good to me. The files are linked correctly; I've checked this a few times. Is it not true, that I have to put my own JS right below Parse and it should work? This is what I've read here: <a href="https://github.com/ParsePlatform/AnyYolk/blob/master/index.html" rel="nofollow">Github Project</a> I use Chrome with the ripple extension. I serve the app via <code>cordova serve</code></p> <p>Any help much appreciated! </p> <p>Here is index.html: </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="format-detection" content="telephone=no" /&gt; &lt;meta name="msapplication-tap-highlight" content="no" /&gt; &lt;meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=device-dpi" /&gt; &lt;link rel="stylesheet" type="text/css" href="../css/index.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="../css/font-awesome.min.css" /&gt; &lt;title&gt;Zone&lt;/title&gt; &lt;meta name="apple-mobile-web-app-capable" content="yes"&gt; &lt;meta name="apple-mobile-web-app-status-bar-style" content="black"&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://www.parsecdn.com/js/parse-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="../js/main.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;img src="../img/site-logo.png" rel="external" class="logo"&gt; &lt;!-- &lt;div class="site-menu"&gt; &lt;i class="fa fa-angle-double-left"&gt;&lt;/i&gt;&lt;p class="title"&gt;&lt;/p&gt;&lt;i&gt;&lt;/i&gt; &lt;/div&gt; --&gt; &lt;a href="#"&gt;&lt;img src="img/suche.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/essentrinken.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/einkaufen.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/kultur.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/dienstleistungen.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/nuetzlich.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/nummern.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/sport.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/verwaltung.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/hotel.jpg" class="icon"&gt;&lt;/a&gt; &lt;a href="#"&gt;&lt;img src="img/neuzuzuger.jpg" class="icon"&gt;&lt;/a&gt; &lt;div class="adad"&gt;&lt;/div&gt; &lt;script type="text/javascript" src="../cordova.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="../js/index.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; app.initialize(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And here the JS file. </p> <pre><code>$(document).ready(function () { Parse.initialize("", ""); var Ad = Parse.Object.extend("Ads"); function getPosts() { var query = new Parse.Query(Ad); query.find({ success: function (results) { console.log("hello"); var output = ""; for (var i in results) { var name = results[i].get("location"); if (name == 10) { output += "&lt;img src = '" + imageurl + "' class='media-object' height='60' width='100'&gt;" } } $("#adad").html(output); console.log(output); }, error: function (error) { console.log("Query error:" + error.message); } }); } getPosts(); }); </code></pre>
0
1,941
Keycloak Spring boot configuration
<p>I'm trying to configure Spring Boot and Keycloak for SSO. I've created a basic AngularJS application that do some requests to the Spring boot backend. <a href="http://slackspace.de/articles/authentication-with-spring-boot-angularjs-and-keycloak/" rel="nofollow noreferrer">using this</a></p> <p>The Angular app is working fine and now I'm trying to follow the new Spring Boot Keycloak apdater docuementation <a href="https://keycloak.gitbooks.io/securing-client-applications-guide/content/topics/oidc/java/spring-boot-adapter.html" rel="nofollow noreferrer">here</a></p> <p>This is my keycloak.json that is in the WEB-INF folder.</p> <pre><code>{ "realm": "my-backend", "bearer-only": true, "realm-public-key": "MIIB...", "auth-server-url": "http://localhost:8180/auth", "ssl-required": "external", "resource": "my-backend", "principal-attribute": "preferred_username", "credentials": { "secret": "a75f55ca-8174-4072-8c60-b545c9ebf7e1" } </code></pre> <p>Here is my security configuration :</p> <pre><code>@Configuration @EnableWebSecurity @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { /** * Registers the KeycloakAuthenticationProvider with the authentication manager. */ @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(keycloakAuthenticationProvider()); } /** * Defines the session authentication strategy. */ @Bean @Override protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**"); } @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); http .authorizeRequests() .antMatchers("/api/v1*").hasRole("user") .antMatchers("/admin/hello*").hasRole("admin") .anyRequest().permitAll(); } } </code></pre> <p>The 2 roles, 'admin' and 'user' are created in Keycloak and the current user has this roles.</p> <pre><code>@RestController @RequestMapping("/") @CrossOrigin("*") public class PharmaController { public class Response{ private String message; public Response(String msg){ this.message = msg; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } } @RequestMapping( path="api/v1/userinfo", method = RequestMethod.GET) @ResponseBody public void getUserInformation(KeycloakAuthenticationToken token) { if(token != null){ System.out.println("token :" + token); try { System.out.println(token.getAccount().getPrincipal().getName()); System.out.println(token.getAccount().getRoles()); } catch (Exception e) { // TODO: handle exception } }else{ System.out.println("User not connected."); } } @RequestMapping( path="admin/hello", method = RequestMethod.GET) @ResponseBody public Response adminHello(KeycloakAuthenticationToken token) { return new Response("Hello"); } } </code></pre> <ol> <li>Even if the user doesn't have any of this role, he can access <strong>api/v1/userinfo</strong> with this response</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>{"data":"","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:8080/api/v1/userinfo","headers":{"Accept":"application/json, text/plain, */*","Access-Control-Allow-Origin":"*","Authorization":"BEARER eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJSN2JSQUgtcmUwNnVEMHh4Vlotd1dyWVIycVI0S0pyMDFIZWQ2QmJMNnA4In0.eyJqdGkiOiI3ZDU4ZGM0Yi0wYzgwLTQwZDYtYWE5OC0yNDk5YzEzZTg2NmMiLCJleHAiOjE0ODM5MTY3OTgsIm5iZiI6MCwiaWF0IjoxNDgzOTE2NDk4LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgxODAvYXV0aC9yZWFsbXMvbXktcGhhcm1hIiwiYXVkIjoicGhhcm1hLXdlYmFwcCIsInN1YiI6IjIxMjI2YzNlLWYwY2UtNGRjNC1hYzk0LTRlNTVmZjc4YWRlMSIsInR5cCI6IkJlYXJlciIsImF6cCI6InBoYXJtYS13ZWJhcHAiLCJub25jZSI6Ijg4MWI1MjhhLWFkOTktNDcwYy04YzJiLTlhYjI0MzM2N2IwOCIsImF1dGhfdGltZSI6MTQ4MzkxNjQ5OCwic2Vzc2lvbl9zdGF0ZSI6Ijg4ZmExODJjLTljOTctNGI2Ny1hMTMzLTk5YjFkNmU4OTZiYyIsImFjciI6IjEiLCJjbGllbnRfc2Vzc2lvbiI6IjJiM2FjNDg1LWQ5ZjUtNDc2ZC1hYjQ1LTA2ZGZmM2VjMTQxMiIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwOi8vbG9jYWxob3N0OjkwMDAiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsInZpZXctcHJvZmlsZSJdfX0sIm5hbWUiOiJVc2VyMSBGTiBVc2VyMSBMTiIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIxIiwiZ2l2ZW5fbmFtZSI6IlVzZXIxIEZOIiwiZmFtaWx5X25hbWUiOiJVc2VyMSBMTiIsImVtYWlsIjoidXNlcjFAeW91LmNvbSJ9.M1RvECaBV3jvNXRxQzLzS4bfKnK-gQp85mkr9GD8HbOsGRui81pZP3Pb_NJ-ieaQ7pca7tO_06UNeSqbHut7c1APV3_GEGTnwuCkKdbu1QKrVwXSXMWNyt0nu_MOdjhzG3bQat3aG68b744KdCSi5i8OBg2L4I3Zmc6nPX5vklf1U7LUXyvs_bswLPZEy1_VQ_ACu_BSIVA8iv64Nl4ng4QlEc6pyEHbhQ2pKpE7wNIiZe-ndfeQWU5FgnV0Ya16b2Up9ZnFw7fpGHDGjzlIEV_As3K32vON171OuAhTKmIbVnG4kuoijQzeqHmkoB-ldfMKPPlLheSILtHvRn8WkA"}},"statusText":""}</code></pre> </div> </div> </p> <ol start="2"> <li>The endpoint <strong>admin/hello</strong> is not reachable.</li> </ol> <p>This is the stack trace :</p> <pre><code>[org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@63858877:org.apache.tomcat.util.net.NioChannel@4d4fa76c:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:51832]], Status in: [OPEN_READ], State out: [OPEN] 2017-01-09 07:11:46.739 DEBUG 14692 --- [nio-8080-exec-2] o.a.coyote.http11.Http11InputBuffer : Received [GET /admin/hello HTTP/1.1 Host: localhost:8080 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Access-Control-Allow-Origin: * Accept: application/json, text/plain, */* Origin: http://localhost:9000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36 Authorization: BEARER eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJSN2JSQUgtcmUwNnVEMHh4Vlotd1dyWVIycVI0S0pyMDFIZWQ2QmJMNnA4In0.eyJqdGkiOiIyMzMzZmI0OC0yMGE2LTQ2YzctODM1YS0wNGRiMDYyNmEyYWEiLCJleHAiOjE0ODM5MTc0MDQsIm5iZiI6MCwiaWF0IjoxNDgzOTE3MTA0LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgxODAvYXV0aC9yZWFsbXMvbXktcGhhcm1hIiwiYXVkIjoicGhhcm1hLXdlYmFwcCIsInN1YiI6IjIxMjI2YzNlLWYwY2UtNGRjNC1hYzk0LTRlNTVmZjc4YWRlMSIsInR5cCI6IkJlYXJlciIsImF6cCI6InBoYXJtYS13ZWJhcHAiLCJub25jZSI6IjQwZDc3MzAyLWViNTYtNGFhMS05OTllLTcyNDRiNmY3MTFkYiIsImF1dGhfdGltZSI6MTQ4MzkxNzEwNCwic2Vzc2lvbl9zdGF0ZSI6IjdmODlkODMyLTNkNTktNDc1Yi04NzI3LTRiZGQ5MDc4ODQ5YSIsImFjciI6IjEiLCJjbGllbnRfc2Vzc2lvbiI6IjJiOGNjMzc3LWY1NjUtNGE3NS1iMWY5LWEyNWFlZTY0ZGM3MCIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwOi8vbG9jYWxob3N0OjkwMDAiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsInZpZXctcHJvZmlsZSJdfX0sIm5hbWUiOiJVc2VyMSBGTiBVc2VyMSBMTiIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIxIiwiZ2l2ZW5fbmFtZSI6IlVzZXIxIEZOIiwiZmFtaWx5X25hbWUiOiJVc2VyMSBMTiIsImVtYWlsIjoidXNlcjFAeW91LmNvbSJ9.S5Jhrea_JzlXEuMPSfJ9Sd8HdNQyknklfdZFDMH_vaFWHiQShVVQAhM3wbwrz8NoJs3M6iFnkA-kuMPhCUR52y65HJ9mEXSxrUN6hPY4U9mEYIKw_kGVXFf_xOirA8lO9cvEmw7c7p2BN0DWmi85RshqhM6CEdGAtIL4z-rl-b3UDJkm9dT3uaMxcYb3l8lq0AkixqnaI8seFLdLgacdhfMblnKuyP6bgWUD2jl2X9ruVGfIHQeBdA19WesMJKHm9XqQaF1mjl0AM0k52bU7GZZ6cOD3yFwl2RMAUMlUPPyX9xq2L5kNEsgYdw4qlgdvjLaX_HipqHh7JHQksJv4Sg Referer: http://localhost:9000/ Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,fr;q=0.4 ] 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] o.a.c.authenticator.AuthenticatorBase : Security checking request GET /admin/hello 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] org.apache.catalina.realm.RealmBase : No applicable constraints defined 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] o.a.c.authenticator.AuthenticatorBase : Not subject to any constraint 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] org.apache.tomcat.util.http.Parameters : Set encoding to UTF-8 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.w.f.OrderedRequestContextFilter : Bound request context to thread: org.apache.catalina.connector.RequestFacade@2683da6f 2017-01-09 07:11:46.740 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /admin/hello' doesn't match 'OPTIONS /** 2017-01-09 07:11:46.741 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 2017-01-09 07:11:46.741 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 2017-01-09 07:11:46.742 DEBUG 14692 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists 2017-01-09 07:11:46.742 DEBUG 14692 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created. 2017-01-09 07:11:46.743 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter' 2017-01-09 07:11:46.743 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter' 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 5 of 13 in additional filter chain; firing Filter: 'KeycloakPreAuthActionsFilter' 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.k.adapters.PreAuthActionsHandler : adminRequest http://localhost:8080/admin/hello 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 6 of 13 in additional filter chain; firing Filter: 'LogoutFilter' 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /admin/hello' doesn't match 'POST /sso/logout 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 7 of 13 in additional filter chain; firing Filter: 'KeycloakAuthenticationProcessingFilter' 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/login'] 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/admin/hello'; against '/sso/login' 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null] 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : matched 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] f.KeycloakAuthenticationProcessingFilter : Request is to process authentication 2017-01-09 07:11:46.744 DEBUG 14692 --- [nio-8080-exec-2] f.KeycloakAuthenticationProcessingFilter : Attempting Keycloak authentication 2017-01-09 07:11:46.871 DEBUG 14692 --- [nio-8080-exec-2] a.s.a.SpringSecurityRequestAuthenticator : Completing bearer authentication. Bearer roles: [uma_authorization] 2017-01-09 07:11:46.871 DEBUG 14692 --- [nio-8080-exec-2] o.k.adapters.RequestAuthenticator : User 'user1' invoking 'http://localhost:8080/admin/hello' on client 'pharma-backend' 2017-01-09 07:11:46.871 DEBUG 14692 --- [nio-8080-exec-2] o.k.adapters.RequestAuthenticator : Bearer AUTHENTICATED 2017-01-09 07:11:46.871 DEBUG 14692 --- [nio-8080-exec-2] f.KeycloakAuthenticationProcessingFilter : Auth outcome: AUTHENTICATED 2017-01-09 07:11:46.871 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.authentication.ProviderManager : Authentication attempt using org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider 2017-01-09 07:11:46.872 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener' 2017-01-09 07:11:46.889 DEBUG 14692 --- [nio-8080-exec-2] o.k.a.s.management.HttpSessionManager : Session created: D309F84825BE807C7B34F16B111E92CD 2017-01-09 07:11:46.890 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.core.session.SessionRegistryImpl : Registering session D309F84825BE807C7B34F16B111E92CD, for principal user1 2017-01-09 07:11:46.891 DEBUG 14692 --- [nio-8080-exec-2] f.KeycloakAuthenticationProcessingFilter : Authentication success using bearer token/basic authentication. Updating SecurityContextHolder to contain: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@a08a84cd: Principal: user1; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@4ebe3c30; Granted Authorities: KeycloakRole{role='uma_authorization'} 2017-01-09 07:11:46.891 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener' 2017-01-09 07:11:46.891 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 2017-01-09 07:11:46.891 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@a08a84cd: Principal: user1; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@4ebe3c30; Granted Authorities: KeycloakRole{role='uma_authorization'}' 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter' 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy@29a23c3d 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.core.session.SessionRegistryImpl : Registering session D309F84825BE807C7B34F16B111E92CD, for principal user1 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.core.session.SessionRegistryImpl : Removing session D309F84825BE807C7B34F16B111E92CD from principal's set of registered sessions 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.core.session.SessionRegistryImpl : Removing principal user1 from registry 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.csrf.CsrfAuthenticationStrategy@20f0cc02 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@a08a84cd: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@a08a84cd: Principal: user1; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@4ebe3c30; Granted Authorities: KeycloakRole{role='uma_authorization'}' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@1a43aa14 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 2017-01-09 07:11:46.892 DEBUG 14692 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /admin/hello at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 2017-01-09 07:11:46.893 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /admin/hello' doesn't match 'POST /sso/logout 2017-01-09 07:11:46.893 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/admin/hello'; against '/api/v1*' 2017-01-09 07:11:46.893 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/admin/hello'; against '/admin/hello*' 2017-01-09 07:11:46.893 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /admin/hello; Attributes: [hasRole('ROLE_admin')] 2017-01-09 07:11:46.893 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@a08a84cd: Principal: user1; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@4ebe3c30; Granted Authorities: KeycloakRole{role='uma_authorization'} 2017-01-09 07:11:46.895 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@58311096, returned: -1 2017-01-09 07:11:46.896 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener' 2017-01-09 07:11:46.899 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is not anonymous); delegating to AccessDeniedHandler org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) ~[spring-security-web-4.1.4.RELEASE.jar:4.1.4.RELEASE] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.1.4.RELEASE.jar:4.1.4.RELEASE] ... java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_111] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.6.jar:8.5.6] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111] 2017-01-09 07:11:46.899 DEBUG 14692 --- [nio-8080-exec-2] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5ca0c4c5 2017-01-09 07:11:46.899 DEBUG 14692 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@a08a84cd: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken@a08a84cd: Principal: user1; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount@4ebe3c30; Granted Authorities: KeycloakRole{role='uma_authorization'}' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@1a43aa14 2017-01-09 07:11:46.899 DEBUG 14692 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed 2017-01-09 07:11:46.899 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.w.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@2683da6f 2017-01-09 07:11:46.900 DEBUG 14692 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error] 2017-01-09 07:11:46.901 DEBUG 14692 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error] 2017-01-09 07:11:46.902 DEBUG 14692 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error 2017-01-09 07:11:46.904 DEBUG 14692 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity&lt;java.util.Map&lt;java.lang.String, java.lang.Object&gt;&gt; org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] 2017-01-09 07:11:46.904 DEBUG 14692 --- [nio-8080-exec-2] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'basicErrorController' 2017-01-09 07:11:46.904 DEBUG 14692 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1 2017-01-09 07:11:46.927 DEBUG 14692 --- [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Mon Jan 09 07:11:46 MYT 2017, status=403, error=Forbidden, message=Access is denied, path=/admin/hello}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@45db4b8b] 2017-01-09 07:11:46.927 DEBUG 14692 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling 2017-01-09 07:11:46.927 DEBUG 14692 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request 2017-01-09 07:11:46.928 DEBUG 14692 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Disabling the response for futher output 2017-01-09 07:11:46.928 DEBUG 14692 --- [nio-8080-exec-2] o.apache.coyote.http11.Http11Processor : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@63858877:org.apache.tomcat.util.net.NioChannel@4d4fa76c:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8080 remote=/0:0:0:0:0:0:0:1:51832]], Status in: [OPEN_READ], State out: [OPEN] </code></pre>
0
10,443
How to click a particular button within a window (without using XPOS YPOS)
<p>I have just started using AUTOHOTKEY and its been phenomenal.I have a doubt though. I want to automate the launching of an application and then clicking on a specific button in it.I would like to accomplish this using AHK.</p> <p>Once I launch the applicaton this window appears <a href="https://www.dropbox.com/s/vkmoccc4hhhxmng/LOGIN%20screenshot.jpg" rel="nofollow">here</a>. I want to hit the "Connect" button, but I cant figure out a good way to move the cursor to the connect button. I tried the following code which uses tab.</p> <pre><code>Loop ,5 { sleep 2*1000 Send {Tab down} } </code></pre> <p><strong>This works, But i feel this is crude and need a better way. Is there a way to use button_name or button_text to my advantage?</strong> </p> <p><strong>I dont want to use screen positions XPOS AND YPOS either.</strong></p> <p>The link to my applcn window screenshot is <a href="https://www.dropbox.com/s/vkmoccc4hhhxmng/LOGIN%20screenshot.jpg" rel="nofollow">this</a>.</p> <p>I have the following info from the WINDOW-SPY feature of <strong>AutoHotKey</strong>.Hope you can find this useful.</p> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <blockquote> <p>( Window Title &amp; Class )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; Asianet Login ahk_class QWidget</p> <blockquote> <blockquote> <p>( Mouse Position )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; On Screen: 881, 306 (less often used) In Active Window: 462, 76</p> </blockquote> </blockquote> </blockquote> <p>( Now Under Mouse Cursor )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; ClassNN: QWidget2 Text: bnConnect Color: 0xC8D0D4 (Blue=C8 Green=D0 Red=D4)</p> <blockquote> <p>( Active Window Position )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; left: 419 top: 230 width: 529 height: 238</p> <blockquote> <p>( Status Bar Text )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</p> <p>( Visible Window Text )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; layoutWidget bnConnect bnAbout bnClose chkRemember edPassword lbPassword edUsername teLog qt_scrollarea_viewport lbUsername</p> <p>( Hidden Window Text )&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; qt_scrollarea_vcontainer qt_scrollarea_hcontainer</p> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> </blockquote> <p>( TitleMatchMode=slow Visible Text )&lt;&lt;&lt;&lt;</p> <p>( TitleMatchMode=slow Hidden Text )&lt;&lt;&lt;&lt;</p> </blockquote> </blockquote> </blockquote> </blockquote>
0
2,093
Binding Path Fill to Button Foreground in ContentPresenter
<p>I have a Button Style with a Template containing a ContentPresenter, in which I am attempting to bind the Fill of a Path to the Foreground of a button:</p> <pre><code>&lt;!-- This is inside the template of a button style --&gt; &lt;ContentPresenter&gt; &lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type Path}"&gt; &lt;Setter Property="Fill" Value="{Binding Path=Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt; &lt;/ContentPresenter&gt; </code></pre> <p>I also have a Path with no Fill set, that I can reference in the button as the content, like so:</p> <pre><code>&lt;Button Style="{DynamicResource MyButtonStyle}" Content="{DynamicResource PathIcon}" Foreground="Blue"/&gt; </code></pre> <p>I would expect the Path inside the button to be blue, but it isn't... it doesn't grab the foreground from the button.</p> <p>How can I get the Path to bind to the color of the button?</p> <p>Thank you!</p> <p>P.S.:</p> <p>If I put a hardcoded color in the Value (i.e. Value="Red"), the Path inside the button is red... so I know that works...</p> <pre><code>&lt;ContentPresenter&gt; &lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type Path}"&gt; &lt;Setter Property="Fill" Value="Red"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt; &lt;/ContentPresenter&gt; </code></pre> <hr> <p>Edit:</p> <p>Here is the complete Style and ControlTemplate:</p> <pre><code>&lt;Style x:Key="Button_Style" TargetType="{x:Type Button}"&gt; &lt;Setter Property="Foreground" Value="{StaticResource White_Brush}"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;Grid x:Name="grid" Background="Transparent"&gt; &lt;ContentPresenter&gt; &lt;ContentPresenter.Resources&gt; &lt;Style TargetType="{x:Type Path}"&gt; &lt;Setter Property="Fill" Value="{Binding Path=Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/&gt; &lt;/Style&gt; &lt;/ContentPresenter.Resources&gt; &lt;/ContentPresenter&gt; &lt;/Grid&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsMouseOver" Value="True"&gt; &lt;!-- Should affect Text as well as Paths in the Content property of the button! --&gt; &lt;Setter Property="Foreground" Value="{StaticResource Black_Brush}"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre>
0
1,404
Force release the connection in weblogic 10.3.4
<p>I am getting following error in my managed server console on oracle soa server(11g).</p> <pre><code>-------------------- &lt;Apr 14, 2011 10:51:37 AM SGT&gt; &lt;Warning&gt; &lt;JDBC&gt; &lt;BEA-001153&gt; &lt;Forcibly releasing inactive connection "weblogic.jdbc.wrapper.PoolConnection_oracle_jdbc_driver_T4CConnection@14267" back into the connect ion pool "JDBC Data Source-0", currently reserved by: java.lang.Exception at weblogic.jdbc.common.internal.ConnectionEnv.setup(ConnectionEnv.java:318) at weblogic.common.resourcepool.ResourcePoolImpl.reserveResource(ResourcePoolImpl.java:344) at weblogic.common.resourcepool.ResourcePoolImpl.reserveResource(ResourcePoolImpl.java:322) at weblogic.jdbc.common.internal.ConnectionPool.reserve(ConnectionPool.java:438) at weblogic.jdbc.common.internal.ConnectionPool.reserve(ConnectionPool.java:317) at weblogic.jdbc.common.internal.ConnectionPoolManager.reserve(ConnectionPoolManager.java:93) at weblogic.jdbc.common.internal.RmiDataSource.getPoolConnection(RmiDataSource.java:342) at weblogic.jdbc.common.internal.RmiDataSource.getConnection(RmiDataSource.java:360) at com.ura.dams.registration.dbcontrol.DBConnection.getConnection(DBConnection.java:35) at com.ura.dams.registration.dbcontrol.SubmissionUploadDBImpl.executeSelect(SubmissionUploadDBImpl.java:786) at com.ura.dams.registration.dbcontrol.SubmissionUploadDBImpl.getSubTypeAndApplTypeInd(SubmissionUploadDBImpl.java:159) at com.ura.dams.registration.businesscontrol.UploadSubmissionImpl.getAcceptanceStatus(UploadSubmissionImpl.java:829) at com.ura.dams.registration.process.RegistrationUpload.perform2(RegistrationUpload.java:121) at orabpel.registrationupload.ExecLetBxExe3.execute(ExecLetBxExe3.java:139) at com.collaxa.cube.engine.ext.bpel.common.wmp.BPELxExecWMP.__executeStatements(BPELxExecWMP.java:42) at com.collaxa.cube.engine.ext.bpel.common.wmp.BaseBPELActivityWMP.perform(BaseBPELActivityWMP.java:162) at com.collaxa.cube.engine.CubeEngine.performActivity(CubeEngine.java:2465) at com.collaxa.cube.engine.CubeEngine.handleWorkItem(CubeEngine.java:1132) at com.collaxa.cube.engine.dispatch.message.instance.PerformMessageHandler.handleLocal(PerformMessageHandler.java:73) at com.collaxa.cube.engine.dispatch.DispatchHelper.handleLocalMessage(DispatchHelper.java:219) at com.collaxa.cube.engine.dispatch.DispatchHelper.sendMemory(DispatchHelper.java:327) at com.collaxa.cube.engine.CubeEngine.endRequest(CubeEngine.java:4350) at com.collaxa.cube.engine.CubeEngine.endRequest(CubeEngine.java:4281) at com.collaxa.cube.engine.CubeEngine._createAndInvoke(CubeEngine.java:713) at com.collaxa.cube.engine.CubeEngine.createAndInvoke(CubeEngine.java:545) at com.collaxa.cube.engine.delivery.DeliveryService.handleInvoke(DeliveryService.java:654) at com.collaxa.cube.engine.ejb.impl.CubeDeliveryBean.handleInvoke(CubeDeliveryBean.java:355) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at com.bea.core.repackaged.springframework.jee.intercept.MethodInvocationInvocationContext.proceed(MethodInvocationInvocationContext.java:104) at oracle.security.jps.ee.ejb.JpsAbsInterceptor$1.run(JpsAbsInterceptor.java:88) at java.security.AccessController.doPrivileged(Native Method) at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313) at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:414) at oracle.security.jps.wls.JpsWeblogicEjbInterceptor.runJaasMode(JpsWeblogicEjbInterceptor.java:61) at oracle.security.jps.ee.ejb.JpsAbsInterceptor.intercept(JpsAbsInterceptor.java:106) at oracle.security.jps.ee.ejb.JpsInterceptor.intercept(JpsInterceptor.java:106) at sun.reflect.GeneratedMethodAccessor813.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310) at com.bea.core.repackaged.springframework.jee.intercept.JeeInterceptorInterceptor.invoke(JeeInterceptorInterceptor.java:69) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at com.bea.core.repackaged.springframework.jee.spi.MethodInvocationVisitorImpl.visit(MethodInvocationVisitorImpl.java:37) at weblogic.ejb.container.injection.EnvironmentInterceptorCallbackImpl.callback(EnvironmentInterceptorCallbackImpl.java:54) at com.bea.core.repackaged.springframework.jee.spi.EnvironmentInterceptor.invoke(EnvironmentInterceptor.java:50) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at com.bea.core.repackaged.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131) at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119) at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at com.bea.core.repackaged.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy245.handleInvoke(Unknown Source) at com.collaxa.cube.engine.ejb.impl.bpel.BPELDeliveryBean_5k948i_ICubeDeliveryLocalBeanImpl.handleInvoke(BPELDeliveryBean_5k948i_ICubeDeliveryLocalBeanImpl.java:132) at com.collaxa.cube.engine.dispatch.message.invoke.InvokeInstanceMessageHandler.handle(InvokeInstanceMessageHandler.java:35) at com.collaxa.cube.engine.dispatch.DispatchHelper.handleMessage(DispatchHelper.java:141) at com.collaxa.cube.engine.dispatch.BaseDispatchTask.run(BaseDispatchTask.java:82) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) -------------------------------------- </code></pre> <p>Can any one tell me why I am getting this error.</p> <p>Following is my settings.</p> <ul> <li>InActive Connection Timeout: 60 </li> <li>Connection Reserve timeout: 20</li> <li>Initial capacity: 10 </li> <li>Maximum CapacityL: 30</li> </ul> <p>I am profiling the connection leak also and i have checked in my application that there is no open connection.</p> <p>thanks,</p>
0
3,076
SonarLint plugin not working in Eclipse Oxygen
<p>I am trying to get SonarLint plugin working in Eclipse but I am not having much luck. More specifically, I don't see any issues detected or highlighted in the "SonarLint On-the-fly" tab when looking at a simple Java class in a Java project.</p> <p>I use the following software.</p> <p><strong>OS</strong>: </p> <p>Win 10 Pro - Version 1709</p> <p><strong>Java</strong>: </p> <p>java version "1.8.0_161"</p> <p>Java(TM) SE Runtime Environment (build 1.8.0_161-b12)</p> <p>Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)</p> <p><strong>Eclipse</strong>:</p> <p>Version: Oxygen.3 Release (4.7.3)</p> <p>Sonar software: </p> <p><strong>SonarLint Eclipse plugin</strong>: </p> <p>org.sonarlint.eclipse.site-3.4.0 source: <a href="https://www.sonarlint.org/eclipse/" rel="nofollow noreferrer">https://www.sonarlint.org/eclipse/</a></p> <p><strong>SonarQube</strong>:</p> <p>SonarQube 7.0 source: <a href="https://www.sonarqube.org/downloads/" rel="nofollow noreferrer">https://www.sonarqube.org/downloads/</a></p> <p><strong>SonarScanner</strong>:</p> <p>sonar-scanner-3.1.0.1141 source: <a href="https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner" rel="nofollow noreferrer">https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner</a> (Windows 64 bit - link)</p> <p>I downloaded the SonarLint Eclipse plugin and successfully installed it in Eclipse. I can see all the SonarLint tabs and configuration options. </p> <p>I downloaded and successfully setup SonarQube server (localhost on the default port 9000). I also downloaded and set up Sonar Scanner. </p> <p>I created a simple Java project in Eclipse and I created a Java class in it. I added the sonar-project.properties file to the Java project. </p> <p><strong>sonar-project.properties</strong></p> <pre><code># must be unique in a given SonarQube instance sonar.projectKey=sp # this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1. sonar.projectName=Simple Project sonar.projectVersion=1.0 # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. # This property is optional if sonar.modules is set. sonar.sources=. # Encoding of the source code. Default is default system encoding #sonar.sourceEncoding=UTF-8 </code></pre> <p>My Eclipse Java project looks like this:</p> <p><a href="https://i.stack.imgur.com/3lavt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3lavt.png" alt="enter image description here"></a></p> <p>I have set up my project bindings successfully.</p> <p><a href="https://i.stack.imgur.com/ybZ4a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ybZ4a.png" alt="enter image description here"></a></p> <p>I can start the SonarQube and login without issues. I navigated to the location of my "Simple Project" in Windows Explorer and opened a Windows PowerShell from there.</p> <p>I executed the command <strong>sonar-scanner</strong> in the Windows PowerShell which successfully scanned the <strong>Simple Project</strong> and I can see the results in my SonarQube server.</p> <p><a href="https://i.stack.imgur.com/2dnkQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2dnkQ.png" alt="enter image description here"></a></p> <p>So all is good so far. BUT... There is no indication of issues in Eclipse. I don't see any issues under the SonarLint On-the-fly tab in Eclipse.</p> <p><a href="https://i.stack.imgur.com/Zi0F9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zi0F9.png" alt="enter image description here"></a></p> <p>I do have "Run SonarLint automatically" enabled (checked) and I also tried to manually analyze the App.java file by <em>right-clicking on the file > SonarLint > Analyze</em>.</p> <p>I see no issues underlined in either the code or listed in the "SonarLint On-the-fly" tab. I must be missing a step somewhere. Could anyone please give me any tips how to get the automatic SonarLint issue detection working in Eclipse?</p> <p>Thank you!</p>
0
1,408
the type org.springframework.data.repository.query.QueryByExampleExecutor cannot be resolved. It is indirectly referenced from required .class files
<p>Good morning, I have a head the end of the week with an error in the project that I'm doing for the study of springboot + angular + jpa.</p> <p>At the time of doing a service management class, I used it according to the tutorial of an extended class of class JpaRepository.</p> <p>But a project error that I can not solve.</p> <p>Follow the pom.xml and some images of the project, if anyone can help I thank you!</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;marco.prova&lt;/groupId&gt; &lt;artifactId&gt;apiweb&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;apiweb&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.0.0.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;version&gt;2.0.5.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.data&lt;/groupId&gt; &lt;artifactId&gt;spring-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Project images in STS.</p> <p><a href="https://uploaddeimagens.com.br/imagens/1-png-6e078f12-f26b-4266-8030-520f0f0fe7d1" rel="noreferrer">https://uploaddeimagens.com.br/imagens/1-png-6e078f12-f26b-4266-8030-520f0f0fe7d1</a></p> <p><a href="https://uploaddeimagens.com.br/imagens/2-png-2224373b-2cec-46dc-b986-e68876ef57db" rel="noreferrer">https://uploaddeimagens.com.br/imagens/2-png-2224373b-2cec-46dc-b986-e68876ef57db</a></p> <p><a href="https://uploaddeimagens.com.br/imagens/3-png-740ac73d-5bd4-4f45-9394-c2717d4a9423" rel="noreferrer">https://uploaddeimagens.com.br/imagens/3-png-740ac73d-5bd4-4f45-9394-c2717d4a9423</a></p> <p><a href="https://uploaddeimagens.com.br/imagens/4-png-9202635e-5a30-4f58-a862-70d3e9034ec6" rel="noreferrer">https://uploaddeimagens.com.br/imagens/4-png-9202635e-5a30-4f58-a862-70d3e9034ec6</a></p> <p>I'm waiting! Thank you!</p>
0
1,650
Ant script: Have <exec> tag dump out entire command line
<p>I have an ant build script with a fairly complex <code>&lt;exec&gt;</code> command with lots of <code>&lt;arg&gt;</code> tags that I'm trying to troubleshoot. I was wondering if it is possible to view the entire command line after ant has constructed it; either in the eclipse debugger or maybe by dumping it to a file.</p> <p>Here's what I'm dealing with:</p> <pre><code>&lt;exec executable='"@{sdk}/bin/mxmlc.exe"' failonerror="true" &gt; &lt;arg line='-load-config "@{sdk}/frameworks/flex-config.xml"'/&gt; &lt;!-- Flex Build Path --&gt; &lt;!-- Source path --&gt; &lt;!-- Main source folder: --&gt; &lt;arg line='-compiler.source-path "@{project-dir}/src"'/&gt; &lt;!-- Additional source folders outside of the main source folder: --&gt; &lt;arg line='-compiler.source-path "@{project-dir}/inc/swf"'/&gt; &lt;arg line='-compiler.source-path "@{project-dir}/inc/images"'/&gt; &lt;!-- Output folder: --&gt; &lt;arg line='-output "@{output}"'/&gt; &lt;!-- Library path --&gt; &lt;!-- Build path libraries: --&gt; &lt;arg line='-compiler.library-path "@{libs}"'/&gt; &lt;arg line='-compiler.library-path "@{sdk}/frameworks/libs"'/&gt; &lt;arg line='-compiler.library-path "@{sdk}/frameworks/locale/en_US"'/&gt; &lt;arg line='-compiler.library-path "${dcradswcs.flex.path}/libs"'/&gt; &lt;arg line='-compiler.library-path "${dcradswcs.flex.path}/locale"'/&gt; &lt;arg line='-compiler.library-path "${fiberswcs.flex.path}/libs"'/&gt; &lt;arg line='-compiler.library-path "${fiberswcs.flex.path}/locale"'/&gt; &lt;arg line='-compiler.library-path "${flexunitframework.flex.path}/flexunitframework/libs/version4libs/Common"'/&gt; &lt;arg line='-compiler.library-path "${flexunitframework.flex.path}/flexunitframework/libs/version4libs/FlexProject"'/&gt; &lt;arg line='-compiler.library-path "${flexunitframework.flex.path}/flexunitframework/locale/version4locale"'/&gt; &lt;arg line='-compiler.library-path "${flexunitframework.flex.path}/flexunitframework/libs"'/&gt; &lt;!-- &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.dcrad_4.0.1.277662/dcradSwcs/4.0/libs"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.dcrad_4.0.1.277662/dcradSwcs/4.0/locale"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.dcrad_4.0.1.277662/fiberSwcs/4.0/libs"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.dcrad_4.0.1.277662/fiberSwcs/4.0/locale"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.flexunit_4.0.1.277662/flexunitframework/libs/version4libs/Common"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.flexunit_4.0.1.277662/flexunitframework/libs/version4libs/FlexProject"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.flexunit_4.0.1.277662/flexunitframework/locale/version4locale"'/&gt; &lt;arg line='-compiler.library-path "C:/rms-it-apps/adobe/fb4/plugins/com.adobe.flexbuilder.flexunit_4.0.1.277662/flexunitframework/libs"'/&gt; --&gt; &lt;!-- Runtime shared libraries. Order matters. --&gt; &lt;!-- Load framework libraries first --&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/textLayout.swc","textLayout_1.1.0.604.swz",,"textLayout_1.1.0.604.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/osmf.swc","osmf_flex.4.0.0.13495.swz",,"osmf_flex.4.0.0.13495.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/framework.swc","framework_4.1.0.16076.swz",,"framework_4.1.0.16076.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/spark.swc","spark_4.1.0.16076.swz",,"spark_4.1.0.16076.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/sparkskins.swc","sparkskins_4.1.0.16076.swz",,"sparkskins_4.1.0.16076.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/rpc.swc","rpc_4.1.0.16076.swz",,"rpc_4.1.0.16076.swf"'/&gt; &lt;arg line='-runtime-shared-library-path="@{sdk}/frameworks/libs/datavisualization.swc","datavisualization_4.1.0.16076.swz",,"datavisualization_4.1.0.16076.swf"'/&gt; &lt;!-- Load after framework libraries --&gt; &lt;!-- Note: do not put spaces between comma delimited values --&gt; &lt;arg line='${rsl.applicationSettings}'/&gt; &lt;arg line='${rsl.authorization}'/&gt; &lt;arg line='${rsl.autofill}'/&gt; &lt;arg line='${rsl.customComponents}'/&gt; &lt;arg line='${rsl.navigation}'/&gt; &lt;arg line='${rsl.lookup}'/&gt; &lt;!-- Libraries needed for QTP --&gt; &lt;arg line="${qtp.arg1}"/&gt; &lt;arg line="${qtp.arg2}"/&gt; &lt;arg line="${qtp.arg3}"/&gt; &lt;arg line="${qtp.arg4}"/&gt; &lt;arg line="${qtp.arg5}"/&gt; &lt;arg line="-verify-digests=false"/&gt; &lt;!-- Flex Compiler --&gt; &lt;!-- Compiler options --&gt; &lt;arg line="-compiler.accessible=true"/&gt; &lt;arg line="-compiler.strict=true"/&gt; &lt;arg line="-warnings=true" /&gt; &lt;!-- Additional compiler arguments: --&gt; &lt;arg line='-theme=@{sdk}/frameworks/themes/Halo/halo.swc -services "@{services-config}" -locale en_US'/&gt; &lt;!-- Flex Server --&gt; &lt;!-- Server location --&gt; &lt;!-- Context root: --&gt; &lt;arg line="-compiler.context-root=@{context-root}"/&gt; &lt;!-- Miscellaneous --&gt; &lt;arg line="-compiler.incremental=true"/&gt; &lt;arg line="-compiler.keep-generated-actionscript=false"/&gt; &lt;arg line="-compiler.verbose-stacktraces=true"/&gt; &lt;arg line="-show-unused-type-selector-warnings=false"/&gt; &lt;arg line="-optimize=true" /&gt; &lt;arg line="-debug=@{debug}" /&gt; &lt;arg line='"@{mxml}"'/&gt; &lt;/exec&gt; </code></pre> <p>This is the error I'm getting:</p> <pre><code>BUILD FAILED C:\dev\workspace\rmsitepi2\build.raytheon.suite.tomcat.xml:50: The following error occurred while executing this line: C:\dev\workspace\rmsitepi2\build.raytheon.flex.xml:33: The following error occurred while executing this line: C:\dev\workspace\rmsitepi2\build.raytheon.flex.xml:159: exec returned: 1 </code></pre>
0
3,815
JtaTransactionManager no rollback after failed commit during "flush"
<p><br/> <strong>Update:</strong> I was testing it with Bitronix TM and it rollbacks perfectly, so the issue is in JBoss TM (arjuna) or in my configuration. <br/></p> <p><strong>Update 2:</strong> It looks like transactions are not global, I've tried different datasources, Bitronix datasource has <em>allowLocalTransactions</em> property and after setting it my application throws an exception that something tried to use it in local mode. If I use Bitronix with this datasource it works without any errors. I believe there is something wrong in configs.</p> <p>I have an issue with JTA transactions. I'm using Tomcat 7 + Hibernate 4 + Spring 3 + JBoss TS 4 and JTA transactions.</p> <p>Suppose there is the following method:</p> <pre><code>@Transactional(propagation = Propagation.REQUIRED) public void testMethod() { insertOfSomeNewEntityInstance(); updateOfAnotherEntity(); } private void insertOfSomeNewEntityInstance() { SomeEntity entity = new SomeEntity(); someEntityDAO.save(entity); } private void updateOfAnotherEntity() { AnotherEntity anotherEntity = anotherEntityDAO.findBySomeProperty(1L); anotherEntity.incrementSomeValue(); anotherEntityDAO.save(anotherEntity); } </code></pre> <p>If this method throws <em>"org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)"</em> during "updateOfAnotherEntity()" method execution or any other runtime exception that might happen during "flush" (Hibernate also shows: <em>HHH000346: Error during managed flush [Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)</em>. then the result of insertOfSomeNewEntityInstance() execution is not rolled back.</p> <p>After debugging this issue I found "doCommit" method in org.springframework.transaction.jta.JtaTransaction Manager</p> <pre><code>@Override protected void doCommit(DefaultTransactionStatus status) { JtaTransactionObject txObject = (JtaTransactionObject) status.getTransaction(); try { int jtaStatus = txObject.getUserTransaction().getStatus(); if (jtaStatus == Status.STATUS_NO_TRANSACTION) { throw new UnexpectedRollbackException("JTA transaction already completed - probably rolled back"); } if (jtaStatus == Status.STATUS_ROLLEDBACK) { try { txObject.getUserTransaction().rollback(); } catch (IllegalStateException ex) { if (logger.isDebugEnabled()) { logger.debug("Rollback failure with transaction already marked as rolled back: " + ex); } } throw new UnexpectedRollbackException("JTA transaction already rolled back (probably due to a timeout)"); } txObject.getUserTransaction().commit(); } catch (RollbackException ex) { throw new UnexpectedRollbackException( "JTA transaction unexpectedly rolled back (maybe due to a timeout)", ex); } catch (HeuristicMixedException ex) { throw new HeuristicCompletionException(HeuristicCompletionException.STATE_MIXED, ex); } catch (HeuristicRollbackException ex) { throw new HeuristicCompletionException(HeuristicCompletionException.STATE_ROLLED_BACK, ex); } catch (IllegalStateException ex) { throw new TransactionSystemException("Unexpected internal transaction state", ex); } catch (SystemException ex) { throw new TransactionSystemException("JTA failure on commit", ex); } } </code></pre> <p>If "txObject.getUserTransaction().commit();" fails with RollbackException then this method throws UnexpectedRollbackException and here is the part of org.springframework.transaction.support.AbstractPl atformTransactionManager processCommit(...) that catches it:</p> <pre><code>} catch (UnexpectedRollbackException ex) { // can only be caused by doCommit triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK); throw ex; } </code></pre> <p>I do not see any rollbacks in triggerAfterCompletion() method and after this method everything else just cleans up resources.</p> <p><strong>To sum up</strong>, spring/jboss just commits the result of insertOfSomeNewEntityInstance(), fails to execute updateOfAnotherEntity() because of concurrent modification error, and does not rollback anything. If I manually throw any runtime or checked exception from updateOfAnotherEntity() it rollbacks correctly, the issue occurs only when Hibernate throws some runtime exception during "flush".</p> <p><strong>hibernate.cfg</strong></p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="dialect"&gt;${dialect}&lt;/property&gt; &lt;property name="max_fetch_depth"&gt;1&lt;/property&gt; &lt;property name="hibernate.jdbc.batch_size"&gt;25&lt;/property&gt; &lt;property name="show_sql"&gt;false&lt;/property&gt; &lt;property name="format_sql"&gt;false&lt;/property&gt; &lt;property name="use_sql_comments"&gt;false&lt;/property&gt; &lt;property name="hibernate.session_factory_name"&gt;TestSessionFactory&lt;/property&gt; &lt;property name="hibernate.session_factory_name_is_jndi"&gt;false&lt;/property&gt; &lt;property name="hibernate.current_session_context_class"&gt;jta&lt;/property&gt; &lt;property name="hibernate.transaction.factory_class"&gt;org.hibernate.transaction.JTATransactionFactory&lt;/property&gt; &lt;property name="hibernate.transaction.jta.platform"&gt;org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform&lt;/property&gt; &lt;property name="hibernate.id.new_generator_mappings"&gt;true&lt;/property&gt; &lt;property name="hibernate.cache.infinispan.cfg"&gt;infinispan.xml&lt;/property&gt; &lt;property name="hibernate.cache.region.factory_class"&gt;org.hibernate.cache.infinispan.InfinispanRegionFactory&lt;/property&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p><strong>jbossts-properties.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt; &lt;properties&gt; &lt;entry key="CoordinatorEnvironmentBean.commitOnePhase"&gt;YES&lt;/entry&gt; &lt;entry key="CoordinatorEnvironmentBean.defaultTimeout"&gt;300&lt;/entry&gt; &lt;entry key="ObjectStoreEnvironmentBean.transactionSync"&gt;ON&lt;/entry&gt; &lt;entry key="CoreEnvironmentBean.nodeIdentifier"&gt;1&lt;/entry&gt; &lt;entry key="JTAEnvironmentBean.xaRecoveryNodes"&gt;1&lt;/entry&gt; &lt;entry key="JTAEnvironmentBean.xaResourceOrphanFilterClassNames"&gt; com.arjuna.ats.internal.jta.recovery.arjunacore.JTATransactionLogXAResourceOrphanFilter com.arjuna.ats.internal.jta.recovery.arjunacore.JTANodeNameXAResourceOrphanFilter &lt;/entry&gt; &lt;entry key="CoreEnvironmentBean.socketProcessIdPort"&gt;0&lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.recoveryModuleClassNames"&gt; com.arjuna.ats.internal.arjuna.recovery.AtomicActionRecoveryModule com.arjuna.ats.internal.txoj.recovery.TORecoveryModule com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule &lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.expiryScannerClassNames"&gt; com.arjuna.ats.internal.arjuna.recovery.ExpiredTransactionStatusManagerScanner &lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.recoveryPort"&gt;4712&lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.recoveryAddress"&gt;&lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.transactionStatusManagerPort"&gt;0&lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.transactionStatusManagerAddress"&gt;&lt;/entry&gt; &lt;entry key="RecoveryEnvironmentBean.recoveryListener"&gt;YES&lt;/entry&gt; &lt;/properties&gt; </code></pre> <p><strong>Part of applicationContext.xml</strong></p> <pre><code>&lt;bean class="com.arjuna.ats.jta.TransactionManager" factory-method="transactionManager" id="arjunaTransactionManager"&gt;&lt;/bean&gt; &lt;bean class="com.arjuna.ats.jta.UserTransaction" factory-method="userTransaction" id="arjunaUserTransaction"&gt;&lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" &gt; &lt;property name="transactionManager" ref="arjunaTransactionManager"/&gt; &lt;property name="userTransaction" ref="arjunaUserTransaction"/&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.apache.tomcat.jdbc.pool.XADataSource" destroy-method="close"&gt; &lt;property name="url" value="${database.url}" /&gt; &lt;property name="driverClassName" value="oracle.jdbc.OracleDriver" /&gt; &lt;property name="username" value="${database.user}" /&gt; &lt;property name="password" value="${database.password}" /&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" destroy-method="destroy"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="configLocation"&gt;&lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt;&lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.cache.use_second_level_cache"&gt;false&lt;/prop&gt; &lt;prop key="hibernate.cache.use_query_cache"&gt;false&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;tx:annotation-driven mode="proxy" proxy-target-class="false" transaction-manager="transactionManager"/&gt; </code></pre> <p><strong>And the log:</strong></p> <pre><code>Completing transaction for [...testMethod] Triggering beforeCommit synchronization Triggering beforeCompletion synchronization BaseTransaction.getStatus TransactionImple.getStatus Initiating transaction commit BaseTransaction.getStatus TransactionImple.getStatus BaseTransaction.commit TransactionImple.commitAndDisassociate SynchronizationImple.beforeCompletion BaseTransaction.getStatus TransactionImple.getStatus insert into ..... update ... set ... BaseTransaction.setRollbackOnly TransactionImple.setRollbackOnly BasicAction::preventCommit( BasicAction: 0:ffffc0a800ab:8d15:51b6fe47:3 status: ActionStatus.RUNNING) HHH000346: Error during managed flush [Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [...]] ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple&lt; 0:ffffc0a800ab:8d15:51b6fe47:4, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization@76d7a0b8 &gt; org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [...] at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2509) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3228) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3126) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3456) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:287) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorImpl.beforeCompletion(SynchronizationCallbackCoordinatorImpl.java:113) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:53) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:273) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:93) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1165) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:126) [narayana-jta-4.17.4.Final.jar:4.17.4.Final] at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1010) [spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) [spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) [spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:387) [spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120) [spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) [spring-aop-3.1.4.RELEASE.jar:3.1.4.RELEASE] at $Proxy126.testMethod(Unknown Source) [na:na] ... BasicAction::preventCommit( BasicAction: 0:ffffc0a800ab:8d15:51b6fe47:3 status: ActionStatus.ABORT_ONLY) BasicAction::Abort() for action-id 0:ffffc0a800ab:8d15:51b6fe47:3 SynchronizationImple.afterCompletion TransactionImple.equals SynchronizationImple.afterCompletion BasicAction::removeChildThread () action 0:ffffc0a800ab:8d15:51b6fe47:3 removing TSThread:2 BasicAction::removeChildThread () action 0:ffffc0a800ab:8d15:51b6fe47:3 removing TSThread:2 result = true TransactionReaper::remove ( BasicAction: 0:ffffc0a800ab:8d15:51b6fe47:3 status: ActionStatus.ABORTED ) Triggering afterCompletion synchronization Clearing transaction synchronization Exception org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction. at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1013) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:387) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) ~[spring-aop-3.1.4.RELEASE.jar:3.1.4.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) ~[spring-aop-3.1.4.RELEASE.jar:3.1.4.RELEASE] at $Proxy126.testMethod(Unknown Source) ~[na:na] ... Caused by: javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction. at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1177) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:126) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1010) ~[spring-tx-3.1.4.RELEASE.jar:3.1.4.RELEASE] ... 32 common frames omitted Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [...] at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:2509) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3228) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3126) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3456) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:287) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorImpl.beforeCompletion(SynchronizationCallbackCoordinatorImpl.java:113) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:53) ~[hibernate-core-4.2.2.Final.jar:4.2.2.Final] at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:273) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:93) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1165) ~[narayana-jta-4.17.4.Final.jar:4.17.4.Final] ... 34 common frames omitted </code></pre>
0
8,345
Angular 2 Routing with Home Page
<p>I am learning Angular2 Routing and try to display the Welcome Page. My app has three pages</p> <ul> <li>Welcome Page (it's just a blank page with just links to other Routes)</li> <li>Home Page - Some texts and Description</li> <li>Todo List Page - List of ToDos</li> </ul> <p>The problem is that I cannot manage to display the Welcome Page. It automatically loads Home page and show the content from the HomeComponent by default.</p> <p>As shown in the screenshot, I want to display only 2 links. I want to load the content from Home/Todo only when it is clicked. But by default, it goes to localhost:xxx/Home and load the Home page.</p> <p><a href="https://i.stack.imgur.com/Dj7Ev.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dj7Ev.png" alt="enter image description here"></a></p> <p>I tried to set the '' blank path to AppComponent as below, but it loads AppComponent twice and shows the links two times.</p> <pre><code>{ path: '', component: AppComponent, pathMatch: 'full' }, </code></pre> <p><strong>app.module.ts</strong></p> <pre><code>@NgModule({ imports: [ BrowserModule, HttpModule, RouterModule.forRoot([ { path: 'home', component: HomeComponent }, { path: 'todo', component: TodoListComponent }, { path: '**', redirectTo: 'home', pathMatch: 'full' } ]) ], declarations: [ AppComponent, HomeComponent, TodoListComponent ], bootstrap: [AppComponent], }) export class AppModule { } </code></pre> <p><strong>app.component.ts</strong></p> <pre><code>import { Component } from "@angular/core" @Component({ moduleId: module.id, selector: 'app', template: ` &lt;div&gt; &lt;nav class='navbar navbar-default'&gt; &lt;div class='container-fluid'&gt; &lt;a class='navbar-brand'&gt;{{pageTitle}}&lt;/a&gt; &lt;ul class='nav navbar-nav'&gt; &lt;li&gt;&lt;a [routerLink]="['/home']"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a [routerLink]="['/todo']"&gt;To Do&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div class='container'&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt; ` }) export class AppComponent { } </code></pre> <p><strong>home/home.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; @Component({ moduleId: module.id, templateUrl: "home.component.html" }) export class HomeComponent { } </code></pre> <p><strong>home/home.component.html</strong></p> <pre><code>&lt;h1&gt;Hello from Home Component&lt;/h1&gt; &lt;h2&gt;This is my first TODO App for Angular 2...&lt;/h2&gt; </code></pre>
0
1,235
Cakephp 3.0.3 How do I use the default layout?
<p>I just installed cakephp 3.0.3 with composer and I am running the built in development cake server to view my site. I have only made two changes to the project. After working with the project for a little while, I realized the default.ctp layout is not loading on my pages.</p> <p>The first thing I did was configure the database connection to MySQL. The next thing I wanted to do was include bootstrap and jQuery. Naturally, I followed the cakephp cookbook and put the css and js in their appropriate folders under webroot. Next I linked to those files in src/Templates/Layout/default.ctp. </p> <p>At first when they did not show up, I guessed it must have been an issue with the command linking them, but when I tried to add other content to be displayed within default.ctp, I realized that the layout is not rendering at all.</p> <p>I am totally new to cakephp and php, but I read straight from the cookbook and just followed their example, I don't know why the default layout would not be loaded at all.</p> <p>I tried to change the appController to include <code>$this-&gt;layout = 'default';</code> as suggested <a href="https://stackoverflow.com/questions/7426469/assigning-layout-in-cakephp">here</a> but that just gave me a strict error saying that appController beforeRender() must be compatible with Controller beforeRender() so I just changed it back to the way it was by default.</p> <p>I am using OS X Yosemite and Google Chrome to view the page if that makes a difference. Everything on the default homepage has check marks saying that everything is installed and configured properly, and I have seen other people that have similar issues where mod_rewrite is their problem but I do not have any errors about mod_rewrite.</p> <p>Here is my default.ctp:</p> <pre><code>&lt;?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 0.10.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ $cakeDescription = "Children's Medical Group"; ?&gt; &lt;!-- This layout is loaded for controller view content --&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;?= $this-&gt;Html-&gt;charset() ?&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;title&gt; &lt;?= $cakeDescription ?&gt;: &lt;?= $this-&gt;fetch('title') ?&gt; &lt;/title&gt; &lt;?= $this-&gt;Html-&gt;meta('icon') ?&gt; &lt;?= $this-&gt;Html-&gt;css('base.css') ?&gt; &lt;?= $this-&gt;Html-&gt;css('cake.css') ?&gt; &lt;?= $this-&gt;fetch('meta') ?&gt; &lt;!-- The following css and js elements are for bootstrap --&gt; &lt;!-- Latest compiled and minified CSS --&gt; &lt;!-- &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"&gt; --&gt; &lt;?= $this-&gt;Html-&gt;css('bootstrap.min.css') ?&gt; &lt;!-- Optional theme --&gt; &lt;!--&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"&gt; --&gt; &lt;?= $this-&gt;Html-&gt;css('bootstrap-theme.min.css') ?&gt; &lt;!-- Not actually sure what this does --&gt; &lt;?= $this-&gt;fetch('css') ?&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="header-title"&gt; &lt;span&gt;&lt;?= $this-&gt;fetch('title') ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="header-help"&gt; &lt;span&gt;&lt;a target="_blank" href="http://book.cakephp.org/3.0/"&gt;Documentation&lt;/a&gt;&lt;/span&gt; &lt;span&gt;&lt;a target="_blank" href="http://api.cakephp.org/3.0/"&gt;API&lt;/a&gt;&lt;/span&gt; &lt;/div&gt; &lt;/header&gt; &lt;div id='.jumbotron'&gt; Testing both bootstrap and default.ctp to see if this shows &lt;/div&gt; &lt;div id="container"&gt; &lt;div id="content"&gt; &lt;?= $this-&gt;Flash-&gt;render() ?&gt; &lt;div class="row"&gt; &lt;?= $this-&gt;fetch('content') ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt; &lt;/footer&gt; &lt;/div&gt; &lt;!-- Latest compiled and minified Bootstrap JavaScript --&gt; &lt;!-- &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"&gt;&lt;/script&gt; --&gt; &lt;?= $this-&gt;Html-&gt;script('bootstrap.min.js'); ?&gt; &lt;!-- Bootstrap requires jQuery to run bootstrap.js--&gt; &lt;?= $this-&gt;Html-&gt;script('jquery-1.11.3.min.js'); ?&gt; &lt;!-- Not actually sure what this does --&gt; &lt;?= $this-&gt;fetch('script') ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and the html source I see when I visit <a href="http://localhost:8765/" rel="nofollow noreferrer">http://localhost:8765/</a>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt; CakePHP: the rapid development php framework &lt;/title&gt; &lt;link href="/favicon.ico" type="image/x-icon" rel="icon"/&gt;&lt;link href="/favicon.ico" type="image/x-icon" rel="shortcut icon"/&gt; &lt;link rel="stylesheet" href="/css/base.css"/&gt; &lt;link rel="stylesheet" href="/css/cake.css"/&gt;&lt;/head&gt; &lt;body class="home"&gt; &lt;header&gt; &lt;div class="header-image"&gt; &lt;img src="http://cakephp.org/img/cake-logo.png" alt=""/&gt; &lt;h1&gt;Get the Ovens Ready&lt;/h1&gt; &lt;/div&gt; &lt;/header&gt; &lt;div id="content"&gt; &lt;p id="url-rewriting-warning" style="background-color:#e32; color:#fff;display:none"&gt; URL rewriting is not properly configured on your server. 1) &lt;a target="_blank" href="http://book.cakephp.org/3.0/en/installation/url-rewriting.html" style="color:#fff;"&gt;Help me configure it&lt;/a&gt; 2) &lt;a target="_blank" href="http://book.cakephp.org/3.0/en/development/configuration.html#general-configuration" style="color:#fff;"&gt;I don't / can't use URL rewriting&lt;/a&gt; &lt;/p&gt; &lt;div class="row"&gt; &lt;div class="columns large-5 platform checks"&gt; &lt;p class="success"&gt;Your version of PHP is 5.4.16 or higher.&lt;/p&gt; &lt;p class="success"&gt;Your version of PHP has the mbstring extension loaded.&lt;/p&gt; &lt;p class="success"&gt;Your version of PHP has the openssl extension loaded.&lt;/p&gt; &lt;p class="success"&gt;Your version of PHP has the intl extension loaded.&lt;/p&gt; &lt;/div&gt; &lt;div class="columns large-6 filesystem checks"&gt; &lt;p class="success"&gt;Your tmp directory is writable.&lt;/p&gt; &lt;p class="success"&gt;Your logs directory is writable.&lt;/p&gt; &lt;p class="success"&gt;The &lt;em&gt;FileEngine&lt;/em&gt; is being used for core caching. To change the config edit config/app.php&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="columns large-12 database checks"&gt; &lt;p class="success"&gt;CakePHP is able to connect to the database.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="columns large-6"&gt; &lt;h3&gt;Editing this Page&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;To change the content of this page, edit: src/Template/Pages/home.ctp.&lt;/li&gt; &lt;li&gt;You can also add some CSS styles for your pages at: webroot/css/.&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="columns large-6"&gt; &lt;h3&gt;Getting Started&lt;/h3&gt; &lt;ul&gt; &lt;li&gt;&lt;a target="_blank" href="http://book.cakephp.org/3.0/en/"&gt;CakePHP 3.0 Docs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a target="_blank" href="http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html"&gt;The 15 min Bookmarker Tutorial&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a target="_blank" href="http://book.cakephp.org/3.0/en/tutorials-and-examples/blog/blog.html"&gt;The 15 min Blog Tutorial&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr/&gt; &lt;div class="row"&gt; &lt;div class="columns large-12"&gt; &lt;h3 class=""&gt;More about Cake&lt;/h3&gt; &lt;p&gt; CakePHP is a rapid development framework for PHP which uses commonly known design patterns like Front Controller and MVC. &lt;/p&gt; &lt;p&gt; Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility. &lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://cakefoundation.org/"&gt;Cake Software Foundation&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Promoting development related to CakePHP&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.cakephp.org"&gt;CakePHP&lt;/a&gt; &lt;ul&gt;&lt;li&gt;The Rapid Development Framework&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://book.cakephp.org/3.0/en/"&gt;CakePHP Documentation&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Your Rapid Development Cookbook&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://api.cakephp.org/3.0/"&gt;CakePHP API&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Quick Reference&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://bakery.cakephp.org"&gt;The Bakery&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Everything CakePHP&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://plugins.cakephp.org"&gt;CakePHP plugins repo&lt;/a&gt; &lt;ul&gt;&lt;li&gt;A comprehensive list of all CakePHP plugins created by the community&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="https://groups.google.com/group/cake-php"&gt;CakePHP Google Group&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Community mailing list&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="irc://irc.freenode.net/cakephp"&gt;irc.freenode.net #cakephp&lt;/a&gt; &lt;ul&gt;&lt;li&gt;Live chat about CakePHP&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="https://github.com/cakephp/"&gt;CakePHP Code&lt;/a&gt; &lt;ul&gt;&lt;li&gt;For the Development of CakePHP Git repository, Downloads&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="https://github.com/cakephp/cakephp/issues"&gt;CakePHP Issues&lt;/a&gt; &lt;ul&gt;&lt;li&gt;CakePHP issues and pull requests&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt; &lt;/footer&gt; &lt;script&gt;var __debug_kit_id = 'cade8b34-e4ea-4601-a30e-a3a941ddf855', __debug_kit_base_url = 'http://localhost:8765/';&lt;/script&gt;&lt;script src="/debug_kit/js/toolbar.js"&gt;&lt;/script&gt;&lt;/body&gt; &lt;/html&gt; </code></pre>
0
6,100
Get PDF hyperlinks on iOS with Quartz
<p>I've spent all day trying to get hyperlinks metadata from PDFs in my iPad application. The CGPDF* APIs are a true nightmare, and the only piece of information I've found on the net about all this is that I have to look for an "Annots" dictionary, but I just can't find it in my PDFs. </p> <p>I even used the old <a href="https://github.com/below/PDF-Voyeur/network" rel="nofollow noreferrer">Voyeur Xcode sample</a> to inspect my test PDF file, but no trace of this "Annots" dictionary...</p> <p>You know, this is a feature I see on every PDF reader - this same question has <a href="https://stackoverflow.com/questions/93297/newbie-wants-to-create-a-pdf-reader-for-ipod-touch-whats-the-best-approach">been</a> <a href="https://stackoverflow.com/questions/3257057/iphone-cgpdfdocument-pdf-links">asked</a> <a href="https://stackoverflow.com/questions/2609602/pdf-hyperlinks-on-iphone-ipad">multiple</a> <a href="https://stackoverflow.com/questions/1247792/how-to-access-hyperlinks-in-pdf-documents-iphone">times</a> here with no real practical answers. I usually never ask for sample code directly but apparently this time I really need it... anyone got this working, possibly with sample code?</p> <p><strong>Update</strong>: I just realized the guy who has done my testing PDF had just inserted an URL as text, and not a real annotation. He tried putting an annotation and my code works now... But that's not what I need, so it seems I'll have to analyze text and search for URLs. But that's another story... </p> <p><strong>Update 2</strong>: So I finally came up with some working code. I'm posting it here so hopefully it'll help someone. It assumes the PDF document actually contains annotations. </p> <pre><code>for(int i=0; i&lt;pageCount; i++) { CGPDFPageRef page = CGPDFDocumentGetPage(doc, i+1); CGPDFDictionaryRef pageDictionary = CGPDFPageGetDictionary(page); CGPDFArrayRef outputArray; if(!CGPDFDictionaryGetArray(pageDictionary, "Annots", &amp;outputArray)) { return; } int arrayCount = CGPDFArrayGetCount( outputArray ); if(!arrayCount) { continue; } for( int j = 0; j &lt; arrayCount; ++j ) { CGPDFObjectRef aDictObj; if(!CGPDFArrayGetObject(outputArray, j, &amp;aDictObj)) { return; } CGPDFDictionaryRef annotDict; if(!CGPDFObjectGetValue(aDictObj, kCGPDFObjectTypeDictionary, &amp;annotDict)) { return; } CGPDFDictionaryRef aDict; if(!CGPDFDictionaryGetDictionary(annotDict, "A", &amp;aDict)) { return; } CGPDFStringRef uriStringRef; if(!CGPDFDictionaryGetString(aDict, "URI", &amp;uriStringRef)) { return; } CGPDFArrayRef rectArray; if(!CGPDFDictionaryGetArray(annotDict, "Rect", &amp;rectArray)) { return; } int arrayCount = CGPDFArrayGetCount( rectArray ); CGPDFReal coords[4]; for( int k = 0; k &lt; arrayCount; ++k ) { CGPDFObjectRef rectObj; if(!CGPDFArrayGetObject(rectArray, k, &amp;rectObj)) { return; } CGPDFReal coord; if(!CGPDFObjectGetValue(rectObj, kCGPDFObjectTypeReal, &amp;coord)) { return; } coords[k] = coord; } char *uriString = (char *)CGPDFStringGetBytePtr(uriStringRef); NSString *uri = [NSString stringWithCString:uriString encoding:NSUTF8StringEncoding]; CGRect rect = CGRectMake(coords[0],coords[1],coords[2],coords[3]); CGPDFInteger pageRotate = 0; CGPDFDictionaryGetInteger( pageDictionary, "Rotate", &amp;pageRotate ); CGRect pageRect = CGRectIntegral( CGPDFPageGetBoxRect( page, kCGPDFMediaBox )); if( pageRotate == 90 || pageRotate == 270 ) { CGFloat temp = pageRect.size.width; pageRect.size.width = pageRect.size.height; pageRect.size.height = temp; } rect.size.width -= rect.origin.x; rect.size.height -= rect.origin.y; CGAffineTransform trans = CGAffineTransformIdentity; trans = CGAffineTransformTranslate(trans, 0, pageRect.size.height); trans = CGAffineTransformScale(trans, 1.0, -1.0); rect = CGRectApplyAffineTransform(rect, trans); // do whatever you need with the coordinates. // e.g. you could create a button and put it on top of your page // and use it to open the URL with UIApplication's openURL } } </code></pre>
0
1,852
ui-bootstrap-tpls failed to load template
<p>I've inherited an angular project, and it's having problems loading the ui-bootstrap-tpls modules.</p> <p>For each directive it's trying to use from bootstrap, I get something similar to the following:</p> <p>Error: [$compile:tpload] Failed to load template: template/datepicker/popup.html</p> <p>I've read about the need to include the tpls version of the ui-bootstrap lib. (ui-bootstrap-tpls-0.10.0.js (instead of ui-bootstrap.js)), but having done that as well as every permutation of module injected into my module as a dependency (ui.bootstrap, ui.bootstrap.tpls, template/datepicker/datepicker.html'), but I can't beat it.</p> <p>Here're my includes: </p> <pre><code>&lt;html class="no-js" ng-app="hiringApp"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;@ViewBag.Title&lt;/title&gt; &lt;meta content="IE=edge" http-equiv="X-UA-Compatible"&gt; &lt;meta content="width=device-width, initial-scale=1.0" name="viewport"&gt; &lt;meta name="layout" content="IRLayout"&gt; &lt;!-- styles IRLayout--&gt; &lt;link rel="stylesheet" href="//cdn.datatables.net/1.10.0-beta.1/css/jquery.dataTables.css"&gt; &lt;!-- BootStrap --&gt; &lt;link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"&gt; &lt;!-- font-awesome --&gt; &lt;link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="@Url.Content("~/content/css/layout.css")"&gt; &lt;link rel="stylesheet" href="@Url.Content("~/content/css/normalize.css")"&gt; &lt;link rel="stylesheet" href="@Url.Content("~/content/css/main.css")"&gt; &lt;link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/Upload.css")"&gt; &lt;link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/styles.css")"&gt; &lt;link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/site-specific.css")"&gt; &lt;link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/rating.css")"&gt; &lt;!-- Upload --&gt; @*&lt;link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/Upload.css")"&gt;*@ &lt;!-- Header Scripts--&gt; &lt;!-- Jquery &amp; Jquery UI --&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/Vendor/underscore-min.js")"&gt;&lt;/script&gt; &lt;!-- BootStrap --&gt; &lt;!-- Validate --&gt; &lt;script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"&gt;&lt;/script&gt; &lt;!-- Analytics --&gt; &lt;script src="//cdn.datatables.net/1.10.0-beta.1/js/jquery.dataTables.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/graphael/0.5.1/g.raphael-min.js"&gt;&lt;/script&gt; &lt;!-- Angular --&gt; &lt;!-- &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-animate.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-resource.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"&gt;&lt;/script&gt; --&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-animate.js"&gt;&lt;/script&gt; &lt;script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-resource.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/app.js")"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/controllers.js")"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/directives.js")"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/filters.js")"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/Scripts/services.js")"&gt;&lt;/script&gt; &lt;script&gt; angular.module("hiringApp").constant("$userProvider", @Model.User.SystemRoles); angular.module("hiringApp").constant("$jobProvider", ''); &lt;/script&gt; &lt;!-- Upload --&gt; &lt;script src="@Url.Content("~/content/js/plupload.full.js")"&gt;&lt;/script&gt; &lt;script src="@Url.Content("~/content/js/UploadImage.js")"&gt;&lt;/script&gt; &lt;script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'&gt;&lt;/script&gt; &lt;script src="~/Content/js/audio/irAudioRecorder.js"&gt;&lt;/script&gt; @RenderSection("script", required: false) &lt;/head&gt; </code></pre> <p>Here's my app module:</p> <pre><code>var hiringApp = angular.module('hiringApp', ['ui.router', 'ngAnimate', 'ngResource', 'filters', 'ui.bootstrap', 'ui.bootstrap.tpls']); </code></pre> <p>Here's the error: </p> <pre><code>GET http://localhost:54720/template/tooltip/tooltip-popup.html 404 (Not Found) angular.js:8539 7Error: [$compile:tpload] Failed to load template: template/tooltip/tooltip-popup.html http://errors.angularjs.org/1.2.22/$compile/tpload?p0=template%2Ftooltip%2Ftooltip-popup.html at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:78:12 at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:6900:17 at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:8098:11 at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78) at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78) at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78) at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11688:76 at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12658:28) at Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12470:31) at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12762:24) </code></pre>
0
3,116
ConstraintViolationException when trying to persist
<p>I get the following error whenever I try to persist a child objects to a existing father object in JPA:</p> <blockquote> <p>Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [store.entidades.Sucursal] during persist time for groups [javax.validation.groups.Default, ] List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Por favor ingrese un valor en direccion', propertyPath=direccion, rootBeanClass=class store.entidades.Sucursal, messageTemplate='Por favor ingrese un valor en direccion'} ConstraintViolationImpl{interpolatedMessage='Por favor ingrese un valor en telefono', propertyPath=telefono, rootBeanClass=class store.entidades.Sucursal, messageTemplate='Por favor ingrese un valor en telefono'} ]</p> </blockquote> <p>This is the parent entity class that Im using:</p> <pre><code> @Entity public class Sucursal { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; // nombre del encargado de esa sucursal private String subgerente; @NotNull(message = "Por favor ingrese un valor en direccion") @Column(length = 120) private String direccion; @NotNull(message = "Por favor ingrese un valor en telefono") @Column(length = 36, unique = true) private String telefono; @OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "producto_sucursal", referencedColumnName = "id") private List&lt;Producto&gt; producto = new ArrayList&lt;Producto&gt;(); //getters and setters </code></pre> <p>This is the child entity class that Im using:</p> <pre><code> @Entity public class Producto { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @NotNull(message = "Por favor ingrese un valor") private String nombre; @NotNull(message = "Por favor ingrese un valor") @Column(length = 140) private String descripcion; @NotNull(message = "Por favor ingrese un valor") private double precio; @NotNull(message = "Por favor ingrese un valor") private String imagen1; @NotNull(message = "Por favor ingrese un valor") private String imagen2; @NotNull(message = "Por favor ingrese un valor") private String imagen3; private int megusta; private int nomegusta; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "comentario_producto", referencedColumnName = "id") private List&lt;Comentario&gt; comentario = new ArrayList&lt;Comentario&gt;();// @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "producto_subcategoria") private Subcategoria subcategoria = new Subcategoria(); @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "producto_categoria") private Categoria categoria = new Categoria(); @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER) @JoinColumn(name = "producto_sucursal") private Sucursal sucursal = new Sucursal(); //getters and setters </code></pre> <p>My DAO class for Sucursal looks like this:</p> <pre><code>@Stateless public class SucursalDAO implements Serializable { @Inject private EntityManager entityManager; public void save(Sucursal sucursal) { if (entityManager.find(Sucursal.class, sucursal.getId()) == null) { insertar(sucursal); } else { update(sucursal); } } // ... } </code></pre> <p>Whenever I click on a save button in front end it calls this method:</p> <pre><code>public void guardar() { System.out.println(newSucursal.getDireccion()); System.out.println(newSucursal.getTelefono()); for (int i = 0; i &lt; listproductos.size(); i++) { // listproductos.get(i).setSucursal(newSucursal); System.out.println(listproductos.get(i).toString()); newSucursal.getProductos().add(listproductos.get(i)); } sucursalDAO.save(newSucursal); } </code></pre> <p>When I call this save method I add the new child <strong>Productos</strong> to my <strong>Sucursales</strong> but when I try to persist the Parent it give me the error I posted above. I have tried many things but cant seem to figure out what the problem is? Is there another way of saving child entities to existing parent entities?</p> <p><strong>EDIT</strong></p> <p>This is the code that fixed my problem for my save method:</p> <pre><code>public void guardar() { System.out.println(newSucursal.getDireccion()); System.out.println(newSucursal.getTelefono()); for (int i = 0; i &lt; listproductos.size(); i++) { listproductos.get(i).setSucursal(newSucursal); Categoria cat = new Categoria(); cat = categoriaDAO.read(listproductos.get(i).getCategoria().getId()); listproductos.get(i).setCategoria(cat); Subcategoria subcat = new Subcategoria(); subcat = subcategoriaDAO.read(listproductos.get(i).getSubcategoria().getId()); listproductos.get(i).setSubcategoria(subcat); System.out.println(listproductos.get(i).toString()); newSucursal.getProductos().add(listproductos.get(i)); } // newSucursal.setProductos(listproductos); sucursalDAO.save(newSucursal); } </code></pre>
0
2,174
jQuery: Clearing Form Inputs
<p>I have tried to different ways to clear a form:</p> <pre><code>&lt;form action="service.php" id="addRunner" name="addRunner" method="post"&gt; First Name: &lt;input type="text" name="txtFirstName" id="txtFirstName" /&gt;&lt;br /&gt; Last Name: &lt;input type="text" name="txtLastName" id="txtLastName" /&gt;&lt;br /&gt; Gender: &lt;select id="ddlGender" name="ddlGender"&gt;&lt;option value=""&gt;--Please Select--&lt;/option&gt; &lt;option value="f"&gt;Female&lt;/option&gt; &lt;option value="m"&gt;Male&lt;/option&gt; &lt;/select&gt;&lt;br /&gt; Finish Time: &lt;input type="text" name="txtMinutes" id="txtMinutes" size="10" maxlength="2"&gt;(Minutes) &lt;input type="text" name="txtSeconds" id="txtSeconds" size="10" maxlength="2"&gt;(Seconds) &lt;br /&gt; &lt;button type="submit" name="btnSave" id="btnSave"&gt;Add Runner&lt;/button&gt; &lt;input type="hidden" name="action" value="addRunner" id="action"&gt; &lt;/form&gt; </code></pre> <p>jQuery #1:</p> <pre><code>function clearInputs(){ $("#txtFirstName").val(''); $("#txtLastName").val(''); $("#ddlGender").val(''); $("#txtMinutes").val(''); $("#txtSeconds").val(''); } </code></pre> <p>This works perfectly.</p> <p>jQuery #2:</p> <pre><code>function clearInputs(data){ $("#addRunner :input").each(function(){ $(this).val(''); }); </code></pre> <p>This clears the form but does not let me submit any more any information to it. I try and click the button again and it does nothing.</p> <p>Here's the button click handler:</p> <pre><code>$("#btnSave").click(function(){ var data = $("#addRunner :input").serializeArray(); $.post($("#addRunner").attr('action'), data, function(json){ if (json.status == "fail"){ alert(json.message); } if (json.status == "success"){ alert(json.message); clearInputs(); } }, "json"); }); </code></pre> <p>PHP Post code:</p> <pre><code>&lt;?php if($_POST){ if ($_POST['action'] == 'addRunner') { $fname = htmlspecialchars($_POST['txtFirstName']); $lname = htmlspecialchars($_POST['txtLastName']); $gender = htmlspecialchars($_POST['ddlGender']); $minutes = htmlspecialchars($_POST['txtMinutes']); $seconds = htmlspecialchars($_POST['txtSeconds']); if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) { fail('Invalid name provided.'); } if( empty($fname) || empty($lname) ) { fail('Please enter a first and last name.'); } if( empty($gender) ) { fail('Please select a gender.'); } if( empty($minutes) || empty($seconds) ) { fail('Please enter minutes and seconds.'); } $time = $minutes.":".$seconds; $query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'"; $result = db_connection($query); if ($result) { $msg = "Runner: ".$fname." ".$lname." added successfully" ; success($msg); } else { fail('Insert failed.'); } exit; } </code></pre> <p>} </p> <p>If I use jQuery method #2, I get this error in the console:</p> <pre><code>Uncaught TypeError: Cannot read property 'status' of null </code></pre> <p>Why does this happen?</p> <p>I forgot to include this key information:</p> <pre><code>function fail ($message){ die(json_encode(array('status'=&gt;'fail', 'message'=&gt;$message))); } function success ($message){ die(json_encode(array('status'=&gt;'success', 'message'=&gt;$message))); </code></pre> <p>This sends the message back to the AJAX function in jQuery. It looks like after I submit the form once using method #2 the success/fail messages are blanked out.</p>
0
1,583
Trigger "onchange" event
<p>The "onchange" event is triggered only when the USER enters some value. Why isn't possible to fire the event when I change the value automatically via Javascript ? Is there an alternative ?</p> <p><strong>Animation:</strong></p> <p><img src="https://i.stack.imgur.com/vqCom.gif" alt="enter image description here"></p> <p><strong>Code:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script&gt; document.addEventListener ("DOMContentLoaded", function () { var input = this.getElementsByTagName ("input")[0]; var div = this.getElementsByTagName ("div")[0]; var i = 0; var seconds = 5; div.innerHTML = "The following input should fire the event in " + seconds + " seconds"; var interval = window.setInterval (function () { i ++; if (i === seconds) { window.clearInterval (interval); input.value = "Another example"; div.innerHTML = "Nothing ! Now try change the value manually"; } else { div.innerHTML = "The following input should fire the event in " + (seconds - i) + " seconds"; } }, 1000); input.addEventListener ("change", function () { alert ("It works !"); }, false); }, false); &lt;/script&gt; &lt;style&gt; body { padding: 10px; } div { font-weight: bold; margin-bottom: 10px; } input { border: 1px solid black; border-radius: 3px; padding: 3px; } &lt;/style&gt; &lt;title&gt;Event&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;&lt;/div&gt; &lt;input type = "text" value = "Example" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Thanks</p>
0
1,132
ASP.NET / C#: DropDownList SelectedIndexChanged event not firing
<p>My selectedindexchanged event is not firing when I select values in my dropdown lists. These dropdown lists are implemented dynamically in the following code. I have tried changing autopostback and enableviewstate settings to no avail. I am using a static panel. Does anyone see how I can cause the selectedindexchanged event to fire?</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ADONET_namespace; namespace AddFileToSQL { public partial class DataMatch : _Default { protected System.Web.UI.WebControls.PlaceHolder phTextBoxes; protected System.Web.UI.WebControls.PlaceHolder phDropDownLists; protected System.Web.UI.WebControls.Button btnAnotherRequest; protected System.Web.UI.WebControls.Panel pnlCreateData; protected System.Web.UI.WebControls.Literal lTextData; protected System.Web.UI.WebControls.Panel pnlDisplayData; //Panel pnlDropDownList; protected static string inputfile2; static string[] headers = null; static string[] data = null; static string[] data2 = null; static DataTable myInputFile = new DataTable("MyInputFile"); static string[] myUserSelections; // a Property that manages a counter stored in ViewState protected int NumberOfControls { get { return (int)ViewState["NumControls"]; } set { ViewState["NumControls"] = value; } } public void EditRecord(object recordID) { SelectedRecordID = recordID; // Load record from database and show in control } protected object SelectedRecordID { get { return ViewState["SelectedRecordID"]; } set { ViewState["SelectedRecordID"] = value; } } // Page Load private void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { this.NumberOfControls = 0; } } // Add DropDownList Control to Placeholder private void CreateDropDownLists() { for (int counter = 0; counter &lt; NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + (counter + 1).ToString(); ddl.DataTextField = "COLUMN_NAME"; ddl.DataValueField = "COLUMN_NAME"; ddl.DataSource = dr; ddl.DataBind(); //myUserSelections[counter] = ""; ddl.AutoPostBack = true; ddl.EnableViewState = true; //Preserves View State info on Postbacks ddl.Style["position"] = "absolute"; ddl.Style["top"] = 100 * counter + 80 + "px"; ddl.Style["left"] = 250 + "px"; ddl.SelectedIndexChanged += new EventHandler(SelectedIndexChanged); pnlDisplayData.Controls.Add(ddl); pnlDisplayData.Controls.Add(new LiteralControl("&lt;br&gt;&lt;br&gt;&lt;br&gt;")); pnlDisplayData.Visible = true; // pnlDropDownList.FindControl(ddl.ID); dr.Close(); } } protected void SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddl = (DropDownList)sender; string ID = ddl.ID; } // Add TextBoxes Control to Placeholder private void RecreateDropDownLists() { for (int counter = 0; counter &lt; NumberOfControls; counter++) { DropDownList ddl = new DropDownList(); SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable); ddl.ID = "DropDownListID" + (counter + 1).ToString(); ddl.DataTextField = "COLUMN_NAME"; ddl.DataValueField = "COLUMN_NAME"; ddl.DataSource = dr; ddl.DataBind(); myUserSelections[counter] = ""; dr.Close(); ddl.AutoPostBack = true; ddl.EnableViewState = false; //Preserves View State info on Postbacks ddl.Style["position"] = "absolute"; ddl.Style["top"] = 100 * counter + 80 + "px"; ddl.Style["left"] = 250 + "px"; pnlDisplayData.Controls.Add(ddl); pnlDisplayData.Controls.Add(new LiteralControl("&lt;br&gt;&lt;br&gt;&lt;br&gt;")); } } // Create TextBoxes and DropDownList data here on postback. protected override void CreateChildControls() { // create the child controls if the server control does not contains child controls this.EnsureChildControls(); // Creates a new ControlCollection. this.CreateControlCollection(); // Here we are recreating controls to persist the ViewState on every post back if (Page.IsPostBack) { RecreateDropDownLists(); RecreateLabels(); } // Create these conrols when asp.net page is created else { PopulateFileInputTable(); CreateDropDownLists(); CreateLabels(); } // Prevent child controls from being created again. this.ChildControlsCreated = true; } // Read all the data from TextBoxes and DropDownLists protected void btnSubmit_Click(object sender, System.EventArgs e) { int cnt = FindOccurence("DropDownListID"); EditRecord("DropDownListID" + Convert.ToString(cnt + 1)); AppendRecords(); pnlDisplayData.Visible = false; } private int FindOccurence(string substr) { string reqstr = Request.Form.ToString(); return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length); } } } </code></pre>
0
3,006
Accessing Keys from Linux Input Device
<h2>What I am trying to do</h2> <p>So, I have been trying to access keyboard input in Linux. Specifically, I need to be able to access modifier key presses <strong>without</strong> other keys being pressed. Furthermore, I want to be able to do this <strong>without</strong> an X system running.</p> <p>So, in short, my requirements are these:</p> <ul> <li>Works on Linux</li> <li>Does not need X11</li> <li>Can retrieve modifier key press <strong>without</strong> any other keys being pressed <ul> <li>This includes the following keys: <ul> <li>Shift</li> <li>Control</li> <li>Alt</li> </ul></li> <li>All I need is a simple <code>0 = not pressed</code>, <code>1 = currently pressed</code> to let me know if the key is being held down when the keyboard is checked</li> </ul></li> </ul> <h2>My computer setup</h2> <p>My normal Linux machine is on a truck towards my new apartment; so, I only have a Macbook Air to work with right now. Therefore, I am running Linux in a VM to test this out.</p> <p><strong>Virtual Machine in VirtualBox</strong></p> <ul> <li>OS: Linux Mint 16</li> <li>Desktop Environment: XFCE</li> </ul> <p>Everything below was done in this environment. I've tried both with X running and in one of the other ttys.</p> <h2>My Thoughts</h2> <p>I'll alter this if someone can correct me.</p> <p>I've done a fair bit of reading to realize that higher-level libraries do not provide this kind of functionality. Modifier keys are used with other keys to provide an alternate key code. Accessing the modifier keys themselves through a high-level library in Linux isn't as easy. Or, rather, I haven't found a high-level API for this on Linux. </p> <p>I thought <a href="http://www.leonerd.org.uk/code/libtermkey/" rel="noreferrer" title="Link to the library">libtermkey</a> would be the answer, but it doesn't seem to support the Shift modifier key any better than normal keystroke retrieval. I'm also not sure if it works without X.</p> <p>While working with libtermkey (before I realized it didn't get shift in cases like Shift-Return), I was planning to write a daemon that would run to gather keyboard events. Running copies of the daemon program would simply pipe requests for keyboard data and receive keyboard data in response. I could use this setup to have something always running in the background, in case I cannot check key code statuses at specific times (have to be receive key codes as they happen).</p> <p>Below are my two attempts to write a program that can read from the Linux keyboard device. I've also included my small check to make sure I had the right device.</p> <h2>Attempt #1</h2> <p>I have tried to access the keyboard device directly, but am encountering issues. I have tried the suggestion <a href="https://stackoverflow.com/a/4225290" title="Stack Overflow suggestion">here</a> that is in another Stack Overflow thread. It gave me a segmentation fault; so, I changed it from fopen to open:</p> <pre><code>// ... int fd; fd = open("/dev/input/by-path/platform-i8042-serio-0-event-kbd", O_RDONLY); char key_map[KEY_MAX/8 + 1]; memset(key_map, 0, sizeof(key_map)); ioctl(fd, EVIOCGKEY(sizeof key_map), key_map); // ... </code></pre> <p>While there was no segmentation fault, there was no indicator of any key press (not just modifier keys). I tested this using:</p> <pre><code>./foo &amp;&amp; echo "TRUE" || echo "FALSE" </code></pre> <p>I've used that to test for successful return codes from commands quite a lot; so, I know that's fine. I've also outputted the key (always 0) and mask (0100) to check. It just doesn't seem to detect anything.</p> <h2>Attempt #2</h2> <p>From here, I thought I'd try a slightly different approach. I wanted to figure out what I was doing wrong. Following <a href="http://baruch.siach.name/blog/posts/linux_input_keys_status/" rel="noreferrer" title="Linux Input Key Status">this</a> page providing a snippet demonstrating printing out key codes, I bundled that into a program:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;fcntl.h&gt; #include &lt;linux/input.h&gt; int main(int argc, char** argv) { uint8_t keys[128]; int fd; fd = open("/dev/input/by-path/platform-i8042-serio-event-kbd", O_RDONLY); for (;;) { memset(keys, 0, 128); ioctl (fd, EVIOCGKEY(sizeof keys), keys); int i, j; for (i = 0; i &lt; sizeof keys; i++) for (j = 0; j &lt; 8; j++) if (keys[i] &amp; (1 &lt;&lt; j)) printf ("key code %d\n", (i*8) + j); } return 0; } </code></pre> <p>Previously, I had the size to 16 bytes instead of 128 bytes. I should honestly spend a bit more time understanding ioctl and EVIOCGKEY. I just know that it supposedly maps bits to specific keys to indicate presses, or something like that (<strong>correct me if I'm wrong, please!</strong>).</p> <p>I also didn't have a loop initially and would just hold down various keys to see if a key code appeared. I received nothing; so, I thought a loop might make the check easier to test in case a missed something.</p> <h2>How I know the input device is the right one</h2> <p>I tested it by running <code>cat</code> on the input device. Specifically:</p> <pre><code>$ sudo cat /dev/input/by-path/platform-i8042-serio-0-event-kbd </code></pre> <p>Garbage ASCII was sent to my terminal on key press and release events starting with the return (enter) key when I began the output using cat. I also know that this seems to work fine with modifier keys like shift, control, function, and even Apple's command key on my Macbook running a Linux VM. Output appeared when a key was pressed, began to appear rapidly from subsequent signals sent by holding the key down, and outputted more data when a key was released.</p> <p>So, while my approach may not be the right one (I'm willing to hear <strong>any</strong> alternative), the device seems to provide what I need.</p> <p>Furthermore, I know that this device is just a link pointing to /dev/input/event2 from running:</p> <pre><code>$ ls -l /dev/input/by-path/platform-i8042-serio-0-event-kbd </code></pre> <p>I've tried both programs above with /dev/input/event2 and received no data. Running cat on /dev/input/event2 provided the same output as with the link.</p>
0
2,023
how to resolve jsoup error: unable to find valid certification path to requested target
<p>I am trying to parse the html of the following URL:</p> <p><a href="https://www.smuc.ac.kr/mbs/smuc/jsp/board/list.jsp?boardId=6993&amp;id=smuc_040100000000" rel="noreferrer">https://www.smuc.ac.kr/mbs/smuc/jsp/board/list.jsp?boardId=6993&amp;id=smuc_040100000000</a></p> <p>I'm getting the following error:</p> <pre><code>sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387) at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) at sun.security.validator.Validator.validate(Validator.java:260) at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491) ... 15 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ... 21 more </code></pre> <p><br/> This is my code:</p> <pre><code>public class MainActivity extends AppCompatActivity { private ListView listView; private TextView textView; public ArrayList&lt;String&gt; arrayList = new ArrayList&lt;String&gt;(); private ArrayAdapter&lt;String&gt; arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); new Insert().execute(); arrayAdapter = new ArrayAdapter&lt;String&gt;(MainActivity.this, R.layout.list_ok, R.id.text, arrayList ); } class Insert extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... params) { try { // Connection.Response res = Jsoup.connect("https://www.smuc.ac.kr/mbs/smuc/index.jsp") // .method(Connection.Method.POST) // .execute(); Document document = Jsoup.connect("https://www.smuc.ac.kr/mbs/smuc/jsp/board/list.jsp?boardId=6993&amp;id=smuc_040100000000").get(); Elements elements = document.select(".tit"); arrayList.clear(); for (Element element : elements) { arrayList.add(element.text()); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result){ listView.setAdapter(arrayAdapter); } } } </code></pre>
0
1,341
Block Check-In on Policy Failure
<p>I've created the check-in policy <a href="https://msdn.microsoft.com/en-us/library/bb668980.aspx" rel="nofollow noreferrer">from this MSDN article</a> as an example (code is just copy / pasted).</p> <p>This works fine, it appears when I try and do a check-in, however it appears as an warning. So I can ignore it by just pressing Check In again. How can I change the code, as listed in the URL, so that it will return an Error not a warning. I can't see any properties on PolicyFailure to do this.</p> <p>Essentially I want it to look like the error in this screenshot: <img src="https://i.stack.imgur.com/oHXIT.png" alt="enter image description here"></p> <p><sup><a href="http://blogs.msmvps.com/vstsblog/2014/05/13/turning-off-policy-overrides-in-tfs/" rel="nofollow noreferrer">Image Source</a></sup></p> <p><strong>EDIT:</strong> Here is the exact code that I'm using. Now it is slightly modified from the original source, but not in any massive way I wouldn't have thought. Unfortunately I can't post screenshots, but I'll try and describe everything I've done.</p> <p>So I have a DLL from the code below, I've added it into a folder at C:\TFS\CheckInComments.dll. I added a registry key under Checkin Policies with the path to the DLL, the string value name is the same as my DLL (minus .dll). In my project settings under source control I've added this Check-In Policy.</p> <p>It all seems to work fine, if I try and do a check-in it will display a warning saying "Please provide some comments about your check-in" which is what I expect, what I'd like is for it to stop the check-in if any policies are not met, however I would still like the user to be able to select Override if necessary. At the moment, even though there is a warning, if I was to click the Check In button then it would successfully check-in the code.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.TeamFoundation.VersionControl.Client; namespace CheckInComments { [Serializable] public class CheckInComments : PolicyBase { public override string Description { get { return "Remind users to add meaningful comments to their checkins"; } } public override string InstallationInstructions { get { return "To install this policy, read InstallInstructions.txt"; } } public override string Type { get { return "Check for Comments Policy"; } } public override string TypeDescription { get { return "This policy will prompt the user to decide whether or not they should be allowed to check in"; } } public override bool Edit(IPolicyEditArgs args) { return true; } public override PolicyFailure[] Evaluate() { string proposedComment = PendingCheckin.PendingChanges.Comment; if (String.IsNullOrEmpty(proposedComment)) { PolicyFailure failure = new PolicyFailure("Please provide some comments about your check-in", this); failure.Activate(); return new PolicyFailure[1] { failure }; } else { return new PolicyFailure[0]; } } public override void Activate(PolicyFailure failure) { MessageBox.Show("Please provide comments for your check-in.", "How to fix your policy failure"); } public override void DisplayHelp(PolicyFailure failure) { MessageBox.Show("This policy helps you to remember to add comments to your check-ins", "Prompt Policy Help"); } } } </code></pre>
0
1,483
Jenkins and maven-buildnumber-plugin
<p>I am using <a href="http://mojo.codehaus.org/buildnumber-maven-plugin/" rel="nofollow">maven-buildnumber-plugin</a> version 1.0-beta-4. This works fine on a project checked out of Subversion, but fails in Jenkins.</p> <p>I assume this problem is due to Jenkins somehow removing the <code>.svn</code> folders.</p> <p>I assumed wrong. Here is the error I got:</p> <pre><code>maven builder waiting mavenExecutionResult exceptions not empty org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:buildnumber-maven-plugin:1.0-beta-4:create (default) on project swift-core: Cannot get the revision information from the scm repository : Error! at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.jvnet.hudson.maven3.launcher.Maven3Launcher.main(Maven3Launcher.java:79) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.plexus.classworlds.launcher.Launcher.launchStandard(Launcher.java:329) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:239) at org.jvnet.hudson.maven3.agent.Maven3Main.launch(Maven3Main.java:146) at hudson.maven.Maven3Builder.call(Maven3Builder.java:124) at hudson.maven.Maven3Builder.call(Maven3Builder.java:71) at hudson.remoting.UserRequest.perform(UserRequest.java:114) at hudson.remoting.UserRequest.perform(UserRequest.java:48) at hudson.remoting.Request$2.run(Request.java:270) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.apache.maven.plugin.MojoExecutionException: Cannot get the revision information from the scm repository : Error! at org.codehaus.mojo.build.CreateMojo.getRevision(CreateMojo.java:673) at org.codehaus.mojo.build.CreateMojo.execute(CreateMojo.java:431) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) ... 27 more Caused by: org.apache.maven.scm.ScmException: Error! at org.codehaus.mojo.build.CreateMojo.checkResult(CreateMojo.java:753) at org.codehaus.mojo.build.CreateMojo.getRevision(CreateMojo.java:648) ... 30 more </code></pre> <p>I overlooked this:</p> <pre><code>Provider message: The svn command failed. Command output: /bin/sh: svn: command not found mojoFailed org.codehaus.mojo:buildnumber-maven-plugin:1.0-beta-4(default) </code></pre> <p>There is no <code>svn</code> client installed on the machine, that is the true source of trouble.</p>
0
1,433
How do I get jqGrid to work using ASP.NET + JSON on the backend?
<p>ok, I'm back. I totally simplified my problem to just three simple fields and I'm still stuck on the same line using the addJSONData method. I've been stuck on this for days and no matter how I rework the ajax call, the json string, blah blah blah...I can NOT get this to work! I can't even get it to work as a function when adding one row of data manually. Can anyone PLEASE post a working sample of jqGrid that works with ASP.NET and JSON? Would you please include 2-3 fields (string, integer and date preferably?) I would be happy to see a working sample of jqGrid and just the manual addition of a JSON object using the addJSONData method. Thanks SO MUCH!! If I ever get this working, I will post a full code sample for all the other posting for help from ASP.NET, JSON users stuck on this as well. Again. THANKS!! </p> <p>tbl.addJSONData(objGridData); //err: tbl.addJSONData is not a function!!</p> <p>Here is what Firebug is showing when I receive this message:</p> <p>• objGridData Object total=1 page=1 records=5 rows=[5]<br> ○ Page "1"<br> Records "5"<br> Total "1"<br> Rows [Object ID=1 PartnerID=BCN, Object ID=2 PartnerID=BCN, Object ID=3 PartnerID=BCN, 2 more... 0=Object 1=Object 2=Object 3=Object 4=Object]<br> (index) 0<br> (prop) ID (value) 1 (prop) PartnerID (value) "BCN" (prop) DateTimeInserted (value) Thu May 29 2008 12:08:45 GMT-0700 (Pacific Daylight Time)<br> * There are three more rows </p> <p>Here is the value of the variable tbl (value) 'Table.scroll' </p> <pre><code>&lt;TABLE cellspacing="0" cellpadding="0" border="0" style="width: 245px;" class="scroll grid_htable"&gt;&lt;THEAD&gt;&lt;TR&gt;&lt;TH class="grid_sort grid_resize" style="width: 55px;"&gt;&lt;SPAN&gt; &lt;/SPAN&gt;&lt;DIV id="jqgh_ID" style="cursor: pointer;"&gt;ID &lt;IMG src="http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif"/&gt;&lt;/DIV&gt;&lt;/TH&gt;&lt;TH class="grid_resize" style="width: 90px;"&gt;&lt;SPAN&gt; &lt;/SPAN&gt;&lt;DIV id="jqgh_PartnerID" style="cursor: pointer;"&gt;PartnerID &lt;/DIV&gt;&lt;/TH&gt;&lt;TH class="grid_resize" style="width: 100px;"&gt;&lt;SPAN&gt; &lt;/SPAN&gt;&lt;DIV id="jqgh_DateTimeInserted" style="cursor: pointer;"&gt;DateTimeInserted &lt;/DIV&gt;&lt;/TH&gt;&lt;/TR&gt;&lt;/THEAD&gt;&lt;/TABLE&gt; </code></pre> <p>Here is the complete function: </p> <pre><code> $('table.scroll').jqGrid({ datatype: function(postdata) { mtype: "POST", $.ajax({ url: 'EDI.asmx/GetTestJSONString', type: "POST", contentType: "application/json; charset=utf-8", data: "{}", dataType: "text", //not json . let me try to parse success: function(msg, st) { if (st == "success") { var gridData; //strip of "d:" notation var result = JSON.parse(msg); for (var property in result) { gridData = result[property]; break; } var objGridData = eval("(" + gridData + ")"); //creates an object with visible data and structure var tbl = jQuery('table.scroll')[0]; alert(objGridData.rows[0].PartnerID); //displays the correct data //tbl.addJSONData(objGridData); //error received: addJSONData not a function //error received: addJSONData not a function (This uses eval as shown in the documentation) //tbl.addJSONData(eval("(" + objGridData + ")")); //the line below evaluates fine, creating an object and visible data and structure //var objGridData = eval("(" + gridData + ")"); //BUT, the same thing will not work here //tbl.addJSONData(eval("(" + gridData + ")")); //FIREBUG SHOWS THIS AS THE VALUE OF gridData: // "{"total":"1","page":"1","records":"5","rows":[{"ID":1,"PartnerID":"BCN","DateTimeInserted":new Date(1214412777787)},{"ID":2,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125000)},{"ID":3,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125547)},{"ID":4,"PartnerID":"EHG","DateTimeInserted":new Date(1235603192033)},{"ID":5,"PartnerID":"EMDEON","DateTimeInserted":new Date(1235603192000)}]}" } } }); }, jsonReader: { root: "rows", //arry containing actual data page: "page", //current page total: "total", //total pages for the query records: "records", //total number of records repeatitems: false, id: "ID" //index of the column with the PK in it }, colNames: [ 'ID', 'PartnerID', 'DateTimeInserted' ], colModel: [ { name: 'ID', index: 'ID', width: 55 }, { name: 'PartnerID', index: 'PartnerID', width: 90 }, { name: 'DateTimeInserted', index: 'DateTimeInserted', width: 100}], rowNum: 10, rowList: [10, 20, 30], imgpath: 'http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images', pager: jQuery('#pager'), sortname: 'ID', viewrecords: true, sortorder: "desc", caption: "TEST Example")}; </code></pre>
0
2,431
Warning Prop `href` did not match. using react server-side-rendering
<p>I am using <code>react-router-dom</code> and I am guessing that this is causing the problem, but I have no clue where to even start looking or how to fix it. I also am getting errors like <code>Warning: Did not expect server HTML to contain a &lt;nav&gt; in &lt;div&gt;</code>.</p> <p>As I stated, I'm not really sure where to look so if you think there is certain code that would be helpful please let me know and I will post it. Otherwise, I can post my code that I use to do SSR.</p> <p><strong>EDIT</strong>: Exact error: <code>Warning: Prop</code>href<code>did not match. Server: "/profile/5a073dc44cb45b00125e5c82" Client: "profile/5a073dc44cb45b00125e5c82"</code></p> <p>I have checked the client and it has <code>/profile/:id</code> so not sure where it says there is not a <code>/</code>, as for the other error with the <code>&lt;nav&gt;</code> in <code>&lt;div&gt;</code> , I have a <code>nav</code> inside my header , but I'm not really sure how to go about "fixing" that.</p> <pre><code>import React from 'react'; import { renderToString } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import { renderRoutes } from 'react-router-config'; import serialize from 'serialize-javascript'; import { Helmet } from 'react-helmet'; import { matchRoutes } from 'react-router-config'; import routes from './src/routes'; import createStore from './src/stores'; function handleRender(req, res) { let initial = {}; if (req.vertexSession != null &amp;&amp; req.vertexSession.user != null) { initial.user = { currentUser: req.vertexSession.user }; } const store = createStore.configure(initial); // create Store in order to get data from redux const promises = matchRoutes(routes, req.path) .map(({ route, match }) =&gt; { // Matches the route and loads data if loadData function is there return route.loadData ? route.loadData(store) : route.loadDataWithMatch ? route.loadDataWithMatch(store, match) : null; }) .map(promise =&gt; { if (promise) { return new Promise((resolve, reject) =&gt; { promise.then(resolve).catch(resolve); // lets all data load even if route fails }); } }); Promise.all(promises).then(() =&gt; { const context = {}; if (context.url) { return res.redirect(301, context.url); // redirect for non auth users } if (context.notFound) { res.status(404); // set status to 404 for unknown route } const content = renderToString( &lt;Provider store={store}&gt; &lt;StaticRouter location={req.path} context={context}&gt; &lt;div&gt;{renderRoutes(routes)}&lt;/div&gt; &lt;/StaticRouter&gt; &lt;/Provider&gt; ); // console.log(store.getState()); const initialState = serialize(store.getState()); const helmet = Helmet.renderStatic(); res.render('index', { content, initialState, helmet }); }); } module.exports = handleRender; </code></pre>
0
1,103
Deleting File and Directory in JUnit
<p>I'm writing a test for a method that creates a file in a directory. Here's what my JUnit test looks like:</p> <pre><code> @Before public void setUp(){ objectUnderTest = new ClassUnderTest(); //assign another directory path for testing using powermock WhiteBox.setInternalState(objectUnderTest, "dirPathField", mockDirPathObject); nameOfFile = "name.txt"; textToWrite = "some text"; } @Test public void shouldCreateAFile(){ //create file and write test objectUnderTest.createFile(nameOfFile, textToWrite); /* this method creates the file in mockPathObject and performs FileWriter.write(text); FileWriter.close(); */ File expect = new File(mockPathObject + "\\" + nameOfFile); assertTrue(expect.exist()); //assert if text is in the file -&gt; it will not be called if first assert fails } @After public void tearDown(){ File destroyFile = new File(mockPathObject + "\\" + nameOfFile); File destroyDir = new File(mockPathObject); //here's my problem destroyFile.delete(); //why is this returning false? destroyDir.delete(); //will also return false since file was not deleted above } </code></pre> <p>I was able to delete the File using deleteOnExit() but I will not be able to delete the directory using delete or deleteOnExit. I will also perform other test for other scenarios in this test script so I don't want to use deleteOnExit.</p> <p>I don't know why I cannot delete it in JUnit test script while I can delete a file created and modified by FileWriter in runtime when the code is not a JUnit test. I also tried performing an infiniteLoop after the test method and delete the file manually but it tells me that other program is still using the file though I'm able to modify its content.</p> <p>Hope somebody can suggest a way to delete the files and directories created during the tests. Thanks :D</p> <p>For more clarity, the method I test looks like this <a href="https://stackoverflow.com/questions/11878716/unit-testing-method-that-invokes-filewriter">Unit testing method that invokes FileWriter</a></p> <p>Edit:Here is the method to test</p> <pre><code> public void createFile(String fileName, String text){ //SOME_PATH is a static string which is a field of the class File dir = new File(SOME_PATH); //I modified SOME_PATH using whitebox for testing if(!dir.exists()){ booelan createDir = dir.mkdirs(); if(!createDir){ sysout("cannot make dir"); return; } } try{ FileWriter fileWrite = new FileWriter(dir.getAbsolutePath() + "/" + fileName, true); fileWrite.write(text); fileWrite.close(); } catch(Exception e){ e.printStackTrace(); } } </code></pre> <p>I cannot modify this method as other developers created it. I was just instructed to create unit tests for test automation. Thanks.</p>
0
1,143
Using Java sessions for login/logout
<p>Having trouble getting session to work in my Java application.</p> <p>My login.jsp page calls this <code>LoginAction</code> page.</p> <pre class="lang-java prettyprint-override"><code>package struts.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import struts.form.LoginForm; public class LoginAction extends org.apache.struts.action.Action { private final static String SUCCESS = "success"; private final static String FAILURE = "failure"; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LoginForm lf = (LoginForm) form; HttpSession session = request.getSession(true); if (lf.getUsername().equals(lf.getPassword())) { session.setAttribute("Username", lf.getUsername()); System.out.println(session.getAttribute("Username")); return mapping.findForward(SUCCESS); } else { return mapping.findForward(FAILURE); } } } </code></pre> <p>Corresponding LoginForm page</p> <pre class="lang-java prettyprint-override"><code>package struts.form; import org.apache.struts.action.*; public class LoginForm extends ActionForm{ private String username; private String password; public LoginForm() { super(); } private static final long serialVersionUID = 104092268304152302L; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } </code></pre> <p>success.jsp, the page shown when logged in</p> <pre class="lang-java prettyprint-override"><code>&lt;%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %&gt; &lt;%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %&gt; &lt;%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %&gt; &lt;%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;&lt;%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;success&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;/head&gt; &lt;body&gt; &lt;H1&gt;Hello: &lt;% session.getAttribute("Username"); %&gt;&lt;/H1&gt; &lt;html:form action="/LogoutAction" &gt; &lt;html:submit value="Logout" /&gt; &lt;/html:form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Logout Action page package struts.action;</p> <pre class="lang-java prettyprint-override"><code>import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class LogoutAction extends org.apache.struts.action.Action { private final static String SUCCESS = "success"; private final static String FAILURE = "failure"; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); System.out.println(session.getAttribute("Username")); try{ session.removeAttribute("Username"); session.invalidate(); return mapping.findForward(SUCCESS); }catch(Exception ex){ System.out.println("Error"); } return mapping.findForward(FAILURE); } } </code></pre> <p>Corresponding LogoutForm package struts.form; import org.apache.struts.action.*;</p> <pre class="lang-java prettyprint-override"><code>public class LogoutForm extends ActionForm{ private static final long serialVersionUID = 1L; } </code></pre> <p>So the session is created in my Login action, and it works, as if I use the getAttribute() and print it to the console, the username comes up. However, the username won't show up on my success.jsp page.</p> <p>Can anyone help?</p>
0
1,703
This method requires a body instead of a semicolon
<p>Selected lines "&lt;------- These" gives an erroror: This method requires a body instead of a semicolon</p> <p>Both files must work together. How to fix it I need quick help. Does anyone have any idea but i dont?</p> <pre><code>package API.Info; import Mains.MiniEvents; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import java.util.HashMap; public class ApiInfo { public static MiniEvents plugin; public ApiInfo(MiniEvents plugin) { ApiInfo.plugin = plugin; } /** * @return number of players in the event. */ public int eventSize() { return plugin.getInfo().eventSize(); } /** * @return "code" name of the current event running; else, "none" * It will return one of the following: * horse, koth, oitc, paint, tdm, ko, lms, parkour, spleef, tnt */ public String getEventName() { return plugin.getInfo().getEventName(); } /** * @return TRUE if an event is starting (counting down). */ public boolean eventStarting(){ return plugin.getInfo().eventStarting(); } /** * @return TRUE if an event has started. */ public boolean eventStarted(); &lt;------- These /** * @param player - Player to check. * @return TRUE if a player is currently playing in an event. */ public boolean inEvent(Player player); &lt;------- These /** * @return the "formal" name of an event that is running. * param eventName - the event for which to return the formal name for. */ public String eventFormalEventName(String eventName); &lt;------- These /** * @return time left until the event starts */ public int getTimeLeft(); &lt;------- These /** * @param player - Gets that player's file. * @return the FileConfiguration where individual player data is stored. */ public FileConfiguration getPlayerFile(Player player); &lt;------- These /** * The is a big "inevent" HashSet&lt;Player&gt; that contains a player no matter what event * that player is in. * * @return the "inevent" HashSet. */ public HashMap&lt;String, String&gt; getPlayersInEvent(); &lt;------- These /** * @return true if a player is currently in spectate mode. */ public boolean inSpectateMode(Player player); &lt;------- These } File Info.jar package Util.Methods; import API.Info.ApiInfo; import Mains.MiniEvents; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; import java.util.HashMap; import java.util.HashSet; public class Info extends ApiInfo{ public MiniEvents plugin; public Info(MiniEvents plugin) { super(plugin); this.plugin = plugin; } public boolean eventstarting = false; public boolean eventstarted = false; public boolean cancelled = false; public final HashSet&lt;String&gt; sbefore = new HashSet&lt;&gt;(); public final HashSet&lt;String&gt; sblue = new HashSet&lt;&gt;(); public final HashSet&lt;String&gt; sred = new HashSet&lt;&gt;(); public final HashSet&lt;String&gt; sfire = new HashSet&lt;&gt;(); public final HashMap&lt;String, String&gt; inevent = new HashMap&lt;&gt;(); public final HashMap&lt;String, Scoreboard&gt; scoreboard = new HashMap&lt;&gt;(); public int eventSize(){ return inevent.size(); } public String getEventName(){ return plugin.getEventName(); } public boolean eventStarting(){ return eventstarting; } public boolean eventStarted(){ return eventstarted; } public boolean inEvent(Player player){ return inevent.containsKey(player.getName()); } public String eventFormalEventName(String s){ return plugin.getFormalName(s); } public int getTimeLeft(){ return plugin.getTimerMain().getTimeLeft(); } public FileConfiguration getPlayerFile(Player player){ return plugin.playerFile(player.getName().toLowerCase()); } public HashMap&lt;String, String&gt; getPlayersInEvent(){ return inevent; } public boolean inSpectateMode(Player player){ return plugin.getSpectateMode().inspec.contains(player.getName()); } } </code></pre>
0
1,602
GdxRuntimeException: Couldn't load file
<p>I am following <a href="http://code.google.com/p/libgdx/wiki/HelloWorld" rel="nofollow">this</a> tutorial on libgdx. What i am trying to do is loading a texture from a copy of badlogic.jpg (copy is called wawa.jpg):</p> <pre><code>public class HelloWorld implements ApplicationListener { SpriteBatch spriteBatch; Texture texture; Texture watched_texture; BitmapFont font; Vector2 textPosition = new Vector2(100, 100); Vector2 textDirection = new Vector2(5, 3); @Override public void create () { font = new BitmapFont(); font.setColor(Color.RED); texture = new Texture(Gdx.files.internal("data/badlogic.jpg")); watched_texture = new Texture(Gdx.files.internal("data/wawa.jpg")); spriteBatch = new SpriteBatch(); } ... </code></pre> <p>What i get is the crash of application and "com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file data/wawa.jpg" in debug:</p> <pre> 10-18 09:24:45.383: WARN/dalvikvm(330): threadid=9: thread exiting with uncaught exception (group=0x40015560) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): FATAL EXCEPTION: GLThread 10 10-18 09:24:45.502: ERROR/AndroidRuntime(330): com.badlogic.gdx.utils.GdxRuntimeException: couldn't load file 'wawa.jpg' 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:135) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.graphics.Texture.(Texture.java:126) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.graphics.Texture.(Texture.java:104) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.test.myfirsttriangle.MyFirstTriangle.create(MyFirstTriangle.java:29) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceCreated(AndroidGraphics.java:284) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1348) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/wawa.jpg (Internal) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:64) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:132) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): ... 6 more 10-18 09:24:45.502: ERROR/AndroidRuntime(330): Caused by: java.io.FileNotFoundException: data/wawa.jpg 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at android.content.res.AssetManager.openAsset(Native Method) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at android.content.res.AssetManager.open(AssetManager.java:314) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at android.content.res.AssetManager.open(AssetManager.java:288) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:62) 10-18 09:24:45.502: ERROR/AndroidRuntime(330): ... 7 more </pre> <p>Just can't figure out what's wrong.</p>
0
1,256
java.lang.ExceptionInInitializerError in the creation of hibernate configuration
<p>I'm working on a Hibernate project and I configured everything.</p> <p>So, I generated the beans and hbm files.</p> <p>Then, I wrote a test class to test the project(I used the <code>Client</code> class)</p> <p>When I executed the code, the following exception was thrown:</p> <pre><code>java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException at org.slf4j.LoggerFactory.singleImplementationSanityCheck(LoggerFactory.java:192) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:113) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255) at org.aness.test.HiberM.&lt;clinit&gt;(HiberM.java:12) Exception in thread "main" </code></pre> <p>the code is : </p> <pre><code>import org.aness.beans.*; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HiberM { final static Logger logger = LoggerFactory.getLogger(Client.class); public static void main(String[]arg){ Configuration cfg = new Configuration().configure(); SessionFactory sf =cfg.buildSessionFactory(); Session s = sf.openSession(); Transaction tx =s.beginTransaction(); Client c =new Client(); c.setRaisonSociale("peugeot algerie"); c.setNumeroRc("3215468897"); c.setIdentificationFiscale("888777999"); c.setAdresseActivite("blida zone atlas"); c.setTelephone("00213(0)25436996"); c.setFax("00213(0)25436996"); s.save(c); tx.commit(); } } </code></pre> <p>that's the whole problem.</p> <p>the hibernate cfg file is : *</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory name="apurement"&gt; &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt; &lt;property name="hibernate.connection.password"&gt;root&lt;/property&gt; &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://localhost/apurement&lt;/property&gt; &lt;property name="hibernate.connection.username"&gt;root&lt;/property&gt; &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>the client mapping is : </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt; &lt;!-- Generated 27 d?c. 2012 11:47:54 by Hibernate Tools 3.4.0.CR1 --&gt; &lt;hibernate-mapping&gt; &lt;class name="org.aness.beans.Client" table="client" catalog="apurement"&gt; &lt;id name="clientId" type="int"&gt; &lt;column name="client_id" /&gt; &lt;generator class="assigned" /&gt; &lt;/id&gt; &lt;property name="raisonSociale" type="string"&gt; &lt;column name="raison_sociale" length="150" not-null="true" /&gt; &lt;/property&gt; &lt;property name="numeroRc" type="string"&gt; &lt;column name="numero_rc" length="45" not-null="true" /&gt; &lt;/property&gt; &lt;property name="identificationFiscale" type="string"&gt; &lt;column name="identification_fiscale" length="45" not-null="true" /&gt; &lt;/property&gt; &lt;property name="adresseActivite" type="string"&gt; &lt;column name="adresse_activite" length="250" not-null="true" /&gt; &lt;/property&gt; &lt;property name="adressePersonelle" type="string"&gt; &lt;column name="adresse_personelle" length="250" /&gt; &lt;/property&gt; &lt;property name="telephone" type="string"&gt; &lt;column name="telephone" length="45" not-null="true" /&gt; &lt;/property&gt; &lt;property name="fax" type="string"&gt; &lt;column name="fax" length="45" not-null="true" /&gt; &lt;/property&gt; &lt;set name="domiciliations" table="domiciliation" inverse="true" lazy="true" fetch="select"&gt; &lt;key&gt; &lt;column name="client_id" not-null="true" /&gt; &lt;/key&gt; &lt;one-to-many class="org.aness.beans.Domiciliation" /&gt; &lt;/set&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
0
1,952
Checkbox checked or unchecked boolean php mysql
<p>I am trying to make this form with checkboxes get values 1 or 0, sort of a boolean, and UPDATE it on mysql, but I havent found a way yet. Maybe you can help. I'll post the form and the code that receives it. I am sure there might be a conflict of loops, but I tryed everything and couldnt get it working. Tks in advance.</p> <p>THE FORM</p> <pre><code>&lt;form action="esconde_cat.php" method="post"&gt; &lt;table width="300px" align="center" width="140" border="1"&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td width="200"&gt;Categoria&lt;/td&gt; &lt;td width="100"&gt;Mostrar&lt;/td&gt; &lt;/tr&gt; &lt;?php include "conecta.php"; include "verifica.php"; $sql = "SELECT * FROM categorias ORDER BY ordem"; $res = mysql_query($sql) or die (mysql_error()); while ($linha=mysql_fetch_array($res)) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;input name="user[]" type="checkbox" value="true"/&gt;&lt;/td&gt; &lt;td&gt;&lt;?=$linha['1']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php if ($linha['3'] == TRUE){ echo 'SIM'; } else {echo 'NÃO'; } ?&gt;&lt;/td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/table&gt; &lt;br/&gt; &lt;table align="center"&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="submit" name="Delete" type="button" value="Alterar"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>THE CODE THAT RECEIVES THE FORM AND UPDATE MYSQL</p> <pre><code>&lt;?php include "conecta.php"; include "verifica.php"; \\THIS PART WORKS, GETS IF THE CHECKBOX IS CHECKED AND RECORD IT ON DB if(isset($_POST['user'])) { foreach ($_POST['user'] as $key =&gt; $read){ $read =(@$_POST['user']=='0')? $_POST['user']:'1'; echo $read; $sql = "UPDATE categorias SET mostrar='$read' WHERE ordem='$key'"; $res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error(); } } \\ON THIS PART OF THE CODE THAT I CANT GET THE VARIABLE TO GET THE \\VALUE FROM CHEBOXES THAT ARE UNCHECKED RECORDED TO DATABASE if (!isset($_POST['user'])) { foreach ($_POST['user'] as $chave =&gt; $leia) { $leia =(@$_POST['user']=='1')? $_POST['user']:'0'; echo $leia; $sql = "UPDATE categorias SET mostrar='$leia' WHERE ordem='$chave'"; $res = mysql_query($sql) or die ("Erro ao excluir") . mysql.error(); } } ?&gt; </code></pre>
0
1,294
Getting issue while deploying spring boot war on tomcat 7
<p>I am having issue in deploying my code on the tomcat server I have written the below code.</p> <p>My main class:</p> <pre><code>package com.indiamart.search; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class SuggestMcatApplication extends SpringBootServletInitializer{ public static void main(String[] args) { SpringApplication.run(SuggestMcatApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { // TODO Auto-generated method stub return builder.sources(SuggestMcatApplication.class); }} </code></pre> <p>My controller class :-</p> <pre><code>package com.abc.search; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class serviceController { @RequestMapping("/suggestMcat/related_info") public String getSearchString(HttpServletRequest request){ JSONObject json; json = new JSONObject(request); return json.toString(); } } </code></pre> <p>My pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.abc&lt;/groupId&gt; &lt;artifactId&gt;suggestMcat&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;suggestMcat&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.1.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt; &lt;dependency&gt; &lt;groupId&gt;org.json&lt;/groupId&gt; &lt;artifactId&gt;json&lt;/artifactId&gt; &lt;version&gt;20171018&lt;/version&gt; &lt;/dependency&gt; &lt;!-- https://mvnrepository.com/artifact/net.sf.jazzy/jazzy --&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.jazzy&lt;/groupId&gt; &lt;artifactId&gt;jazzy&lt;/artifactId&gt; &lt;version&gt;0.5.2-rtext-1.4.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;configuration&gt; &lt;outputDirectory&gt;../../tomcat/webapps/&lt;/outputDirectory&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;warName&gt;${project.artifactId}&lt;/warName&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-install-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;install-javaml-jar&lt;/id&gt; &lt;phase&gt;clean&lt;/phase&gt; &lt;configuration&gt; &lt;file&gt;${project.basedir}/src/main/resources/javaml-0.1.6.jar&lt;/file&gt; &lt;repositoryLayout&gt;default&lt;/repositoryLayout&gt; &lt;groupId&gt;com.indiamart&lt;/groupId&gt; &lt;artifactId&gt;javaml&lt;/artifactId&gt; &lt;version&gt;0.1.6&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;generatePom&gt;true&lt;/generatePom&gt; &lt;/configuration&gt; &lt;goals&gt; &lt;goal&gt;install-file&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;install-ajt-jar&lt;/id&gt; &lt;phase&gt;clean&lt;/phase&gt; &lt;configuration&gt; &lt;file&gt;${project.basedir}/src/main/resources/ajt-2.11.jar&lt;/file&gt; &lt;repositoryLayout&gt;default&lt;/repositoryLayout&gt; &lt;groupId&gt;com.indiamart&lt;/groupId&gt; &lt;artifactId&gt;ajt&lt;/artifactId&gt; &lt;version&gt;2.11&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;generatePom&gt;true&lt;/generatePom&gt; &lt;/configuration&gt; &lt;goals&gt; &lt;goal&gt;install-file&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;finalName&gt;${project.artifactId}&lt;/finalName&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I m getting the below error when i m building the war and deploying on tomcat server:</p> <pre><code>Caused by: java.lang.NoClassDefFoundError: org/springframework/web/filter/FormContentFilter at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na] at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1009) 2018-12-04 17:59:39.859 WARN 14727 --- [io-8080-exec-29] o.s.boot.SpringApplication : Unable to close ApplicationContext java.lang.IllegalStateException: Failed to introspect Class [org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration] from ClassLoader [WebappClassLoader context: /suggestMcat delegate: false repositories: /WEB-INF/classes/ ---------- Parent Classloader: java.net.URLClassLoader@3dd4520b </code></pre> <p>Please suggest.</p> <p>After the answer 2 my issue has been resolved of deploying but the issue is coming with controller Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.</p> <p>Tue Dec 04 21:36:49 IST 2018 There was an unexpected error (type=Not Found, status=404). No message available</p>
0
3,345
TypeError: Cannot read property 'apply' of undefined for Express framework
<p>app.js</p> <pre><code>var app = express(); app.listen(PORT, () =&gt; console.log(`Listening on ${ PORT }`)); // all environments app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session({ secret: 'keyboard cat', resave: true, saveUninitialized: false, // cookie: { // maxAge: 365 * 24 * 60 * 60 * 1000, // path : '/' // } })); app.use('/portal/admin', adminRouter); app.use('/portal/merchant', indexRouter); app.use('/users', usersRouter); app.use('/api/v1/users',apiRouter); app.use('/api/v1/users',customerInstallmentAPIRouter); app.use('/api/v1/payment',paymentMethodAPIRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization, Content-Type'); res.setHeader('Access-Control-Allow-Credentials', true); next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); app.get('/portal/merchant',indexRouter); //call to index site //login app.get('/login', usersRouter); // call to login site app.post('/login',usersRouter); // post to /users/login site //logout app.get('/home/logout',usersRouter); //signup app.get('/signup', usersRouter); // call to /users/signup site app.post('/signup',usersRouter); //call to /post/signup //dashboard app.get('/home/dashboard',usersRouter); //profile app.get('/home/profile',usersRouter); db.sequelize .authenticate() .then(() =&gt; { console.log('Connection has been established successfully.'); }) .catch(err =&gt; { console.error('Unable to connect to the database:', err); }); //run scheduler to check due date //cronJob.dueDateCronJob(); app.use(passport.initialize()); app.use(passport.session()); // persistent login sessions require('./routes/adminportal/home.js')(app,passport); module.exports = app; </code></pre> <p>It seems that the error happens at <code>require('./routes/adminportal/home.js')(app,passport);</code> </p> <p>passport.js</p> <pre><code>// config/passport.js // load all the things we need var LocalStrategy = require('passport-local').Strategy; // load up the user model var User = require('../models/admin.js'); // expose this function to our app using module.exports module.exports = function(passport) { // ========================================================================= // passport session setup ================================================== // ========================================================================= // required for persistent login sessions // passport needs ability to serialize and unserialize users out of session // used to serialize the user for the session passport.serializeUser(function(user, done) { done(null, user.id); }); // used to deserialize the user passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); // ========================================================================= // LOCAL LOGIN ============================================================= // ========================================================================= // we are using named strategies since we have one for login and one for signup // by default, if there was no name, it would just be called 'local' passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email_address', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email' : email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash // if the user is found but the password is wrong if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata // all is well, return successful user return done(null, user); }); })); }; </code></pre> <p>home.js</p> <pre><code>var express = require('express'); var router = express.Router(); var db = require('../sequelizeDB.js'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; /* GET home page. */ router.get('/', function(req, res, next) { if(req.session.userId != null){ message = ''; //res.render('dashboard',{message:message}); res.redirect("adminportal/home.ejs"); }else{ var message = ''; var sess = req.session; res.render('adminportal/login.ejs',{message: message}); } }); router.post('/login',passport.authenticate('local-login', { successRedirect : '/listOfCustomers', // redirect to the secure profile section failureRedirect : '/', // redirect back to the signup page if there is an error failureFlash : true // allow flash messages }), function(req, res, next) { var message = ''; var sess = req.session; if(req.method === "POST"){ var post = req.body; var name= post.user_name; var pass= post.password; } else { res.render('adminportal/login.ejs',{message: message}); } }); function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page res.redirect('adminportal/login.ejs'); } router.get('/listOfCustomers',isLoggedIn, function(req, res, next) { if(req.method === "GET"){ db.customers.findAll().then(customers =&gt;{ res.render('adminportal/listOfCustomers.ejs',{data:customers}); }) } }); module.exports = router; </code></pre> <p>Am I doing it wrongly ? I am following a tutorial on this website: <a href="https://scotch.io/tutorials/easy-node-authentication-setup-and-local" rel="nofollow noreferrer">https://scotch.io/tutorials/easy-node-authentication-setup-and-local</a></p> <p>I am trying to do authentication on my website by using passport.js. Been struggling for hours to solve this. Any help will be appreciated. Thanks. </p>
0
2,592
invalid new-expression of abstract class type error
<p><strong>Homework</strong> <br/> I'm getting this type of error for my Merge Sort function. I think the error has something to do with my <code>merge()</code> method, but I thought I took care of it by using it in <code>MergeSort()</code>. Any help would be appreciated.<br/><br/> Sort.h</p> <pre><code>#ifndef SORT_H_ #define SORT_H_ class Sort { protected: unsigned long num_cmps; // number of comparisons performed in sort function public: virtual void sort(int A[], int size)= 0; // main entry point bool testIfSorted(int A[], int size); // returns false if not sorted // true otherwise unsigned long getNumCmps() { return num_cmps; } // returns # of comparisons void resetNumCmps() { num_cmps = 0; } }; class MergeSort:public Sort { // MergeSort class public: void sort(int A[], int size, int low, int high); // main entry point }; #endif </code></pre> <p><br/> Sort.cpp <br/></p> <pre><code> Sort* s; switch(op.getAlg()) { case 'S': s=new SelectionSort(); break; case 'I': s=new InsertionSort(); break; case 'B': s=new BubbleSort(); break; case 'H': s=new HeapSort(); break; case 'R': s=new RadixSort(); radixsortQ = true; break; case 'M': s=new MergeSort(); --&gt; error break; } </code></pre> <p><br/> Merge Sort.cpp <br/></p> <pre><code>#include &lt;iostream&gt; #include "Sort.h" using namespace std; void MergeSort::sort(int A[], int size, int low, int high) // main entry point { if (low &lt; high){ int middle = (low + high) / 2; MergeSort(A, size, low, middle); MergeSort(A, size, middle+1, high); merge(A, size, low, middle, high); } } void merge::sort(int A[], int size, int low, int middle, int high){ int temp[size]; for(int i = low; i &lt;= high; i++){ temp[i] = A[i]; } int i = low; int j = middle + 1; int k = low; while(i &lt;= middle &amp;&amp; j &lt;= high){ if(temp[i] &lt;= temp[j]){ A[k] = temp[i]; ++i; } else { A[k] = temp[j]; ++j; } ++k; } while(i &lt;= middle){ A[k] = temp[i]; ++k; ++i; } } </code></pre>
0
1,180
ERROR 1007 (HY000) at line 1: Can't create database 'mgsv'; database exists
<p>I converted this <a href="https://github.com/qunfengdong/mGSV/" rel="nofollow noreferrer">original</a> project into a docker-compose project <a href="https://github.com/mictadlo/mGSV-docker" rel="nofollow noreferrer">here</a> and followed a their setup <a href="https://github.com/qunfengdong/mGSV/blob/master/INSTALLATION" rel="nofollow noreferrer">instructions</a>. It seems that I am not able to connect with the browser.</p> <p>The <a href="https://github.com/mictadlo/mGSV-docker/blob/master/mysql/mgsv.sql" rel="nofollow noreferrer">SQL file</a> contains the database schema and looks like this:</p> <pre><code>CREATE DATABASE mgsv; CREATE USER 'mgsv_user'@'localhost' IDENTIFIED BY 'mgsvpass'; GRANT SELECT, INSERT, CREATE, DROP ON mgsv.* TO 'mgsvuser'@'localhost'; use mgsv; CREATE TABLE IF NOT EXISTS `userinfo` ( `id` int(10) NOT NULL AUTO_INCREMENT, `email` text NOT NULL, `hash` text NOT NULL, `synfilename` text NOT NULL, `annfilename` text NOT NULL, `url` text NOT NULL, `session_id` text NOT NULL, `annImage` int(5) NOT NULL, `create_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; </code></pre> <p>The <a href="https://github.com/mictadlo/mGSV-docker/blob/master/docker-compose.yml" rel="nofollow noreferrer">docker-compose.yml</a> looks like this:</p> <pre><code>version: '3.1' services: db: image: mysql restart: always environment: - MYSQL_DATABASE=mgsv - MYSQL_USER=mgsv_user - MYSQL_PASSWORD=mgsvpass - MYSQL_ROOT_PASSWORD=mysql123 volumes: - ./mysql:/docker-entrypoint-initdb.d www: build: ./mGSV restart: always ports: - 8080:8080 </code></pre> <p>And the <a href="https://github.com/mictadlo/mGSV-docker/blob/master/mGSV/Dockerfile" rel="nofollow noreferrer">Dockerfile</a> contains PHP and all other tools setup and looks like this.</p> <pre><code>FROM php:5-apache RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends \ openjdk-7-jdk \ maven \ git \ &amp;&amp; rm -rf /var/lib/apt/lists/* RUN git clone https://github.com/qunfengdong/mGSV.git # Move the folder 'mgsv' to DocumentRoot of Apache web server. By default, the DocumentRoot of Apache is /var/www/ (speak to the system administrator to know the exact DocumentRoot). RUN cd /var/www/html/mGSV \ &amp;&amp; mkdir tmp \ &amp;&amp; chmod -R 777 tmp RUN cd /var/www/html/mGSV &amp;&amp; sed -i.bak "s|'gsv'|'mgsv_user'|" lib/settings.php \ &amp;&amp; sed -i.bak "s|$database_pass = ''|$database_pass = 'mgsvpass'|" lib/settings.php \ &amp;&amp; sed -i.bak "s|cas-qshare.cas.unt.edu|localhost|" lib/settings.php RUN cp /var/www/html/mGSV/Arial.ttf /usr/share/fonts/truetype/ #Do not understand #7. Cleanup scripts are provided to drop database synteny and annotation tables, remove entries from database table 'userinfo' and delete the folder containing image files which are older than 60 days. This task is accomplished by cron job to run the cleanup script every day. To create a cron job, use the command below: # shell&gt; crontab -e #At the last line of crontab, copy and paste the line below, and provide the exact path to mgsv/lib/cleanup.php # 30 04 * * * /var/www/mgsv/lib/cleanup.php #The script cleanup.php will be executed at 4:30 AM every morning. #8. mGSV uses the mail function from PHP to send email to users. Speak to your system administrator to provide required information in the PHP configuration file called 'php.ini'. #9. When installation completes, you can now open Install/index.php (i.e., http://&lt;YOUR_SERVER_DOMAIN_NAME&gt;/mgsv/Install/), which verifies prerequisites, database setup, and installation. YOUR_SERVER_DOMAIN_NAME refers to the domain name of your server. RUN cd /var/www/html/mGSV/ws \ &amp;&amp; tar -xzf mgsv-ws-server.tar.gz RUN cd /var/www/html/mGSV/ws/mgsv-ws-server \ &amp;&amp; mvn package RUN cp -f /var/www/html/mGSV/ws/mgsv-ws-server/target/ws-server-1.0RC1-jar-with-dependencies.jar /var/www/html/mGSV/ws/ RUN cd /var/www/html/mGSV/ws \ &amp;&amp; echo "mgsv_upload_url=http://localhost/mgsv" &gt; config.properties \ &amp;&amp; echo "ws_publish_url=http\://localhost\:8081/MGSVService" &gt;&gt; config.properties \ &amp;&amp; java -jar ws-server-1.0RC1-jar-with-dependencies.jar &amp; #To stop the web service #shell&gt; ps aux | grep ws-server-1.0RC1-jar-with-dependencies.jar #*Note the process id from the output* #shell&gt; kill -9 &lt;process id&gt; </code></pre> <p>This is the output which I got:</p> <pre><code>Attaching to mgsvdocker_www_1, mgsvdocker_db_1 www_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.20.0.2. Set the 'ServerName' directive globally to suppress this message www_1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.20.0.2. Set the 'ServerName' directive globally to suppress this message www_1 | [Mon Mar 19 22:12:02.742360 2018] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.10 (Debian) PHP/5.6.34 configured -- resuming normal operations www_1 | [Mon Mar 19 22:12:02.744224 2018] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND' db_1 | Initializing database db_1 | 2018-03-19T22:12:02.855291Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-03-19T22:12:03.251862Z 0 [Warning] InnoDB: New log files created, LSN=45790 db_1 | 2018-03-19T22:12:03.348644Z 0 [Warning] InnoDB: Creating foreign key constraint system tables. db_1 | 2018-03-19T22:12:03.411853Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 8d99d2f8-2bc2-11e8-8ace-0242ac140003. db_1 | 2018-03-19T22:12:03.414590Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened. db_1 | 2018-03-19T22:12:03.415526Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option. db_1 | 2018-03-19T22:12:05.555076Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.555603Z 1 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.556433Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.557353Z 1 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.558712Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.559068Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.559557Z 1 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:05.560388Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | Database initialized db_1 | Initializing certificates db_1 | Generating a 2048 bit RSA private key db_1 | ..........................................+++ db_1 | ...........................+++ db_1 | unable to write 'random state' db_1 | writing new private key to 'ca-key.pem' db_1 | ----- db_1 | Generating a 2048 bit RSA private key db_1 | ....................................................................+++ db_1 | .................................................+++ db_1 | unable to write 'random state' db_1 | writing new private key to 'server-key.pem' db_1 | ----- db_1 | Generating a 2048 bit RSA private key db_1 | ..........+++ db_1 | ...................................+++ db_1 | unable to write 'random state' db_1 | writing new private key to 'client-key.pem' db_1 | ----- db_1 | Certificates initialized db_1 | MySQL init process in progress... db_1 | 2018-03-19T22:12:09.627477Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-03-19T22:12:09.628759Z 0 [Note] mysqld (mysqld 5.7.21) starting as process 87 ... db_1 | 2018-03-19T22:12:09.633134Z 0 [Note] InnoDB: PUNCH HOLE support available db_1 | 2018-03-19T22:12:09.634171Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins db_1 | 2018-03-19T22:12:09.634378Z 0 [Note] InnoDB: Uses event mutexes db_1 | 2018-03-19T22:12:09.634769Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier db_1 | 2018-03-19T22:12:09.635298Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 db_1 | 2018-03-19T22:12:09.635485Z 0 [Note] InnoDB: Using Linux native AIO db_1 | 2018-03-19T22:12:09.636263Z 0 [Note] InnoDB: Number of pools: 1 db_1 | 2018-03-19T22:12:09.636914Z 0 [Note] InnoDB: Using CPU crc32 instructions db_1 | 2018-03-19T22:12:09.639991Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M db_1 | 2018-03-19T22:12:09.650561Z 0 [Note] InnoDB: Completed initialization of buffer pool db_1 | 2018-03-19T22:12:09.660208Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority(). db_1 | 2018-03-19T22:12:09.673096Z 0 [Note] InnoDB: Highest supported file format is Barracuda. db_1 | 2018-03-19T22:12:09.697190Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables db_1 | 2018-03-19T22:12:09.701919Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ... db_1 | 2018-03-19T22:12:09.754718Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB. db_1 | 2018-03-19T22:12:09.756113Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active. db_1 | 2018-03-19T22:12:09.756140Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active. db_1 | 2018-03-19T22:12:09.757786Z 0 [Note] InnoDB: Waiting for purge to start db_1 | 2018-03-19T22:12:09.808245Z 0 [Note] InnoDB: 5.7.21 started; log sequence number 2551166 db_1 | 2018-03-19T22:12:09.809069Z 0 [Note] Plugin 'FEDERATED' is disabled. db_1 | 2018-03-19T22:12:09.817123Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool db_1 | 2018-03-19T22:12:09.822791Z 0 [Note] InnoDB: Buffer pool(s) load completed at 180319 22:12:09 db_1 | 2018-03-19T22:12:09.834211Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them. db_1 | 2018-03-19T22:12:09.834819Z 0 [Warning] CA certificate ca.pem is self signed. db_1 | 2018-03-19T22:12:09.846515Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.846560Z 0 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.846579Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.846613Z 0 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.846622Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.846640Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.853203Z 0 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.853233Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:09.890674Z 0 [Note] Event Scheduler: Loaded 0 events db_1 | 2018-03-19T22:12:09.890927Z 0 [Note] mysqld: ready for connections. db_1 | Version: '5.7.21' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server (GPL) db_1 | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it. db_1 | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it. db_1 | 2018-03-19T22:12:13.111650Z 4 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.113784Z 4 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.115619Z 4 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.118409Z 4 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.118432Z 4 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.118458Z 4 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.118526Z 4 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.118543Z 4 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | mysql: [Warning] Using a password on the command line interface can be insecure. db_1 | mysql: [Warning] Using a password on the command line interface can be insecure. db_1 | mysql: [Warning] Using a password on the command line interface can be insecure. db_1 | mysql: [Warning] Using a password on the command line interface can be insecure. db_1 | 2018-03-19T22:12:13.219113Z 8 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222332Z 8 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222366Z 8 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222426Z 8 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222437Z 8 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222459Z 8 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222753Z 8 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. db_1 | 2018-03-19T22:12:13.222768Z 8 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. db_1 | db_1 | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/mgsv.sql db_1 | mysql: [Warning] Using a password on the command line interface can be insecure. db_1 | ERROR 1007 (HY000) at line 1: Can't create database 'mgsv'; database exists </code></pre> <p>I am not quite sure whether I did a mistake in the <a href="https://github.com/mictadlo/mGSV-docker/blob/master/docker-compose.yml" rel="nofollow noreferrer">docker-compose.yml</a> file or database configuration inside the <a href="https://github.com/mictadlo/mGSV-docker/blob/master/mGSV/Dockerfile#L16-L18" rel="nofollow noreferrer">Dockerfile</a>.</p> <p>By any chance, do anyone know what I am missing?</p> <p>Thank you in advance </p>
0
6,104
GDB won't load source file
<ol> <li>I'm using <code>arm-linux-gcc</code> to compile a simple C file at host (debian i386) with <code>-g</code>.</li> <li>Then copy the <code>a.out</code> file to the target (arm,uclibc) computer.</li> <li>Run the <code>a.out</code> – it's just ok.</li> <li>Use GDB (target) <code>gdb a.out</code> and list the source code, it says <code>No such file or directory</code>. The fact has always been so?</li> <li>If I copy the <code>1.c</code> file to the target, then <code>list</code> command it lists the source code.</li> </ol> <p>My Question:</p> <h3>GDB has always been so, or there are other options I can control?</h3> <h3>Do you have any suggestions to debug the program?</h3> <p>Some information maybe is useful:</p> <p><strong>source code 1.c file</strong>:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; // main function int main(void) { int i; for(i=0;i&lt;3;i++){ printf("i=%d\n",i); } return 0; } </code></pre> <p><strong>cross compile version(host)</strong></p> <pre><code>zodiac1111@debian:tmp$ arm-linux-gcc -v Using built-in specs. Target:arm-unknown-linux-uclibcgnueabi Configured with:/home/ldsh/rt9x5/linux/buildroot/buildroot/output/toolchain/gcc-4.3.5/configure \ --prefix=/opt/rt9x5/arm-linux-uclibcgnueabi/usr --build=i686-pc-linux-gnu --host=i686-pc-linux-gnu \ --target=arm-unknown-linux-uclibcgnueabi --enable-languages=c,c++ \ --with-sysroot=/opt/rt9x5/arm-linux-uclibcgnueabi/usr/arm-unknown-linux-uclibcgnueabi/sysroot \ --with-build-time-tools=/opt/rt9x5/arm-linux-uclibcgnueabi/usr/arm-unknown-linux-uclibcgnueabi/bin \ --disable-__cxa_atexit --enable-target-optspace --disable-libgomp --with-gnu-ld --disable-libssp \ --disable-multilib --disable-tls --enable-shared --with-gmp=/opt/rt9x5/arm-linux-uclibcgnueabi/usr \ --with-mpfr=/opt/rt9x5/arm-linux-uclibcgnueabi/usr --enable-threads --disable-decimal-float \ --with-float=soft --with-abi=aapcs-linux --with-arch=armv5te --with-tune=arm926ej-s \ --with-pkgversion='Buildroot 2011.05-dirty' \ --with-bugurl=http://bugs.buildroot.net/ : (reconfigured) /home/ldsh/rt9x5/linux/buildroot/buildroot/output/toolchain/gcc-4.3.5/configure \ --prefix=/opt/rt9x5/arm-linux-uclibcgnueabi/usr --build=i686-pc-linux-gnu --host=i686-pc-linux-gnu \ --target=arm-unknown-linux-uclibcgnueabi --enable-languages=c,c++ \ --with-sysroot=/opt/rt9x5/arm-linux-uclibcgnueabi/usr/arm-unknown-linux-uclibcgnueabi/sysroot \ --with-build-time-tools=/opt/rt9x5/arm-linux-uclibcgnueabi/usr/arm-unknown-linux-uclibcgnueabi/bin \ --disable-__cxa_atexit --enable-target-optspace --disable-libgomp --with-gnu-ld --disable-libssp \ --disable-multilib --disable-tls --enable-shared --with-gmp=/opt/rt9x5/arm-linux-uclibcgnueabi/usr \ --with-mpfr=/opt/rt9x5/arm-linux-uclibcgnueabi/usr --enable-threads --disable-decimal-float \ --with-float=soft --with-abi=aapcs-linux --with-arch=armv5te --with-tune=arm926ej-s \ --with-pkgversion='Buildroot 2011.05-dirty' --with-bugurl=http://bugs.buildroot.net/ Thread model:posix gcc version 4.3.5 (Buildroot 2011.05-dirty) </code></pre> <p><strong>compile command:</strong></p> <pre><code>arm-linux-gcc -g 1.c </code></pre> <p><strong>host:</strong></p> <pre><code>zodiac1111@debian:tmp$ uname -a Linux debian 3.12-1-686-pae #1 SMP Debian 3.12.9-1 (2014-02-01) i686 GNU/Linux </code></pre> <p><strong>target:</strong></p> <pre><code># uname -a Linux AT91SAM9-RT9x5 2.6.39 #25 Mon Dec 30 17:40:40 CST 2013 armv5tejl GNU/Linux </code></pre> <p><strong>after copy to the target,then:</strong></p> <pre><code># ls -l total 1 -rwxr--r-- 1 ftp 83 6094 Feb 21 15:19 a.out </code></pre> <p><strong>execute is ok</strong></p> <pre><code># ./a.out i=0 i=1 i=2 </code></pre> <p><strong>the target gdb version</strong></p> <pre><code># gdb -v dlopen failed on 'libthread_db.so.1' - File not found GDB will not be able to debug pthreads. GNU gdb 6.8 Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "arm-unknown-linux-uclibcgnueabi". </code></pre> <p><strong>debug a.out</strong></p> <pre><code># gdb a.out &lt;...&gt; (gdb) list 1 1.c: No such file or directory. in 1.c (gdb) break main Breakpoint 1 at 0x847c: file 1.c, line 8. (gdb) run Starting program: /data/a.out Breakpoint 1, main () at 1.c:8 8 in 1.c (gdb) step 9 in 1.c (gdb) p i $1 = 0 (gdb) step i=0 8 in 1.c (gdb) p i $2 = 0 (gdb) step 9 in 1.c (gdb) p i $3 = 1 (gdb) </code></pre> <p><strong>if I copy the source code file 1.c into the same directory</strong></p> <pre><code># ls -l -rw-r--r-- 1 ftp 83 158 Feb 21 15:51 1.c -rwxr--r-- 1 ftp 83 6094 Feb 21 15:19 a.out </code></pre> <p><strong>gdb could list the source code now.</strong></p> <pre><code># gdb a.out &lt;...&gt; (gdb) list warning: Source file is more recent than executable. 1 #include &lt;stdio.h&gt; 2 #include &lt;string.h&gt; 3 #include &lt;stdlib.h&gt; 4 // main function 5 int main(void) 6 { 7 int i; 8 for(i=0;i&lt;3;i++){ 9 printf("i=%d\n",i); 10 } (gdb) </code></pre> <p>At host Platform,if I </p> <ol> <li>compile with <code>gcc -g 1.c</code> at host platform. </li> <li>than <strong>rename</strong> or <strong>remove</strong> the <code>1.c</code> file.</li> <li>Use<code>gdb a.out</code></li> </ol> <p>The same situation occurs.</p> <pre><code>zodiac1111@debian:tmp$ gdb -v GNU gdb (GDB) 7.6.2 (Debian 7.6.2-1) Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i486-linux-gnu". For bug reporting instructions, please see: &lt;http://www.gnu.org/software/gdb/bugs/&gt;. zodiac1111@debian:tmp$ gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/i486-linux-gnu/4.8/lto-wrapper Target: i486-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Debian 4.8.2-14' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-i386/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-i386 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-i386 --with-arch-directory=i386 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-targets=all --enable-multiarch --with-arch-32=i586 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu Thread model: posix gcc version 4.8.2 (Debian 4.8.2-14) </code></pre>
0
3,218
Online shopping cart java
<p>I'm having a hard time figuring out why this code is not adding up at the end in "TOTAL COST".</p> <p>Two classes: </p> <p>ShoppingCartPrinter.java and ItemToPurchase.java</p> <p>The result I keep getting are all 0's in "TOTAL COST". Any help would be greatly appreciated. Thanks.</p> <p>ShoppingCartPrinter.java code: </p> <pre><code>import java.util.Scanner; public class ShoppingCartPrinter { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int i = 0; String productName; int productPrice = 0; int productQuantity = 0; int cartTotal = 0; ItemToPurchase item1 = new ItemToPurchase(); ItemToPurchase item2 = new ItemToPurchase(); System.out.println("Item 1"); System.out.println("Enter the item name: "); productName = scnr.nextLine(); // Sets the variable productName for user input System.out.println("Enter the item price: "); productPrice = scnr.nextInt(); // Set the variable productPrice for user input System.out.println("Enter the item quantity: "); productQuantity = scnr.nextInt(); // Set the variable productQuantity for user user input System.out.println(""); item1.setName(productName); item1.setPrice(productPrice); item1.setQuantity(productQuantity); System.out.println("Item 2"); System.out.println("Enter the item name: "); scnr.nextLine(); productName = scnr.nextLine(); // Set the variable productName for user input System.out.println("Enter the item price: "); productPrice = scnr.nextInt(); // Set the variable productPrice for user input System.out.println("Enter the item quantity: "); productQuantity = scnr.nextInt(); // Set the variable productQuantity for user input System.out.println(""); item2.setName(productName); item2.setPrice(productPrice); item2.setQuantity(productQuantity); cartTotal = (item1.getPrice() * item1.getQuantity()) + (item2.getPrice() * item2.getQuantity()); System.out.println("TOTAL COST"); System.out.println(item1.getName() + " " + item1.getQuantity() + " @ $" + item1.getPrice() + " = $" + (item1.getPrice() * item1.getQuantity())); System.out.println(item2.getName() + " " + item2.getQuantity() + " @ $" + item2.getPrice() + " = $" + (item2.getPrice() * item2.getQuantity())); System.out.println(""); System.out.println("Total: $" + cartTotal); return; } } </code></pre> <p>ItemToPurchase.java</p> <pre><code>public class ItemToPurchase { private String itemName; private int itemPrice; private int itemQuantity; public ItemToPurchase() { itemName = "none"; itemPrice = 0; itemQuantity = 0; return; } public void setName(String name) { itemName = name; return; } public void setPrice(int price) { itemPrice = 0; return; } public void setQuantity (int quantity) { itemQuantity = 0; return; } public String getName() { return itemName; } public int getPrice() { return itemPrice; } public int getQuantity() { return itemQuantity; } public void printItemPurchase() { System.out.println(itemQuantity + " " + itemName + " $" + itemPrice + " = $" + (itemPrice * itemQuantity)); } } </code></pre>
0
1,272
How to use a RegExp literal as object key?
<p>I would like to use create a object that contains regular expressions as the key value. I tried to use the following syntax:</p> <pre><code>var kv = { /key/g : "value" }; </code></pre> <p>But it fails according <a href="http://www.javascriptlint.com/">JavaScript lint</a>:</p> <pre><code>SyntaxError: invalid property id </code></pre> <p>How can I fix it?</p> <h3>Update</h3> <p>Background: The reason why I want to do this is to implement a workaround that fixes wrong unicode in a HTTP API result. I know this is very hackish, but since I have no control over the API server code I think this is the best I can do.</p> <p>Currently I implemented the mapping by having a keys array and a values array:</p> <pre><code>function fixUnicode(text) { var result = text; var keys = []; var values = []; keys.push(/&amp;Atilde;&amp;copy;/g); values.push("&amp;eacute;"); keys.push(/&amp;Atilde;&amp;uml;/g); values.push("&amp;egrave;"); keys.push(/&amp;Atilde;&amp;ordf;/g); values.push("&amp;ecirc;"); keys.push(/&amp;Atilde;&amp;laquo;/g); values.push("&amp;euml;"); keys.push(/&amp;Atilde;&amp;nbsp;/g); values.push("&amp;agrave;"); keys.push(/&amp;Atilde;&amp;curren;/g); values.push("&amp;auml;"); keys.push(/&amp;Atilde;&amp;cent;/g); values.push("&amp;acirc;"); keys.push(/&amp;Atilde;&amp;sup1;/g); values.push("&amp;ugrave;"); keys.push(/&amp;Atilde;&amp;raquo;/g); values.push("&amp;ucirc;"); keys.push(/&amp;Atilde;&amp;frac14;/g); values.push("&amp;uuml;"); keys.push(/&amp;Atilde;&amp;acute;/g); values.push("&amp;ocirc;"); keys.push(/&amp;Atilde;&amp;para;/g); values.push("&amp;ouml;"); keys.push(/&amp;Atilde;&amp;reg;/g); values.push("&amp;icirc;"); keys.push(/&amp;Atilde;&amp;macr;/g); values.push("&amp;iuml;"); keys.push(/&amp;Atilde;&amp;sect;/g); values.push("&amp;ccedil;"); for (var i = 0; i &lt; keys.length; ++i) { result = result.replace(keys[i], values[i]); } return result; } </code></pre> <p>But I want to implement to use a JavaScript object to map keys as values:</p> <pre><code>function fixUnicode(text) { var result = text; var keys = { /&amp;Atilde;&amp;copy;/g : "&amp;eacute;", /&amp;Atilde;&amp;uml;/g : "&amp;egrave;" // etc... }; for (var key in keys) { result = result.replace(key, keys[key]); } return result; } </code></pre>
0
1,059
AOP : java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut
<p>I am new to AOP. I got some problem like this.</p> <pre><code>package org.suman.Aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class LoginAspect { //@Before("execution(public String getName())") //@Before("execution(public String org.suman.Model.Triangle.getName())") //@Before("execution(* get*())") //@Before("execution(* get*(..))") //@Before("execution(* org.suman.Model.*.get*())") //@Before("execution(* get*())&amp;&amp; within(org.suman.Model.Circle)") @Before("execution(* get*())&amp;&amp; allCircle()") //@Before("allGetters() &amp;&amp; allCircle()") public void LoginAdvice() { System.out.println("Advice run.. getMethod is called"); } @Before("execution(* get*())") //@Before("allGetters()") public void SecondAdvice() { System.out.println("this is a second Advice"); } @Pointcut("execution(* get*())") public void allGetters(){} //@Pointcut("execution (* * org.suman.Model.Circle.*(..))") @Pointcut("within(org.suman.Model.Circle)") public void allCircle(){} } </code></pre> <p>when using pointcut, the method <code>allGetters()</code> to <code>LoginAdvice</code> method, if I use <code>@Before("execution(* get*())")</code> then no error but if I use <code>@Before("allGetters()")</code> then gives error </p> <blockquote> <p>java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut allGetters </p> </blockquote> <p>if I use <code>@Before("execution(* get*())&amp;&amp; within(org.suman.Model.Circle)")</code> instead of method name it works. </p> <p>My xml like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"&gt; &lt;!-- &lt;context:annotation-config /&gt; --&gt; &lt;aop:aspectj-autoproxy /&gt; &lt;bean name="triangle" class="org.suman.Model.Triangle"&gt; &lt;property name="name" value="Triangle Name"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean name="circle" class="org.suman.Model.Circle"&gt; &lt;property name="name" value="Circle name"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean name="shapeService" class="org.suman.Services.ShapeService" autowire="byName"&gt;&lt;/bean&gt; &lt;bean name="loginAspect" class="org.suman.Aspect.LoginAspect"&gt;&lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>Please solve the problem with pointcut by which it takes method</p>
0
1,260
How to .Scan() a MySQL TIMESTAMP value into a time.Time variable?
<p>I have this Go code:</p> <pre><code>package main import ( "fmt" "database/sql" _"github.com/go-sql-driver/mysql" "time" ) type User struct { id uint32 name string email string rating uint8 subscription uint8 date_registered time.Time online string } // main entry point func main() { // setup db connection db, err := sql.Open("mysql", "user:@tcp(127.0.0.1:3306)/c9?parseTime=true") if err != nil { fmt.Println(err) } defer db.Close() // query rows, err := db.Query("SELECT * FROM users WHERE id = ?", 1) if err != nil { fmt.Println(err) } defer rows.Close() usr := User{} for rows.Next() { err := rows.Scan(&amp;usr.id, &amp;usr.name, &amp;usr.email, &amp;usr.rating, &amp;usr.subscription, &amp;usr.date_registered, &amp;usr.online) if err != nil { fmt.Println(err) } } fmt.Println(usr) err = rows.Err() if err != nil { fmt.Println(err) } } </code></pre> <p>This is what I get from MySQL console:</p> <pre><code>mysql&gt; describe users; +-----------------+---------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------------------+------+-----+-------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(50) | NO | | NULL | | | email | varchar(50) | NO | | NULL | | | rating | tinyint(3) unsigned | YES | | NULL | | | subscription | tinyint(3) unsigned | NO | | 0 | | | date_registered | timestamp | NO | | CURRENT_TIMESTAMP | | | online | char(1) | NO | | N | | +-----------------+---------------------+------+-----+-------------------+----------------+ 7 rows in set (0.00 sec) mysql&gt; SELECT * FROM users; +----+------------+-----------------------+--------+--------------+---------------------+--------+ | id | name | email | rating | subscription | date_registered | online | +----+------------+-----------------------+--------+--------------+---------------------+--------+ | 1 | alakhazamm | abcdefghhhh@gmail.com | NULL | 0 | 2014-10-28 15:37:44 | N | +----+------------+-----------------------+--------+--------------+---------------------+--------+ 1 row in set (0.00 sec) </code></pre> <hr> <p>After <code>.Scan()</code>, <code>fmt.Println(usr)</code> prints</p> <pre><code>{1 alakhazamm abcdefghhhh@gmail.com 0 0 {0 0 &lt;nil&gt;} } </code></pre> <p>The last two fields of the struct are wrong but I have no idea why. I've tried using <code>date_registered string</code> in the struct definition, but I get an empty string after <code>.Scan()</code>. I've also read in the driver's docs that <code>?parseTime=true</code> parses MySQL DATE and DATETIME values into time.Time, but they don't mention TIMESTAMP which is what I'm currently using.</p> <p>Am I missing something important or is it a bug/missing feature of the library?</p>
0
1,554
Under Spring Framework: WARN: WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader)
<p>I have spent all day trying to solve the logging problem I'm having with log4j in a webapp. No matter what I do, I cannot get rid of the following:</p> <pre><code>log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. </code></pre> <p>Just to be clear, I have read all of the articles here on Stack Overflow addressing this issue. I've read the log4j manual. I've been through a dozen different tutorials. I've tried the properties approach and the XML approach (log4j.properties and log4j.xml, respectively). Also, I have confirmed that the log4j.xml file is being read. Aside from the fact that the server tells me so during startup, I can influence the level of feedback through the .xml file. So, yes, the log4j.xml file is in the CLASSPATH.</p> <p>I know I'm missing something simple and fundamental. Below are the relevant files:</p> <p>LOG4J.XML (/WEB-INF):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"&gt; &lt;log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"&gt; &lt;!-- Appenders --&gt; &lt;appender name="console" class="org.apache.log4j.ConsoleAppender"&gt; &lt;param name="Target" value="System.out" /&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%-5p: %c - %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;!-- Application Loggers --&gt; &lt;logger name="com.tiersoftinc.testlog"&gt; &lt;level value="info" /&gt; &lt;/logger&gt; &lt;!-- 3rdparty Loggers --&gt; &lt;logger name="org.springframework.core"&gt; &lt;level value="info" /&gt; &lt;/logger&gt; &lt;logger name="org.springframework.beans"&gt; &lt;level value="info" /&gt; &lt;/logger&gt; &lt;logger name="org.springframework.context"&gt; &lt;level value="info" /&gt; &lt;/logger&gt; &lt;logger name="org.springframework.web"&gt; &lt;level value="info" /&gt; &lt;/logger&gt; &lt;!-- Root Logger --&gt; &lt;root&gt; &lt;priority value="warn" /&gt; &lt;appender-ref ref="console" /&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre> <p>and WEB.XML (/WEB-INF):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;!-- The definition of the Root Spring Container shared by all Servlets and Filters, and the applicationContext.xml file --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/spring/root-context.xml /WEB-INF/spring/app-context.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Logging listener --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/log4j.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- Creates the Spring Container shared by all Servlets and Filters --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- Processes application requests --&gt; &lt;servlet&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/spring/appServlet/servlet-context.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>and APP-CONTEXT.XML (/WEB-INF/spring):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"&gt; &lt;!-- Activates various annotations to be detected in bean classes --&gt; &lt;context:annotation-config /&gt; &lt;!-- Scans the classpath for annotated components that will be auto-registered as Spring beans. For example @Controller and @Service. Make sure to set the correct base-package --&gt; &lt;context:component-scan base-package="com.tiersoftinc.gridlab3" /&gt; &lt;!-- Configures the annotation-driven Spring MVC Controller programming model. Note that, with Spring 3.0, this tag works in Servlet MVC only! --&gt; &lt;mvc:annotation-driven /&gt; &lt;mvc:resources mapping="/resources/**" location="/resources/" /&gt; &lt;!-- Imports datasource configuration --&gt; &lt;import resource="app-context-mongo.xml"/&gt; &lt;/beans&gt; </code></pre> <p>and APP-CONTEXT-MONGO.XML (/WEB-INF/spring):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"&gt; &lt;!-- Activate Spring Data MongoDB repository support --&gt; &lt;mongo:repositories base-package="com.tiersoftinc.gridlab3.repository" /&gt; &lt;bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;/WEB-INF/spring/database.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- MongoDB host --&gt; &lt;mongo:mongo host="${mongo.host.name}" port="${mongo.host.port}"/&gt; &lt;!-- Template for performing MongoDB operations --&gt; &lt;bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" c:mongo-ref="mongo" c:databaseName="${mongo.db.name}"/&gt; &lt;!-- Service for initializing MongoDB with sample data using MongoTemplate --&gt; &lt;bean id="initGridLab3Service" class="com.tiersoftinc.gridlab3.services.InitGridLab3Service" init-method="init"/&gt; &lt;/beans&gt; </code></pre> <p>and, finally, ROOT-CONTEXT.XML (/WEB-INF/spring):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"&gt; &lt;!-- Root Context: defines shared resources visible to all other web components --&gt; &lt;context:annotation-config /&gt; &lt;/beans&gt; </code></pre> <p>What am I missing?</p> <p>Thank you.</p>
0
3,947
Huffman Tree Encoding
<p>My Huffman tree which I had asked about earlier has another problem! Here is the code: </p> <pre><code>package huffman; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Scanner; public class Huffman { public ArrayList&lt;Frequency&gt; fileReader(String file) { ArrayList&lt;Frequency&gt; al = new ArrayList&lt;Frequency&gt;(); Scanner s; try { s = new Scanner(new FileReader(file)).useDelimiter(""); while (s.hasNext()) { boolean found = false; int i = 0; String temp = s.next(); while(!found) { if(al.size() == i &amp;&amp; !found) { found = true; al.add(new Frequency(temp, 1)); } else if(temp.equals(al.get(i).getString())) { int tempNum = al.get(i).getFreq() + 1; al.get(i).setFreq(tempNum); found = true; } i++; } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return al; } public Frequency buildTree(ArrayList&lt;Frequency&gt; al) { Frequency r = al.get(1); PriorityQueue&lt;Frequency&gt; pq = new PriorityQueue&lt;Frequency&gt;(); for(int i = 0; i &lt; al.size(); i++) { pq.add(al.get(i)); } /*while(pq.size() &gt; 0) { System.out.println(pq.remove().getString()); }*/ for(int i = 0; i &lt; al.size() - 1; i++) { Frequency p = pq.remove(); Frequency q = pq.remove(); int temp = p.getFreq() + q.getFreq(); r = new Frequency(null, temp); r.left = p; r.right = q; pq.add(r); // put in the correct place in the priority queue } pq.remove(); // leave the priority queue empty return(r); // this is the root of the tree built } public void inOrder(Frequency top) { if(top == null) { return; } else { inOrder(top.left); System.out.print(top.getString() +", "); inOrder(top.right); return; } } public void printFreq(ArrayList&lt;Frequency&gt; al) { for(int i = 0; i &lt; al.size(); i++) { System.out.println(al.get(i).getString() + "; " + al.get(i).getFreq()); } } } </code></pre> <p>What needs to be done now is I need to create a method that will search through the tree to find the binary code (011001 etc) to the specific character. What is the best way to do this? I thought maybe I would do a normal search through the tree as if it were an AVL tree going to the right if its bigger or left if it's smaller. </p> <p>But because the nodes don't use ints doubles etc. but only using objects that contain characters as strings or null to signify its not a leaf but only a root. The other option would be to do an in-order run through to find the leaf that I'm looking for but at the same time how would I determine if I went right so many times or left so many times to get the character.</p> <pre><code>package huffman; public class Frequency implements Comparable { private String s; private int n; public Frequency left; public Frequency right; Frequency(String s, int n) { this.s = s; this.n = n; } public String getString() { return s; } public int getFreq() { return n; } public void setFreq(int n) { this.n = n; } @Override public int compareTo(Object arg0) { Frequency other = (Frequency)arg0; return n &lt; other.n ? -1 : (n == other.n ? 0 : 1); } } </code></pre> <p>What I'm trying to do is find the binary code to actually get to each character. So if I were trying to encode <code>aabbbcccc</code> how would I create a string holding the binary code for a going left is 0 and going right is 1. </p> <p>What has me confused is because you can't determine where anything is because the tree is obviously unbalanced and there is no determining if a character is right or left of where you are. So you have to search through the whole tree but if you get to a node that isn't what you are looking for, you have backtrack to another root to get to the other leaves.</p>
0
2,178
Transpose of a sparse matrix in C++
<p>I am very new to C++. Here, I am trying to find out transpose of a sparse matrix. Here is the code:</p> <pre><code>#include&lt;iostream&gt; using namespace std; class transposeM{ int m1[20][20],m2[20][20],i,j,row,column,t; public: void read(){ t=0; cout&lt;&lt;"Enter the number of row: \n"; cin&gt;&gt;row; cout&lt;&lt;"enter the number of column: \n"; cin&gt;&gt;column; for(i=0;i&lt;row;i++){ for(j=0;j&lt;column;j++){ cin&gt;&gt;m1[i][j]; if(m1[i][j]){ t++; // cout&lt;&lt;"first t is:"&lt;&lt;t; //if non zero m2[t][0]=i+1; m2[t][1]=j+1; m2[t][2]=m1[i][j]; } } } m2[0][0]=row; m2[0][1]=column; m2[0][2]=t; } void displaysp(){ cout&lt;&lt;"sparse matrix is: \n"; for(i=0;i&lt;=t;i++){ for(j=0;j&lt;3;j++){ cout&lt;&lt;m2[i][j]&lt;&lt;" "; } cout&lt;&lt;"\n"; } } void transpose(){ int transpose[20][3]; transpose[0][0]=m2[0][0]; transpose[0][1]=m2[0][1]; transpose[0][2]=m2[0][2]; cout&lt;&lt;"Transpose is: \n"; int q=1; for(i=1;i&lt;=column;i++){ for(int p=1;p&lt;=t;p++){ if(m2[p][1]==i){ transpose[q][0]=m2[p][0]; transpose[q][1]=m2[p][1]; transpose[q][2]=m2[p][2]; q++; } } } for(i=0;i&lt;=column;i++){ for(j=0;j&lt;3;j++){ cout&lt;&lt;transpose[i][j]&lt;&lt;" "; } cout&lt;&lt;"\n"; } } void display(){ for(i=0;i&lt;row;i++){ for(j=0;j&lt;column;j++){ cout&lt;&lt;m1[i][j]&lt;&lt;" "; } cout&lt;&lt;"\n"; } } }; int main(int argc,char ** argv){ transposeM obj; obj.read(); obj.display(); obj.displaysp(); obj.transpose(); return 0; } </code></pre> <p>Output:</p> <pre><code>Enter the number of row: 2 enter the number of column: 2 0 1 2 0 0 1 2 0 sparse matrix is: 2 2 2 1 2 1 2 1 2 Transpose is: 2 2 2 2 1 2 1 2 1 </code></pre> <p>But something went wrong; read matrix and convert the same to sparse matrix is fine. But finding out transpose got some logical error.</p>
0
1,702
JTable in JScrollPane
<p>I am adding <code>JTable</code> in a <code>JScrollPane</code> then adding scrollpane to the panel, then adding panel to the frame but it doesn't work here's the code. I want to have scroll bar on table or frame that will make table scrollable so user can see it. I have tried many ways but non worked for me here is the whole code</p> <pre><code>public class View extends JFrame { private static final long serialVersionUID = 1L; /** * Launch the application. */ //here in the main method i it adds in the JFrame everything public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { View frame = new View(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public void showData() throws SQLException, ParseException { panel = new JPanel(); panel_1 = new JPanel(); model_1 = new DefaultTableModel(); model_2 = new DefaultTableModel(); model_1.addColumn("Title"); model_1.addColumn("Priority "); model_1.addColumn("DeadLine"); model_1.addColumn("Time"); model_1.addColumn("Progress"); model_2.addColumn("Task Title"); model_2.addColumn("Priority "); model_2.addColumn("DeadLine"); model_2.addColumn("Time"); model_2.addColumn("Done"); Database obj = new Database(); ArrayList&lt;Task&gt; list = obj.getTasks(); for (int i = 0; i &lt; list.size(); i++) { Task task = list.get(i); Object[] row = { task.title, task.priority, task.deadine, task.time, task.progress }; // Comparing Dates Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat("MM-d-yyyy"); String dateNow = formatter.format(currentDate.getTime()); java.util.Date systemDate = new SimpleDateFormat("MM-d-yyyy", Locale.ENGLISH).parse(dateNow); if (!task.deadine.before(systemDate)) { // add row to to do tab model_1.addRow(row); } else { // add row to done tab model_2.addRow(row); } // ********************** } toDoTable = new JTable(model_1); doneTable = new JTable(model_2); toDoTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); doneTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); toDoTable.setFillsViewportHeight(true); doneTable.setFillsViewportHeight(true); //here i add the JScrollPane and it doesnt work JScrollPane jpane = new JScrollPane(toDoTable); JScrollPane jpane1 = new JScrollPane(doneTable); panel.add(jpane); panel_1.add(jpane1); panel.add(jpane); panel_1.add(jpane1); } } </code></pre>
0
1,158
View layout doesn't refresh on orientation change in android
<p>I'd like my VIEW layout to be adjusted on orientation change.</p> <p>My Manifest is set up with: <code>android:configChanges="keyboardHidden|orientation"</code> on the activity.</p> <p>I have <code>res/layout-land</code>, <code>res/layout-port</code>.</p> <p>I have <code>onConfigurationChanged</code> in my <code>Activity</code> (it get's called on rotation).</p> <p>In my <code>Activity</code> I have a <code>ViewFlipper</code> and inside it I have <code>LinearLayouts</code>.</p> <p>When I START the <code>Activity</code> in port or land mode, the View's layout is correct (according to my <code>res/layout-????</code> files).</p> <p>But when I'm already in the <code>Activity</code> and I rotate the phone, then my View layout is not changed. The screen is rotated, and the <code>onCreate</code> of the activity is not called, as it's supposed to be, the <code>onConfigurationChanged</code> is called in the <code>Activity</code>, but the screen is always redrawn with the <code>LinearLayout</code> that was loaded when the <code>Activity</code> started.</p> <p>I have a feeling that I miss out something in the <code>onConfigurationChanged</code>, but don't know what. I guess I need to call some function on the <code>ViewFlipper</code> or on the <code>LinearLayout</code> that's inside. What functions should I call?</p> <pre><code>ViewFlipper flipper; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); flipper = new ViewFlipper(getApplicationContext()); setContentView(flipper); initLayout(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(flipper); } void initLayout() { MyView myview = createMyView(0); flipper.addView(myview, 0); myview = createMyView(1); flipper.addView(myview, 1); myview = createMyView(1); flipper.addView(myview, 1); } </code></pre> <p>I tried to add <code>flipper = new ViewFlipper(getApplicationContext());</code> to <code>onConfigurationChanged()</code> but that made everything black after rotation. I guess I'll have to call initLayout, but that would recalculate everything (and that's exactly what I don't want to do, and that's why I'm trying to do it with <code>onConfigurationChanged</code>, as opposed to the android default "dropMyActivity &amp; createANewActivity"</p> <p><strong>SOLUTION:</strong> Previously I thought I can trigger the layout to be refreshed on rotation, but it seems I have to re-create the layout with the current context (after the orientation change)</p> <pre><code>@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setContentView(R.layout.category_flipper); ViewFlipper oldFlipper = viewFlipper; viewFlipper = (ViewFlipper)findViewById(R.id.categoryFlipper); for (int i = 0; i &lt; 3; i++) { final CardLayout cl = new CardLayout(this, cardData[i]); viewFlipper.addView(cl); } cardData[viewIndex].restorePlayer(); viewFlipper.setDisplayedChild(viewIndex); oldFlipper.removeAllViews(); } </code></pre>
0
1,028
How to cast object to type described by Type class?
<p>I have a object:</p> <pre><code>ExampleClass ex = new ExampleClass(); </code></pre> <p>And:</p> <pre><code>Type TargetType </code></pre> <p>I would like to cast ex to type described by TargetType like this:</p> <pre><code>Object o = (TargetType) ex; </code></pre> <p>But when I do this I get:</p> <blockquote> <p>The type or namespace name 't' could not be found</p> </blockquote> <p>So how to do this? Am I missing something obious here?</p> <p>Update:</p> <p>I would like to obtain something like this:</p> <pre><code>public CustomClass MyClassOuter { get { return (CustomClass) otherClass; } } private otherClass; </code></pre> <p>And because I will have many properties like this I would like do this:</p> <pre><code>public CustomClass MyClassOuter { get { return (GetThisPropertyType()) otherClass; } } private SomeOtherTypeClass otherClass; </code></pre> <p>Context:</p> <p>Normally in my context in my class I need to create many properties. And in every one replace casting to the type of property. It does not seem to have sense to me (in my context) because I know what return type is and I would like to write some kind of code that will do the casting for me. Maybe it's case of generics, I don't know yet. </p> <p>It's like I can assure in this property that I get the right object and in right type and am 100% able to cast it to the property type. </p> <p>All I need to do this so that I do not need to specify in every one property that it has to "cast value to CustomClass", I would like to do something like "cast value to the same class as this property is".</p> <p>For example:</p> <pre><code>class MYBaseClass { protected List&lt;Object&gt; MyInternalObjects; } class MyClass { public SpecialClass MyVeryOwnSpecialObject { get { return (SpecialClass) MyInteralObjects["MyVeryOwnSpecialObject"]; } } } </code></pre> <p>And ok - I can make many properties like this one above - but there is 2 problems: </p> <p>1) I need to specify name of object on MyInternalObjects but it's the same like property name. This I solved with System.Reflection.MethodBase.GetCurrentMethod().Name.</p> <p>2) In every property I need to cast object from MyInternalObjects to different types. In MyVeryOwnSpecialObject for example - to SpecialClass. It's always the same class as the property.</p> <p>That's why I would like to do something like this:</p> <pre><code>class MYBaseClass { protected List&lt;Object&gt; MyInternalObjects; } class MyClass { public SpecialClass MyVeryOwnSpecialObject { get { return (GetPropertyType()) MyInteralObjects[System.Reflection.MethodBase.GetCurrentMethod().Name]; } } } </code></pre> <p>And now concerns: Ok, what for? Because further in my application I will have all benefits of safe types and so on (intellisense).</p> <p>Second one: but now you will lost type safety in this place? No. Because I'm very sure that I have object of my type on a list.</p>
0
1,024
How to navigate one page to another page using AngularJs
<p>How to navigate from one page to another page. Assume i have a login page, after entering username and password fileds while click on submit button it needs to validate and if both username and password is correct it needs to go home page. Home page content needs to display. Here i am posting code. In Browser url is changing but content is not changing.</p> <p><strong>index.html</strong></p> <pre><code>&lt;html ng-app='myApp'&gt; &lt;head&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body &gt; &lt;div id='content' ng-controller='LoginController'&gt; &lt;div class="container"&gt; &lt;form class="form-signin" role="form" ng-submit="login()"&gt; &lt;h3 class="form-signin-heading"&gt;Login Form&lt;/h3&gt; &lt;span&gt;&lt;b&gt;Username :&lt;/b&gt;&amp;nbsp; &lt;input type="username" class="form-control" ng-model="user.name" required&gt; &lt;/span&gt; &lt;/br&gt; &lt;/br&gt; &lt;span&gt;&lt;b&gt;Password :&lt;/b&gt;&amp;nbsp;&amp;nbsp; &lt;input type="password" class="form-control" ng-model="user.password" required&gt; &lt;/span&gt; &lt;br&gt;&lt;br&gt; &lt;button class="btn btn-lg btn-primary btn-block" type="submit"&gt; &lt;b&gt;Sign in&lt;/b&gt; &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- /container --&gt; &lt;/div&gt; &lt;script src='test.js' type="text/javascript"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>home.html</strong></p> <pre><code>Hello I am from Home page </code></pre> <p><strong>test.js</strong></p> <pre><code>var applog = angular.module('myApp',['ngRoute']); applog.config([ '$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider.when('/home', { templateUrl : 'home.html', controller : 'HomeController' }).otherwise({ redirectTo : 'index.html' }); //$locationProvider.html5Mode(true); //Remove the '#' from URL. } ]); applog.controller("LoginController", function($scope, $location) { $scope.login = function() { var username = $scope.user.name; var password = $scope.user.password; if (username == "admin" &amp;&amp; password == "admin") { $location.path("/home" ); } else { alert('invalid username and password'); } }; }); applog.controller("HomeController", function($scope, $location) { }); </code></pre>
0
1,350
Out of memory on a 16571536 byte allocation
<p>Basically i'm adding a wallpaper picker for android 4.4.2 lockscreen background and when the image is set and i turn the screen off then back on to view the lockscreen my screen is going black and logcat is giving me an out of memory allocation error. So far i have tried using Bitmap decodeFile(String pathName) and i also rebased to use Bitmap decodeFile(String pathName, Options opts) but the result is the same every time...</p> <p>Here is the original method used to set the image:</p> <pre><code>private static final String WALLPAPER_IMAGE_PATH = "/data/data/com.android.settings/files/lockscreen_wallpaper.png"; private KeyguardUpdateMonitorCallback mBackgroundChanger = new KeyguardUpdateMonitorCallback() { @Override public void onSetBackground(Bitmap bmp) { if (bmp != null) { mKeyguardHost.setCustomBackground( new BitmapDrawable(mContext.getResources(), bmp)); } else { File file = new File(WALLPAPER_IMAGE_PATH); if (file.exists()) { mKeyguardHost.setCustomBackground( new BitmapDrawable(mContext.getResources(), WALLPAPER_IMAGE_PATH)); } else { mKeyguardHost.setCustomBackground(null); } } updateShowWallpaper(bmp == null); } }; </code></pre> <p>which is being called from case 1 in:</p> <pre><code> public void setCustomBackground(Drawable d) { if (!mAudioManager.isMusicActive()) { int mBackgroundStyle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_BACKGROUND_STYLE, 2); int mBackgroundColor = Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_BACKGROUND_COLOR, 0x00000000); switch (mBackgroundStyle) { case 0: d = new ColorDrawable(mBackgroundColor); d.setColorFilter(BACKGROUND_COLOR, PorterDuff.Mode.SRC_OVER); mCustomBackground = d; break; case 1: KeyguardUpdateMonitor.getInstance(getContext()).dispatchSetBackground(null); break; case 2: default: mCustomBackground = d; } computeCustomBackgroundBounds(mCustomBackground); setBackground(mBackgroundDrawable); } if (!ActivityManager.isHighEndGfx()) { mCustomBackground = d; if (d != null) { d.setColorFilter(BACKGROUND_COLOR, PorterDuff.Mode.SRC_OVER); } computeCustomBackgroundBounds(mCustomBackground); invalidate(); } else { if (getWidth() == 0 || getHeight() == 0) { d = null; } if (d == null) { mCustomBackground = null; setBackground(mBackgroundDrawable); return; } Drawable old = mCustomBackground; if (old == null) { old = new ColorDrawable(0); computeCustomBackgroundBounds(old); } d.setColorFilter(BACKGROUND_COLOR, PorterDuff.Mode.SRC_OVER); mCustomBackground = d; computeCustomBackgroundBounds(d); Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); mBackgroundDrawable.draw(c); Drawable dd = new BitmapDrawable(b); mTransitionBackground = new TransitionDrawable(new Drawable[]{old, dd}); mTransitionBackground.setCrossFadeEnabled(true); setBackground(mTransitionBackground); mTransitionBackground.startTransition(200); mCustomBackground = dd; invalidate(); } if (d != null) { d.setColorFilter(BACKGROUND_COLOR, PorterDuff.Mode.SRC_OVER); } computeCustomBackgroundBounds(mCustomBackground); invalidate(); } </code></pre> <p>this is my logcat output:</p> <pre> I/dalvikvm-heap(13100): Forcing collection of SoftReferences for 16571536-byte allocation E/dalvikvm-heap(13100): Out of memory on a 16571536-byte allocation. I/dalvikvm(13100): "main" prio=5 tid=1 RUNNABLE I/dalvikvm(13100): | group="main" sCount=0 dsCount=0 obj=0x4159fe40 self=0x414d4548 I/dalvikvm(13100): | sysTid=13100 nice=0 sched=0/0 cgrp=apps handle=1074098536 I/dalvikvm(13100): | state=R schedstat=( 0 0 0 ) utm=877 stm=93 core=1 I/dalvikvm(13100): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) I/dalvikvm(13100): at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:613) I/dalvikvm(13100): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:589) I/dalvikvm(13100): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:369) I/dalvikvm(13100): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:395) I/dalvikvm(13100): at com.android.keyguard.KeyguardViewManager$1.onSetBackground(KeyguardViewManager.java:127) I/dalvikvm(13100): at com.android.keyguard.KeyguardUpdateMonitor.dispatchSetBackground(KeyguardUpdateMonitor.java:452) I/dalvikvm(13100): at com.android.keyguard.KeyguardViewManager$ViewManagerHost.setCustomBackground(KeyguardViewManager.java:302) </pre> <p>nothing i have tried as of yet has worked, any ideas?</p> <p>EDITED</p> <p>to further clarify this is what sets the image in Settings:</p> <pre><code> } else if (requestCode == REQUEST_PICK_WALLPAPER) { FileOutputStream wallpaperStream = null; try { wallpaperStream = getActivity().openFileOutput(WALLPAPER_NAME, Context.MODE_WORLD_READABLE); } catch (FileNotFoundException e) { return; // NOOOOO } Uri selectedImageUri = getLockscreenExternalUri(); Bitmap bitmap; if (data != null) { Uri mUri = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), mUri); bitmap.compress(Bitmap.CompressFormat.PNG, 100, wallpaperStream); Toast.makeText(getActivity(), getResources().getString(R.string. background_result_successful), Toast.LENGTH_LONG).show(); Settings.System.putInt(getContentResolver(), Settings.System.LOCKSCREEN_BACKGROUND_STYLE, 1); updateVisiblePreferences(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath()); bitmap.compress(Bitmap.CompressFormat.PNG, 100, wallpaperStream); } catch (NullPointerException npe) { Log.e(TAG, "SeletedImageUri was null."); Toast.makeText(getActivity(), getResources().getString(R.string. background_result_not_successful), Toast.LENGTH_LONG).show(); super.onActivityResult(requestCode, resultCode, data); return; } } } </code></pre>
0
3,579
How to Create Dynamic Menu from Database using Menu control in asp.net?
<p>I want to create a menu from Database and show in Menu Control.</p> <p>Code Here in .aspx page:</p> <pre><code> &lt;asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem" DynamicMenuItemStyle-CssClass="menuItem" runat="server"&gt; </code></pre> <p>In .cs Page of Master:</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { populateMenuItem(); } } private void populateMenuItem() { DataTable menuData = GetMenuData(); AddTopMenuItems(menuData); } /// Filter the data to get only the rows that have a /// null ParentID (This will come on the top-level menu items) private void AddTopMenuItems(DataTable menuData) { DataView view = new DataView(menuData); view.RowFilter = "DepartmentParentID IS NULL"; foreach (DataRowView row in view) { //MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString()); MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString()); Menu1.Items.Add(newMenuItem); AddChildMenuItems(menuData, newMenuItem); } } //This code is used to recursively add child menu items by filtering by ParentID private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem) { DataView view = new DataView(menuData); view.RowFilter = "DepartmentParentID=" + parentMenuItem.Value; foreach (DataRowView row in view) { MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString()); parentMenuItem.ChildItems.Add(newMenuItem); AddChildMenuItems(menuData, newMenuItem); } } private DataTable GetMenuData() { using (SqlConnection con = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand("SELECT DepartmentID,OfficeID,DepartmentName,DepartmentParentID,IsActive,CreatedByID,CreatedDate,LastModifiedByID,LastModifiedDt FROM DepartmentMst", con)) { SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } </code></pre> <p>The Problem is in AddTopMenuItems() Method where it shows "Object reference not set to instance of an object" at line Menu1.Items.Add(newMenuItem); Don't know Why?</p> <p>Here is Data in SQLSERVER2008 DepartmentMst:</p> <pre><code>DepartmentID DepartmentName IsActive DepartmentParentID 1 HR 1 NULL 2 IT 1 NULL 3 Operations 1 NULL 4 Desktop Engineer 1 2 5 Network Engineer 1 2 6 Employee Salary 1 1 </code></pre> <p>When the DepartmentParentID is NULL then it is Main Menu and if not null then it is Child node with respected to its Parent ID.</p> <p>Sample here <a href="http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/" rel="nofollow">http://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/</a></p> <p>Help Appreciated!</p>
0
1,478
docker-compose mysql container denies access to wordpress container
<p>I have a problem with mysql 5.7 container denying access to wordpress container. I'm using docker-compose and I'm running docker on Mac OSX. Docker should be on latest version available.</p> <p>Here's my docker-compose.yml</p> <pre><code>version: '2' services: wordpress: depends_on: - db image: wordpress:latest container_name: wordpress ports: - "8000:80" - "443:443" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_NAME: blog WORDPRESS_DB_USER: blog_admin WORDPRESS_DB_PASSWORD: userpasswd networks: - wordpress_net db: image: mysql:5.7 container_name: db ports: - "3306:3306" volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: rootpasswd MYSQL_DATABASE: blog MYSQL_USER: blog_admin MYSQL_PASSWORD: userpasswd networks: - wordpress_net networks: wordpress_net: volumes: db_data: </code></pre> <p>Logs from db container are: </p> <pre><code>2017-05-12T23:28:06.138429Z 321 [Note] Access denied for user 'blog_admin'@'172.19.0.3' (using password: YES) </code></pre> <p>Logs from wordpress container are:</p> <pre><code>MySQL Connection Error: (1045) Access denied for user 'blog_admin'@'172.19.0.3' (using password: YES) Warning: mysqli::mysqli(): (HY000/1045): Access denied for user 'blog_admin'@'172.19.0.3' (using password: YES) in - on line 22 </code></pre> <p>docker ps:</p> <pre><code>CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1b02f0146fe7 wordpress:latest "docker-entrypoint..." 25 minutes ago Up 26 seconds 0.0.0.0:443-&gt;443/tcp, 0.0.0.0:8000-&gt;80/tcp wordpress 5d932ed6c269 mysql:5.7 "docker-entrypoint..." 25 minutes ago Up 25 minutes 0.0.0.0:3306-&gt;3306/tcp db </code></pre> <p>What have I tried:</p> <ol> <li>Restarting docker host.</li> <li>docker-compose rm -v and then docker-compose up -d again.</li> <li>Logging in with those user credentials and root credentials outside of wordpress container.</li> <li>Removing docker images and pulling them again from scratch.</li> <li>Using root credentials in <code>WORDPRESS_DB_HOST, WORDPRESS_DB_USER</code></li> </ol> <p>I can see all the env vars for db when I connect to db container. Wordpress container keeps restarting it self. I saw one answer on stack overflow which recommended flushing privileges and setting new user account but I want to know if I'm doing something wrong that could cause this problem to appear again on other machine.</p>
0
1,170
How to properly copy/clone DOM element and then paste/insert it as HTML element in Angular.js?
<p>So I've got such big webapp that uses Angular.js.<br />Small part of this webapp has sidebar which, currently, displays two div containers: one that shows user profile stats (thumbnail, reputation, messages, some skills .etc) and second which is slider (angular-ui) carousel showing some images.</p> <p>What I want to do, is to clone this whole skills sidebar and paste this cloned DOM object into slider as another slide, but converted into HTML element.</p> <p>Here's code of this slider:</p> <pre><code>&lt;div id="scrolling-sidebar"&gt; &lt;carousel interval="myInterval"&gt; &lt;slide ng-repeat="slide in slides" active="slide.active"&gt; &lt;a href="{{slide.link}}" ng-if="$index != 1"&gt; &lt;img ng-src="{{slide.image}}" /&gt; &lt;/a&gt; &lt;a href="{{slide.link}}" ng-bind-html="slide.content"&gt;&lt;/a&gt; &lt;/slide&gt; &lt;/carousel&gt; &lt;/div&gt; </code></pre> <p>Here's part of this whole sidebar controller .coffee script:</p> <pre><code>'use strict' angular.module('someApp') .controller 'SidebarCtrl', ($scope, $modal, $http, $location, settings) -&gt; $scope.myInterval = 5000 $scope.slides = [ { image: "/images/_getpro_banners1.png" link: "#/get-pro" } { content: $("#profile-skills-sidebar").clone() link: "#/get-pro" } { image: "/images/_getpro_banners2.png" link: "#/get-pro" } { image: "/images/_getpro_banners3.png" link: "#/get-noticed" } { image: "/images/_getpro_banners4.png" link: "#/get-pro" } { image: "/images/_getpro_banners5.png" link: "#/get-pro" } { image: "/images/_getpro_banners6.png" link: "#/get-pro" } { image: "/images/_getpro_banners7.png" link: "#/get-pro" } ] console.log "Cloned dom element: " + $scope.slides[1].content[0].html() </code></pre> <p>When running this webapp (basically refreshing webpage), I get following error in developer console: <code>TypeError: Cannot read property 'html' at new &lt;anonymous&gt; (http://127.0.0.1:9000/scripts/controllers/sidebar.js:39:69) of undefined</code> which corresponds to this line <code>console.log("Cloned dom element: " + $scope.slides[1].content[0].html());</code> in compiled to js sidebar.js file.</p> <p>So this basically means, that this line <code>content: $("#profile-skills-sidebar").clone()</code> doesn't work like intended - it looks like the DOM element isn't even cloned.</p> <p>Thus, second slide is <code>[object Object]</code> instead copied skills bar.</p> <p>I got jQuery loaded in (using bower and grunt for frontend development), I can use in while in browser devtools:</p> <pre><code>&gt; var skills = $("#profile-skills-sidebar"); &lt; undefined &gt; skills &lt; [&lt;div id="profile-skills-sidebar"&gt;…&lt;/div&gt;] &gt; skills[0] &lt; &lt;div id="profile-skills-sidebar"&gt;…&lt;/div&gt; </code></pre> <p>I tried creating directive in .coffee script:</p> <pre><code>.directive "skillsBarSlide", ['$compile', ($scope, $compile, $timeout) -&gt; restrict: 'A' #template: '&lt;a href="{{slide.link}}"&gt;&lt;/a&gt;' link: (scope, elem, attrs) -&gt; $timeout( -&gt; scope.slides[1].content = angular.element($("#profile-skills-sidebar")).copy() element.append($compile(scope.slides[1].content)(scope)) ) ] </code></pre> <p>but it didn't worked.</p> <p>So what steps precisely I have to make to:<br /> 1. clone needed DOM element<br /> 2. Probably convert it to string of HTML elements (because cloned DOM will be an object)<br /> 3. Insert into desired div container</p> <p>I know that I need here probably $sce, $compile maybe $sanitize (I've read the angular docs a bit), but I'm fresh to angular, didn't understood it well yet.</p> <p>Thanks for eventual help.</p>
0
1,718
Search data in table using ajax in ASP.net MVC
<p>I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...</p> <p>Index.cshtml</p> <pre><code>@model IEnumerable&lt;MvcApplication4.Models.tbl_product&gt; @{ Layout = null; } &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"&gt;&lt;/script&gt; &lt;title&gt;Index&lt;/title&gt; &lt;script type="text/javascript"&gt; $(document).ready(function () { $('#Button1').click(function () { alert("button clicked"); $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", url: 'Home/Index', data: "{'searchString':'" + document.getElementById('searchString').value + "'}", async: false, Success: function (response) { alert("Success"); window.location.reload(); }, error: function () { alert("error"); } }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; @* @using (@Html.BeginForm("Index", "Home")) {*@ @Html.TextBox("searchString"); &lt;input type="button" value="filter" id="Button1" /&gt; @* }*@ &lt;table id="showData"&gt; @{Html.RenderPartial("SearchList");} &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>SearchList.cshtml(Partial View)</p> <pre><code>@foreach (var item in Model) { &lt;tr&gt; &lt;td&gt;@item.ProductName&lt;/td&gt; &lt;td&gt;@item.ProductId&lt;/td&gt; &lt;td&gt;@item.ProductDesc&lt;/td&gt; &lt;/tr&gt; } </code></pre> <p>HomeController.cs</p> <pre><code> public class HomeController : Controller { // // GET: /Home/ ProductEntities dbentity = new ProductEntities(); public ActionResult Index() { return View(dbentity.tbl_product.ToList()); } [HttpPost] public ActionResult Index(string searchString) { var query = dbentity.tbl_product.Where(c =&gt; c.ProductName.Contains(searchString)); return View(query.ToList()); } } </code></pre>
0
1,208
Docker Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) Ubuntu
<p>I was playing with docker and mounted my local mysql to a docker container and connected MySql-Workbench so I could view the DB (experimenting) here is the command I ran.</p> <pre><code>docker run -d --name alldb-mysql -v /var/lib/mysql:/var/lib/mysql -e MYSQL_USER=root -e MYSQL_PASSWORD=password -p 3306:3306 mysql:latest </code></pre> <p>after I stopped my container and removed it, I can't start/restart mysql (local install). when I run <code>sudo /etc/init.d/mysql start</code> it returns </p> <pre><code>[....] Starting mysql (via systemctl): mysql.serviceJob for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details. failed! </code></pre> <p>so I checked <code>systemctl status mysql.service</code></p> <pre><code> mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled) Active: activating (start-post) (Result: exit-code) since Mon 2017-04-03 22:26:15 IST; 26s ago Process: 5470 ExecStart=/usr/sbin/mysqld (code=exited, status=1/FAILURE) Process: 5465 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS) Main PID: 5470 (code=exited, status=1/FAILURE); : 5471 (mysql-systemd-s) Tasks: 2 Memory: 1.6M CPU: 222ms CGroup: /system.slice/mysql.service └─control ├─5471 /bin/bash /usr/share/mysql/mysql-systemd-start post └─6579 sleep 1 Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.980564Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explici Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.980614Z 0 [Warning] Can't create test file /var/lib/mysql/n.lower-test Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.980638Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.17-0ubuntu0.16.04.1) starting as process 5470 . Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.981928Z 0 [Warning] Can't create test file /var/lib/mysql/n.lower-test Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.981936Z 0 [Warning] Can't create test file /var/lib/mysql/n.lower-test Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.982122Z 0 [ERROR] failed to set datadir to /var/lib/mysql/ Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.982142Z 0 [ERROR] Aborting Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.982162Z 0 [Note] Binlog end Apr 03 22:26:15 n mysqld[5470]: 2017-04-03T21:26:15.982213Z 0 [Note] /usr/sbin/mysqld: Shutdown complete Apr 03 22:26:15 n systemd[1]: </code></pre> <p>I also tried to login mysql with my detail: <code>mysql -uroot -ppassword1</code> which returned </p> <pre><code>mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) </code></pre> <p>when I run the following command <code>ls -la /var/lib/ | grep mysql</code> on the var lib directory it returns.</p> <pre><code>drwx------ 12 root docker 4096 Apr 3 21:17 mysql drwx------ 2 mysql mysql 4096 Feb 23 22:35 mysql-files drwx------ 2 mysql mysql 4096 Feb 23 22:35 mysql-keyring drwxr-xr-x 2 root root 4096 Jan 18 21:45 mysql-upgrade </code></pre> <p>By the looks of things I (well docker did) messed up my ownership on my mysql directory.</p> <p>If I run <code>ls -la /var/lib/mysql</code> it returns </p> <pre><code>ls: cannot open directory '/var/lib/mysql': Permission denied </code></pre> <p>and running same command with sudo <code>sudo ls -la /var/lib/mysql </code> it returns </p> <pre><code>total 188480 drwx------ 12 root docker 4096 Apr 3 21:17 . drwxr-xr-x 80 root root 4096 Mar 29 19:28 .. -rw-r----- 1 guest-okauxv docker 56 Feb 23 22:35 auto.cnf drwxr-x--- 2 guest-okauxv docker 4096 Mar 24 23:51 concretepage -rw-r--r-- 1 guest-okauxv docker 0 Feb 23 22:35 debian-5.7.flag drwxr-x--- 2 guest-okauxv docker 4096 Mar 25 00:10 myfidser drwxr-x--- 2 guest-okauxv docker 4096 Mar 4 00:54 myotherFliDB drwxr-x--- 2 guest-okauxv docker 4096 Mar 1 12:33 testFFAPI -rw-r----- 1 guest-okauxv docker 679 Apr 3 21:16 ib_buffer_pool -rw-r----- 1 guest-okauxv docker 79691776 Apr 3 21:17 ibdata1 -rw-r----- 1 guest-okauxv docker 50331648 Apr 3 21:17 ib_logfile0 -rw-r----- 1 guest-okauxv docker 50331648 Feb 23 22:35 ib_logfile1 -rw-r----- 1 guest-okauxv docker 12582912 Apr 3 21:17 ibtmp1 drwxr-x--- 2 guest-okauxv docker 4096 Feb 23 22:35 mysql drwxr-x--- 2 guest-okauxv docker 4096 Mar 25 16:58 NodeRestDB drwxr-x--- 2 guest-okauxv docker 4096 Feb 23 22:35 performance_schema drwxr-x--- 2 guest-okauxv docker 12288 Feb 23 22:35 sys drwxr-x--- 2 guest-okauxv docker 4096 Mar 29 10:34 testDB drwxr-x--- 2 guest-okauxv docker 4096 Mar 1 11:52 demoDB </code></pre> <p>By the looks of this, I (well docker did) managed to changed the owner and group of all the directories in mysql directory.</p> <p><strong>Do I need to do a complete reinstall of MySQL Server?</strong></p> <p><strong>What is the simplest, easiest way to fix this?</strong></p> <p>your help will be much appreciated.</p> <p><strong>Updated with FIX</strong></p> <blockquote> <p>Just what Andy Shinn said in point one, I just ran <code>sudo chown -R mysql:mysql /var/lib/mysql</code> to change the owner back and started mysql by running <code>sudo /etc/init.d/mysql start</code> and mysql returned </p> <p><code>[ ok ]Starting mysql (via systemctl): mysql.service.</code></p> </blockquote> <p>G</p>
0
2,281
HTTP/1.1 401 Unauthorized in Response Headers in Load runner for GET Requests
<p>I am new to Load runner , Am facing am issue while play back of the script</p> <p>LR 12.50</p> <p>O.S Windows 7 SP2</p> <p>Protocol is Mobile HTTP/HTML</p> <p>Recording mode is Proxy</p> <p>Let me explain my scenario</p> <p>While executing following function:</p> <pre><code> web_custom_request("authenticate", "URL=https://ws-xx.xxx.com/tcs/rest/authenticate?include=user,company", "Method=POST", "Resource=0", "RecContentType=application/json", "Referer=", "Snapshot=t1.inf", "Mode=HTTP", "EncType=application/json", "Body={\"password\":\"xxx\",\"username\":\"xxx\",\"version\":\"1.0.40\"}", LAST); </code></pre> <p>For the above POST method , am getting response as below </p> <pre><code> HTTP/1.1 200 OK\r\n Date: Tue, 13 Oct 2015 19:19:21 GMT\r\n Server: Apache-Coyote/1.1\r\n Content-Type: application/json\r\n Set-Cookie: dtCookie=DBE9311E44E5C47902702DC762030583|TXlBcHB8MQ; Path=/; Domain=.xxx.com\r\n Connection: close\r\n Transfer-Encoding: chunked\r\n </code></pre> <p>Which is fine ,Now the second custom request is shown below </p> <pre><code> web_custom_request("profiles", "URL=https://ws-test.xxx.com/tcs/rest/profiles", "Method=GET", "Resource=1", "RecContentType=application/json", "Referer=", "Snapshot=t2.inf", LAST); </code></pre> <p>For the above GET requests in the replay logs am getting:</p> <blockquote> <p>401 unauthorized error.</p> </blockquote> <pre><code> GET /tcs/rest/profiles HTTP/1.1\r\n User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)\r\n Accept: */*\r\n Connection: Keep-Alive\r\n Host: ws-test.xxx.com\r\n Cookie: dtCookie=DBE9311E44E5C47902702DC762030583|TXlBcHB8MQ\r\n \r\n t=5921ms: 172-byte response headers for "https://ws-test.xxx.com/tcs/rest/profiles" (RelFrameId=1, Internal ID=2) HTTP/1.1 401 Unauthorized\r\n Date: Tue, 13 Oct 2015 19:19:22 GMT\r\n Server: Apache-Coyote/1.1\r\n Content-Type: application/json\r\n Connection: close\r\n Transfer-Encoding: chunked\r\n \r\n t=5922ms: 4-byte chunked response overhead for "https://ws-test.xxx.com/tcs/rest/profiles" (RelFrameId=1, Internal ID=2) 8b\r\n t=5923ms: 139-byte chunked response body for "https://ws-test.xxx.com/tcs/rest/profiles" (RelFrameId=1, Internal ID=2) {"errors":[{"message":"Authentication required to access endpoint","status":"401","code":" NotAuthenticated","header":"Not Authenticated"}]} </code></pre> <p>I refereed <a href="http://www.sqaforums.com/showflat.php?Number=645138" rel="nofollow noreferrer">this link</a>.</p> <p>My understanding from the above custom request , login is success but the next subsequent requests are getting failed.</p> <p>I have used web_cleanup_cookies() function but didn't solve the issue .</p> <p>I tried to capture the Cookie ID using the below function</p> <pre><code>web_reg_save_param("COOKIE_ID", "LR= Cookie: dtCookie=" , "RB= |TXlBcHB8MQ\r\n", "Ord=All", "RelFrameId=1", "Search=All", LAST); web_add_header("Cookie",lr_eval_string("{COOKIE_ID}")); </code></pre> <p>Now question is where to place parameter "COOKIE_ID" in my script while there is </p> <p>no value in script for COOKIE_ID?</p> <p>How to handle this issue ? Can anybody please help me .</p>
0
1,595
BeanCreationException : Invocation of init method failed
<p>I am trying to implement LDAP configuration for my Spring Project but LDAP Repository is not getting initialized. </p> <p>Error Trace is - </p> <pre><code>xx:xx:xx.116 [localhost-startStop-1] WARN o.s.w.c.s.XmlWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo': Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.springframework.ldap.repository.support.LdapRepositoryFactory$LdapQueryLookupStrategy.resolveQuery(Ljava/lang/reflect/Method;Lorg/springframework/data/repository/core/RepositoryMetadata;Lorg/springframework/data/projection/ProjectionFactory;Lorg/springframework/data/repository/core/NamedQueries;)Lorg/springframework/data/repository/query/RepositoryQuery; xx:xx:xx.124 [localhost-startStop-1] ERROR o.s.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepo': Invocation of init method failed; nested exception is java.lang.AbstractMethodError: org.springframework.ldap.repository.support.LdapRepositoryFactory$LdapQueryLookupStrategy.resolveQuery(Ljava/lang/reflect/Method;Lorg/springframework/data/repository/core/RepositoryMetadata;Lorg/springframework/data/projection/ProjectionFactory;Lorg/springframework/data/repository/core/NamedQueries;)Lorg/springframework/data/repository/query/RepositoryQuery; at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) ~[spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5068) [catalina.jar:7.0.68] at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5584) [catalina.jar:7.0.68] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) [catalina.jar:7.0.68] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1572) [catalina.jar:7.0.68] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1562) [catalina.jar:7.0.68] at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_73] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_73] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_73] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_73] Caused by: java.lang.AbstractMethodError: org.springframework.ldap.repository.support.LdapRepositoryFactory$LdapQueryLookupStrategy.resolveQuery(Ljava/lang/reflect/Method;Lorg/springframework/data/repository/core/RepositoryMetadata;Lorg/springframework/data/projection/ProjectionFactory;Lorg/springframework/data/repository/core/NamedQueries;)Lorg/springframework/data/repository/query/RepositoryQuery; at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.&lt;init&gt;(RepositoryFactorySupport.java:435) ~[spring-data-commons-1.12.1.RELEASE.jar:na] at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:220) ~[spring-data-commons-1.12.1.RELEASE.jar:na] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:266) ~[spring-data-commons-1.12.1.RELEASE.jar:na] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:252) ~[spring-data-commons-1.12.1.RELEASE.jar:na] at org.springframework.ldap.repository.support.LdapRepositoryFactoryBean.afterPropertiesSet(LdapRepositoryFactoryBean.java:47) ~[spring-ldap-core-2.0.4.RELEASE.jar:2.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE] ... 21 common frames omitted </code></pre> <p>UserRepo.java</p> <pre><code>package domain; import org.springframework.ldap.repository.LdapRepository; import java.util.List; public interface UserRepo extends LdapRepository&lt;User&gt; { User findByEmployeeNumber(int employeeNumber); List&lt;User&gt; findByFullNameContains(String name); } </code></pre> <p>applicationContext.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:ldap="http://www.springframework.org/schema/ldap" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/ldap http://www.springframework.org/schema/ldap/spring-ldap.xsd"&gt; &lt;context:property-placeholder location="classpath:/ldap.properties" system-properties-mode="OVERRIDE" /&gt; &lt;context:annotation-config /&gt; &lt;ldap:context-source id="contextSource" password="${sample.ldap.password}" url="${sample.ldap.url}" username="${sample.ldap.userDn}" base="${sample.ldap.base}" /&gt; &lt;ldap:ldap-template id="ldapTemplate" context-source-ref="contextSource"/&gt; &lt;!-- This will scan the org.springframework.ldap.samples.useradmin.domain package for interfaces extending CrudRepository (in our case, LdapRepository), automatically creating repository beans based on these interfaces. --&gt; &lt;ldap:repositories base-package="domain" /&gt; &lt;bean class="service.UserService"&gt; &lt;property name="directoryType" value="${sample.ldap.directory.type}" /&gt; &lt;/bean&gt; &lt;!-- Required to make sure BaseLdapName is populated in UserService --&gt; &lt;bean class="org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor" /&gt; &lt;beans profile="default"&gt; &lt;!-- Populates the LDAP server with initial data --&gt; &lt;bean class="org.springframework.ldap.test.LdifPopulator" depends-on="embeddedLdapServer"&gt; &lt;property name="contextSource" ref="contextSource" /&gt; &lt;property name="resource" value="classpath:/setup_data.ldif" /&gt; &lt;property name="base" value="${sample.ldap.base}" /&gt; &lt;property name="clean" value="${sample.ldap.clean}" /&gt; &lt;property name="defaultBase" value="dc=example,dc=com" /&gt; &lt;/bean&gt; &lt;!-- This is for test and demo purposes only - EmbeddedLdapServerFactoryBean launches an in-process LDAP server. --&gt; &lt;bean id="embeddedLdapServer" class="org.springframework.ldap.test.EmbeddedLdapServerFactoryBean"&gt; &lt;property name="partitionName" value="example"/&gt; &lt;property name="partitionSuffix" value="${sample.ldap.base}" /&gt; &lt;property name="port" value="18880" /&gt; &lt;/bean&gt; &lt;/beans&gt; &lt;beans profile="no-apacheds"&gt; &lt;!-- Populates the LDAP server with initial data --&gt; &lt;bean class="org.springframework.ldap.test.LdifPopulator"&gt; &lt;property name="contextSource" ref="contextSource" /&gt; &lt;property name="resource" value="classpath:/setup_data.ldif" /&gt; &lt;property name="base" value="${sample.ldap.base}" /&gt; &lt;property name="clean" value="${sample.ldap.clean}" /&gt; &lt;property name="defaultBase" value="dc=example,dc=com" /&gt; &lt;/bean&gt; &lt;/beans&gt; &lt;/beans&gt; </code></pre> <p>UserService.java</p> <pre><code>package service; import java.util.List; import java.util.Set; import javax.naming.Name; import javax.naming.ldap.LdapName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.core.support.BaseLdapNameAware; import org.springframework.ldap.support.LdapNameBuilder; import org.springframework.ldap.support.LdapUtils; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import domain.DirectoryType; import domain.User; import domain.UserRepo; /** * */ public class UserService implements BaseLdapNameAware { private final UserRepo userRepo; private LdapName baseLdapPath; private DirectoryType directoryType; @Autowired public UserService(UserRepo userRepo) { this.userRepo = userRepo; //this.groupRepo = groupRepo; } public void setDirectoryType(DirectoryType directoryType) { this.directoryType = directoryType; } public void setBaseLdapPath(LdapName baseLdapPath) { this.baseLdapPath = baseLdapPath; } public Iterable&lt;User&gt; findAll() { return userRepo.findAll(); } public User findUser(String userId) { return userRepo.findOne(LdapUtils.newLdapName(userId)); } public LdapName toAbsoluteDn(Name relativeName) { return LdapNameBuilder.newInstance(baseLdapPath) .add(relativeName) .build(); } /** * This method expects absolute DNs of group members. In order to find the actual users * the DNs need to have the base LDAP path removed. * * @param absoluteIds * @return */ public Set&lt;User&gt; findAllMembers(Iterable&lt;Name&gt; absoluteIds) { return Sets.newLinkedHashSet(userRepo.findAll(toRelativeIds(absoluteIds))); } public Iterable&lt;Name&gt; toRelativeIds(Iterable&lt;Name&gt; absoluteIds) { return Iterables.transform(absoluteIds, new Function&lt;Name, Name&gt;() { public Name apply(Name input) { return LdapUtils.removeFirst(input, baseLdapPath); } }); } public List&lt;User&gt; searchByNameName(String lastName) { return userRepo.findByFullNameContains(lastName); } } </code></pre> <p>Following are dependencies-</p> <p><a href="https://i.stack.imgur.com/iByrv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iByrv.png" alt="enter image description here"></a></p> <p>I am not able to resolve this error. LDAP repositories base package is mentioned in applicationContext.xml but still exption follows. Please let me know for correct implimentation.</p> <p>Edit - : Dependency tree</p> <p><a href="https://i.stack.imgur.com/AZYJn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AZYJn.png" alt="enter image description here"></a></p>
0
5,094
Top 1 on Left Join SubQuery
<p>I am trying to take a person and display their current insurance along with their former insurance. I guess one could say that I'm trying to flaten my view of customers or people. I'm running into an issue where I'm getting multiple records back due to multiple records existing within my left join subqueries. I had hoped I could solve this by adding "TOP 1" to the subquery, but that actually returns nothing...</p> <p>Any ideas?</p> <pre><code> SELECT p.person_id AS 'MIRID' , p.firstname AS 'FIRST' , p.lastname AS 'LAST' , pg.name AS 'GROUP' , e.name AS 'AOR' , p.leaddate AS 'CONTACT DATE' , [dbo].[GetPICampaignDisp](p.person_id, '2009') AS 'PI - 2009' , [dbo].[GetPICampaignDisp](p.person_id, '2008') AS 'PI - 2008' , [dbo].[GetPICampaignDisp](p.person_id, '2007') AS 'PI - 2007' , a_disp.name AS 'CURR DISP' , a_ins.name AS 'CURR INS' , a_prodtype.name AS 'CURR INS TYPE' , a_t.date AS 'CURR INS APP DATE' , a_t.effdate AS 'CURR INS EFF DATE' , b_disp.name AS 'PREV DISP' , b_ins.name AS 'PREV INS' , b_prodtype.name AS 'PREV INS TYPE' , b_t.date AS 'PREV INS APP DATE' , b_t.effdate AS 'PREV INS EFF DATE' , b_t.termdate AS 'PREV INS TERM DATE' FROM [person] p LEFT OUTER JOIN [employee] e ON e.employee_id = p.agentofrecord_id INNER JOIN [dbo].[person_physician] pp ON p.person_id = pp.person_id INNER JOIN [dbo].[physician] ph ON ph.physician_id = pp.physician_id INNER JOIN [dbo].[clinic] c ON c.clinic_id = ph.clinic_id INNER JOIN [dbo].[d_Physgroup] pg ON pg.d_physgroup_id = c.physgroup_id LEFT OUTER JOIN ( SELECT tr1.* FROM [transaction] tr1 LEFT OUTER JOIN [d_vendor] ins1 ON ins1.d_vendor_id = tr1.d_vendor_id LEFT OUTER JOIN [d_product_type] prodtype1 ON prodtype1.d_product_type_id = tr1.d_product_type_id LEFT OUTER JOIN [d_commission_type] ctype1 ON ctype1.d_commission_type_id = tr1.d_commission_type_id WHERE prodtype1.name &lt;&gt; 'Medicare Part D' AND tr1.termdate IS NULL ) AS a_t ON a_t.person_id = p.person_id LEFT OUTER JOIN [d_vendor] a_ins ON a_ins.d_vendor_id = a_t.d_vendor_id LEFT OUTER JOIN [d_product_type] a_prodtype ON a_prodtype.d_product_type_id = a_t.d_product_type_id LEFT OUTER JOIN [d_commission_type] a_ctype ON a_ctype.d_commission_type_id = a_t.d_commission_type_id LEFT OUTER JOIN [d_disposition] a_disp ON a_disp.d_disposition_id = a_t.d_disposition_id LEFT OUTER JOIN ( SELECT tr2.* FROM [transaction] tr2 LEFT OUTER JOIN [d_vendor] ins2 ON ins2.d_vendor_id = tr2.d_vendor_id LEFT OUTER JOIN [d_product_type] prodtype2 ON prodtype2.d_product_type_id = tr2.d_product_type_id LEFT OUTER JOIN [d_commission_type] ctype2 ON ctype2.d_commission_type_id = tr2.d_commission_type_id WHERE prodtype2.name &lt;&gt; 'Medicare Part D' AND tr2.termdate IS NOT NULL ) AS b_t ON b_t.person_id = p.person_id LEFT OUTER JOIN [d_vendor] b_ins ON b_ins.d_vendor_id = b_t.d_vendor_id LEFT OUTER JOIN [d_product_type] b_prodtype ON b_prodtype.d_product_type_id = b_t.d_product_type_id LEFT OUTER JOIN [d_commission_type] b_ctype ON b_ctype.d_commission_type_id = b_t.d_commission_type_id LEFT OUTER JOIN [d_disposition] b_disp ON b_disp.d_disposition_id = b_t.d_disposition_id WHERE pg.d_physgroup_id = @PhysGroupID </code></pre>
0
1,954
How can I fix Laravel 5.1 - 404 Not Found?
<p>I am trying to use Laravel 5.1 for the first time. I was able to install it and <code>https://sub.example.com/laravel/public/</code> is displaying what is should. However, views I create are giving me a 404 error Page not found.</p> <p>Here is what I have done so far:</p> <p>I created a controller in <code>laravel\app\Http\controllers\Authors.php</code></p> <p>Here is the code behind the <code>Authors.php</code> file</p> <pre><code>&lt;?php class Authors_Controller extends Base_Controller { public $restful = true; public function get_index() { return View::make('authors.index') -&gt;with('title', 'Authors and Books') -&gt;with('authors', Author::order_by('name')-&gt;get()); } } </code></pre> <p>Then I created a view in <code>laravel\resources\views\Authors\index.blade.php</code></p> <p>Here is the code behind the <code>index.blade.php</code> file</p> <pre><code>@layout('layouts.default') @section('content') Hello, this is a test @endsection </code></pre> <p>Then I created a layout in <code>laravel\resources\views\layouts\default.blade.php</code></p> <p>Here is the code behind the <code>default.blade.php</code> file</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;{{ $title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; @if(Session::has('message')) &lt;p style="color: green;"&gt;{{ Session::get('message') }}&lt;/p&gt; @endif @yield('content') Hello - My first test &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Finally I created a route in <code>laravel\app\Http\routes.php</code></p> <pre><code>&lt;?php Route::get('/', function () { return view('welcome'); }); Route::get('authors', array('as'=&gt;'authors', 'uses'=&gt;'authors@index')); </code></pre> <p>But for some reason I keep getting 404 error Page not found.</p> <p>I enabled the mod_rewrite on my Apache 2.4.9 by uncommenting out the line</p> <pre><code>LoadModule rewrite_module modules/mod_rewrite.so </code></pre> <p>Then restarted Apache.</p> <p>From what I can tell in the <code>php_info()</code> output the mod_rewrite is enabled</p> <pre><code>Loaded Modules core mod_win32 mpm_winnt http_core mod_so mod_php5 mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl </code></pre> <p>My current .htaccess file looks like this "which is the factory default"</p> <p> Options -MultiViews </p> <pre><code>RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </code></pre> <p></p> <p>I have also tried to change it to the code below as per the <a href="http://laravel.com/docs/5.1" rel="nofollow noreferrer">documentation</a>:</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </code></pre> <p>However, I am still getting the 404 page when I go to</p> <pre><code>https://sub.example.com/laravel/public/authors </code></pre> <p>What am I doing wrong? How can I fix this problem?</p>
0
1,397
How to make expandable panel layout in android?
<p>I have very complex layout to do in android ?</p> <p>I need two panels the if one expanded the other is extended and otherwise, i would like to make a behavior like slidingdrawer but because i can have in view only button and nothing else i'm in deep trouble.</p> <p><img src="https://i.stack.imgur.com/Vvscs.png" alt="enter image description here"></p> <p>here is the example of what i need please help, i have spent already 3 days on it, havent found an answer for this.</p> <p>here is my code`</p> <p> </p> <pre><code> &lt;RelativeLayout android:id="@+id/imagesContent" android:orientation="vertical" android:layout_alignBottom="@+id/lhsLogo" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="3dp" android:src="@drawable/orange_price_tag" android:layout_toLeftOf="@+id/lhsLogo" android:layout_alignBottom="@+id/lhsLogo" /&gt; &lt;LinearLayout android:layout_centerHorizontal="true" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="0dp" android:text="50%" android:singleLine="false" android:textColor="#ffffff" android:textSize="17dp" android:id="@+id/discountTypeNumbers" android:layout_weight="1" /&gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="הנחה" android:singleLine="false" android:textColor="#ffffff" android:textSize="14dp" android:id="@+id/discountTypeText" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; &lt;TextView android:id="@+id/detailsTextContent" android:layout_below="@+id/imagesContent" android:layout_width="fill_parent" android:layout_height="200dp" android:textSize="11dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:scrollbars = "vertical" android:layout_marginTop="10dp" android:text="some textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome textsome" android:singleLine="false" /&gt; &lt;RelativeLayout android:id="@+id/frame" android:background="#ffffff" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"&gt; &lt;!--... stuff you want to cover at full-size ...--&gt; &lt;LinearLayout android:id="@+id/special_details_buttons" android:layout_marginTop="5dp" android:layout_marginLeft="5dp" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;ImageView android:id="@+id/specialTerms" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginLeft="2dp" android:src="@drawable/special_terms" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginLeft="5dp" android:src="@drawable/special_details" /&gt; &lt;CheckBox android:id="@+id/setFavorite" style="@style/favorites_button" android:button="@drawable/favorites_button"/&gt; &lt;ImageView android:id="@+id/acceptTerms" android:src="@drawable/accept_special" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginLeft="48dp" /&gt; &lt;/LinearLayout&gt; &lt;RelativeLayout android:layout_below="@+id/special_details_buttons" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" android:orientation="vertical"&gt; &lt;il.co.package.widgets.WrappingSlidingDrawer android:id="@+id/drawer" android:layout_width="fill_parent" android:layout_height="200dp" android:content="@+id/content" android:handle="@+id/handle"&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/handle"&gt; &lt;ImageView android:id="@+id/slide_handle" android:src="@drawable/expand_open" android:layout_width="170dp" android:layout_height="21dp" android:layout_alignParentRight="true" /&gt; &lt;/RelativeLayout&gt; &lt;LinearLayout android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ffffff" android:id="@+id/content"&gt; &lt;/LinearLayout&gt; &lt;/il.co.package.widgets.WrappingSlidingDrawer&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p> `</p>
0
3,028
spring-boot datasource profiles w/ application.properties
<p><strong><em>Updated Question based upon feedback:</em></strong></p> <p>I have a spring-boot application that has three databases: H2 for integration testing, and Postgresql for qa &amp; production. Since spring-boot creates a default datasource for you, I don't have anything defined for my integration tests. I thought I would use application.properties to define my datasource connection values but I am not certain what is the best way to handle this. </p> <p>I have two files:</p> <p><strong>src/main/resources/application.properties</strong></p> <pre><code>spring.profiles.active=production appName = myProduct serverPort=9001 spring.datasource.url=jdbc:postgresql://localhost/myDatabase spring.datasource.username=user spring.datasource.password=password spring.datasource.driverClassName=org.postgresql.Driver spring.jpa.hibernate.hbm2ddl.auto=update spring.jpa.hibernate.ejb.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy spring.jpa.hibernate.show_sql=true spring.jpa.hibernate.format_sql=true spring.jpa.hibernate.use_sql_comments=false spring.jpa.hibernate.type=all spring.jpa.hibernate.disableConnectionTracking=true spring.jpa.hibernate.default_schema=dental </code></pre> <p><strong>src/main/resources/application-test.properties</strong></p> <pre><code>spring.profiles.active=test serverPort=9002 spring.datasource.url = jdbc:h2:~/testdb spring.datasource.username = sa spring.datasource.password = spring.datasource.driverClassName = org.h2.Driver liquibase.changeLog=classpath:/db/changelog/db.changelog-master.sql </code></pre> <p>I used to run my tests with with gradle (using "gradle build test") or within IntelliJ. I updated my gradle file to use:</p> <pre><code>task setTestEnv { run { systemProperty "spring.profiles.active", "test" } } </code></pre> <p>But when I run <strong>gradle clean build setTestEnv test</strong> I get errors that seem to indicate the test is trying to connect to an actual Postgresql database: </p> <pre><code>Caused by: org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections. at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:138) at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66) at org.postgresql.jdbc2.AbstractJdbc2Connection.&lt;init&gt;(AbstractJdbc2Connection.java:125) at org.postgresql.jdbc3.AbstractJdbc3Connection.&lt;init&gt;(AbstractJdbc3Connection.java:30) at org.postgresql.jdbc3g.AbstractJdbc3gConnection.&lt;init&gt;(AbstractJdbc3gConnection.java:22) at org.postgresql.jdbc4.AbstractJdbc4Connection.&lt;init&gt;(AbstractJdbc4Connection.java:32) at org.postgresql.jdbc4.Jdbc4Connection.&lt;init&gt;(Jdbc4Connection.java:24) at org.postgresql.Driver.makeConnection(Driver.java:393) at org.postgresql.Driver.connect(Driver.java:267) at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:278) at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:182) at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:701) at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:635) at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:486) at org.apache.tomcat.jdbc.pool.ConnectionPool.&lt;init&gt;(ConnectionPool.java:144) at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:116) at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:103) at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:127) at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:288) ... 42 more Caused by: java.net.ConnectException: Connection refused at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) </code></pre> <p>I haven't figured out how to set the default system.property == "test" within IntelliJ yet...</p>
0
1,457
How do I scroll in tmux using the mouse?
<p>I'm using tmux 1.8 on Mac OS X 1.9.3 in the Terminal.app with an Apple magic mouse. I'm also using oh-my-zsh.</p> <p>I can't scroll at all with the mouse when tmux is running. It just scrolls the whole terminal window up which goes beyond the output of tmux.</p> <p>I've tried these settings in the tmux.conf file but nothing works:</p> <pre><code>set -g mode-mouse on setw -g mode-mouse on set -g terminal-overrides 'xterm*:smcup@:rmcup@' </code></pre> <p>I made sure to reload the tmux.conf and also killed a sessions and created new ones just to make sure. And it still doesn't work.</p> <p>Please help. Here is my entire tmux.conf</p> <pre><code>set -g default-terminal "xterm-256color" set -g history-limit 10000 set -g status-interval 60 # status config set -g status-utf8 on set -g status-position top set -g status-fg colour15 set -g status-bg colour24 # status line left side set -g status-left-length 40 set -g status-left "#[fg=colour214,bold] #S #[fg=colour45] " # status line right side set -g status-right "#(~/.dotfiles/bin/tmux_battery_status) | %I:%M %p | %D " # no more machine counting set -g base-index 1 setw -g pane-base-index 1 # enable activity alerts setw -g monitor-activity on set -g visual-activity on # window list colors setw -g window-status-fg colour250 setw -g window-status-bg default setw -g window-status-format " #I #W " setw -g window-status-current-format "  #W " setw -g window-status-current-fg colour118 setw -g window-status-current-bg default setw -g window-status-activity-attr underscore,bold # center the window list set -g status-justify left # pane colors set -g pane-border-fg colour24 set -g pane-border-bg default set -g pane-active-border-fg colour15 set -g pane-active-border-bg colour15 # command / message line colors set -g message-fg colour15 set -g message-bg black set -g message-attr bright # rebind clear screen with Ctrl-l bind C-l send-keys 'C-l' # reload tmux conf bind r source-file ~/.tmux.conf \; display "Reloaded tmux.conf!" # setup reattach-to-user-namespace for copy and paste set-option -g default-command "reattach-to-user-namespace -l $SHELL" # use vim keybindings in copy mode setw -g mode-keys vi setw -g mode-mouse on setw -g mouse-utf8 on setw -g mouse-select-pane on setw -g mouse-select-window on setw -g mouse-resize-pane on # setup 'v' to begin selection as in vim bind -t vi-copy v begin-selection bind -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy" # update default binding of 'enter' to also use copy-pipe unbind -t vi-copy Enter bind -t vi-copy enter copy-pipe "reattach-to-user-namespace pbcopy" # splitting panes bind | split-window -h bind - split-window -v # fast resizing (-r for repeatable) bind -r h resize-pane -L 5 bind -r j resize-pane -D 5 bind -r k resize-pane -U 5 bind -r l resize-pane -R 5 # tmux navigator with vim (-n allows binding without tmux prefix) bind -n C-h run "(tmux display-message -p '#{pane_current_command}' | grep -iqE '(^|\/)vim(diff)?$' &amp;&amp; tmux send-keys C-h) || tmux select-pane -L" bind -n C-j run "(tmux display-message -p '#{pane_current_command}' | grep -iqE '(^|\/)vim(diff)?$' &amp;&amp; tmux send-keys C-j) || tmux select-pane -D" bind -n C-k run "(tmux display-message -p '#{pane_current_command}' | grep -iqE '(^|\/)vim(diff)?$' &amp;&amp; tmux send-keys C-k) || tmux select-pane -U" bind -n C-l run "(tmux display-message -p '#{pane_current_command}' | grep -iqE '(^|\/)vim(diff)?$' &amp;&amp; tmux send-keys C-l) || tmux select-pane -R" bind -n C-\ run "(tmux display-message -p '#{pane_current_command}' | grep -iqE '(^|\/)vim(diff)?$' &amp;&amp; tmux send-keys 'C-\\') || tmux select-pane -l" </code></pre>
0
1,408
C# Parallel Vs. Threaded code performance
<p>I've been testing the performance of System.Threading.Parallel vs a Threading and I'm surprised to see Parallel taking longer to finish tasks than threading. I'm sure it's due to my limited knowledge of Parallel, which I just started reading up on.</p> <p>I thought i'll share few snippets and if anyone can point out to me paralle code is running slower vs threaded code. Also tried to run the same comparison for finding prime numbers and found parallel code finishing much later than threaded code.</p> <pre><code>public class ThreadFactory { int workersCount; private List&lt;Thread&gt; threads = new List&lt;Thread&gt;(); public ThreadFactory(int threadCount, int workCount, Action&lt;int, int, string&gt; action) { workersCount = threadCount; int totalWorkLoad = workCount; int workLoad = totalWorkLoad / workersCount; int extraLoad = totalWorkLoad % workersCount; for (int i = 0; i &lt; workersCount; i++) { int min, max; if (i &lt; (workersCount - 1)) { min = (i * workLoad); max = ((i * workLoad) + workLoad - 1); } else { min = (i * workLoad); max = (i * workLoad) + (workLoad - 1 + extraLoad); } string name = "Working Thread#" + i; Thread worker = new Thread(() =&gt; { action(min, max, name); }); worker.Name = name; threads.Add(worker); } } public void StartWorking() { foreach (Thread thread in threads) { thread.Start(); } foreach (Thread thread in threads) { thread.Join(); } } } </code></pre> <p>Here is the program:</p> <pre><code>Stopwatch watch = new Stopwatch(); watch.Start(); int path = 1; List&lt;int&gt; numbers = new List&lt;int&gt;(Enumerable.Range(0, 10000)); if (path == 1) { Parallel.ForEach(numbers, x =&gt; { Console.WriteLine(x); Thread.Sleep(1); }); } else { ThreadFactory workers = new ThreadFactory(10, numbers.Count, (min, max, text) =&gt; { for (int i = min; i &lt;= max; i++) { Console.WriteLine(numbers[i]); Thread.Sleep(1); } }); workers.StartWorking(); } watch.Stop(); Console.WriteLine(watch.Elapsed.TotalSeconds.ToString()); Console.ReadLine(); </code></pre> <p><strong>Update:</strong></p> <p>Taking Locking into consideration: I tried the following snippet. Again the same results, Parallel seems to finish much slower.</p> <p>path = 1; cieling = 10000000;</p> <pre><code> List&lt;int&gt; numbers = new List&lt;int&gt;(); if (path == 1) { Parallel.For(0, cieling, x =&gt; { lock (numbers) { numbers.Add(x); } }); } else { ThreadFactory workers = new ThreadFactory(10, cieling, (min, max, text) =&gt; { for (int i = min; i &lt;= max; i++) { lock (numbers) { numbers.Add(i); } } }); workers.StartWorking(); } </code></pre> <p><strong>Update 2:</strong> Just a quick update that my machine has Quad Core Processor. So Parallel have 4 cores available.</p>
0
1,577
Error: 1265 SQLSTATE: 01000 (WARN_DATA_TRUNCATED)
<p>First of all, sorry if I wrote some nosense, but I don't usually write in English, and it's a little hard to me. Second, I'm a newbie as programmer, so it's probably my question is too easy and obvius (I promise I tried to find the answer before ask here).</p> <p>Well, I want to practice with php and mysql, so I want to make a bbdd and a GUI to control it. Here are the code where I have the problem:</p> <p>MySql (v5.6.12):</p> <pre><code>CREATE TABLE IF NOT EXISTS `personaje` ( `id_personaje` int(3) NOT NULL AUTO_INCREMENT, `nombre` varchar(30) NOT NULL, `servidor` varchar(25) NOT NULL, `nivel` int(3) NOT NULL, `faccion` varchar(10) NOT NULL, `clase` varchar(25) NOT NULL, `raza` char(30) NOT NULL, `profesion1` varchar(20) NOT NULL, `nivel1` int(4) NOT NULL, `profesion2` varchar(20) NOT NULL, `nivel2` int(4) NOT NULL, `nivel_coc` int(4) NOT NULL, `nivel_pes` int(4) NOT NULL, `nivel_arqu` int(4) NOT NULL, `nivel_prim` int(4) NOT NULL, PRIMARY KEY (`id_personaje`), UNIQUE KEY `raza` (`raza`), UNIQUE KEY `clase` (`clase`), UNIQUE KEY `prof1` (`profesion1`), UNIQUE KEY `prof2` (`profesion2`), UNIQUE KEY `faccion` (`faccion`) ) ENGINE=InnoDB </code></pre> <p>PHP(v5.4.12):</p> <pre><code> &lt;?php //Recoger los datos que llegan $nombre = $_POST['nombreChar']; $raza = $_POST['razaChar']; $clase = $_POST['claseChar']; $servidor = $_POST['servidorChar']; $faccion = $_POST['faccionChar']; $nivel = $_POST['nivelChar']; settype($nivel,"int"); $prof1 = $_POST['prof1Char']; $lvlpr1 = $_POST['lvlpr1Char']; $prof2 = $_POST['prof2Char']; $lvlpr2 = $_POST['lvlpr2Char']; $nivel_coc = $_POST['nivel_cocChar']; $nivel_arqu = $_POST['nivel_arquChar']; $nivel_pes = $_POST['nivel_pesChar']; $nivel_prim = $_POST['nivel_primChar']; $muestra = gettype($nivel); //Conectandonos con la base de datos $conexion = mysql_connect(/* ... */); mysql_select_db (/* ... */, $conexion) OR die ("No se puede conectar"); //Comprobar que no haya otro personaje repetido /* $Consulta_per = "SELECT nombre, servidor FROM personaje WHERE nombre = '".$nombre."' &amp;&amp; servidor = '".$servidor."'"; $busqueda = mysql_query($Consulta_per,$conexion) or die ("Error en busqueda " . mysql_error()); if (!$busqueda) */ $res = mysql_query("INSERT INTO personaje (nombre, servidor, nivel, faccion, clase, raza, profesion1, nivel1, profesion2, nivel2, nivel_coc, nivel_pes, nivel_arqu, nivel_prim) VALUE ('$nombre','$servidor', '$nivel,','$faccion','$clase','$raza','$prof1','$lvlpr1', '$prof2','$lvlpr2','$nivel_coc','$nivel_pes','$nivel_arqu', '$nivel_prim')",$conexion) or die ("No se pudo insertar " . mysql_error() ." ". $nivel . $muestra );// this line show the error echo "Insertado con exito"; mysql_close($conexion); ?&gt; </code></pre> <p>The form that comes is:</p> <pre><code> &lt;FORM method="POST" action="crear-personaje.php"&gt; Nombre &lt;INPUT type="text" name="nombreChar" id="nombreChar" value="Nombre"&gt;&lt;/br&gt; Raza &lt;INPUT type="text" name="razaChar" id="razaChar" value="Raza"&gt;&lt;/br&gt; Facción &lt;INPUT type="text" name="faccionChar" id="faccionChar" value="Facción"&gt;&lt;/br&gt; Clase &lt;INPUT type="text" name="claseChar" id="claseChar" value="Clase"&gt;&lt;/br&gt; Servidor &lt;INPUT type="text" name="servidorChar" id="servidorChar" value="Servidor"&gt;&lt;/br&gt; Nivel &lt;INPUT type="number" name="nivelChar" id="nivelChar" value="1"&gt;&lt;/br&gt; Profesión 1 &lt;INPUT type="text" name="prof1Char" id="prof1Char" value="Profesion1"&gt;&lt;/br&gt; Nivel de profesión 1 &lt;INPUT type="text" name="lvlpr1Char" id="lvlpr1Char" value="1"&gt;&lt;/br&gt; Profesion 2 &lt;INPUT type="text" name="prof2Char" id="prof2Char" value="Profesion2"&gt;&lt;/br&gt; Nivel de profesion 2 &lt;INPUT type="text" name="lvlpr2Char" id="lvlpr2Char" value="1"&gt;&lt;/br&gt; Nivel cocina&lt;INPUT type="text" name="nivel_cocChar" id="nivel_cocChar" value="1"&gt;&lt;/br&gt; Nivel pesca&lt;INPUT type="text" name="nivel_pesChar" id="nivel_pesChar" value="1"&gt;&lt;/br&gt; Nivel primeros auxilios&lt;INPUT type="text" name="nivel_primChar" id="nivel_primChar" value="1"&gt;&lt;/br&gt; Nivel arqueología&lt;INPUT type="text" name="nivel_arquChar" id="nivel_arquChar" value="1"&gt;&lt;/br&gt; &lt;INPUT type="submit" NAME="enviar" VALUE="Dar de alta!" id="enviar"&gt; &lt;/FORM&gt; </code></pre> <p>Apache version 2.4.4</p> <p>Everything must be ok, but... no. When I tried to insert a integer value (like 87 or 1) in the "nivel" field, mysql give me the next error:</p> <p><code>"No se pudo insertar Data truncated for column 'nivel' at row 1 1integer"</code>, like the comment I wrote in the code.</p> <p>("No se pudo insertar" means "Cannot insert").</p> <p>As you can see, I forced the variable $nivel as integer, and PHP recognice correctly (that's the reason I put $nivel and $muestra in the die sentence). I tried change the type "nivel" variable from int (3) to Varchar (3) in MySql, and let me introduce the character, but... I preffer use the type int (the level of a character ever is a integer, obviusly).</p> <p>Anyone know why MySql give me this error? What can I do to solve this? </p> <p>Thanks for help!</p>
0
2,503
How to show validation message below each textbox using jQuery?
<p>I am trying to make a login form in which I have email address and password as the textbox. I have done the validation on the email address part so that it should have proper email address and also on the empty check both for email address and password text box.</p> <p>Here is my <a href="https://jsfiddle.net/aoksoh69/5/" rel="nofollow noreferrer">jsfiddle</a>.</p> <p>As of now, I have added an alert box saying, <code>Invalid</code> if email address and password textbox is empty. Instead of that, I would like to show a simple message just below each text box saying , please enter your email address or password if they are empty?</p> <p>Just like it has been done here on <a href="https://www.sitepoint.com/basic-jquery-form-validation-tutorial/" rel="nofollow noreferrer">sitepoint blog</a>.</p> <p>Is this possible to do in my current HTML form?</p> <p><strong>Update:-</strong></p> <pre><code>&lt;body&gt; &lt;div id=&quot;login&quot;&gt; &lt;h2&gt; &lt;span class=&quot;fontawesome-lock&quot;&gt;&lt;/span&gt;Sign In &lt;/h2&gt; &lt;form action=&quot;login&quot; method=&quot;POST&quot;&gt; &lt;fieldset&gt; &lt;p&gt; &lt;label for=&quot;email&quot;&gt;E-mail address&lt;/label&gt; &lt;/p&gt; &lt;p&gt; &lt;input type=&quot;email&quot; id=&quot;email&quot; name=&quot;email&quot;&gt; &lt;/p&gt; &lt;p&gt; &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt; &lt;/p&gt; &lt;p&gt; &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot;&gt; &lt;/p&gt; &lt;p&gt; &lt;input type=&quot;submit&quot; value=&quot;Sign In&quot;&gt; &lt;/p&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- end login --&gt; &lt;/body&gt; </code></pre> <p>And my JS -</p> <pre><code>&lt;script&gt; $(document).ready(function() { $('form').on('submit', function (e) { e.preventDefault(); if (!$('#email').val()) { if ($(&quot;#email&quot;).parent().next(&quot;.validation&quot;).length == 0) // only add if not added { $(&quot;#email&quot;).parent().after(&quot;&lt;div class='validation' style='color:red;margin-bottom: 20px;'&gt;Please enter email address&lt;/div&gt;&quot;); } } else { $(&quot;#email&quot;).parent().next(&quot;.validation&quot;).remove(); // remove it } if (!$('#password').val()) { if ($(&quot;#password&quot;).parent().next(&quot;.validation&quot;).length == 0) // only add if not added { $(&quot;#password&quot;).parent().after(&quot;&lt;div class='validation' style='color:red;margin-bottom: 20px;'&gt;Please enter password&lt;/div&gt;&quot;); } } else { $(&quot;#password&quot;).parent().next(&quot;.validation&quot;).remove(); // remove it } }); }); &lt;/script&gt; </code></pre> <p>I am working with JSP and Servlets so as soon as I click Sign In button, it was taking me to another page with valid email and password earlier but now nothing is happening after I click Sign In button with valid email and password.</p> <p>Any thoughts what could be wrong?</p>
0
1,734
Generic Linked List of Objects (Java)
<p>I'm pretty new to Java, with this being my second class (in College) using it. Towards the beginning of the semester, I made a simple class representing Zombies that holds their age, type, and name. Later on, I made a linked list of integers. Now, I need to make a generic linked list that can hold these 'Zombies'. I also have to make a menu that allows me to add, remove, count, and display 'Zombies'. I've been staring at this for hours, going through my book, and looking online for the answer to my problem. I can add and display these 'Zombies', but counting them in the list and trying to remove them simply has it tell me there's none with the parameters I entered. In other words, there might be a problem with how I compare the 'Zombies'. Here's my code. I understand it's a good 300 lines of code to look through... but i'm out of ideas.</p> <p>Zombie.java</p> <pre><code>public class Zombie { private String zAge; private String zType; private String zName; public Zombie(String zA, String zT, String zN) { zAge = zA; zType = zT; zName = zN; } public void setZAge(String zA) { zAge = zA; } public void setZType(String zT) { zType = zT; } public void setZName(String zN) { zName = zN; } public String getZAge() { return zAge; } public String getZType() { return zType; } public String getZName() { return zName; } public boolean equals(Zombie zomb) { if(zomb.getZAge() == zAge &amp;&amp; zomb.getZType() == zType &amp;&amp; zomb.getZName() == zName) return true; else return false; } } </code></pre> <p>LinkedBag.java</p> <pre><code>public class LinkedBag&lt;E&gt; { //Head node and number of nodes in bag private Node&lt;E&gt; head; private int manyNodes; //Constructor public LinkedBag() { head = null; manyNodes = 0; } //Returns the number of nodes in the bag public int getSize() { return manyNodes; } //Returns the node that is at the head of the linked list public Node&lt;E&gt; getListStart() { return head; } //Adds a node to the beginning of the list public void add(E element) { head = new Node&lt;E&gt;(element,head); //Creates a new node pointing to the head and sets the head of the linked bag to the new Node manyNodes++; //Increments Node counter } //Counts the number of times Node [target] occurs within the bag public int countOccurences(E target) { int count = 0; //Initializes incrementable counter if(head==null) //Checks if bag is empty and returns null if bag is empty return 0; if(head.getData().equals(target)) //Checks if the head of the linked list is [target] count++; //Increments counter Node&lt;E&gt; cursor = head; //Sets temporary Node [cursor] to the same value and pointer as head while(cursor.getLink() != null) //Loops until the next Node contains no value { if(cursor.getLink().getData().equals(target)) //Checks if the value of the next Node is [target] count++; //Increments counter cursor=cursor.getLink(); //Cursor continues down linked list } return count; //Returns incremented int [count], number of occurences of [target] } //Checks if Node [target] exists within the bag public boolean exists(E target) { if(head.getData().equals(target)) //Checks if the head of the linked list is [target] return true; Node&lt;E&gt; cursor = head; //Sets temporary Node [cursor] to the same value and pointer as head while(cursor.getLink() != null) //Loops until the next Node contains no value { if(cursor.getData().equals(target)) //Checks if current Node is [target] and returns true if true return true; cursor=cursor.getLink(); //Cursor continues down linked list } return false; //Returns false if cursor goes through entire linked list and [target] isn't found } //Checks if Node [target] exists within the bag and removes the first occurence of it public boolean remove(E target) { if(head==null) //Returns false if bag is empty return false; if(head.getData().equals(target)) //If the head Node's data is [target] { head = head.getLink(); //Make the next Node the head manyNodes--; //Decrements Node counter return true; //Returns true, found [target] } Node&lt;E&gt; cursor = head; //Sets temporary Node [cursor] to the same value and pointer as head while(cursor.getLink() != null) //Loops until the next Node contains no value { cursor = cursor.getLink(); //Cursor continues down linked list if(cursor.getLink().getData().equals(target)) //If the next node's data is [target] { cursor.setLink(cursor.getLink().getLink()); //Sets current Node's link to the next Node's link, by passing the next Node manyNodes--; //Decrements Node counter return true; //Returns true, found [target] } } return false; //Returns false, [target] not found } } </code></pre> <p>Node.java</p> <pre><code>public class Node&lt;E&gt; { private E data; private Node&lt;E&gt; link; public Node(E initialData, Node&lt;E&gt; initialLink) { data = initialData; link = initialLink; } public E getData() { return data; } public Node&lt;E&gt; getLink () { return link; } public void setData(E element) { data = element; } public void setLink(Node&lt;E&gt; newLink) { link = newLink; } } </code></pre> <p>And this is the menu file that the user interacts with ZombiesProj2.java</p> <pre><code>import java.util.Scanner; public class ZombiesProj2 { public static void main(String[] args) throws InterruptedException { LinkedBag&lt;Zombie&gt; zBag = new LinkedBag&lt;Zombie&gt;(); //Linked bag to hold Zombie Objects String choice = ""; Scanner input = new Scanner(System.in); while(!choice.equalsIgnoreCase("x")) { //Menu System.out.println("\nSac de Zombi\n"); System.out.println("S - Display size of bag"); System.out.println("A - Add 'Zombie' to bag"); System.out.println("R - Remove 'Zombie' from bag"); System.out.println("F - Find 'Zombie' in bag"); System.out.println("D - Display contents of bag"); System.out.println("X - Exit"); System.out.print("Enter Selection: "); //Input and Output choice = input.nextLine(); if(choice.equalsIgnoreCase("s")) { System.out.println("\nSize = " + zBag.getSize() + "\n"); } else if(choice.equalsIgnoreCase("a")) //adds zombie { String zAge; String zType; String zName; System.out.print("How many years has this zombie ROAMED THE EARTH: "); zAge = input.nextLine(); System.out.print("What type of zombie is it: "); zType = input.nextLine(); System.out.print("What would you like to name this zombie: "); zName = input.nextLine(); Zombie newZomb = new Zombie(zAge,zType,zName); zBag.add(newZomb); } else if(choice.equalsIgnoreCase("r")) //removes zombie { String zAge; String zType; String zName; System.out.print("How many years has this zombie ROAMED THE EARTH: "); zAge = input.nextLine(); System.out.print("What type of zombie is it: "); zType = input.nextLine(); System.out.print("What is the name of the zombie: "); zName = input.nextLine(); Zombie rZomb = new Zombie(zAge,zType,zName); zBag.remove(rZomb); } else if(choice.equalsIgnoreCase("f")) //counts number of matching zombies { String zAge; String zType; String zName; System.out.print("How many years has this zombie ROAMED THE EARTH: "); zAge = input.nextLine(); System.out.print("What type of zombie is it: "); zType = input.nextLine(); System.out.print("What is the name of the zombie: "); zName = input.nextLine(); Zombie fZomb = new Zombie(zAge,zType,zName); System.out.println("The " + zAge + " year old zombie type " + zType + " named " + zName + " occurs " + zBag.countOccurences(fZomb)+ " time(s)"); } else if(choice.equalsIgnoreCase("d")) //displays entire zombie 'bag' { Node cursor = zBag.getListStart(); Zombie dZomb; while(cursor !=null) { dZomb = (Zombie)cursor.getData(); System.out.print("[Zombie "+dZomb.getZAge()+" "+dZomb.getZType()+" "+dZomb.getZName()+"],"); cursor = cursor.getLink(); } } else if(!choice.equalsIgnoreCase("x")) { System.out.println("Error: Invalid Entry"); } } } } </code></pre> <p>Updated equals and hashCode</p> <pre><code>public boolean equals(Object obj) { if(obj==null) return false; if(obj==this) return true; if(obj.getClass() != getClass()) return false; Zombie zomb = (Zombie)obj; if(zomb.getZAge().equals(zAge) &amp;&amp; zomb.getZType().equals(zType) &amp;&amp; zomb.getZName().equals(zName)) return true; else return false; } public int hashCode() { return 0; } </code></pre>
0
4,104
ErrorHandling in Spring Security for @PreAuthorize AccessDeniedException returns 500 rather then 401
<p>Dear all I like to customize the error handling in a Spring 4 Rest application so it should return a HTTP Code 401 rather a Server Error 500 in case the check in @PreAuthorize annotation in my controller fails.</p> <p>I have an own AuthenticationEntryPoint and AuthenticationFailureHandler registered which its commence / error handling methods returns a 401. This works fine for my JWT authentication but in case of a failed @PreAuthorize check with "AccessDeniedException" these error methods get never called and spring returns a server error 500. </p> <p>How can I customize that? Looks like I missed something? Thanks for any hints in advance.</p> <p>Here my AuthenticationEntryPoint class:</p> <pre><code>@Component public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException, ServletException { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getOutputStream().println("{ \"error\": \"" + authException.getMessage() + "\" }"); } } </code></pre> <p>Here my AuthenticationFailureHandler:</p> <pre><code>public class JWTAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.sendError(401, (new StringBuilder()).append("Authentication Failed: ").append(exception.getMessage()).toString()); } } </code></pre> <p>Here my spring security configuration</p> <pre><code>&lt;security:global-method-security pre-post-annotations="enabled"/&gt; &lt;security:http pattern="/api/**" entry-point-ref="restAuthenticationEntryPoint" &gt; &lt;security:csrf disabled="true"/&gt; &lt;security:intercept-url pattern="/api/**" access="isAuthenticated()" /&gt; &lt;security:custom-filter ref="authenticationTokenProcessingFilter" before="FORM_LOGIN_FILTER" /&gt; &lt;/security:http&gt; &lt;security:authentication-manager alias="authenticationManager"&gt; &lt;security:authentication-provider ref="jwtAuthenticationProvider" /&gt; &lt;/security:authentication-manager&gt; &lt;bean id="restAuthenticationEntryPoint" class="ch.megloff.common.webservice.jwt.RestAuthenticationEntryPoint"/&gt; &lt;bean id="authenticationTokenProcessingFilter" class="ch.megloff.common.webservice.jwt.JWTAuthenticationFilter"&gt; &lt;constructor-arg type="java.lang.String"&gt;&lt;value&gt;/api/**&lt;/value&gt;&lt;/constructor-arg&gt; &lt;property name="authenticationManager" ref="authenticationManager"&gt;&lt;/property&gt; &lt;property name="authenticationFailureHandler" ref="jwtAuthenticationFailureHandler" /&gt; &lt;/bean&gt; &lt;bean id="jwtAuthenticationProvider" class="ch.megloff.common.webservice.jwt.JWTAuthenticationProvider" /&gt; &lt;bean id="jwtAuthenticationFailureHandler" class="ch.megloff.common.webservice.jwt.JWTAuthenticationFailureHandler" /&gt; </code></pre> <p>Here my rest controller class</p> <pre><code>@RestController public class UserController { @Autowired private UserService userService; @PreAuthorize("hasAuthority('admin')") @RequestMapping(value = "/api/user/", method = RequestMethod.GET) public ResponseEntity&lt;List&lt;User&gt;&gt; listAllUsers(HttpServletRequest request, HttpServletResponse response) { System.out.println("Fetching all Users"); List&lt;User&gt; users = userService.getUsers(); if(users.isEmpty()){ return new ResponseEntity&lt;List&lt;User&gt;&gt;(HttpStatus.NO_CONTENT); } return new ResponseEntity&lt;List&lt;User&gt;&gt;(users, HttpStatus.OK); } </code></pre> <p>Here the stack trace from the server when @PreAuthorize check in the annotation fails:</p> <pre><code>SEVERE: Servlet.service() for servlet [myusers] in context with path [/JWTAuthenticationExample] threw exception [Request processing failed; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied] with root cause org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:65) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at ch.megloff.myusers.UserController$$EnhancerBySpringCGLIB$$635caa86.listAllUsers(&lt;generated&gt;) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318) at org.springframework.security.web.firewall.RequestWrapper$FirewalledRequestAwareRequestDispatcher.forward(RequestWrapper.java:154) at ch.megloff.common.webservice.jwt.JWTAuthenticationSuccessHandler.onAuthenticationSuccess(JWTAuthenticationSuccessHandler.java:23) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.successfulAuthentication(AbstractAuthenticationProcessingFilter.java:326) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:240) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)` </code></pre>
0
3,394
Use of undeclared type in Swift project
<p>I am trying to import <a href="https://github.com/AndrewShmig/Vkontakte-iOS-SDK-LV/tree/master/Project/Vkontakte-iOS-SDK-LV" rel="nofollow noreferrer">this library</a> in my Swift project. I am doing all step by step from <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_74" rel="nofollow noreferrer">this document</a> and <a href="https://stackoverflow.com/a/24477751/523630">this answer</a>, but nothing works.</p> <p>Here is my <a href="https://i.stack.imgur.com/M8Sq0.png" rel="nofollow noreferrer">screenshot</a>: <img src="https://i.stack.imgur.com/M8Sq0.png" alt="enter image description here"></p> <p>Here is my Bridging-Header.h:</p> <pre><code>// // Use this file to import your target's public headers that you would like to expose to Swift. // #import &lt;UIKit/UIKit.h&gt; #import "VKUser.h" #import "VKAccessToken.h" #import "VKCache.h" #import "VKStorage.h" #import "VKStorageItem.h" #import "VKRequestManager.h" #import "VKRequest.h" #import "VKConnector.h" #import "VKMethods.h" #import "NSData+toBase64.h" #import "NSString+Utilities.h" </code></pre> <p>The important thing is that I have VKConnector class and VKConnectorDelegate protocol in one file. Maybe thats the problem?</p> <pre><code>// // Copyright (c) 2013 Andrew Shmig // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #import &lt;Foundation/Foundation.h&gt; #import &lt;UIKit/UIKit.h&gt; #import "VKMethods.h" #import "VKAccessToken.h" #import "VKStorage.h" #import "NSString+Utilities.h" #import "VKStorageItem.h" @class VKConnector; static NSString *const kVKErrorDomain = @"kVkontakteErrorDomain"; typedef enum { kVKApplicationWasDeletedErrorCode } kVkontakteErrorCode; /** Protocol incapsulates methods that are triggered during user authorization process or access token status changes. */ @protocol VKConnectorDelegate &lt;NSObject&gt; @optional /** @name Show/hide web view */ /** Method is called when user needs to perform some action (enter login and password, authorize your application etc) @param connector VKConnector instance that sends notifications @param webView UIWebView that displays authorization page */ - (void)VKConnector:(VKConnector *)connector willShowWebView:(UIWebView *)webView; /** Method is called when UIWebView should be hidden, this method is called after user has entered login+password or has authorized an application (or pressed cancel button etc). @param connector VKConnector instance that sends notifications @param webView UIWebView that displays authorization page and needs to be hidden */ - (void)VKConnector:(VKConnector *)connector willHideWebView:(UIWebView *)webView; /** @name UIWebView started/finished loading a frame */ /** Method is called when UIWebView starts loading a frame @param connector VKConnector instance that sends notifications @param webView UIWebView that displays authorization page */ - (void)VKConnector:(VKConnector *)connector webViewDidStartLoad:(UIWebView *)webView; /** Method is called when UIWebView finishes loading a frame @param connector VKConnector instance that sends notifications @param webView UIWebView that displays authorization page */ - (void) VKConnector:(VKConnector *)connector webViewDidFinishLoad:(UIWebView *)webView; /** @name Access token */ /** Method is called when access token is successfully updated @param connector VKConnector instance that sends notifications @param accessToken updated access token */ - (void) VKConnector:(VKConnector *)connector accessTokenRenewalSucceeded:(VKAccessToken *)accessToken; /** Method is called when access token failed to be updated. The main reason could be that user denied/canceled to authorize your application. @param connector VKConnector instance that sends notifications @param accessToken access token (equals to nil) */ - (void) VKConnector:(VKConnector *)connector accessTokenRenewalFailed:(VKAccessToken *)accessToken; /** @name Connection &amp; Parsing */ /** Method is called when connection error occurred during authorization process. @param connector VKConnector instance that sends notifications @param error error description */ - (void)VKConnector:(VKConnector *)connector connectionError:(NSError *)error; /** Method is called if VK application was deleted. @param connector VKConnector instance that sends notifications @param error error description */ - (void) VKConnector:(VKConnector *)connector applicationWasDeleted:(NSError *)error; @end /** The main purpose of this class is to process user authorization and obtain access token which then will be used to perform requests from behalf of current user. Example: [[VKConnector sharedInstance] startWithAppID:@"12345567" permissions:@[@"wall"] webView:webView delegate:self]; */ @interface VKConnector : NSObject &lt;UIWebViewDelegate&gt; /** @name Properties */ /** Delegate */ @property (nonatomic, weak, readonly) id &lt;VKConnectorDelegate&gt; delegate; /** Application's unique identifier */ @property (nonatomic, strong, readonly) NSString *appID; /** Permissions */ @property (nonatomic, strong, readonly) NSArray *permissions; /** @name Class methods */ /** Returns shared instances of VKConnector class. */ + (id)sharedInstance; /** @name User authorization */ /** Starts user authorization process. @param appID application's unique identifier @param permissions array of permissions (wall, friends, audio, video etc) @param webView UIWebView which will be used to display VK authorization page @param delegate delegate which will receive notifications */ - (void)startWithAppID:(NSString *)appID permissons:(NSArray *)permissions webView:(UIWebView *)webView delegate:(id &lt;VKConnectorDelegate&gt;)delegate; /** @name Cookies */ /** Removes all cookies which were obtained after user has authorized VK application. This method is used to log out current user. */ - (void)clearCookies; @end </code></pre> <p>I have tried to split VKConnector header file into two - VKConnector class and VKConnectorDelegate, but that didn't work.</p> <p>What am I doing wrong? </p>
0
2,220
NIO load file in an unit test from src/test/resources
<p><strong>The Problem</strong></p> <p>I'd like to write a data import in java with java7s NIO. The user enters the path of a file as a String and the programm try to open it by using Paths. When it want to read its DosFileAttributes an java.nio.file.NoSuchFileException: file.txt occures.</p> <p><strong>What i've found</strong></p> <p>The only answers i've found till yet is to use an resource Stream - but this seams not practicable, because the file to be loaded is provided by the user and should not be part of the jar. Or did i missunderstood it? <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29</a></p> <p><strong>What i've got</strong></p> <p>The Setup:</p> <ul> <li>Maven 3</li> <li>Java7</li> <li>TestNG</li> <li>Spring</li> </ul> <p>Project Structure:</p> <ul> <li>src/main/java - the classes</li> <li>src/test/java - the testcases</li> <li>src/test/resources - perhaps file.txt ? actual it is there</li> </ul> <p>The source that loads the file:</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.DosFileAttributes; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; @Component( "fileLoader" ) public class BufferdFileLoader implements FileLoader { @Override public List&lt;String&gt; loadFile( String path ) throws IOException { if ( path == null || path.length() == 0 ) { throw new IllegalArgumentException( "path should not be null" ); } Path file = Paths.get( path ); // here the Exception is thrown DosFileAttributes attrs = Files.readAttributes( file, DosFileAttributes.class ); if ( !attrs.isRegularFile() ) { throw new IOException( "could not read file, invalid path" ); } List&lt;String&gt; result = new ArrayList&lt;String&gt;(); try (BufferedReader reader = Files.newBufferedReader( file, Charset.forName( "UTF-8" ) )) { String line = null; while ( ( line = reader.readLine() ) != null ) { result.add( line ); } } return result; } } </code></pre> <p>And the Test case is as simple:</p> <pre><code>import java.io.IOException; import java.util.List; import javax.inject.Inject; import lombok.Setter; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; /** * Class under test {@link BufferdFileLoader} * */ @ContextConfiguration public class BufferdFileLoaderTest extends AbstractTestNGSpringContextTests { /** * Class under test */ @Inject @Setter private BufferdFileLoader bufferdFileLoader; /** * Method under test {@link BufferdFileLoader#loadFile(String)} * * @throws IOException */ @Test( groups = { "integration" }, enabled = true ) public void testImportFeedsFromXMLFileWitEmptyXml() throws IOException { String filename = "empty-example-takeout.xml"; List&lt;String&gt; list = this.bufferdFileLoader.loadFile( filename ); Assert.assertEquals( list.size(), 0 ); } } </code></pre> <p><strong>So my question is</strong></p> <p>How to load a file using NIO so it is testable with maven and also works in production environment?</p>
0
1,432
Array merge on multidimensional array
<p>Either I'm blind or I can't find this problem anywhere here on SO. Yesterday I had a problem with merging arrays, which I could fix with the help of SO. Today I have, again, a problem with merging arrays, but this time it's with multidimensional Arrays.</p> <p>I have an array <code>$usergroup['groups']</code> and an array <code>$usergroup['lang']</code></p> <p><code>$usergroup['groups']</code> looks like this:</p> <pre><code>Array ( [0] =&gt; Usergroup_Model Object ( [id] =&gt; 1 [deleted] =&gt; 0 ) [1] =&gt; Usergroup_Model Object ( [id] =&gt; 2 [deleted] =&gt; 0 ) [2] =&gt; Usergroup_Model Object ( [id] =&gt; 3 [deleted] =&gt; 0 ) ) </code></pre> <p>And <code>$usergroup['lang']</code> looks like this:</p> <pre><code>Array ( [0] =&gt; Usergroup_Model Object ( [id] =&gt; [id_usergroup] =&gt; 1 [name] =&gt; Administratoren [id_lang] =&gt; 1 ) [1] =&gt; Usergroup_Model Object ( [id] =&gt; [id_usergroup] =&gt; 2 [name] =&gt; Benutzer [id_lang] =&gt; 1 ) [2] =&gt; Usergroup_Model Object ( [id] =&gt; [id_usergroup] =&gt; 3 [name] =&gt; Gäste [id_lang] =&gt; 1 ) ) </code></pre> <p>I want my merged array to look like this:</p> <pre><code>Array ( [0] =&gt; Usergroup_Model Object ( [id] =&gt; 1 [id_usergroup] =&gt; 1 [name] =&gt; Administratoren [id_lang] =&gt; 1 [deleted] =&gt; 0 ) [1] =&gt; Usergroup_Model Object ( [id] =&gt; 2 [id_usergroup] =&gt; 2 [name] =&gt; Benutzer [id_lang] =&gt; 1 [deleted] =&gt; 0 ) [2] =&gt; Usergroup_Model Object ( [id] =&gt; 3 [id_usergroup] =&gt; 3 [name] =&gt; Gäste [id_lang] =&gt; 1 [deleted] =&gt; 0 ) ) </code></pre> <p><a href="http://www.whathaveyoutried.com" rel="nofollow">What have I tried?</a></p> <p>I've tried several merging functions (<code>array_merge()</code> and <code>array_merge_recursive()</code>) of PHP, the closest result I got was, that the second Array (<code>['lang']</code>) overwrote the first Array (<code>['groups']</code>). To fix that, I tried to remove the empty values on the <code>lang</code> Array (which is always <code>id</code>). But that does not fix it. The code - at the moment - looks like this:</p> <pre><code>public static function getAll() { $usergroup['groups'] = self::find(); $usergroup['lang'] = self::findInTable(array( 'id_lang' =&gt; Language_Model::getDefaultLanguage() ), self::dbTranslationTable); foreach ($usergroup as $ug) { $ug = array_filter($ug, function($val) { return $val != ''; }); } return array_merge($ug); } </code></pre> <p>The array_merge() on the return command doesn't seem to do anything at all, so I'm probably not gathering the data correctly or I mess something up with the Arrays (forgetting to add [], or I don't know...). I kinda miss the forest for the trees here.</p> <p>Any suggestions in which direction I could go?</p> <p><strong>Edit:</strong> With the code provided by Pé de Leão I was able to solve the problem. My function now looks like this:</p> <pre><code>public static function getAll() { $usergroup['groups'] = self::find(); $usergroup['lang'] = self::findInTable(array( 'id_lang' =&gt; Language_Model::getDefaultLanguage() ), self::dbTranslationTable); $out = array(); foreach ($usergroup['groups'] as $key =&gt; $value) { $out[] = (object) array_merge((array) $usergroup['lang'][$key], (array) $value); } return $out; } </code></pre> <p>And the result is exactly how I wanted it!</p>
0
1,869
Where to put default-servlet-handler in Spring MVC configuration
<p>In my <code>web.xml</code>, the default servlet mapping, i.e. <code>/</code>, is mapped to Spring dispatcher. In my Spring dispatcher configuration, I have <code>DefaultAnnotationHandlerMapping</code>, <code>ControllerClassNameHandlerMapping</code> and <code>AnnotationMethodHandlerAdapter</code> which allows me to map url to controllers either by its class name or its <code>@Requestmapping</code> annotation. However, there are some static resources under the web root which I also want spring dispatcher to serve using default servlet. According to <a href="http://static.springsource.org/spring/docs/3.0.5.RELEASE/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-default-servlet-handler" rel="noreferrer">Spring documentation</a>, this can be done using <code>&lt;mvc:default-servlet-handler/&gt;</code> tag.</p> <p>In the configuration below, there are 4 candidate locations that I marked which are possible to insert this tag. Inserting the tag in different location causes the dispatcher to behave differently as following :</p> <p><strong>Case 1</strong> : If I insert it at location 1, the dispatcher will no longer be able to handle mapping by the @RequestMapping and controller class name but it will be serving the static content normally.</p> <p><strong>Cas 2, 3</strong> : It will be able to handle mapping by the @RequestMapping and controller class name as well as serving the static content if other mapping cannot be done successfully.</p> <p><del><strong>Case 4</strong> : It will not be able to serve the static contents.</del> <em>Removal Note : This was a bug when implementing a controller which has a method mapped to <code>/**</code> but does not have explicit request mapping on the controller class name.</em></p> <p>Therefore, <strong>Case 2</strong> and <strong>3</strong> are desirable .According to Spring documentation, this tag configures a handler which precedence order is given to lowest so why the position matters? and Which is the best position to put this tag?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&gt; &lt;context:annotation-config/&gt; &lt;context:component-scan base-package="webapp.controller"/&gt; &lt;!-- Location 1 --&gt; &lt;!-- Enable annotation-based controllers using @Controller annotations --&gt; &lt;bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/&gt; &lt;!-- Location 2 --&gt; &lt;bean id="controllerClassNameHandlerMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/&gt; &lt;!-- Location 3 --&gt; &lt;bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&gt; &lt;!-- Location 4 --&gt; &lt;mvc:default-servlet-handler/&gt; &lt;!-- All views are JSPs loaded from /WEB-INF/jsp --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/&gt; &lt;property name="prefix" value="/WEB-INF/jsp/"/&gt; &lt;property name="suffix" value=".jsp"/&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
0
1,231
Unable to use webpack dynamic import because of static publicPath
<p>I love the ability to dynamically import a chunk using the <code>import</code> command in webpack 3. Unfortunately it seems as if it can only be used if the resources are in a rather static directory configuration on the server.</p> <p>In my environment the html pages generated dynamically in the backend (let's say <code>http:/localhost/app</code>). All other resources (js, css, images, etc.) are in a different directory (let's say <code>http:/localhost/res</code>) but additionally <code>res</code> is not static but can rather change dynamically in the backend.</p> <p>As long as I do not use any dynamic imports everything works as expected but when trying to dynamically load any chunks this fails because webpack by default expects the chunks to be in <code>http:/localhost/app</code> and I cannot use <code>publicPath</code> because the url where the resources are is dynamic.</p> <p>Is there any way to (runtime) configure webpack into loading the resources relative to the path where the current resource is located. If for example the chunk <code>page1.js</code> located in <code>http:/localhost/resA</code> dynamically loads the chunk <code>sub1.js</code> he should look for it in <code>http:/localhost/resA</code> instead of <code>http:/localhost/app</code>.</p> <p><strong>generated html will be available at <code>http:/localhost/app/page1</code>:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="http:/localhost/resA/page1.bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>file <code>src/page1.js</code> will be available as <code>http:/localhost/resA/page1.bundle.js</code>:</strong></p> <pre><code>import(/* webpackChunkName: "sub1" */ './sub1').then(({MyClass}) =&gt; {/*...*/}); </code></pre> <p><strong>file <code>src/sub1</code> will be available as <code>http:/localhost/resA/sub1.bundle.js</code>:</strong></p> <pre><code>export class MyClass {}; </code></pre> <p><strong>file `webpack.config.js':</strong></p> <pre><code>const path = require('path'); const webpack = require('webpack'); function config(env) { return { entry: { index: ['./src/page1.js'] }, output: { filename: '[name].bundle.js', chunkFilename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: './' }, module: { rules: [ { test: /\.js$/i, include: /src/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, devtool: 'source-map' }; } module.exports = config; </code></pre>
0
1,171
How to filter and map array of documents in MongoDB query?
<p>So I've got these documents in my people collection:</p> <pre><code>{ "_id" : ObjectId("595c0630939a8ae59053a9c3"), "name" : "John Smith", "age" : 37, "location" : "San Francisco, CA", "hobbies" : [ { "name" : "Cooking", "type" : "Indoor", "regular" : true }, { "name" : "Baseball", "type" : "Outdoor", "regular" : false } ] } { "_id" : ObjectId("595c06b7939a8ae59053a9c4"), "name" : "Miranda Thompson", "age" : 26, "location" : "Modesto, CA", "hobbies" : [ { "name" : "Lego building", "type" : "Indoor", "regular" : false }, { "name" : "Yoga", "type" : "Indoor", "regular" : false } ] } { "_id" : ObjectId("595c078e939a8ae59053a9c5"), "name" : "Shelly Simon", "age" : 26, "location" : "Salt Lake City, UT", "hobbies" : [ { "name" : "Hunting", "type" : "Outdoor", "regular" : false }, { "name" : "Soccer", "type" : "Outdoor", "regular" : true } ] } </code></pre> <p>I am trying to filter my "hobbies" array only to regular hobbies AND project the fields _id, name, age and hobby's name and type.</p> <p>I want my output to be something like this:</p> <pre><code>{ "_id" : ObjectId("595c0630939a8ae59053a9c3"), "name" : "John Smith", "age" : 37, "hobbies" : [ { "name" : "Cooking", "type" : "Indoor" } ] } { "_id" : ObjectId("595c06b7939a8ae59053a9c4"), "name" : "Miranda Thompson", "age" : 26, "hobbies" : [] } { "_id" : ObjectId("595c078e939a8ae59053a9c5"), "name" : "Shelly Simon", "age" : 26, "hobbies" : [ { "name" : "Soccer", "type" : "Outdoor" } ] } </code></pre> <p>Well... I can achieve this output using this command in mongo shell:</p> <pre><code>db.people.aggregate([ { $project: { hobbies: { $filter: { input: "$hobbies", as: "hobby", cond: { $eq: ["$$hobby.regular", true] } } }, name: 1, age: 1 } }, { $project: { "hobbies.name": 1, "hobbies.type": 1, name: 1, age: 1 } } ]) </code></pre> <p>As you can see, I had to use two $project operators in sequence and I think this smells bad.</p> <p>Is there a way to achieve the same result with another query that does not use the same operator twice and in sequence?</p>
0
2,091
syntax error near unexpected token `('
<p>Below is my code, it keeps telling me that line 10 is causing this "syntax error near unexpected token `('" but I cannot figure out why. I am adding to a code that was already written but the part where it says there is an error is not part of what I added. So I'm very confused about why I'm getting this error. Also I would like a good definition of what this error actually means.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "applanix_data.h" #include "applanix_pos_out.h" #define DEGREES2RADIANS (3.141592654 / 180.0) int output_group_1(FILE *fp, /* This is line 10 */ FILE *fpout, unsigned short myyear, unsigned short mymonth, unsigned short myday, double time_sod, double double_time_met) { struct applanix_data_group1 data1; struct pospacsbet sbet; if(fread(&amp;data1,sizeof(struct applanix_data_group1),1,fp)==1) { sbet.gpstime = time_sod; sbet.latitude = data1.latitude * DEGREES2RADIANS; sbet.longitude = data1.longitude * DEGREES2RADIANS; sbet.altitude = data1.altitude; sbet.x_velocity = data1.eVelocity; sbet.y_velocity = data1.nVelocity; sbet.z_velocity = data1.dVelocity; sbet.roll = data1.aircraftRoll * DEGREES2RADIANS; sbet.pitch = data1.aircraftPitch * DEGREES2RADIANS; sbet.platform_heading = data1.aircraftHeading * DEGREES2RADIANS; sbet.wander_angle = data1.aircraftWanderAngle * DEGREES2RADIANS; sbet.x_body_acceleration = data1.aircraftTransverseAcceleration; sbet.y_body_acceleration = data1.aircraftLongitudinalAcceleration; sbet.z_body_acceleration = data1.aircraftDownAcceleration; sbet.x_body_angular_rate = data1.aircraftAngularRateAboutDownAxis; sbet.y_body_angular_rate = data1.aircraftLongitudinalAcceleration; sbet.z_body_angular_rate = data1.aircraftAngularRateAboutDownAxis; if(fwrite(&amp;sbet,sizeof(struct pospacsbet),1,fpout)!=1) { fprintf(stderr,"Error writing POSPAC SBET output!\n"); exit(-2); } sbet.latitude1 = sbet.latitude * (180/3.141592654); sbet.longitude1 = sbet.longitude * (180/3.14592654); sbet.day = sbet.gpstime/86400; sbet.time = sbet.gpstime/86400; sbet.hour1 = (sbet.time - sbet.day); sbet.hour = sbet.hour1*24; sbet.time = sbet.hour1*24; sbet.minute1 = (sbet.time - sbet.hour); sbet.minute = sbet.minute1*60; sbet.time = sbet.minute1 * 60; sbet.second1 = (sbet.time - sbet.minute); sbet.second = sbet.second1*60; printf("%12.8f, %12.8f, %6.3f, %i:%i:%4.2f\n",sbet.longitude1,sbet.latitude1,sbet.altitude,sbet.hour, sbet.minute, sbet.second); return 0; } else return -1; } </code></pre> <p><em>Editing the OP's comment into the question</em>:</p> <pre><code>unix&gt; g++ applanixraw2out.c unix&gt; ./applanixraw2out.c applanix_raw_20120508.bin &gt; test.txt ./applanixraw2out.c: line 10: syntax error near unexpected token (' </code></pre>
0
1,338
.NET Core RuntimeIdentifier vs TargetFramework
<p>Can someone explain the purpose of this two in csproj file (VS2017):</p> <pre><code>&lt;TargetFramework&gt;netstandard1.6&lt;/TargetFramework&gt; &lt;RuntimeIdentifier&gt;win7&lt;/RuntimeIdentifier&gt; </code></pre> <p>I just migrated from VS2015 and now can't publish my web api because it looks I should use only one target framework. In addition I can't specify multiple RIDs. All these changed things make me frustrated. Nothing works from scratch, should overcome something over and over. </p> <p>I just want developing my web-api on windows, run xUnit tests here and then deploy web-api to run on linux (ubuntu) server. What I should put in both parameters in csproj ? Links with good explanation is highly appreciated. </p> <p><strong>Update1</strong></p> <p>I have web api with referenced .net core libraries. Everything where migrated from VS2015. Now in root project I have <code>&lt;TargetFrameworks&gt;netcoreapp1.1;net461&lt;/TargetFrameworks&gt;</code>. When I publish via VS2017 I got error: </p> <blockquote> <p>C:\Program Files\dotnet\sdk\1.0.3\Sdks\Microsoft.NET.Sdk\buildCrossTargeting\Microsoft.NET.Sdk.targets(31,5): error : The 'Publish' target is not supported without specifying a target framework. The current project targets multiple frameworks, please specify the framework for the published application.</p> </blockquote> <p>But I have specified target framework in publish as <code>netcoreapp1.1</code>. OK. Then I updated my csproj with <code>&lt;PropertyGroup Condition="$(TargetFramework)'=='netcoreapp1.1'"&gt; &lt;RuntimeIdentifier&gt;ubuntu.16.10-x64&lt;/RuntimeIdentifier&gt; &lt;/PropertyGroup&gt;</code> as suggested below. But now I even can't build app, get error:</p> <blockquote> <p>5>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.targets(92,5): error : Assets file '\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v1.1/ubuntu.16.10-x64'. Ensure you have restored this project for TargetFramework='netcoreapp1.1' and RuntimeIdentifier='ubuntu.16.10-x64'.</p> </blockquote> <p>I just want develop with VS2017 at windows 8.1/windows7 and deploy to ubuntu 16.10. What I'm doing wrong ?</p> <p><strong>Update2</strong></p> <p>I have 8 projects in solution. 3 of them are xUnit tests. Thus we have 5 projects. 4 of these 5 are class libraries and 1 is my web-app. All 4 class libraries have this: </p> <pre><code>&lt;TargetFrameworks&gt;netstandard1.6;net461&lt;/TargetFrameworks&gt; &lt;ItemGroup Condition=" '$(TargetFramework)' == 'net461' "&gt; &lt;Reference Include="System" /&gt; &lt;Reference Include="Microsoft.CSharp" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>My web app:</p> <pre><code>&lt;TargetFrameworks&gt;netcoreapp1.1;net461&lt;/TargetFrameworks&gt; &lt;ItemGroup Condition=" '$(TargetFramework)' == 'net461' "&gt; &lt;Reference Include="System" /&gt; &lt;Reference Include="Microsoft.CSharp" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>How to publish my web-app ?</p>
0
1,055
STM32F429 is not receiving the CAN Message
<p>I am using STM32F429 Microcontroller and need to implement CAN Bus Communication between CAN2 and PCAN View.I am able to transmit the message from CAN2 but I am not able to receive any message.I am using TJA1041A CAN transreceiver in the microcontroller.The Problem is that during debugging my CAN bus are properly initalized but it doesn't go to the receive command although I have initalized FIFO0.Herewith I am attching the program for further reference.I have used STM32 HAL Cube for programming.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>/** ****************************************************************************** * File Name : main.c * Date : 05/12/2014 09:43:55 * Description : Main program body ****************************************************************************** * * COPYRIGHT(c) 2014 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private variables ---------------------------------------------------------*/ CAN_HandleTypeDef hcan1; CAN_HandleTypeDef hcan2; /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_CAN1_Init(void); static void MX_CAN2_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_CAN1_Init(); MX_CAN2_Init(); /* USER CODE BEGIN 2 */ __GPIOD_CLK_ENABLE(); GPIO_InitTypeDef GPIO_Initpins; GPIO_Initpins.Mode = GPIO_MODE_OUTPUT_PP ; GPIO_Initpins.Pin = GPIO_PIN_5|GPIO_PIN_7; GPIO_Initpins.Pull = GPIO_NOPULL ; HAL_GPIO_Init(GPIOD, &amp;GPIO_Initpins); HAL_GPIO_WritePin(GPIOD, GPIO_PIN_5|GPIO_PIN_7, GPIO_PIN_SET); /* USER CODE END 2 */ /* USER CODE BEGIN 3 */ /* Infinite loop */ CanTxMsgTypeDef TxMess; TxMess.StdId = 0x123; TxMess.DLC = 0x0; TxMess.Data[0] = 0x12; TxMess.IDE = 0; TxMess.RTR = 0; hcan2.pTxMsg = &amp;TxMess; HAL_CAN_Transmit(&amp;hcan2,50); HAL_Delay(500); /* USER CODE END 2 */ CanRxMsgTypeDef RMess; RMess.FIFONumber = CAN_FIFO1; RMess.FMI = 14; RMess.StdId = 0x541; RMess.DLC = 0; RMess.RTR = 0; RMess.IDE = CAN_ID_STD; hcan2.pRxMsg = &amp;RMess; HAL_CAN_Receive_IT(&amp;hcan2,CAN_FIFO1); /* USER CODE BEGIN 3 */ /* Infinite loop */ while (1) { HAL_CAN_Receive(&amp;hcan2,CAN_FIFO1,0); } /* USER CODE END 3 */ } /** System Clock Configuration */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_ClkInitTypeDef RCC_ClkInitStruct; __PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; HAL_RCC_OscConfig(&amp;RCC_OscInitStruct); RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; HAL_RCC_ClockConfig(&amp;RCC_ClkInitStruct, FLASH_LATENCY_0); } /* CAN1 init function */ void MX_CAN1_Init(void) { hcan1.Instance = CAN1; hcan1.Init.Prescaler = 16; hcan1.Init.Mode = CAN_MODE_NORMAL; hcan1.Init.SJW = CAN_SJW_1TQ; hcan1.Init.BS1 = CAN_BS1_1TQ; hcan1.Init.BS2 = CAN_BS2_1TQ; hcan1.Init.TTCM = DISABLE; hcan1.Init.ABOM = DISABLE; hcan1.Init.AWUM = DISABLE; hcan1.Init.NART = DISABLE; hcan1.Init.RFLM = DISABLE; hcan1.Init.TXFP = DISABLE; HAL_CAN_Init(&amp;hcan1); /*CAN_FilterConfTypeDef CAN_Filters; CAN_Filters.BankNumber = 0; CAN_Filters.FilterActivation = ENABLE; CAN_Filters.FilterFIFOAssignment = CAN_FILTER_FIFO0 ; CAN_Filters.FilterIdHigh = 0x00; CAN_Filters.FilterIdLow = 0x00; CAN_Filters.FilterMaskIdHigh = 0x00; CAN_Filters.FilterMaskIdLow = 0x00; CAN_Filters.FilterMode = CAN_FILTERMODE_IDMASK; CAN_Filters.FilterNumber = 0; CAN_Filters.FilterScale = CAN_FILTERSCALE_32BIT; HAL_CAN_ConfigFilter(&amp;hcan1, &amp;CAN_Filters);*/ } /* CAN2 init function */ void MX_CAN2_Init(void) { hcan2.Instance = CAN2; hcan2.Init.Prescaler = 2; hcan2.Init.Mode = CAN_MODE_NORMAL; hcan2.Init.SJW = CAN_SJW_1TQ; hcan2.Init.BS1 = CAN_BS1_5TQ; hcan2.Init.BS2 = CAN_BS2_2TQ; hcan2.Init.TTCM = DISABLE; hcan2.Init.ABOM = DISABLE; hcan2.Init.AWUM = DISABLE; hcan2.Init.NART = DISABLE; hcan2.Init.RFLM = DISABLE; hcan2.Init.TXFP = DISABLE; HAL_CAN_Init(&amp;hcan2); } /** Configure pins as * Analog * Input * Output * EVENT_OUT * EXTI */ void MX_GPIO_Init(void) { /* GPIO Ports Clock Enable */ __GPIOH_CLK_ENABLE(); __GPIOB_CLK_ENABLE(); __GPIOA_CLK_ENABLE(); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/</code></pre> </div> </div> </p> <p>Thanks </p>
0
3,029
$httpBackend in AngularJs Jasmine unit test
<p>I'm unable to get my unit test to work properly. I have a $scope array that starts out empty, but should be filled with an $http.get(). In the real environment, there'd be approx 15 or so objects in the array, but for my unit test I just grabbed 2. For the unit test, I have:</p> <pre><code>expect($scope.stuff.length).toBe(2); </code></pre> <p>But jasmine's error is: Expected 0 to be 2.</p> <p>here's my controller.js:</p> <pre><code>$scope.stuff = []; $scope.getStuff = function () { var url = site.root + 'api/stuff'; $http.get(url) .success(function (data) { $scope.stuff = data; }) .error(function(error) { console.log(error); }); }; </code></pre> <p>and my controller.spec.js is:</p> <pre><code>/// &lt;reference path="../../../scripts/angular-loader.min.js" /&gt; /// &lt;reference path="../../../scripts/angular.min.js" /&gt; /// &lt;reference path="../../../scripts/angular-mocks.js" /&gt; /// &lt;reference path="../../../scripts/angular-resource.js" /&gt; /// &lt;reference path="../../../scripts/controller.js" /&gt; beforeEach(module('ui.router')); beforeEach(module('ngResource')); beforeEach(module('ngMockE2E')); beforeEach(module('myApplication')); var $scope; var controller; var httpLocalBackend; beforeEach(inject(function ($rootScope, $controller, $injector) { $scope = $rootScope.$new(); controller = $controller("StuffController", { $scope: $scope }); })); beforeEach(inject(function ($httpBackend) { httpLocalBackend = $httpBackend; })); it('should get stuff', function () { var url = '/api/stuff'; var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }]; httpLocalBackend.expectGET(url).respond(200, httpResponse); $scope.getStuff(); expect($scope.stuff.length).toBe(2); //httpLocalBackend.flush(); } ); </code></pre> <p>Now, obviously, I changed variable names and such since this is for work, but hopefully this is enough information for anybody to help me. I can provide more if needed. I also get a second error when uncommenting the .flush() line, but I'll get to that a bit later.</p> <p>Any help is greatly appreciated and thanks in advance!</p> <p>EDIT:</p> <p>Finally got it working! Here's my final code:</p> <pre><code>it('should get stuff', function () { var url = '/api/stuff'; var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }]; httpLocalBackend.expectGET(url).respond(200, httpResponse); $scope.getStuff(); httpLocalBackend.flush(); expect($scope.stuff.length).toBe(2); } ); </code></pre> <p>EDIT 2: I ran into another problem, which I think may have been the root cause of this. See <a href="https://stackoverflow.com/questions/25794501/unit-test-failing-when-function-called-on-startup">Unit test failing when function called on startup</a></p>
0
1,033
Can I use ng-model with isolated scope?
<p>I am creating simple ui-datetime directive. It splits javascript Date object into _date, _hours and _minutes parts. _date uses jquery ui datepicker, _hours and _minutes - number inputs.</p> <pre><code>angular.module("ExperimentsModule", []) .directive("uiDatetime", function () { return { restrict: 'EA', replace: true, template: '&lt;div class="ui-datetime"&gt;' + '&lt;input type="text" ng-model="_date" class="date"&gt;' + '&lt;input type="number" ng-model="_hours" min="0" max="23" class="hours"&gt;' + '&lt;input type="number" ng-model="_minutes" min="0" max="59" class="minutes"&gt;' + '&lt;br /&gt;Child datetime1: {{datetime1}}' + '&lt;/div&gt;', require: 'ngModel', scope: true, link: function (scope, element, attrs, ngModelCtrl) { var elDate = element.find('input.date'); ngModelCtrl.$render = function () { var date = new Date(ngModelCtrl.$viewValue); var fillNull = function (num) { if (num &lt; 10) return '0' + num; return num; }; scope._date = fillNull(date.getDate()) + '.' + fillNull(date.getMonth() + 1) + '.' + date.getFullYear(); scope._hours = date.getHours(); scope._minutes = date.getMinutes(); }; elDate.datepicker({ dateFormat: 'dd.mm.yy', onSelect: function (value, picker) { scope._date = value; scope.$apply(); } }); var watchExpr = function () { var res = scope.$eval('_date').split('.'); if (res.length == 3) return new Date(res[2], res[1] - 1, res[0], scope.$eval('_hours'), scope.$eval('_minutes')); return 0; }; scope.$watch(watchExpr, function (newValue) { ngModelCtrl.$setViewValue(newValue); }, true); } }; }); function TestController($scope) { $scope.datetime1 = new Date(); } </code></pre> <p><a href="http://jsfiddle.net/andreev_artem/nWsZp/3/"><kbd>jsfiddle</kbd></a></p> <p>On github: <a href="https://github.com/andreev-artem/angular_experiments/tree/master/ui-datetime">https://github.com/andreev-artem/angular_experiments/tree/master/ui-datetime</a></p> <p>As far as I understand - best practice when you create a new component is to use isolated scope.</p> <p>When I tried to use isolated scope - nothing works. ngModel.$viewValue === undefined.</p> <p>When I tried to use new scope (my example, not so good variant imho) - ngModel uses value on newly created scope.</p> <p>Of course I can create directive with isolated scope and work with ngModel value through "=expression" (<a href="https://github.com/andreev-artem/angular_experiments/blob/uiDatetime_impl2/ui-datetime/ui-datetime.js">example</a>). But I think that working with ngModelController is a better practice.</p> <p>My questions:</p> <ol> <li>Can I use ngModelController with isolated scope?</li> <li>If it is not possible which solution is better for creating such component?</li> </ol>
0
1,439
In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string:
<p>I am trying to condense a very large log file, and to do so, I must eliminate every line which contains the string "StatusRequest" and "StatusResponse", while printing the other lines w/o this string. The code I have so far is as follows (to run from the command prompt):</p> <blockquote> <pre><code> if (sys.argv[1])=="--help": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") if (sys.argv[1])=="-h": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") else: print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) Numarg = (len(sys.argv)) i=1 while i&lt;=(Numarg-4): search1="StatusRequest" search2="StatusResponse" if (sys.argv[Numarg-2])=="-o": outputfile=sys.argv[Numarg-1] if (sys.argv[Numarg-2])=="--output": outputfile=sys.argv[Numarg-1] if (sys.argv[i])=="-i": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 if (sys.argv[i])=="--input": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 for line in readlines_data: if not ("StatusRequest" or "StatusResponse") in line: result=line print (line) f=open(outputfile, 'a') f.write(result + "\n") f.close() </code></pre> </blockquote> <p>You can just focus on the end of the script to answer my question, really...Anyways, I am not sure why this doesn't work...It is outputting every line still. And I already tried switching the place of the not so it would make more sense idiomatically, but it didn't change anything with the code. Any help is much appreciated :)</p>
0
1,281
Android Camera Server Died and Camera Error - 100
<p>I'm facing Camera error 100 while testing my android application, I have found some topics on <code>StackOverflow</code> but they were not so helpful. I'm searching for a relevant solution to fix the error.</p> <p>Code that I've written:</p> <pre><code>mrec = new MediaRecorder(); // Works well mCamera = Camera.open(); mCamera.unlock(); mrec.setCamera(mCamera); mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA); mrec.setAudioSource(MediaRecorder.AudioSource.MIC); mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); mrec.setOutputFile("/sdcard/zzzz.3gp"); mrec.prepare(); mrec.start(); </code></pre> <p>Code to record Camera :</p> <pre><code>protected void startRecordingVideo() throws IOException { camera = Camera.open(); camera.unlock(); SimpleDateFormat timeStampFormat = new SimpleDateFormat( "yyyy-MM-dd-HH.mm.ss"); String fileName = "video_" + timeStampFormat.format(new Date()) + ".3gp"; String fileURL = "/sdcard/"+fileName; surfaceView = (SurfaceView) findViewById(R.id.surface_camera); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mrec = new MediaRecorder(); mrec.setCamera(camera); mrec.setPreviewDisplay(surfaceHolder.getSurface()); mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA); mrec.setAudioSource(MediaRecorder.AudioSource.MIC); mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW)); mrec.setPreviewDisplay(surfaceHolder.getSurface()); mrec.setOutputFile("/sdcard/"+fileName); mrec.prepare(); mrec.start(); } protected void stopRecordingVideo() { mrec.stop(); mrec.release(); camera.release(); } private void releaseMediaRecorder(){ if (mrec != null) { mrec.reset(); // clear recorder configuration mrec.release(); // release the recorder object mrec = null; camera.lock(); } } private void releaseCamera(){ if (camera != null){ camera.release(); camera = null; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub if (camera != null){ Parameters params = camera.getParameters(); camera.setParameters(params); } else { Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show(); finish(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { releaseMediaRecorder(); camera.stopPreview(); camera.release(); } </code></pre> <p>Here are the Logcat output :</p> <pre><code>12-27 17:52:02.788: W/IMediaDeathNotifier(21434): media server died! 12-27 17:52:02.788: W/Camera(21434): Camera server died! 12-27 17:52:02.788: W/Camera(21434): ICamera died 12-27 17:52:03.048: E/Camera(21434): Error 100 </code></pre>
0
1,047
Vue.js 3 and typescript : Property '$store' does not exist on type 'ComponentPublicInstance
<p>Can't find anything to solve this seemingly obvious issue.</p> <p>Just upgraded from Vue 2 to Vue 3 and Vuex with Typescript.</p> <p>this.$store doesn't seem to be accessible, despite following the Vue 3 instructions.</p> <blockquote> <p>ERROR in src/components/FlashMessages.vue:28:25 TS2339: Property '$store' does not exist on type 'ComponentPublicInstance&lt;{}, {}, {}, { getAllFlashMessages(): Word; }, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase&lt;{}, {}, {}, { getAllFlashMessages(): Word; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}&gt;&gt;'.</p> </blockquote> <pre><code> 26 | computed: { 27 | getAllFlashMessages (): FlashType { &gt; 28 | return this.$store.getters.getFlashMessages; | ^^^^^^ 29 | }, 30 | }, 31 | </code></pre> <p>main.ts</p> <pre><code>import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store from './store' import './assets/styles/index.css' const app = createApp(App) app.use(store) app.use(router) app.mount('#app') </code></pre> <p>store.ts</p> <pre><code>import { createStore } from 'vuex' import FlashType from '@/init' export default createStore({ state: { flashMessages: [] as FlashType[], }, getters: { getFlashMessages (state) { return state.flashMessages } }, </code></pre> <p>FlashMessages.vue</p> <pre><code>&lt;script lang=&quot;ts&quot;&gt; import { defineComponent } from &quot;vue&quot;; import FlashType from &quot;@/init&quot;; export default defineComponent({ name: &quot;FlashMessages&quot;, data () { return {}; }, computed: { getAllFlashMessages (): FlashType { return this.$store.getters.getFlashMessages; }, }, </code></pre> <p>init.ts</p> <pre><code>export type FlashType = { kind: 'success' | 'error'; message: string; time: number; } </code></pre> <p>Any wisdom appreciated :)</p> <p>File structure</p> <pre><code>├── .editorconfig ├── client │   ├── babel.config.js │   ├── CONTRACTS.md │   ├── cypress.json │   ├── jest.config.js │   ├── package.json │   ├── package-lock.json │   ├── postcss.config.js │   ├── public │   │   ├── favicon.ico │   │   ├── index.html │   │   └── robots.txt │   ├── README.md │   ├── src │   │   ├── App.vue │   │   ├── assets │   │   │   ├── logo.png │   │   │   └── styles │   │   │   └── index.css │   │   ├── components │   │   │   ├── admin │   │   │   │   ├── AdminAdd.vue │   │   │   │   ├── AdminList.vue │   │   │   │   ├── AdminWord.vue │   │   │   │   ├── EmotionAdd.vue │   │   │   │   ├── EmotionsList.vue │   │   │   │   └── Emotion.vue │   │   │   └── FlashMessages.vue │   │   ├── init.ts │   │   ├── main.ts │   │   ├── registerServiceWorker.ts │   │   ├── router │   │   │   └── index.ts │   │   ├── shims-vue.d.ts │   │   ├── store │   │   │   └── index.ts │   │   └── views │   │   ├── About.vue │   │   ├── Admin.vue │   │   ├── Emotions.vue │   │   └── Home.vue │   ├── tsconfig.json │   └── vue.config.js ├ └── server ├── api ├── api.bundle.js ├── index.ts ├── logger │   └── logger.ts ├── models ├── nodemon.json ├── package.json ├── package-lock.json ├── router │   ├── db.ts │   └── emotions.ts ├── tsconfig.json └── webpack.config.js </code></pre> <p>This is my first time properly using eslint, so I'm not sure if I've set it up correctly.. I ended up with a different tsconfig in /client and /server directories.</p> <p>client/tsconfig.json</p> <pre><code>{ &quot;compilerOptions&quot;: { &quot;target&quot;: &quot;esnext&quot;, &quot;module&quot;: &quot;esnext&quot;, &quot;strict&quot;: true, &quot;jsx&quot;: &quot;preserve&quot;, &quot;importHelpers&quot;: true, &quot;moduleResolution&quot;: &quot;node&quot;, &quot;skipLibCheck&quot;: true, &quot;esModuleInterop&quot;: true, &quot;allowSyntheticDefaultImports&quot;: true, &quot;sourceMap&quot;: true, &quot;baseUrl&quot;: &quot;./&quot;, &quot;types&quot;: [ &quot;webpack-env&quot;, &quot;jest&quot; ], &quot;paths&quot;: { &quot;@/*&quot;: [ &quot;src/*&quot; ] }, &quot;lib&quot;: [ &quot;esnext&quot;, &quot;dom&quot;, &quot;dom.iterable&quot;, &quot;scripthost&quot; ] }, &quot;include&quot;: [ &quot;src/**/*.ts&quot;, &quot;src/**/*.tsx&quot;, &quot;src/**/*.vue&quot;, &quot;tests/**/*.ts&quot;, &quot;tests/**/*.tsx&quot; ], &quot;exclude&quot;: [ &quot;node_modules&quot; ] } </code></pre>
0
2,231
Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)
<p>I am upgrading my angular 2 app from beta 9 to RC5 and i get this error in my form template.</p> <p>Here is the full error</p> <pre><code>zone.js:461 Unhandled Promise rejection: Template parse errors: Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) (" &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; [ERROR -&gt;]"): ParametersFormComponent@186:0 Invalid ICU message. Missing '}'. ("arr"&gt; &lt;p&gt;{{ pa }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(pa, [ERROR -&gt;]'param')"&gt;&lt;/button&gt; &lt;/li&gt; "): ParametersFormComponent@158:70 Unexpected closing tag "button" (" &lt;p&gt;{{ pa }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;[ERROR -&gt;]&lt;/button&gt; &lt;/li&gt; "): ParametersFormComponent@158:80 Unexpected closing tag "li" ("/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;&lt;/button&gt; [ERROR -&gt;]&lt;/li&gt; &lt;pre&gt;{ Restrict Operator } parameters&lt;/pre&gt; "): ParametersFormComponent@159:6 Invalid ICU message. Missing '}'. ("arr"&gt; &lt;p&gt;{{ la }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(la, [ERROR -&gt;]'liftOperator')"&gt;&lt;/button&gt; &lt;/li&gt; "): ParametersFormComponent@170:70 Unexpected closing tag "button" ("{{ la }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;[ERROR -&gt;]&lt;/button&gt; &lt;/li&gt; "): ParametersFormComponent@170:87 Unexpected closing tag "li" (" &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;&lt;/button&gt; [ERROR -&gt;]&lt;/li&gt; &lt;pre&gt;{ xInitial } parameters&lt;/pre&gt; "): ParametersFormComponent@171:6 Invalid ICU message. Missing '}'. (" &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; [ERROR -&gt;]"): ParametersFormComponent@186:0 ; Zone: &lt;root&gt; ; Task: Promise.then ; Value: BaseException {message: "Template parse errors:↵Unexpected character "EOF" …tion&gt;↵[ERROR -&gt;]"): ParametersFormComponent@186:0", stack: "Error: Template parse errors:↵Unexpected character…ttp://localhost:4200/polyfills.bundle.js:3385:38)"}message: "Template parse errors:↵Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("↵ &lt;/div&gt;↵ &lt;/div&gt;↵&lt;/section&gt;↵[ERROR -&gt;]"): ParametersFormComponent@186:0↵Invalid ICU message. Missing '}'. ("arr"&gt;↵ &lt;p&gt;{{ pa }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, [ERROR -&gt;]'param')"&gt;&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@158:70↵Unexpected closing tag "button" (" &lt;p&gt;{{ pa }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;[ERROR -&gt;]&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@158:80↵Unexpected closing tag "li" ("/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;&lt;/button&gt;↵ [ERROR -&gt;]&lt;/li&gt;↵↵ &lt;pre&gt;{ Restrict Operator } parameters&lt;/pre&gt;↵"): ParametersFormComponent@159:6↵Invalid ICU message. Missing '}'. ("arr"&gt;↵ &lt;p&gt;{{ la }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(la, [ERROR -&gt;]'liftOperator')"&gt;&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@170:70↵Unexpected closing tag "button" ("{{ la }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;[ERROR -&gt;]&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@170:87↵Unexpected closing tag "li" (" &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;&lt;/button&gt;↵ [ERROR -&gt;]&lt;/li&gt;↵↵ &lt;pre&gt;{ xInitial } parameters&lt;/pre&gt;↵"): ParametersFormComponent@171:6↵Invalid ICU message. Missing '}'. ("↵ &lt;/div&gt;↵ &lt;/div&gt;↵&lt;/section&gt;↵[ERROR -&gt;]"): ParametersFormComponent@186:0"stack: "Error: Template parse errors:↵Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("↵ &lt;/div&gt;↵ &lt;/div&gt;↵&lt;/section&gt;↵[ERROR -&gt;]"): ParametersFormComponent@186:0↵Invalid ICU message. Missing '}'. ("arr"&gt;↵ &lt;p&gt;{{ pa }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, [ERROR -&gt;]'param')"&gt;&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@158:70↵Unexpected closing tag "button" (" &lt;p&gt;{{ pa }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;[ERROR -&gt;]&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@158:80↵Unexpected closing tag "li" ("/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;&lt;/button&gt;↵ [ERROR -&gt;]&lt;/li&gt;↵↵ &lt;pre&gt;{ Restrict Operator } parameters&lt;/pre&gt;↵"): ParametersFormComponent@159:6↵Invalid ICU message. Missing '}'. ("arr"&gt;↵ &lt;p&gt;{{ la }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(la, [ERROR -&gt;]'liftOperator')"&gt;&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@170:70↵Unexpected closing tag "button" ("{{ la }}&lt;/p&gt;↵ &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;[ERROR -&gt;]&lt;/button&gt;↵ &lt;/li&gt;↵↵"): ParametersFormComponent@170:87↵Unexpected closing tag "li" (" &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;&lt;/button&gt;↵ [ERROR -&gt;]&lt;/li&gt;↵↵ &lt;pre&gt;{ xInitial } parameters&lt;/pre&gt;↵"): ParametersFormComponent@171:6↵Invalid ICU message. Missing '}'. ("↵ &lt;/div&gt;↵ &lt;/div&gt;↵&lt;/section&gt;↵[ERROR -&gt;]"): ParametersFormComponent@186:0↵ at new BaseException (http://localhost:4200/main.bundle.js:3322:23)↵ at TemplateParser.parse (http://localhost:4200/main.bundle.js:14533:19)↵ at RuntimeCompiler._compileTemplate (http://localhost:4200/main.bundle.js:32136:51)↵ at http://localhost:4200/main.bundle.js:32064:83↵ at Set.forEach (native)↵ at compile (http://localhost:4200/main.bundle.js:32064:47)↵ at ZoneDelegate.invoke (http://localhost:4200/polyfills.bundle.js:3352:29)↵ at Zone.run (http://localhost:4200/polyfills.bundle.js:3245:44)↵ at http://localhost:4200/polyfills.bundle.js:3600:58↵ at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.bundle.js:3385:38)"__proto__: ErrorconsoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494 </code></pre> <p>and the html file</p> <pre><code>&lt;section class="container-fluid"&gt; &lt;div class="col-sm-8"&gt; &lt;h1&gt;Parameters Form&lt;/h1&gt; &lt;form [ngFormModel]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="parameters-form"&gt; &lt;fieldset&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="numberOfModelParameters"&gt;Number of Model Parameters(n)&lt;/label&gt; &lt;input type="number" #n id="numberOfModelParameters" class="form-control" placeholder="numberOfModelParameters Param" [ngFormControl]="myForm.controls['numberOfModelParameters']"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="numberOfModelVariables"&gt;Number of Model Variables(m)&lt;/label&gt; &lt;input type="number" #m id="numberOfModelVariables" class="form-control" placeholder="numberOfModelVariables Param" [ngFormControl]="myForm.controls['numberOfModelVariables']"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="systemParameters"&gt;System Parameters&lt;/label&gt; &lt;input type="text" id="systemParameters" class="form-control" placeholder="systemParameters Param" [ngFormControl]="systemParameters" (keypress)="addToArray($event, systemParameters.value, 'systemParameters')"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="restrictOperator"&gt;Restrict Operator&lt;/label&gt; &lt;input type="text" id="restrictOperator" class="form-control" placeholder="restrictOperator Param" [ngFormControl]="myForm.controls['restrictOperator']" (keypress)="addToArray($event, restrictOperator.value, 'restrictOperator')"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="param"&gt;Param&lt;/label&gt; &lt;input type="number" id="param" class="form-control" placeholder="param" [ngFormControl]="myForm.controls['param']" (keypress)="addToArray($event, param.value, 'param')"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="liftOperator"&gt;Lift Operator&lt;/label&gt; &lt;input type="text" id="liftOperator" class="form-control" placeholder="liftOperator Param" [ngFormControl]="myForm.controls['liftOperator']" (keypress)="addToArray($event, liftOperator.value, 'liftOperator')"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="netLogoFile"&gt;Net Logo File&lt;/label&gt; &lt;input type="text" id="netLogoFile" class="form-control" placeholder="netLogoFile Param" [ngFormControl]="myForm.controls['netLogoFile']"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="xInitial"&gt;xInitial&lt;/label&gt; &lt;input type="number" id="xInitial" class="form-control" placeholder="xInitial Param" [ngFormControl]="myForm.controls['xInitial']" (keypress)="addToArray($event, xInitial.value, 'xInitial')"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="realisations"&gt;Realisations&lt;/label&gt; &lt;input type="number" id="realisations" class="form-control" placeholder="Realisations Param" [ngFormControl]="myForm.controls['realisations']"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="NumConstSteps"&gt;Number of Constant Steps&lt;/label&gt; &lt;input type="number" id="NumConstSteps" class="form-control" placeholder="NumConstSteps Param" [ngFormControl]="myForm.controls['numConstSteps']"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="timeHorizon"&gt;Time Horizon&lt;/label&gt; &lt;input type="number" id="timeHorizon" class="form-control" placeholder="timeHorizon Param" [ngFormControl]="myForm.controls['timeHorizon']"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="continuationStep"&gt;Continuation Step&lt;/label&gt; &lt;input type="number" id="continuationStep" class="form-control" placeholder="continuationStep Param" [ngFormControl]="myForm.controls['continuationStep']"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="continuationStepSign"&gt;Continuation Step Sign (+,-)&lt;/label&gt; &lt;input type="text" id="continuationStepSign" class="form-control" placeholder="continuationStep sign" [ngFormControl]="myForm.controls['continuationStepSign']"&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;button [disabled]="!isFullfilled(m.value, n.value) || !myForm.valid" type="submit" class="btn btn-success"&gt;Submit&lt;/button&gt; &lt;!-- &lt;button type="submit" class="btn btn-success"&gt;Submit&lt;/button&gt; --&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="col-sm-4"&gt; &lt;div class="parameter-values-display" *ngIf="system_arr.length != 0 || param_arr.length != 0 || restrict_arr.length != 0 || lift_arr.length != 0 || xinitial_arr.length != 0"&gt; &lt;pre&gt;{ System } parameters&lt;/pre&gt; &lt;li class="parameters" *ngFor="#sa of system_arr"&gt; &lt;p&gt;{{ sa }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(sa, 'systemParameters')"&gt;&lt;/button&gt; &lt;/li&gt; &lt;pre&gt;{ Param } Parameters&lt;/pre&gt; &lt;li class="parameters" *ngFor="#pa of param_arr"&gt; &lt;p&gt;{{ pa }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(pa, 'param')"&gt;&lt;/button&gt; &lt;/li&gt; &lt;pre&gt;{ Restrict Operator } parameters&lt;/pre&gt; &lt;li class="parameters" *ngFor="#ra of restrict_arr"&gt; &lt;p&gt;{{ ra }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(ra, 'restrictOperator')"&gt;&lt;/button&gt; &lt;/li&gt; &lt;pre&gt;{ Lift Operator } parameters&lt;/pre&gt; &lt;li class="parameters" *ngFor="#la of lift_arr"&gt; &lt;p&gt;{{ la }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(la, 'liftOperator')"&gt;&lt;/button&gt; &lt;/li&gt; &lt;pre&gt;{ xInitial } parameters&lt;/pre&gt; &lt;li class="parameters" *ngFor="#xa of xinitial_arr"&gt; &lt;p&gt;{{ xa }}&lt;/p&gt; &lt;button class="destroy" type="button" (click)="deleteItem(xa, 'xInitial')"&gt;&lt;/button&gt; &lt;/li&gt; &lt;div class="response-wrapper"&gt; &lt;label&gt;Response&lt;/label&gt; &lt;pre&gt;&lt;span&gt;{{ response | json }}&lt;/span&gt;&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>this was working fine in beta i haven't changed anything since. Any insight?</p>
0
7,356
How to create a oAuth request using java?
<p>I need to make a connection with <a href="http://developer.viagogo.net/documentation/api-security/oauth-authentication-for-public-services">Viagogo website</a> using oAuth. Referring to their <a href="http://developer.viagogo.net/documentation/api-security/oauth-authentication-for-public-services">documentation</a> I need to create a request similar to the following one </p> <pre><code>Using the example in step 1A, this means you may generate a signature base string that looks like the following: GET&amp;http%3A%2F%2Fapi.viagogo.net%2FPublic%2FSimpleOAuthAccessRequest&amp;oauth_consumer_key%3Dtestkey%26oauth_nonce%3Dmyn0nc3%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1292404912%26oauth_version%3D1.0%26scope%3DAPI.Public </code></pre> <p>I am using the following code but when I comment lines 1,2 it return <em>unauthorized error</em>, and when I use them it shows <em>oauthService.signRequest</em> returns void.</p> <p>TradeKingAPI.java</p> <pre><code>import org.scribe.builder.api.DefaultApi10a; import org.scribe.model.Token; public class TradeKingAPI extends DefaultApi10a { @Override public String getRequestTokenEndpoint() { return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest"; } @Override public String getAccessTokenEndpoint() { return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest"; } @Override public String getAuthorizationUrl(Token requestToken) { return "http://api.viagogo.net/Public/SimpleOAuthAccessRequest"; } } </code></pre> <p>main.java</p> <pre><code>import org.scribe.builder.ServiceBuilder; import org.scribe.model.OAuthRequest; import org.scribe.model.Response; import org.scribe.model.Token; import org.scribe.model.Verb; import org.scribe.oauth.OAuthService; import api.TradeKingAPI; import org.scribe.builder.api.DefaultApi10a; import org.scribe.model.OAuthConstants; import org.scribe.oauth.OAuthService; ........ OAuthService oauthService = new ServiceBuilder() .provider(TradeKingAPI.class) .apiKey("My consumer key") .apiSecret("My secret") .scope("API.Public") .build(); Long seconds = (System.currentTimeMillis() / 1000); System.out.println("&gt;&gt;&gt;" + seconds); String stSeconds = seconds.toString(); OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.viagogo.net/Public /SimpleOAuthAccessRequest"); request.addOAuthParameter(OAuthConstants.CONSUMER_KEY, "My consumer key"); request.addOAuthParameter(OAuthConstants.NONCE, "myn0nc3"); request.addOAuthParameter(OAuthConstants.SIGN_METHOD, "HMAC-SHA1"); request.addOAuthParameter(OAuthConstants.TIMESTAMP, seconds.toString()); request.addOAuthParameter(OAuthConstants.VERSION, "1.0"); request.addOAuthParameter("scope", "API.Public"); 1 String signature = oauthService.signRequest(OAuthConstants.EMPTY_TOKEN, request); 2 request.addOAuthParameter(OAuthConstants.SIGNATURE,signature); Response response = request.send(); System.err.println("&gt;&gt;" + response.isSuccessful()); System.err.println("&gt;&gt;" + response.getMessage()); System.err.println("&gt;&gt;" + response.getBody()); </code></pre>
0
1,245
changing font color on hovering the mouse over text
<p>I don't know very much about css, but i'm a tid bit stuck. I want to change the color of the font to a light blue on hover. however, i want the default color to be white... how do i do this? what i have right now, has changed the default text to purple.. and underlined :S it does change the font to blue though, on the hover..</p> <p>code:</p> <p><strong>CSS:</strong></p> <pre><code> a:hover { text-decoration:none; color: #B9D3EE; } .navigationBar { background: gray; height: 50px; width: 100%; } .menuOption { width:143px; text-align: center; position: static; float:left; } #search { position:relative; font-weight: bold; color: white; height: 27px; margin-left: 23px; left: 133px; top: -17px; margin-top: 1px; } #reports { position:relative; font-weight: bold; color: white; height: 27px; margin-left: 23px; left: 34px; top: -16px; margin-top: 1px; } #addProject { position:relative; font-weight: bold; color: #B9D3EE; height: 27px; margin-left: 23px; left: -542px; top: -18px; margin-top: 1px; } #editProject { position:relative; font-weight: bold; color: white; height: 27px; margin-left: 23px; left: -611px; top: -18px; margin-top: 1px; } #more { position:relative; font-weight: bold; color: white; height: 27px; margin-left: 23px; left: -66px; top: -15px; margin-top: 1px; } </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;div class = "navigationBar"&gt; &lt;asp:ImageButton ID="ImageButton1" runat="server" Height="18px" ImageUrl="~/g.png" style="margin-left: 1012px; margin-top: 18px" Width="23px" /&gt; &lt;div id = "search" class = "menuOption" &gt; &lt;a href=""&gt; Search &lt;/a&gt; &lt;/div&gt; &lt;div id = "reports" class = "menuOption" &gt; &lt;a href=""&gt; Reports &lt;/a&gt; &lt;/div&gt; &lt;div id = "more" class = "menuOption" &gt; &lt;a href=""&gt; More... &lt;/a&gt; &lt;/div&gt; &lt;div id = "addProject" class = "menuOption" &gt; &lt;a href=""&gt; Add Project &lt;/a&gt; &lt;/div&gt; &lt;div id = "editProject" class = "menuOption" &gt; &lt;a href=""&gt; Edit Project &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
0
1,258
Nginx reverse proxy to private aws s3 bucket bad gateaway
<p>I have created a private bucket on aws and I want to reverse proxy it using nginx. I have used the same server for all the different proxies. this is the configuration file for nginx:</p> <pre><code>user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { server_names_hash_bucket_size 64; server { listen 80; server_name ec2-...-...-....eu-central-1.compute.amazonaws.com; rewrite ^(.*) https://$host$1 permanent; } server { listen 443; server_name ec2-...-...-....eu-central-1.compute.amazonaws.com; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; ssl on; ssl_session_cache builtin:1000 shared:SSL:10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4; ssl_prefer_server_ciphers on; access_log /var/log/nginx/ssl_access.log; location ^~ / { #proxy_set_header x-real-IP $remote_addr; #proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; #proxy_set_header host $host; #proxy_pass https://url.com; #proxy_set_header Host $host; #proxy_set_header X-Real-IP $remote_addr; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header X-Forwarded-Proto $scheme; # Fix the “It appears that your reverse proxy set up is broken" error. proxy_pass https://url.com; proxy_read_timeout 30; proxy_ssl_session_reuse off; proxy_ssl_verify off; } location /one/service { # proxy_set_header X-Real-IP $remote_addr; # proxy_set_header Host $host; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://beanstalk-4.212314.eu-central-1.elasticbeanstalk.com/; proxy_read_timeout 30; proxy_ssl_session_reuse off; proxy_ssl_verify off; } location /privateproxy { set $s3_bucket 'bucketname.s3.eu-central-1.amazonaws.com'; set $aws_access_key 'AWSAccessKeyId=mykey'; set $url_expires 'Expires=$arg_e'; set $url_signature 'Signature=$arg_st'; set $url_full '$1?$aws_access_key&amp;$url_expires&amp;$url_signature'; proxy_http_version 1.1; proxy_set_header Host $s3_bucket; proxy_set_header Authorization ''; proxy_hide_header x-amz-id-2; proxy_hide_header x-amz-request-id; proxy_hide_header Set-Cookie; proxy_ignore_headers "Set-Cookie"; proxy_buffering off; proxy_intercept_errors on; resolver 172.16.0.23 valid=300s; resolver_timeout 10s; proxy_pass http://$s3_bucket/$url_full; } } } </code></pre> <p>But I am getting 502 Bad Gateway Have I done something wrong in the config?</p> <p>The log file: 2016/03/21 09:13:42 [error] 16695#0: *8 bucket.s3.eu-central-1.amazonaws.com could not be resolved (110: Operation timed out)</p>
0
1,711
Reading in environmental Variable Using Viper Go
<p>I am trying to make Viper read my environment variables, but its not working. Here is my configuration:</p> <pre><code># app.yaml dsn: RESTFUL_APP_DSN jwt_verification_key: RESTFUL_APP_JWT_VERIFICATION_KEY jwt_signing_key: RESTFUL_APP_JWT_SIGNING_KEY jwt_signing_method: "HS256" </code></pre> <p>And my <code>config.go</code> file:</p> <pre><code>package config import ( "fmt" "strings" "github.com/go-ozzo/ozzo-validation" "github.com/spf13/viper" ) // Config stores the application-wide configurations var Config appConfig type appConfig struct { // the path to the error message file. Defaults to "config/errors.yaml" ErrorFile string `mapstructure:"error_file"` // the server port. Defaults to 8080 ServerPort int `mapstructure:"server_port"` // the data source name (DSN) for connecting to the database. required. DSN string `mapstructure:"dsn"` // the signing method for JWT. Defaults to "HS256" JWTSigningMethod string `mapstructure:"jwt_signing_method"` // JWT signing key. required. JWTSigningKey string `mapstructure:"jwt_signing_key"` // JWT verification key. required. JWTVerificationKey string `mapstructure:"jwt_verification_key"` } func (config appConfig) Validate() error { return validation.ValidateStruct(&amp;config, validation.Field(&amp;config.DSN, validation.Required), validation.Field(&amp;config.JWTSigningKey, validation.Required), validation.Field(&amp;config.JWTVerificationKey, validation.Required), ) } func LoadConfig(configpaths ...string) error { v := viper.New() v.SetConfigName("app") v.SetConfigType("yaml") v.SetEnvPrefix("restful") v.AutomaticEnv() v.SetDefault("error_file", "config/errors.yaml") v.SetDefault("server_port", 1530) v.SetDefault("jwt_signing_method", "HS256") v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) for _, path := range configpaths { v.AddConfigPath(path) } if err := v.ReadInConfig(); err != nil { return fmt.Errorf("Failed to read the configuration file: %s", err) } if err := v.Unmarshal(&amp;Config); err != nil { return err } // Checking with this line. This is what I get: // RESTFUL_JWT_SIGNING_KEY fmt.Println("Sign Key: ", v.GetString("jwt_signing_key")) return Config.Validate() } </code></pre> <p>This line <code>fmt.Println("Sign Key: ", v.GetString("jwt_signing_key"))</code> gives me just the key passed in the yaml file <code>RESTFUL_JWT_SIGNING_KEY</code>. I don't know what I'm doing wrong.</p> <p>According to doc:</p> <blockquote> <p>AutomaticEnv is a powerful helper especially when combined with SetEnvPrefix. When called, Viper will check for an environment variable any time a viper.Get request is made. It will apply the following rules. It will check for a environment variable with a name matching the key uppercased and prefixed with the EnvPrefix if set.</p> </blockquote> <p>So, why isn't it reading the environment variables?</p> <p>Using <code>JSON</code></p> <pre><code>{ "dsn": "RESTFUL_APP_DSN", "jwt_verification_key": "RESTFUL_APP_JWT_VERIFICATION_KEY", "jwt_signing_key": "RESTFUL_APP_JWT_SIGNING_KEY", "jwt_signing_method": "HS256" } </code></pre> <p>And my parser looks like thus:</p> <pre><code>// LoadConfigEnv loads configuration from the given list of paths and populates it into the Config variable. // Environment variables with the prefix "RESTFUL_" in their names are also read automatically. func LoadConfigEnv(environment string, configpaths ...string) error { v := viper.New() v.SetConfigName(environment) v.SetConfigType("json") v.SetEnvPrefix("restful") v.AutomaticEnv() v.SetDefault("jwt_signing_method", "HS256") v.SetDefault("error_file", "config/errors.yaml") v.SetDefault("server_port", 1530) v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) for _, path := range configpaths { v.AddConfigPath(path) } if err := v.ReadInConfig(); err != nil { return fmt.Errorf("Failed to read the configuration file: %s", err) } if err := v.Unmarshal(&amp;Config); err != nil { return err } return Config.Validate() } </code></pre> <p>In the <code>Validate</code> function, I decided to check the <code>Config</code> struct, and this is what I got:</p> <p><code>Config: {config/errors.yaml 1530 RESTFUL_APP_DSN HS256 RESTFUL_APP_JWT_SIGNING_KEY RESTFUL_APP_JWT_VERIFICATION_KEY}</code></p>
0
1,664
Representing an Abstract Syntax Tree in C
<p>I'm implementing a compiler for a simple toy language in C. I have a working scanner and parser, and a reasonable background on the conceptual function/construction of an AST. My question is related to the specific way to represent an AST in C. I've come across three styles pretty frequently in different texts/resources online:</p> <p><strong>One struct per type of node.</strong></p> <p>This has a base node "class"(struct) that is the first field in all the child structs. The base node contains an enum that stores the type of node(constant, binary operator, assignment, etc). Members of the struct are accessed using a set of macros, with one set per struct. It looks something like this:</p> <pre><code>struct ast_node_base { enum {CONSTANT, ADD, SUB, ASSIGNMENT} class; }; struct ast_node_constant { struct ast_node_base *base; int value; }; struct ast_node_add { struct ast_node_base *base; struct ast_node_base *left; struct ast_node_base *right; }; struct ast_node_assign { struct ast_node_base *base; struct ast_node_base *left; struct ast_node_base *right; }; #define CLASS(node) ((ast_node_base*)node)-&gt;class; #define ADD_LEFT(node) ((ast_node_add*)node)-&gt;left; #define ADD_RIGHT(node) ((ast_node_add*)node)-&gt;right; #define ASSIGN_LEFT(node) ((ast_node_assign*)node)-&gt;left; #define ASSIGN_RIGHT(node) ((ast_node_assign*)node)-&gt;right; </code></pre> <p><strong>One struct per layout of node.</strong></p> <p>This appears to be mostly the same as the above layout, except instead of having ast_node_add and ast_node_assign it would have an ast_node_binary to represent both, because the layout of the two structs is the same and they only differ by the contents of base->class. The advantage to this seems to be a more uniform set of macros(LEFT(node) for all nodes with a left and right instead of one pair of macros per), but the disadvantage seems that the C type checking won't be as useful(there would be no way to detect an ast_node_assign where there should only be an ast_node_add, for example).</p> <p><strong>One struct total, with a union to hold different types of node data.</strong></p> <p>A better explanation of this than I can give can be found <a href="http://lambda.uta.edu/cse5317/notes/node25.html">here</a>. Using the types from the previous example it would look like:</p> <pre><code>struct ast_node { enum { CONSTANT, ADD, SUB, ASSIGNMENT } class; union { int value; struct { struct ast_node* left; struct ast_node* right; } op; }; </code></pre> <p>I'm inclined to like the third option the most because it makes recursive traversal much easier(in that lots of pointer casting is avoided in favor of the union), but it also doesn't take advantage of C type checking. The first option seems the most dangerous in that it relies on pointers to structs being cast to access the member of any node(even different members of the same node requiring different cases to access(base vs. left)), but these casts are type checked so that might be moot. The second option to me seems like the worst of both worlds, although maybe I'm missing something.</p> <p><strong>Which of these three schemes are the best, and why? Is there a better fourth option I haven't come across yet?</strong> I'm assuming none of them are a "one size fits all" solution, so if it matters the language I'm implementing is a statically typed imperative language, almost a small subset of C.</p> <p>A specific question I have about the third(union) layout. <strong>If I use only the value field, will there be empty space following the value to accommodate for the possibility of op being written to?</strong></p>
0
1,130
UIView Round Corners with Shadow
<p>I am trying to display a UIView with round corners and with a drop shadow. But the problem is that maskToBounds property only works for either of the case. </p> <p>If maskToBounds is YES then round corners show up and when NO then shadow shows up. Here is the implementation but it only displays round corners with no shadow: </p> <pre><code>[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_gradient.jpeg"]]]; self.view.layer.masksToBounds = YES; self.view.layer.opaque = NO; self.view.layer.cornerRadius = 15.0f; self.view.layer.shadowColor = [UIColor blackColor].CGColor; self.view.layer.shadowRadius = 5.0; self.view.layer.shadowOffset = CGSizeMake(3.0, 3.0); self.view.layer.shadowOpacity = 0.9f; </code></pre> <p>ideas!</p> <p>NOTE: I have read and implemented the code in the following thread but it does not work: <a href="https://stackoverflow.com/questions/4754392/uiview-with-rounded-corners-and-drop-shadow">UIView with rounded corners and drop shadow?</a></p> <p><strong>UPDATE 1:</strong> </p> <p>I tried to create two separate views. One will represent the radius and one will represent the shadow. The problem is that is creates the shadow on top of the radius view as shown in the screenshot below: </p> <p><img src="https://i.stack.imgur.com/1EiIh.png" alt="enter image description here"></p> <p>H</p> <pre><code>ere is the code: self.view.layer.masksToBounds = YES; self.view.layer.opaque = NO; self.view.layer.cornerRadius = 15.0f; // self.view.backgroundColor = [UIColor clearColor]; self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_gradient.jpeg"]]; // UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; shadowView.layer.shadowColor = [UIColor blackColor].CGColor; shadowView.layer.shadowRadius = 2.0; shadowView.backgroundColor = [UIColor clearColor]; shadowView.layer.shadowOffset = CGSizeMake(3.0, 3.0); shadowView.layer.shadowOpacity = 0.9f; shadowView.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 100, 100)].CGPath; [self.view addSubview:shadowView]; </code></pre> <p>UPDATE 2: </p> <p>Inverted still does not work. No round corners are created. </p> <pre><code>UIView *roundCornerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; roundCornerView.layer.masksToBounds = YES; roundCornerView.layer.opaque = NO; roundCornerView.layer.cornerRadius = 15.0f; self.view.layer.shadowColor = [UIColor blackColor].CGColor; self.view.layer.shadowRadius = 2.0; //self.view.backgroundColor = [UIColor clearColor]; self.view.layer.shadowOffset = CGSizeMake(3.0, 3.0); self.view.layer.shadowOpacity = 0.9f; self.view.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 100, 100)].CGPath; [self.view addSubview:roundCornerView]; </code></pre> <p><strong>SOLUTION:</strong> </p> <pre><code> UIView *roundCornerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; roundCornerView.layer.masksToBounds = YES; roundCornerView.layer.opaque = NO; roundCornerView.layer.cornerRadius = 15.0f; roundCornerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_gradient.jpeg"]]; self.view.layer.shadowColor = [UIColor blackColor].CGColor; self.view.layer.shadowRadius = 2.0; self.view.backgroundColor = [UIColor clearColor]; self.view.layer.shadowOffset = CGSizeMake(3.0, 3.0); self.view.layer.shadowOpacity = 0.9f; //self.view.layer.shadowPath = [UIBezierPath // bezierPathWithRect:CGRectMake(0, 0, 100, 100)].CGPath; [self.view addSubview:roundCornerView]; </code></pre>
0
1,624
zf2 navigation - 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for navigation'
<p>Hy everybody!</p> <p>I am learning zf2, and trying to set up a navigation panel(based on: <a href="https://stackoverflow.com/questions/11397226/zend-framework-2-zend-navigation">Zend Framework 2: Zend_Navigation</a>), but the answer from the computer is still:</p> <p>An error occurred An error occurred during execution; please try again later. Additional information: Zend\ServiceManager\Exception\ServiceNotFoundException File: /var/www/zf2-tutorial/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:453 Message: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for navigation</p> <p>The module.config.php contain:</p> <pre><code> 'servicemanager' =&gt; array( 'factories' =&gt; array( 'navigation' =&gt; function($sm) { $config = $sm-&gt;get('Config'); $navigation = new \Zend\Navigation\Navigation($config-&gt;get('navigation')); return $navigation; } ), ), </code></pre> <p>I have an application.global.php in the main config/autoload folder which is looks like:</p> <pre><code>&lt;?php return array( // All navigation-related configuration is collected in the 'navigation' key 'navigation' =&gt; array( // The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key 'default' =&gt; array( // And finally, here is where we define our page hierarchy 'Album' =&gt; array( 'label' =&gt; 'Albumlista', 'route' =&gt; 'album', 'action' =&gt; 'index', 'pages' =&gt; array( array( 'label' =&gt; 'Add', 'route' =&gt; 'album', 'action' =&gt; 'add' ) ) ), 'Application' =&gt; array( 'label' =&gt; 'Alap alkalmazás', 'route' =&gt; 'application', 'action' =&gt; 'index', ) ), ), ); </code></pre> <p>And from the controller i give this command:</p> <pre><code>$config = $this-&gt;getServiceLocator()-&gt;get('navigation'); </code></pre> <p>Could somebody help me to solve this problem? I read about <a href="http://adam.lundrigan.ca/2012/07/quick-and-dirty-zf2-zend-navigation/" rel="nofollow noreferrer">http://adam.lundrigan.ca/2012/07/quick-and-dirty-zf2-zend-navigation/</a> , I tried it, and I did it, but I would like to combine with acl so that I wrote this question.</p> <p>Thanks for every help!</p>
0
1,350
How to diagnose a KERN_PROTECTION_FAILURE
<p>I am getting an interesting crash that I can never seem to replicate on the simulator:</p> <pre><code>Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x00000008 Crashed Thread: 0 Thread 0 Crashed: 0 libobjc.A.dylib 0x3212e86c 0x3212c000 + 10348 1 StockTwits 0x00016b06 0x1000 + 88838 2 Foundation 0x30718422 0x306db000 + 250914 3 Foundation 0x307183a4 0x306db000 + 250788 4 CFNetwork 0x30933e74 0x30923000 + 69236 5 CFNetwork 0x30927b70 0x30923000 + 19312 6 CFNetwork 0x30927e62 0x30923000 + 20066 7 CFNetwork 0x30927a60 0x30923000 + 19040 8 CFNetwork 0x30927a12 0x30923000 + 18962 9 CFNetwork 0x30927990 0x30923000 + 18832 10 CFNetwork 0x3092790e 0x30923000 + 18702 11 CoreFoundation 0x30352a86 0x302e1000 + 465542 12 CoreFoundation 0x30354768 0x302e1000 + 472936 13 CoreFoundation 0x30355504 0x302e1000 + 476420 14 CoreFoundation 0x302fe8e4 0x302e1000 + 121060 15 CoreFoundation 0x302fe7ec 0x302e1000 + 120812 16 GraphicsServices 0x31a776e8 0x31a74000 + 14056 17 GraphicsServices 0x31a77794 0x31a74000 + 14228 18 UIKit 0x323272a0 0x32321000 + 25248 19 UIKit 0x32325e10 0x32321000 + 19984 20 StockTwits 0x00002fd4 0x1000 + 8148 21 StockTwits 0x00002fa4 0x1000 + 8100 </code></pre> <p>I have NSZombies enabled as well as stack logging. Ran through the static analyzer to make sure all objects are retained and released properly, though I have a feeling it is still related to retain/releasing.</p> <p>Thoughts?</p>
0
1,050
OpenCV: how to use createBackgroundSubtractorMOG
<p>I was trying to go through this tutorial på OpenCV.org:</p> <p><a href="http://docs.opencv.org/trunk/doc/tutorials/video/background_subtraction/background_subtraction.html#background-subtraction" rel="noreferrer">http://docs.opencv.org/trunk/doc/tutorials/video/background_subtraction/background_subtraction.html#background-subtraction</a></p> <p>The MOG pointer is initialized as</p> <pre><code>Ptr&lt;BackgroundSubtractor&gt; pMOG; //MOG Background subtractor </code></pre> <p>and in main, it is used in the following manner:</p> <pre><code>pMOG = createBackgroundSubtractorMOG(); </code></pre> <p>However, this yields the following error:</p> <pre><code> Error: Identifier "createBackgroundSubtractorMOG" is undefined </code></pre> <p>Also, when the background model is to be updated, the following command is used:</p> <pre><code>pMOG-&gt;apply(frame, fgMaskMOG); </code></pre> <p>Which in turn yields the following error:</p> <pre><code> Error: class "cv::BackgroundSubtractor" has no member "apply" </code></pre> <p>Any idea of what can be done about this? Many thanks in advance!</p> <p>Here is the entire tutorial code:</p> <pre class="lang-c prettyprint-override"><code>//opencv #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/video/background_segm.hpp&gt; //C #include &lt;stdio.h&gt; //C++ #include &lt;iostream&gt; #include &lt;sstream&gt; using namespace cv; using namespace std; //global variables Mat frame; //current frame Mat fgMaskMOG; //fg mask generated by MOG method Mat fgMaskMOG2; //fg mask fg mask generated by MOG2 method Ptr&lt;BackgroundSubtractor&gt; pMOG; //MOG Background subtractor Ptr&lt;BackgroundSubtractor&gt; pMOG2; //MOG2 Background subtractor int keyboard; //function declarations void help(); void processVideo(char* videoFilename); void processImages(char* firstFrameFilename); void help() { cout &lt;&lt; "--------------------------------------------------------------------------" &lt;&lt; endl &lt;&lt; "This program shows how to use background subtraction methods provided by " &lt;&lt; endl &lt;&lt; " OpenCV. You can process both videos (-vid) and images (-img)." &lt;&lt; endl &lt;&lt; endl &lt;&lt; "Usage:" &lt;&lt; endl &lt;&lt; "./bs {-vid &lt;video filename&gt;|-img &lt;image filename&gt;}" &lt;&lt; endl &lt;&lt; "for example: ./bs -vid video.avi" &lt;&lt; endl &lt;&lt; "or: ./bs -img /data/images/1.png" &lt;&lt; endl &lt;&lt; "--------------------------------------------------------------------------" &lt;&lt; endl &lt;&lt; endl; } int main(int argc, char* argv[]) { //print help information help(); //check for the input parameter correctness if(argc != 3) { cerr &lt;&lt;"Incorret input list" &lt;&lt; endl; cerr &lt;&lt;"exiting..." &lt;&lt; endl; return EXIT_FAILURE; } //create GUI windows namedWindow("Frame"); namedWindow("FG Mask MOG"); namedWindow("FG Mask MOG 2"); //create Background Subtractor objects pMOG = createBackgroundSubtractorMOG(); //MOG approach pMOG2 = createBackgroundSubtractorMOG2(); //MOG2 approach if(strcmp(argv[1], "-vid") == 0) { //input data coming from a video processVideo(argv[2]); } else if(strcmp(argv[1], "-img") == 0) { //input data coming from a sequence of images processImages(argv[2]); } else { //error in reading input parameters cerr &lt;&lt;"Please, check the input parameters." &lt;&lt; endl; cerr &lt;&lt;"Exiting..." &lt;&lt; endl; return EXIT_FAILURE; } //destroy GUI windows destroyAllWindows(); return EXIT_SUCCESS; } void processVideo(char* videoFilename) { //create the capture object VideoCapture capture(videoFilename); if(!capture.isOpened()){ //error in opening the video input cerr &lt;&lt; "Unable to open video file: " &lt;&lt; videoFilename &lt;&lt; endl; exit(EXIT_FAILURE); } //read input data. ESC or 'q' for quitting while( (char)keyboard != 'q' &amp;&amp; (char)keyboard != 27 ){ //read the current frame if(!capture.read(frame)) { cerr &lt;&lt; "Unable to read next frame." &lt;&lt; endl; cerr &lt;&lt; "Exiting..." &lt;&lt; endl; exit(EXIT_FAILURE); } //update the background model pMOG-&gt;apply(frame, fgMaskMOG); pMOG2-&gt;apply(frame, fgMaskMOG2); //get the frame number and write it on the current frame stringstream ss; rectangle(frame, cv::Point(10, 2), cv::Point(100,20), cv::Scalar(255,255,255), -1); ss &lt;&lt; capture.get(CAP_PROP_POS_FRAMES); string frameNumberString = ss.str(); putText(frame, frameNumberString.c_str(), cv::Point(15, 15), FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0)); //show the current frame and the fg masks imshow("Frame", frame); imshow("FG Mask MOG", fgMaskMOG); imshow("FG Mask MOG 2", fgMaskMOG2); //get the input from the keyboard keyboard = waitKey( 30 ); } //delete capture object capture.release(); } void processImages(char* fistFrameFilename) { //read the first file of the sequence frame = imread(fistFrameFilename); if(!frame.data){ //error in opening the first image cerr &lt;&lt; "Unable to open first image frame: " &lt;&lt; fistFrameFilename &lt;&lt; endl; exit(EXIT_FAILURE); } //current image filename string fn(fistFrameFilename); //read input data. ESC or 'q' for quitting while( (char)keyboard != 'q' &amp;&amp; (char)keyboard != 27 ){ //update the background model pMOG-&gt;apply(frame, fgMaskMOG); pMOG2-&gt;apply(frame, fgMaskMOG2); //get the frame number and write it on the current frame size_t index = fn.find_last_of("/"); if(index == string::npos) { index = fn.find_last_of("\\"); } size_t index2 = fn.find_last_of("."); string prefix = fn.substr(0,index+1); string suffix = fn.substr(index2); string frameNumberString = fn.substr(index+1, index2-index-1); istringstream iss(frameNumberString); int frameNumber = 0; iss &gt;&gt; frameNumber; rectangle(frame, cv::Point(10, 2), cv::Point(100,20), cv::Scalar(255,255,255), -1); putText(frame, frameNumberString.c_str(), cv::Point(15, 15), FONT_HERSHEY_SIMPLEX, 0.5 , cv::Scalar(0,0,0)); //show the current frame and the fg masks imshow("Frame", frame); imshow("FG Mask MOG", fgMaskMOG); imshow("FG Mask MOG 2", fgMaskMOG2); //get the input from the keyboard keyboard = waitKey( 30 ); //search for the next image in the sequence ostringstream oss; oss &lt;&lt; (frameNumber + 1); string nextFrameNumberString = oss.str(); string nextFrameFilename = prefix + nextFrameNumberString + suffix; //read the next frame frame = imread(nextFrameFilename); if(!frame.data){ //error in opening the next image in the sequence cerr &lt;&lt; "Unable to open image frame: " &lt;&lt; nextFrameFilename &lt;&lt; endl; exit(EXIT_FAILURE); } //update the path of the current frame fn.assign(nextFrameFilename); } } </code></pre>
0
3,019
rgb to yuv420 algorithm efficiency
<p>I wrote an algorithm to convert a RGB image to a YUV420. I spend a long time trying to make it faster but I haven't find any other way to boost its efficiency, so now I turn to you so you can tell me if this is as good as I get, or if there's another more efficient way to do it (the algorithm is in C++ but C and assembler are also options)</p> <pre><code>namespace { // lookup tables int lookup_m_94[] = { 0, -94, -188, -282, -376, -470, -564, -658, -752, -846, -940, -1034, -1128, -1222, -1316, -1410, -1504, -1598, -1692, -1786, -1880, -1974, -2068, -2162, -2256, -2350, -2444, -2538, -2632, -2726, -2820, -2914, -3008, -3102, -3196, -3290, -3384, -3478, -3572, -3666, -3760, -3854, -3948, -4042, -4136, -4230, -4324, -4418, -4512, -4606, -4700, -4794, -4888, -4982, -5076, -5170, -5264, -5358, -5452, -5546, -5640, -5734, -5828, -5922, -6016, -6110, -6204, -6298, -6392, -6486, -6580, -6674, -6768, -6862, -6956, -7050, -7144, -7238, -7332, -7426, -7520, -7614, -7708, -7802, -7896, -7990, -8084, -8178, -8272, -8366, -8460, -8554, -8648, -8742, -8836, -8930, -9024, -9118, -9212, -9306, -9400, -9494, -9588, -9682, -9776, -9870, -9964, -10058, -10152, -10246, -10340, -10434, -10528, -10622, -10716, -10810, -10904, -10998, -11092, -11186, -11280, -11374, -11468, -11562, -11656, -11750, -11844, -11938, -12032, -12126, -12220, -12314, -12408, -12502, -12596, -12690, -12784, -12878, -12972, -13066, -13160, -13254, -13348, -13442, -13536, -13630, -13724, -13818, -13912, -14006, -14100, -14194, -14288, -14382, -14476, -14570, -14664, -14758, -14852, -14946, -15040, -15134, -15228, -15322, -15416, -15510, -15604, -15698, -15792, -15886, -15980, -16074, -16168, -16262, -16356, -16450, -16544, -16638, -16732, -16826, -16920, -17014, -17108, -17202, -17296, -17390, -17484, -17578, -17672, -17766, -17860, -17954, -18048, -18142, -18236, -18330, -18424, -18518, -18612, -18706, -18800, -18894, -18988, -19082, -19176, -19270, -19364, -19458, -19552, -19646, -19740, -19834, -19928, -20022, -20116, -20210, -20304, -20398, -20492, -20586, -20680, -20774, -20868, -20962, -21056, -21150, -21244, -21338, -21432, -21526, -21620, -21714, -21808, -21902, -21996, -22090, -22184, -22278, -22372, -22466, -22560, -22654, -22748, -22842, -22936, -23030, -23124, -23218, -23312, -23406, -23500, -23594, -23688, -23782, -23876, -23970 }; int lookup_m_74[] = { 0, -74, -148, -222, -296, -370, -444, -518, -592, -666, -740, -814, -888, -962, -1036, -1110, -1184, -1258, -1332, -1406, -1480, -1554, -1628, -1702, -1776, -1850, -1924, -1998, -2072, -2146, -2220, -2294, -2368, -2442, -2516, -2590, -2664, -2738, -2812, -2886, -2960, -3034, -3108, -3182, -3256, -3330, -3404, -3478, -3552, -3626, -3700, -3774, -3848, -3922, -3996, -4070, -4144, -4218, -4292, -4366, -4440, -4514, -4588, -4662, -4736, -4810, -4884, -4958, -5032, -5106, -5180, -5254, -5328, -5402, -5476, -5550, -5624, -5698, -5772, -5846, -5920, -5994, -6068, -6142, -6216, -6290, -6364, -6438, -6512, -6586, -6660, -6734, -6808, -6882, -6956, -7030, -7104, -7178, -7252, -7326, -7400, -7474, -7548, -7622, -7696, -7770, -7844, -7918, -7992, -8066, -8140, -8214, -8288, -8362, -8436, -8510, -8584, -8658, -8732, -8806, -8880, -8954, -9028, -9102, -9176, -9250, -9324, -9398, -9472, -9546, -9620, -9694, -9768, -9842, -9916, -9990, -10064, -10138, -10212, -10286, -10360, -10434, -10508, -10582, -10656, -10730, -10804, -10878, -10952, -11026, -11100, -11174, -11248, -11322, -11396, -11470, -11544, -11618, -11692, -11766, -11840, -11914, -11988, -12062, -12136, -12210, -12284, -12358, -12432, -12506, -12580, -12654, -12728, -12802, -12876, -12950, -13024, -13098, -13172, -13246, -13320, -13394, -13468, -13542, -13616, -13690, -13764, -13838, -13912, -13986, -14060, -14134, -14208, -14282, -14356, -14430, -14504, -14578, -14652, -14726, -14800, -14874, -14948, -15022, -15096, -15170, -15244, -15318, -15392, -15466, -15540, -15614, -15688, -15762, -15836, -15910, -15984, -16058, -16132, -16206, -16280, -16354, -16428, -16502, -16576, -16650, -16724, -16798, -16872, -16946, -17020, -17094, -17168, -17242, -17316, -17390, -17464, -17538, -17612, -17686, -17760, -17834, -17908, -17982, -18056, -18130, -18204, -18278, -18352, -18426, -18500, -18574, -18648, -18722, -18796, -18870 }; int lookup_m_38[] = { 0, -38, -76, -114, -152, -190, -228, -266, -304, -342, -380, -418, -456, -494, -532, -570, -608, -646, -684, -722, -760, -798, -836, -874, -912, -950, -988, -1026, -1064, -1102, -1140, -1178, -1216, -1254, -1292, -1330, -1368, -1406, -1444, -1482, -1520, -1558, -1596, -1634, -1672, -1710, -1748, -1786, -1824, -1862, -1900, -1938, -1976, -2014, -2052, -2090, -2128, -2166, -2204, -2242, -2280, -2318, -2356, -2394, -2432, -2470, -2508, -2546, -2584, -2622, -2660, -2698, -2736, -2774, -2812, -2850, -2888, -2926, -2964, -3002, -3040, -3078, -3116, -3154, -3192, -3230, -3268, -3306, -3344, -3382, -3420, -3458, -3496, -3534, -3572, -3610, -3648, -3686, -3724, -3762, -3800, -3838, -3876, -3914, -3952, -3990, -4028, -4066, -4104, -4142, -4180, -4218, -4256, -4294, -4332, -4370, -4408, -4446, -4484, -4522, -4560, -4598, -4636, -4674, -4712, -4750, -4788, -4826, -4864, -4902, -4940, -4978, -5016, -5054, -5092, -5130, -5168, -5206, -5244, -5282, -5320, -5358, -5396, -5434, -5472, -5510, -5548, -5586, -5624, -5662, -5700, -5738, -5776, -5814, -5852, -5890, -5928, -5966, -6004, -6042, -6080, -6118, -6156, -6194, -6232, -6270, -6308, -6346, -6384, -6422, -6460, -6498, -6536, -6574, -6612, -6650, -6688, -6726, -6764, -6802, -6840, -6878, -6916, -6954, -6992, -7030, -7068, -7106, -7144, -7182, -7220, -7258, -7296, -7334, -7372, -7410, -7448, -7486, -7524, -7562, -7600, -7638, -7676, -7714, -7752, -7790, -7828, -7866, -7904, -7942, -7980, -8018, -8056, -8094, -8132, -8170, -8208, -8246, -8284, -8322, -8360, -8398, -8436, -8474, -8512, -8550, -8588, -8626, -8664, -8702, -8740, -8778, -8816, -8854, -8892, -8930, -8968, -9006, -9044, -9082, -9120, -9158, -9196, -9234, -9272, -9310, -9348, -9386, -9424, -9462, -9500, -9538, -9576, -9614, -9652, -9690 }; int lookup_m_18[] = { 0, -18, -36, -54, -72, -90, -108, -126, -144, -162, -180, -198, -216, -234, -252, -270, -288, -306, -324, -342, -360, -378, -396, -414, -432, -450, -468, -486, -504, -522, -540, -558, -576, -594, -612, -630, -648, -666, -684, -702, -720, -738, -756, -774, -792, -810, -828, -846, -864, -882, -900, -918, -936, -954, -972, -990, -1008, -1026, -1044, -1062, -1080, -1098, -1116, -1134, -1152, -1170, -1188, -1206, -1224, -1242, -1260, -1278, -1296, -1314, -1332, -1350, -1368, -1386, -1404, -1422, -1440, -1458, -1476, -1494, -1512, -1530, -1548, -1566, -1584, -1602, -1620, -1638, -1656, -1674, -1692, -1710, -1728, -1746, -1764, -1782, -1800, -1818, -1836, -1854, -1872, -1890, -1908, -1926, -1944, -1962, -1980, -1998, -2016, -2034, -2052, -2070, -2088, -2106, -2124, -2142, -2160, -2178, -2196, -2214, -2232, -2250, -2268, -2286, -2304, -2322, -2340, -2358, -2376, -2394, -2412, -2430, -2448, -2466, -2484, -2502, -2520, -2538, -2556, -2574, -2592, -2610, -2628, -2646, -2664, -2682, -2700, -2718, -2736, -2754, -2772, -2790, -2808, -2826, -2844, -2862, -2880, -2898, -2916, -2934, -2952, -2970, -2988, -3006, -3024, -3042, -3060, -3078, -3096, -3114, -3132, -3150, -3168, -3186, -3204, -3222, -3240, -3258, -3276, -3294, -3312, -3330, -3348, -3366, -3384, -3402, -3420, -3438, -3456, -3474, -3492, -3510, -3528, -3546, -3564, -3582, -3600, -3618, -3636, -3654, -3672, -3690, -3708, -3726, -3744, -3762, -3780, -3798, -3816, -3834, -3852, -3870, -3888, -3906, -3924, -3942, -3960, -3978, -3996, -4014, -4032, -4050, -4068, -4086, -4104, -4122, -4140, -4158, -4176, -4194, -4212, -4230, -4248, -4266, -4284, -4302, -4320, -4338, -4356, -4374, -4392, -4410, -4428, -4446, -4464, -4482, -4500, -4518, -4536, -4554, -4572, -4590 }; int lookup25[] = { 0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525, 550, 575, 600, 625, 650, 675, 700, 725, 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725, 1750, 1775, 1800, 1825, 1850, 1875, 1900, 1925, 1950, 1975, 2000, 2025, 2050, 2075, 2100, 2125, 2150, 2175, 2200, 2225, 2250, 2275, 2300, 2325, 2350, 2375, 2400, 2425, 2450, 2475, 2500, 2525, 2550, 2575, 2600, 2625, 2650, 2675, 2700, 2725, 2750, 2775, 2800, 2825, 2850, 2875, 2900, 2925, 2950, 2975, 3000, 3025, 3050, 3075, 3100, 3125, 3150, 3175, 3200, 3225, 3250, 3275, 3300, 3325, 3350, 3375, 3400, 3425, 3450, 3475, 3500, 3525, 3550, 3575, 3600, 3625, 3650, 3675, 3700, 3725, 3750, 3775, 3800, 3825, 3850, 3875, 3900, 3925, 3950, 3975, 4000, 4025, 4050, 4075, 4100, 4125, 4150, 4175, 4200, 4225, 4250, 4275, 4300, 4325, 4350, 4375, 4400, 4425, 4450, 4475, 4500, 4525, 4550, 4575, 4600, 4625, 4650, 4675, 4700, 4725, 4750, 4775, 4800, 4825, 4850, 4875, 4900, 4925, 4950, 4975, 5000, 5025, 5050, 5075, 5100, 5125, 5150, 5175, 5200, 5225, 5250, 5275, 5300, 5325, 5350, 5375, 5400, 5425, 5450, 5475, 5500, 5525, 5550, 5575, 5600, 5625, 5650, 5675, 5700, 5725, 5750, 5775, 5800, 5825, 5850, 5875, 5900, 5925, 5950, 5975, 6000, 6025, 6050, 6075, 6100, 6125, 6150, 6175, 6200, 6225, 6250, 6275, 6300, 6325, 6350, 6375 }; int lookup66[] = { 0, 66, 132, 198, 264, 330, 396, 462, 528, 594, 660, 726, 792, 858, 924, 990, 1056, 1122, 1188, 1254, 1320, 1386, 1452, 1518, 1584, 1650, 1716, 1782, 1848, 1914, 1980, 2046, 2112, 2178, 2244, 2310, 2376, 2442, 2508, 2574, 2640, 2706, 2772, 2838, 2904, 2970, 3036, 3102, 3168, 3234, 3300, 3366, 3432, 3498, 3564, 3630, 3696, 3762, 3828, 3894, 3960, 4026, 4092, 4158, 4224, 4290, 4356, 4422, 4488, 4554, 4620, 4686, 4752, 4818, 4884, 4950, 5016, 5082, 5148, 5214, 5280, 5346, 5412, 5478, 5544, 5610, 5676, 5742, 5808, 5874, 5940, 6006, 6072, 6138, 6204, 6270, 6336, 6402, 6468, 6534, 6600, 6666, 6732, 6798, 6864, 6930, 6996, 7062, 7128, 7194, 7260, 7326, 7392, 7458, 7524, 7590, 7656, 7722, 7788, 7854, 7920, 7986, 8052, 8118, 8184, 8250, 8316, 8382, 8448, 8514, 8580, 8646, 8712, 8778, 8844, 8910, 8976, 9042, 9108, 9174, 9240, 9306, 9372, 9438, 9504, 9570, 9636, 9702, 9768, 9834, 9900, 9966, 10032, 10098, 10164, 10230, 10296, 10362, 10428, 10494, 10560, 10626, 10692, 10758, 10824, 10890, 10956, 11022, 11088, 11154, 11220, 11286, 11352, 11418, 11484, 11550, 11616, 11682, 11748, 11814, 11880, 11946, 12012, 12078, 12144, 12210, 12276, 12342, 12408, 12474, 12540, 12606, 12672, 12738, 12804, 12870, 12936, 13002, 13068, 13134, 13200, 13266, 13332, 13398, 13464, 13530, 13596, 13662, 13728, 13794, 13860, 13926, 13992, 14058, 14124, 14190, 14256, 14322, 14388, 14454, 14520, 14586, 14652, 14718, 14784, 14850, 14916, 14982, 15048, 15114, 15180, 15246, 15312, 15378, 15444, 15510, 15576, 15642, 15708, 15774, 15840, 15906, 15972, 16038, 16104, 16170, 16236, 16302, 16368, 16434, 16500, 16566, 16632, 16698, 16764, 16830 }; int lookup112[] = { 0, 112, 224, 336, 448, 560, 672, 784, 896, 1008, 1120, 1232, 1344, 1456, 1568, 1680, 1792, 1904, 2016, 2128, 2240, 2352, 2464, 2576, 2688, 2800, 2912, 3024, 3136, 3248, 3360, 3472, 3584, 3696, 3808, 3920, 4032, 4144, 4256, 4368, 4480, 4592, 4704, 4816, 4928, 5040, 5152, 5264, 5376, 5488, 5600, 5712, 5824, 5936, 6048, 6160, 6272, 6384, 6496, 6608, 6720, 6832, 6944, 7056, 7168, 7280, 7392, 7504, 7616, 7728, 7840, 7952, 8064, 8176, 8288, 8400, 8512, 8624, 8736, 8848, 8960, 9072, 9184, 9296, 9408, 9520, 9632, 9744, 9856, 9968, 10080, 10192, 10304, 10416, 10528, 10640, 10752, 10864, 10976, 11088, 11200, 11312, 11424, 11536, 11648, 11760, 11872, 11984, 12096, 12208, 12320, 12432, 12544, 12656, 12768, 12880, 12992, 13104, 13216, 13328, 13440, 13552, 13664, 13776, 13888, 14000, 14112, 14224, 14336, 14448, 14560, 14672, 14784, 14896, 15008, 15120, 15232, 15344, 15456, 15568, 15680, 15792, 15904, 16016, 16128, 16240, 16352, 16464, 16576, 16688, 16800, 16912, 17024, 17136, 17248, 17360, 17472, 17584, 17696, 17808, 17920, 18032, 18144, 18256, 18368, 18480, 18592, 18704, 18816, 18928, 19040, 19152, 19264, 19376, 19488, 19600, 19712, 19824, 19936, 20048, 20160, 20272, 20384, 20496, 20608, 20720, 20832, 20944, 21056, 21168, 21280, 21392, 21504, 21616, 21728, 21840, 21952, 22064, 22176, 22288, 22400, 22512, 22624, 22736, 22848, 22960, 23072, 23184, 23296, 23408, 23520, 23632, 23744, 23856, 23968, 24080, 24192, 24304, 24416, 24528, 24640, 24752, 24864, 24976, 25088, 25200, 25312, 25424, 25536, 25648, 25760, 25872, 25984, 26096, 26208, 26320, 26432, 26544, 26656, 26768, 26880, 26992, 27104, 27216, 27328, 27440, 27552, 27664, 27776, 27888, 28000, 28112, 28224, 28336, 28448, 28560 }; int lookup129[] = { 0, 129, 258, 387, 516, 645, 774, 903, 1032, 1161, 1290, 1419, 1548, 1677, 1806, 1935, 2064, 2193, 2322, 2451, 2580, 2709, 2838, 2967, 3096, 3225, 3354, 3483, 3612, 3741, 3870, 3999, 4128, 4257, 4386, 4515, 4644, 4773, 4902, 5031, 5160, 5289, 5418, 5547, 5676, 5805, 5934, 6063, 6192, 6321, 6450, 6579, 6708, 6837, 6966, 7095, 7224, 7353, 7482, 7611, 7740, 7869, 7998, 8127, 8256, 8385, 8514, 8643, 8772, 8901, 9030, 9159, 9288, 9417, 9546, 9675, 9804, 9933, 10062, 10191, 10320, 10449, 10578, 10707, 10836, 10965, 11094, 11223, 11352, 11481, 11610, 11739, 11868, 11997, 12126, 12255, 12384, 12513, 12642, 12771, 12900, 13029, 13158, 13287, 13416, 13545, 13674, 13803, 13932, 14061, 14190, 14319, 14448, 14577, 14706, 14835, 14964, 15093, 15222, 15351, 15480, 15609, 15738, 15867, 15996, 16125, 16254, 16383, 16512, 16641, 16770, 16899, 17028, 17157, 17286, 17415, 17544, 17673, 17802, 17931, 18060, 18189, 18318, 18447, 18576, 18705, 18834, 18963, 19092, 19221, 19350, 19479, 19608, 19737, 19866, 19995, 20124, 20253, 20382, 20511, 20640, 20769, 20898, 21027, 21156, 21285, 21414, 21543, 21672, 21801, 21930, 22059, 22188, 22317, 22446, 22575, 22704, 22833, 22962, 23091, 23220, 23349, 23478, 23607, 23736, 23865, 23994, 24123, 24252, 24381, 24510, 24639, 24768, 24897, 25026, 25155, 25284, 25413, 25542, 25671, 25800, 25929, 26058, 26187, 26316, 26445, 26574, 26703, 26832, 26961, 27090, 27219, 27348, 27477, 27606, 27735, 27864, 27993, 28122, 28251, 28380, 28509, 28638, 28767, 28896, 29025, 29154, 29283, 29412, 29541, 29670, 29799, 29928, 30057, 30186, 30315, 30444, 30573, 30702, 30831, 30960, 31089, 31218, 31347, 31476, 31605, 31734, 31863, 31992, 32121, 32250, 32379, 32508, 32637, 32766, 32895 }; } void Bitmap2Yuv420p(boost::uint8_t *destination, boost::uint8_t *rgb, const int &amp;width, const int &amp;height) { boost::uint8_t *y; boost::uint8_t *u; boost::uint8_t *v; boost::uint8_t *r; boost::uint8_t *g; boost::uint8_t *b; std::size_t image_size = width * height; std::size_t upos = image_size; std::size_t vpos = upos + upos / 4; for (std::size_t i = 0; i &lt; image_size; ++i) { r = rgb + 3 * i; g = rgb + 3 * i + 1; b = rgb + 3 * i + 2; y = destination + i; *y = ((lookup66[*r] + lookup129[*g] + lookup25[*b]) &gt;&gt; 8) + 16; if (!((i / width) % 2) &amp;&amp; !(i % 2)) { u = destination + upos++; v = destination + vpos++; *u = ((lookup_m_38[*r] + lookup_m_74[*g] + lookup112[*b]) &gt;&gt; 8) + 128; *v = ((lookup112[*r] + lookup_m_94[*g] + lookup_m_18[*b]) &gt;&gt; 8) + 128; } } } </code></pre>
0
10,594
How to set custom handler_name metadata for subtitle stream using FFMPEG
<p>I'm currently using <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a> to embed subtitles into my MP4 files and I am stumped trying to figure out how to custom set the "handler_name" metadata tag on my subtitle stream so I can control the name that is displayed when selecting the subtitle within a player like <a href="http://mpc-hc.org/" rel="noreferrer">MPC-HC</a> (Media Player Classic)?</p> <p>My current command to embed the subtitle is:</p> <pre><code>ffmpeg -i "video.mp4" -sub_charenc UTF-8 -i "video.srt" -c:v copy -c:a copy -c:s mov_text -metadata:s:s:0 language=eng -metadata:s:s:0 handler_name="English" -id3v2_version 3 -write_id3v1 1 "subbed_video.mp4" </code></pre> <p>Output:</p> <pre><code>C:\path\to&gt;ffmpeg -y -i "video.mp4" -sub_charenc UTF-8 -i "video.srt" -c:v copy -c:a copy -c:s mov_text -metadata:s:s:0 language="eng" -metadata:s:s:0 handler_name="English" -id3v2_version 3 -write_id3v1 1 "subbed_video.mp4" ffmpeg version N-68482-g92a596f Copyright (c) 2000-2014 the FFmpeg developers built on Dec 16 2014 02:53:08 with gcc 4.9.2 (GCC) configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-avisynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libfreetype --enable-libgme --enable-libgsm --enable libavutil 54. 15.100 / 54. 15.100 libavcodec 56. 15.100 / 56. 15.100 libavformat 56. 15.105 / 56. 15.105 libavdevice 56. 3.100 / 56. 3.100 libavfilter 5. 3.101 / 5. 3.101 libswscale 3. 1.101 / 3. 1.101 libswresample 1. 1.100 / 1. 1.100 libpostproc 53. 3.100 / 53. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf55.34.101 Duration: 01:27:44.17, start: 0.000000, bitrate: 878 kb/s Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x536 [SAR 1:1 DAR 160:67], 842 kb/s, 24 fps, 24 tbr, 12288 tbn, 48 tbc (default) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac (HE-AAC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 32 kb/s (default) Metadata: handler_name : SoundHandler Stream #0:2(eng): Subtitle: mov_text (tx3g / 0x67337874), 0 kb/s (default) Metadata: handler_name : SubtitleHandler Input #1, srt, from 'video.srt': Duration: N/A, bitrate: N/A Stream #1:0: Subtitle: subrip Output #0, mp4, to 'subbed_video.mp4': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf56.15.105 Stream #0:0(und): Video: h264 ([33][0][0][0] / 0x0021), yuv420p, 1280x536 [SAR 1:1 DAR 160:67], q=2-31, 842 kb/s, 24 fps, 24 tbr, 12288 tbn, 12288 tbc (default) Metadata: handler_name : VideoHandler Stream #0:1(und): Audio: aac ([64][0][0][0] / 0x0040), 48000 Hz, stereo, 32 kb/s (default) Metadata: handler_name : SoundHandler Stream #0:2(eng): Subtitle: mov_text ([8][0][0][0] / 0x0008) (default) Metadata: handler_name : English encoder : Lavc56.15.100 mov_text Stream mapping: Stream #0:0 -&gt; #0:0 (copy) Stream #0:1 -&gt; #0:1 (copy) Stream #0:2 -&gt; #0:2 (mov_text (native) -&gt; mov_text (native)) Press [q] to stop, [?] for help frame=126337 fps=13751 q=-1.0 Lsize= 564499kB time=01:27:44.17 bitrate= 878.5kbits/s video:541239kB audio:20564kB subtitle:39kB other streams:0kB global headers:0kB muxing overhead: 0.472881% </code></pre> <p>The command completes sucessfully, but when I run:</p> <pre><code>ffmpeg -i "C:\path\to\subbed_video.mp4" </code></pre> <p>it shows:</p> <pre><code>Stream #0:2(eng): Subtitle: mov_text (tx3g / 0x67337874), 0 kb/s (default) Metadata: handler_name : SubtitleHandler </code></pre> <p>Even though the output from the command shows:</p> <pre><code>Stream #0:2(eng): Subtitle: mov_text ([8][0][0][0] / 0x0008) (default) Metadata: handler_name : English encoder : Lavc56.15.100 mov_text </code></pre> <p>No matter what options I have tried or what order I place the -metadata tags in, this tag simply will not set with <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a>? I find it really ugly to see <strong>SubtitleHandler [eng] (tx3g) (English)</strong> within my player's menu instead of simply saying <strong>English</strong>.</p> <p>Now, I can work around this issue by using <a href="http://gpac.wp.mines-telecom.fr/mp4box/" rel="noreferrer">MP4BOX</a> to embed the subtitles into my mp4's using:</p> <pre><code>MP4BOX -lang eng -add "video.srt:name=English" "video.mp4" -out "subbed_video.mp4" </code></pre> <p>Adding <strong>"name=English"</strong> allows me to set the subtitle stream's "handler_name" to "English"; which displays perfectly in <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a> and <a href="http://mpc-hc.org/" rel="noreferrer">MPC-HC</a>, but the problem is that I do not want my app to be dependent on an additional external tool like <a href="http://gpac.wp.mines-telecom.fr/mp4box/" rel="noreferrer">MP4BOX</a> if it can be avoided?</p> <p>I would greatly appreciate any advice regarding how to properly set the "handler_name" tag on my subtitle stream using <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a>, or maybe a confirmation as to whether <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a> can even handle this tag seeing as it is not technically listed in <a href="https://www.ffmpeg.org/doxygen/2.4/group__metadata__api.html" rel="noreferrer">FFMPEG's valid metadata tag list</a>?</p> <p><em>P.S. As an alternative to <a href="https://www.ffmpeg.org/" rel="noreferrer">FFMPEG</a>, I would be willing to use <a href="http://atomicparsley.sourceforge.net/" rel="noreferrer">AtomicParsley</a> to set the "handler_name" as I will already be using it to set advanced metadata on the "subbed_video.mp4" after I embed the subtitles. It does seem like it would be possible to do with <a href="http://atomicparsley.sourceforge.net/" rel="noreferrer">AtomicParsley</a>, but I have not been able to understand half the help information with regards to setting custom ATOM's.</em></p> <p>TIA!!</p>
0
2,551
Cancel async_read due to timeout
<p>I'm trying to write a wrapper synchronous method around <code>async_read</code> to allow non blocking reads on a socket. Following several examples around internet I have developed a solution that seems to be almost right but which is not working.</p> <p>The class declares these relevant attributes and methods:</p> <pre><code>class communications_client { protected: boost::shared_ptr&lt;boost::asio::io_service&gt; _io_service; boost::shared_ptr&lt;boost::asio::ip::tcp::socket&gt; _socket; boost::array&lt;boost::uint8_t, 128&gt; _data; boost::mutex _mutex; bool _timeout_triggered; bool _message_received; boost::system::error_code _error; size_t _bytes_transferred; void handle_read(const boost::system::error_code &amp; error, size_t bytes_transferred); void handle_timeout(const boost::system::error_code &amp; error); size_t async_read_helper(unsigned short bytes_to_transfer, const boost::posix_time::time_duration &amp; timeout, boost::system::error_code &amp; error); ... } </code></pre> <p>The method <code>async_read_helper</code> is the one that encapsulates all the complexity, while the other two <code>handle_read</code>and <code>handle_timeout</code> are just the event handlers. Here is the implementation of the three methods:</p> <pre><code>void communications_client::handle_timeout(const boost::system::error_code &amp; error) { if (!error) { _mutex.lock(); _timeout_triggered = true; _error.assign(boost::system::errc::timed_out, boost::system::system_category()); _mutex.unlock(); } } void communications_client::handle_read(const boost::system::error_code &amp; error, size_t bytes_transferred) { _mutex.lock(); _message_received = true; _error = error; _bytes_transferred = bytes_transferred; _mutex.unlock(); } size_t communications_client::async_read_helper(unsigned short bytes_to_transfer, const boost::posix_time::time_duration &amp; timeout, boost::system::error_code &amp; error) { _timeout_triggered = false; _message_received = false; boost::asio::deadline_timer timer(*_io_service); timer.expires_from_now(timeout); timer.async_wait( boost::bind( &amp;communications_client::handle_timeout, this, boost::asio::placeholders::error)); boost::asio::async_read( *_socket, boost::asio::buffer(_data, 128), boost::asio::transfer_exactly(bytes_to_transfer), boost::bind( &amp;communications_client::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); while (true) { _io_service-&gt;poll_one(); if (_message_received) { timer.cancel(); break; } else if (_timeout_triggered) { _socket-&gt;cancel(); break; } } return _bytes_transferred; } </code></pre> <p>The main question I have is: why this works with a loop on <code>_io_service-&gt;poll_one()</code>and no without a loop and calling <code>_io_service-&gt;run_one()</code>? Also, I would like to know if it looks correct to anyone who is more used to work with Boost and Asio. Thank you!</p> <hr> <h2><strong>FIX PROPOSAL #1</strong></h2> <p>According to the comments done by <a href="https://stackoverflow.com/users/981959/jonathan-wakely">Jonathan Wakely</a> the loop could be replaced using <code>_io_service-&gt;run_one()</code> with a call to <a href="http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/reference/io_service/reset.html" rel="nofollow noreferrer"><code>_io_service-&gt;reset()</code></a> after the operations have finished. It should look like:</p> <pre><code>_io_service-&gt;run_one(); if (_message_received) { timer.cancel(); } else if (_timeout_triggered) { _socket-&gt;cancel(); } _io_service-&gt;reset(); </code></pre> <p>After some testing, I have checked that this kind of solution alone is not working. The <code>handle_timeout</code>method is being called continuously with the error code <code>operation_aborted</code>. How can these calls be stopped?</p> <h2><strong>FIX PROPOSAL #2</strong></h2> <p>The answer by <a href="https://stackoverflow.com/users/1053968/twsansbury">twsansbury</a> is accurate and based onto solid documentation basis. That implementation leads to the following code within the <code>async_read_helper</code>:</p> <pre><code>while (_io_service-&gt;run_one()) { if (_message_received) { timer.cancel(); } else if (_timeout_triggered) { _socket-&gt;cancel(); } } _io_service-&gt;reset(); </code></pre> <p>and the following change to the <code>handle_read</code> method:</p> <pre><code>void communications_client::handle_read(const boost::system::error_code &amp; error, size_t bytes_transferred) { if (error != boost::asio::error::operation_aborted) { ... } } </code></pre> <p>This solution has proved solid and correct during testing.</p>
0
1,991
How to call rest api on button click in Angular
<p>I have an angular app, at the moment it has some data coming in from a rest api. I want to just call that api on a click function, what would be the correct way to implement this?</p> <p><strong>component.ts</strong></p> <pre><code>import { Component, OnInit } from '@angular/core'; import { ApiService } from '../../../services/api.service'; @Component({ selector: 'app-content', templateUrl: './content.component.html', styleUrls: ['./content.component.scss'] }) export class ContentComponent implements OnInit { public data = []; public apiData: any; constructor(private service: ApiService) { } private getAll() { this.service.getAll().subscribe((results) =&gt; { console.log('Data is received - Result - ', results); this.data = results.results; }) } ngOnInit() { //this.getAll(); } onClick() { this.getAll() } } </code></pre> <p><strong>html</strong></p> <pre><code>&lt;div class="jumbotron hero"&gt; &lt;div class="container"&gt; &lt;h1 class="display-4 text-center header mb-5"&gt;SEARCH&lt;/h1&gt; &lt;form&gt; &lt;div class="row"&gt; &lt;div class="col-8"&gt; &lt;div class="form-group"&gt; &lt;label for="inputPassword2" class="sr-only"&gt;Search&lt;/label&gt; &lt;input type="password" class="form-control form-control-lg" id="inputPassword2" placeholder="Search iTunes..."&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-4"&gt; &lt;button (click)="onClick" class="btn btn-primary btn-block btn-lg"&gt;Get All&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container" &gt; &lt;table class="table"&gt; &lt;thead class="thead-light"&gt; &lt;tr&gt; &lt;th&gt;Artwork&lt;/th&gt; &lt;th&gt;Artist&lt;/th&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Genre&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr *ngFor="let user of data"&gt; &lt;td&gt;&lt;img src="{{user.artworkUrl60}}"&gt;&lt;/td&gt; &lt;td&gt;{{user.artistName}}&lt;/td&gt; &lt;td&gt;{{user.collectionName}}&lt;/td&gt; &lt;td&gt;{{user.primaryGenreName}}&lt;/td&gt; &lt;td&gt;{{user.collectionPrice}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre>
0
1,189
JNI DETECTED ERROR IN APPLICATION: JNI NewGlobalRef called with pending exception java.lang.ClassNotFoundException:
<p>I am working on VPN app and follows the code of <a href="https://github.com/vmlinz/strongswan-android" rel="noreferrer">strongswan</a> app. I have used the code of this app and it is loading <code>.so</code> files through JNI and i have copied these files from the strongswan project. It gives this exception for one of these files:</p> <pre><code>A/art: art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: JNI NewGlobalRef called with pending exception java.lang.ClassNotFoundException: Didn't find class "org.strongswan.android.logic.CharonVpnService" on path: DexPathList[[zip file "/data/app/com.whizpool.vpn-1/base.apk"],nativeLibraryDirectories=[/data/app/com.whizpool.vpn-1/lib/arm, /data/app/com.whizpool.vpn-1/base.apk!/lib/armeabi, /vendor/lib, /system/lib]] art/runtime/java_vm_ext.cc:410] at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56) art/runtime/java_vm_ext.cc:410] at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511) art/runtime/java_vm_ext.cc:410] at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469) art/runtime/java_vm_ext.cc:410] at java.lang.String java.lang.Runtime.nativeLoad(java.lang.String, java.lang.ClassLoader, java.lang.String) (Runtime.java:-2) art/runtime/java_vm_ext.cc:410] at java.lang.String java.lang.Runtime.doLoad(java.lang.String, java.lang.ClassLoader) (Runtime.java:435) art/runtime/java_vm_ext.cc:410] at void java.lang.Runtime.loadLibrary(java.lang.String, java.lang.ClassLoader) (Runtime.java:370) art/runtime/java_vm_ext.cc:410] at void java.lang.System.loadLibrary(java.lang.String) (System.java:1076) art/runtime/java_vm_ext.cc:410] at void com.whizpool.vpn.logic.CharonVpnService.&lt;clinit&gt;() (CharonVpnService.java:744) art/runtime/java_vm_ext.cc:410] at java.lang.Object java.lang.Class.newInstance!() (Class.java:-2) art/runtime/java_vm_ext.cc:410] at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3772) art/runtime/java_vm_ext.cc:410] at void android.app.ActivityThread.access$2100(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:221) art/runtime/java_vm_ext.cc:410] at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1882) art/runtime/java_vm_ext.cc:410] at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102) art/runtime/java_vm_ext.cc:410] at void android.os.Looper.loop() (Looper.java:158) art/runtime/java_vm_ext.cc:410] at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:7224) art/runtime/java_vm_ext.cc:410] at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2) art/runtime/java_vm_ext.cc:410] at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1230) art/runtime/java_vm_ext.cc:410] at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1120) art/runtime/java_vm_ext.cc:410] art/runtime/java_vm_ext.cc:410] in call to NewGlobalRef art/runtime/java_vm_ext.cc:410] from java.lang.String java.lang.Runtime.nativeLoad(java.lang.String, java.lang.ClassLoader, java.lang.String) art/runtime/java_vm_ext.cc:410] "main" prio=5 tid=1 Runnable art/runtime/java_vm_ext.cc:410] | group="main" sCount=0 dsCount=0 obj=0x767e53e8 self=0xf4be4500 art/runtime/java_vm_ext.cc:410] | sysTid=15402 nice=0 cgrp=default sched=0/0 handle=0xf73eeb4c art/runtime/java_vm_ext.cc:410] | state=R schedstat=( 0 0 0 ) utm=15 stm=9 core=6 HZ=100 art/runtime/java_vm_ext.cc:410] | stack=0xff291000-0xff293000 stackSize=8MB art/runtime/java_vm_ext.cc:410] | held mutexes= "mutator lock"(shared held) art/runtime/java_vm_ext.cc:410] native: #00 pc 00371bd7 /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, int, BacktraceMap*, char const*, art::ArtMethod*, void*)+142) art/runtime/java_vm_ext.cc:410] native: #01 pc 00351199 /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, BacktraceMap*) const+160) art/runtime/java_vm_ext.cc:410] native: #02 pc 0025b30b /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+742) art/runtime/java_vm_ext.cc:410] native: #03 pc 0025b9e5 /system/lib/libart.so (art::JavaVMExt::JniAbortV(char const*, char const*, std::__va_list)+64) art/runtime/java_vm_ext.cc:410] native: #04 pc 000fd391 /system/lib/libart.so (art::ScopedCheck::AbortF(char const*, ...)+32) art/runtime/java_vm_ext.cc:410] native: #05 pc 001024a5 /system/lib/libart.so (art::ScopedCheck::Check(art::ScopedObjectAccess&amp;, bool, char const*, art::JniValueType*) (.constprop.95)+5072) art/runtime/java_vm_ext.cc:410] native: #06 pc 00114891 /system/lib/libart.so (art::CheckJNI::NewGlobalRef(_JNIEnv*, _jobject*)+392) art/runtime/java_vm_ext.cc:410] native: #07 pc 00002a44 /data/app/com.whizpool.vpn-1/lib/arm/libandroidbridge.so (JNI_OnLoad+108) art/runtime/java_vm_ext.cc:410] native: #08 pc 0025bf6f /system/lib/libart.so (art::JavaVMExt::LoadNativeLibrary(_JNIEnv*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; const&amp;, _jobject*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt;*)+1238) art/runtime/java_vm_ext.cc:410] native: #09 pc 002d1fc7 /system/lib/libart.so (art::Runtime_nativeLoad(_JNIEnv*, _jclass*, _jstring*, _jobject*, _jstring*)+194) art/runtime/java_vm_ext.cc:410] native: #10 pc 0020d51d /system/framework/arm/boot.oat (Java_java_lang_Runtime_nativeLoad__Ljava_lang_String_2Ljava_lang_ClassLoader_2Ljava_lang_String_2+144) art/runtime/java_vm_ext.cc:410] at java.lang.Runtime.nativeLoad(Native method) art/runtime/java_vm_ext.cc:410] at java.lang.Runtime.doLoad(Runtime.java:435) art/runtime/java_vm_ext.cc:410] - locked &lt;0x0d37d22d&gt; (a java.lang.Runtime) art/runtime/java_vm_ext.cc:410] at java.lang.Runtime.loadLibrary(Runtime.java:370) art/runtime/java_vm_ext.cc:410] at java.lang.System.loadLibrary(System.java:1076) art/runtime/java_vm_ext.cc:410] at com.whizpool.vpn.logic.CharonVpnService.&lt;clinit&gt;(CharonVpnService.java:744) art/runtime/java_vm_ext.cc:410] at java.lang.Class.newInstance!(Native method) art/runtime/java_vm_ext.cc:410] at android.app.ActivityThread.handleCreateService(ActivityThread.java:3772) art/runtime/java_vm_ext.cc:410] at android.app.ActivityThread.access$2100(ActivityThread.java:221) art/runtime/java_vm_ext.cc:410] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1882) art/runtime/java_vm_ext.cc:410] at android.os.Handler.dispatchMessage(Handler.java:102) art/runtime/java_vm_ext.cc:410] at android.os.Looper.loop(Looper.java:158) art/runtime/java_vm_ext.cc:410] at android.app.ActivityThread.main(ActivityThread.java:7224) art/runtime/java_vm_ext.cc:410] at java.lang.reflect.Method.invoke!(Native method) art/runtime/java_vm_ext.cc:410] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) art/runtime/java_vm_ext.cc:410] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) art/runtime/java_vm_ext.cc:410] A/art: art/runtime/runtime.cc:366] Runtime aborting... art/runtime/runtime.cc:366] Aborting thread: art/runtime/runtime.cc:366] "main" prio=5 tid=1 Native art/runtime/runtime.cc:366] | group="" sCount=0 dsCount=0 obj=0x767e53e8 self=0xf4be4500 art/runtime/runtime.cc:366] | sysTid=15402 nice=0 cgrp=default sched=0/0 handle=0xf73eeb4c art/runtime/runtime.cc:366] | state=R schedstat=( 0 0 0 ) utm=15 stm=10 core=4 HZ=100 art/runtime/runtime.cc:366] | stack=0xff291000-0xff293000 stackSize=8MB art/runtime/runtime.cc:366] | held mutexes= "abort lock" art/runtime/runtime.cc:366] native: #00 pc 00371bd7 /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, int, BacktraceMap*, char const*, art::ArtMethod*, void*)+142) art/runtime/runtime.cc:366] native: #01 pc 00351199 /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, BacktraceMap*) const+160) art/runtime/runtime.cc:366] native: #02 pc 00333fb9 /system/lib/libart.so (art::AbortState::DumpThread(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, art::Thread*) const+28) art/runtime/runtime.cc:366] native: #03 pc 00334257 /system/lib/libart.so (art::Runtime::Abort()+566) art/runtime/runtime.cc:366] native: #04 pc 000f476b /system/lib/libart.so (art::LogMessage::~LogMessage()+2226) art/runtime/runtime.cc:366] native: #05 pc 0025b635 /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+1552) art/runtime/runtime.cc:366] native: #06 pc 0025b9e5 /system/lib/libart.so (art::JavaVMExt::JniAbortV(char const*, char const*, std::__va_list)+64) art/runtime/runtime.cc:366] native: #07 pc 000fd391 /system/lib/libart.so (art::ScopedCheck::AbortF(char const*, ...)+32) art/runtime/runtime.cc:366] native: #08 pc 001024a5 /system/lib/libart.so (art::ScopedCheck::Check(art::ScopedObjectAccess&amp;, bool, char const*, art::JniValueType*) (.constprop.95)+5072) art/runtime/runtime.cc:366] native: #09 pc 00114891 /system/lib/libart.so (art::CheckJNI::NewGlobalRef(_JNIEnv*, _jobject*)+392) art/runtime/runtime.cc:366] native: #10 pc 00002a44 /data/app/com.whizpool.vpn-1/lib/arm/libandroidbridge.so (JNI_OnLoad+108) art/runtime/runtime.cc:366] native: #11 pc 0025bf6f /system/lib/libart.so (art::JavaVMExt::LoadNativeLibrary(_JNIEnv*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; const&amp;, _jobject*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt;*)+1238) art/runtime/runtime.cc:366] native: #12 pc 002d1fc7 /system/lib/libart.so (art::Runtime_nativeLoad(_JNIEnv*, _jclass*, _jstring*, _jobject*, _jstring*)+194) art/runtime/runtime.cc:366] native: #13 pc 0020d51d /system/framework/arm/boot.oat (???) art/runtime/runtime.cc:366] at java.lang.Runtime.nativeLoad(Native method) art/runtime/runtime.cc:366] at java.lang.Runtime.doLoad(Runtime.java:435) art/runtime/runtime.cc:366] - locked &lt;0x0d37d22d&gt; (a java.lang.Runtime) art/runtime/runtime.cc:366] at java.lang.Runtime.loadLibrary(Runtime.java:370) art/runtime/runtime.cc:366] at java.lang.System.loadLibrary(System.java:1076) art/runtime/runtime.cc:366] at com.whizpool.vpn.logic.CharonVpnService.&lt;clinit&gt;(CharonVpnService.java:744) art/runtime/runtime.cc:366] at java.lang.Class.newInstance!(Native method) art/runtime/runtime.cc:366] at android.app.ActivityThread.handleCreateService(ActivityThread.java:3772) art/runtime/runtime.cc:366] at android.app.ActivityThread.access$2100(ActivityThread.java:221) art/runtime/runtime.cc:366] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1882) art/runtime/runtime.cc:366] at android.os.Handler.dispatchMessage(Handler.java:102) art/runtime/runtime.cc:366] at android.os.Looper.loop(Looper.java:158) art/runtime/runtime.cc:366] at android.app.ActivityThread.main(ActivityThread.java:7224) art/runtime/runtime.cc:366] at java.lang.reflect.Method.invoke!(Native method) art/runtime/runtime.cc:366] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) art/runtime/runtime.cc:366] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) art/runtime/runtime.cc:366] Pending exception java.lang.ClassNotFoundException: Didn't find class "org.strongswan.android.logic.CharonVpnService" on path: DexPathList[[zip file "/data/app/com.whizpool.vpn-1/base.apk"],nativeLibraryDirectories=[/data/app/com.whizpool.vpn-1/lib/arm, /data/app/com.whizpool.vpn-1/base.apk!/lib/armeabi, /vendor/lib, /system/lib]] art/runtime/runtime.cc:366] at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56) art/runtime/runtime.cc:366] at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511) art/runtime/runtime.cc:366] at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469) art/runtime/runtime.cc:366] at java.lang.String java.lang.Runtime.nativeLoad(java.lang.String, java.lang.ClassLoader, java.lang.String) (Runtime.java:-2) art/runtime/runtime.cc:366] at java.lang.String java.lang.Runtime.doLoad(java.lang.String, java.lang.ClassLoader) (Runtime.java:435) art/runtime/runtime.cc:366] at void java.lang.Runtime.loadLibrary(java.lang.String, java.lang.ClassLoader) (Runtime.java:370) art/runtime/runtime.cc:366] at void java.lang.System.loadLibrary(java.lang.String) (System.java:1076) art/runtime/runtime.cc:366] at void com.whizpool.vpn.logic.CharonVpnService.&lt;clinit&gt;() (CharonVpnService.java:744) art/runtime/runtime.cc:366] at java.lang.Object java.lang.Class.newInstance!() (Class.java:-2) art/runtime/runtime.cc:366] at void android.app.ActivityThread.handleCreateService(android.app.ActivityThread$CreateServiceData) (ActivityThread.java:3772) art/runtime/runtime.cc:366] at void android.app.ActivityThread.access$2100(android.app.ActivityThread, android.app.ActivityThread$CreateServiceData) (ActivityThread.java:221) art/runtime/runtime.cc:366] at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1882) art/runtime/runtime.cc:366] at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102) art/runtime/runtime.cc:366] at void android.os.Looper.loop() (Looper.java:158) art/runtime/runtime.cc:366] at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:7224) art/runtime/runtime.cc:366] at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2) art/runtime/runtime.cc:366] at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1230) art/runtime/runtime.cc:366] at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1120) art/runtime/runtime.cc:366] Dumping all threads without appropriate locks held: thread list lock mutator lock art/runtime/runtime.cc:366] All threads: art/runtime/runtime.cc:366] DALVIK THREADS (12): art/runtime/runtime.cc:366] "main" prio=5 tid=1 Runnable art/runtime/runtime.cc:366] | group="" sCount=0 dsCount=0 obj=0x767e53e8 self=0xf4be4500 art/runtime/runtime.cc:366] | sysTid=15402 nice=0 cgrp=default sched=0/0 handle=0xf73eeb4c art/runtime/runtime.cc:366] | state=R schedstat=( 0 0 0 ) utm=15 stm=12 core=0 HZ=100 art/runtime/runtime.cc:366] | stack=0xff291000-0xff293000 stackSize=8MB art/runtime/runtime.cc:366] | held mutexes= "abort lock" "mutator lock"(shared held) art/runtime/runtime.cc:366] native: #00 pc 00371bd7 /system/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, int, BacktraceMap*, char const*, art::ArtMethod*, void*)+142) art/runtime/runtime.cc:366] native: #01 pc 00351199 /system/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;, BacktraceMap*) const+160) art/runtime/runtime.cc:366] native: #02 pc 0035b0b7 /system/lib/libart.so (art::DumpCheckpoint::Run(art::Thread*)+446) art/runtime/runtime.cc:366] native: #03 pc 0035bc79 /system/lib/libart.so (art::ThreadList::RunCheckpoint(art::Closure*)+212) art/runtime/runtime.cc:366] native: #04 pc 0035c1ef /system/lib/libart.so (art::ThreadList::Dump(std::__1::basic_ostream&lt;char, std::__1::char_traits&lt;char&gt; &gt;&amp;)+154) art/runtime/runtime.cc:366] native: #05 pc 003341cd /system/lib/libart.so (art::Runtime::Abort()+428) art/runtime/runtime.cc:366] native: #06 pc 000f476b /system/lib/libart.so (art::LogMessage::~LogMessage()+2226) art/runtime/runtime.cc:366] native: #07 pc 0025b635 /system/lib/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+1552) art/runtime/runtime.cc:366] native: #08 pc 0025b9e5 /system/lib/libart.so (art::JavaVMExt::JniAbortV(char const*, char const*, std::__va_list)+64) art/runtime/runtime.cc:366] native: #09 pc 000fd391 /system/lib/libart.so (art::ScopedCheck::AbortF(char const*, ...)+32) art/runtime/runtime.cc:366] native: #10 pc 001024a5 /system/lib/libart.so (art::ScopedCheck::Check(art::ScopedObjectAccess&amp;, bool, char const*, art::JniValueType*) (.constprop.95)+5072) art/runtime/runtime.cc:366] native: #11 pc 00114891 /system/lib/libart.so (art::CheckJNI::NewGlobalRef(_JNIEnv*, _jobject*)+392) art/runtime/runtime.cc:366] native: #12 pc 00002a44 /data/app/com.whizpool.vpn-1/lib/arm/libandroidbridge.so (JNI_OnLoad+108) art/runtime/runtime.cc:366] native: #13 pc 0025bf6f /system/lib/libart.so (art::JavaVMExt::LoadNativeLibrary(_JNIEnv*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; const&amp;, _jobject*, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt;*)+1238) art/runtime/runtime.cc:366] native: #14 pc 002d1fc7 /system/lib/libart.so (art::Runtime_nativeLoad(_JNIEnv*, _jclass*, _jstring*, _jobject*, _jstring*)+194) art/runtime/runtime.cc:366] native: #15 pc 0020d51d /system/framework/arm/boot.oat (Java_java_lang_Runtime_nativeLoad__Ljava_lang_String_2Ljava_lang_ClassLoader_2Ljava_lang_String_2+144) art/runtime/runtime.cc:366] at java.lang.Runtime.nativeLoad(Native method) art/runtime/runtime.cc:366] at java.lang.Runtime.doLoad(Runtime.java:435) art/runtime/runtime.cc:366] - locked &lt;0x0d37d22d&gt; (a java.lang.Runtime) art/runtime/runtime.cc:366] at java.lang.Runtime.loadLibrary(Runtime.java:370) art/runtime/runtime.cc:366] at java.lang.System.loadLibrary(System.java:1076) art/runtime/runtime.cc:366] at com.whizpool.vpn.logic.CharonVpnService.&lt;clinit&gt;(CharonVpnService.java:744) art/runtime/runtime.cc:366] at java.lang.Class.newInstance!(Native method) art/runtime/runtime.cc:366] at android.app.ActivityThread.handleCreateService(ActivityThread.java:3772) art/runtime/runtime.cc:366] at android.app.ActivityThread.access$2100(ActivityThread.java:221) art/runtime/runtime.cc:366] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1882) art/runtime/runtime.cc:366] at android.os.Handler.dispatchMessage(Handler.java:102) art/runtime/runtime.cc:366] at android.os.Looper.loop(Looper.java:158) art/runtime/runtime.cc:366] at android.app.ActivityThread.main(ActivityThread.java:7224) art/runtime/runtime.cc:366] at java.lang.reflect.Method.invoke!(Native method) art/runtime/runtime.cc:366] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) art/runtime/runtime.cc:366] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) art/runtime/runtime.cc:366] art/runtime/runtime.cc:366] "Signal Catcher" prio=5 tid=2 WaitingInMainSignalCatcherLoop art/runtime/runtime.cc:366] | group="" sCount=1 dsCount=0 obj=0x12c680a0 self=0xee3e2c00 art/runtime/runtime.cc:366] | sysTid=15407 nice=0 cgrp=default sched=0/0 handle=0xf425c930 art/runtime/runtime.cc:366] | state=S schedstat=( 0 0 0 ) utm=0 stm=0 core=5 HZ=100 art/runtime/runtime.cc:366] | stack=0xf4160000-0xf4162000 stackSize=1014KB art/runtime/runtime.cc:366] | held mutexes= art/runtime/runtime.cc:366] kernel: do_sigtimedwait+0xd8/0x1ac art/runtime/runtime.cc:366] kernel: compat_SyS_rt_sigtimedwait+0x94/0xd8 art/runtime/runtime.cc:366] kernel: __sys_trace+0x3c/0x40 art/runtime/runtime.cc:366] native: #00 pc 0004135c /system/lib/libc.so (__rt_sigtimedwait+12) art/runtime/runtime.cc:366] native: #01 pc 0001d0df /system/lib/libc.so (sigwait+22) art/runtime/runtime.cc:366] native: #02 pc 0033aae9 /system/lib/libart.so (art::SignalCatcher::WaitForSignal(art::Thread*, art::SignalSet&amp;)+76) art/runtime/runtime.cc:366] native: #03 pc 0033c535 /system/lib/libart.so (art::SignalCatcher::Run(void*)+260) art/runtime/runtime.cc:366] native: #04 pc 0003fc53 /system/lib/libc.so (__pthread_start(void*)+30) art/runtime/runtime.cc:366] native: #05 pc 0001a38b /system/lib/libc.so (__start_thread+6) art/runtime/runtime.cc:366] (no managed stack frames) art/runtime/runtime.cc:366] art/runtime/runtime.cc:366] "JDWP" prio=5 tid=3 WaitingInMainDebuggerLoop art/runtime/runtime.cc:366] | group="" sCount=1 dsCount=0 obj=0x12c6b0a0 self=0xee43b900 art/runtime/runtime.cc:366] | sysTid=15408 nice=0 cgrp=default sched=0/0 handle=0xf415d930 art/runtime/runtime.cc:366] | state=S schedstat=( 0 0 0 ) utm=0 stm=0 core=5 HZ=100 art/runtime/runtime.cc:366] | stack=0xf4061000-0xf4063000 stackSize=1014KB art/runtime/runtime.cc:366] | held mutexes= art/runtime/runtime.cc:366] kernel: poll_schedule_timeout+0x54/0xb8 art/runtime/runtime.cc:366] kernel: do_select+0x414/0x468 art/runtime/runtime.cc:366] kernel: compat_core_sys_select+0x160/0x20c art/runtime/runtime.cc:366] kernel: compat_sys_pselect6+0x178/0x214 art/runtime/runtime.cc:366] kernel: __sys_trace+0x3c/0x40 art/runtime/runtime.cc:366] native: #00 pc 00041278 /system/lib/libc.so (__pselect6+20) art/runtime/runtime.cc:366] native: #01 pc 0001c431 /system/lib/libc.so (select+60) art/runtime/runtime.cc:366] native: #02 pc 00402093 /system/lib/libart.so (art::JDWP::JdwpAdbState::ProcessIncoming()+218) art/runtime/runtime.cc:366] native: #03 pc 00267a2f /system/lib/libart.so (art::JDWP::JdwpState::Run()+314) art/runtime/runtime.cc:366] native: #04 pc 002688ad /system/lib/libart.so (art::JDWP::StartJdwpThread(void*)+16) art/runtime/runtime.cc:366] native: #05 pc 0003fc53 /system/lib/libc.so (__pthread_start(void*)+30) art/runtime/runtime.cc:366] native: #06 pc 0001a38b /system/lib/libc.so (__start_thread+6) art/runtime/runtime.cc:366] (no managed stack frames) art/runtime/runtime.cc:366] A/art: art/runtime/runtime.cc:366] "ReferenceQueueDaemon" prio=5 tid=4 Waiting art/runtime/runtime.cc:366] | group="" sCount=1 dsCount=0 obj=0x12c64e80 self=0xee43a500 art/runtime/runtime.cc:366] | sysTid=15409 nice=0 cgrp=default sched=0/0 handle=0xf405e930 art/runtime/runtime.cc:366] | state=S schedstat=( 0 0 0 ) utm=0 stm=0 core=4 HZ=100 art/runtime/runtime.cc:366] | stack=0xf3f5c000-0xf3f5e000 stackSize=1038KB art/runtime/runtime.cc:366] | held mutexes= art/runtime/runtime.cc:366] kernel: futex_wait_queue_me+0xd4/0x12c art/runtime/runtime.cc:366] kernel: futex_wait+0xd8/0x1cc art/runtime/runtime.cc:366] kernel: do_futex+0xc8/0x8d0 art/runtime/runtime.cc:366] kernel: compat_SyS_futex+0xd0/0x14c art/runtime/runtime.cc:366] kernel: __sys_trace+0x3c/0x40 art/runtime/runtime.cc:366] native: #00 pc 00017684 /system/lib/libc.so (syscall+28) art/runtime/runtime.cc:366] native: #01 pc 000f6d05 /system/lib/libart.so (art::ConditionVariable::Wait(art::Thread*)+96) art/runtime/runtime.cc:366] native: #02 pc 002bf87d /system/lib/libart.so (art::Monitor::Wait(art::Thread*, long long, int, bool, art::ThreadState)+1144) art/runtime/runtime.cc:366] native: #03 pc 002c05db /system/lib/libart.so (art::Monitor::Wait(art::Thread*, art::mirror::Object*, long long, int, bool, art::ThreadState)+142) art/runtime/runtime.cc:366] native: #04 pc 002d1e2b /system/lib/libart.so (art::Object_wait(_JNIEnv*, _jobject*)+38) </code></pre> <p>Excecption pointing error at this line :</p> <pre><code>System.loadLibrary("androidbridge"); </code></pre> <p>Package name in the exception is the package name of the project from where i copied the code. <code>org.strongswan.android.logic.CharonVpnService</code></p> <p>but my app's package name is <code>com.whizpool.vpn.logic.CharonVpnService</code>.</p> <p>I have searched this <code>org.strongswan.android</code> every where but no where in my project.</p> <p>here is my manifest file:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.whizpool.vpn"&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".MainActivity" android:launchMode="singleTask"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;intent-filter&gt; &lt;action android:name="com.whizpool.vpn.action.START_PROFILE" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;service android:name=".logic.VpnStateService" android:exported="false" &gt; &lt;/service&gt; &lt;service android:name=".logic.CharonVpnService" android:exported="false" android:permission="android.permission.BIND_VPN_SERVICE" &gt; &lt;intent-filter&gt; &lt;action android:name="android.net.VpnService" /&gt; &lt;/intent-filter&gt; &lt;/service&gt; &lt;provider android:name=".data.LogContentProvider" android:authorities="com.whizpool.vpn.content.log" android:exported="true" &gt; &lt;!-- android:grantUriPermissions="true" combined with a custom permission does not work (probably too many indirections with ACTION_SEND) so we secure this provider with a custom ticketing system --&gt; &lt;/provider&gt; &lt;/application&gt; &lt;/manifest&gt;[enter link description here][1] </code></pre>
0
10,726
Reclassing an instance in Python
<p>I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.</p> <p>I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway).</p> <p>The following solution seems to work.</p> <pre><code># This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # &lt;-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #&gt;Hi, my name is Joel. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #&gt;Hi, my name is Jeff A. #&gt;I'll have to remember malloc and free and pointer arithmetic and curly braces. </code></pre> <p>However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical <code>__class__</code> just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this.</p> <p>Is there?</p> <hr> <p>Edit: Thanks everyone for your answers. Here is what I get from them:</p> <ul> <li><p>Although the idea of reclassing an instance by assigning to <code>__class__</code> is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments &amp; votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general.</p></li> <li><p>None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming.</p></li> </ul> <p>As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (<code>import this</code>), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way.</p> <ul> <li><p>Using <code>{has,get,set}attr</code> seems more explicit, as we are explicitly making our changes to the object instead of using magic.</p></li> <li><p>Using <code>__class__ = newclass</code> seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class.</p></li> </ul> <p>Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." </p> <p>I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far.</p> <p>P.S. The actual use case is a UI data control object that needs to grow additional functionality <em>at runtime</em>. However, the question is meant to be very general.</p>
0
1,417
Wampserver icon not going green fully, mysql services not starting up?
<p>I'm running an application on <code>localhost</code>, it's been running successfully for at least a year now, but suddenly today wampserver isn't starting up. Whenever I rightclick on the taskbar icon and "start all services", it gets orange, but never green. Yesterday there was a data loss problem because one of the mysql tables crashed and had to be repaired, if that's related to this in any way.</p> <p>If I try <code>http://localhost/phpmyadmin</code>, I get a <code>403 Forbidden</code> error, which I never got before.</p> <p>I checked the apache log today and its latest entries are:</p> <pre><code>[Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP 2. mysql_real_escape_string() D:\\wamp\\www\\zeejflow\\index_exe.php:25, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP Warning: mysql_real_escape_string() [&lt;a href='function.mysql-real-escape-string'&gt;function.mysql-real-escape-string&lt;/a&gt;]: A link to the server could not be established in D:\\wamp\\www\\zeejflow\\index_exe.php on line 25, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:31 2013] [error] [client 127.0.0.1] PHP 2. mysql_real_escape_string() D:\\wamp\\www\\zeejflow\\index_exe.php:25, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Warning: mysql_real_escape_string() [&lt;a href='function.mysql-real-escape-string'&gt;function.mysql-real-escape-string&lt;/a&gt;]: [2002] No connection could be made because the target machine actively (trying to connect via tcp://localhost:3306) in D:\\wamp\\www\\zeejflow\\index_exe.php on line 26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 2. mysql_real_escape_string() D:\\wamp\\www\\zeejflow\\index_exe.php:26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Warning: mysql_real_escape_string() [&lt;a href='function.mysql-real-escape-string'&gt;function.mysql-real-escape-string&lt;/a&gt;]: No connection could be made because the target machine actively refused it.\r\n in D:\\wamp\\www\\zeejflow\\index_exe.php on line 26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 2. mysql_real_escape_string() D:\\wamp\\www\\zeejflow\\index_exe.php:26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Warning: mysql_real_escape_string() [&lt;a href='function.mysql-real-escape-string'&gt;function.mysql-real-escape-string&lt;/a&gt;]: A link to the server could not be established in D:\\wamp\\www\\zeejflow\\index_exe.php on line 26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:32 2013] [error] [client 127.0.0.1] PHP 2. mysql_real_escape_string() D:\\wamp\\www\\zeejflow\\index_exe.php:26, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:33 2013] [error] [client 127.0.0.1] PHP Warning: mysql_num_rows() expects parameter 1 to be resource, integer given in D:\\wamp\\www\\zeejflow\\index_exe.php on line 34, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:33 2013] [error] [client 127.0.0.1] PHP Stack trace:, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:33 2013] [error] [client 127.0.0.1] PHP 1. {main}() D:\\wamp\\www\\zeejflow\\index_exe.php:0, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:33 2013] [error] [client 127.0.0.1] PHP 2. mysql_num_rows() D:\\wamp\\www\\zeejflow\\index_exe.php:34, referer: http://localhost/zeejflow/index.php [Sat Jul 20 14:17:33 2013] [error] an unknown filter was not added: DEFLATE [Sat Jul 20 14:17:33 2013] [error] an unknown filter was not added: DEFLATE [Sat Jul 20 14:17:33 2013] [error] an unknown filter was not added: DEFLATE </code></pre> <p>Lines 25 and 26 on index_exe.php are simply as below (I was trying to log in to the application): </p> <pre><code>$userName = mysql_real_escape_string($_POST['userName']); $Password = mysql_real_escape_string($_POST['Password']); </code></pre> <p>Because of the <code>[2002] No connection could be made because the target machine actively (trying to connect via tcp://localhost:3306</code> error, I figured maybe there's a problem with some other application using the same port, so I tried the following (my wamp is running on D:) :</p> <pre><code>C:\Users\admin&gt;netstat Active Connections Proto Local Address Foreign Address State TCP 127.0.0.1:5939 localhost127:49313 ESTABLISHED TCP 127.0.0.1:5939 localhost127:49317 ESTABLISHED TCP 127.0.0.1:49155 localhost127:49156 ESTABLISHED TCP 127.0.0.1:49156 localhost127:49155 ESTABLISHED TCP 127.0.0.1:49157 localhost127:49158 ESTABLISHED TCP 127.0.0.1:49158 localhost127:49157 ESTABLISHED TCP 127.0.0.1:49311 localhost127:49312 ESTABLISHED TCP 127.0.0.1:49312 localhost127:49311 ESTABLISHED TCP 127.0.0.1:49313 localhost127:5939 ESTABLISHED TCP 127.0.0.1:49315 localhost127:49316 ESTABLISHED TCP 127.0.0.1:49316 localhost127:49315 ESTABLISHED TCP 127.0.0.1:49317 localhost127:5939 ESTABLISHED TCP 127.0.0.1:49320 localhost127:49321 ESTABLISHED TCP 127.0.0.1:49321 localhost127:49320 ESTABLISHED TCP 192.168.15.200:49166 server6201:5938 ESTABLISHED TCP 192.168.15.200:49847 Server-PC:netbios-ssn TIME_WAIT TCP 192.168.15.200:49848 Server-PC:netbios-ssn TIME_WAIT D:\&gt;netstat Active Connections Proto Local Address Foreign Address State TCP 127.0.0.1:80 localhost127:49799 TIME_WAIT TCP 127.0.0.1:80 localhost127:49800 TIME_WAIT TCP 127.0.0.1:80 localhost127:49801 TIME_WAIT TCP 127.0.0.1:80 localhost127:49802 TIME_WAIT TCP 127.0.0.1:80 localhost127:49803 TIME_WAIT TCP 127.0.0.1:80 localhost127:49804 TIME_WAIT TCP 127.0.0.1:80 localhost127:49806 TIME_WAIT TCP 127.0.0.1:80 localhost127:49810 TIME_WAIT TCP 127.0.0.1:80 localhost127:49811 TIME_WAIT TCP 127.0.0.1:5939 localhost127:49313 ESTABLISHED TCP 127.0.0.1:5939 localhost127:49317 ESTABLISHED TCP 127.0.0.1:49155 localhost127:49156 ESTABLISHED TCP 127.0.0.1:49156 localhost127:49155 ESTABLISHED TCP 127.0.0.1:49157 localhost127:49158 ESTABLISHED TCP 127.0.0.1:49158 localhost127:49157 ESTABLISHED TCP 127.0.0.1:49311 localhost127:49312 ESTABLISHED TCP 127.0.0.1:49312 localhost127:49311 ESTABLISHED TCP 127.0.0.1:49313 localhost127:5939 ESTABLISHED TCP 127.0.0.1:49315 localhost127:49316 ESTABLISHED TCP 127.0.0.1:49316 localhost127:49315 ESTABLISHED TCP 127.0.0.1:49317 localhost127:5939 ESTABLISHED TCP 127.0.0.1:49320 localhost127:49321 ESTABLISHED TCP 127.0.0.1:49321 localhost127:49320 ESTABLISHED TCP 192.168.15.200:49166 server6201:5938 ESTABLISHED TCP 192.168.15.200:49805 mrs02s05-in-f4:http ESTABLISHED </code></pre> <p>But now I don't know what to make of this. I made sure my.ini had specified port 3306, and it had (anyway noone changed it in a year how could it suddenly have another value). Any help please! I think Apache is working because when I type in <code>http://localhost</code>, it works and gives the option to go to phpmyadmin or my application folder, but it appears mysql services aren't starting up or something? I confirmed with the admin and no new software (such as Skype) have been installed or anything. </p> <h2>Update</h2> <p>I went to <code>Services.msc</code> and checked <code>wampapache</code>, the status was "started". But <code>wampmysqld</code> had no status. So I right-clicked and chose "Start". A message said "Windows is attempting to start the service on the local computer", but then I got this error: </p> <pre><code>Windows could not start the wampmysqld service on Local Computer Error 1067: The process terminated unexpectedly </code></pre> <p>What on earth is up? :(</p> <h2>Update 2</h2> <p>I got the mysql working again, here:</p> <p><a href="https://stackoverflow.com/questions/17770846/mysqld-working-but-wampmysqld-not-starting-up/17770958#17770958">mysqld working but wampmysqld not starting up</a></p> <p>HowEVER, <code>localhost://phpmyadmin</code> still gives me a <code>403 forbidden</code> error, and <code>mysql_connect</code> keeps giving me an "Access denied" error.</p>
0
4,229
How to force Java FX scene refresh?
<p>I have an Java FX scene with a start button and several rectangles which represent the tiles of a map. I also have drawn a sphere which represents my explorer (it has to explore the map), but I am having difficulties with running the animation.</p> <p>In my OnMouseClicked handler for the start button, I start an algorithm for exploring the map which changes the position of the sphere and the colors of the tiles which have been visited. The problem is that the scene won't update itself while the algorithm is running, so I only get to see how the final scene will look like (after the algorithm has stopped running). How can I force a scene update so I can see all the color changes sequentially?</p> <p>Later edit:</p> <pre><code>import javafx.application.Application; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class Test extends Application { private static final double boxOuterSize = 50; private static final double boxInnerSize = 48; private static final double boxCornerRadius = 20; private Stage applicationStage; private Scene applicationScene; private static double sceneWidth = 1024; private static double sceneHeight = 800; private static HBox container = new HBox(); private static Group root = new Group(); private Rectangle[] rectangles = new Rectangle[10]; @Override public void start(Stage mainStage) throws Exception { applicationStage = mainStage; container.setSpacing(10); container.setPadding(new Insets(10, 10, 10, 10)); try { applicationScene = new Scene(container, sceneWidth, sceneHeight); applicationScene.addEventHandler(EventType.ROOT,(EventHandler&lt;? super Event&gt;)this); applicationScene.setFill(Color.WHITE); } catch (Exception exception) { System.out.println ("exception : "+exception.getMessage()); } applicationStage.setTitle("HurtLockerRobot - Tema 3 IA"); applicationStage.getIcons().add(new Image("icon.png")); applicationStage.setScene(applicationScene); for(int i=0; i&lt;10; i++) { Rectangle r = new Rectangle(); r.setFill(Color.BLUE); r.setX(i * boxOuterSize); r.setY(0); r.setWidth(boxInnerSize); r.setHeight(boxInnerSize); r.setArcHeight(boxCornerRadius); r.setArcWidth(boxCornerRadius); r.setSmooth(true); rectangles[i] = r; root.getChildren().add(rectangles[i]); } container.getChildren().add(root); Button startButton = new Button("Start"); startButton.setOnMouseClicked(new EventHandler&lt;Event&gt;() { @Override public void handle(Event arg0) { for(int i=0; i&lt;10; i++) { rectangles[i].setFill(Color.RED); // TODO: some kind of scene refresh here } } }); container.getChildren().add(startButton); applicationStage.show(); } public static void main(String[] args) { launch(args); } } </code></pre> <p>Initially all the rectangles are blue. The behavior I want to obtain here is to see the rectangles changing colors sequentially. The problem is that I only get to see the end result (all the rectangles change their color at the same time).</p>
0
1,227