text
stringlengths
64
89.7k
meta
dict
Q: PHP - Variable vs Array Call Say I have an array $order containing the data of entire order and user as well. To display the name of user; I use $order['users'][33]['firstname'];. I do this in several parts of page. Does it really matter to the memory and process to do this way (using associative array)? Or should I store user in a variable $user = $order['users'][33]['firstname']; and keep using $user where ever needed? Which method is prefered? A: It really depends on what your application does. If $order contains only one user and every subarray contain only one data value, then store the information in variables and give them readable names. Otherwise, if $order contains many users and information are kind of a tree, then array is definitely a good way to implement your application. In terms of memory consumption, as long as you are storing the same amount of information I don't think it will be a crucial difference.
{ "pile_set_name": "StackExchange" }
Q: sap.ui.core.format.DateFormat.format give wrong date For one Client, and only when switch the browser to english, the following code: convertTimeToDate: function(dateobj) { if ((dateobj == undefined) || (dateobj == null)) { return ""; } var dateFormat = sap.ui.core.format.DateFormat.getDateInstance({ pattern: "dd. MMM YYYY" }); var dateFormatted = dateFormat.format(dateobj); return dateFormatted; }, returns when inputing the highdate '9999-12-31' the datestring '31. Dec 10000' what could be the problem? It is reproducible only on the maschine of this one person, but for her it happens ALWAYS. A: To avoid problems with timezones, especially in UI5 apps in HR, I decided to send/receive dates and times in ISO format as strings in my recent developments, it guarantees that a user in browser will see the same value as in the SAP back-end system. To make sure you use these values both for input and output it is recommended to implement a Custom Data Type. Suppose you have an sap.m.DateRangeSelection which accepts JavaScript Date objects as dateValue and secondDateValue, and you want bind these properties to a model, where properties like startDate and endDate are date strings of yyyy-MM-dd pattern. In this case a sample custom data type can be like this: sap.ui.define([ "sap/ui/model/SimpleType", "sap/ui/core/format/DateFormat" ], function(SimpleType, DateFormat) { "use strict"; return SimpleType.extend("MyProject.model.ISODateType", { /** * Converts JavaScript Date object to ISO date string * * @public * @param {string} sISO the ISO value of the formatted property * @returns {string} */parseValue: function(oDate) { var oFormat = DateFormat.getDateInstance({ pattern: "yyyy-MM-dd" }); return oFormat.format(oDate); }, /** * Produces JavaScript Date object from ISO date string * * @public * @param {string} sISO the ISO value of the formatted property * @returns {string} */ formatValue: function(sValue) { return new Date(sValue); }, /** * Validates the value to be parsed (should be ISO date string) * * @public * no client side validation is required * @returns {boolean} true */ validateValue: function(sValue) { var sPattern = /(\d{4})-(\d{2})-(\d{2})/; return sValue.match(sPattern); } }); }); And the binding in an XML View can look like this: <DateRangeSelection width="30%" dateValue="{ path: '/startDate', type: 'MyProject.model.ISODateType' }" secondDateValue="{ path: '/endDate', type: 'MyProject.model.ISODateType' }" change="onDateIntervalChange"/> A: I was plagued by the same 10k date. My pattern was {pattern: 'MMMM Y'}. Changing it to {pattern: 'MMMM yyyy'} solved the problem. I cannot find any documents on the difference between 'Y' and 'y' though.
{ "pile_set_name": "StackExchange" }
Q: Cannot read property 'id' of undefined on ngOnInit() Angular7 I am beginner to angular. Problem is actually in EmployeeComponent.ts , if i call this.resetForm(); in ngOnInit() then the controls of dialog gets displayed during page load... but during edit when it comes from employeelist the service.formData sets back to null all time i don't want this to happen. I want both functionalities to happen. This below error if i remove this.resetForm(); in ngOnInit(). (but edit works fine) Note : service.formData contains fields id, description and active Consolelog error : EmployeeComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'id' of undefined at EmployeeComponent.push. EmployeeComponent.ts ngOnInit() { this.resetForm(); } resetForm(form ? : NgForm) { if (form != null) form.resetForm(); this.service.formData = { id: null, description: '', active: true, } console.log(this.service.formData.id); } EmployeeListComponent.ts onEdit(emp: Employee) { this.service.formData = Object.assign({}, emp); const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.width = "50%"; this.dialog.open(EmployeeComponent, dialogConfig); } Employee.component.html <form #form="ngForm" autocomplete="off" > <mat-grid-list cols="2"> <input type="hidden" name="id" #id="ngModel" [(ngModel)]="service.formData.id"> <mat-form-field> <input name="description" matInput #description="ngModel" [(ngModel)]="service.formData.description" placeholder="Employee" required> </mat-form-field> <mat-checkbox matInput #active="ngModel" [(ngModel)]="service.formData.active" name="active">Active</mat-checkbox> </mat-grid-list> <button mat-raised-button color="primary" type="submit" [disabled]="form.invalid" (click)="onSubmit(form)">Submit</button> <button mat-raised-button color="warn" style="margin-left: 6px;" (click)="onClear(form)">Clear</button> </form> A: Here EmployeeComponent is your mat dialog component to open so you need to provide data to the dialog using below in your constructor of EmployeeComponent constructor( @Inject(MAT_DIALOG_DATA) data)){} and when you open the dialog for editing purpose, you need to set data onEdit(emp: Employee) { dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.width = "50%"; // Provide your data here dialogConfig.data = emp; this.dialog.open(EmployeeComponent, dialogConfig); } Now you can use this data on EmployeeComponent by name "data" property and only use reset form in ngOninit ngOnInit() { if (form != null) form.resetForm(); } Other things you need to handle like clear this data when you have done with save
{ "pile_set_name": "StackExchange" }
Q: Drone Delivery Scheduling Service I recently did a interview with WalmartLabs. I was tasked with a take home assignment. I didn't sign a NDA and a team at WalmartLabs said I could post the code on GitHub. I was tasked with developing a program that would deliver orders in such a way to maximize customer satisfaction. My approach to solve this problem was to use a priority queue. The priority queue would prioritize by order created date and distance from the target. Admittedly, I made a mistake by not considering the total passing time when prioritizing orders. I want to become a better developer. I would like to know if someone could look at my github project at https://github.com/vaughnshaun/Walmart_DroneChallenge and tell me any flaws and/or good points of my design. Below is a snippet of a main class for my program. The full project is at my github. The spec for the project is in a pdf named DroneDeliveryChallengeSpec.pdf. public class OrderDeliverer { private List<DeliveredOrder> completedOrders = new List<DeliveredOrder>(); private IOrderStreamer orderStreamer; private Warehouse warehouse; private Double promoters; private Double detractors; private Action<DeliveredOrder> deliveredOrderAction; public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer) { this.warehouse = warehouse; this.orderStreamer = orderStreamer; } public virtual void ProcessOrder() { // Artificially advance the time to the next order waiting to be created // This is a fail safe, just in case the the processing of orders don't advance time enough if (!warehouse.HasOrders) { orderStreamer.AdvanceTime(); } // Keep processing orders while there are orders if (warehouse.HasOrders) { Order order; // If there isn't time for delivery the order should be moved to next day delivery if (!warehouse.HasTimeToDeliverNextOrder(orderStreamer.CurrentTime)) { warehouse.MoveNextOrderToNextDay(); } else if (warehouse.TrySendNextOrder(out order)) // Try to send the order out of the warehouse { // Create a delivered order and track its status and times DeliveredOrder outboundOrder = new DeliveredOrder(order.Id); outboundOrder.OrderPlaced = order.Created; outboundOrder.DepartureTime = orderStreamer.CurrentTime; outboundOrder.DeliveredTime = outboundOrder.DepartureTime; // Time traveled to the destination double travelMinutes = warehouse.GetOrderDeliveryMinutes(order); outboundOrder.DeliveredTime = outboundOrder.DeliveredTime.AddMinutes(travelMinutes); // Total time traveled, includes to destination and returning back to the warehouse travelMinutes += warehouse.GetOrderReturnMinutes(order); completedOrders.Add(outboundOrder); deliveredOrderAction(outboundOrder); switch (outboundOrder.GetRating()) { case OrderHelper.RatingType.Detractor: detractors++; break; case OrderHelper.RatingType.Promoter: promoters++; break; } warehouse.DockDrone(); // Update the mock global time (will also bring more new orders depending on the time) orderStreamer.AddMinutesToTime(travelMinutes); } } } public void OnDeliveredOrder(Action<DeliveredOrder> deliveredAction) { deliveredOrderAction += deliveredAction; } /// <summary> /// The number of orders successfully delivered /// </summary> /// <returns>Returns an int for the count of delivered orders</returns> public int GetNumberOfCompleted() { return completedOrders.Count; } public double GetNps() { double nps = 0; if (completedOrders.Count > 0) { double promoterPercent = (promoters / completedOrders.Count) * 100; double detractorPercent = (detractors / completedOrders.Count) * 100; int decimalPlaces = 2; nps = Math.Round(promoterPercent - detractorPercent, decimalPlaces); } return nps; } } A: There are some basic considerations to make in your design. Guard arguments Perform at least NotNull checks on arguments on public entrypoints of your API. public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer) { this.warehouse = warehouse; this.orderStreamer = orderStreamer; } public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer) { if (warehouse == null) throw new ArgumentNullException(nameof(warehouse)); if (orderStreamer== null) throw new ArgumentNullException(nameof(orderStreamer)); this.warehouse = warehouse; this.orderStreamer = orderStreamer; } Avoid nesting statements if you can Code reads easier with the amount of nested statements kept to a minimum. if (!warehouse.HasOrders) { orderStreamer.AdvanceTime(); } // Keep processing orders while there are orders if (warehouse.HasOrders) { // code when HasOrders .. } if (!warehouse.HasOrders) { orderStreamer.AdvanceTime(); return; } // Keep processing orders while there are orders // code when HasOrders .. Avoid redundant comments Comments should be added only if they add substantial new information to the code. In the above snippet, you could do without // Keep processing orders while there are orders Inline variable declaration This can be written in a more concise fashion. Order order; else if (warehouse.TrySendNextOrder(out order)) else if (warehouse.TrySendNextOrder(out Order order)) Redundant variable type The declared type does not need to be printed out when it can be derived logically from the instantiated type. DeliveredOrder outboundOrder = new DeliveredOrder(order.Id); var outboundOrder = new DeliveredOrder(order.Id); Event lifetime management Do you have a way to unsubscribe from the event? This is the cause of many memory leaks. travelMinutes += warehouse.GetOrderReturnMinutes(order); Property vs Method How to decide? Consider using a property for a simple getter GetNumberOfCompleted. Virtual methods Declare virtual methods when there is a use case for it. What is the reason you declare your method virtual? public virtual void ProcessOrder(
{ "pile_set_name": "StackExchange" }
Q: Eclipse Subversion: Risks of the team project I develop some project with my team using svn. SVN is new for me, I have checked out the project and would like to try out the differents functionality of SVN (for example, team-> commit, update, revert.. etc) My Question is: Is there any risk for the project the whole team is using? Can I do something wrong on the projct (for example changing/deleting files, which can not be undo) A: Well there is lot of points can be considered but that is the benefit of SVN that you can synchronize with your team and aware of changes asap. So I mean purpose of SVN is to get rid of those risks. Some points I can say so far: *You should have a reflex that you need to update your project in every opportunity *Make sure you are synchronized (keep in touch) with the team and you know who is working on what so you can get rid of editing conflicts and updating same code *If you get conflicts never change someone else code, if possible revert to latest changes and add your changes. *Make very clear comments, if you are working with ticket system consider ticket number *You can see entire history of SVN and changes on specified file. i.e. x person changed this code block on this date etc... so it gives you clear overview *You can compare any revision/commit with another commit. This also gives a clear overview and makes faster debugging progress. **When I delete a file first I update project to see if file has been pointed out from someone else in last minutes if not I am running application that agin make sure test cases has valid result and commiting my changes. And with subversion: everything can be undo. That is the one the great benefit that you can rever to previous revisions. **Iam not sure this question belongs to here but I have added my answer.
{ "pile_set_name": "StackExchange" }
Q: componentDidMount only fires once when rendering multiple Component via map() I am facing a weird problem. I've written a React component which renders multiple custom child components via the array.map()-method like this: public render(): React.ReactElement<IParentProps> { return ( this.children.map((item, idx) => { return (<Child customProperty={item}>); } ); } All of my children get rendered, but componentDidMount gets called just once and not, like I would like it to be, every time a Child components gets created. It's crazy. I am using React 15.6.2 (can't upgrade, it's a, SharePoint 2019 solution). A: To further Murats answer, what you're likely looking for is componentDidUpdate()
{ "pile_set_name": "StackExchange" }
Q: Is there something like user.home to get the \Users\Public directory in java? I would like to use the Users\Public directory to write some files to share between accounts easily, is there a way to get this as a system variable in Java? A: The way to find the public directory is System.getenv("PUBLIC"); This should get something like C:\Users\Public, or if your main drive is D:, D:\Users\Public. This Wikipedia article is a good reference for Windows environment variables.
{ "pile_set_name": "StackExchange" }
Q: Looping through a nested array in javascript. Not able to display it I am trying to loop through a nested array but not able to display. I am new to Javascript any help would be appreciated. Thank you let shoppingList = [ ['Shirts', 'Pants', 'Tie', 'Belt'], ['Fruits', 'Vegetables', 'Spices', 'Utensils'], ['Toilet paper', 'Washing liquid', 'Brushes', 'Sponges'] ]; //accessing the above array using for loop for(let shoppingIndex=0; shoppingIndex < shoppingList.length; shoppingIndex++) { document.querySelector('p').innerHTML = shoppingList(shoppingIndex); } <p> </p> A: You need to access the list items using []. Also at the moment you will only ever display the last array, to display all arrays you can use += and instead of using innerHTML you can use textContent since you're simply displaying text with no HTML. let shoppingList = [ ['Shirts', 'Pants', 'Tie', 'Belt'], ['Fruits', 'Vegetables', 'Spices', 'Utensils'], ['Toilet paper', 'Washing liquid', 'Brushes', 'Sponges'] ]; //accessing the above array using for loop for(let shoppingIndex=0; shoppingIndex<shoppingList.length; shoppingIndex++) { document.querySelector('p').textContent += shoppingList[shoppingIndex]; } <p></p>
{ "pile_set_name": "StackExchange" }
Q: What are the new unusual effects for Scream Fortress 2014? Does anyone know what the new effects are? I also heard there are 2 new effects for taunts. A: Here are the Unusual effects for hats and taunts in Scream Fortress 2014. Hats, from left to right: Amaranthine, Bonzo the All-Gnawing, Haunted Phantasm Jr, Ghastly Ghosts Jr, Stare From Beyond, The Ooze. Taunts: Ghastly Ghosts, Haunted Phantasm. (There's a chance that the taunt effects and their Jr hat variants may have been mixed up on the wiki, by the looks of it.)
{ "pile_set_name": "StackExchange" }
Q: azure storage blob file dont exist on local machine I am following the steps from edx course and when I am running a command from azure storage blob to upload files as instructed in the course I am getting the error. Where do on the local machine I have to create the demofile. ping www.microsoft.com > demofile.txt what is that doing ? A: Was not using the full path in the command
{ "pile_set_name": "StackExchange" }
Q: Importing GFF file with Biopython Is there a way to import a GFF file for an organism with Biopython in the same way you can for a Genbank file? For example, from Bio import Entrez as ez ez.email = '...' handle = ez.efetch(db='gene', id='AE015451.2', rettype='genbank', retmode='xml') h = handle.read() print(h) This will import a Gebank xml file for Pseudomonas putida. Is there a way to do this for a GFF file? A: No, there is currently no GFF support in biopython. However, you can read in GFF files into python using this package, gffutils. There are also a few other packages to read/write GFF files, like gff3.
{ "pile_set_name": "StackExchange" }
Q: Time to first success for a simple event I beg your pardon for the silly question. An urn contains $c$ elements, $\gamma$ of which are of type $G$. We define the event $E_n^G$ as to get in $n$ independent trials, exactly $n$ times one element of kind $G$, so that $P(E_n^G)=\left(\frac{\gamma}{c}\right)^n$. Clearly, the event $E_n^G$ cannot occur before the last trial $n$. I learned that the time to first success can be seen as the number of trials needed to get, in average, the first success of a given event. But then what is the expected "time to to first success" for the event $E^G_n$? Is it $n$? Yes/No? Why? A: If you have an event $A$, and a number of trials $N$ (which can be $\infty$), then the definition of the "time to first success" of A is $$T_A = \min \{n \le N\;:\; A\;\text{is true at the $n-$th trial}\}$$ You can see that if the event $A$ does not occurs for the $N$ trials then $\{n \le N\;:\; A\;\text{is true at the $n-$th trial}\}$ is empty and then $T_A = \infty$ Let us assume that $\gamma < c$. If you define $E_n^G$ only for $n$ trials then the "time to first success" of $E_n^G$, will be $n$ with probability $\left(\frac\gamma c\right)^n$ and $\infty$ with probability $1-\left(\frac\gamma c\right)^n > 0$, in this case the expected value of the "time to first succes" is $\infty$. This can be easily generalized when the number of trials is finite. However if the number of trials is infinite you can see that getting $n$ times an element of $G$ is equivalent to getting $n$ times one time an element of $G$. Then $$\mathbb E \left[T_{E_n^G}\right] = n \mathbb E\left[T_{E_1^G}\right] = n\frac c \gamma$$
{ "pile_set_name": "StackExchange" }
Q: Multiply a column using awk How do I multiply a column by an integer (say 3) and replace the older value by new one, using awk? Input: Data 9390.900391 10573.089844 80.000000 200.000000 2.700000 Data 17762.810547 18536.189453 85.000000 200.000000 2.700000 Expected output: (after multiplying the last column by 3) Data 9390.900391 10573.089844 80.000000 200.000000 8.100000 Data 17762.810547 18536.189453 85.000000 200.000000 8.100000 A: Try: $ awk 'NF{$NF = sprintf("%.6f", $NF*3)}1' file Data 9390.900391 10573.089844 80.000000 200.000000 8.100000 Data 17762.810547 18536.189453 85.000000 200.000000 8.100000 Change $NF to the $n where nis the field you want to change.
{ "pile_set_name": "StackExchange" }
Q: Using SimpleXML with Android and Gradle I'm having troubles trying to compile an Android application with Gradle 0.5.+ and Android Studio, using SimpleXML. This is the error: Gradle: Execution failed for task ':MyApplication:dexDebug'. > Failed to run command: /Applications/Android Studio.app/sdk/build-tools/android-4.2.2/dx --dex --output <REALLY_LONG_STRING.....> Error Code: 1 Output: trouble processing "javax/xml/stream/events/StartElement.class": Ill-advised or mistaken usage of a core class (java.* or javax.*) when not building a core library. This is often due to inadvertently including a core library file in your application's project, when using an IDE (such as Eclipse). If you are sure you're not intentionally defining a core class, then this is the most likely explanation of what's going on. However, you might actually be trying to define a class in a core namespace, the source of which you may have taken, for example, from a non-Android virtual machine project. This will most assuredly not work. At a minimum, it jeopardizes the compatibility of your app with future versions of the platform. It is also often of questionable legality. If you really intend to build a core library -- which is only appropriate as part of creating a full virtual machine distribution, as opposed to compiling an application -- then use the "--core-library" option to suppress this error message. If you go ahead and use "--core-library" but are in fact building an application, then be forewarned that your application will still fail to build or run, at some point. Please be prepared for angry customers who find, for example, that your application ceases to function once they upgrade their operating system. You will be to blame for this problem. If you are legitimately using some code that happens to be in a core package, then the easiest safe alternative you have is to repackage that code. That is, move the classes in question into your own package namespace. This means that they will never be in conflict with core system classes. JarJar is a tool that may help you in this endeavor. If you find that you cannot do this, then that is an indication that the path you are on will ultimately lead to pain, suffering, grief, and lamentation. 1 error; aborting build.gradle is configured like that: dependencies { [...] compile 'org.simpleframework:simple-xml:2.7.+' } repositories { [...] mavenCentral() } How can i solve this problem? EDIT The problem is not present if i install Simple-XML directly as a Jar inside libs/ - of course a maven solution would be cleaner. A: You need to also exclude stax-API. implementation('org.simpleframework:simple-xml:2.7.+'){ exclude module: 'stax' exclude module: 'stax-api' exclude module: 'xpp3' } A: Try this if previous solution doesn't work: configurations { compile.exclude module: 'stax' compile.exclude module: 'stax-api' compile.exclude module: 'xpp3' } dependencies { [...] compile 'org.simpleframework:simple-xml:2.7.+' } repositories { [...] mavenCentral() } A: I think you need to exclude some of dependencies. compile('org.simpleframework:simple-xml:2.7.+'){ exclude module: 'stax' exclude module: 'xpp3' }
{ "pile_set_name": "StackExchange" }
Q: Power dissipated in resistor Suppose one has a circuit consisting of an inductor $L$ and resistor $R$ in series where $L$ and $R$ are known, passes an alternating voltage of frequency $\omega$ through it and that one wishes to calculate the mean power dissipated in the resistor. Let the RMS voltage across the series combination be $V_0$. Then the RMS current through the components will be $I=\frac{V_0}{i\omega L + R}$ and the mean power dissipated in $R_2$ will be $\overline{P}=I^2R$. However, at this point, $I$ involves a complex quantity. How do you calculate the mean power? Do you calculate the magnitude of the complex current? With very many thanks, Froskoy. A: okay, This was really cool and I got some help from my physics professors on this one (apparently I won't learn this until next semester) and to find the magnitude of the square of a complex number you take it times it's complex conjugate. So in this case $$\frac{V_0}{i \omega L +R}$$ is multiplied with $$\frac{V_0}{-i \omega L + R}$$ leaving you with simply $$\frac{V_0^2}{w^2L^2+R^2}$$, then just take it times your $$R_2$$ giving you $$\frac{V_0^2}{\omega^2 L^2+R^2} \times R_2$$ for the average power. Sorry that my equations aren't very pretty, LaTex isn't working on my ubuntu install yet..... Hope this helps!!
{ "pile_set_name": "StackExchange" }
Q: I have always—and will always—do X? or done X? (This has gotta be a duplicate, but I didn't quite manage to find anything...) Is either of the following correct? If so, what is the general rule that makes the other one wrong? I have always—and will always—preferred chocolate over vanilla. I have always—and will always—prefer chocolate over vanilla. I'm aware that I could just sidestep the whole issue with I have always preferred—and will always prefer—chocolate over vanilla. but that doesn't answer my question. A: To answer my own question: the following is the natural way to say this: I have—and will—always prefer chocolate over vanilla. Now if you "distribute" the "always" that was factored out, you get: I have always—and will always—prefer chocolate over vanilla. which is still sounds like the more natural way to say it.
{ "pile_set_name": "StackExchange" }
Q: calling ajax on button click I have a simple html button. When I click it, the ajax is called. This is my code. <INPUT type="button" class="form6form" id="newsubmit" name="newsubmit" value="Submit"> And here is the ajax full code. I want the ajax to validate my code and then use success handler $('body').on('click', '#newsubmit', function (event) { $("#form6").validate({ debug: false, rules: { plnonew: "required", pldtnew: "required", noboxnew: "required", }, messages: { plnonew: "Please select a pack list id..", pldtnew: "Please select a date..", noboxnew: "Please select a box no..", }, submitHandler: function (form) { $.ajax({ type: "POST", url: "try.php", data: $('#form6').serialize(), cache: false, success: function (html) { var div1 = $(html).filter('#div1'); loading_hide(); $("#container").html(div1); } }); } }); }); Nothing happens when i click the button. Any idea? Thank you. A: At html code client Side index.html file <!doctype html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> function myCall() { var request = $.ajax({ url: "ajax.php", type: "GET", dataType: "html" }); request.done(function(msg) { $("#mybox").html(msg); }); request.fail(function(jqXHR, textStatus) { alert( "Request failed: " + textStatus ); }); } </script> <meta charset="utf-8" /> <title>My jQuery Ajax test</title> <style type="text/css"> #mybox { width: 300px; height: 250px; border: 1px solid #999; } </style> </head> <body> The following div will be updated after the call:<br /> <div id="mybox"> </div> <input type="button" value="Update" /> </body> </html> At server side ajax.php file <?php echo '<p>Hi I am some random ' . rand() .' output from the server.</p>'; ?>
{ "pile_set_name": "StackExchange" }
Q: Apparent time-travelling via python's multiprocessing module: surely I've done something wrong I use python for video-game-like experiments in cognitive science. I'm testing out a device that detects eye movements via EOG, and this device talks to the computer via USB. To ensure that data is being continuously read from the USB while the experiment does other things (like changing the display, etc), I thought I'd use the multiprocessing module (with a multicore computer of course), put the USB reading work in a separate worker process, and use a queue to tell that worker when events of interest occur in the experiment. However, I've encountered some strange behaviour such that even when there is 1 second between the enqueuing of 2 different messages to the worker, when I look at the worker's output at the end, it seems to have received the second almost immediately after the first. Surely I've coded something awry, but I can't see what, so I'd very much appreciate help anyone can provide. I've attempted to strip down my code to a minimal example demonstrating this behaviour. If you go to this gist: https://gist.github.com/914070 you will find "multiprocessing_timetravel.py", which codes the example, and "analysis.R", which analyzes the "temp.txt" file that results from running "multiprocessing_timetravel.py". "analysis.R" is written in R and requires you have the plyr library installed, but I've also included example of the analysis output in the "analysis_results.txt" file at the gist. A: Ah, I solved it and it turned out to be much simpler than I expected. There were 5 events per "trial" and the final event triggered a write of data to the HD. If this final write takes a long time, the worker may not grab the next trial's first event until the second event has already been put into the queue. When this happens, the first event lasts (to the worker's eyes) for only one of its loops before it encounters the second event. I'll have to either figure out a faster way to write out the data or leave the data in memory until a break in the experiment permits a long write.
{ "pile_set_name": "StackExchange" }
Q: "Das ist kein Thema" - What does it mean? Recently I moved to the Konstanz area, and what I noticed is people saying "Das ist kein Thema" for everything. So, what exactly does it mean? And when to use it? A: Usually, this is used in the sense of "no problem". "Kannst Du mich bitte heute abend vom Kino abholen?" -- "Klar, kein Thema." "Das ist aber ganz schön teuer." -- "Geld ist kein Thema." It can of course be used literally, for example when someone is reprimanded for bringing up a topic they shouldn't have: "Gestern hatte ich scheußlichen Durchfall." -- "Das ist kein Thema für den Esstisch!" ...or when discussing a list of topics: "Sprecht Ihr dann auch über Umweltverschmutzung?" -- "Nein, das ist in der Konferenz kein Thema." A: The basic meaning is "This is no topic requiring further discussion". It can be used in many contexts, such as to avert expressions of gratitude, or to acknowledge a request. Similar phrases that also cover a wide range of uses include kein Ding (regional) and kein Problem. Kannst du das bis morgen mittag erledigen? – Kein Thema. Vielen herzlichen Dank dafür! – Kein Thema. Tut mir leid, daß ich so spät bin. – Kein Thema.
{ "pile_set_name": "StackExchange" }
Q: Fetching Customer firstName lastName I want to output a list of all orders of all customers, including customers first name and last name. But can't get these two elements. What I have now is: {% set pastOrders = craft.commerce.orders.find() %} {% for order in pastOrders %} {% for item in order.lineItems %} <tr> <td>{{ order.id }}</td> <td>{{ craft.commerce.customer.firstName }}</td> <td>{{ craft.commerce.customer.lastName }}</td> <td>{{ item.description }}</td> <td>{{ order.email }}</td> <td>{{ item.options.evenement }}</td> <td>{{ item.note }}</td> <td>{{order.orderStatus.name}}</td> <td>{{ order.datePaid.localeDate() }}</td> </tr> {% endfor %} {% endfor %} But as you may guess, I've got an error in both fields firstName lastName A: Not all orders will necessarily have a craft user associated with the order. But all orders must have a billing address, so: order.billingAddress.firstName and order.billingAddress.lastName will get you what you need.
{ "pile_set_name": "StackExchange" }
Q: myFunction is not defined with ActiveAdmin form & Rails I don't understand why I have this issue. It's like my function hiddenField() is not read. My form : f.input :contact, :as => :radio, :collection => ["slide", "formulaire de contact", "map", "video"], input_html: {:class => "select", :onblur => "hiddenField()"} f.input :title_map, label: I18n.t('title_map'), input_html: {:class => "hidden_title"}, placeholder: "Entrer un titre pour la map" My Script : var ready; ready = function() { function hiddenField() { $(".select").on( 'click', function() { document.getElementsByClassName("hidden_title").removeAttribute("input"); }; }; hiddenField(); }; $(document).ready(ready); $(document).on('page:load', ready); Thanks. EDIT : Sorry, I forgot. My form is in admin/page.rb. I use ActiveAdmin. A: $(function() { $('.select').change(function() { $('.hidden_title').removeAttr('input') }) })
{ "pile_set_name": "StackExchange" }
Q: Where should I put my htaccess files from my 301 redirect? We are switching from Cart32 (powered by ASP.Net) to OpenCart (powered by php). We have links all over the site pointing to the older cart location. We also have an older cart on our site consisting of a bunch of html pages that I used a META redirect on, but want to switch to a 301 redirect for these pages as well. I want to redirect these pages: /cgi-bin/cart32.exe/TLDM-store /products/OrderForm/Default.htm to /store/ I got this code for the first one: # Permanent URL redirect - generated by www.rapidtables.com Redirect 301 /cgi-bin/cart32.exe/TLDM-store http://www.tldm.org/store/ And this for the second one: # Permanent URL redirect - generated by www.rapidtables.com Redirect 301 /products/OrderForm/Default.htm http://www.tldm.org/store/ Where should I put these htaccess files? In the root directory or in the /cgi-bin/ and /products/ folders respectively. A: From the documentation : A [htaccess] file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof. Both solutions will work (in the root directory vs in sub directories), the difference is a matter of taste. If you have only two rules I would put them in the same file at the root folder, if you have more rules I would probably split them. A third (better) solution, if you have access to the server configuration, is to put the rewrite rules there : In general, you should only use .htaccess files when you don't have access to the main server configuration file. [...] Likewise, mod_rewrite directives work better, in many respects, in the main server configuration. Don't forget to enable and check the debug logs for the rewrite module say (RewriteLog and RewriteLogLevel for apache 2.2, LogLevel for apache 2.4) if you have troubles with rules that don't apply.
{ "pile_set_name": "StackExchange" }
Q: Center logo and nav links vertically in header I have just started my website, and I am currently working on the header/navigation bar. I've got it looking how I want, however the one thing I can't figure out, is how to centre the logo and hyperlinks vertically in the header? Here is my HTML: <body> <div class="header"> <div class="container"> <div class="logo"> <h1><a href="index.html"><img src="logo.png"></a></h1> </div> <div class="nav"> <ul> <li><a href="index.html">ABOUT ME</a></li> <li><a href="">PROJECTS</a></li> <li><a href="">CONTACT</a></li> </ul> </div> </div> </div> <div class="content"> <p> </p> </div> </body> And CSS: body { font-family: 'Nunito', sans-serif; width: 100%; margin: auto; background: #F4F4F4; } a { text-decoration: none; color: #fff; } img { max-width: 100%; } /********************************** HEADING/NAVIGATION ***********************************/ li { list-style: none; float: left; margin-left: 25px; padding-top: 10px; } .container { width: 960px; margin: 0 auto; } .header { background: #5BBB9B; width: 100%; height: 200px; top: 0; position: fixed; border-bottom: 1px solid black; } .logo { float: left; } .nav { float: right; } I have tried using vertical-alignment: middle;, however this didn't work. Anyone have any suggestions? A: Use display:table; height:100%; for the parent and display: table-cell; text-align: center; vertical-align: middle; and check out this awesome article: https://css-tricks.com/centering-in-the-unknown/
{ "pile_set_name": "StackExchange" }
Q: How do I download a file from SourceForge with wget? I am writing a script which needs to download a release file from sourceforge. How to get the good link? The same question and its answer was given here in 2013, but it does not work anymore. https://unix.stackexchange.com/questions/86971/how-do-i-download-from-sourceforge-with-wget $ wget 'http://downloads.sourceforge.net/project/romfs/genromfs/0.5.2/genromfs-0.5.2.tar.gz' Saving to: ‘download?use_mirror=vorboss.html’ Update: log following @vookimedlo's answer: $ ls -ld $(which wget) lrwxr-xr-x 1 david admin 30 Mar 29 16:17 /usr/local/bin/wget -> ../Cellar/wget/1.19.1/bin/wget $ wget --version GNU Wget 1.19.1 built on darwin16.4.0. -cares +digest -gpgme +https +ipv6 -iri +large-file -metalink -nls +ntlm +opie -psl +ssl/openssl Wgetrc: /Users/david/.wgetrc (user) /usr/local/etc/wgetrc (system) Compile: clang -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/usr/local/etc/wgetrc" -DLOCALEDIR="/usr/local/Cellar/wget/1.19.1/share/locale" -I. -I../lib -I../lib -I/usr/local/opt/openssl/include -DNDEBUG Link: clang -DNDEBUG -liconv -L/usr/local/opt/openssl/lib -lssl -lcrypto -ldl -lz ftp-opie.o openssl.o http-ntlm.o ../lib/libgnu.a $ wget --content-disposition -c https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2 --2017-07-25 10:55:27-- https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2 Resolving sourceforge.net... 216.34.181.60 Connecting to sourceforge.net|216.34.181.60|:443... connected. HTTP request sent, awaiting response... HTTP/1.1 302 Found Server: nginx Date: Tue, 25 Jul 2017 08:55:28 GMT Content-Type: text/html; charset=UTF-8 Content-Length: 365 Connection: close Pragma: no-cache Cache-Control: no-cache X-UA-Compatible: IE=edge,chrome=1 X-Frame-Options: SAMEORIGIN Content-Security-Policy: upgrade-insecure-requests Set-Cookie: VISITOR=2b8474db-e3d7-4710-8a3d-974b86ef1b5a; expires="Fri, 23-Jul-2027 08:55:28 GMT"; httponly; Max-Age=315360000; Path=/ Set-cookie: sourceforge=bcda7ec9e4ed439a64c5e64e590620b984ed89bcgAJ9cQEoVQVwcmVmc3ECfXEDVQ5fYWNjZXNzZWRfdGltZXEER0HWXcHgBmPgVQNrZXlxBVUkMmI4NDc0ZGItZTNkNy00NzEwLThhM2QtOTc0Yjg2ZWYxYjVhcQZVDl9jcmVhdGlvbl90aW1lcQdHQdZdweAGY9xVA19pZHEIVSA0MzRjODBmYjk0NjM0ZGNmYjU4Y2JhYWIxODdkMjVkN3EJdS4=; expires=Tue, 19-Jan-2038 03:14:07 GMT; httponly; Path=/; secure Location: https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000 Location: https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download [following] --2017-07-25 10:55:28-- https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download Connecting to sourceforge.net|216.34.181.60|:443... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Server: nginx Date: Tue, 25 Jul 2017 08:55:28 GMT Content-Type: text/html; charset=utf-8 Content-Length: 128476 Connection: close Pragma: no-cache Cache-Control: no-cache X-UA-Compatible: IE=edge,chrome=1 X-Frame-Options: SAMEORIGIN Content-Security-Policy: upgrade-insecure-requests Set-Cookie: VISITOR=2b8474db-e3d7-4710-8a3d-974b86ef1b5a; expires="Fri, 23-Jul-2027 08:55:28 GMT"; httponly; Max-Age=315360000; Path=/ Set-cookie: sourceforge=797e45184f27a13d79e45d16b390a5e0bc9ef06dgAJ9cQEoVQhfZXhwaXJlc3ECY2RhdGV0aW1lCmRhdGV0aW1lCnEDVQoH9gETAw4HAAAAhVJxBFUDX2lkcQVVIDQzNGM4MGZiOTQ2MzRkY2ZiNThjYmFhYjE4N2QyNWQ3cQZVBmRsaGlzdHEHXXEIfXEJKFUHcmVsZWFzZXEKfXELKFUEZGF0ZXEMaANVCgfhBQ0KNwAAAACFUnENVQpzZl9maWxlX2lkcQ5KtGSWAVUIZmlsZW5hbWVxD1gjAAAAL2ZyZWV0eXBlMi8yLjgvZnJlZXR5cGUtMi44LnRhci5iejJxEHVVB3Byb2plY3RxEX1xEihVCXNob3J0bmFtZXETWAgAAABmcmVldHlwZXEUVQVzZl9pZHEVTVUMVQRuYW1lcRZYFAAAAFRoZSBGcmVlVHlwZSBQcm9qZWN0cRd1dWFVA2tleXEYVSQyYjg0NzRkYi1lM2Q3LTQ3MTAtOGEzZC05NzRiODZlZjFiNWFxGVUKY3VycmVudF9vc3EaXXEbKFUFd2luMzJxHFUHV2luZG93c3EdZVUFcHJlZnNxHn1xH1UOX2FjY2Vzc2VkX3RpbWVxIEdB1l3B4C2D8VUOX2NyZWF0aW9uX3RpbWVxIUdB1l3B4AZj3HUu; expires=Tue, 19-Jan-2038 03:14:07 GMT; httponly; Path=/; secure X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000 Length: 128476 (125K) [text/html] Last-modified header missing -- time-stamps turned off. --2017-07-25 10:55:28-- https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download Connecting to sourceforge.net|216.34.181.60|:443... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Server: nginx Date: Tue, 25 Jul 2017 08:55:29 GMT Content-Type: text/html; charset=utf-8 Content-Length: 143733 Connection: close Pragma: no-cache Cache-Control: no-cache X-UA-Compatible: IE=edge,chrome=1 X-Frame-Options: SAMEORIGIN Content-Security-Policy: upgrade-insecure-requests Set-Cookie: VISITOR=2b8474db-e3d7-4710-8a3d-974b86ef1b5a; expires="Fri, 23-Jul-2027 08:55:29 GMT"; httponly; Max-Age=315360000; Path=/ Set-cookie: sourceforge=b5bd929d9431625f7b220b04e97d1949367d4ed4gAJ9cQEoVQhfZXhwaXJlc3ECY2RhdGV0aW1lCmRhdGV0aW1lCnEDVQoH9gETAw4HAAAAhVJxBFUDX2lkcQVVIDQzNGM4MGZiOTQ2MzRkY2ZiNThjYmFhYjE4N2QyNWQ3cQZVBmRsaGlzdHEHXXEIfXEJKFUHcmVsZWFzZX1xCihVBGRhdGVoA1UKB+EFDQo3AAAAAIVScQtVCnNmX2ZpbGVfaWRKtGSWAVUIZmlsZW5hbWVYIwAAAC9mcmVldHlwZTIvMi44L2ZyZWV0eXBlLTIuOC50YXIuYnoydVUHcHJvamVjdH1xDChVCXNob3J0bmFtZVgIAAAAZnJlZXR5cGVVBXNmX2lkTVUMVQRuYW1lWBQAAABUaGUgRnJlZVR5cGUgUHJvamVjdHV1YVUDa2V5cQ1VJDJiODQ3NGRiLWUzZDctNDcxMC04YTNkLTk3NGI4NmVmMWI1YXEOVQpjdXJyZW50X29zcQ9dcRAoVQV3aW4zMnERVQdXaW5kb3dzcRJlVQVwcmVmc3ETfXEUVQ5fYWNjZXNzZWRfdGltZXEVR0HWXcHgU/ahVQ5fY3JlYXRpb25fdGltZXEWR0HWXcHgBmPcdS4=; expires=Tue, 19-Jan-2038 03:14:07 GMT; httponly; Path=/; secure X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000 Length: 143733 (140K) [text/html] Saving to: ‘download.html’ download.html 100%[============================================================================================================>] 140.36K 338KB/s in 0.4s 2017-07-25 10:55:29 (338 KB/s) - ‘download.html’ saved [143733/143733] A: You could use wget only if you are fine that you will use an experimental functionality, which is the required "--content-disposition" option. wget --content-disposition -c https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2 All redirections are handled automagically, see the output below. --2017-07-22 22:26:05-- https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2 Resolving sourceforge.net... 216.34.181.60 Connecting to sourceforge.net|216.34.181.60|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download [following] --2017-07-22 22:26:06-- https://sourceforge.net/projects/freetype/files/freetype2/2.8/freetype-2.8.tar.bz2/download Connecting to sourceforge.net|216.34.181.60|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://downloads.sourceforge.net/project/freetype/freetype2/2.8/freetype-2.8.tar.bz2?r=&ts=1500755167&use_mirror=kent [following] --2017-07-22 22:26:07-- https://downloads.sourceforge.net/project/freetype/freetype2/2.8/freetype-2.8.tar.bz2?r=&ts=1500755167&use_mirror=kent Resolving downloads.sourceforge.net... 216.34.181.59 Connecting to downloads.sourceforge.net|216.34.181.59|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://kent.dl.sourceforge.net/project/freetype/freetype2/2.8/freetype-2.8.tar.bz2 [following] --2017-07-22 22:26:08-- https://kent.dl.sourceforge.net/project/freetype/freetype2/2.8/freetype-2.8.tar.bz2 Resolving kent.dl.sourceforge.net... 212.219.56.185 Connecting to kent.dl.sourceforge.net|212.219.56.185|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1873526 (1.8M) [application/octet-stream] --2017-07-22 22:26:08-- https://kent.dl.sourceforge.net/project/freetype/freetype2/2.8/freetype-2.8.tar.bz2 Connecting to kent.dl.sourceforge.net|212.219.56.185|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1873526 (1.8M) [application/octet-stream] Saving to: ‘freetype-2.8.tar.bz2’ freetype-2.8.tar.bz2 100%[==========================================================================================================>] 1.79M 5.60MB/s in 0.3s 2017-07-22 22:26:08 (5.60 MB/s) - ‘freetype-2.8.tar.bz2’ saved [1873526/1873526] Update to provide more details ➜ ~ ls -ld $(which wget) lrwxr-xr-x 1 duda admin 32 4 črv 19:44 /usr/local/bin/wget -> ../Cellar/wget/1.19.1_1/bin/wget ➜ ~ wget --version GNU Wget 1.19.1 built on darwin16.6.0. -cares +digest -gpgme +https +ipv6 -iri +large-file -metalink -nls +ntlm +opie -psl +ssl/openssl Wgetrc: /usr/local/etc/wgetrc (system) Compile: clang -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/usr/local/etc/wgetrc" -DLOCALEDIR="/usr/local/Cellar/wget/1.19.1_1/share/locale" -I. -I../lib -I../lib -I/usr/local/opt/[email protected]/include -DNDEBUG Link: clang -DNDEBUG -liconv -L/usr/local/opt/[email protected]/lib -lssl -lcrypto -ldl -lz ftp-opie.o openssl.o http-ntlm.o ../lib/libgnu.a Copyright (C) 2015 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://www.gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Originally written by Hrvoje Niksic <[email protected]>. Please send bug reports and questions to <[email protected]>.
{ "pile_set_name": "StackExchange" }
Q: Cannot draw on canvas with custom view I have a class GameActivityas follows (I just post the relevant part): public class GameActivity extends AppCompatActivity { // initiate variables private GameView mGameView; private Display mDisplay; private Point mSize; public static int window_width = 0; public static int window_height = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); mDisplay = getWindowManager().getDefaultDisplay(); mSize = new Point(); mDisplay.getSize(mSize); window_width = mSize.x; window_height = mSize.y; // initialize game view object mGameView = new GameView(this); // adding it to the content view //setContentView(mGameView); setContentView(R.layout.activity_game); } And I have the class GameView as follows with two constructors because of the custom view (also just the relevant parts to keep it clear): private Context mContext; //These objects will be used for drawing private SurfaceHolder mSurfaceHolder; private Paint mPaint; public GameView(Context context){ super(context); Log.d("TEST","Constructor 1"); init(context, null); // clear all lists ... // create object of map in beginning of game ... // create objects of HQs ... // create other sprite objects and add them to lists ... } public GameView(Context context, AttributeSet attrs) { super(context, attrs); Log.d("TEST","Constructor 2"); init(context, attrs); } And I call in both of the constructors the init() method private void init(Context context, AttributeSet attrs) { mContext = context; mSurfaceHolder = getHolder(); mPaint = new Paint(); mPaint.setColor(Color.DKGRAY); } My run() is like this: @Override public void run(){ Log.d("TEST","RUN"); long current_time = 0; long old_time; while (playing) { old_time = current_time; // update the game update(); //to draw the frame //onDraw(canvas); draw(); //to control (lets the game sleep for some milliseconds) control(); current_time = SystemClock.elapsedRealtime(); frametime = current_time - old_time; framerate = 1000/ (current_time - old_time); } } And the draw() (where the mistake happens) is like this: private void draw() { // BUG: mSurfaceHolder.getSurface.isValid ist niemals valid Canvas canvas; //if(true){ //checking if surface is valid if (mSurfaceHolder.getSurface().isValid()) { Log.d("Test","DRAW"); //locking the canvas canvas = mSurfaceHolder.lockCanvas(); //drawing a background color for canvas canvas.drawColor(Color.GREEN); // call draw methods here // bigger objects should be called before smaller objects for visibility draw_ground(canvas); draw_hq(canvas); draw_soldiers(canvas); draw_bullets(canvas); draw_HUD(canvas); //Unlocking the canvas mSurfaceHolder.unlockCanvasAndPost(canvas); } } No the question is: If I in the first class GameActivity pass the object mGameView of the class GameView to setContentView everything is fine and the draw() methods works normal which means mSurfaceHolder.getSurface().isValid()) is valid. But if I put in the first class setContentView(R.layout.activity_game); then mSurfaceHolder.getSurface().isValid()) is never valid. Everything else works (e.g. I hear the game sound) but he doesn't draw. If I don't check for mSurfaceHolder.getSurface().isValid()) then the game crashes because in the code below in draw() the canvas is empty. My aim is to create a custom view and overlay this with buttons. Here is the XML: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".GameActivity"> <!--Test--> <com.example.mirco.battlefront.GameView android:id="@+id/gameView" android:layout_width="match_parent" android:layout_height="match_parent" /> <Button android:id="@+id/button" android:layout_width="119dp" android:layout_height="wrap_content" android:text="Button" /> <!--Test--> </FrameLayout> The XML seems to be correct because Android Studio recognizes it (custom view with overlayed button). But he doesn't draw in it. Like I said with setContentView(mGameView); everything is fine except that I only have one view where I can't overlay buttons and so on which is not what I want. What am I doing wrong? I tried to follow that LINK as good as possible. I am trying for days now to solve this but also can't find the solution anywhere. A: Instead of mGameView = new GameView(this); // adding it to the content view //setContentView(mGameView); setContentView(R.layout.activity_game); You should do setContentView(R.layout.activity_game); mGameView = (GameView)findViewById (R.id.gameView); Then the mGameview is the one in your layout.
{ "pile_set_name": "StackExchange" }
Q: Tag rename request: "standards" => "community-guidelines" Title says it all. So it's a "title-only question" ;-) A: Thanks Mark for bringing this up. Following up on our Slack discussion, I agree that it makes more sense for standards to be changed to community-guidelines. I would be more than happy to go through this list and retag myself. Or we can wait for Robert.
{ "pile_set_name": "StackExchange" }
Q: What does it mean for a program to link to both libstdc++ and libc++? Recently, I saw a C++ program list both libstdc++ and libc++ in its dynamic section (readelf -d). I’m confused because one is from GNU and the other from LLVM and they are both implementations of the STL. Then how can a program link both? What’s that mean? How does it resolve a symbol (std::string, for example) that both provide, when linking? A: This might for example happen if a program links with one standard-library implementation and also with a static library that links to the other. This wouldn’t cause an issue because names such as std::string are mangled into something longer and more complicated that won’t clash. (This is also how functions with the same name can be overloaded and called with different argument types, and why programs written for older versions of the standard library don’t break when it’s upgraded.) One important caveat: this only works if the STL is not part of the interface of any component that links to a different version. Otherwise, any client code will compile against a different version of the standard library than it links to when it calls that component, or even pass the wrong data structures to and from the library.
{ "pile_set_name": "StackExchange" }
Q: Electronics Blogs and Podcasts There are some great blogs out there for programmers (Joel on Software, Paul Graham's Essays, etc.). I would love to know about any similar quality content for electronics. Do you have any great blogs or podcasts you love? (submit one answer for each blog) A: Electronics Engineering Video Blog Podcast(eevblog) A: Chris Gammell's Analog Life A: http://www.hackaday.com
{ "pile_set_name": "StackExchange" }
Q: Java custom annotation not visible For my project I am converting classes to json with jackson fasterXml. Now I have to change in one place the way the objects are converted so that @JsonIgnore is ignored and the property is serialised. I found out that I can do this with extending a JacksonAnnotationIntrospector and a custom annotation. The problem is that the custom annotation is only visible if it is defined in the same package/project/osgi bundle as the implementing class while I would like to define it in the service package which exposes the json convertion. If the annotation is in the implementing package, I cannot reference it in the JacksonAnnotationIntrospector and I would need to check on the name of the annotation. I have two identical annotations with only difference the package: import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotationName { } When I set both on the implementation, I only see the annotation defined from within the same package/project/osgi bundle as the implementation class. Is there a constraint regarding this or has anyone an idea what could be the problem? A: Put your custom annotation in a unique package ideally using a reverse domain name you control. Put this into a separate API bundle (at least for now). In your user code add the API bundle to the maven dependencies and use the new annotation. The maven-bundle-plugin (or what you use) should create an Import-Package statement in your Manifest. This will make sure the annotation can be wired at runtime. In the code where you parse the annotations make sure you use the classloader of the user bundle. This classloader should be able to see the standard annotations as well as the custom one.
{ "pile_set_name": "StackExchange" }
Q: Bash script not working with `sh` I'm testing a simple script and I'm wondering why it works fine when executed from directory: ./test.sh but when I try with "sh" command sh test.sh it's not working: test.sh: 3: test.sh: [[: not found test.sh: 7: test.sh: [[: not found Script: #!/usr/bin/env bash if [[ $1 = one ]] then printf "%b" "two\n" >&2 exit 0 elif [[ $1 = two ]] then printf "%b" "one\n" >&2 exit 0 else printf "%b" "Specify argument: one/two\n" exit 1 fi A: Summary sh is a different program than bash. Detail The problem is that the Bourne shell (sh) is not the Bourne Again shell (bash). Namely, sh doesn't understand the [[ pragma. In fact, it doesn't understand [ either. [ is an actual program or link to /bin/test (or /usr/bin/[, /usr/bin/test). $ which [ /bin/[ $ ls -lh /bin/[ -r-xr-xr-x 2 root wheel 42K Feb 29 17:11 /bin/[ When you execute your script directly through ./test.sh, you're calling the script as the first argument to the program specified in the first line. In this case: #!/usr/bin/env bash Often, this is directly the interpreter (/bin/bash, or any number of other script interpreters), but in your case you're using env to run a program in a modified environment -- but that follow argument is still bash. Effectively, ./test.sh is bash test.sh. Because sh and bash are different shells with different syntax interpretations, you're seeing that error. If you run bash test.sh, you should see what is expected. More info Others have pointed out in comments that /bin/sh can be a link or other shell. Historically, sh was the Bourne shell on the old AT&T Unix, and in my mind the canonical descent. However, that is different in BSD variations and has diverged in other Unix based systems and distributions over time. If you're really interested in the inner workings (including how /bin/sh and /bin/bash can be the same program and behave totally differently), read the following: SuperUser: What is the difference between bash and sh Wikipedia: Bourne shell A: As noted: /bin/sh typically (though not always) invokes a POSIX-compliant Bourne shell. Bash is Not Bourne. Bash will attempt to emulate Bourne when invoked as 'sh' (as when /bin/sh symlinks or links to /bin/bash), or if $POSIXLY_CORRECT is defined in the invoking environment, when invoked with the --posix invocation option, or when 'set -o posix' has been executed. This enables testing a Bourne shell script / command for POSIX compliance. Alternately, invoke scripts / test commands with a known POSIX-compliant shell. 'dash' is close, the Korn shell (ksh) IIRC offers a POSIX compliant option as well.
{ "pile_set_name": "StackExchange" }
Q: Recover User account in virtual machine (after trying to extend memory) I installed Ubuntu 14.04 in virtual box. Now the desktop doesn't appear after I log in with my username. I can still log in with the guest account. I think this is the result from an unsuccessfull memory extension of the virtual machine (the memory was fixed, but I didn't realise this until after) or from trying to update to Ubuntu 16.04. without having enough disk space. Is there any way to retrieve the files on my user account? A: This is no attempt to rescue your broken installation (we don't know what went wrong) but to show you how to recover files from your HOME when the virtual OS won't boot. Create a new virtual machine You may want to recreate a running virtual machine anyway - so it is the best time to do that now. Please also create a new virtual disk (VDI) file for your new installation an make it large enough to not run out of space again. When creating a dynamically growing disk it will not use up more physical space than needed but it can grow up to the size we gave it on demand. So it is safe to create a large virtual drive (tak 50 or 100 GByte if your system allows this). Bind the old virtual disk to your new virtual machine If all is set up to your liking you may want to copy your personal files from the broken virtual machine. To do so you just add the old VDI-file that holds your broken Ubuntu: You will see that you new Ubuntu is able to mount this drive with Nautilus. Then you can browse files and copy them over to your new machine. As long as you don't delete the old VDI you have all the time you need to do so. When all is finished you can remove the old drive from the virtual machine.
{ "pile_set_name": "StackExchange" }
Q: MongooseIM REST API's not working for POST requests Have anyone tried the MongooseIM 2.0.0 Bets services to hit web services. I am able to to the GET calls as defined in this Swagger site link but unable to get the POST request as it gives me error for the same data that I use with my IP address instead of localhost. Here in my Mongoose Im error response. ] emulator Error in process <0.4026.0> on node mongooseim@localhost with exit value: {{nocatch,[{reason,{error,{3,invalid_json}}},{mfa,{mongoose_api_admin,from_json,2}},{stacktrace,[{jiffy,decode,2,[{file,"src/jiffy.erl"},{line,68}]},{mongoose_api_common,parse_request_body,1,[{file,"src/mongoose_api_common.erl"},{line,169}]},{mongoose_api_admin,from_json,2,[{file,"src/mongoose_api_admin.erl"},{line,114}]},{cowboy_rest,call,3,[{file,"src/cowboy_rest.erl"},{line,976}]},{cowboy_rest,process_content_type,3,[{file,"src/cowboy_rest.erl"},{line,777}]},{cowboy_protocol,execute,4,[{file,"src/cowboy_protocol.erl"},{line,442}]}]},{req,[{socket,#Port<0.35385>},{transport,ranch_tcp},{connection,keepalive},{pid,<0.4026.0>},{method,<<"POST">>},{version,'HTTP/1.1'},{peer,{{118,200,26,4},1036}},{host,<<"ec2-54-111-111-111.ap-southeast-1.compute.amazonaws.com">>},{host_info,undefined},{port,8090},{path,<<"/api/messages">>},{path_info,undefined},{qs,<<>>},{qs_vals,undefined},{bindings,[]},{headers,[{<<"host">>,<<"ec2-54-111-111-111.ap-southeast-1.compute.amazonaws.com:8090">>},{<<"user-agent">>,<<"curl/7.49.1">>},{<<"content-type">>,<<"application/json">>},{<<"accept">>,<<"application/json">>},{<<"content-length">>,<<"208">>}]},{p_headers,[{<<"content-type">>,{<<"application">>,<<"json">>,[]}},{<<"if-modified-since">>,undefined},{<<"if-none-match">>,undefined},{<<"if-unmodified-since">>,undefined},{<<"if-match">>,undefined},{<<"accept">>,[{{<<"application">>,<<"json">>,[]},1000,[]}]}]},{cookies,undefined},{meta,[{media_type,{<<"application">>,<<"json">>,[]}},{charset,undefined}]},{body_state,waiting},{buffer,<<"{ \ \n \"caller\": \"+6512345699@ec2-54-111-111-111.ap-southeast-1.compute.amazonaws.com\", \ \n \"to\": \"+6512345678@ec2-54-111-111-111.ap-southeast-1.compute.amazonaws.com\", \ \n \"body\": \"Hi Rabbit!\" \ \n }">>},{multipart,undefined},{resp_compress,false},{resp_state,waiting},{resp_headers,[{<<"content-type">>,[<<"application">>,<<"/">>,<<"json">>,<<>>]}]},{resp_body,<<>>},{onresponse,undefined}]},{state,{http_api_state,[<<"GET">>,<<"POST">>,<<"POST">>,<<"GET">>,<<"POST">>,<<"GET">>,<<"POST">>,<<"POST">>,<<"POST">>,<<"GET">>,<<"GET">>,<<"DELETE">>,<<"DELETE">>,<<"POST">>,<<"DELETE">>,<<"POST">>,<<"PUT">>],[],undefined,<<"messages">>,undefined,admin,[]}}]},[{cowboy_rest,process_content_type,3,[{file,"src/cowboy_rest.erl"},{line,777}]},{cowboy_protocol,execute,4,[{file,"src/cowboy_protocol.erl"},{line,442}]}]} 2016-11-02 05:25:37.428 [error] <0.4026.0> Ranch listener 'ejabberd_cowboy_166.36.16.166_8090' terminated with reason: {nocatch,[{reason,{error,{3,invalid_json}}},{mfa,{mongoose_api_admin,from_json,2}},{stacktrace,[{jiffy,decode,2,[{file,"src/jiffy.erl"},{line,68}]},{mongoose_api_common,parse_request_body,1,[{file,"src/mongoose_api_common.erl"},{line,169}]},{mongoose_api_admin,from_json,2,[{file,"src/mongoose_api_admin.erl"},{line,114}]},{cowboy_rest,call,3,[{file,"src/cowboy_rest.erl"},{line,976}]},{cowboy_rest,process_content_type,3,[{file,"src/cowboy_rest.erl"},{line,777}]},{cowboy_protocol,execute,4,[{file,...},...]}]},...]} in cowboy_rest:process_content_type/3 line 777 A: This was probably answered here: https://github.com/esl/MongooseIM/issues/1055 already. Am I right?
{ "pile_set_name": "StackExchange" }
Q: Collecting and using data returned from a http Curl (php) Post I need assistance with using the data returned after a http post. Below is my current post code that posts the data to a specific website <?php //extract data from the post extract($_POST); //set POST variables $url = 'https://test.com'; $fields = array( 'surname' => urlencode($surname), 'first_name' => urlencode($first_name), 'dob' => urlencode($dob), 'email' => urlencode($email), 'home_phone' => urlencode($home_phone), 'mobile_phone' => urlencode($mobile_phone), 'work_phone' => urlencode($work_phone), 'postcode' => urlencode($postcode), 'leadid' => urlencode(123), 'affid' => urlencode(123), 'subid' => urlencode(123), 'bank_acno' => urlencode($bank_acno), 'bank_sort' => urlencode($bank_sort), 'amount_required' => urlencode($amount_required), ); //url-ify the data for the POST foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string, '&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_POST, count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?> I get either one of 2 response's - {result:true} or {result:false} I need to know is how to do the following : When I get a {result:true} I want to redirect to url "http://thisurl.com" When I get a {result:false} I want to return a response "Denied" Please note the response is not json , it is just returned in that format. A: You need to check what $result variable contains and then make the redirect or show denied message according to situation: <?php //extract data from the post extract($_POST); //set POST variables $url = 'https://test.com'; $fields = array( 'surname' => urlencode($surname), 'first_name' => urlencode($first_name), 'dob' => urlencode($dob), 'email' => urlencode($email), 'home_phone' => urlencode($home_phone), 'mobile_phone' => urlencode($mobile_phone), 'work_phone' => urlencode($work_phone), 'postcode' => urlencode($postcode), 'leadid' => urlencode(123), 'affid' => urlencode(123), 'subid' => urlencode(123), 'bank_acno' => urlencode($bank_acno), 'bank_sort' => urlencode($bank_sort), 'amount_required' => urlencode($amount_required), ); //url-ify the data for the POST foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string, '&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_POST, count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); $result_true = 'true'; $check_true = strpos($result, $result_true); if ($check_true !== false) { header('Location: http://url.com'); die; } $result_false = 'false'; $check_false = strpos($result, $result_false); if ($check_false !== false) { echo "Denied"; } And in your code you've used: curl_setopt($ch,CURLOPT_POST, count($fields)); But in php.net manual: CURLOPT_POST: TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms. So counting fields is not the proper way to do this it could be TRUE or FALSE not the count. Of course if $fields array is empty result will be 0 which is equal to FALSE or if it's 1 then it's 1 (TRUE) but when the result of the count is greater than 1 that's makes no sense.
{ "pile_set_name": "StackExchange" }
Q: Character diff/annotation algorithm I have a set of string representing the history of a document. Each string is the whole document - there has not yet been any diff analysis. I need a relatively efficient algorithm to allow me to annotate substrings of the document with the version they came from. For example, if the document history was like this: Rev1: The quiet fox Rev2: The quiet brown fox Rev3: The quick brown fox The algorithm would give: The quick brown fox 1111111331222222111 i.e. "The qui" was added in revision 1, "ck" was added in revision 3, " " was added in revision 1, "brown " was added in revision 2 and finally "fox" was added in revision 1. A: I have a class library that can do this easily, though I don't know how well it performs performance-wise with large or many such revisions. The library is here: DiffLib on CodePlex (you can also install it through NuGet.) The script for your example in the question is here (you can run this in LINQPad if you add a reference to the DiffLib assembly): void Main() { var revs = new string[] { "The quiet fox", "The quiet brown fox", "The quick brown fox", "The quick brown fox.", "The quick brown fox jumped over the lazy dog.", "The quick brown fox jumped over the lazy cat.", "The Quick Brown Fox jumped over the Lazy Cat.", }; string current = revs[0]; List<int> owner = new List<int>(); foreach (char c in current) owner.Add(1); // owner 1 owns entire string Action<int> dumpRev = delegate(int rev) { Debug.WriteLine("rev " + rev); Debug.WriteLine(current); Debug.WriteLine(new string(owner.Select(i => (char)(48 + i)).ToArray())); Debug.WriteLine(""); }; dumpRev(0); for (int index = 1; index < revs.Length; index++) { int ownerId = index + 1; var diff = new DiffLib.Diff<char>(current, revs[index]).ToArray(); int position = 0; foreach (var part in diff) { if (part.Equal) position += part.Length1; else { // get rid of old owner for the part that was // removed or replaced for (int index2 = 0; index2 < part.Length1; index2++) owner.RemoveAt(position); // insert new owner for the part that was // added or did replace the old text for (int index2 = 0; index2 < part.Length2; index2++) owner.Insert(position, ownerId); position += part.Length2; } } current = revs[index]; dumpRev(index); } } The output: rev 0 The quiet fox 1111111111111 rev 1 The quiet brown fox 1111111111222222111 rev 2 The quick brown fox 1111111331222222111 rev 3 The quick brown fox. 11111113312222221114 rev 4 The quick brown fox jumped over the lazy dog. 111111133122222211155555555555555555555555554 rev 5 The quick brown fox jumped over the lazy cat. 111111133122222211155555555555555555555556664 rev 6 The Quick Brown Fox jumped over the Lazy Cat. 111171133172222271155555555555555555755557664
{ "pile_set_name": "StackExchange" }
Q: R Shiny: Editing DT with locked columns I am trying to have a DT that is editable by the user but I only want certain columns to be editable. Since this isn't a feature yet in DT, I am trying to hack it together by having the table refresh back to the original value when edited a column that I want "locked". Below is my code: library (shiny) library (shinydashboard) library (DT) library (dplyr) library (data.table) rm(list=ls()) ###########################/ui.R/################################## #Header---- header <- dashboardHeaderPlus() #Left Sidebar---- sidebar <- dashboardSidebar() #Body---- body <- dashboardBody( useShinyjs(), box( title = "Editable Table", DT::dataTableOutput("TB") ), box( title = "Backend Table", DT::dataTableOutput("Test") ), box( title = "Choice Selection", DT::dataTableOutput("Test2") ), box( verbatimTextOutput("text1"), verbatimTextOutput("text2"), verbatimTextOutput("text3") ) ) #Builds Dashboard Page---- ui <- dashboardPage(header, sidebar, body) ###########################/server.R/############################### server <- function(input, output, session) { Hierarchy <- data.frame(Lvl0 = c("US","US","US","US","US"), Lvl1 = c("West","West","East","South","North"), Lvl2 = c("San Fran","Phoenix","Charlotte","Houston","Chicago"), stringsAsFactors = FALSE) ########### rvs <- reactiveValues( data = NA, #dynamic data object dbdata = NA, #what's in database editedInfo = NA #edited cell information ) observe({ rvs$data <- Hierarchy rvs$dbdata <- Hierarchy }) output$TB <- DT::renderDataTable({ DT::datatable( rvs$data, rownames = FALSE, editable = TRUE, extensions = c('Buttons','Responsive'), options = list( dom = 't', buttons = list(list( extend = 'collection', buttons = list(list(extend='copy'), list(extend='excel', filename = "Site Specifics Export"), list(extend='print') ), text = 'Download' )) ) ) %>% # Style cells with max_val vector formatStyle( columns = c("Lvl0","Lvl1"), color = "#999999" ) }) observeEvent(input$TB_cell_edit, { info = input$TB_cell_edit i = info$row j = info$col + 1 v = info$value #Editing only the columns picked if(j == 3){ rvs$data[i, j] <<- DT::coerceValue(v, rvs$data[i, j]) #GOOD #Table to determine what has changed if (all(is.na(rvs$editedInfo))) { #GOOD rvs$editedInfo <- data.frame(row = i, col = j, value = v) #GOOD } else { #GOOD rvs$editedInfo <- dplyr::bind_rows(rvs$editedInfo, data.frame(row = i, col = j, value = v)) #GOOD rvs$editedInfo <- rvs$editedInfo[!(duplicated(rvs$editedInfo[c("row","col")], fromLast = TRUE)), ] #FOOD } } else { if (all(is.na(rvs$editedInfo))) { v <- Hierarchy[i, j] rvs$data[i, j] <<- DT::coerceValue(v, rvs$data[i, j]) } else { rvs$data[as.matrix(rvs$editedInfo[1:2])] <- rvs$editedInfo$value } } }) output$Test <- DT::renderDataTable({ rvs$data }, server = FALSE, rownames = FALSE, extensions = c('Buttons','Responsive'), options = list( dom = 't', buttons = list(list( extend = 'collection', buttons = list(list(extend='copy'), list(extend='excel', filename = "Site Specifics Export"), list(extend='print') ), text = 'Download' )) ) ) output$Test2 <- DT::renderDataTable({ rvs$editedInfo }, server = FALSE, rownames = FALSE, extensions = c('Buttons','Responsive'), options = list( dom = 't', buttons = list(list( extend = 'collection', buttons = list(list(extend='copy'), list(extend='excel', filename = "Site Specifics Export"), list(extend='print') ), text = 'Download' )) ) ) output$text1 <- renderText({input$TB_cell_edit$row}) output$text2 <- renderText({input$TB_cell_edit$col + 1}) output$text3 <- renderText({input$TB_cell_edit$value}) } #Combines Dasboard and Data together---- shinyApp(ui, server) Everything works as expected except within the observeEvent where I try to refresh the DT if they edited the wrong column: if (all(is.na(rvs$editedInfo))) { v <- Hierarchy[i, j] rvs$data[i, j] <<- DT::coerceValue(v, rvs$data[i, j]) } else { rvs$data[as.matrix(rvs$editedInfo[1:2])] <- rvs$editedInfo$value } I can't seem to get the DT to coerce back to the original values (the if). Also, when a user has changed values in the correct column and changes something in the wrong column, it doesn't reset the original value (wrong column) while keeping the values changed (corrected column) (the else) EDIT I have tried the following and it coerces as expected to "TEST". I have looked at the class of both v = info$value and v <- Hierarchy[i,j] and they are both character and produce the value that I expect. Cannot figure out why it won't coerce to v <- Hierarchy[i,j]. if (all(is.na(rvs$editedInfo))) { v <- Hierarchy[i, j] v <- "TEST" rvs$data[i, j] <<- DT::coerceValue(v, rvs$data[i, j]) } A: I have added this feature to the development version of DT. remotes::install_github('rstudio/DT') You can find an example in the Table 10 of the Shiny app at https://yihui.shinyapps.io/DT-edit/.
{ "pile_set_name": "StackExchange" }
Q: How get jsonp from remote server? Please help get jsonp-data from remote server: document.addEventListener("DOMContentLoaded", function() { function readresponse(response){ console.log(response); } (function(){ var src = 'http://json-schema.org/draft-04/schema#?callback=readresponse'; var script = document.createElement('SCRIPT'); script.src = src; document.body.appendChild(script); })(); }); But chrome browser tab 'network' display 200 status and correct json response A: If you take a look at the content your src url is returning you will see that it's a JSON and not JSONP. If it were to be JSONP your src should be: var src = 'http://json-schema.org/draft-04/schema&callback=readresponse' and the data it would return would be wrapped as: readresponse({...}) instead of just {...} which is why you receive the parse error. You can find out more on this topic reading this post.
{ "pile_set_name": "StackExchange" }
Q: Fatal error: Cannot redeclare class / Include extern .php I'm very new to PHP and I got the following problem: Everytime I want to run my file, I get this err message: "Fatal error: Cannot redeclare class Customer in /home/www/p161/html/customer-class.php on line 2" My Code looks like this: <?php include 'customer-class.php'; function crateConnection(){ $database_url = "pdb1.pretago.de"; $username = "p161"; $password = "mJMmTGPR"; $db_name = "usr_p161_1"; //Verbindung zur Datenbank herstellen und setzen des ERRORMODE, damit Exceptions abgefangen //werden können. $connection = new PDO("mysql:host=$database_url;dbname=$db_name", $username, $password); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $connection; } function isInDB($customer, $connection){ $stmt = $connection->prepare("SELECT * FROM Customer WHERE mailadresse = :emailaddress "); $stmt->bindParam(':emailaddress', $customer->email); $stmt->execute(); if($stmt->rowCount() == 0){ return false; }else{ return true; } } function insert($customer, $connection){ $statement = $connection->prepare("INSERT INTO Customer (vorname, nachname, strasse, stadt, plz, mailadresse, telefon) VALUES (?,?,?,?,?,?,?)"); //Query ausführen $statement->execute($customer->getDataToStore()) or die("SQL Error: ".$statement->queryString." - ".$statement->errorInfo()[2]); //Verbindung schließen $connection = null; } ?> db-methods.php <?php include 'customer-class.php'; include 'db-methods.php'; /* * Diese Funktion lädt die Form Daten in ein Customer Objekt */ function getCustomer(){ $fname = $_POST["fname"]; $lname = $_POST["lname"]; $street = $_POST["street"]; $city = $_POST["city"]; $place = $_POST["place"]; $email = $_POST["email"]; $phone = $_POST["phone"]; $message = $_POST["message"]; return new Customer($fname, $lname, $street, $city, $place, $email, $phone, $message); } function sendMail($customer){ $empfaenger = "[email protected]"; $betreff = "Kontaktformular von Ihrer Homepage"; $from = "Von $customer->fname, $customer->lname <$customer->email>"; $text = $customer->message; mail($empfaenger, $betreff, $text, $from); } try{ $connection = createConnection(); //Laden der Form Daten in ein Customer Objekt $customer = getCustomer(); if(!isInDB($customer, $connection)){ insert($customer, $connection); } //E-Mail versenden //sendMail($customer); header( 'Location: http://p161.prtg1.pretago.de/wordpress/testseite-fuer-db/'); exit(); }catch(PDOException $exception){ echo "Verbdinung fehlgeschlagen: " . $exception->getMessage(); } ?> contact-form.php <?php class Customer{ var $fname,$lname, $street, $city, $place, $email, $phone, $message; function Customer($fname, $lname, $street, $city, $place, $email, $phone, $message){ $this->fname = $fname; $this->lname = $lname; $this->street = $street; $this->city = $city; $this->place = $place; $this->email = $email; $this->phone = $phone; $this->message = $message; } //Funktion, welche ein Array zurückgibt in welchem die Daten die gespeichert werden sollen enthalten sind function getDataToStore(){ return array($this->fname, $this->lname, $this->street, $this->city, $this->place, $this->email, $this->phone); } } ?> customer-class.php So I've thought that I declared Customer twice, but I can't recognize anything. So I googled, but I can't find an answer. Can anybody help me? A: this because you include class customer file twice, you should use include_once instead, or remove this line include 'customer-class.php'; : <?php //include 'customer-class.php'; include 'db-methods.php'; because you included it in the db-methods.php file before
{ "pile_set_name": "StackExchange" }
Q: Put button on layout bottom always I have the button on the bottom on a RelativeLayout but on the page there are editTexts and when those are active the keyboard pops up and the button doesn't stay on the bottom it moves to above the keyboard. This button is for sending a finished filled in form so I can't have the button moving above the keyboard when it's activated. This is the layout right now <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/lightGray" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/ind_survey_title" android:layout_width="0dp" android:layout_height="wrap_content" android:text="asdfasdfds group" android:textColor="@color/mediumBlue" android:textSize="20sp" app:layout_constrainedWidth="true" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_percent="0.75" /> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" app:layout_constrainedWidth="true" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_percent="0.25"> <ImageView android:id="@+id/ind_survey_anonymous_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleX="0.8" android:scaleY="0.8" android:src="@drawable/ic_x" /> <TextView android:id="@+id/ind_survey_anonymous" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/anonymous" android:textColor="@color/red" android:textSize="14sp" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> <TextView android:id="@+id/ind_survey_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/D5dp" android:paddingStart="@dimen/D20dp" android:paddingEnd="@dimen/D5dp" android:text="" android:textColor="@android:color/black" android:textSize="14sp" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/mediumGray" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/reclycer_view_survey_questions" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/lightGray" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:gravity="end" android:orientation="vertical"> <Button android:id="@+id/sendbtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/login_button" android:minHeight="0dp" android:text="@string/send_survey" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="14sp" /> </LinearLayout> </RelativeLayout> How can I make sure the button doesn't move when the keyboard is active? A: Make use of this: android:windowSoftInputMode="adjustNothing" To avoid your Views to be adjusted as per the keyboard moment. Add this line within your Activity Tag in the Manifest file.
{ "pile_set_name": "StackExchange" }
Q: docker push to the registry with changed Dockerfile and same tag Imagine, I have docker image based on Dockerfile, I will tag & push it into docker registry Over time, I change Dockerfile (add/change new instructions, ...) Now, I will tag new image again with the same tag I used in the first place and push it into docker registry How does docker registry react to new layers? How does docker registry react to changed layers? Will it overwrite existing image with the latest version? Should I use different tag to make sure I have correct new image in place? A: How does docker registry react to new layers? How does docker registry react to changed layers? It will function the same as a pull -- unchanged layers will not be pushed again and new layers will be pushed. Will it overwrite existing image with the latest version? Yep. Should I use different tag to make sure I have correct new image in place? Usually. Using latest to represent the most recent is fine but you should add a second tag for the actual version so that dependent systems can pin to that version and upgrade as needed.
{ "pile_set_name": "StackExchange" }
Q: Running time analysis of Z3 I'm using the Z3 SMT solver implemented through python. I have the source code, and I would like to have some, any, indication that the process is running. Is it possible to use some verbose command or anything to get an idea of what the process is currently doing? I know the algorithm behind it, but I want to visualize, even with printf, what is occurring in the code. Thanks! A: You can use: set_option(verbose=10) to obtain verbose output to standard err. After a solver has finished, you can get statistics using the statistics() method. In debug mode you can use enable_trace("arith") to get low level traces (here given with "arith" as an example tag). This is intended for debugging only.
{ "pile_set_name": "StackExchange" }
Q: Java JNI 'C' code with external libraries I have followed this guide Beginning JNI with NetBeans IDE and C/C++ Plugin on Linux to run 'C' code from my Java application and everything worked. My issue is when I'm trying to use external libraries (like amqp.h) I'm getting an error: symbol lookup error: /home/amir/NetBeansProjects/c_pcap_parser/lib/c_pcap_parser.so: undefined symbol: amqp_new_connection Java Result: 127 How ca I include the libraries in my final .so file? A: first of all, you should get an basic understanding regarding native libraries on your platform. There are static and dynamic libraries. Static means that all native code is added into a library file for the purpose of reuse. So if you already compiled some C code you will know about the *.o files, which contain the binary code which is understanded by your processor. A static library is just a collection of them. They usually have the file extention .a on linux platforms. When linking to a static library, all native binrary code will be added to your application (let's say to your executable). In contrast, a dynamic library will not be added physically into your executable, it will be referenced if required from a global system directory (this is similar to the PATH environment). They are called shared objects on linux (extention .so). There is also an environment variable for that on most platforms, i think it's called LD_LIBRARY_PATH (see this stack overflow for destinction). All directories of the environment variable will be searched for shared objects which can be linked at startup time to your application. Ok with that in mind, You can try to solve the problem. I suppose that amqp.h belongs to the C rabbitmq client. If you want to use that c code in java, you need first to compile it on your platform. This is done by following the description on the github project page which I referenced above. Ok, after a successful build process you will get some library file out of the compilation, I think they will create a dynamic library but I am not sure of that. The result of this outcome determines your action for your java code. If it is a dynamic library, It would be enough to add the shared object to the java native library path. This is also shown in the tutorial that you referenced. I just added a entry for the potential shared object of the rabbitmq c library: static { System.load("full-path-to-NetBeansProjects-dir/JNIDemoCdl/dist/libJNIDemoCdl.so"); System.load("full-path-to-dir-where-the-rabbitmq-so-lives-in/librabbitmq.so"); } If it would be a static library, you would actually need to go different about that. You would need to link the librabbitmq.a library during your C compilation to get things wired up correctly. In the tutorial referenced in your question I saw that Netbeans have a linker section for the C compiler in which you may be capable to add the static lib of rabbitmq during C compilation. One disclaimer: if you just want to access rabbitmq with java code there of course also exits a java library which should be much easier to use with rabbitmq (you would not need the whole JNI and C compilation things). Also one note to the given tutorial in your question: They compile the C code with the -m32 flag which produces a 32 bit shared object. If you follow my instructions above this could be a issue! The reason would be that you need to compile the rabbitmq C client also with this flag, to 32 bit. The default gcc compiler on most platforms will produce 64 bit libraries, which are not compatible with a 32 bit JVM and your 32 bit shared library. So ensure all is 32 bit or 64 bit, but not mixed in anyway! For example living on a 64 bit machine, with a 64 bit JVM, you must delete the -m32 flag.
{ "pile_set_name": "StackExchange" }
Q: Finding an element of a list when the list is in a dictionary? This is homework, so I don't expect the answer, just a point in the right direction. In python I have a dictionary that is like so: {'bike101': ('Road Bike', [('WH139', 2), ('TR102', 2), ('TU177', 2), ('FR101', 1), ('FB101', 1), ('BB101', 1), ('GS101', 1)]), 'bike201': ('Mountain Bike', [('WH239', 2), ('TR202', 2), ('TU277', 2), ('FR201', 1), ('FB201', 1), ('BB201', 1), ('GS201', 1)]), 'bike301': ('Racing Bike', [('WH339', 2), ('TR302', 2), ('TU377', 2), ('FR301', 1), ('FB301', 1), ('BB301', 1), ('GS301', 1)])} For example 'Racing Bike' is the product name and the list of pairs is (part, amount required), respectively. I have to write a function that, given the above dictionary and the product name as an argument will then return the key for it and return 'None' if the product name does not exist. I used: return [key for key, value in product_dict.iteritems() if list(value)[0] == string] And this returned the correct key when tested but I don't know how to make it return 'none' if the product name doesn't exist and I am not sure if this is the best way to do this.' I can only use the builtin functions in python, any help is greatly appreciated! A: Since you're asking for hints, I won't post working code. Your code is a list comprehension, so it outputs a list. If there is no result, the list will be empty. You can bind the list to a variable, use len() to check its length and return None if it is 0.
{ "pile_set_name": "StackExchange" }
Q: C++ error typedef cannot be overloaded I have this c++ programm and for some reason it wont compile . I am using XP with VS 2005 . #include "stdafx.h" #include "MainThread.h" HANDLE hStopEvent = NULL; int main(int argc, char *argv[]) { return 0; } error C2146: syntax error : missing ';' before identifier 'hStopEvent' error C2377: 'HANDLE' : redefinition; typedef cannot be overloaded with any other symbol see declaration of 'HANDLE' error C4430: missing type specifier - int assumed. Note: C++ does not support default-int A: That error is most likely because you've got a problem in the header file, which has resulted in the compiler treating the first thing it finds in the source file as an identifier. Something like having an unfinished struct or class definition: struct blah { int a; } // MISSING ';' If you can't see it, I suggest posting the header file.
{ "pile_set_name": "StackExchange" }
Q: PHP: Set php variable on javascript onclick How do I set a php variable when a radio button is clicked? Or is there any other way without using ajax. What I would like to do is set $_SESSION['a'] = $a; Where $a is an array of answers which was initially set to 0. I have a radio button of questions with 4 options. When a user clicks on a radio button, I would like my session to record that radio button. I was thinking of OnClick function on the radio button. How do I do this. or how do I store that chosen radio button in the session. A: by only JavaScript its not possible you need to use ajax to do this or by submitting form
{ "pile_set_name": "StackExchange" }
Q: Low Search Related Child in List I am working on a client site and they have a search form which we are using Low Search for. Two current search fields for keywords and topics (a Playa field) work fine. I am working on the third field where we need to filter by the position (text input) field of a related employee (Playa field). Here is the code I currently have: <select id="position" name="child:news_related_employees[]"> <option value="">All</option> {exp:query sql="SELECT GROUP_CONCAT(entry_id) AS entry_ids, field_id_34 AS p_position FROM exp_channel_data WHERE field_id_34 != '' GROUP BY field_id_34 ORDER BY field_id_34 ASC"} <option value="{entry_ids}">{p_position}</option> {/exp:query} </select> The query works fine, I get a comma separated list of entry_ids per unique position, however the form does not return any results. I assume that's because it is trying to match the entire string of entry_ids to an employee in the Playa field. Can anyone shed some light on this or know of a way to do what we need? Thanks. A: Low Search expects a pipe | as a value separator. You can define that in the GROUP_CONCAT clause of your query. So try this: GROUP_CONCAT(entry_id SEPARATOR '|') AS entry_ids
{ "pile_set_name": "StackExchange" }
Q: Re-cert after upgrading Apache + OpenSSL This is probably a captain noobenstein question but I cannot figure out how to google this issue for an answer. I've just upgraded from Apache 2.4.10 w/ OpenSSL 1.0.1j to Apache 2.4.18 w/ OpenSSL 1.0.2e Do I need to regenerate my SSL files and get re-validated with my certificate authority? If not, then why? FWIW My previous .key and .csr files were created like this: openssl.exe genrsa -out {The_FQDN}.key 2048 openssl.exe req -new -sha256 -key {The_FQDN}.key -out {The_FQDN}.csr A: The certificate validation process contains four basic steps. Generate a request Generate a key (the .key file in your apache config) Submit the request to a CA for validation Receive a certificate (the .cer or .crt in your apache config) Since these steps are time sensitive - the request which was submitted is still the request which was validated - there is no reason to go through the validation process again. In other words your certificate / key binding is already made and there is no reason to revise it. This does assume that you still have the same certificate and key as previously used.
{ "pile_set_name": "StackExchange" }
Q: Java Jackcess Library Documentation? I need to read and write some data on .mdb Access file and over the web I found the Jackcess library that that does exactly that. Unfortunately I could't find any documentation to use that. On the library website there are a couple of examples, but no real documentation. Can anyone tell me if there's some sort of documentation somewhere? A: The javadoc is intended to be fairly explanatory. The primary classes would be Database and Table. The library is also heavily unit tested, so you can dig into the unit test code to see many examples. There isn't currently a great "getting started" document. It has been discussed before, but, unfortunately no one has picked up the ball on actually writing it. That said, the help forum is actively monitored. UPDATE: There is now a cookbook, which is the beginnings of a more comprehensive user-level documentation.
{ "pile_set_name": "StackExchange" }
Q: Gruff Bar Graph Data in array, I need a Bar Graph in Gruff with two Bars. For two subjects, I loop through to get the values for activity and grade : sub = ["English", "Maths"] activity = [] grade = [] sub.each do |sub| activity.push(sub["activity"].to_i) grade.push(sub["grade"].to_i) end Now, I am using these values for my Bar Graph. g = Gruff::Bar.new('500x250') g.maximum_value = 100 g.minimum_value = 0 g.y_axis_increment = 15 g.data( "Activity", activity.inspect) g.data( "Summative", grade.inspect) g.labels = {0 => 'English', 1 => 'Language II'} g.write('images/overall_score.png') But, this throws an error " comparison of String with 0 failed". I need the data to be printed as g.data( "Activity", [10,20]) puts activity.inspect prints the array as above ex: [10,20] Looks like the values are treated as strings. What should I do to resolve this. Any help is greatly appreciated. Cheers! A: Actually inspect method returns String. I think you should just pass your arrays to data method like this: g.data("Activity", activity) g.data("Summative", grade)
{ "pile_set_name": "StackExchange" }
Q: WCF Validation - Requiring and validating custom values We are currently developing some new systems to replace parts of several legacy systems. We have some new WCF web services which will sit alongside existing ASMX web services. The ASMX web services authenticate via a Soap Header Context object with 4 custom properties including a token (previously generated and returned at login) which are then validated. We are not re-writing the validation code yet and the login is still being handled by the existing ASMX services, so we are required to call the existing validator passing in a Context object with the 4 properties from the WCF service application. How do we capture the 4 properties via the WCF service? A previous WCF project implemented WCFExtras+ to replicate the Soap Header over WCF. We can do that again but would prefer a native WCF approach. I have found options such as custom UserNamePasswordValidator or ServiceAuthorizationManager but have been unable to determine how to exactly apply these to our specific requirements. Is this possible? How? A: After much googling I wrote my own custom behaviour using IOperationBehavior, IContractBehavior and IDispatchMessageInspector
{ "pile_set_name": "StackExchange" }
Q: What can i control when i restoring a databese? For example can i OverWrite the existing databse? Im building a program who can restore a database from a .bak file. I want to know if i can get the path for mdf and log file for a specific database from a tsql script? A: Use the WITH MOVE option of the RESTORE command. See the Example D in the docs. To find the correct syntax you can also use SSMS and use the "Script" button in the "Restore Database" dialog.
{ "pile_set_name": "StackExchange" }
Q: I have a blank page after submitting mailchimp subscribe php I use bellow html code to submit user email in my mailchimp account list using mailchimp API. Form Code: ..... <form id="signup-form" action="php/newsletter-subscribe.php" method="post"> <input type="email" name="email" id="email" placeholder="Email Address" /> <br> <input type="submit" value="Go!" onclick="wating()" /> </form> ...... newsletter-subscribe PHP code: require_once 'mailchimp/MailChimp.php'; use \DrewM\MailChimp\MailChimp; // Email address verification function isEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } if($_POST) { $mailchimp_api_key = 'xxxxxxxxxxxxxxxxxxxxx-xx'; // enter your MailChimp API Key $mailchimp_list_id = 'xxxxxxxxxx'; // enter your MailChimp List ID $subscriber_email = addslashes( trim( $_POST['email'] ) ); if( !isEmail($subscriber_email) ) { echo '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>'; } else { $array = array(); $MailChimp = new MailChimp($mailchimp_api_key); $result = $MailChimp->post("lists/$mailchimp_list_id/members", [ 'email_address' => $subscriber_email, 'status' => 'subscribed', ]); if($result == false) { $array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>'; } else { $array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>'; } echo json_encode($array); } } The problem is after i submit the form i get blank page without any error log and the email added to my mailchimp account without any error. I try to change the echo javascript in line 22, 35 and 38 with another java script alert like alert("Text Here"); and it's work except i get the same thing blank page How to solve this problem and echo the javascript alert in the same html form page without redirect to blank page? A: First you are setting: $array = array(); However later, you do: if($result == false) { $array = '<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>'; } else { $array = '<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>'; } echo json_encode($array); In other words, you are changing array to a string. Try to change the code to: if($result == false) { $array = array('<script type="text/javascript">swal("Error!", "Please try again.", "error")</script>'); } else { $array = array('<script type="text/javascript">swal("Great!", "Your email has been subscribed", "success")</script>'); } echo json_encode($array); Also, I would avoid using <script type="text/javascript"> there and I would just return a proper json response. Then, you call this file with ajax (jquery), decode the json and show the alert. Perhaps something like this will give you an idea: http://labs.jonsuh.com/jquery-ajax-php-json/
{ "pile_set_name": "StackExchange" }
Q: Guid in Excel Using SpreadSheetGear I just need a confirmation/quick info. I feel it's an obvious question but just want to make sure and fully understand what's happening. Couldn't find much detail on the web. I'm using SpreadSheetGear to dump data in spreadsheets from a datatable. There are some Guid in those tables. Now when I try to copy from my data table, I get an error saying wrong data type, unless I'm importing using the flags AllText or by removing the columns containing Guids in my datable. Seems like excel cannot support Guids as variable/data type. Is this normal? I don't necessarly need the data anyway can convert easily in text format, but I just want to fully understand this issue. Here's a sample code with the following error: Invalid cell value type. public void Test() { DataTable table = new DataTable(); table.Columns.Add("ID", typeof(Guid)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); table.Rows.Add(Guid.NewGuid(), "Indocin", "David", DateTime.Now); table.Rows.Add(Guid.NewGuid(), "Enebrel", "Sam", DateTime.Now); table.Rows.Add(Guid.NewGuid(), "Hydralazine", "Christoff", DateTime.Now); IWorkbook wrk = Factory.GetWorkbook(); IWorksheet wsht = wrk.Worksheets["Sheet1"]; IRange rng = wsht.Cells["A1"]; rng.CopyFromDataTable(table, SpreadsheetGear.Data.SetDataFlags.None); wrk.SaveAs("C:\\MyData.xls",FileFormat.OpenXMLWorkbook); wrk.Close(); } A: Using IRange.CopyFromDataTable(...) without the SetDataFlags.AllText flag is basically like using a loop to set IRange.Value for each "cell" of data in your DataTable, which means the data types used in this incoming DataTable data are subject to the setter requirements of IRange.Value, which states: ...sets the value of the specified cell as a System.String, System.Double, System.Int32, System.Int64, System.Int16, System.Char, System.Boolean, System.DateTime, SpreadsheetGear.ValueError, System.Decimal, System.DBNull, object[,] or null Since Guid is not a valid type to use with IRange.Value, using this data type in a DataTable won't work either. When you specify the SetDataFlags.AllText flag, SpreadsheetGear first calls ToString() on each "cell" of data in your DataTable, so all incoming data types will be accepted, regardless of whether it is in the above list or not.
{ "pile_set_name": "StackExchange" }
Q: How to convert handlebars to ejs This is probably an easy question but I can't figure it out. I want to change this handlebar code into ejs {{#if hasErrors}} <div class="alert alert-danger"> {{#each messages}} <p>{{ this }}</p> {{/each}} </div> {{/if}} I tried but i'm getting syntax error <%= if (Errors) {%> <div class="alert alert-danger"> <%= each messages %> <p><%= this%></p> </div> <% }%> A: If your "hasError" variable is of type boolean, and your messages variable is an array of message strings; <% if (hasErrors) {%> <div class="alert alert-danger"> <% messages.forEach(function(message){ %> <p><%= message %></p> <% });%> </div> <% }%>
{ "pile_set_name": "StackExchange" }
Q: Pixel Bender vs Stage3D, Stage Video and Starling Does Pixel Bender (2D) combine with Stage3D? Namely: Does Pixel Bender work on top of Stage Video (GPU accelerated video)? Does Pixel Bender work on top of Starling viewport? Thanks A: I fear that the answer is no. There is no high level shading language for Stage3D. If you want to write shaders for Stage3D, you'll have to use the incredibly ugly AGAL. I'm not even kidding, assembler code for graphical programming. Wtf, indeed. By not offering a high-level language, Adobe is practically killing any ambitious 3D projects that want to be made within a reasonable amount of time. And trust me, writing AGAL code is anything but reasonable and fast. There are some Flash 3D engines like Away3D and Alternativa, which are fine, but even those come with their own premade shaders and if you want something of your own, good luck. That said, there were some efforts to make some kind of Pixel Bender 3D, as you can see here. But the development has been halted since 09.2011, and the last version is something you have to compile yourself, which has no UI, etc. So, again, virtually useless. No idea what Adobe is/was thinking ;) I'm unsure about Starling, but I would doubt that you could use PB2 shaders with Starling, as that would mean Starling has an own parser for (old) PB2 code. But no guarantees here.
{ "pile_set_name": "StackExchange" }
Q: React-native: Absolute positioned components not rendering completely unless a state is changed I have a screen that has several components, some with relative positioning and some with absolute. When the screen is opened, the absolute positioned components don't go all the way to their final correct position, or size. They appear on the screen, but in the wrong spot and size. Only by changing a state with a button press, do the components finish rendering. Here's a simplified version of the screen below: The screenshot on the left has the absolutely positioned menu icon (3 horizontal lines at the top right), not all the way in its correct position yet. The screen on the right shows the icon in its final correct position, only after I changed a state by pressing a touchable region. Here is the code: import React, {Component} from 'react'; import {View, Text, StyleSheet, Animated, Image, Dimensions, TouchableWithoutFeedback} from 'react-native'; import colors from '../config/colors'; import Icon from 'react-native-vector-icons/Ionicons'; import Orientation from 'react-native-orientation-locker'; const w = (Dimensions.get('window').width); const h = (Dimensions.get('window').height); const r = h / w; if (r > 1.9) { mission_font_heading = 14; mission_font = 12; check_dimension = 14; name_font = 10; } else { mission_font_heading = 12; mission_font = 10; check_dimension = 12; name_font = 8; } class how_to_play9_screen extends Component { constructor (props) { super(props); this.state = { test: 0, //changing this state "fixes" the component's position } } componentDidMount() { Orientation.lockToPortrait(); } openMenu() {} showMission() { this.setState({test: 2}); //this changes the state } render() { return ( <View> <Image style={styles.backgroundImage} source={require('../images/Background.png')} > </Image> <View style={{alignItems: 'center'}}> <TouchableWithoutFeedback onPress={() => this.showMission()}> <View style={styles.missionContainer}> <Text style={styles.missionTitleText}> MISSION TITLE </Text> <Text style={styles.text}> (X VP) </Text> <View style={{flexDirection: 'row'}}> <Image style={styles.checkBox} source={require('../images/Checkbox.jpg')} /> <Text style={styles.missionReqText}> Mission Requirement 1 </Text> </View> </View> </TouchableWithoutFeedback> </View> // below is the absolute positioned component <View style={{ position: 'absolute', top: 5, right: 5, }} > <TouchableWithoutFeedback onPress={() => this.openMenu()} > <Icon name='ios-menu' size={(Dimensions.get('window').width) * .08} color={colors.JBDarkTeal} /> </TouchableWithoutFeedback> </View> </View> ); } } const styles = StyleSheet.create({ backgroundImage: { width: (Dimensions.get('window').height) * .65, height: (Dimensions.get('window').height) * 1.3, position: 'absolute', left: 0, top: 0, }, missionContainer: { backgroundColor: colors.JBTealTrans, borderWidth: 2, borderColor: colors.JBTan, marginVertical: 10, paddingVertical: 3, paddingRight: 5, width: '80%', }, missionTitleText: { fontSize: mission_font_heading, textAlign: 'center', color: colors.JBTan, marginVertical: 3, marginHorizontal: 5, }, text: { fontSize: mission_font, textAlign: 'center', color: colors.JBTan, marginVertical: 3, }, missionReqText: { fontSize: 12, color: colors.JBTan, marginVertical: 3, marginLeft: 5, marginRight: 5, }, checkBox: { width: check_dimension, height: check_dimension, marginVertical: 3, marginLeft: 5, }, }) export default how_to_play9_screen; I want the icon and any other absolute positioned components to go straight to their final position upon screen opening. Edit: I should also mention that the previous screen locks the orientation to landscape, and this screen locks it back to portrait. I found that if I load this screen from a different screen that is already in portrait, then this one renders correctly, so it seems that it doesn't like me changing the orientation. A: The position is not the problem, the problem is size of <Icon /> try to using number instad Dimensions calc, or make this calc on componentDidMount or render
{ "pile_set_name": "StackExchange" }
Q: Block label margin-bottom I'm trying to add a margin to a radio label. I've changed the display style to block and added a bottom margin but it does not seem to affect the spacing at all, and overlaps with subsequent elements. https://jsfiddle.net/wospyqah/ e.g.: .slider-label { position: absolute; display: block; cursor: pointer; color: #5e5e5e; text-align: center; margin-bottom: 50px; } A: The issue is that the .radios-to-slider class is set to use position:relative, which takes it out of the normal flow of the document. Instead of adding a bottom margin to that class, just add a top margin to the divinput class. div.divinput { margin-top:50px; margin-bottom: 15px; display: block; } See this fiddle: https://jsfiddle.net/uuzw5cwe/1/
{ "pile_set_name": "StackExchange" }
Q: IE javascript redirection I have a javascript function which redirects user to a diff page. It goes like this... redirect : function(url) { if(!url) return false; alert(url); if (this.browserClass.isW3C) //IE 6.X comes here { window.location.href = url; } else if(this.browserClass.isIE4) { window.location.href = url; } else if (this.browserClass.isNN4) { window.location = url; } else { window.location = url; } return false; }, But the problem is that this does not work in IE (internet explorer 6.X). After a short battle I saw that IE was redirecting when I change the code to this - if (this.browserClass.isW3C) setTimeout("location.href = '" +url+"'", 0); Problem is solved. But what's going on here? Could someone educate me? or is it just one of those mind numbing idiosyncrasies of IE... A: This function is a complete waste of time. Assignment to location.href works equally well in all currently extant browsers. this.browserClass.isNN4 is a hint that this code is worrying about stuff that doesn't exist in this century. As if being stinky old browser-sniffing wasn't bad enough. (Anyway even in Netscape, both these assignments worked.) setTimeout("location.href = '" +url+"'", 0); Try not to pass strings to setTimeout, it's the same thing as eval with all the same problems (eg. your URL contains an apostrophe... boom). Pass a function, an inline one if necessary (setTimeout(function() { location.href= url; }, 0);). However what this smells like to me is you're trapping a click or mousedown event on a link, and not cancelling the event (by returning false from the event handler). Consequently the link following default action can occur and may, depending on browser, override the location.href navigation.
{ "pile_set_name": "StackExchange" }
Q: Names of instances and loading objects from a database I got for example the following structure of a class. class Company(object): Companycount = 0 _registry = {} def __init__(self, name): Company.Companycount +=1 self._registry[Company.Companycount] = [self] self.name = name k = Company("a firm") b = Company("another firm") Whenever I need the objects I can access them by using Company._registry which gives out a dictionary of all instances. Do I need reasonable names for my objects since the name of the company is a class attribute, and I can iterate over Company._registry? When loading the data from the database does it matter what the name of the instance (here k and b) is? Or can I just use arbitrary strings? A: Both your Company._registry and the names k and b are just references to your actual instances. Neither play any role in what you'd store in the database. Python's object model has all objects living on a big heap, and your code interacts with the objects via such references. You can make as many references as you like, and objects automatically are deleted when there are no references left. See the excellent Facts and myths about Python names and values article by Ned Batchelder. You need to decide, for yourself, if the Company._registry structure needs to have names or not. Iteration over a list is slow if you already have a name for a company you wanted to access, but a dictionary gives you instant access. If you are going to use an ORM, then you don't really need that structure anyway. Leave it to the ORM to help you find your objects, or give you a sequence of all objects to iterate over. I recommend using SQLAlchemy for this.
{ "pile_set_name": "StackExchange" }
Q: How to join non-relational models in Django 1.3 on 2 fields I've got 2 existing models that I need to join that are non-relational (no foreign keys). These were written by other developers are cannot be modified by me. Here's a quick description of them: Model Process Field filename Field path Field somethingelse Field bar Model Service Field filename Field path Field servicename Field foo I need to join all instances of these two models on the filename and path columns. I've got existing filters I have to apply to each of them before this join occurs. Example: A = Process.objects.filter(somethingelse=231) B = Service.objects.filter(foo='abc') result = A.filter(filename=B.filename,path=B.path) A: This sucks, but your best bet is to iterate all models of one type, and issue queries to get your joined models for the other type. The other alternative is to run a raw SQL query to perform these joins, and retrieve the IDs for each model object, and then retrieve each joined pair based on that. More efficient at run time, but it will need to be manually maintained if your schema evolves.
{ "pile_set_name": "StackExchange" }
Q: How do I print a strucure in c++? We can print elements of a structure using structure.element. But I want to print a complete structure at once. Is there a method something like cout<<strucutre, the same way we can print a list or tuple in Python. This is what I want: struct node { int next; string data; }; main() { node n; cout<<n; } A: You need to overload the << operator properly: #include <string> #include <iostream> struct node { int next; std::string data; friend std::ostream& operator<< (std::ostream& stream, const node& myNode) { stream << "next: " << myNode.next << ", Data: " << myNode.data << std::endl; return stream; } }; int main(int argc, char** argv) { node n{1, "Hi"}; std::cout << n << std::endl; return 0; }
{ "pile_set_name": "StackExchange" }
Q: creating list gives error when not enough data creating list gives error when not enough data What I did: <?php $a=$b=$c=array(); list($a,$b,$c) = array_chunk(array("A","B","C","D","E"), 3); echo "<pre>"; print_r(array($a,$b,$c)); ?> getting error like: Notice: Undefined offset: 2 in /var/www/html/test.php on line 13 how to fix it? in above case if there is no value then keep last array blank. How to devide data in 3 array ? and if there is no enough data then keep last array blank. A: list($a,$b,$c) = array_pad(array_chunk(array("A","B","C","D","E"), 3), 3, array()); If you are less elements in your array, array_pad will fill it with default value.
{ "pile_set_name": "StackExchange" }
Q: Unsetting a value from local storage on click I'm using local storage to save the id as seen below, it works as it's suppose to. When I click on the anchor it sends the value into an array. The problem is when I click it again, it saves that same value again into the same array. I would like to take that value out of the array on the second click. So basically I want it to act as a toggle. $(".favorites").click(function() { var favorite = JSON.parse(localStorage.getItem( 'favorite' )); if (favorite == undefined) { favorite = Array(); } favorite.push($(this).attr('data-petid')); localStorage.setItem( 'favorite', JSON.stringify(favorite) ); JSON.parse( localStorage.getItem( 'favorite' ) ); }); A: OK, your description is not clear at first, you mean take the value out of an array, right? $(".favorites").click(function() { var favorite = localStorage.getItem( 'favorite' ); var petid = $(this).attr('data-petid'); var index; favorite = JSON.parse(favorite) || []; if ((index = favorite.indexOf(petid)) === -1) { favorite.push(petid); } else { favorite.splice(index, 1); } localStorage.setItem('favorite', JSON.stringify(favorite) ); }
{ "pile_set_name": "StackExchange" }
Q: Custom listview with multiple values in a row im trying to implement a custom listadapter that is set to display only distinct values for each row via the sql query. In each row i want to implement a list of textview values that displays data from another sql query. How can i implement an adapter like this ? A: If you could be a little clear on your question. From what I understand, you want a listview of textviews inside a listview of textviews? More of a nested ListView. If that's the case then you can go for an ExpandableListView like this one: http://developer.android.com/reference/android/widget/ExpandableListView.html
{ "pile_set_name": "StackExchange" }
Q: Explanation of pysftp.Connection.walktree() parameters I have just started using Python's pysftp and I am confused as how to call it's walktree function. I found some code (found at http://pydoc.net/Python/pysftp/0.2.8/pysftp/) that helped me better understand what form my parameters should take def walktree(self, remotepath, fcallback, dcallback, ucallback, recurse=True): '''recursively descend, depth first, the directory tree rooted at remotepath, calling discreet callback functions for each regular file, directory and unknown file type. :param str remotepath: root of remote directory to descend, use '.' to start at :attr:`.pwd` :param callable fcallback: callback function to invoke for a regular file. (form: ``func(str)``) :param callable dcallback: callback function to invoke for a directory. (form: ``func(str)``) :param callable ucallback: callback function to invoke for an unknown file type. (form: ``func(str)``) :param bool recurse: *Default: True* - should it recurse :returns: None But I am still confused on what exactly is meant by "callback function to invoke for a regular file, for a directory, and for an unknown file type. I have also looked through the official documentation: https://media.readthedocs.org/pdf/pysftp/latest/pysftp.pdf but all it tells me about the walktree() function is that: Is a powerful method that can recursively (default) walk a remote directory structure and calls a user-supplied callback functions for each file, directory or unknown entity it encounters. It is used in the get_x methods of pysftp and can be used with great effect to do your own bidding. Each callback is supplied the pathname of the entity. (form: func(str)) which I felt did not give me much information on how to call it properly. If someone could provide an example of calling this function correctly and an explanation of why you are passing your chosen arguments, it would be greatly appreciated! A: Here is the sample code you are looking for. import pysftp file_names = [] dir_names = [] un_name = [] def store_files_name(fname): file_names.append(fname) def store_dir_name(dirname): dir_names.append(dirname) def store_other_file_types(name): un_name.append(name) cnopts = pysftp.CnOpts() cnopts.hostkeys = None sftp = pysftp.Connection(host="Your_ftp_server_name", username="ftp_username", private_key="location_of_privatekey", cnopts=cnopts) sftp.walktree("/location_name/",store_files_name,store_dir_name,store_other_file_types,recurse=True) print file_names,dir_names,un_name file names, directory names and unknown file types are stored in lists file_names, dir_names and un_name respectively.
{ "pile_set_name": "StackExchange" }
Q: Asp.NET server control events not firing Thanks for all who reads. I have a code issue that has been discussed many times on stackoverflow, but I can't make the provided solutions work. It's about server control that contain other controls and I can't fire their events. My issue is simple, i need to add any numbers ok LinButton into my server control. this is my code: protected override void CreateChildControls() { for (int i = 0; i < IndiceValue; i++) { LinkButton imageTemp = new LinkButton() { CommandName = String.Format("{1}_{0}", CommandNames, i), Text = i.ToString(), ID = Guid.NewGuid().ToString()}; imageTemp.Click += ImageTempOnClick; this.Controls.Add(imageTemp); } base.CreateChildControls(); } I have a custom event in my control: public delegate void IndiceFiabiliteCommand(object sender, IndiceFiabiliteCommandEventArg e); public event IndiceFiabiliteCommand Command; And theorically, when any of the LinkButton is clicked, I want the user to be warn that any of the LinkButton has been clicked. I give him all the needed infos but i don't think this part is the problem. Last thing to know is that I implement INamingContainer and I tried to implement both, IPostBackDataHandler and IPostBackEventHandler but it didn't worked. I hope it's understandable enough thanks! A: The problem is ID = Guid.NewGuid().ToString() You cannot have dynamically created control with dynamic id. Change the code to ... i.ToString(), ID = i.ToString() Basically, dynamic control's ID must be same as the ID originally created. Otherwise, new control is created on every post-back, and it cannot find the control which causes the post-back. FYI: if you need to catch an event, I would like to suggest to use CompositeControl which already have INamingContainer. Note: it is just what I found based on your code; it might be other issue too.
{ "pile_set_name": "StackExchange" }
Q: Is "field" a must in Redis Stream Xadd command? According Redis' document here, XADD has format like below: XADD key ID field value [field value ...] In my use case, the format and number of the field is fixed. I wonder if I should just exclude "field" in the command? Take an example: Current command: XADD stream * timestamp [ts_value] msg [msg_value] uid [uid_value] status [status_value] New command XADD stream * [ts_value] [msg_value] [uid_value] [status_value] What will be the problem or will it be a bad practice if I use the "new command" considering that "fields" are fixed in my use case? A: This could work, but would not be intuitive for anyone trying to understand the data without prior knowledge - the use of field-value makes parsing the data easier. This will not only make another developer's experience harder, but would also probably mess with any kind of 3rd party application (e.g. a Redis GUI). Also, your method will require to always have an even fixed number of fields. Additionally, any future changes to the data model (yeah, nothing is really "fixed") will make maintaining this into a nightmare. You'll either have to version rows or migrate the data or who knows what. So the real question is why would anyone want to not use field names. If you read the docs you'll find that Redis compresses the names if they repeat themselves, so there's little wastage in terms of space. The only reason I can think of is perhaps optimizing the amount of traffic, but I wouldn't go there unless it was a real issue. Regardless, if you're hell-bent on not using field names, you can use just one and serialize all your "fixed" values into it. This will be more Redis-like, although you'd still be in trouble once the schema changes: XADD stream * data "[ts_value],[msg_value],[uid_value],[status_value]"
{ "pile_set_name": "StackExchange" }
Q: Treat function that returns array What's the best way to treat a situation like this: I personally always have used this way, creating a variable with type array and assigning the function to it. But when I started to using NetBeans 8, it shows me a warning, saying that must be only 1 attribution to a variable. I think this way is more verbose and makes the code more readable. Should I just create this way? $test = returnArray(); A: check out this article, they discuss this in the portion titled immutable variables. It seems like the second way is the recommended method.
{ "pile_set_name": "StackExchange" }
Q: What is involved with writing a lobby server? So I'm writing a Chess matchmaking system based on a Lobby view with gaming rooms, general chat etc. So far I have a working prototype but I have big doubts regarding some things I did with the server. Writing a gaming lobby server is a new programming experience to me and so I don't have a clear nor precise programming model for it. I also couldn't find a paper that describes how it should work. I ordered "Java Network Programming 3rd edition" from Amazon and still waiting for shipment, hopefully I'll find some useful examples/information in this book. Meanwhile, I'd like to gather your opinions and see how you would handle some things so I can learn how to write a server correctly. Here are a few questions off the top of my head: (may be more will come) First, let's define what a server does. It's primary functionality is to hold TCP connections with clients, listen to the events they generate and dispatch them to the other players. But is there more to it than that? Should I use one thread per client? If so, 300 clients = 300 threads. Isn't that too much? What hardware is needed to support that? And how much bandwidth does a lobby consume then approx? What kind of data structure should be used to hold the clients' sockets? How do you protect it from concurrent modification (eg. a player enters or exists the lobby) when iterating through it to dispatch an event without hurting throughput? Is ConcurrentHashMap the correct answer here, or are there some techniques I should know? When a user enters the lobby, what mechanism would you use to transfer the state of the lobby to him? And while this is happening, where do the other events bubble up? A: Model everything as objects. You have the classes chat-room, game-session, player... Don't spawn new threads for new players. Instead try to see every class as a state machine: A player can be connected or disconnected, he has a TcpConnection and a variable specifying how much time he has left to make his move (just as an example). Then when you have all your objects in an array or something like that, you iterate over it every 10milliseconds (the number is an example too ofcourse) and take appropriate actions. For example, terminate a game-session if one of the players left the game, send moves from one player to the other player... For all events that happen in the game you will have to send message trough the network. Create one extra class / enumeration that holds the different message types. If one player makes a move you could send this to the server "move d4 to d5" or something. If you only make a chess game, you can send strings trough the network. For anything more complex I would suggest you send only single bytes. Typically game packets consist of: the length of the packet, the packet message type / event type (move, player-joined, player-left, ...) and the content (if a player joins, the content would be the name for example)
{ "pile_set_name": "StackExchange" }
Q: Concurrent processing using Stanford CoreNLP (3.5.2) I'm facing a concurrency problem in annotating multiple sentences simultaneously. It's unclear to me whether I'm doing something wrong or maybe there is a bug in CoreNLP. My goal is to annotate sentences with the pipeline "tokenize, ssplit, pos, lemma, ner, parse, dcoref" using several threads running in parallel. Each thread allocates its own instance of StanfordCoreNLP and then uses it for the annotation. The problem is that at some point an exception is thrown: java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at java.util.Collections$UnmodifiableCollection$1.next(Collections.java:1042) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:463) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.analyzeNode(GrammaticalStructure.java:488) at edu.stanford.nlp.trees.GrammaticalStructure.<init>(GrammaticalStructure.java:201) at edu.stanford.nlp.trees.EnglishGrammaticalStructure.<init>(EnglishGrammaticalStructure.java:89) at edu.stanford.nlp.semgraph.SemanticGraphFactory.makeFromTree(SemanticGraphFactory.java:139) at edu.stanford.nlp.pipeline.DeterministicCorefAnnotator.annotate(DeterministicCorefAnnotator.java:89) at edu.stanford.nlp.pipeline.AnnotationPipeline.annotate(AnnotationPipeline.java:68) at edu.stanford.nlp.pipeline.StanfordCoreNLP.annotate(StanfordCoreNLP.java:412) I'm attaching a sample code of an application that reproduces the problem in about 20 seconds on my Core i3 370M laptop (Win 7 64bit, Java 1.8.0.45 64bit). This app reads an XML file of the Recognizing Textual Entailment (RTE) corpora and then parses all sentences simultaneously using standard Java concurrency classes. The path to a local RTE XML file needs to be given as a command line argument. In my tests I used the publicly available XML file here: http://www.nist.gov/tac/data/RTE/RTE3-DEV-FINAL.tar.gz package semante.parser.stanford.server; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; public class StanfordMultiThreadingTest { @XmlRootElement(name = "entailment-corpus") @XmlAccessorType (XmlAccessType.FIELD) public static class Corpus { @XmlElement(name = "pair") private List<Pair> pairList = new ArrayList<Pair>(); public void addPair(Pair p) {pairList.add(p);} public List<Pair> getPairList() {return pairList;} } @XmlRootElement(name="pair") public static class Pair { @XmlAttribute(name = "id") String id; @XmlAttribute(name = "entailment") String entailment; @XmlElement(name = "t") String t; @XmlElement(name = "h") String h; private Pair() {} public Pair(int id, boolean entailment, String t, String h) { this(); this.id = Integer.toString(id); this.entailment = entailment ? "YES" : "NO"; this.t = t; this.h = h; } public String getId() {return id;} public String getEntailment() {return entailment;} public String getT() {return t;} public String getH() {return h;} } class NullStream extends OutputStream { @Override public void write(int b) {} }; private Corpus corpus; private Unmarshaller unmarshaller; private ExecutorService executor; public StanfordMultiThreadingTest() throws Exception { javax.xml.bind.JAXBContext jaxbCtx = JAXBContext.newInstance(Pair.class,Corpus.class); unmarshaller = jaxbCtx.createUnmarshaller(); executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); } public void readXML(String fileName) throws Exception { System.out.println("Reading XML - Started"); corpus = (Corpus) unmarshaller.unmarshal(new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8)); System.out.println("Reading XML - Ended"); } public void parseSentences() throws Exception { System.out.println("Parsing - Started"); // turn pairs into a list of sentences List<String> sentences = new ArrayList<String>(); for (Pair pair : corpus.getPairList()) { sentences.add(pair.getT()); sentences.add(pair.getH()); } // prepare the properties final Properties props = new Properties(); props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref"); // first run is long since models are loaded new StanfordCoreNLP(props); // to avoid the CoreNLP initialization prints (e.g. "Adding annotation pos") final PrintStream nullPrintStream = new PrintStream(new NullStream()); PrintStream err = System.err; System.setErr(nullPrintStream); int totalCount = sentences.size(); AtomicInteger counter = new AtomicInteger(0); // use java concurrency to parallelize the parsing for (String sentence : sentences) { executor.execute(new Runnable() { @Override public void run() { try { StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = new Annotation(sentence); pipeline.annotate(annotation); if (counter.incrementAndGet() % 20 == 0) { System.out.println("Done: " + String.format("%.2f", counter.get()*100/(double)totalCount)); }; } catch (Exception e) { System.setErr(err); e.printStackTrace(); System.setErr(nullPrintStream); executor.shutdownNow(); } } }); } executor.shutdown(); System.out.println("Waiting for parsing to end."); executor.awaitTermination(10, TimeUnit.MINUTES); System.out.println("Parsing - Ended"); } public static void main(String[] args) throws Exception { StanfordMultiThreadingTest smtt = new StanfordMultiThreadingTest(); smtt.readXML(args[0]); smtt.parseSentences(); } } In my attempt to find some background information I encountered answers given by Christopher Manning and Gabor Angeli from Stanford which indicate that contemporary versions of Stanford CoreNLP should be thread-safe. However, a recent bug report on CoreNLP version 3.4.1 describes a concurrency problem. As mentioned in the title, I'm using version 3.5.2. It's unclear to me whether the problem I'm facing is due to a bug or due to something wrong in the way I use the package. I'd appreciate it if someone more knowledgeable could shed some light on this. I hope that the sample code would be useful for reproducing the problem. Thanks! [1]: A: Have you tried using the threads option? You can specify a number of threads for a single StanfordCoreNLP pipeline and then it will process sentences in parallel. For example, if you want to process sentences on 8 cores, set the threads option to 8: Properties props = new Properties(); props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref"); props.put("threads", "8") StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Nevertheless I think your solution should also work and we'll check whether there is some concurrency bug, but using this option might solve your problem in the meantime.
{ "pile_set_name": "StackExchange" }
Q: set bluetooth authentication PIN when listening from adapter I'm making an app that needs to connect with a bluetooth device and get data from it... that device is set as master, so I needed to implement a Thread, where I listenUsingRfcommWithServiceRecord and wait for a connection from it: public AcceptThread(Context context, String serverName, UUID myUUID) { this.context = context; BluetoothServerSocket tmp = null; BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); try { // MY_UUID is the app's UUID string, also used by the client code tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(serverName, myUUID); } catch (IOException e) { } mmServerSocket = tmp; } Then on run I run the code socket = mmServerSocket.accept(5000) to wait until it starts pairing with the device: public void run() { BluetoothSocket socket = null; while (true) { try { socket = mmServerSocket.accept(5000); } catch (IOException e) { Log.e(TAG,"IOException: " + e); } // If a connection was accepted if (socket != null) { // Manage the connection ManageConnectedSocket manageConnectedSocket = new ManageConnectedSocket(socket); manageConnectedSocket.run(); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "IOException: " + e); } break; } } } The Device asks for an authentication PIN, and I need to have an automatic procedure... for that I though of implementing a broadcast receiver to know when the device is asked to par with another device: IntentFilter filter = new IntentFilter(ACTION_PAIRING_REQUEST); context.registerReceiver(mPairReceiver, filter); and receive it: private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_PAIRING_REQUEST.equals(action)) { Log.e(TAG,"ACTION_PAIRING_REQUEST"); setBluetoothPairingPin(device); } } }; In my setBluetoothPairingPin method I receive a BluetoothDevice object : public void setBluetoothPairingPin(BluetoothDevice device) { byte[] pinBytes = convertPinToBytes("0000"); try { Log.e(TAG, "Try to set the PIN"); Method m = device.getClass().getMethod("setPin", byte[].class); m.invoke(device, pinBytes); Log.e(TAG, "Success to add the PIN."); try { device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, false); Log.e(TAG, "Success to setPairingConfirmation."); } catch (Exception e) { // TODO Auto-generated catch block Log.e(TAG, e.getMessage()); e.printStackTrace(); } } catch (Exception e) { Log.e(TAG, e.getMessage()); e.printStackTrace(); } } The problem is that I can't know when my socket receives information, and consecutively, can't know what is my BluetoothDevice to set Pairing Pin before it's connected... Can someone help me on how to surpass this? Or is there other way to put the pin authentication when I'm listenning from BluetoothServerSocket? If I'm not explaining correctly, please let me know... Thanks in advance A: With the help from this and this, I was able to make work for me... My confusion was with the method setBluetoothPairingPin that I couldn't understand that the ACTION_PAIRING_REQUEST is actually called when the device is being starting to pairing, and that is when the PIN is asked from the user... so invoking BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);, and changing a bit of the set pairing method I manage to make it work... Here's my final code: public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_PAIRING_REQUEST.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String PIN = "0000"; byte[] pin = new byte[0]; try { pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, PIN); BluetoothDevice.class.getMethod("setPin", byte[].class).invoke(device, pin); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
{ "pile_set_name": "StackExchange" }
Q: Haskell learning exercise gives strange results this is the question: "Write a function that computes the mean of a list, i.e. the sum of all elements in the list divided by its length. (You may need to use the fromIntegral function to convert the length of the list from an integer into a floating point number.)" first i tried this: mean :: [Double] -> Double mean [] = 0 mean (x:xs) = (x + mean xs) / (1 + mean xs) but it give me strange results, for example, when i use it like that: mean [2,4,6] it give me the result: 1.41176 where it should be: 4 why? i tried another thing: mean :: [Double] -> Double mean list = (summ list) / (count list) where count [] = 0 count (x:xs) = 1 + count xs summ [] = 0 summ (x:xs) = x + summ xs but i have an error when i tried to load the file into GHC. the error is: parse error on input 'count' Failed, modules loaded: none again, what am i doing wrong? at last, i tried this one (that succeeded): mean :: [Double] -> Double count [] = 0 count (x:xs) = 1 + count xs summ [] = 0 summ (x:xs) = x + summ xs mean list = summ list / count list it's the same as the above one (with the 'where' keyword), but it succeed only here, and not in the above one. why? thanks a lot. p.s. i'm learning from the book -- Real World Haskell and the exercise is from here -- (roll it down :-)) thanks to you all. it's a strange thing. the second example also work for me too when i copied it from here and tested it. i don't know why it didn't work for me yesterday :-) but i still don't understand why the first one doesn't work. i think it should be like that (2 + mean [4,6]) / (1 + mean [4,6]) (4 + mean [6 ]) / (1 + mean [ 6]) (6 + mean [ ]) / (1 + mean [ ]) so now it is like that (6 + 0 ) / (1 + 0 ) -- last recursion (4 + (6 + 0) ) / (1 + (1 + 0) ) (2 + (4 + (6 + 0))) / (1 + (1 + (1 + 0)) so now it should be: 12 / 3 isn't it? what i don't understand? thank you :-). A: You get the wrong answers for your first attempt, because you use an incorrect formula. Garbage in, garbage out. (Other people have covered this.) You are probably getting a parse error because some lines are using spaces and others are using tabs. Or you are using all tabs, but with a non-standard tab width. No indentation is used or required here, so the spaces -v- tabs issue doesn't arise.
{ "pile_set_name": "StackExchange" }
Q: What's the proper and easiest way of handling content URLs in ASP.NET MVC? First we have the form: <link href="../../../content/somecontent" /> This is annoying to figure out (need to count path depth one by one) and the most prone to mistakes. Someone came up with this: <link runat="server" href="~/content/somecontent" /> This is easier but I don't know how casual I can be using that solution. Can it be used anywhere? Does it work with Spark? How does it affect rendering speed? And the last and worst resort would be: <link href="/content/somecontent" /> This doesn't allow the web app to reside in a sub directory which I don't like, especially for testing purposes. Are there other, better ways that I'm not aware of? A: You can use <link href="<%= Url.Content("~/Content/somecontent") %>" /> to point to some file. Using relative locations (your first example) won't work all the time because of the way routing can change depending on the current URL. In most of my projects, I use URL helpers to do this kind of thing. public static class ExtensionsOfUrlHelper { // TODO: Prepare for .NET 4.0, this will return MvcHtmlString public static string Asset(this UrlHelper url, string asset) { var path = "~/assets/" + asset; return string.Format("<link href=\"{0}\" />", url.Content(path)); } } This keeps the view lighter, and I can just type... <%= Url.Asset("some_asset") %> ... and be done with it. When .NET 4.0 comes out, and you update your code base, you'll change your static to return a shiny new MvcHtmlString. This will happily prevent and double-escaping. (And you'll want to do this in any code that writes out HTML.)
{ "pile_set_name": "StackExchange" }
Q: Illegal Character on Jenkins Server I had now several Problems with my Jenkins Build Server and i dont know where they come from... I'm getting this error message: illegal character: \65279 which seems like to be UTF16-BOM. When i open the corresponding file with a HEX Editor, i cant see a FE FF mark at the beginning, or somewhere else in the code. Also file does not say anything about BOM: TransactionFunctionImpl.java: UTF-8 Unicode Java program text Whats going on there? Another question is: why cant my jenkins server build bom files, when my eclipse does it? A: According to this site: Note: the JDK 1.6 javac compiler will not compile a UTF-8 source file starting with a byte order mark, failing with the error illegal character: \65279. So presumably the JDK version differs between your desktop and your Jenkins server. The best solution would be to remove the redundant BOM from your source, as suggested in this related answer.
{ "pile_set_name": "StackExchange" }
Q: Can a creature with only a swim speed even move while on land? There are creatures, such as the hunter shark, which has a 40-foot swim speed and a 0-foot "normal/walking" speed; it's longest range attack is 5 feet. Does this mean you could (by some means) drag this creature onto land, and then stab it with a reach weapon? To me this is just somewhat of a disconnect (though I know 5e is not simulationist) since a creature with only a "walking/normal" speed can swim through the water but a creature with only a swim speed cannot walk on land. If you'd like a creature that can more reasonably survive on land there is the dolphin and the ixitxachitl, which can breathe even on land. Can a creature with only a swim speed even move while on land? A: No, they can't The base speed refers to the land speed of any creature, and a speed of 0 means they can't move on land. This is further reinforced in the Monster Manual section on speeds (p. 8): All creatures have a walking speed, simply called the monster's speed. Creatures that have no form of ground-based locomotion have a walking speed of 0 feet. A: No A creature's standard movement speed is its movement on land (the default). The Swim speed is specifically for underwater (movement rules and pg 8 of the Monster Manual). If both are specified then the creature is able to move on land but is also at home in the water. In this case I would expect a listed Swim speed to be greater than half its normal movement, otherwise there wouldn't be much point. If a creature has no movement listed then its default movement (on land) would be 0, though a DM may determine it can flop about a bit. You are right that there isn't a rule the other way around (stating that creatures with only a Swim speed can move at half-movement on land). But this a realistic "disconnect" and pretty much as per real life. I have a walking speed and I can also swim (badly) as many land creatures can. My goldfish has a swim speed but would certainly not be able to move on land! An entirely aquatic creature would also not be able to breathe on land and would suffocate as per the suffocation rules (which do apply either way around). Some creatures can breathe both water and air, and these are pointed out in the Monster descriptions.
{ "pile_set_name": "StackExchange" }
Q: Horizontal scroll css? I want to have one <div> with id that has horizontal scroll, but the problem is it has to be responsive, not with fixed width. html, body {margin: 0; padding: 0;} #myWorkContent{ width:530px; height:210px; border: 13px solid #bed5cd; overflow-x: scroll; overflow-y: hidden; white-space: nowrap; } #myWorkContent a { display: inline-block; vertical-align: middle; } #myWorkContent img {border: 0;} <div id="myWorkContent"> <a href="assets/work/1.jpg"><img src="http://placekitten.com/200/200/" height="190"></a> <a href="assets/work/2.jpg"><img src="http://placekitten.com/120/120/"/></a> <a href="assets/work/3.jpg"><img src="http://placekitten.com/90/90/" height="90" width="90"></a> <a href="assets/work/4.jpg"><img src="http://placekitten.com/50/50/" height="190"></a> <a href="assets/work/5.jpg"><img src="http://placekitten.com/100/100/"></a> <a href="assets/work/6.jpg"><img src="http://placekitten.com/200/200/" height="190"></a> </div><!-- end myWorkContent --> Thanks to http://jsfiddle.net/clairesuzy/FPBWr/ The problem is with that 530px. I would like to use 100% instead. But then I got page scroll and scroll of the DIV goes right, can not get it, any idea? Here is article in Serbian about solution http://www.blog.play2web.com/index.php?id=18 A: Just set your width to auto: #myWorkContent{ width: auto; height:210px; border: 13px solid #bed5cd; overflow-x: scroll; overflow-y: hidden; white-space: nowrap; } This way your div can be as wide as possible, so you can add as many kitty images as possible ;3 Your div's width will expand based on the child elements it contains. jsFiddle A: Below worked for me. Height & width are taken to show that, if you 2 such children, it will scroll horizontally, since height of child is greater than height of parent scroll vertically. Parent CSS: .divParentClass { width: 200px; height: 100px; overflow: scroll; white-space: nowrap; } Children CSS: .divChildClass { width: 110px; height: 200px; display: inline-block; } To scroll horizontally only: overflow-x: scroll; overflow-y: hidden; To scroll vertically only: overflow-x: hidden; overflow-y: scroll;
{ "pile_set_name": "StackExchange" }
Q: How do I prevent Laravel from logging 404 errors? My production laravel log is getting stuffed with 404 errors from bots and the like. I want to be able to review my log daily for real errors, but it's impossible to sort through all of this. What I would prefer is to log everything except 404 errors. Everything else I want to see. What is the best practice for accomplishing this? A: You may use the App::missing() function to catch the error and display a 404 page http://laravel.com/docs/4.2/errors
{ "pile_set_name": "StackExchange" }
Q: Javascript arrays and updating elements with a loop? I'm struggling with this one a little. I'm a junior python developer by trade and I have been asked to build a website. Naturally I said yes and chose Django. Regardless, I'm having a little issue building a calendar widget. I'm using AJAX to pass the request back to the view, and update certain elements based on whether the user is requesting the previous/next month of days. function getPreviousMonth( event ) { $.ajax({ type: "GET", dataType: "json", url: "{% url 'events' %}", data: { 'month': previousMonth, 'year': previousYear } }) .done(function(response) { console.log(response); nextMonth = response.next_month; nextYear = response.next_year; previousMonth = response.previous_month; previousYear = response.previous_year; currentMonth = response.current_month; currentYear = response.current_year; $('#currentMonth').text(currentMonth); $('#currentYear').text(currentYear); }); }; This all seems to be working well. In the response object I have an array of lists (I think, certainly correct me if I am wrong). On the template side I am using Django to setup the calendar from an array of days arrays: {% for week in weeks %} <ul class="days"> {% for day in week %} {% if day == 0 %} <li></li> {% else %} <li>{{ day }}</li> {% endif %} {% endfor %} </ul> {% endfor %} All looks nice (and importantly, functions spot on): What I now want to do, is perform the same logic for the unoredered list (class="days") on the template after response is met. I have the days as the following (the "weeks" array, 0 if the day is contained in the month, overwise it has the day of the month as an integer, hopefully this makes sense): Above is after clicking on the next month, so this corresponds to the days in February. So for each [] list in the array of lists - I want to go in, and update all li's within a ul - hopefully that makes sense. A loop within a loop essentially. A: As I understand it, you want to recreate what you've made with the django template in javascript. As you're using jQuery this should work: // Make this selector more specific if needed $("ul.days").each(function (i) { $(this).find('li').each(function (j) { if (weeks[i][j]) { $(this).html(weeks[i][j]); } else { $(this).html(''); } }); });
{ "pile_set_name": "StackExchange" }
Q: Grid Lines below the contour in Matplotlib I have one question about the grid lines matplotlib. I am not sure if this is possible to do or not. I am plotting the following graph as shown in the image. I won't give the entire code, since it is involving reading of files. However the important part of code is here - X, Y = np.meshgrid(smallX, smallY) Z = np.zeros((len(X),len(X[0]))) plt.contourf(X, Y, Z, levels, cmap=cm.gray_r, zorder = 1) plt.colorbar() ... # Set Border width zero [i.set_linewidth(0) for i in ax.spines.itervalues()] gridLineWidth=0.1 ax.set_axisbelow(False) gridlines = ax.get_xgridlines()+ax.get_ygridlines() #ax.set_axisbelow(True) plt.setp(gridlines, 'zorder', 5) ax.yaxis.grid(True, linewidth=gridLineWidth, linestyle='-', color='0.6') ax.xaxis.grid(False) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') Now, my questions is like this - If I put the grid lines below the contour, they disappear since they are below it. If I put the grid line above the contour, they looks like what they are looking now. However, what I would like to have is the grid lines should be visible, but should be below the black portion of the contour. I am not sure if that is possible. Thank You ! A: In addition to specifying the z-order of the contours and the gridlines, you could also try masking the zero values of your contoured data. Here's a small example: import numpy as np import matplotlib.pyplot as plt x = np.arange(-2*np.pi, 2*np.pi, 0.1) y = np.arange(-2*np.pi, 2*np.pi, 0.1) X, Y = np.meshgrid(x, y) Z = np.sin(X) - np.cos(Y) Z = np.ma.masked_less(Z, 0) # you use mask_equal(yourData, yourMagicValue) fig, ax = plt.subplots() ax.contourf(Z, zorder=5, cmap=plt.cm.coolwarm) ax.xaxis.grid(True, zorder=0) ax.yaxis.grid(True, zorder=0) And the output:
{ "pile_set_name": "StackExchange" }
Q: Bind featherlight gallery to a button? I'm trying to bind a featherlight.js image gallery to a button. See this pen: https://codepen.io/jasonbradberry/pen/aqjLbw I've bound a lightbox to the button (.lightbox-trigger) with the following code: $('#gallery-trigger').featherlightGallery('#gallery a', {}); But it just places the gallery thumbnails into the lightbox instead of the image. What am I missing here? A: Simplest is simply that click on button == click on first image. $('#gallery-trigger').click( function() { $('#gallery a:first').click() } )
{ "pile_set_name": "StackExchange" }
Q: Is there a way to create multiple columns using the max() function in MYSQL? I'm trying to create a new table from a sub table using the following formula: create table if not exists `new_table` as select * from ( select descrip, max(case when ID = 1.01 then value else 0 end) 1.01 from( select ID, `JUL-08` value, 1 descrip from original_table union all select ID, `AGO-08` value, 2 descrip from original_table union all select ID, `SET-08` value, 3 descrip from original_table union all select ID, `OUT-08` value, 4 descrip from original_table union all select ID, `NOV-08` value, 5 descrip from original_table union all select ID, `DEZ-08` value, 6 descrip from original_table ) src group by descrip ) as `new_table`; the formula works well, it creates the table it is intended to create, but i wonder if the max function could be used to create more than 1 column for the same table, or if i have to repeat the whole formula for each ID there is to make a new table or either repeat the max() function in the same formula. A: You can repeat expressions as often as you like. You will need to give them different names. I also note that you have too many subqueries in your expression: create table if not exists `new_table` as select descrip, max(case when ID = 1.01 then value else 0 end) as `1.01`, max(case when ID = 2.01 then value else 0 end) as `2.01` from (select ID, `JUL-08` as value, 1 as descrip from original_table union all select ID, `AGO-08` as value, 2 as descrip from original_table union all select ID, `SET-08` as value, 3 as descrip from original_table union all select ID, `OUT-08` as value, 4 as descrip from original_table union all select ID, `NOV-08` as value, 5 as descrip from original_table union all select ID, `DEZ-08` as value, 6 as descrip from original_table ) src group by descrip; I don't advise you to name your columns as numbers (or SQL keywords for that matter). But if you do, you should use escape characters to be clear on what you are doing. I would recommend something more like id_1_01 so the column name does not need to be escaped.
{ "pile_set_name": "StackExchange" }
Q: Adjusting VoronoiMesh size How it is possible to extend VoronoiMesh to the whole ListPlot in the following example? pts = {{-3, -4}, {-2, 1}, {3, -2}}; Show[ ListPlot[2 pts, PlotRange -> Automatic, AspectRatio -> 1, Frame -> True, Axes -> False], ListPlot[ pts, PlotRange -> Automatic, AspectRatio -> 1, Frame -> True, Axes -> False, PlotMarkers -> {"\[Cross]", 36}, PlotStyle -> Red ], HighlightMesh[ VoronoiMesh[pts], {Style[2, Transparent], Style[1, Thin, Red], Labeled[2, "Index"]}] ] Instead I would like to get something like this without indicating VoronoiMesh range explicitly, like proposed in comments A: This is a hack, but it seems to do what you are asking by creating a new mesh object from the old one. pts = {{-3, -4}, {-2, 1}, {3, -2}}; vm = VoronoiMesh@pts; oldcoords = MinMax /@ Transpose[MeshCoordinates@vm] // Flatten; plot1 = ListPlot[2 pts, PlotRange -> Automatic, AspectRatio -> 1, Frame -> True, Axes -> False]; newcoords = plot1 // Charting`get2DPlotRange // Flatten; plot2 = ListPlot[pts, PlotRange -> Automatic, AspectRatio -> 1, Frame -> True, Axes -> False, PlotMarkers -> {"\[Cross]", 36}, PlotStyle -> Red]; Show[ plot1, plot2, HighlightMesh[ MeshRegion[(MeshCoordinates@vm) /. Thread[oldcoords -> newcoords], MeshCells[vm, 2]], {Style[2, Transparent], Style[1, Thin, Red], Labeled[2, "Index"]}] ]
{ "pile_set_name": "StackExchange" }
Q: Cancel button click event in the new form I have created an external list and in the new form I have a few input controls. Some of them are required fields but are not indicated as such on page. So I am trying to check if the input is empty and show a message that they need to fill it in. But the problem is that once the button is clicked it immediately sends the user the list. So, how can I cancel the click event if the fields are empty? $('#ctl00_ctl40_g_9068430e_e259_454c_8cfa_f5a629496c52_ctl00_toolBarTbl_RightRptControls_ctl00_ctl00_diidIOSaveItem').click(function() { var descText = $('#Description_$TextField').val(); if(descText=='') { $('#Description_$TextField').append('<p>Please enter a description</p>'); return false; } }); A: What you are looking for is called PreSaveAction(). This function allows to override behavior for a Save button. See here for more info: http://www.ilikesharepoint.de/2014/06/sharepoint-presaveaction-helps-for-actions-before-saving-an-item/
{ "pile_set_name": "StackExchange" }
Q: Override Chrome keyboard shortcuts in a user script I wrote a user script that performs a certain operation on selected text in a textarea when pressing CTRL+SHIFT+B. This is done by registering a keypress event for the textarea and then checking the pressed key. To prevent the browser from handling the key combination I'm using the preventDefault() method which works fine in Firefox (the Library window is not opened but my code is executed instead). However, in Chrome that key combination opens the bookmarks bar and the keypress event is not even triggered. I wonder if there's a way to create such a shortcut in Chrome. It needs to work with a userscript - a real extension is not an option since I'd prefer not to maintain two different "versions" for Firefox and Chrome. A: Apparently, the Chrome UI triggers off of keydown instead of keypress (This Quirksmode article may suggest why -- keypress is supposed to fire when an actual character is being inserted). So changing the appropriate line to: $(document).on('keydown', '.wmd-input', function(e) { Seems to work on both FF and Chrome.
{ "pile_set_name": "StackExchange" }
Q: Calculate point of intersection line of two planes I found some source code that I do not really understand. I will give some pseudo-code in my description to give you a better idea how the algorithm works. Basically, two planes with three vertices each are taken into account and the line of intersection for the two planes is calculated. The goal is to calculate the direction vector and the origin point of the intersection line. The two planes are described as follows: plane1 = {(0.0, 0.5, 0.8), (0.0, -0.5, 0.8), (0, 0, 0)) plane2 = {(0.5, -0.5, 0.5), (0.5, 0.5, 0.5), (-0.5, -0.5, 0.5)} If you draw these two triangles, you will notice that they both intersect. Now I want to calculate the line of intersection. First I calculate the two normal vectors for both planes, I call them n1 and n2. Then I calculate the direction of the intersection line by using the cross-product of the two normal vectors: direction = n1 X n2 The direction vector is 0, -1, 0 since the intersection line goes along the negative y-axis. So far so good. Next, I use the plane equation (ax + by +cz = -d) to calculate the distance from the two points of each plane to the coordinate origin: d1 = -(n1.x * plane1.v1.x + n1.y * plane1.v1.y + n1.z * plane1.v1.z) d2 = -(n2.x * plane2.v2.x + n2.y * plane2.v2.y + n2.z * plane2.v2.z) So n1.x, n1.y and n1.z are the a, b and c components of the normal-vector n1. This is analog to n2. And now comes the part that I do not understand. Given is the following source-code: if(Math.abs(direction.x)>0) { point.x = 0; point.y = (d2*normalFace1.z - d1*normalFace2.z)/direction.x; point.z = (d1*normalFace2.y - d2*normalFace1.y)/direction.x; } else if(Math.abs(direction.y)>0) { point.x = (d1*normalFace2.z - d2*normalFace1.z)/direction.y; point.y = 0; point.z = (d2*normalFace1.x - d1*normalFace2.x)/direction.y; } else { point.x = (d2*normalFace1.y - d1*normalFace2.y)/direction.z; point.y = (d1*normalFace2.x - d2*normalFace1.x)/direction.z; point.z = 0; } Here, the origin point of the intersection line is calculated, but I do not understand how it is done. Why is x, y or z set to zero if the corresponding x, y or z values of direction is greater 0? Where does the formulas inside of the if-statements come from? Thanks for your help! A: If the line is not parallel to $yz$ plane (abs(direction.x) not equal to $0$), it has to cross $yz$ plane at one point. At that point, $x=0$. Since the line is the intersection of the two planes, the $y,z$ values satisfy: $$b_1y+c_1z=-d_1\\ b_2y+c_2z=-d_2$$ We then find the $y,z$ value by solving this system of linear equations. You can apply Cramer's rule to get $$y=\frac{\det\begin{pmatrix}-d_1&c_1\\-d_2&c_2\end{pmatrix}}{\det\begin{pmatrix}b_1&c_1\\b_2&c_2\end{pmatrix}}$$ You can see this is exactly the first case. The other two cases are similar.
{ "pile_set_name": "StackExchange" }
Q: How to quickly mock services in spring unit tests? @Bean public EntityManager(EntityManagerFactory emf) { //... } How can I quickly mock both of these beans (em + emf) inside a JUnit test? Is there some framework that allows me to define eg @Mock EntitiyManager em;? A: Take a look at springockito together with spring-test. It integrates spring with mockito and supports both annotation based mocks and mocks configured in a spring applicationContext. A: You seem to be aware of the @Mock annotation, so presumably you know what Mockito is. You just mock the EntityManager exactly the same way you would mock anything else. @Mock EntitiyManager em; initMocks(); MyService myService = new MyServiceImpl(em);
{ "pile_set_name": "StackExchange" }
Q: Different voltage rails output filter does share same core I am reviewing circuit diagrams of ATX power supplies. I have noticed this in almost all different designs of ATX power supplies. Different voltage power rails output filter share a one core [ toroid ]. Is there is a specific reason for this or this is just to reduce the core size and number of components? A: This is what's known as a coupled inductor. From a DC/steady-state standpoint, the behaviour is identical to independent inductors. Under dynamic conditions, the coupled inductor provides numerous benefits (in addition to the lower parts count you mentioned): Improved transient response Improved cross regulation Ripple current steering Easier current limiting
{ "pile_set_name": "StackExchange" }
Q: TYPO3: what abstract to use for articles? I'm just wondering how to implement pages with articles in TYPO3. I've seen News admin and tt_news package, so it seems these could be used too. But articles are not exactly news, so I wonder if using tt_news for this purpose isn't just some dirty hack and I wonder if there is some cleaner concept to be used for articles. With article I mean something on certain topic which is not quickly outdated (contrary to news), the publish date is not so important, and the sort order of articles would not necessarily be by date. A: No, using tt_news is not dirty hack, it was used through long years for veeeeery different purposes and for now it's best solution I think (without writing custom extensions). What's more that's not only my thoughts this extension has the biggest number of downloads from TYPO3 repository. Using different templates, categories and RealURL settings you can 'mask' that is tt_news in one place and use it for an example to build simple product's catalogue with lists and single views. It also offers possibility to use hooks for extending ie. by adding additional template markers so instead writing the ext from the scratch, you just only write simple hooks functionality and that's all. As far as I remember there are even sample hooks in tt_news source code, so you just need to copy it into your own ext. PS. by default tt_news doesn't support manual sorting (it sorts from newest to oldest from the range), however you'll find few extensions in repository to add this functionality.
{ "pile_set_name": "StackExchange" }
Q: PlaceAutocompleteFragment disappears on click I wanted to implement AutocompleteTextView (google places) but when I click to searchView in a fragment, the fragment disappears (fell down). My code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_autocomplete); PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); AutocompleteFilter typeFilter = new AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES) .build(); autocompleteFragment.setFilter(typeFilter); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(com.google.android.gms.location.places.Place place) { // TODO: handle click } @Override public void onError(Status status) { // TODO: Handle the error. } }); } xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="ui.screen.activity.AutocompleteActivity"> <fragment android:id="@+id/place_autocomplete_fragment" android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" android:layout_width="match_parent" android:layout_height="wrap_content"/> </RelativeLayout> Thanks for any advice A: I had the same problem. I messed up a little bit with the API Console https://console.developers.google.com/ enabling the Maps API AND the Places API for Android and now it's working fine.
{ "pile_set_name": "StackExchange" }
Q: Eclipse Menu distorted in Ubuntu-13.10 I have recently installed Ubuntu 13.10 on my Lenovo intel core2 duo 32 bit laptop with 15'' screen. Some days back I downloaded eclipse-standard-kepler-SR1-linux-gtk.tar.gz from the eclipse web site. But after starting eclipse I see the menu distorted. You can refer the video here : http://youtu.be/fcBHLAlFj4Y A: You can try the following command: UBUNTU_MENUPROXY= eclipse (Where eclipse is the path to your eclipse) For more details check out this link
{ "pile_set_name": "StackExchange" }
Q: Output forEach loop to innerHTML Dumb question, getting acclimated to working with ES6 / Vanilla JS. This is the loop working perfectly with console.log here.... const theServices = ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"]; theServices.forEach(function(element) { let formName = element; formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase(); console.log( ` <div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" /> <label for="${formName}">${element} </label> </div> `) }); <div id="place-here"></div> Now trying to insert into DOM with innerHTML returns undefined. What is the appropriate way to output loops like these? const theServices = ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"]; let theseCheckBoxes = theServices.forEach(function(element) { let formName = element; formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase(); return ` <div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" /> <label for="${formName}">${element} </label> </div> ` }); ; document.querySelector('#place_here').innerHTML = theseCheckBoxes; <div id="place_here"></div> A: ForEach doesn't return anything. So theseCheckBoxes will be undefined. Try changing it to map() and the join() the results. const theServices = ["Accounting", "Big Data", "Business", "Category", "Concept", "Consultant", "Consumer", "Corporate", "Cost", "Customer", "Development", "Digital", "Distribution", "Due Diligence", "Financial", "Global Sourcing", "Go-to-market", "Growth", "Improvement", "Information", "Technology", "Innovation", "Lean", "Management", "Manufacturing", "Marketing", "Merchandising", "Mergers & Acquisitions", "Operations", "Organization / Organizational", "Performance", "Portfolio", "Post-merger", "Pricing", "Procurement", "Product", "Profitability", "Purchasing", "Restructuring", "Retail", "Revenue", "Sales", "Strategy", "Supply Chain", "Sustainable", "Technology", "Transformation", "Turnaround", "Zero-based", "Budgeting"]; let theseCheckBoxes = theServices.map(function(element) { // <-- map instead of forEach let formName = element; formName = formName.replace(/[^A-Za-z0-9]/g, '_').toLowerCase(); return ` <div><input type="checkbox" id="${formName}" name="cpg_services" value="${formName}" /> <label for="${formName}">${element} </label> </div> ` }); ; document.querySelector('#place_here').innerHTML = theseCheckBoxes.join('\n'); <div id="place_here"></div>
{ "pile_set_name": "StackExchange" }
Q: What reasons would a supervisor have for silently listening in to a phone interview being conducted by his subordinates? I've worked in the IT profession for 12 years and participated in maybe ~40 phone interviews as the interviewer and interviewee. Never have I seen or heard of the interviewer's boss silently listening in to the call and not introducing themselves. This happened for the first time I'm aware recently. In this case, the interviewer made an offhanded joke referring to his boss in the room. I see the red flags in this, as the subordinates may feel pressure to hold back on any perceived negatives. Their boss also called me personally to ask me to apply, as I had a previous working relationship with him elsewhere. I don't want to ignore red flags, but what would be neutral or positive reasons for this? Edit: I took @mutt's (obvious in hindsight) advice and asked the boss directly. Turns out I made an assumption that the subordinates were in a conference room. They were at their desks which are located next to the boss. While I question not being in a conference room for guaranteed privacy, it wasn't on the boss and more on the subordinates in that case. A: In general a boss would "listen in" to get the gist of the candidates, but most likely to get the style of the interviewer themselves to know better how they go about interviewing and selecting candidates. I personally would do this to know about the interviewer. I would also introduce myself and let people know I am listening in, but I have run into a few folks that seem to like to be secretive. It is not necessarily a bad thing, but it does indicate they are a type of person that keeps secrets vs. sharing alot of info with others. This could be a red flag, but you really should just ask them why they are on there without introducing themselves if you want to know. There is not enough information to assume anything realistic or certain from this simple interaction. Also, there are some places that require supervision on interviews for internal company political reasons. If the boss must be on the interview but really doesn't plan on saying anything this could be a reason. Again, when in doubt on something like this your best bet is to be direct and ask. Their response will either throw red flags or ease them which it sounds like that is what you need in this case. A: Personally I (technical team lead) would see it fit in the following occasions training/feedback; I have a junior co-worker which starts to do interviews. In such interviews I typically make a very brief introduction like ('i am another colleague') and remain silent for the rest of the interview, and then share my thoughts about how my colleague performed in the interview later; I could imagine that some people may even skip the short introduction completely. schedule. Sometimes my colleague starts without me (i have a tight schedule). Instead of interrupting the interview by introducing myself when it is already ongoing for 20 min, i rather remain silent instead of making the candidate more nervous.
{ "pile_set_name": "StackExchange" }
Q: Is there any out of the box admin page for SimpleMembershipProvider or OAuth in ASPNET MVC 4? I'm using SimpleMembershipProvider in and ASPNET MVC 4 applcation which uses WebApi, Entity Framework 5 and Code First. I did it following this post, which seeds the database and seems to work. My question is: Is there any out of the box admin page to give or remove roles like admin from users? If not, any suggestion? Thanks! Guillermo. A: No, sadly there isn't. On the bright side, you can create your own and it's designed to work well with EF. Simple Membership is far more flexible than the old .NET Membership. This is a nice, though not exhaustive overview of simple membership and how to integrate it with EF Code-First. http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx This link guides you through the process of manually creating an admin (near bottom) http://blog.osbornm.com/2010/07/21/using-simplemembership-with-asp-net-webpages/ In truth, classic Membership is more convenient to use 'out of the box'. setting up 'simpleMembership' is (ironically) heavy compared to the boxed older version. But, after all the OMG, you will probably find it to be a better solution.
{ "pile_set_name": "StackExchange" }
Q: Python 3 : IndexError: list index out of range I am trying to remove duplicates from a list. I am trying to do that with below code. >>> X ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b'] >>> for i in range(X_length) : ... j=i+1 ... if X[i] == X[j] : ... X.pop([j]) But I am getting Traceback (most recent call last): File "<stdin>", line 2, in <module> IndexError: list index out of range Please help. A: When you start to remove items from a list, it changes in size. So, the ith index may no longer exist after certain removals: >>> x = ['a', 'b', 'c', 'd', 'e'] >>> x[4] 'e' >>> x.pop() 'e' >>> x[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range A simpler way to remove duplicate items is to convert your list to a set, which can only contain unique items. If you must have it as a list, you can convert it back to a list: list(set(X)). However, order is not preserved here. If you want to remove consecutive duplicates, consider using a new array to store items that are not duplicates: unique_x = [] for i in range(len(x) - 1): if x[i] != x[i+1]: unique_x.append(x[i]) unique_x.append(x[-1]) Note that our range bound is len(x) - 1 because otherwise, we would exceed the array bounds when using x[i+1].
{ "pile_set_name": "StackExchange" }
Q: Ruby split string and preserve separator In Ruby, what's the easiest way to split a string in the following manner? 'abc+def' should split to ['abc', '+', 'def'] 'abc\*def+eee' should split to ['abc', '\*', 'def', '+', 'eee'] 'ab/cd*de+df' should split to ['ab', '/', 'cd', '\*', 'de', '+', 'df'] The idea is to split the string about these symbols: ['-', '+', '*', '/'] and also save those symbols in the result at appropriate locations. A: Option 1 /\b/ is a word boundary and it has zero-width, so it will not consume any characters 'abc+def'.split(/\b/) # => ["abc", "+", "def"] 'abc*def+eee'.split(/\b/) # => ["abc", "*", "def", "+", "eee"] 'ab/cd*de+df'.split(/\b/) # => ["ab", "/", "cd", "*", "de", "+", "df"] Option 2 If your string contains other word boundary characters and you only want to split on -, +, *, and /, then you can use capture groups. If a capture group is used, String#split will also include captured strings in the result. (Thanks for pointing this out @Jordan) (@Cary Swoveland sorry, I didn't see your answer when I made this edit) 'abc+def'.split /([+*\/-])/ # => ["abc", "+", "def"] 'abc*def+eee'.split /([+*\/-])/ # => ["abc", "*", "def", "+", "eee"] 'ab/cd*de+df'.split /([+*\/-])/ # => ["ab", "/", "cd", "*", "de", "+", "df"] Option 3 Lastly, for those using a language that might not support string splitting with a capture group, you can use two lookarounds. Lookarounds are also zero-width matches, so they will not consume any characters 'abc+def'.split /(?=[+*\/-])|(?<=[+*\/-])/ # => ["abc", "+", "def"] 'abc*def+eee'.split /(?=[+*\/-])|(?<=[+*\/-])/ # => ["abc", "*", "def", "+", "eee"] 'ab/cd*de+df'.split /(?=[+*\/-])|(?<=[+*\/-])/ # => ["ab", "/", "cd", "*", "de", "+", "df"] The idea here is to split on any character that is preceded by one of your separators, or any character that is followed by one of the separators. Let's do a little visual ab ⍿ / ⍿ cd ⍿ * ⍿ de ⍿ + ⍿ df The little ⍿ symbols are either preceded or followed by one of the separators. So this is where the string will get cut. Option 4 Maybe your language doesn't have a string split function or sensible ways to interact with regular expressions. It's nice to know you don't have to sit around guessing if there's clever built-in procedures that magically solve your problems. There's almost always a way to solve your problem using basic instructions class String def head self[0] end def tail self[1..-1] end def reduce acc, &f if empty? acc else tail.reduce yield(acc, head), &f end end def separate chars res, acc = reduce [[], ''] do |(res, acc), char| if chars.include? char [res + [acc, char], ''] else [res, acc + char] end end res + [acc] end end 'abc+def'.separate %w(- + / *) # => ["abc", "+", "def"] 'abc*def+eee'.separate %w(- + / *) # => ["abc", "*", "def", "+", "eee"] 'ab/cd*de+df'.separate %w(- + / *) # => ["ab", "/", "cd", "*", "de", "+", "df"] A: I see this is close to part of @naomic's answer, but I'll leave it for the small differences. splitters = ['-', '+', '*', '/'] r = /(#{ Regexp.union(splitters) })/ # => /((?-mix:\-|\+|\*|\/))/ 'abc+def'.split r #=> ["abc", "+", "def"] "abc\*def+eee".split r #=> ["abc", "*", "def", "+", "eee"] 'ab/cd*de+df'.split r #=> ["ab", "/", "cd", "*", "de", "+", "df"] Notes: the regex places #{ Regexp.union(splitters) } in a capture group, causing String#split to include the strings that do the splitting (last sentence of the third paragraph). the second example string must be in double quotes in order to escape *.
{ "pile_set_name": "StackExchange" }
Q: chart looking strange on phone´s browser using chart.js I am using chart.js to create my charts. The chart itself looks pretty neat as long as I display it on my PC´s browsers. As soon as I use my phone´s browser the chart does not look neat anmyore at all, the x-Axis being cut partly. I am also using Bootstrap. My code looks as following: <div id="TempChart" class="chart-container col-md-8 col-xs-8 col-lg-8 col-sm-8" style ="position: relative; 40vh; width 80vw"> <canvas id="chart"></canvas> </div> Changing it to following did not help: <canvas id="chart" class = "img-responsive"></canvas> I have also added following part in my javascript code for generating the chart. options: { animation: { duration: 0 }, responsive: true, Does anybody have an idea how to make it look neat on a phone´s browser as well? A: To display properly on changing viewport size use options: { maintainAspectRatio: false, Edit: I found the best experience in a particular case was using the above mentioned but without options: { responsive: true, so you might wanna try that as well :-)
{ "pile_set_name": "StackExchange" }
Q: Rectangular select in Eclipse editor as in any Microsoft tools In Microsoft tools such as Word and Visual Studio, there is a feature to select text in a rectangle manner by pressing the Alt key while selecting. Is there anything like that in Eclipse? A: Pressing Shift + Alt + A toggles Block or Column selection mode in Eclipse 3.5 or later. Other than that you can try the 'Columns 4 Eclipse' Plug-in for Eclipse 3.3.1 here. A: As another poster noted- the Android ADT blocks the use of Alt+Shift+A. An easy fix is to go to Window->Preferences->General->Keys and look for "Toggle Block Selection" From there, you can assign your own hotkey that will not conflict with the Android tools. For example I tied it to Alt+A, which works just fine. As others have said, this will not work in Eclipse 3.4 or earlier. I am using Eclipse 3.7.2, YMMV. A: For the Mac, use ⌥⌘A (option+command+A) to toggle between the two selection modes. Command-Shift-A will give you something quite unexpected.
{ "pile_set_name": "StackExchange" }
Q: Extract pvalue from glm I'm running many regressions and am only interested in the effect on the coefficient and p-value of one particular variable. So, in my script, I'd like to be able to just extract the p-value from the glm summary (getting the coefficient itself is easy). The only way I know of to view the p-value is using summary(myReg). Is there some other way? e.g.: fit <- glm(y ~ x1 + x2, myData) x1Coeff <- fit$coefficients[2] # only returns coefficient, of course x1pValue <- ??? I've tried treating fit$coefficients as a matrix, but am still unable to simply extract the p-value. Is it possible to do this? Thanks! A: You want coef(summary(fit))[,4] which extracts the column vector of p values from the tabular output shown by summary(fit). The p-values aren't actually computed until you run summary() on the model fit. By the way, use extractor functions rather than delve into objects if you can: fit$coefficients[2] should be coef(fit)[2] If there aren't extractor functions, str() is your friend. It allows you to look at the structure of any object, which allows you to see what the object contains and how to extract it: summ <- summary(fit) > str(summ, max = 1) List of 17 $ call : language glm(formula = counts ~ outcome + treatment, family = poisson()) $ terms :Classes 'terms', 'formula' length 3 counts ~ outcome + treatment .. ..- attr(*, "variables")= language list(counts, outcome, treatment) .. ..- attr(*, "factors")= int [1:3, 1:2] 0 1 0 0 0 1 .. .. ..- attr(*, "dimnames")=List of 2 .. ..- attr(*, "term.labels")= chr [1:2] "outcome" "treatment" .. ..- attr(*, "order")= int [1:2] 1 1 .. ..- attr(*, "intercept")= int 1 .. ..- attr(*, "response")= int 1 .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> .. ..- attr(*, "predvars")= language list(counts, outcome, treatment) .. ..- attr(*, "dataClasses")= Named chr [1:3] "numeric" "factor" "factor" .. .. ..- attr(*, "names")= chr [1:3] "counts" "outcome" "treatment" $ family :List of 12 ..- attr(*, "class")= chr "family" $ deviance : num 5.13 $ aic : num 56.8 $ contrasts :List of 2 $ df.residual : int 4 $ null.deviance : num 10.6 $ df.null : int 8 $ iter : int 4 $ deviance.resid: Named num [1:9] -0.671 0.963 -0.17 -0.22 -0.956 ... ..- attr(*, "names")= chr [1:9] "1" "2" "3" "4" ... $ coefficients : num [1:5, 1:4] 3.04 -4.54e-01 -2.93e-01 1.34e-15 1.42e-15 ... ..- attr(*, "dimnames")=List of 2 $ aliased : Named logi [1:5] FALSE FALSE FALSE FALSE FALSE ..- attr(*, "names")= chr [1:5] "(Intercept)" "outcome2" "outcome3" "treatment2" ... $ dispersion : num 1 $ df : int [1:3] 5 4 5 $ cov.unscaled : num [1:5, 1:5] 0.0292 -0.0159 -0.0159 -0.02 -0.02 ... ..- attr(*, "dimnames")=List of 2 $ cov.scaled : num [1:5, 1:5] 0.0292 -0.0159 -0.0159 -0.02 -0.02 ... ..- attr(*, "dimnames")=List of 2 - attr(*, "class")= chr "summary.glm" Hence we note the coefficients component which we can extract using coef(), but other components don't have extractors, like null.deviance, which you can extract as summ$null.deviance. A: I've used this technique in the past to pull out predictor data from summary or from a fitted model object: coef(summary(m))[grepl("var_i_want$",row.names(coef(summary(m)))), 4] which lets me easily edit which variable I want to get data on. Or as pointed out be @Ben, use match or %in%, somewhat cleaner than grepl: coef(summary(m))[row.names(coef(summary(m))) %in% "var_i_want" , 4] A: Instead of the number you can put directly the name coef(summary(fit))[,'Pr(>|z|)'] the other ones available from the coefficient summary: Estimate Std. Error z value Pr(>|z|)
{ "pile_set_name": "StackExchange" }
Q: Linq query to display unique set of names for current data set I have a linq query that is used to display the list of requests from multiple users.And a Requestor can have multple requests(So the grid can have same Requestor multiple times). Now i am creating a dropdown list with unique Requestor that are displayed on the grid.(issue is i am not getting the distinct list but getting all the Requestor multiple times). Below is the linq query i am unsing.Can anyone suggest with correct linq query. Dim rqstQry = From x In db.Request_vws _ Order By x.RequestID Descending _ Select x.RequestID, Descr = x.Descr, _ RequestorName = String.Format("{0} {1}", x.FIRST_NAME, x.LAST_NAME), _ RelatedTask = GetTaskDescr(x.WorkID, x.TaskLabel, x.TaskDescr), _ RequestDescr = GetRequestDescr(x.RequestType), x.SubmitDttm, x.UpdatedDttm, _ x.ChangeDttm, _ x.MigrTimeStr, x.MigrApptTime, _ x.Requestor Ditinct DataBind: RequestorCB1.DataSource = rqstQry RequestorCB1.DataTextField = "Requestor" RequestorCB1.DataValueField = "REquestor" RequestorCB1.DataBind() Need distinct user in the dropdownlist A: Got this by using the below query. Dim rqstQry = (From x In db.Request_vws _ Order By x.RequestID Descending _ Select x.RequestID, Descr = x.Descr, _ RequestorName = String.Format("{0} {1}", x.FIRST_NAME, x.LAST_NAME), _ RelatedTask = GetTaskDescr(x.WorkID, x.TaskLabel, x.TaskDescr), _ RequestDescr = GetRequestDescr(x.RequestType), x.SubmitDttm, x.UpdatedDttm, _ x.ChangeDttm, _ x.MigrTimeStr, x.MigrApptTime, _ x.Requestor). Distinct() Dim rqstQry2 = (From y In rqstQry _ Select y.Requestor, y.RequestorName).Distinct()
{ "pile_set_name": "StackExchange" }
Q: Javascript associative array how to map multiple strings to a number Javascript newbie here. I currently have an associative array in the following format: StringA: number, StringB: number Is it possible to map multiple strings to the same number? Something like this (some numbers may have a different number of Strings mapped to them): StringA, StringB, StringC: number, StringD, StringE: number, StringF, StringG, StringH, StringI: number Basically, I want holder to have the same value whether I write var holder = arr[StringA] or var holder = arr[StringC]. If it's not possible could someone point me in the right direction? Any help would be greatly appreciated! A: You could use an object with a value for the object with multiple keys for one object. Basically this creates a reference to the shared object. Then you could change the value inside of the object. var temp = { value: 42 }, object = { a: temp, b: temp, c: temp }; console.log(object.a.value); // 42 object.b.value = 7; console.log(object.c.value); // 7
{ "pile_set_name": "StackExchange" }
Q: What's the purpose of dropdown-toggle class in bootstrap dropdowns? Dropdown menus work perfectly with or without the dropdown-toggle bootstrap class being applied to <button> element,so why use it in the first place? A: The dropdown-toggle class adds the outline: 0; on :focus to the button, so when you click on the button it will not have the surrounding blue border of the "active" element. Check the next two bottons: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container"> <h2>Dropdowns</h2> <p>The .divider class is used to separate links inside the dropdown menu with a thin horizontal line:</p> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials - no border <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">HTML</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> <li class="divider"></li> <li><a href="#">About Us</a></li> </ul> </div> </div> <div class="container"> <h2>Dropdowns</h2> <p>The .divider class is used to separate links inside the dropdown menu with a thin horizontal line:</p> <div class="dropdown"> <button class="btn btn-default" type="button" data-toggle="dropdown">Tutorials - with border <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">HTML</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> <li class="divider"></li> <li><a href="#">About Us</a></li> </ul> </div> </div> A: It adds the following CSS properties, but they impact when dropdown button's content is displayed: It's basically some button inner box-shadow when .open, as well as color, background-color, border-color and outline (on :focus) removal. Here a comparison between the two: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Single button --> <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> With .dropdown-toggle <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">Action</a> </li> <li><a href="#">Another action</a> </li> <li><a href="#">Something else here</a> </li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a> </li> </ul> </div> <!-- Single button --> <div class="btn-group"> <button type="button" class="btn btn-default" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Without .dropdown-toggle <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">Action</a> </li> <li><a href="#">Another action</a> </li> <li><a href="#">Something else here</a> </li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a> </li> </ul> </div> Difference tested in Chrome, Opera & Safari:
{ "pile_set_name": "StackExchange" }