text
stringlengths
15
59.8k
meta
dict
Q: Procedure to perform a web search (Bing) in Office 2013 task pane app I am trying to make an office 2013 task pane app where it is required to make a web search and display the result in the task pane. Please explain the processes involved. There is not much given in MSDN. Thank You! A: http://technet.microsoft.com/en-us/library/jj219429.aspx This explains the process in detail. The process is slightly different depending on which office app you're building for. You can do task panes in... Excel, Word, Project and PowerPoint. Here is a link to tutorials and samples... http://msdn.microsoft.com/en-us/library/office/fp142152.
{ "language": "en", "url": "https://stackoverflow.com/questions/20408398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If Route doesn't exist -> go to other route using its default action? So I'm having a little problem here with routing. There are two parts to this web application:   1. Brochure / Display Website   2. Internal Site / Client Application We wanted a way to release changes for the brochure without having to do a whole release of said Web application. Visiting existing named views will take the user to a brochure page, however if it doesn't exist, it will act like they are a client and will redirect them to their company's login screen. Global.asax: //if view doesnt exist then url is a client and should be redirected routes.MapRoute( name: "Brochure", url: "{id}", defaults: new { controller = "brochure", action = "Brochure", id = "Index" }, namespaces: new[] { "Web.Areas.Brochure.Controllers" } ); //This is home page routes.MapRoute( name: "HomeDefault", url: "{client}/{action}", defaults: new { controller = "home", action = "index" }, namespaces: new string[] { "Web.Controllers" } ); Controller: /// <summary> Check if the view exists in our brochure list </summary> private bool ViewExists(string name) { ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null); return (result.View != null); } /// <summary> Generic action result routing for all pages. /// If the view doesn't exist in the brochure area, then redirect to interal web /// This way, even when we add new pages to the brochure, there is no need to re-compile & release the whole Web project. </summary> public ActionResult Brochure(string id) { if (ViewExists(id)) { return View(id); } return RedirectToRoute("HomeDefault", new { client = id }); } This code works fine up until we log in and go to the landing page. It seems to keep the Brochure action in the route and doesn't want to go to the subsequent controller which results in a 500 error. e.g. 'domain/client/Brochure' when it needs to be: 'domain/client/Index' Things tried but not worked: * *Changing RedirectToRoute() to a RedirectToAction() - this results in a finite loop of going back to the ActionResult Brochure(). So changing controllers through that didn't work. *Create an ActionResult called Brochure() inside the 'HomeController'. It doesn't even get hit. *Passed in namespaces for RedirectToRoute() as an attribute. I knew this would probably not work, but it was worth a try. So the question is: How can I get the route to act properly? A: If you can restrict id to some subset of all values you can add that constraints to route (i.e. numbers only) to let default handle the rest. routes.MapRoute( name: "Brochure", url: "{id}", defaults: new { controller = "brochure", action = "Brochure", id = "Index" }, namespaces: new[] { "Web.Areas.Brochure.Controllers" } constraints : new { category = @"\d+"} ); If you can't statically determine restrictions - automatically redirecting in your BrochureController similar to your current code would work. The only problem with sample in the question is it hits the same route again and goes into infinite redirect loop - redirect to Url that does not match first rule: // may need to remove defaults from second route return RedirectToRoute("HomeDefault", new { client = id, action = "index" }); If standard constraints do not work and you must keep single segment in url - use custom constraints - implement IRouteConstraint and use it in first route. See Creating custom constraints. A: Two ways I could have solved this issue: Way 1 I reviewed the redirect and just passed in an action in order to get a route that has 2 segments in the url. i.e. client/Index. The Index action now handles logins - going past a custom controller. public class HomeController : CustomController public ActionResult Brochure(string id, string action) { if (ViewExists(id)) { return View(id); } return RedirectToAction("Index", "Home", new { client = id, action = "Index" }); } Way 2 (from @Alexei_Levenkov) Create a custom Route constraint so the route will be ignored if the view cannot be found. namespace Web.Contraints { public class BrochureConstraint : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { //Create our 'fake' controllerContext as we cannot access ControllerContext here HttpContextWrapper context = new HttpContextWrapper(HttpContext.Current); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "brochure"); ControllerContext controllerContext = new ControllerContext(new RequestContext(context, routeData), new BrochureController()); //Check if our view exists in the folder -> if so the route is valid - return true ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext, "~/Areas/Brochure/Views/Brochure/" + values["id"] + ".cshtml", null); return result.View != null; } } } namespace Web { public class MvcApplication : System.Web.HttpApplication { //If view doesnt exist then url is a client so use the 'HomeDefault' route below routes.MapRoute( name: "Brochure", url: "{id}", defaults: new { controller = "brochure", action = "Brochure", id = "Index" }, namespaces: new[] { "Web.Areas.Brochure.Controllers" }, constraints: new { isBrochure = new BrochureConstraint() } ); //This is home page for client routes.MapRoute( name: "HomeDefault", url: "{client}/{action}", defaults: new { controller = "home", action = "index" }, namespaces: new string[] { "Web.Controllers" } ); } } I hope this helps someone else out there. A: There are several issues with your configuration. I can explain what is wrong with it, but I am not sure I can set you on the right track because you didn't provide the all of the URLs (at least not all of them from what I can tell). Issues * *Your Brouchure route, which has 1 optional URL segment named {id}, will match any URL that is 0 or 1 segments (such as / and /client). The fact that it matches your home page (and you have another route that is named HomeDefault that will never be given the chance to match the home page) leads me to believe this wasn't intended. You can make the {id} value required by removing the default value id = "Index". *The Brouchure route has a namespace that indicates it is probably in an Area. To properly register the area, you have to make the last line of that route ).DataTokens["area"] = "Brochure"; or alternatively put it into the /Areas/Brouchure/AreaRegistration.cs file, which will do that for you. *The only way to get to the HomeDefault route is to supply a 2 segment URL (such as /client/Index, which will take you to the Index method on the HomeController). The example URLs you have provided have 3 segments. Neither of the routes you have provided will match a URL with 3 segments, so if these URLs are not getting 404 errors they are obviously matching a route that you haven't provided in your question. In other words, you are looking for the problem in the wrong place. If you provide your entire route configuration including all Area routes and AttributeRouting routes (including the line that registers them), as well as a complete description of what URL should go to what action method, I am sure you will get more helpful answers. So the question is: How can I get the route to act properly? Unknown. Until you describe what properly is. Related: Why map special routes first before common routes in asp.net mvc?
{ "language": "en", "url": "https://stackoverflow.com/questions/36145574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the correct way to prevent reentrancy and ensure a lock is acquired for certain operations? I'm designing a base class that, when inherited, will provide business functionality against a context in a multithreaded environment. Each instance may have long-running initialization operations, so I want to make the objects reusable. In order to do so, I need to be able to: * *Assign a context to one of these objects to allow it to do its work *Prevent an object from being assigned a new context while it already has one *Prevent certain members from being accessed while the object doesn't have a context Also, each context object can be shared by many worker objects. Is there a correct synchronization primitive that fits what I'm trying to do? This is the pattern I've come up with that best fits what I need: private Context currentContext; internal void BeginProcess(Context currentContext) { // attempt to acquire a lock; throw if the lock is already acquired, // otherwise store the current context in the instance field } internal void EndProcess() { // release the lock and set the instance field to null } private void ThrowIfNotProcessing() { // throw if this method is called while there is no lock acquired } Using the above, I can protect base class properties and methods that shouldn't be accessed unless the object is currently in the processing state. protected Context CurrentContext { get { this.ThrowIfNotProcessing(); return this.context; } } protected void SomeAction() { this.ThrowIfNotProcessing(); // do something important } My initial though was to use Monitor.Enter and related functions, but that doesn't prevent same-thread reentrancy (multiple calls to BeginProcess on the original thread). A: There is one synchronization object in .NET that isn't re-entrant, you are looking for a Semaphore. Before you commit to this, do get your ducks in a row and ask yourself how it can be possible that BeginProcess() can be called again on the same thread. That is very, very unusual, your code has to be re-entrant for that to happen. This can normally only happen on a thread that has a dispatcher loop, the UI thread of a GUI app is a common example. If this is truly possible and you actually use a Semaphore then you'll get to deal with the consequence as well, your code will deadlock. Since it recursed into BeginProcess and stalls on the semaphore. Thus never completing and never able to call EndProcess(). There's a good reason why Monitor and Mutex are re-entrant :) A: You can use Semaphore class which came with .NET Framework 2.0. A good usage of Semaphores is to synchronize limited amount of resources. In your case it seems you have resources like Context which you want to share between consumers. You can create a semaphore to manage the resources like: var resourceManager = new Semaphore(0, 10); And then wait for a resource to be available in the BeginProcess method using: resourceManager.WaitOne(); And finally free the resource in the EndProcess method using: resourceManager.Release(); Here's a good blog about using Semaphores in a situation like yours: https://web.archive.org/web/20121207180440/http://www.dijksterhuis.org/using-semaphores-in-c/ A: There is very simple way to prevent re-entrancy (on one thread): private bool bRefresh = false; private void Refresh() { if (bRefresh) return; bRefresh = true; try { // do something here } finally { bRefresh = false; } } A: The Interlocked class can be used for a thread-safe solution that exits the method, instead of blocking when a re-entrant call is made. Like Vlad Gonchar solution, but thread-safe. private int refreshCount = 0; private void Refresh() { if (Interlocked.Increment(ref refreshCount) != 1) return; try { // do something here } finally { Interlocked.Decrement(ref refreshCount); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19016595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: laravel image validation image intervention I have a file upload in my vue js component which sends base64 in server methods: { onFileChange(e) { console.log(e.target.files[0]); let fileReader = new FileReader(); fileReader.readAsDataURL(e.target.files[0]); fileReader.onload = (e) => { this.product.cover_image = e.target.result }; }, <div class="form-group"> <label for="exampleInputFile">Upload Image of Product</label> <input type="file" ref="fileupload" v-on:change="onFileChange" id="exampleInputFile"> </div> and in my controller in laravel im using image intervention to save the image via Image::make public function store(Request $request){ $this->validate($request, [ 'name' => 'required|max:255', 'price' => 'required|numeric', ]); $image = $request->get('cover_image'); $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1]; Image::make($request->get('cover_image'))->save(public_path('cover_images/').$name); $product = new Product; $product->name = $request->input('name'); $product->description = $request->input('description'); $product->price = $request->input('price'); $product->cover_image = $name; if($product->save()) { return new ProductsResource($product); } } how can i validate the image before saving? it is in base64 i dont know how to validate it on laravel. A: Inside the AppServiceProvider i put the custom validation public function boot() { Validator::extend('image64', function ($attribute, $value, $parameters, $validator) { $type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1]; if (in_array($type, $parameters)) { return true; } return false; }); Validator::replacer('image64', function($message, $attribute, $rule, $parameters) { return str_replace(':values',join(",",$parameters),$message); }); } and on the validation.php i put the 'image64' => 'The :attribute must be a file of type: :values.', now i can use this in validating the request 'image' => 'required|image64:jpeg,jpg,png' credits to https://medium.com/@jagadeshanh/image-upload-and-validation-using-laravel-and-vuejs-e71e0f094fbb A: If you only want to validate uploaded file to be an image type: $this->validate($request, [ 'name' => 'required|max:255', 'price' => 'required|numeric', 'cover_image' => 'required|image' ]); The file under validation must be an image (jpeg, png, bmp, gif, or svg) Laravel 5.6 image validation rule
{ "language": "en", "url": "https://stackoverflow.com/questions/51758398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating a unique random non-key value in Entity Framework/SQL I have a booking application where a customer will create a reservation. I do not want them to have to create an account and log in, so they will modify/view their reservation using a Confirmation code (like the airlines use) and the last 4 of their credit card (again, like airlines). My reservation class already has a primary key, a GUID, however, I do not want to give that to the customer, I want something nicer to look at like a 6-8 digit alpha code. I am using Entity Framework and C#/ASP.NET Core, and while I COULD generate the value in my code, check with the DB (MSSQL) that the value has not been used, and then persist if it is unique, I would rather have a single operation if I could. Is the accepted way of doing something like this to have the database generate the value or is there a more EF way of doing it? A: Like a two-factor (TOTP) code, but based on your GUID instead of a timestamp? // userData should be populated with whatever immutable user data you want // applicationSecret should be a constant public string ComputeCode(byte[] userData, byte[] applicationSecret, int length) { using var hashAlgorithm = new HMACSHA256(applicationSecret); var hash = hashAlgorithm.ComputeHash(userData); return BitConverter.ToString(hash).Replace("-", "").Substring(0, length); } A: I can't speak to the EF-related aspects of your question, but I recently had to figure out a way to generate unique, user-friendly IDs for a personal project. What I eventually settled on was the following: * *Start with a 32-bit integer. (In my case it was an incrementing database ID.) *"Encrypt" the integer using RC5 with a block size of 32 bits. This scrambles the key space. You'll probably have to write your own RC5 implementation, but it's a simple algorithm. (Mine was <100 lines of python.) *Encode the resulting 4 bytes in Base32. I recommend z-base-32 for the most user-friendly alphabet. You might have to write your own Base32 implementation, but again, it's quite simple. This algorithm produces a reversible mapping similar to the following: 1 <-> "4zm5cna" 2 <-> "5ytgepe" 3 <-> "e94rs4e" etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/71245565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening PDF on React Native I tried to open a pdf file using react-native-pdf-view my code is : export default class PDFExample extends Component { constructor(props) { super(props); } render(){ return( <PDFView ref={(pdf)=>{this.pdfView = pdf;}} src={"./Tizi.pdf"} onLoadComplete = {(pageCount)=>{ this.pdfView.setNativeProps({ zoom: 1.5 }); }} style={styles.pdf}/> ) } } and i got this error : Invariant Violation: Native component for "RNPDFView" does not exist A: The issue is that you did not link the library. The steps are usually the following: 1) npm install THE_PACKAGE --save 2) react-native THE_PACKAGE If the package does not contain any issues it will be linked, otherwise you need to link it manually, or switch to another solution, for example, https://www.npmjs.com/package/react-native-view-pdf. There you can also find a readme which describes the steps need to be done. It's generic, so you can apply for any package.
{ "language": "en", "url": "https://stackoverflow.com/questions/52303207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google LineChart Html tag with html tooltip I'm using google line charts in my project and I've got a bit of a problem with customizing tooltips. Fiddle with this problem : http://jsfiddle.net/nq7sk6mq/7/ I want to use HTML tooltips and my chart settings are: if google google.load "visualization", "1.0", packages: ["corechart"] callback: -> data = new google.visualization.DataTable() data.addColumn('number', ' v1') data.addColumn('number', 'v2') data.addColumn({type:'boolean',role:'certainty'}) data.addColumn('number', 'v3') data.addColumn({type:'boolean',role:'certainty'}) data.addColumn('number', 'v4') data.addColumn({type:'boolean',role:'certainty'}) data.addColumn({type: 'string', role: 'tooltip','p':{'html': 'true'}}) My data for it: values.push [ iterator, values2[iterator], true, values3[iterator], true, values4[iterator], false, customTooltip()] Options: options = { legend:{position:"top"}, vAxes: { 0: {}, }, hAxis: { ticks: data.getDistinctValues(0) }, series:{ 0: {pointSize: 5, color: "#0f8d4c"}, 1: {pointSize: 5, color: "#b74848"}, 2: {color: "#00a259", pointSize: 4} }, width : width, tooltip: {isHtml: true} } call the draw: google.setOnLoadCallback(drawChart(values,chartid,options)) drawChart: (data, chartid,options) -> chart = new google.visualization.LineChart(document.getElementById(chartid)); chart.draw(data,options) customTooltip: customTooltip: () -> return '<div style="padding:5px 5px 5px 5px; height:20px;">' + "<p>Teeest</p>"+ '</div>' And I get in Chrome: <div> <undefined class="google-visualization-tooltip" style="width: 66px; height: 20px; left: 181.5px; top: 133.5px;"> <div style="padding:5px 5px 5px 5px; height:20px;"> <p>Teeest</p> </div> </undefined> </div> Charts are displayed correctly and, if using normal tooltips, they also works correctly. So my question is why do I get this undefined tag which is destroying the tooltip layout? I found that not only I am the person who encountered this problem.http://code.google.com/p/google-visualization-api-issues/issues/detail?id=1290 A: According to @juvian help The problem was that styling was set inline on div cointainer and it seems that tooltips inherited it from div. So the answer is to remove the styling from div container and apply it to the desired element.
{ "language": "en", "url": "https://stackoverflow.com/questions/25660665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mocking AOP method implementation for unit tests I've a java application which has multiple modules - (GWT-)RPC services, perf-library, remote-client (All java code written/owned by my team). The perf-library contains Spring AOP aspects related code and it's primarily used to push intercepted method logs to a data store. Now, perf-library is dependent on another remote-client which actually maintains a queue and handles the job of pushing logs to the data store. So, in a way, perf-library just delegates the task to remote-client. The business logic code calls intercepted methods which have AOP logic and hence there is a dependency on remote-client. Obviously, I don't want to connect to the remote-client from within unit tests. I think I need to mock the implementation of method push() which connects to remote-client. What I'm unable to figure out is how to use the mock implementation for the business logic code package unit tests. To clarify things, I've modules like this - * *RPC service module - e.g. method login() is intercepted. *perf-library - Has aspects (to intercept methods like login()) and implementation to call remote-client *remote-client - Push data to some data-store Now, for writing the unit tests for RPC service methods, how do I get the mock implementation of push() as it is internal to perf-library. Let's say, I've an interface LogClient (having method push()) which is implemented by two classes (one for production and another for test). I can use this Test implementation for unit tests of perf-library itself, but how do I make the RPC unit tests use it. I'm new to Spring, so not sure if this can be done easily with Spring or anything else. Any help will be nice. Note: We're using Spring for maintaining beans and DI. A: Not sure exactly how but Mockito can be a good choice. Check this link for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/12385042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular Nested mat-menu expansion mat-menu gracefully handles expansion when opening near the bottom of a page (if too close to bottom of page, it will open up) but what if there is an expandable button within the mat-menu. Expansion will always open downwards and off the screen. A workaround seems to be to programmatically scroll screen by 1 pixel. This allows the mat-menu to recalculate its position and pop up to a viewable area, but it is quite a hack and not performant on IE browser. Is there a more elegant solution? Sample: <mat-menu #menu="matMenu" xPosition="before"(closed)="onMenuClosed()"> <ng-template matMenuContent> <div #popoverMenu> <button mat-menu-item class="primary-action" [ngClass]="{'expanded-section': isPanelExpanded }" (click)="expandMenuOptions($event)"> . . .
{ "language": "en", "url": "https://stackoverflow.com/questions/52878275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java delete single file from GridFS Is there a way to delete a single file without the objedId in GridFS? I just found this on MongoDB: objectId fileId; //ObjectId of a file uploaded to GridFS gridFSBucket.delete(fileId); But I don't know how to query all the objectId's to do this. Thanks in advance for your help. A: I got the solution: GridFSFindIterable gridFSFile = gridFSBucket.find(eq("filename",listOfFiles.get(i).getName())); // listOfFiles are a list which contains the names gridFSBucket.delete(gridFSFile.cursor().next().getId()); I hope it is helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/67257131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combine two different device capture frame into one frame and write a video I'm beginner in opencv but well versed in C#/C++. I have created a openCV console app to capture and write frames data to videos from multiple devices or RTSP streams which is working fine. I require to merge the output of two separate devices frames into one frame and write to video have done this in the snippet below but the video file generated is corrupted. The video capture and video writer are set to grab at 1920 x 1080 resolution. for (int i = 0; i < devices; i++) { Mat frame; Mat f1, f2; //Grab frame from camera capture if (videoCapturePool[i].grab()) { videoCapturePool[i].retrieve(f1); f2 = f1.clone(); if (isPause) { circle(f1, Point(f1.size().width / 2, f1.size().height / 2), 10, (255, 255, 10), -1); circle(f2, Point(f2.size().width / 2, f2.size().height / 2), 10, (255, 255, 10), -1); } hconcat(f1, f2, frame); imshow("Output", frame); waitKey(10); frameData[i].camerFrames.push_back(frame); } f1.release(); f2.release(); } for (int i = 0; i < devices; i++) { int32_t frame_width(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_WIDTH))); int32_t frame_height(static_cast < int32_t > (videoCapturePool[i].get(CV_CAP_PROP_FRAME_HEIGHT))); VideoWriter vidwriter = VideoWriter(videoFilePaths[i], CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(frame_width, frame_height), true); videoWriterPool.push_back(vidwriter); writer << frameData[i].camerFrames.size() << endl; for (size_t j = 0; j < frameData[i].camerFrames.size(); j++) { //write the frame videoWriterPool[i].write(frameData[i].camerFrames[j]); } frameData[i].camerFrames.clear(); } A: Your approach must be generally refactored. I don't say about code - just about architecture. It has a big problem with memory - let's calculate! * *The size of the one RGB frame 1920x1080: frame_size = 1920 * 1080 * 3 = 6 Mb *How many frames do you want capture from 2 cameras? For example 1 minute of video with 30 fps: video_size = 2 camera * 6 Mb/frame * 60 seconds = 21 Gb! Do you have so memory per process? I advice to make queues in different threads for capture frames and 2 threads for pick up frames from capture queues and write it to files.
{ "language": "en", "url": "https://stackoverflow.com/questions/55137443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: supoprtedInterfaceOrientation caled every time a rotation occurs supportedInterfaceOrientation should be called only once when viewDidLoad, but in my case it is called every time the simulator rotates. I need only two orientations potrait and portrait upside down. when i rotate to upside down the supported interface orientation is called 4 times and my view becomes upside down. on rotation to landscape it is called only once(but it shouldn't ?). Any solution ? PS: I am not using any Navigation controller so setting rotation equal to top view controller wont matter. And in my pList only 2 orientations are supported Also I have a main View Controller in which I add subviews and I have set the supported interface orientation in my view controller. Weird thing is 3 view controllers that are before(presented before) the faulty one, they rotate just fine. A: You can check the interfaceOrientation in viewDidLoad. You can get the interfaceOrientation with self.userInterFaceOrientation. Maybe it would be better to check the interfaceOrientation in viewWillAppear. The difference is, that viewDidLoad will only called one and viewWillAppear every time you enter that view. A: Its so Simple you just click on your Project -> Summary -> Supported Interface Orientations. You can click the Interface Orientations as your requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/14435651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML div with img in it displaying strangely On the website I'm working on (this), I have a div with an img in it. This is the html <div><overlay> <img class="img1" height="225" src="NYC/wtc1.JPG" width="225" /></overlay</div> <div><overlay> <img class="img2" height="225" src="NYC/wtcmem.jpg" width="225" /></overlay></div> <div><overlay> <img class="img3" height="225" src="NYC/sky.jpg" width="225" /></overlay></div> <p>&nbsp;</p> nothing too complicated. This is the CSS for the classes img1, img2, and img3. .img1 { position:absolute; left:12%; } .img2 { display:block; margin:auto; } .img3 { position:absolute; right:12%; } also pretty simple. But, if you look at the website, the 3rd image (at least for me on Safari) is much lower than the other two. Why would this happen? I don't see anything in the CSS or HTML that would cause this. A: I've tried to do the best I can with your code, the following will work for you: <div class="container" style="overflow:hidden; text-align:center;"> <div style="display:inline-block; margin: 0px 80px;"> <div class="overlay"> <img class="img1" height="225" src="NYC/wtc1.JPG" width="225"> </div> </div> <div style="display:inline-block; margin: 0px 80px;"> <div class="overlay"> <img class="img2" height="225" src="NYC/wtcmem.jpg" width="225"> </div> </div> <div style="display:inline-block; margin: 0px 80px;"> <div class="overlay"> <img class="img3" height="225" src="NYC/sky.jpg" width="225"> </div> </div> </div> Note that <overlay> is not a valid HTML element. also I've seen on the page you used something like <margin>. It's not a good practice to invent HTML elements.. You can get all the functionality you need using regular <div>s (although I don't think this will break your page.. maybe only in older browsers..). What I basically did: * *Wrapped the three <div>s with a container with text-align:center. This will make the three divs inside it aligned to the center. *Added display:inline-block; to make all the divs follow the text-align. *Added margins to the divs to space them Note that I strongly recommend to replace your <overlay> with something like <div class="overlay"> A: If you have some markup like this: <div class="wrapper"> <div><img class="img1" height="225" src="http://rwzimage.com/albums/NYC/wtc1.JPG" width="225" /></div> <div><img class="img2" height="225" src="http://rwzimage.com/albums/NYC/wtcmem.jpg" width="225" /></div> <div><img class="img3" height="225" src="http://rwzimage.com/albums/NYC/sky.jpg" width="225" /></div> </div> Then I think this CSS will have approximately the effect you're after: .wrapper { display: table; width: 960px; } .wrapper > div { display: table-cell; width: 33%; text-align: center; } .wrapper > div:hover img { opacity: 0.5; } Demo. I set width: 960px; so that it would force things to be wider than the JSFiddle window, but you could set width: 100%; for your page. A: div tag naturally stack vertically. So you will need to add an id to each div or you could just put all the img in one div. The block css attribute is effecting the layout. It is pushing the next img to the next line.
{ "language": "en", "url": "https://stackoverflow.com/questions/17625960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inflating class org.osmdroid.views.MapView cause crash I use eclipse as IDE to write a simple test program that put some TextView and Button on the screen and works fine. Then, I do... (1) set compiler compliance level to 15 (2) set ANDROID_SDK_PLATFORM to C:/ADT/sdk/platforms/android-15 (3)add these as external JARs osmdroid-android-4.2.jar slf4j-android-1.7.7.jar AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.test.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> fragment_main.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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.test.MainActivity$PlaceholderFragment" > <Button android:id="@+id/bt_test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/bt_test" android:text="@string/hello_world" android:textSize="24sp" /> <org.osmdroid.views.MapView android:id="@+id/mapview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> MainActivity.java package com.example.test; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import org.osmdroid.views.MapView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.fragment_main, container, false); // return rootView; getActivity().setContentView(R.layout.fragment_main); return null; } } } compilation ok, apk installation ok, but app crash... (I use a real phone with android 4.2.2 as debug device.) Here comes the log: 06-06 23:03:06.007: D/jdwp(18476): sendBufferedRequest : len=0x3B 06-06 23:03:06.013: D/dalvikvm(18476): open_cached_dex_file : /data/app/com.example.test-1.apk /data/dalvik- cache/data@[email protected]@classes.dex 06-06 23:03:06.027: D/skia(18476): Flag is not 10 06-06 23:03:06.029: D/skia(18476): Flag is not 10 06-06 23:03:06.032: W/IconCustomizer(18476): can't load transform_config.xml 06-06 23:03:06.035: D/skia(18476): Flag is not 10 06-06 23:03:06.040: D/skia(18476): Flag is not 10 06-06 23:03:06.043: D/skia(18476): Flag is not 10 06-06 23:03:06.058: D/skia(18476): Flag is not 10 06-06 23:03:06.060: D/skia(18476): Flag is not 10 06-06 23:03:06.066: D/skia(18476): Flag is not 10 06-06 23:03:06.067: D/skia(18476): Flag is not 10 06-06 23:03:06.069: D/skia(18476): Flag is not 10 06-06 23:03:06.071: D/skia(18476): Flag is not 10 06-06 23:03:06.072: D/skia(18476): Flag is not 10 06-06 23:03:06.077: V/Provider/Settings(18476): invalidate [secure]: current 7 != cached 0 06-06 23:03:06.080: V/Provider/Settings(18476): from db cache, name = access_control_lock_enabled , value = null 06-06 23:03:06.111: D/libEGL(18476): loaded /vendor/lib/egl/libEGL_mtk.so 06-06 23:03:06.114: D/libEGL(18476): loaded /vendor/lib/egl/libGLESv1_CM_mtk.so 06-06 23:03:06.117: D/libEGL(18476): loaded /vendor/lib/egl/libGLESv2_mtk.so 06-06 23:03:06.252: D/OpenGLRenderer(18476): Enabling debug mode 0 06-06 23:03:06.253: V/InputMethodManager(18476): onWindowFocus: null softInputMode=288 first=true flags=#9810100 06-06 23:03:06.254: V/InputMethodManager(18476): START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{4221c418 V.E..... R.....ID 0,0-720,1280} ic=null tba=android.view.inputmethod.EditorInfo@42289610 controlFlags=#104 06-06 23:03:06.256: V/InputMethodManager(18476): Starting input: Bind result=InputBindResult{null com.cootek.smartinputv5/.TouchPalIME #4739} 06-06 23:03:06.265: D/skia(18476): Flag is not 10 06-06 23:03:08.041: I/SurfaceTextureClient(18476): [STC::queueBuffer] (this:0x5c2c73f8) fps:0.57, dur:1745.04, max:1745.04, min:1745.04 06-06 23:03:08.627: D/OpenGLRenderer(18476): Flushing caches (mode 0) 06-06 23:03:08.845: D/OpenGLRenderer(18476): Flushing caches (mode 1) 06-06 23:03:08.849: D/OpenGLRenderer(18476): Flushing caches (mode 0) 06-06 23:03:45.893: D/jdwp(18569): sendBufferedRequest : len=0x3B 06-06 23:03:45.899: D/dalvikvm(18569): open_cached_dex_file : /data/app/com.example.test-2.apk /data/dalvik- cache/data@[email protected]@classes.dex 06-06 23:03:45.911: D/skia(18569): Flag is not 10 06-06 23:03:45.914: D/skia(18569): Flag is not 10 06-06 23:03:45.918: W/IconCustomizer(18569): can't load transform_config.xml 06-06 23:03:45.921: D/skia(18569): Flag is not 10 06-06 23:03:45.925: D/skia(18569): Flag is not 10 06-06 23:03:45.929: D/skia(18569): Flag is not 10 06-06 23:03:45.942: D/skia(18569): Flag is not 10 06-06 23:03:45.944: D/skia(18569): Flag is not 10 06-06 23:03:45.950: D/skia(18569): Flag is not 10 06-06 23:03:45.952: D/skia(18569): Flag is not 10 06-06 23:03:45.953: D/skia(18569): Flag is not 10 06-06 23:03:45.955: D/skia(18569): Flag is not 10 06-06 23:03:45.956: D/skia(18569): Flag is not 10 06-06 23:03:45.961: D/AndroidRuntime(18569): Shutting down VM 06-06 23:03:45.961: W/dalvikvm(18569): threadid=1: thread exiting with uncaught exception (group=0x419d59a8) 06-06 23:03:45.964: E/AndroidRuntime(18569): FATAL EXCEPTION: main 06-06 23:03:45.964: E/AndroidRuntime(18569): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.view.InflateException: Binary XML file line #24: Error inflating class org.osmdroid.views.MapView 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread.performLaunchActivity( ActivityThread.java:2333) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread.handleLaunchActivity( ActivityThread.java:2385) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread.access$600(ActivityThread.java:157) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread$H.handleMessage( ActivityThread.java:1341) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.os.Handler.dispatchMessage(Handler.java:99) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.os.Looper.loop(Looper.java:153) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread.main(ActivityThread.java:5322) 06-06 23:03:45.964: E/AndroidRuntime(18569): at java.lang.reflect.Method.invokeNative(Native Method) 06-06 23:03:45.964: E/AndroidRuntime(18569): at java.lang.reflect.Method.invoke(Method.java:511) 06-06 23:03:45.964: E/AndroidRuntime(18569): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:848) 06-06 23:03:45.964: E/AndroidRuntime(18569): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615) 06-06 23:03:45.964: E/AndroidRuntime(18569): at dalvik.system.NativeStart.main(Native Method) 06-06 23:03:45.964: E/AndroidRuntime(18569): Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class org.osmdroid.views.MapView 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:768) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.rInflate(LayoutInflater.java:816) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.inflate(LayoutInflater.java:559) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.inflate(LayoutInflater.java:466) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.inflate(LayoutInflater.java:419) 06-06 23:03:45.964: E/AndroidRuntime(18569): at com.android.internal.policy.impl.PhoneWindow.setContentView (PhoneWindow.java:354) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.Activity.setContentView(Activity.java:1981) 06-06 23:03:45.964: E/AndroidRuntime(18569): at com.example.test.MainActivity$PlaceholderFragment.onCreateView (MainActivity.java:63) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.Fragment.performCreateView(Fragment.java:1695) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.FragmentManagerImpl.moveToState (FragmentManager.java:885) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.FragmentManagerImpl.moveToState (FragmentManager.java:1057) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.BackStackRecord.run(BackStackRecord.java:694) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.FragmentManagerImpl.execPendingActions (FragmentManager.java:1435) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.Activity.performStart(Activity.java:5233) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2306) 06-06 23:03:45.964: E/AndroidRuntime(18569): ... 11 more 06-06 23:03:45.964: E/AndroidRuntime(18569): Caused by: java.lang.ClassNotFoundException: Didn't find class "org.osmdroid.views.MapView" on path: DexPathList[[zip file "/data/app/com.example.test-2.apk"],nativeLibraryDirectories= [/data/app-lib/com.example.test-2, /vendor/lib, /system/lib]] 06-06 23:03:45.964: E/AndroidRuntime(18569): at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:53) 06-06 23:03:45.964: E/AndroidRuntime(18569): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 06-06 23:03:45.964: E/AndroidRuntime(18569): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.createView(LayoutInflater.java:622) 06-06 23:03:45.964: E/AndroidRuntime(18569): at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:757) 06-06 23:03:45.964: E/AndroidRuntime(18569): ... 25 more 06-06 23:03:48.547: I/Process(18569): Sending signal. PID: 18569 SIG: 9 A: I solve it. Add osmdroid-android-4.2.jar, osmdroid-third-party-4.2.jar, slf4j-android-1.7.7.jar and slf4j-api-1.7.7 as external JARs. And put all four files into the libs directory of the "test" project.
{ "language": "en", "url": "https://stackoverflow.com/questions/24084459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: segmentation fault using pointers on array of strings hi there i have this test code written that produces a segmentation fault on third iteration of while... using a debugger i saw the value of tokens[count] and it is correct but in the last iteration there is a segmentation fault, str_split divide the string using ; as divisor(it works) anybody can help? sportello[0].elenco_ris[0]=strdup("string;of;test"); tokens=str_split(sportello[0].elenco_ris[0],';'); int p=0; int count=0; int lungh=strlen(""); while(p!=-1){ lungh=strlen(tokens[count]); if(lungh!=0){ printf("\nprinto: %s",tokens[count]); count++; } else p=-1; } print: string print: of RUN FINISHED; Segmentation fault; real time: 0ms; user: 0ms; system: 0ms A: ok i solved..the problem was what i thought...thaks to a comment by @Joachim Pileborg i've tried with this (NULL)... so thanks to you all `int p=0; int count=0; while(p!=-1){ if (tokens[count] != NULL){ printf("\nprinto: %s",tokens[count]); count++; } else p=-1; }` A: the segmentation fault occures when the process execute strlen(tokens[count]) inside the IF at the last iteration..the return value would be 0(no string?) but instead seg fault... probably in that location there isn't a string so this occures...how can i solve the problem? anyway this is str_split,it is the same(more or less) posted on this site somewhere,it works char** str_split(char* a_str, char a_delim) { char** result = 0; size_t count = 0; char* tmp = a_str; char* last_comma = 0; char delim[2]; delim[0] = a_delim; delim[1] = 0; /* Count how many elements will be extracted. */ while (*tmp) { if (a_delim == *tmp) { count++; last_comma = tmp; } tmp++; } /* Add space for trailing token. */ count += last_comma < (a_str + strlen(a_str) - 1); /* Add space for terminating null string so caller knows where the list of returned strings ends. */ count++; result = malloc(sizeof (char*) * count); if (result) { size_t idx = 0; char* token = strtok(a_str, delim); while (token) { assert(idx < count); *(result + idx++) = strdup(token); token = strtok(0, delim); } assert(idx == count - 1); *(result + idx) = 0; } return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27928166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Make VSCode apply syntax highlighting to .tsx files Trying to start a gatsby+react+typescript project and VSCode will only apply syntax highlighting to the HTML in my .tsx files. The typescript code remains a single color. How do I fix this? Note: I have no plugins installed at the moment and the highlighting works if the file type is set to .jsx A: Clicking on the language button in the lower right corner and selecting typescript react fixed the problem. A: I faced same problem, even "Typescript React" was selected as the language. I had to click and select the language pack version before getting syntax highlighting working. A: In my case "JavaScript and TypeScript Nightly" extension was causing the problem. I had the same problem even when "Typescript React" was selected. I disabled all the extensions and problem solved. Then I enabled each extension individually and I've found out "JavaScript and TypeScript Nightly" was causing the problem. I hope this will help someone. A: I solved this issue just reloading vscode as required by JavaScript and TypeScript Nightly extension, once it was reload I just double checked that Typescript react was selected and the problem was resolved. Seems like the real problem was that the library JavaScript and TypeScript Nightly was not fully reloaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/58177640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android kotlin calling same api with different date params and inserting to room all together I have an api to return data based on from and to date params. The api is limited to return only 1 day data at a time. I need to fetch data for 7 days and insert it to room db. Fetching day by day and inserting to db is time consuming and hence causing bad user experience. * *How can I make 7 parallel calls to same api with different date params? *After making all 7 parallel api calls, how can I combine the responses and bulk insert to room db *Is there any other better way to fetch the entire data and insert to db with minimal time. My code to fetch single day data is as follows. runBlocking { val queryParams = BaseQuery( device_id = "12345", date_from = fromDate, date_to = toDate, quantity = "200" ) myDataUsecase.executeFetchDataUseCase(queryParams.asMap) .onStart { // DO Something when this starts } .catch { exception -> // Catch any exception here and log it } .collect { baseResult -> parseBaseResult(baseResult) } } How can I achieve my requirement in an efficient way? Any suggestions are appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/72704775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check mulitple data in rows using javascript? I have check calculation in rows of data. Here is my row format. When I have select first row of "Purchase Document". It will automaticaly fill the value in its row fields. As per shown in image. Now In second row, when I select "Purchase Document" with same value then, I need to calculate of LPO AMT (Total Amount), Pending Amout & Amount. Means if there Amount fill with 1000 then in second row it will not be more then 23500 (Pending Amount). Here my code : function doLPOamt(val) { var req = Inint_AJAX(); req.onreadystatechange = function () { if (req.readyState==4) { if (req.status==200) { document.getElementById('LPO_AMT').value=""; document.getElementById('LPO_AMT').value=req.responseText; //retuen value } } }; req.open("GET", "lpoamnt.php?val="+val); //make connection req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header req.send(null); //send value } function doPendingamt(val) { var req = Inint_AJAX(); req.onreadystatechange = function () { if (req.readyState==4) { if (req.status==200) { document.getElementById('PENDING_AMT').value=""; document.getElementById('PENDING_AMT').value=req.responseText; //retuen value } } }; req.open("GET", "pendingamnt.php?val="+val); //make connection req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header req.send(null); //send value } I hope you understand well Thank you in advance A: I have solved this problem. I have just modify the code and get sollution Here is my modified function function doPendingamt(val,cnt) { var req = Inint_AJAX(); req.onreadystatechange = function () { if (req.readyState==4) { if (req.status==200) { //document.getElementById('PENDING_AMT').value=""; //document.getElementById('PENDING_AMT').value=req.responseText; //retuen value $('input[name=PENDING_AMT['+cnt+']]').val(); $('input[name=PENDING_AMT['+cnt+']]').val(req.responseText); var elements = document.getElementsByClassName('purshasedocscss'); var totalAmt = 0; var pendingAmt = 0; var greater = 0; for(var x=0; x < elements.length; x++){ if(val == elements[x].value && elements[x].value != -1){ if(pendingAmtTmp > pendingAmt) { pendingAmt = pendingAmtTmp; } greater++; } } if(greater > 1) { for(var y=0; y < elements.length; y++){ if(val == elements[y].value && $('input[name=AMOUNT['+y+']]').val() != ''){ var amount = $('input[name=AMOUNT['+y+']]').val(); totalAmt = parseFloat(amount) + parseFloat(totalAmt); } } var amt = pendingAmt - totalAmt; $('input[name=PENDING_AMT['+cnt+']]').val(amt); } } } }; req.open("GET", "pendingamnt.php?val="+val); //make connection req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header req.send(null); //send value } Thank you who have give time for this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/22835898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Radio Button change event not working in chrome or safari I've got some radio buttons on a page and when Yes is selected, some other controls (dropdowns and textboxes) become visible. If No is selected, they become invisible again. This is working fine in FF & IE. It does work when I use the mouse with chrome, but when I'm tabbing through the page, the controls never become visible. It's as if the change event doesn't trigger because I'm tabbing. Any ideas of what might be causing this, or how I'd go about fixing it? The show/hide functionality is being done with JQuery. Edit: Showing the code that is giving problems. $("#rbtnControlYes").change(function () { $("#otherControls").show(); }); A: Found the answer to this. Instead of using the .change event, I switched it to .click and everything worked fine. Hope this helps someone. Slap A: For those not using JQuery, the onClick event is what you want. It appears that onClick has the behavior of what we intuitively call "select". That is, onClick will capture both click events and tab events that select a radio button. onClick on Chrome onClick has this behavior across all browsers (I've tested with IE 7-9, FF 3.6, Chrome 10, & Safari 5).
{ "language": "en", "url": "https://stackoverflow.com/questions/5090560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular 6 HttpClient set param date only if its not null I am trying to pass parameter to URL. For which I am using Angular HttpParams. How do I set date param only if date is not null or undefined? Code: let params = new HttpParams() .set('Id', Id) .set('name', name) if (startDate !== null) { params.set('startDate', startDate.toDateString()); } if (endDate !== null) { params.set('endDate', endDate.toDateString()); } A: set does not mutate the object on which it is working - it returns a new object with the new value set. You can use something like this: let params = new HttpParams() .set('Id', Id) .set('name', name) if (startDate != null) { params = params.set('startDate', startDate.toDateString()); } if (endDate != null) { params = params.set('endDate', endDate.toDateString()); } Note how the params object is being reassigned. Also note the use of != to protect against both null and undefined. A: Instead of using the HttpParams object you can define and mutate your own object and pass it within the http call. let requestData = { Id: Id, name: name } if (startDate) { //I am assuming you are using typescript and using dot notation will throw errors //unless you default the values requestData['startDate'] = startDate } if (endDate) { requestData['endDate'] = endDate } //Making the assumption this is a GET request this.httpClientVariableDefinedInConstructor.get('someEndpointUrl', { params: requestData })
{ "language": "en", "url": "https://stackoverflow.com/questions/52407951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Rails getting validation failed error, but no errors in ActiveRecord error model I am having a problem with validation errors when saving a model using save!. The ActiveRecord error model error messages are blank, so i dont know what errors are happening on a validation attempt. When I try errors.full_messages or errors.each_full according to the documentation, it should display the errors, which it doesn't. The model I am trying to save is the Orders model (ecommerce site using Spree). When an item in the order gets deleted, update_totals! gets called which recalculates the totals, and then save! is called, which triggers the validation error (this error happens very rarely but only when I'm logged in, and I havent been able to find the cause of it). The order model has two validations in its model: validates_numericality_of :item_total validates_numericality_of :total i recorded order.item_total.inspect, order.total.inspect, and order.errors.full_messages.inspect and got this: Wed Jan 25 08:53:08 -0800 2012order item total: #<BigDecimal:15780c60,'0.279E2',8(16)> Wed Jan 25 08:53:08 -0800 2012order total: #<BigDecimal:152bf410,'0.2448225E2',12(20)> Wed Jan 25 08:53:08 -0800 2012: ERRORS SAVING ORDER: Wed Jan 25 08:53:08 -0800 2012[] item_total and total are stored in the mySQL database as decimal(8,2). The last line is order.errors.full_messages.inspect, which is an empty array. The validation error looks like this: ActiveRecord::RecordInvalid (Validation failed: {{errors}}): vendor/extensions/mgx_core/app/models/order.rb:382:in `update_totals!' vendor/extensions/mgx_core/app/controllers/line_items_controller.rb:7:in `destroy' app/middleware/flash_session_cookie_middleware.rb:19:in `call' C:\Users\mgx\My Documents\Aptana Studio 3 Workspace\catalogue-spree\script\server:3 c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_load' c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_program' c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/bin/rdebug-ide:87 c:/Ruby187/bin/rdebug-ide:19:in `load' c:/Ruby187/bin/rdebug-ide:19 I guess my question is twofold: 1. Why is my activerecord errors model not saying what the validation error is? 2. How do I fix this problem? Is my item_total and total valid for saving as decimal(8,2)? I am using rails 2.3.5 and spree 0.10.2 A: When you have before_validation declarations and if they return false then you'll get a Validation failed (ActiveRecord::RecordInvalid) message with an empty error message (if there are no other errors). Note that before_validation callbacks must not return false (nil is okay) and this can happen by accident, e.g., if you are assigning false to a boolean attribute in the last line inside that callback method. Explicitly write return true in your callback methods to make this work (or just true at the end if your callback is a block (as noted by Jesse Wolgamott in the comments)). UPDATE: This will no longer be an issue starting Rails 5.0, as return false will no longer halt the callback chain (throw :abort will now halt the callback chain). UPDATE: You might also receive ActiveRecord::RecordNotSaved: Failed to save the record if a callback returns false. A: I think the problem lies in the controller code. The order variable is set before the line item is destroyed, and is not aware it's been destroyed afterwards. This code should really be in the model: # line_item.rb after_destroy :update_totals! delegate :update_totals, :to=> :order And the controller should just destroy the line item. A: Regarding 1. Why is my activerecord errors model not saying what the validation error is?, see if you have the gem i18n installed. If you do, try uninstalling or an earlier version of the gem i18n. gem uninstall i18n A: It looks to me like you are using Ruby 1.8.7. Have you tried running your app using Ruby 1.9.3? A: When you create other register in a before_validation method, if it fails, the error will be thrown by the 'father' class, so it won't show error, just <ActiveRecord::RecordInvalid: Validation failed: > I noticed that when I got an error in my 'child' record using byebug inside before validation method A: Throwing a reply in here as it took a bit for us to track this down. We were upgrading to Rails 5.2 and suddenly started getting this exception. It was due to us overriding destroyed? on the model (we were soft deleting items).
{ "language": "en", "url": "https://stackoverflow.com/questions/9007093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Shrink polygon to a specific area by offsetting I have a 2D polygon that I want to shrink by a specific offset (A) to match a certain area ratio (R) of the original polygon. Is there a formula or algorithm for such a problem? I am interested in a simple solution for a triangle/quad but also a solution for complex polygons. I attached an image for explanation. The original polygon is offset by A (equal-distant for each edge). A has to be chosen so that the new polygon has a specific area. In this example it should have half the area of the initial polygon. A: Your question is very nonspecific, but here is one way to do what you are looking for, assuming I understand what you are asking. Note that this may cause an undesirable offset in position which you will have to deal with in some way. Not knowing what point you want to scale the polygon about, these solutions assume the simplest circumstances. The reason for the square root in all of these formulas is that area tends to change with the square of linear scaling, just as volume does with the cube of linear scaling. For general polygon: A = sqrt(R) for each point in polygon: point.x := point.x * A point.y := point.y * A For circle: A = sqrt(R) circle.radius := circle.radius * A For rectangle in terms of width and height: A = sqrt(R) rect.w := rect.w * A rect.h := rect.h * A
{ "language": "en", "url": "https://stackoverflow.com/questions/20230481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Fill Datatable with Variable dont work. But if i put the exact same value to a php site and request it with ajax. It works.... Why? This is in the variable "test": {"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de Naplouse"},{"HistChar_ID":"2","Vorname":"Robert","Nachname":"de Sable"},{"HistChar_ID":"7","Vorname":"Ibn","Nachname":"Dschubair"},{"HistChar_ID":"6","Vorname":"Baha ad-Din","Nachname":"ibn Schaddad"},{"HistChar_ID":"1","Vorname":"Richard","Nachname":"L\u00f6wenherz"},{"HistChar_ID":"5","Vorname":"Wilhelm","Nachname":"von Montferrat"}]} HTML: <table id="example" class="display" style="width:100%"> <thead class="thead1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </thead> <tfoot class="tfoot1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </tfoot> </table> An the following Code Wont fill the Datatable. $('#example').DataTable({ data: test, columns: [ { data: 'HistChar_ID' }, { data: 'Vorname' }, { data: 'Nachname' }, ] it throws an Error like this: DataTables warning: table id=example - Requested unknown parameter 'HistChar_ID' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 I tried so much. But if i take whats inside of "test" and put it into a php and use ajax it works just fine with this. $('#example').DataTable({ ajax: 'RESOURCES/PHP/Searchfield.php', columns: [ { data: 'HistChar_ID' }, { data: 'Vorname' }, { data: 'Nachname' }, ] PHP/Searchfield include 'connection.php'; $searchstuff = $_GET['Searchfield']; $sql = "select * FROM historischercharacter WHERE Vorname LIKE '%$searchstuff%' OR Nachname LIKE '%$searchstuff%' ORDER BY Nachname" ; $result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn)); $emparray = array(); while($row =mysqli_fetch_assoc($result)) { $emparray[] = $row; } echo json_encode(array('data'=>$emparray)); mysqli_close($conn); Can someone explain me why? Is it impossible to fill the Datatable with a variable?? I just dont get it... A: If you look at the examples in the documentation, the hard-coded array being passed into the table doesn't have the outer data property, it's just an array by itself - see https://datatables.net/examples/data_sources/js_array.html . You can see the same thing here as well: https://datatables.net/reference/option/data The requirements when defining an AJAX data source are different. As per the example at https://datatables.net/reference/option/ajax by default you must supply an object with a "data" property as per the structure you've shown us in your question. So it's simply that the requirements for each type of data source are different. Always read the documentation! Demo of how to set the data source using a variable, with your variable. Note the absence of the "data" property...instead "test" is just a plain array: var test = [{ "HistChar_ID": "4", "Vorname": "Garnier", "Nachname": "de Naplouse" }, { "HistChar_ID": "2", "Vorname": "Robert", "Nachname": "de Sable" }, { "HistChar_ID": "7", "Vorname": "Ibn", "Nachname": "Dschubair" }, { "HistChar_ID": "6", "Vorname": "Baha ad-Din", "Nachname": "ibn Schaddad" }, { "HistChar_ID": "1", "Vorname": "Richard", "Nachname": "L\u00f6wenherz" }, { "HistChar_ID": "5", "Vorname": "Wilhelm", "Nachname": "von Montferrat" }]; $('#example').DataTable({ data: test, columns: [{ data: 'HistChar_ID' }, { data: 'Vorname' }, { data: 'Nachname' }, ] }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> <table id="example" class="display" style="width:100%"> <thead class="thead1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </thead> <tfoot class="tfoot1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </tfoot> </table> A: Here is an example using a JavaScript variable which does not require you to change the data you show in your question: var test = { "data": [ { ... }, { ... }, ... ] }; In the above structure, each element in the array [ ... ] contains the data for one table row. In this case, the DataTable uses the data option to specify where that array can be found: data: test.data Here is the runnable demo: var test = { "data": [{ "HistChar_ID": "4", "Vorname": "Garnier", "Nachname": "de Naplouse" }, { "HistChar_ID": "2", "Vorname": "Robert", "Nachname": "de Sable" }, { "HistChar_ID": "7", "Vorname": "Ibn", "Nachname": "Dschubair" }, { "HistChar_ID": "6", "Vorname": "Baha ad-Din", "Nachname": "ibn Schaddad" }, { "HistChar_ID": "1", "Vorname": "Richard", "Nachname": "L\u00f6wenherz" }, { "HistChar_ID": "5", "Vorname": "Wilhelm", "Nachname": "von Montferrat" }] }; $(document).ready(function() { $('#example').DataTable({ data: test.data, columns: [ { data: 'HistChar_ID' }, { data: 'Vorname' }, { data: 'Nachname' }, ] } ); } ); <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Demo</title> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css"> <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css"> </head> <body> <div style="margin: 20px;"> <table id="example" class="display" style="width:100%"> <thead class="thead1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </thead> <tfoot class="tfoot1"> <tr> <th class="th1">HistChar_ID</th> <th class="th2">Vorname</th> <th class="th3">Nachname</th> </tr> </tfoot> </table> </div> </body> </html> JavaScript Data Sources In the above example, the data is sourced from a JavaScript variable - so at the very least you always need to tell DataTables what the name of the JS variable is, using the data option. And, you may also need to tell DataTables where the array of row data can be found in that variable. This is what we needed to do in the above example. If the JavaScript variable had been structured like this (an array, not an object containing an array)... var test = [ { ... }, { ... }, ... ]; ...then in that case, we only need to use data: test in the DataTable. Ajax Data Source For Ajax-sourced data, things are slightly different. There is no JavaScript variable - there is only a JSON response. By default, if that JSON response has the following structure (an array of objects called "data" - or an array of arrays)... { "data": [ { ... }, { ... }, ... ] } ...then you do not need to provide any additional instructions for DataTables to locate the array. It uses "data" as the default value. Otherwise if you have a different JSON structure, you need to use the Ajax dataSrc option to specify where the array is in the JSON response. For the above example, if you do not provide the dataSrc option, that is the same as providing the following: ajax: { url: "your URL here", dataSrc: "data" // this is the default value - so you do not need to provide it } This is why your Ajax version "just works" when you only provide the URL: ajax: 'RESOURCES/PHP/Searchfield.php' DataTables is using the default value of data to find the array it needs. And this is why it doesn't work when you use a JavaScript variable called test with data: test. So, for JavaScript-sourced data, there is no default value. You always have to provide the JavaScript variable name - and maybe additional info for the location of the array in the varaible. But for Ajax-sourced data, there is a default value (data) - and I believe this is only provided for backwards compatibility with older versions of DataTables.
{ "language": "en", "url": "https://stackoverflow.com/questions/72559045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a CAAnimation effect like moon rotates around the earth and rotates by itself at the same time in IOS? I know it is simple to create the effect making the moon circling around the earth in IOS. Suppose the moon is a CALayer object, just change the anchorPoint of this object to the earth then it will animate circling around the earth. But how to create the moon that rotate by itself at the same time? since the moon can only have one anchorPoint, seems I can not make this CALayer object rotate by itself anymore. What do you guys think? thanks. A: You can cause the "moon" to revolve around a point by animating it along a bezier path, and at the same time animate a rotation transform. Here is a simple example, @interface ViewController () @property (strong,nonatomic) UIButton *moon; @property (strong,nonatomic) UIBezierPath *circlePath; @end @implementation ViewController -(void)viewDidLoad { self.moon = [UIButton buttonWithType:UIButtonTypeInfoDark]; [self.moon addTarget:self action:@selector(clickedCircleButton:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.moon]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; CGRect circleRect = CGRectMake(60,100,200,200); self.circlePath = [UIBezierPath bezierPathWithOvalInRect:circleRect]; self.moon.center = CGPointMake(circleRect.origin.x + circleRect.size.width, circleRect.origin.y + circleRect.size.height/2.0); } - (void)clickedCircleButton:(UIButton *)sender { CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"position"]; orbit.path = self.circlePath.CGPath; orbit.calculationMode = kCAAnimationPaced; orbit.duration = 4.0; orbit.repeatCount = CGFLOAT_MAX; [self.moon.layer addAnimation:orbit forKey:@"circleAnimation"]; CABasicAnimation *fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; fullRotation.fromValue = 0; fullRotation.byValue = @(2.0*M_PI); fullRotation.duration = 4.0; fullRotation.repeatCount = CGFLOAT_MAX; [self.moon.layer addAnimation:fullRotation forKey:@"Rotate"]; } These particular values will cause the "moon" to keep the same face toward the center like earth's moon does. A: Use two layers. * *One is an invisible "arm" reaching from the earth to the moon. It does a rotation transform around its anchor point, which is the center of the earth. This causes the moon, out at the end of the "arm", to revolve around the earth. *The other is the moon. It is a sublayer of the "arm", sitting out at the end of the arm. If you want it to rotate independently, rotate it round its anchor point, which is its own center. (Be aware, however, that the real moon does not do this. For the real moon, the "arm" is sufficient, because the real moon rotates in sync with its own revolution around the earth - so that we see always the same face of the moon.) A: I was looking for this kind of implementation myself. I followed rdelmar answer and used this swift version: class ViewController: UIViewController { var circlePath: UIBezierPath! var moon = UIButton(frame: CGRect(x: 10, y: 10, width: 50, height: 50)) override func viewDidLoad() { super.viewDidLoad() setup() } func setup() { let circleRect = CGRect(x: 60, y: 100, width: 200, height: 200) self.circlePath = UIBezierPath(ovalIn: circleRect) self.moon.center = CGPoint(x: circleRect.origin.x + circleRect.size.width, y: circleRect.origin.y + circleRect.size.height/2.0) self.moon.addTarget(self, action: #selector(didTap), for: .touchUpInside) moon.backgroundColor = .blue self.view.addSubview(moon) } @objc func didTap() { let orbit = CAKeyframeAnimation(keyPath: "position") orbit.path = self.circlePath.cgPath orbit.calculationMode = .paced orbit.duration = 4.0 orbit.repeatCount = Float(CGFloat.greatestFiniteMagnitude) moon.layer.add(orbit, forKey: "circleAnimation") let fullRotation = CABasicAnimation(keyPath: "transform.rotation.z") fullRotation.fromValue = 0 fullRotation.byValue = CGFloat.pi*2 fullRotation.duration = 4 fullRotation.repeatCount = Float(CGFloat.greatestFiniteMagnitude) moon.layer.add(orbit, forKey: "Rotate") } }
{ "language": "en", "url": "https://stackoverflow.com/questions/28399892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given this is my codes can anyone tell me what is wrong? $result ="SELECT * FROM report" ; if(mysqli_query($cons, $result)) { echo(" <div class='sc'> <table id='to1' width='90%' border='0' cellspaceing='1' cellpadding='8' align='center'> <tr bgcolor='#9B7272'> <td > ID </td> <td > first_name </td> <td > last_name </td> <td > phone </td> <td > address </td> <td > email </td> <td > birthdate </td> <td > gender </td> <td > city </td> <td > dr_name </td> </tr> "); while($row = mysqli_fetch_array($result)) { $ID =$row['ID']; $first_name =$row['first_name']; $last_name =$row['last_name']; $phone =$row['phone']; $address =$row['address']; $email =$row['email']; $birthdate =$row['birthdate']; $gender =$row['gender']; $city =$row['city']; $dr_name =$row['dr_name']; echo " <tr bgcolor='#C7B8B8'> A: Problem You are missing how to pass the argument to mysqli_fetch_array(). Solution Therefore, this line: if(mysqli_query($cons, $result)) { should be if($res = mysqli_query($cons, $result)) { // assign the return value of mysqli_query to $res (FWIW, I'd go with $res = mysqli_query($cons, $result); then do if($res) {.) And then do while($row = mysqli_fetch_array($res)) // pass $res to mysqli_fetch_array instead of the query itself Why? You were giving to mysqli_fetch_array() - as an argument - the string that contains your query. That's not how it works. You should pass the return value of mysqli_query() instead. Therefore, you could also write: while($row = mysqli_fetch_array(mysqli_query($cons, $result))) {} (but it's not adviced, it is just to show you how it works). A: As mentioned in the comment, you need to set a $result from your query and use that in your loop instead. $qry ="SELECT * FROM report"; $result = mysqli_query($cons, $qry); if ($result){ while($row = mysqli_fetch_array($result)){ } } A: you can write like this:- $query = mysqli_query($cons,"SELECT * FROM items WHERE id = '$id'"); if (mysqli_num_rows($query) > 0) { while($row = mysqli_fetch_assoc($query)) { $result=$row; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/31511923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Restify & Bluebird - how to pass an error from a catch block to restify error handler? I am working on a node js server, and using bluebird for promise implementation. I understand how to use promises, but my problem is what to do with the error returned from a promise. I tried the simple solution - just trowing the error again - but bluebird catch it, and the client never receive a response. Bellow is a demo code, to illustrate my question: var restify = require('restify'); var Promise = require('bluebird'); var server = restify.createServer({ name: 'myapp', version: '1.0.0' }); server.get('/', function (req, res, next) { new Promise(function(resolve, reject){ reject(new Error()); }).then(function(res){ res.send('hello'); }).catch(function(e){ throw e; }); }); server.on('uncaughtException', function (req, res, route, error) { console.log('error'); }); server.listen(7070, function () { console.log('%s listening at %s', server.name, server.url); }); I am looking for a way to somehow pass the error to restify, so it will raise the uncaughtException event and I could handle it like any other uncaught exception. After searching this a bit, I found that I can simply do something like next(new InternalServerError()) and restify will raise an event for this specific error, but this is look a bit weird to me, so I am looking for a better way. A: Here's a PoC that will rethrow any "possibly unhandled rejections". These will subsequently trigger Restify's uncaughtException event: var Promise = require('bluebird'); var restify = require('restify'); var server = restify.createServer(); server.listen(3000); Promise.onPossiblyUnhandledRejection(function(err) { throw err; }); server.get('/', function (req, res, next) { Promise.reject(new Error('xxx')); // no `.catch()` needed }); server.on('uncaughtException', function (req, res, route, err) { console.log('uncaught error', err); return res.send(500, 'foo'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/32175643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firebug freezes Firefox on showing errors from FirePHP I have problem with debugging one of my projects. Every notice/warning/error is caught by FirePHP, and set with headers to browser. I catch all those errors with enabled Firebug, and everything's showing right in console: One of function of FirePHP with Firebug is to show details about those errors. And here's the problem - when i hover error with my mouse, Firefox freezes. CPU usage is very low, but memory consumption rises to 1,5-2GB. Cure is to kill FF, or wait 3-5 minutes till it suggests to kill frozen script chrome://firephp/content/viewer/panel.js:601 Do anyone struggles with similar issue? Versions: * *Firefox 36.0.1 *Firebug 2.0.8 *FirePHP 0.7.4 UPDATE: Ok, so i found why is it freezing. Data sent to Firebug contains all i18n messages from my app (as i'm using SF1.0 - it is in context) - and it simply is too large to quickly parse it to viewer. I dug up into my code, and even disabling sending all context from my PHP, doesn't disable context to show up in Variable viewer. A: This may not be the most elegant solution, but I would try (for a test) disabling firePHP and use instead a logging tool such as log4php and have it log your exceptions where and when they might be thrown. Thus, if you're not doing so already.. use try and catch blocks and in the catch blocks, log your exception to a file that you'd declare in the config/instantiation of log4php. Just a suggestion.
{ "language": "en", "url": "https://stackoverflow.com/questions/28985429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error: useHref() may be used only in the context of a component. in register,js Good afternoon, I am creating an app in reactjs and all the routes work fine, only the register user gives the error Error: useHref() may be used only in the context of a component.I am using firebase for this, the login with google and user and password works 100%, thanks register.js code import { push } from "firebase/database"; import React, { useEffect, useState } from "react"; import { useAuthState } from "react-firebase-hooks/auth"; import { Link, Route, useHistory } from "react-router-dom"; import { auth, registerWithEmailAndPassword, signInWithGoogle, } from "../config/firebase"; function Register() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const [user, loading, error] = useAuthState(auth); const register = () => { if (!name) alert("Please enter name"); registerWithEmailAndPassword(name, email, password); }; useEffect(() => { if (loading) return; if (user) Route.push("/dashboard"); }, [user, loading]); return ( <div className="register"> <div className="register__container"> <input type="text" className="register__textBox" value={name} onChange={(e) => setName(e.target.value)} placeholder="Full Name" /> <input type="text" className="register__textBox" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="E-mail Address" /> <input type="password" className="register__textBox" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" /> <button className="register__btn" onClick={register}> Register </button> <button className="register__btn register__google" onClick={signInWithGoogle} > Register with Google </button> <div> Already have an account? <Link to="/">Login</Link> now. </div> </div> </div> ); } export default Register; A: You forgot to wrap your React App within BrowserRouter or some router. Go to index.js in src folder. Wrap it like this. <BrowserRouter> <App /> </BrowserRouter> Then, add some Route. For example, like this. <BrowserRouter> <Routes> <Route element={<Home/>} path={"/"} /> <Route element={<Another />} path={"/another}/> </Routes> </BrowserRouter>
{ "language": "en", "url": "https://stackoverflow.com/questions/72931914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSLT replace an element that exists inside another element value I am new to XSLT (using XSLT v1.0) and I have the following input: <SUMMARY> <TITLE>Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </TITLE> <P> Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </P> </SUMMARY> <REFERENCE> <TI>Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </TI> <P> Lorem ipsum dolor <QUOTE ID="replace with this string"/> sit vel eu. </P> </REFERENCE> How could I replace all the occurrences of the element QUOTE inside my XML input, with a String that is the value of the QUOTE/ID attribute. A: Add to the identity transform a special template to handle QUOTE: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="QUOTE"> <xsl:value-of select="@ID"/> </xsl:template> </xsl:stylesheet> The identity transformation will copy everything to the output XML, and the special QUOTE template will copy over the value of its @ID attribute in place of the QUOTE element.
{ "language": "en", "url": "https://stackoverflow.com/questions/52223949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Visual C++, multiple for loops using same iterator name, visible outside of scope in debug mode I'm using Visual Studio Express 2013 and have multiple for loops where I use the same name for the iterator, like so: for (int i = 0; i < 10; i++) { // do something } .... for (int i = 0; i < 10; i++) { // do something else } When I step through in debug mode, after leaving the first for loop the first 'i' remains visible in the Locals window at its final value 10, even though it has gone out of scope. Then I enter the second for loop and I now have two i's showing (albeit with different values). It's a slight annoyance because I'll break somewhere on another condition and I can't immediately see what the value of i is. I can get around that by just declaring 'i' once outside the iterator scope: int i; ... for (i = 0; i < 10; i++) { // do something } ... for (i = 0; i < 10; i++) { // do something else } But it still bothers me because it seems inconsistent. I would expect to see the same behavior as this, where the first 'i' disappears from the Locals window once it goes out of scope: { int i = 0;} } ... { int i = 1; } I want to know whether it's just a Microsoft thing, or if I don't properly understand scoping in for loops ... A: Nice catch. To me, it sounds like a compiler bug more or less. There is an option in VC to select to "Force Conformance In For Loop Scope" so that the for loop variable goes out of scope outside for loop. However, that doesn't fix the issue you mentioned in the debugger. Regardless of which option you select, both variables are there in the debugger, which appears to be confusing. The only way to distinguish between them is that out-of-scope i should have value 0xcccccccc in debug mode. This should be compiler specific, and WinDbg handles it in a different way, as mentioned in the following article. What I tried: VC2008, VC2012 There is a good article well experimenting this issue. A: MSVC has a special compiler flag that can affect the scoping of int i in your examples: /Zc:forScope. It's on by default, but the debugger is probably set up to accommodate for it to be turned off with /Zc:forScope- which would make the following code valid (even though it's not standards-compliant): { for (int i=0; i < 10; ++i) { // Do something } for(i=0; i < 10; ++i) { // Do something else } } Alternatively, if you've accidentally turned it off, your code is not working as you (and the C++ standard) expect, but then you'd probably get a warning on redeclaring i. A: There is an option in Visual Studio that controls whether the scope of variables defined in a for loop are visible beyond the for loop. It's called /Zc:forScope. When you use /Zc:forScope-, you get the behavior you described. To change the behavior to conform to C++ stanards, you have to use /Zc:forScope More information can be found at MSDN Website: /Zc:forScope (Force Conformance in for Loop Scope).
{ "language": "en", "url": "https://stackoverflow.com/questions/23050912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to reach my main form controlls from my UserControl I have Balloon user control that opens in the tray when my application is minimyze. So i created simple Button on this Balloon: public partial class ApplicationBalloon : UserControl { private void btnStart_Click(object sender, RoutedEventArgs e) { } } When this event is fired i want to click on specific button in my main form so i can i reach my main form controlls from this UserControl ? EDIT In my main form after the c'tor: applicationBalloon = new ApplicationBalloon(); applicationBalloon.BalloonClicked += applicationBalloon_BalloonClicked; And in my User Control: public partial class ApplicationBalloon : UserControl { public event EventHandler<RoutedEventArgs> BalloonClicked; public ApplicationBalloon() { InitializeComponent(); } private void btnStart_Click(object sender, RoutedEventArgs e) { if (BalloonClicked != null) BalloonClicked(sender, e); } } The btnStart_Click is after my application is running and allthough BalloonClicked is still null. A: Add an event to your balloon class, handle the click in your balloon class and pass the arguments up to whoever attaches to your event. In your balloon class: public partial class ApplicationBalloon : UserControl { public event EventHandler<RoutedEventArgs> BalloonClicked; private void OnButtonClicked(object sender, RoutedEventArgs e) { if (BalloonClicked != null) BalloonClicked(sender, e); } } You can now add a handler to your main form attached to BalloonClicked. A: Just access it with: Application.Current.MainWindow And cast it to whatever your main window type is.
{ "language": "en", "url": "https://stackoverflow.com/questions/33439262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add value between tags using XElement? I have looked a bunch of XML samples using XDocument and XElement but they all seem to have self closing tags like <To Name="John Smith"/>. I need to do the following: <To Type="C">John Smith</To> I thought the following would work and tried to look at the object model of the Linq.XML class, but I'm off just a tad (see line below that is not working) new XElement("To", new XAttribute("Type", "C")).SetValue("John Smith") Any assistance on how to get the XML formed properly is appreciated, thanks! A: How about new XElement("To", new XAttribute("Type", "C"), "John Smith") A: I'd use: new XElement("To", new XAttribute("Type", "C"), "John Smith"); Any plain text content you provide within the XElement constructor ends up as a text node. You can call SetValue separately of course, but as it doesn't return anything, you'll need to store a reference to the element in a variable first.
{ "language": "en", "url": "https://stackoverflow.com/questions/14483455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Error org.json.JSONException: Value Error of type java.lang.String cannot be converted to JSONObject I have a Android app about Public Transportation, and I have a PHP script that connects to mySQL database. This is the main.java package com.chera.trans; import com.chera.trans.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.traseu2: Intent traseu2 = new Intent(this, Traseu2.class); this.startActivity(traseu2); break; case R.id.traseu401: Intent traseu401 = new Intent(this, Traseu401.class); this.startActivity(traseu401); break; default: return super.onOptionsItemSelected(item); } return true; } } And this is the code for Traseu2.java package com.chera.trans; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.chera.trans.R; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; public class Traseu2 extends Activity { private String jsonResult; private String url = "http://transploiesti.tk/2.php"; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.traseu2); listView = (ListView) findViewById(R.id.listView1); accessWebService(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.traseu2: Intent traseu2 = new Intent(this, Traseu2.class); this.startActivity(traseu2); break; case R.id.traseu401: Intent traseu401 = new Intent(this, Traseu401.class); this.startActivity(traseu401); break; default: return super.onOptionsItemSelected(item); } return true; } // Async Task to access the web private class JsonReadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(params[0]); try { HttpResponse response = httpclient.execute(httppost); jsonResult = inputStreamToString( response.getEntity().getContent()).toString(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (IOException e) { // e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show(); } return answer; } @Override protected void onPostExecute(String result) { ListDrwaer(); } }// end async task public void accessWebService() { JsonReadTask task = new JsonReadTask(); // passes values for the urls string array task.execute(new String[] { url }); } // build hash set for list view public void ListDrwaer() { List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>(); try { JSONObject jsonResponse = new JSONObject(jsonResult); JSONArray jsonMainNode = jsonResponse.optJSONArray("traseudoi"); for (int i = 0; i < jsonMainNode.length(); i++) { JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); String name = jsonChildNode.optString("Statie"); String number = jsonChildNode.optString("Oraplecare"); String outPut = "Autobuzul pleaca din " + name + " la ora " + number; employeeList.add(createEmployee("employees", outPut)); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show(); } SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] { "employees" }, new int[] { android.R.id.text1 }); listView.setAdapter(simpleAdapter); } private HashMap<String, String> createEmployee(String name, String number) { HashMap<String, String> employeeNameNo = new HashMap<String, String>(); employeeNameNo.put(name, number); return employeeNameNo; } } ` Why I receive this error when I m running the app? Thanks! A: HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further.
{ "language": "en", "url": "https://stackoverflow.com/questions/25653512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android-tab new contents while viewing it? Some apps have this feature, that when a new post is added while the app is in the foreground it shows this view: Can anybody offer an article or blog post to get this view with animation and all that? I can do it by myself, but I want it to look professional. Any advice would be appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/40684682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is setting Roles in JWT a best practice? I am considering to use JWT. In the jwt.io example I am seeing the following information in the payload data: "admin": true Admin can be considered as a Role, hence my question. Is setting the role in the token payload a habitual/good practice? Given that roles can be dynamically modified, I'm quite interrogative. A: Nothing stops you from creating claims to store extra information in your token if they can be useful for your client. However I would rely on JWT only for authentication (who the caller is). If you need to perform authorization (what the caller can do), look up the caller roles/permissions from your persistent storage to get the most updated value. For short-lived tokens (for example, when propagating authentication and authorization in a microservices cluster), I find it useful to have the roles in the token. A: As mentioned here, ASP.NET Core will automatically detect any roles mentioned in the JWT: { "iss": "http://www.jerriepelser.com", "aud": "blog-readers", "sub": "123456", "exp": 1499863217, "roles": ["Admin", "SuperUser"] } and 'map' them to ASP.NET Roles which are commonly used to secure certain parts of your application. [Authorize(Roles = "Admin")] public class SettingsController : Controller The server which is giving out (and signing) the JWT is commonly called an authorization server and not just an authentication server, so it makes sense to include role information (or scope) in the JWT, even though they're not registered claims. A: The official JWT site explicitly mentions "authorization" (in contrast to "authentication") as a usecase for JWTs: When should you use JSON Web Tokens? Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. That being said, from a security-perspective you should think twice whether you really want to include roles or permissions in the token. (The text below can be understood as a more "in-depth" follow up to the rather short-kept accepted answer) Once you created and signed the token you grant the permission until the token expires. But what if you granted admin permissions by accident? Until the token expires, somebody is now operating on your site with permissions that were assigned by mistake. Some people might argue that the token is short-lived, but this is not a strong argument given the amount of harm a person can do in short time. Some other people advocate to maintain a separate blacklist database table for tokens, which solves the problem of invalidating tokens, but adds some kind of session-state tracking to the backend, because you now need to keep track of all current sessions that are out there – so you would then have to make a db-call to the blacklist every time a request arrives to make sure it is not blacklisted yet. One may argue that this defeats the purpose of "putting the roles into the JWT to avoid an extra db-call" in the first place, since you just traded the extra "roles db-call" for an extra "blacklist db-call". So instead of adding authorization claims to the token, you could keep information about user roles and permissions in your auth-server's db over which you have full control at any time (e.g. to revoke a certain permission for a user). If a request arrives, you fetch the current roles from the auth-server (or wherever you store your permissions). By the way, if you have a look at the list of public claims registered by the IANA, you will see that these claims evolve around authentication and are not dealing with what the user is allowed to do (authorization). So in summary you can... * *add roles to your JWT if (a) convenience is important to you and (b) you want to avoid extra database calls to fetch permissions and (c) do not care about small time windows in which a person has rights assigned he shouldn't have and (d) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions. *add roles to your JWT and use a blacklist if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have and (b) accept that this comes at the cost of making a request to a blacklist for every incoming request and (c) you do not care about the (slight) increase in the JWT's payload size resulting from adding the permissions. *not add roles to your JWT and fetch them on demand if (a) you want to prevent any time windows in which a person has rights assigned he shouldn't have or (b) avoid the overhead of a blacklist or (c) avoid increasing the size of your JWT payload to increase slightly and (d) if you accept that this comes at the cost of sometimes/always querying the roles on incoming requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/47224931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: what is missing for DocumentNode function to show text in datagridview? What i´m trying to do is to use the documentnode method to find a specific table from the internet and put it into datagridview. My code can be seen below: ` List<string> list = new List<string>(); DataTable dt1 = new DataTable(); var table = doc.DocumentNode.SelectNodes("xpath link") .Descendants("tr") .Where(tr=>tr.Elements("td").Count()>1) .Select(td => td.InnerText.Trim()) .ToList(); foreach (var tables in table) { list.Add(tables.ToString());} dataGridView1.DataSource = list ` The result I get in the table is a list of numbers instead of text (datagridview table). As I have tried to see it the text actually appears I changed the foreach with the following code: ` foreach (var tables in table) { list.Add(tables.ToString()); richTextBox1.Text += tables; } ` The result I get from the change is a string of the table in richTextBox1 but still a table of numbers in datagridview1 richtextbox1 text. This means I´m getting the right table from the internet and its being loaded correctly but i´m still missing something for the datagridview1 as I get a list of numbers instead of text that is being shown in richtextbox1. I followed this up by changing the DocumentNode function with removing parts in the .select part of the code and the datagridview1 stilled showed numbers (I added for example .ToString, .ToList() etc.). What exactly have I missed in my code that makes this happen and should I have added something else to make it show the text instead of numbers? Edit: New code. ` List<string> list = new List<string>(); DataTable dt1 = new DataTable(); dt1.Columns.Add("td", typeof(int)); var table = doc.DocumentNode.SelectNodes("//div[@id=\"cr_cashflow\"]/div[2]/div/table") .Descendants("tr") .Select(td => td.InnerText.Trim()) .ToList(); foreach (var tables in table) { dt1.Rows.Add(new object[] { int.Parse(tables) }); } dataGridView1.DataSource= dt1; ` A: Try something like this List<string> list = new List<string>(); DataTable dt1 = new DataTable(); dt1.Columns.Add("td",typeof(int)); var rows = doc.DocumentNode.SelectNodes("xpath link") .Descendants("tr") .Where(tr=>tr.Elements("td").Count()>1) .Select(td => td.InnerText.Trim()) .ToList(); foreach (var row in rows) { dt.Rows.Add(new object[] { int.Parse(row)}); }
{ "language": "en", "url": "https://stackoverflow.com/questions/74656378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: javascript syntax for new objects and prototypes I'm femiliar with OOP from PHP / JAVA but i'm a newbie in JS prototype objects. My question is: I found that there are 4 ways (probably more) to instantiate a new object: 1. var d = Object.create(Object.prototype); 2. var d = {}; 3. var d = new Object(); 4. var d = function(){}; d.prototype = {a:xxx, b:yyy}; what is the different between the four in regards to the prototype (as i understand prototype is the main Object constructor which all object inherits from). Hope I got it right....thanks, Danny
{ "language": "en", "url": "https://stackoverflow.com/questions/18695748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Align link to bottom of div and center it I'm trying to make a link stick to the bottom center of a div and have it be centered. So far I've come up with this: http://jsfiddle.net/r494Lx0r/2/ div.container { position: relative; height: 110px; width: 120px; border: dashed 1px red; } div.container div.text { position: absolute; bottom: 0px; border: solid 1px black; } Now how do I make it so that it's centered? I've tried adding text-align:center; and margin:0 auto; to the container but neither of those do anything. Does anyone know how to do this? A: UPDATE add text-algin: center to the parent to center the anchor and set border: solid 1px black; to your anchor: div.container { position: relative; height: 110px; width: 120px; border: dashed 1px red; } div.container div.text { position: absolute; bottom: 0px; right: 0; left: 0; text-align: center; } a{border: solid 1px black;} <div class="container"> <div class="text"> <a href="#">Google.com</a> </div> </div> Add Width: 100% and text-align: center div.container { position: relative; height: 110px; width: 120px; border: dashed 1px red; } div.container div.text { position: absolute; bottom: 0px; text-align: center; width:100%; border: solid 1px black; } <div class="container"> <div class="text"> <a href="#">Google.com</a> </div> </div> or left: 0;, right: 0; and text-align: center; div.container { position: relative; height: 110px; width: 120px; border: dashed 1px red; } div.container div.text { position: absolute; bottom: 0px; left: 0; right: 0; text-align: center; border: solid 1px black; } <div class="container"> <div class="text"> <a href="#">Google.com</a> </div> </div> or you can combine `margin-left: 50%;` and `transform: translate(-50%)` div.container { position: relative; height: 110px; width: 120px; border: dashed 1px red } div.container div.text { position: absolute; bottom: 0px; border: solid 1px black; margin-left: 50%; -webkit-transform: translate(-50%); -moz-transform: translate(-50%); transform: translate(-50%) } <div class="container"> <div class="text"> <a href="#">Google.com</a> </div> </div> A: display:block; margin:auto; makes elements centered. So you could edit your code to become: div.container div.text { bottom: 0px; border: solid 1px black; display:block; margin:auto; } A: .text{ width: 100%; text-align: auto; } The text wrapping div will then be as wide as its container, so text align will work as expected. The reason text-align isn't working for you on your current code is because the "text" div is only as wide as the link, therefore centering its contents does nothing. A: PROVIDED the link is the bottom/last element in the div- add this to the div: text-align: center; //centers the text and then set the link to: margin-top: auto; // pushes the text down to the bottom worked in my case. Simple and quick, but only works provided your link is the last element in the div.
{ "language": "en", "url": "https://stackoverflow.com/questions/27198088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Finding specific data in Oracle Tables I needed to find a value for a column in my oracle database but i don't know which table or column it's stored in How can I search for a specific or like %% data as I do in select * from SYS.dba_source is there a table like that Column Name ID Data Type Null? Comments OWNER 1 VARCHAR2 (30 Byte) Y NAME 2 VARCHAR2 (30 Byte) Y Name of the object TYPE 3 VARCHAR2 (12 Byte) Y Type of the object: "TYPE", "TYPE BODY", "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE BODY" or "JAVA SOURCE" LINE 4 NUMBER Y Line number of this line of source TEXT 5 VARCHAR2 (4000 Byte) Y Source text A: LINK: pl/sq to find any data in a schema Imagine, there are a few tables in your schema and you want to find a specific value in all columns within these tables. Ideally, there would be an sql function like select * from * where any(column) = 'value'; Unfortunately, there is no such function. However, a PL/SQL function can be written that does that. The following function iterates over all character columns in all tables of the current schema and tries to find val in them. create or replace function find_in_schema(val varchar2) return varchar2 is v_old_table user_tab_columns.table_name%type; v_where Varchar2(4000); v_first_col boolean := true; type rc is ref cursor; c rc; v_rowid varchar2(20); begin for r in ( select t.* from user_tab_cols t, user_all_tables a where t.table_name = a.table_name and t.data_type like '%CHAR%' order by t.table_name) loop if v_old_table is null then v_old_table := r.table_name; end if; if v_old_table <> r.table_name then v_first_col := true; -- dbms_output.put_line('searching ' || v_old_table); open c for 'select rowid from "' || v_old_table || '" ' || v_where; fetch c into v_rowid; loop exit when c%notfound; dbms_output.put_line(' rowid: ' || v_rowid || ' in ' || v_old_table); fetch c into v_rowid; end loop; v_old_table := r.table_name; end if; if v_first_col then v_where := ' where ' || r.column_name || ' like ''%' || val || '%'''; v_first_col := false; else v_where := v_where || ' or ' || r.column_name || ' like ''%' || val || '%'''; end if; end loop; return 'Success'; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/10879483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Minizinc, how to create a map or a dictionary datastructure I have a simple question regarding the Minizinc's syntax. My input .dzn file contain a set of 2 dimentional arrays (approximately up to 30 arrays), declared as follows: rates_index_0 = array2d(1..3, 1..501, [ 15, 20, 23, .... rates_index_12 = array2d(1..3, 1..501, [ 21, 24, 27, .... ... note: index numbers have gaps in them (e.g., 12 -> 20) In my model, I need to use one of these arrays depending on the value of the variable. In common programming language I would solve it using a map or a dictionary datastructure. But in Minizinc I am hardcoding this in the following way: function var int: get_rate(int: index, var int: load, int: dc_size) = if index == 0 then rates_index_0[dc_size, load] else if index == 12 then rates_index_12[dc_size, load] else if index == 16 then rates_index_16[dc_size, load] else if index == 20 then rates_index_20[dc_size, load] else assert(false, "unknown index", 0) endif endif endif endif; The one obvious problem with this code is that I need to change model each time I change input. Is there a better way how I can code this in a generic way? Thanks! A: In an more abstract way a map-structure is nothing more than a function mapping inputs of a certain type to an array. A map can thus be replaced by a array and a function. (The difference being you will have to define the function yourself) Before I get started with the rest I would like to point out that if your model compiles generally fast, you might want to try a triple array without the function, rates_index = array3d(0..60, 1..3, 1..501, [ 15, 20, 23, ..... This will cost more memory, but will make the model more flexible. The general way of using a map-structure would be to define a function map_index, that maps your input, in this case integers, to the index of the array, also integers. This means that we can then define a extra level array to point to the right one: rates_index = array3d(0..nr_arrays, 1..3, 1..501, ..... This means that the content of get_rates can then be: rates_index[map_index(index), dc_size, load]. The function map_index itself in its simplest form would contain another version of your if-then-else statements: function int: map_index(int: index) = if index == 0 then 0 else if index == 12 then 1 else if index == 16 then 2 else if index == 20 then 3 else assert(false, "unknown index", 0) endif endif endif endif; However you can make it dynamic by generating an extra array containing the array number for each index, putting -1 for all arrays that are not available. For your example the mapping would look like this: array[0..20] of int: mapping = [0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 2, -1, -1, -1, 3];. The map_index function could then dynamically be defined as: function int: map_index(int: index) = mapping[index];
{ "language": "en", "url": "https://stackoverflow.com/questions/46262667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can users use their email accts to look for friends on my site? I'm working on a new social networking site and I want to give users a way to: 1) Automatically scan my site for people they already know (email/linkedin/facebook/etc) 2) Provide users with the option of inviting their friends to join the site It seems like many of these tools have their own api, but in most cases it doesn't look like I would be able to get a unique id (the email, basically). Are there other tools out there I could/should look at? A: As for Facebook, unfortunately this is not possible using email since users may choose not to share their real email with you. One way, for Facebook, is to store the Facebook user id (you should be doing this anyway) and retrieve the newly registered user friends' ids and check if any of these ids present in your DB. A: I implemented this on one of my sites. When users register for an account, I require an email address. I give them an option to find their email accounts (gmail, hotmail, aol, and yahoo all have oauth services you can use to get contacts). I also give them the option for LinkedIn, Facebook, and Twitter. This doesn't work as well as those 3 social networks won't disclose email addresses (and rightfully so). So each user that authenticates, I log their id from that service. Then I get the id's of their friends, and see if any of those friends have associated their account with my site. The key for this to work is to encourage your users to associate those accounts.
{ "language": "en", "url": "https://stackoverflow.com/questions/6350536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tensorflow distributed inference I have a large model (GPT-J 6B) and two 16G GPUs (V100 with no NVLink). I would like to do inference (generation). GPT-J needs 24G memory, so I need to split the model across my two GPUs. For me, simplicity is much more important than maximizing utilization/throughput. What is the easiest way to distribute the network? Is it possible to put first half of the network on one GPU and the second half on the other? (pipeline-parallel essentially)
{ "language": "en", "url": "https://stackoverflow.com/questions/73547018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error 'class HotelRoom' has no member named 'menu' even though it is there I am attempting to build a hotel reservation program in C++. however, I have an issue. I keep getting the above error message and I can't seem to find a fix. Please provide some assistance. Anything would be greatly appreciated. Below is what I have written thus far. using namespace std; class HotelRoom{ private: int roomnum; //Room numbers int roomcap; //Room capacity int roomoccuoystst = 0; int maxperperroom; double dailyrate; public: HotelRoom() { roomcap = 0; maxperperroom = 2; dailyrate = 175; } int gettotal = 0; int gettotallist = 0; string room; string guestroom,message; void viewrooms() { char viewselect, back; cout<<"Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : " ; cin>>viewselect; switch(viewselect) { case '1': viewaddromm(); break; case '2': viewresromm(); break; default: cout<<"Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : "; cin>>back; switch(back) { case '1': viewrooms(); break; case '2': hotelmenu(); break; default: exitpro(); } } } void viewresromm() { int occup,rmchoose,up; string roomtochange, items; string guestroomdb; int newaccupancy; char decisionmade,savinf; string fname, lname, nationality; string checkaddroom; ifstream getdatafromaddroom; //creation of the ifstream object getdatafromaddroom.open("reserveroom.out"); if(getdatafromaddroom.fail()) //if statement used for error checking { cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file } cout<<endl; cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl; cout<<"-------------------------------------------------------"<<endl; string items; while(!getdatafromaddroom.eof()) { // getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb; getline(getdatafromaddroom, items); //cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl; gettotallist++; if( getdatafromaddroom.eof() ) break; cout<<items<<endl; } for(int getlist = 0; getlist < gettotallist; getlist++ ) { cout<<items<<endl; // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl; } } void viewaddromm() { int occup,rmchoose,up; string roomtochange; string guestroomdb; int newaccupancy; char decisionmade,savinf; string fname, lname, nationality; string checkaddroom; fstream getdatafromaddroom; //creation of the ifstream object getdatafromaddroom.open("addroom.out"); if(getdatafromaddroom.fail()) //if statement used for error checking { cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file } cout<<endl; cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl; cout<<"-------------------------------------------------------"<<endl; string items; while(!getdatafromaddroom.eof()) { // getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb; getline(getdatafromaddroom, items); //cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl; gettotallist++; if( getdatafromaddroom.eof() ) break; cout<<items<<endl; } for(int getlist = 0; getlist < gettotallist; getlist++ ) { cout<<items<<endl; // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl; } } void exitpro() { cout<<"Program closing......Goodbye"<<endl; system("Pause"); exit(0); } menu() { char menuchoice; cout<<"[-------------------------------------------------------]"<<endl; cout<<"[-Welcome to the hotel booking and reseration menu-]"<<endl; cout<<"[--------------------------------------------------------]"<<endl; cout<<setw(30)<<"Addroom -- 1"<<endl; cout<<setw(32)<<"Reserve a room -- 2"<<endl; cout<<setw(34)<<" Modify a room -- 3"<<endl; cout<<setw(36)<<"View roms -- 4"<<endl; cout<<setw(38)<<" Exist -- 5"<<endl; cin>>menuchoice; switch(menuchoice) { case '1': Addroom(); break; case '2': reserveroom(); break; case '3': modifyroom(); break; case '4': viewrooms(); break; } } }; #endif A: #include<string> #include<iostream> #include<fstream> #include<iomanip> using namespace std; class HotelRoom { private: int roomnum; // Room numbers int roomcap; // Room capacity int roomoccuoystst = 0; int maxperperroom; double dailyrate; public: HotelRoom() { roomcap = 0; maxperperroom = 2; dailyrate = 175; } int gettotal = 0; int gettotallist = 0; string room; string guestroom, message; void viewrooms() { char viewselect, back; cout << "Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : "; cin >> viewselect; switch (viewselect) { case '1': viewaddromm(); break; case '2': viewresromm(); break; default: cout << "Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : "; cin >> back; switch (back) { case '1': viewrooms(); break; case '2': menu(); break; default: exitpro(); } } } void viewresromm() { string roomtochange, items; string guestroomdb; // int newaccupancy; // char decisionmade,savinf; string fname, lname, nationality; string checkaddroom; ifstream getdatafromaddroom; // creation of the ifstream object getdatafromaddroom.open("reserveroom.out"); if (getdatafromaddroom.fail()) // if statement used for error // checking { cout << "Could not open file" << endl; // message that will be // printed if the program // cannot open the file return; } cout << endl; cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" << '-' << "Room #" << endl; cout << "-------------------------------------------------------" << endl; // string items; while (!getdatafromaddroom.eof()) { // getdatafromaddroom // >>fname>>lname>>nationality>>occup>>guestroomdb; getline(getdatafromaddroom, items); // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' // '<<setw(9)<<guestroomdb<<endl; gettotallist++; if (getdatafromaddroom.eof()) break; cout << items << endl; } for (int getlist = 0; getlist < gettotallist; getlist++) { cout << items << endl; // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' // '<<setw(9)<<guestroomdb<<endl; } } void viewaddromm() { // int occup,rmchoose,up; string roomtochange; string guestroomdb; // int newaccupancy; // char decisionmade,savinf; string fname, lname, nationality; string checkaddroom; fstream getdatafromaddroom; // creation of the ifstream object getdatafromaddroom.open("addroom.out"); if (getdatafromaddroom.fail()) // if statement used for error // checking { cout << "Could not open file" << endl; // message that will be // printed if the program // cannot open the file return; } cout << endl; cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" << '-' << "Room #" << endl; cout << "-------------------------------------------------------" << endl; string items; while (!getdatafromaddroom.eof()) { // getdatafromaddroom // >>fname>>lname>>nationality>>occup>>guestroomdb; getline(getdatafromaddroom, items); // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' // '<<setw(9)<<guestroomdb<<endl; gettotallist++; if (getdatafromaddroom.eof()) break; cout << items << endl; } for (int getlist = 0; getlist < gettotallist; getlist++) { cout << items << endl; // cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' // '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' // '<<setw(9)<<guestroomdb<<endl; } } void exitpro() { cout << "Program closing......Goodbye" << endl; // system("Pause"); exit(0); } void Addroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } void reserveroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } void modifyroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } void menu() { while (true) { char menuchoice; cout << "[-------------------------------------------------------]" << endl; cout << "[-Welcome to the hotel booking and reseration menu-]" << endl; cout << "[--------------------------------------------------------]" << endl; cout << setw(30) << "Addroom -- 1" << endl; cout << setw(30) << "Reserve a room -- 2" << endl; cout << setw(30) << "Modify a room -- 3" << endl; cout << setw(30) << "View rooms -- 4" << endl; cout << setw(30) << "Exit -- 5" << endl; cin >> menuchoice; switch (menuchoice) { case '1': Addroom(); break; case '2': reserveroom(); break; case '3': modifyroom(); break; case '4': viewrooms(); break; case '5': exitpro(); } } } }; int main() { try { HotelRoom room; room.menu(); } catch(std::logic_error * ex) { std::cout << ex->what(); } } you have a lot more to go with this project. I've fixed the portion you specifically asked about and its now a runninng application with somewhat approperate diagnostics. I'm not going to get too deep into how this language works but you have several functions that were not implimented, missing return types, and just general logic errors like trying to use a file after you determined it wasnt open. it runs now, and you can get a clear indication of what you need to complete. You also had several unused varables. i added , at minimal, void Addroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } void reserveroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } void modifyroom() { std::string mess = __func__; mess += " is not yet implimented."; throw new std::logic_error(mess.c_str()); } and a return type to menu. `void menu() you cannot call functions you have not yet written, and all functions have a return type even if they return nothing. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/53376361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use a Variable in Jmeter Regex Extractor I am new to jMeter. I am recording a script for creating a shift. For every transaction New shift ID is generated. I have tried to extract it by using regx Exp extractor but not getting anything. Pls see below information. *Reference Name: strgenShiftId Regular Expression: end="${strWeekEndDate}" gs="(.+?)" Template: $1$ Match No. Default Value: Where ${strWeekEndDate} is a variable which extracts the date from some other previous response. My Response code is as following- week start="07/27/2015" end="08/02/2015" gs="61530" unitSkey="811" fy="2015" fw="30" ac="Y"> I want to extract the gs="61531". The full response is: <data> <weeks selWkIndex="5"> <week start="06/29/2015" end="07/05/2015" gs="71526" unitSkey="811" fy="2015" fw="26" ac="N"> </week> <week start="07/06/2015" end="07/12/2015" gs="71527" unitSkey="811" fy="2015" fw="27" ac="N"> </week> <week start="07/13/2015" end="07/19/2015" gs="71528" unitSkey="811" fy="2015" fw="28" ac="N"> </weeks> </data> A: You can extract gs value using following regular expression: gs=\"([^"]+)\". Always remember to escape " with \ in regular epressions, unless you want " to be evaluated as part of regular expression.
{ "language": "en", "url": "https://stackoverflow.com/questions/31664128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL - How to combine the column data into one row I am making an employee attendance record and I have trouble merging the raw data into time in and time out combination format. From the given "Raw Data" Table below I need to combine the time in and time out of the employee into one row like the "Merge Time in/out" sample below. Also consider that the employee has two shifting schedule the day shift and night shift. Take note that if the employee is in night shift schedule the time out date is different to time in date. Day shift empid(ID001,ID002) Night shift empid(ID003) Raw Data Table -------------------------------------------- empid date time[in/out] in_out -------------------------------------------- ID001 2014-08-01 7:00am IN ID002 2014-08-01 7:01am IN ID003 2014-08-01 8:05pm IN <--Night Shift ID001 2014-08-01 5:00pm OUT ID002 2014-08-01 5:01pm OUT ID003 2014-08-02 6:01am OUT <--take note of date Merge Time in/out Table -------------------------------------------- empid date time_in time_out -------------------------------------------- ID001 2014-08-01 7:00am 5:00pm ID002 2014-08-01 7:01am 5:01pm ID003 2014-08-01 8:05pm 6:01am A: select r1.empid, r1.date, r1.time as time_in, r2.time as time_out from raw_Data r1 inner join raw_data r2 on r1.empid = r2.empid where r1.in_out = 'IN' and r2.in_out = 'OUT'; A: Ok, so you can tell if the employee worked the night shift when his time_out was AM. In this case, it's the last row's case. What I did was determinate a real date field. It is the day before when you're out from the night shift, and the current date in any other case select empid, IF(RIGHT(timeinout,2)='am' AND in_out='OUT', DATE_ADD(date, INTERVAL -1 DAY), date) as realdate, MAX(if(in_out='IN',timeinout,null)) as time_in, MAX(if(in_out='OUT',timeinout,null)) as time_out from shifts group by empid, realdate Outputs depending on the table size it might be worth using this way just for saving yourself a join. In almost any other case, a join is cleaner. I guess you have no control over the format of the input, so you'll have to stick to times as text and make a comparison for the am/pm suffix in the last 2 characters. I find that rather error prone, but let's pray the raw data will stick to that format. This solution makes a few assumptions that I rather explain here to avoid further misunderstandings * *The workers can't work the night shift if they worked the day shift (since we're grouping by date, you would need an extra field to distinguish day shift and night shift for a given day) *Input will never list an OUT time earlier than a IN time for a given day/employee tuple (if it happens, this would need an extra verification step to guarantee consistent output) *Input will always include timein and timeout for a given shift (if it didn't, you would need an extra step to discard orfan timeentries). A: Try this query and tell me if it works SELECT empid, date, MAX(CASE WHEN in_out = 'IN' THEN time ELSE '' END) time_in, MAX(CASE WHEN in_out = 'OUT' THEN time ELSE '' END) time_out FROM Raw Data GROUP BY empid, date
{ "language": "en", "url": "https://stackoverflow.com/questions/25383198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Having a developer-specific configuration for Apache Ivy I'm using Apache Ivy to manage dependencies in the project with several developers. They will share most of the Ivy configuration, but some pieces (like corporate proxy username and password) should be developer-specific. I've created a reference file for everyone to place in the ~/.ivy2/ivysettings.xml (this is where developer could specify his password), but cannot include it from the ivy:configure on Windows machines (Ivy does not expand environment variables there, and pointing to every developer's ~ is problematic). Any suggestions on how could I allow developer-wide configuration in this setup? A: The java property user.home performs the same role as the ~ from *NIX systems. (Note: On windows, the USERPROFILE environment variable fills this role) Ivy can work with java system properties, just use the ${user.home} notation as you would in Ant. References: * *http://www.mindspring.com/~mgrand/java-system-properties.htm *http://www.wilsonmar.com/1envvars.htm#WinVars *http://ant.apache.org/ivy/history/2.0.0-rc1/settings.html
{ "language": "en", "url": "https://stackoverflow.com/questions/2027967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find the string from string array in firestore I have a list of documents and each document has a field of a string array named "fav", it has more than 50k emails, there are almost 1000 documents and in each document's "fav" array has variable length including 50k, 20k,10, etc. I was fetching all documents Firestore.instance.collection("save").snapshots(); through StreamBuilder StreamBuilder( stream: Firestore.instance.collection("save").snapshots();, builder: (context, snapshot) { if (!snapshot.hasData) return Text("Loading Data............."); else { listdata = snapshot.data.documents; return _buildBody(snapshot.data.documents); } }, ) Now How I can search my required email from each document's field "fav"? I have to perform an operation after finding the required id in the array locally. A: The question is not very clear, but for my understanding, this is what you are looking for Firestore.instance.collection('save') .where('fav', arrayContains: '[email protected]').snapshots() A: The question is not very clear, but for my understanding, you want to find one e-mail in the array field. This array is contained on each document, and all the documents are "streamed" in a collection of snapshots. Contains Method: https://api.dartlang.org/stable/2.0.0/dart-core/Iterable/contains.html bool contains ( Object element ) Returns true if the collection contains an element equal to element. This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element. The equality used to determine whether element is equal to an element of the iterable defaults to the Object.== of the element. Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys. Implementation bool contains(Object element) { for (E e in this) { if (e == element) return true; } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/58162355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Rails using Websockets with Nginx and Unicorn? I am considering implementing chess (which needs websockets) with Rails, and in production deployment using Nginx as a reverse proxy to a bunch of Unicorn processes. In thinking about how to make that work led me to have the following questions: As far as I understand websockets are a persistent connection. Since everything goes through the reverse proxy Nginx how exactly would a Unicorn worker process maintain a websocket connection to a client browser? Would Nginx maintain state about which Unicorn process each browser websocket is connected to and act as a kind of intermediary? Does keeping a persistent websocket connection in a Unicorn process block the entire worker process? Is there a recommended way to implementing chess (with websockets) using Rails? A: Connecting synchronous processing by Unicorn with asynchronous delivery using nginx would imply some logic on nginx side that seems at least awkward to me. At most - impossible. There is a Railscast about Private Pub gem that makes use of Thin webserver. It's way more suitable for this task: it's asynchronous, it's able to handle many concurrent requests with event-based IO. So I suggest you replace Unicorn with Thin or install Thin side-by-side. Puma webserver might also be an option, however, I can't give more info about that. A: nginx won't do websockets. Are you sure you can't do this with AJAX? If you really need push capability you could try something built around the Comet approach: http://en.wikipedia.org/wiki/Comet_(programming) Faye is a pretty good gem for implementing comet in rails: http://faye.jcoglan.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/14906400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: HTML & case sensitive HTML in general is case insensitive. However I`ve noticed some escape names are case sensitive. For example , &Aacute; and &aacute;. Is &amp; case sensitive regarding HTML standard? A: Yes, reserved entities in HTML are case sensitive. Browsers will be nice to you and accept whatever you give them, but you should be using the proper casing. See also: https://www.w3.org/TR/html52/syntax.html#named-character-references A: From the below resource: https://www.tutorialrepublic.com/html-tutorial/html-entities.php Note: HTML entities names are case-sensitive! Please check out the HTML character entities reference for a complete list of character entities of special characters and symbols And From https://www.youth4work.com/Talent/html/Forum/117977-is-html-case-sensitive Generally, HTML is case-insensitive, but there are a few exceptions. Entity names (the things that follow ampersands) are case-senstive, but many browsers will accept many of them entirely in uppercase or entirely in lowercase; a few must be cased in particular ways. For example, Ç is Ç and ç is ç. Other combinations of upper and lower case are no good.
{ "language": "en", "url": "https://stackoverflow.com/questions/65741886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Finding the indexPath of a cell with a gesture recogniser in handler method I have a pan gesture recogniser on a UITableViewCell which is attached to a method called didPan(sender: UIPanGestureRecognizer). How can I use this method to determine which cell in a tableView this was activated from? A: A good way to do this is to add the gesture recognizer in the UITableViewCell subclass and also have a delegate property in that class as well. So in your subclass: protocol MyCustomCellDelegate { func cell(cell: MyCustomCell, didPan sender: UIPanGestureRecognizer) } class MyCustomCell: UITableViewCell { var delegate: MyCustomCellDelegate? override func awakeFromNib() { let gesture = UIPanGestureRecognizer(target: self, action: "panGestureFired:") contentView.addGestureRecognizer(gesture) } func panGestureFired(sender: UIPanGestureRecognizer) { delegate?.cell(self, didPan: sender) } } Then in cellForRowAtIndexPath you just assign you view controller as the cells delegate. A: You could add your pan gesture to the UITableViewCell in cellForRowAtIndexPath. Then extract the optional UITableViewCell and look up the indexPath in the tableView. Make sure you setup the UITableView as an IBOutlet so you can get to it in didPan: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PanCell", forIndexPath: indexPath) let panGesture = UIPanGestureRecognizer(target: self, action: "didPan:") cell.addGestureRecognizer(panGesture) return cell } func didPan(sender: UIPanGestureRecognizer) { // Sender will be the UITableViewCell guard let cell = sender.view as? UITableViewCell else { return } let indexPathForPan = tableView.indexPathForCell(cell) }
{ "language": "en", "url": "https://stackoverflow.com/questions/34316447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Enable/Disable command buttons in CK Editor I am new to CK Editor. I have a created a plugin that shows a button on UI. I want to disable and enable based on some condition. So I am using the following code to enable var command = editorInstance.getCommand('myButton') command.enable() and to disable var command = editorInstance.getCommand('myButton') command.disable() functionality-wise this works fine but it shows button in disable mode always on UI(always greyed button) Am I missing something? A: You can hide a button with CSS by using the class names that CKEditor creates for toolbar buttons. Try this (tested with v4.5.11): // hide document.getElementsByClassName('cke_button__myButton')[0].style.display = 'none'; //show document.getElementsByClassName('cke_button__myButton')[0].style.display = 'block';
{ "language": "en", "url": "https://stackoverflow.com/questions/43362761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to migrate Oracle View to Teradata I am working on migration project of Oracle to Teradata. The tables have been migrated using datastage jobs. How do I migrate Oracle Views to Teradata? Direct script copying is not working due to SQL statements difference of both databases Please help? A: The DECODE() Oracle function is available as part of the Oracle UDF Library on the Teradata Developer Exchange Downloads section. Otherwise, you are using the DECODE function in your example in the same manner in which the ANSI COALESCE() function behaves: COALESCE(t.satisfaction, 'Not Evaluated') It should be noted that the data types of the COALESCE() function must be implicitly compatible or you will receive an error. Therefore, t.satisfaction would need to be at least CHAR(13) or VARCHAR(13) in order for the COALESCE() to evaluate. If it is not, you can explicitly cast the operand(s). COALESCE(CAST(t.satisfaction AS VARCHAR(13)), 'Not Evaluated') If your use of DECODE() includes more evaluations than what is in your example I would suggest implementing the UDF or replacing it with a more standard evaluated CASE statement. That being said, with Teradata 14 (or 14.1) you will find that many of the Oracle functions that are missing from Teradata will be made available as standard functions to help ease the migration path from Oracle to Teradata.
{ "language": "en", "url": "https://stackoverflow.com/questions/10602085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linq to Entities - Subquery in the where statement This must be simple, but I've been searching for 2 hours, and can't find an answer. How do I write this in Linq to Entities: SELECT Reg4, Reg5, Reg6 FROM dbo.Table1 WHERE Reg1 = 15 AND Reg2 = ( SELECT MAX(Reg2) FROM dbo.Table2 WHERE Reg1 = 15); Is it possible to do it both in query expressions and method based syntaxes? Tks A: var r1 = 15; var q = from t in Context.Table1 where t.Reg1 == r1 && t.Reg2 == Context.Table2 .Where(t2 => t2.Reg1 == r1) .Max(t2 => t2.Reg2) select t; Easier still if you have a navigation/association from Table1 to Table2. But you didn't show that, so neither will I....
{ "language": "en", "url": "https://stackoverflow.com/questions/4694212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to store list of objects that have different properties in django db? It is straightforward to store in mysql data like [ { 'name': 'Object1', 'color': 'red', 'shape': 'ellipse' }, { 'name': 'Object2', 'color': 'green', 'shape': 'circle' } ] But what if object has different number of attributes (attributes are flat, they are not nested)? [ { 'name': 'Object1', 'color': 'red', 'shape': 'ellipse', 'eccentricity': 0.5 }, { 'name': 'Object2', 'color': 'green', 'shape': 'circle' 'radius': 5 } ] There are many attributes, so sub-classing is not solution. How do I handle it in mysql? Or if this is not possible, maybe postgresql? What about non-relational databases, what is the best to use? I need to make queries based on those attributes. Thanks in advance. A: There is JsonField in postgres which can be used for this kind of tasks. Also there is many apps for django which add JsonField that can work with mysql like django-extensions for example A: I'm not sure why you're avoiding subclassing, it's built pretty much for this purpose. The best way to do this is subclassing. For this example, it looks like you'd probably want to use the shape attribute as the major class. For example, you could create a Shape class thusly: class Shape(models.Model): color = models.CharField(max_length=20) class Meta: abstract = True class Circle(Shape): radius = FloatField() class Ellipse(Shape): eccentricity = FloatField() This would create two tables in your model, a Circle table with a color and radius column, as well as a Ellipse table with a color and a eccentricity column. If you really want to avoid subclassing for some reason, and you are using PostgreSQL, you can declare a JSONField (probably called attributes or something similar) of the different values. They would be harder to access programmatically, though. That would look like this: class Shape(models.Model): color = models.CharField(max_length=20) attributes = models.JSONField()
{ "language": "en", "url": "https://stackoverflow.com/questions/39991554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to install WSO2 Enterprise Mobility Manager Hi i am unable to install the WSO2 Enterprise mobility Manager platform , followed the installation provided in the website, java environment variable is set, but getting error as below [2014-05-02 11:27:41,150] ERROR {JAGGERY.config.app:js} - [2014-05-02 11:27:41,151] ERROR {JAGGERY.config.app:js} - [2014-05-02 11:27:41,151] ERROR {JAGGERY.config.app:js} - Database is not confgured or has not started up it is saying database is not configured, in the website they never mentioned about the database during the installation, can someone help me with this issue and als how to setup and database and run this platform. A: this issue arise with mysql database setup. please follow below listed link to sorted out that issue.. https://docs.wso2.org/display/EMM100/General+Server+Configurations there are few mistakes on documentation. On step 6, type exit; and Step 9. add given config values within <datasources> </datasources> A: Please check using MySQL console whether the admin has permission to access EMM_DB. Meanwhile you can try WSO2 EMM 1.1.0 http://wso2.com/products/enterprise-mobility-manager/
{ "language": "en", "url": "https://stackoverflow.com/questions/23421772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to depict non-grid 3D data as heat map? I have 3 columns of numbers x, y, z, where x and y are coordinates and z is intencity. I would like to represent the data as heat map in gnuplot. A: You can set dgrid3d to fill in missing values: set dgrid3d splot 'input.txt' with pm3d
{ "language": "en", "url": "https://stackoverflow.com/questions/12777936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android onTouch Listener Background Color Change I'm using onTouchListener to change the background color when the user's finger is down and change back to default when the user's finger is up. The problem is that when the user's finger is down the background color changes but if the user doesn't takes the finger up and starts scrolling the background color doesn't change to default. Please help. Below is my code: V.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()) { case MotionEvent.ACTION_DOWN: V.setBackgroundColor(Color.BLUE); break; case MotionEvent.ACTION_UP: V.setBackgroundColor(Color.BLACK); break; } return true; } }); I've also tried to return false but the result is the same A: There are a few different approaches you can use. You can look at MotionEvent.ACTION_MOVE and act when you receive that in your onTouch. You can look at MotionEvent.ACTION_OUTSIDE and see if they have left the region your are checking. You can also put a listener on your scroll View and change the background when it moves. Synchronise ScrollView scroll positions - android Alternately, you could use a gestureListener and detect that.
{ "language": "en", "url": "https://stackoverflow.com/questions/15908274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Encrypting Signed Data I'm submitting a file with the sensitive data to a 3rd party, could anyone explain what is the point in signing it and encrypting at the same time? Does just encrypting not verify my identity (the 3rd party requested it to be signed and then encrypted)? A: You sign with your private key. Signature is proof of origin, it proves that you were in possession of the private key therefore the data must be from you, and the data was not altered. You encrypt with the destination public key. This is to ensure that only the destination can decrypt it. As you see, the signature and encryption serve different purposes. A: Signing is putting your signature on a letter, and encrypting is putting the letter in an envelope. The envelope keeps other people from reading the letter. The signature proves that you wrote the letter. Additionally, you sign and then encrypt, in that order, because if you instead put the letter in the envelope first, and then sign the envelope, this doesn't really prove that you wrote letter. You could argue in front of a judge that you didn't get to see the letter before the envelope was sealed. Finally, you should not use the same key for both signing and encrypting. There are cryptographic reasons, but another, simpler reason is that the key that you use for encrypting can be held in escrow by other people (for example, the company you work for) to have access to the contents of all of your envelopes if needed, but the key you use for signing should only be given to people you would trust to legally sign in your place, as if a power of attorney.
{ "language": "en", "url": "https://stackoverflow.com/questions/32221764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you create in Netbeans a new PHP project with source files located in local network? I'm trying to create a new PHP project in a situation where our client gave us only remote desktop connection to to their files. How does it work usually in Netbeans: To put it simple when a project is created with external sources we can click in our project on the single file and upload and download it (via ftp). I'd like to be able to do this also on remote files located in a server which can be reached by our local network but which hasn't ftp installed. Extra details Until now we have been able to work normally with this setup by using Dreamweaver which allows to set in the server options an address located in the local network. I really would like to switch to Netbeans and being able to click on upload and download on the local files to sync with their server but I can't find a way to achieve this. There seem to be no option when creating a new project that allows this kind of setup. Selecting remote website seem to allow only ftp synch. On the other hand if i select "Local web site" i can select the files in the local network, but NB doesn't allow me to make a local copy of them. note 1: the server we're accessing hasn't ftp installed. note 2: the "copy files from sources folder to another location" isn't really an option for me since I'd like to keep separated my local copy from what's on the server (and this setup I think would just copy the files without giving me any control on them). note 3: creating a project with existing sources seem to allow only to have remote files reachable via ftp. A: It would be useful to have some versioning system (git, mercurial, svn...). Can you mount the network drive in Windows? (see here ). This would at least allow you to easily create project from existing sources (although working via network could be quite slow) One hacky way I can think of is to: * *mount the network drive as described above and map it to some letter, say Z *install local FTP server (e.g. FileZilla) *configure FileZilla FTP server to use the network drive as "ftp home" (aka the folder which FileZilla will use for saving files sent over FTP) - simply use Z:\ path to point to the mounted network drive mapped to letter Z *in NetBeans, create a new PHP project from remote server (where remote server is actually your local FileZilla server) In theory, this should work. A: Here is the fragment from NetBeans site: To set up a NetBeans project for an existing web application: Choose File > New Project (Ctrl-Shift-N on Windows/Cmd-Shift-N on OS X). Choose Java Web > Web Application with Existing Sources. Click Next. In the Name and Location page of the wizard, follow these steps: In the Location field, enter the folder that contains the web application's source root folders and web page folders. Type a project name. (Optional) Change the location of the project folder. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox and specify the location for the libraries folder. See Sharing Project Libraries in NetBeans IDE for more information on this option. (Optional) Select the Set as Main Project checkbox. When you select this option, keyboard shortcuts for commands such as Clean and Build Main Project (Shift-F11) apply to this project. Click Next to advance to the Server and Settings page of the wizard. (Optional) Add the project to an existing enterprise application. Select a server to which to deploy. If the server that you want does not appear, click Add to register the server in the IDE. Set the source level to the Java version on which you want the application to run. (Optional) Adjust the context path. By default, the context path is based on the project name. Click Next to advance to the Existing Sources and Libraries page of the wizard. Verify all of the fields on the page, such as the values for the Web Pages Folder and Source Package Folders. Click Finish.
{ "language": "en", "url": "https://stackoverflow.com/questions/21875211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to link 1st collection's item property with item from 2nd collection enter image description here Dim stations As New Collection Dim trains As New Collection For i = 1 To 60 Dim new_station As New station With new_station .id = S_stationsDataSet.Node_Table.Rows(i - 1)(0) .name = S_stationsDataSet.Node_Table.Rows(i - 1)(1) .t = S_stationsDataSet.Node_Table.Rows(i - 1)(4) .name_t = new_station.name & new_station.t .x = S_stationsDataSet.Node_Table.Rows(i - 1)(2) .y = S_stationsDataSet.Node_Table.Rows(i - 1)(3) End With stations.Add(new_station, new_station.name_t) Next Dim a, c, l, n As String Dim m, b As Single For i = 1 To 78 Step 2 a = S_trainsDataSet.T.Rows(1)(i) b = S_trainsDataSet.T.Rows(1)(i + 1) c = a & b l = S_trainsDataSet.T.Rows(2)(i) m = S_trainsDataSet.T.Rows(2)(i + 1) n = l & m Dim new_train As New train With new_train .id = S_trainsDataSet.T.Rows(0)(i) .src_t = S_trainsDataSet.T.Rows(1)(i + 1) .dst_t = S_trainsDataSet.T.Rows(2)(i + 1) .src = stations.Item(c) .dst = stations.Item(n) End With trains.Add(new_train, new_train.id.ToString()) Next For Each station In stations station.come = New Collection station.go = New Collection For Each train In trains If train.src.name_t = station.name_t Then station.go.add(train, train.id.ToString()) End If If train.dst.name_t = station.name_t Then station.come.add(train, train.id.ToString()) End If Next Next vb : property of item in the 1st item is item in the 2nd collection and vise versa .. when I delete an item .. it isn't updated as null in the other collection how can we link items of the two collections with each other A: After a very long wait I finally got some time over to finish this. Very sorry for the extremely long wait. I don't know if it's fully what you're looking for, but it will make the train and station classes work more together. As you have so many collections (as they're even within your classes) it's hard to update them all. I'd recommend you to use a Dictionary(Of TKey, TValue) and just having Boolean properties in your train classes. Your Dictionary would look like this: Dictionary(Of station, List(Of train)). First we'll need some extensions methods to later help us find and iterate through the stations and trains. We'll start with a function that will find a station by specifying it's name. Create a new Module and add this code within: ''' <summary> ''' Finds a station by it's name. ''' </summary> ''' <param name="StationCollection">The dictionary to look for the station in.</param> ''' <param name="Name">The name of the station to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindStationByName(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal Name As String) As station Name = Name.ToLower() 'ToLower() provides case-insensitive checking. 'Iterating through a Dictionary requires iterating through it's keys, as it's not index based. For Each k As station In StationCollection.Keys If k.name_t.ToLower() = Name Then Return k End If Next Return Nothing End Function Then we need extension methods for finding a train by it's id or it's name. We also an extension for finding all trains linked to a specific station. In the same module as above add: ''' <summary> ''' Finds a train by it's ID. ''' </summary> ''' <param name="TrainCollection">The list to look for the train in.</param> ''' <param name="Id">The ID of the train to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainById(ByRef TrainCollection As List(Of train), ByVal Id As Integer) As train For Each t As train In TrainCollection If t.id = Id Then Return t End If Next Return Nothing End Function ''' <summary> ''' Finds a train by it's name. ''' </summary> ''' <param name="TrainCollection">The list to look for the train in.</param> ''' <param name="TrainName">The name of the train to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainByName(ByRef TrainCollection As List(Of train), ByVal TrainName As String) As train TrainName = TrainName.ToLower() For Each t As train In TrainCollection If t.name_t = TrainName Then Return t End If Next Return Nothing End Function ''' <summary> ''' Finds all trains linked to the specified station. ''' </summary> ''' <param name="StationCollection">The dictionary to look for the station in.</param> ''' <param name="StationName">The name of the station which's trains to find.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function FindTrainsByStation(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal StationName As String) As List(Of train) StationName = StationName.ToLower() For Each k As station In StationCollection.Keys If k.name_t.ToLower() = StationName Then Return StationCollection(k) End If Next Return Nothing End Function Finally we'll need an extension method to remove a train from all the stations. This extension method will be used by the RemoveAll() and RemoveAllByName() methods in the train class later. ''' <summary> ''' Removes a trains link from all stations. ''' </summary> ''' <param name="StationCollection">The dictionary of stations which's links to this train to remove.</param> ''' <param name="train">The train to remove.</param> ''' <param name="MatchName">If true, match by the train's name instead of it's ID.</param> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Sub RemoveTrainFromAllStations(ByVal StationCollection As Dictionary(Of station, List(Of train)), ByVal train As train, ByVal MatchName As Boolean) For Each k As station In StationCollection.Keys For i = 0 To StationCollection(k).Count - 1 Dim t As train = StationCollection(k)(i) If MatchName = False Then 'Wether to match against the train's name or id. If t.id = train.id Then t.Remove() End If Else If t.name_t = train.name_t Then t.Remove() End If End If Next Next End Sub Now onto your classes. Passing the Dictionary reference to your station and train classes can also help you create functions for checking which train belongs to which station, etc. By doing this you have the classes working together with the Dictionary, you can even make another wrapper class around this to reduce "messieness" even more. You will also need to override the Equals and GetHashCode methods in order for dictionaries and hash tables to be able to lookup your key correctly. This is just example code, so I haven't included your properties here: Public Class train Private StationCollection As Dictionary(Of station, List(Of train)) 'Storing the main dictionary. Private _parent As station ''' <summary> ''' Wether this train is departing or arriving. ''' </summary> ''' <remarks></remarks> Public Property Departing As Boolean = False ''' <summary> ''' The station that owns this train (multiple stations can own trains with the same names and IDs). ''' This is mainly used for internal functions. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property ParentStation As station Get Return _parent End Get End Property ''' <summary> ''' Initializes a new instance of the train class. ''' </summary> ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param> ''' <param name="ParentStation">The station that owns this train (multiple stations can own trains with the same names and IDs).</param> ''' <remarks></remarks> Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train)), ByVal ParentStation As station) Me.StationCollection = StationCollection Me._parent = ParentStation End Sub ''' <summary> ''' Removes this train from it's station. ''' </summary> ''' <remarks></remarks> Public Sub Remove() Me.StationCollection(ParentStation).Remove(Me) End Sub ''' <summary> ''' Removes this, and all other trains having the same ID as this, from all stations in the main dictionary. ''' </summary> ''' <remarks></remarks> Public Sub RemoveAll() Me.StationCollection.RemoveTrainFromAllStations(Me, False) End Sub ''' <summary> ''' Removes this, and all other trains having the same name as this, from all stations in the main dictionary. ''' </summary> ''' <remarks></remarks> Public Sub RemoveAllByName() Me.StationCollection.RemoveTrainFromAllStations(Me, True) End Sub 'the rest of your code... 'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two trains' id's. Public Overrides Function Equals(obj As Object) As Boolean Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(train) AndAlso DirectCast(obj, train).id = Me.id End Function Public Overrides Function GetHashCode() As Integer Return Me.id.GetHashCode() End Function End Class And the station class: Public Class station Private StationCollection As Dictionary(Of station, List(Of train)) 'Linking this station to the main Dictionary. ''' <summary> ''' Gets a list of trains arriving at this station. Modifying the returned list will NOT affect the main dictionary or it's stations. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property ArrivingTrains As List(Of train) Get Return Me.GetTrainsByType(False) End Get End Property ''' <summary> ''' Gets a list of trains departing from this station. Modifying the returned list will NOT affect the main dictionary or it's stations. ''' </summary> ''' <remarks></remarks> Public ReadOnly Property DepartingTrains As List(Of train) Get Return Me.GetTrainsByType(True) End Get End Property ''' <summary> ''' Gets all trains of the specified type that are linked to this station. ''' </summary> ''' <param name="Departing">Wether to get all departing trains or all arriving trains.</param> ''' <remarks></remarks> Private Function GetTrainsByType(ByVal Departing As Boolean) As List(Of train) Dim TrainList As List(Of train) = StationCollection(Me) 'Getting all trains for this station. Dim ReturnList As New List(Of train) For Each t As train In TrainList If t.Departing = Departing Then ReturnList.Add(t) End If Next Return ReturnList End Function ''' <summary> ''' Removes this station and all links to trains arriving or departing from it. ''' </summary> ''' <remarks></remarks> Public Sub Remove() For Each t As train In StationCollection(Me) 'Iterate though all the trains for this station. GetType(train).GetField("_parent", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).SetValue(t, Nothing) 'Use reflection to set the train's parent to Nothing. Next StationCollection.Remove(Me) End Sub ''' <summary> ''' Initializes a new instance of the station class. ''' </summary> ''' <param name="StationCollection">The main dictionary containing this train and it's station.</param> ''' <remarks></remarks> Public Sub New(ByRef StationCollection As Dictionary(Of station, List(Of train))) Me.StationCollection = StationCollection End Sub 'the rest of your code... 'Overriding Equals() and GetHashCode(), comparison will be performed by comparing two stations' names. Public Overrides Function Equals(obj As Object) As Boolean Return obj IsNot Nothing AndAlso obj.GetType() Is GetType(station) AndAlso DirectCast(obj, station).name_t = Me.name_t End Function Public Overrides Function GetHashCode() As Integer Return Me.name_t.GetHashCode() End Function End Class Adding new stations/trains When adding items to the dictionary you would first have to initialize a new station class, then you create new train classes where you point the ParentStation parameter to the station you just created. For example: Dim MainDictionary As New Dictionary(Of station, List(Of train)) 'Create the dictionary (only do this once, unless you need multiple of course). Dim new_station As New station(MainDictionary) 'Create a new station. new_station.name = "Station 1" MainDictionary.Add(new_station, New List(Of train)) Dim new_train As New train(MainDictionary, new_station) 'Create a new train. new_train.id = 3 new_train.name_t = "Train 1" new_train.Departing = True 'This train is leaving from the station. MainDictionary(new_station).Add(new_train) 'Add the train to the station. Extension methods The extension methods are used when... * *You want to find a specific station by it's name. For example: Dim st As station = MainDictionary.FindStationByName("Station 1") *You want to find a train by it's id or name. For example: Dim t As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainById(3) Dim t2 As train = MainDictionary.FindStationByName("Station 1").ArrivingTrains.FindTrainByName("Train 1") *Or when you want to get all trains from a specific station (by it's name). For example: Dim trains As List(Of train) = MainDictionary.FindTrainsByStation("Station 1") Overview of the methods, fields and properties: - The train class - StationCollection * *A private field holding the reference to your main dictionary of all stations. _parent * *A private field holding the station this train is "linked" to. Departing * *A public property indicating if this train is departing (leaving) or arriving (coming) ParentStation * *A public read-only property returning the value of _parent. Remove() * *Removes this train from the station it's linked to. RemoveAll() * *Removes this train, and all other trains having the same ID as this, from all stations in the main dictionary. RemoveAllByName() * *Same as RemoveAll(), but matches against the trains' names instead of their IDs. - The station class - StationCollection * *Same as in the train class. ArrivingTrains * *A read-only property returning all trains arriving at (coming to) this station. DepartingTrains * *A read-only property returning all trains departing (leaving) from this station. GetTrainsByType() * *A private method for getting arriving/departing trains. Used by the above properties. Remove() * *Removes this station and all links to arriving or departing trains (by nullifying their _parent field) that are in the main dictionary. Hope this helps! And sorry again for taking so long.
{ "language": "en", "url": "https://stackoverflow.com/questions/36607544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 2D Platformer multiple classes without code duplication I'm working on a 2D platformer in c#, as most people are, but I have got a decent start to the project I have a class called Player, I then handle all collision for that player as well as the scrolling of the blocks in the background within the gamescreen class. I have just added another player (as a different class in this case a warrior), but all of my collision is based around the players positions and velocity, how would I change the blocks movement and collision to be around the warrior's velocity and positions instead (without duplicating or creating quite a lot of code). Thanks for any help Sam. A: Inheritance is your friend. You should probably have a base Player class, or even something more low level than that. The base class implements the colision detection and movement code. Your Warrior and other player types should inherit that class and override different parts to change the behavior. A: My strategy works approximately like this: I have a Character class. It contains a HitboxSet. The HitboxSet exposes an active Hitbox. All my collision is done based on Hitbox instances. Depending on what kind of character I need, I pass in different sprites, hitboxes, movements, etc. The result is a high degree of flexibility, while allowing you to keep your concerns thoroughly separated. This strategy is known as Composition, and is widely considered superior to inheritance based strategies in almost all cases. The main advantage of this strategy over inheritance is the ability to mix and match components. If, one day, you decide that you need a new projectile that's smaller than a previous one, and moves in a sine pattern, you simply use a new sine movement. You can reuse such things infinitely, in any combination. You can do something like this with inheritance: a child class can override a method and do something differently. The problem is that you either keep adding new child classes with different combinations and end up with a terrifyingly complex tree, or you limit your options. In short, if something is naturally going to vary, as it almost certainly will in a game, those variations should be distinct classes that can be combined in different ways rather than mutually exclusive overrides.
{ "language": "en", "url": "https://stackoverflow.com/questions/22871495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return blank or zero when 'On Error Resume Next' leaves previous value in variable? I have VBA code that gets the stock price in a loop. There are stock symbols not found in this API source. It will result to error for those stocks. I'm using On Error Resume Next so the VBA code will continue to the next symbol. My problem is the symbol in error will return a stock price of the last stock symbol not in error. I would like to make the result blank or zero for the stock symbols in error. Current Result - the italicized symbols are those that are in error. Stock Symbol Price BDO 158.00 ABS 15.80 GREEN 1.87 ALHI 1.87 LAND 1.87 PLC 0.57 LBC 0.57 EVER 0.57 Desired Result - the italicized symbols those that are in error will result or will give return of 0 Stock Symbol Price BDO 158.00 ABS 15.80 GREEN 1.87 ALHI 0 LAND 0 PLC 0.57 LBC 0 EVER 0 Set myrequest = CreateObject("WinHttp.WinHttpRequest.5.1") myrequest.Open "Get", "http://phisix-api.appspot.com/stocks/" & symbol & ".json" myrequest.Send Dim Json As Object Set Json = JsonConverter.ParseJson(myrequest.ResponseText) i = Json("stock")(1)("price")("amount") ws.Range(Cells(n, 2), Cells(n, 2)) = i n = n + 1 On Error Resume Next Next X ws.Columns("B").AutoFit MsgBox ("Stock Quotes Refreshed.") ws.Range("B4:B" & lastrow).HorizontalAlignment = xlGeneral ws.Range("B4:B" & lastrow).NumberFormat = "#,##0.00" Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub A: Your code as it stands sets On Error Resume Next at the end of the first time through the loop, and from that point on ignores any and all errors. That's bad. The general method of using OERN should be Other non error causing code Optionally initialise variables in preparation for error trap On Error Resume Next Execute the instruction that might cause an error On Error GoTo 0 If (test if instruction succeeded) Then Process the result Else Optionally handle the error case End If A: You can always put a conditional check statement based on the error you receive for invalid stocks, if you are getting empty value in myrequest on invalid stock. You can write your logic like below and update price value to 0. If myrequest is Nothing Then 'For Invalid Stocks End or If myrequest.ResponseText = "" Then 'For Invalid Stocks End Let me know if it helps. Otherwise share the JSON response for both valid and invalid stocks. Update: Based on the value of myrequest.ResponseStatus for invalid response, update the <add-condition> condition in If statement according to your requirement. For Each X In rng Dim Json As Object Dim i symbol = X Set myrequest = CreateObject("WinHttp.WinHttpRequest.5.1") myrequest.Open "Get", "http://phisix-api.appspot.com/stocks/" & symbol & ".json" On Error Resume Next myrequest.Send On Error GoTo 0 Debug.Print myrequest.ResponseStatus If <add-condition> Then Set Json = JsonConverter.ParseJson(myrequest.ResponseText) i = Json("stock")(1)("price")("amount") Else i = 0 End If ws.Range(Cells(n, 2), Cells(n, 2)) = i n = n + 1 Next X
{ "language": "en", "url": "https://stackoverflow.com/questions/59550283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: convert Cartesian width and height to Isometric I'm trying to create an Isometric game in the SDL graphics library. When you render in SDL you require a source rectangle and a destination rectangle. The source rectangle is the portion of the texture you have loaded that you wish to render and the destination rectangle is the area on the screen you are rendering to. Rectangles simply consist of 4 properties, X position, Y position, Width, and Height. Now say I have a Cartesian destination rectangle with these coordinates: X=20, Y=10, Width=16, Height=16 Now say I wanted to convert this to Isometric. To convert the X and Y coordinates I would use: isometricX = cartX - cartY; isometricY = (cartX + cartY) / 2; Now what I don't understand is what I would do to convert the Cartesian Width and Height to Isometric Width and Height to create the illusion that the view port is being moved 45 degrees to one side and 30 degrees down, creating the Isometric look. EDIT: I'd like to clarify my question a little, so when I convert the Cartesian Coordinates to Isometric I change this:http://i.stack.imgur.com/I79yK.png to this:http://i.stack.imgur.com/ZCJg1.png. So now I am trying to figure out how to rotate the tiles so they all fit together and how I need to adjust the Height and Width to get this to happen. A: To start with you'll need these operations to convert to and from isometric coordinates: isoX = carX + carY; isoY = carY - carX / 2.0; carX = (isoX - isoY) / 1.5; carY = isoX / 3.0 + isoY / 1.5; right-angled corners in the top-left and bottom-right become 120 degrees, the other two corners become 60 degrees. the bottom-right corner becomes the bottom corner, the top-left corner becomes the top. this also assumes that y increases going up, and x increases going right (if your system is different, flip the signs accordingly). you can verify via substitution that these operations are eachothers inverse. for a rectangle you need 4 points transformed - the corners - as they will not be 'rectangular' for the purposes of SDL (it will be a parallelogram). this is easier to see numerically. first, assign the corners names of some sort. i prefer clockwise starting with the bottom-left - this coordinate shall be known as C1, and has an associated X1 and Y1, the others will be C2-4. C2 - C3 | | C1 - C4 then compute their cartesian coordinates... X1 = RECT.X; Y1 = RECT.Y; X2 = X1; // moving vertically Y2 = RECT.Y + RECT.HEIGHT; X3 = RECT.X + RECT.WIDTH; Y3 = Y2; // moving horizontally X4 = X3; // moving vertically Y4 = RECT.Y; and lastly apply the transform individually to each coordinate, to get I1, I2, I3, I4 coordinates... iX1 = X1 + Y1; iY1 = Y1 - X1 / 2.0; // etc and what you end up with is on-screen coordinates I1-4, that take this shape: I2 / \ I1 I3 \ / I4 But unlike this shoddy depiction, the angles for I4 and I2 will be ~127 deg, and for I1 and I3 it should be ~53 deg. (this could be fine-tuned to be exactly 60/120, and depends on the 2.0 factor for carX when computing isoY - it should be sqrt(3) rather than 2.0 but meh, close enough) if you use the inverse transform, you can turn back the I1-4 coordinates into C1-4, or locate a world coordinate from a screen coordinate etc. implementing a camera / viewport gets a little tricky if only at first but it's beyond what was asked so i won't go there (without further prodding)... (Edit) Regarding SDL... SDL does not appear to "play nice" with generalized transforms. I haven't used it but its interface is remarkably similar to GDI (windows) which I've played around with for a game engine before and ran into this exact issue (rotating + scaling textures). There is one (looks to be non-standard) SDL function that does both scaling and rotating of textures, but it does it in the wrong order so it always maintains the perspective of the image, and that's not what is needed here. Basic geometry will be fine, as you've seen, because it's fills and lines which don't need to be scaled, only positioned. But for textures... You're going to have to either write code to render the texture one pixel at a time, or use a combination of transforms (scale after rotate), or layering (drawing an alpha-masked isometric square and rendering a pre-computed texture) and so on... Or of course, if it's an option for you, use something suited for raw geometry and texture data like OpenGL / Direct3D. Personally I'd go with OpenGL / SFML for something like this. A: Unfortunately I cannot comment to ask for clarification so I must answer with a question: can you not convert all four points then from those points calculate the width and height from the transformed points? X=20, Y=10, Width=16, Height=16 as you've said isometricX = cartX - cartY; isometricY = (cartX + cartY) / 2; so isometricX1 = cartX1 - cartY1; isometricY1 = (cartX1 + cartY1) / 2; and isometricWidth = std::abs(isometricY - isometricY1) There's probably a more efficient route though but as I do not know Cartesian geometry I can't find that solution EDITisometricWidth found the distance between the two points not the width and hieght another note is you'd need opposite corners (yes I realize the other guy probably as a much better answer :P)
{ "language": "en", "url": "https://stackoverflow.com/questions/31577053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dynamic prop value in react? I want a dynamic prop value for react. I already have a list of Fruits, but my prop value should be Fruits[0] + 'prop' For example: ApplesProp index.js const ApplesProp = { Name: "Green", Age: 34 } const Fruits = ["Apples", "Pears", "Oranges"] <App prop={dynamic-fruit+'Prop'} /> Tried <App prop={Fruits[0]+'Prop'}/> but this results in passing the string: 'ApplesProp' not the ApplesProp object (i.e. Name: Green, Age: 34). A: Fruits[0]+'Prop' Adding a string to a string returns a string. To accomplish what you need, you can create an object with fruits as keys and props as values: const fruitVsProps = { Apples: ApplesProp // add more as you like } <App prop={fruitVsProps[Fruits[0]]} /> A: there is two way you can Do it. 1.better way use array.map() then pass to your props. let Fruits = ["Apples", "Pears", "Oranges"]; <ff> {Fruits.map((item)=>{<App props={item} /> })} </ff> 2.second way you can use literal template A: Create an object and add your object in that const props = { ApplesProp: { Name: "Green", Age: 34 } } const Fruits = ["Apples", "Pears", "Oranges"] console.log(props[Fruits[0]+'Prop']) and now you could use it like <App prop={props[Fruits[0]+'Prop']} /> A: To accomplish the above task you need to create an object with fruits as keys and props as values const AppleProps = {Name : "Green } const Fruits = {"Apples", "Banana"} const FruitsAndProps = { Apples: AppleProps } A: You need to consider passing your dynamic string inside backticks => `` instead of quotes and use eval() method to convert your string to variable (so that IDE knows you are refering to a variable not a string). The result should look like this: const ApplesProp = { Name: "Green", Age: 34 } const Fruits = ["Apples", "Pears", "Oranges"] console.log(eval(`${Fruits[0]}Prop`)) //the console returns an object. so passing it through props should be fine. <App prop={eval(`${Fruits[0]}Prop`)}/> Although there are cleaner ways to solve this, since i don't want to mess with your logic i come up with the above code.
{ "language": "en", "url": "https://stackoverflow.com/questions/70692145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Items not being found in search box even though they exist So basically I have a search box setup in Sheet 2 where I use a barcode scanner to scan the item IDs and when I hit search it populates the information about that item that is found in Sheet 1. I have 2 types of item IDs in the system, one which consists of letters and numbers and the other strictly numbers. The problem I am currently encountering is that when I scan the strictly number ID into my search box, it cannot find it, but it can find it if I just copy and paste the ID from sheet 1 into the search box. I feel as if it has something to do with formatting of my search, like maybe its just looking for text and when I copy and paste into the search box they are formatted as text? I'm not too sure but any insight would be greatly appreciated. Attached below is my code. Sub SearchBox() Dim lastrow As Long Dim i As Long, x As Long Dim count As Integer lastrow = Sheets("Charlotte Gages").Cells(rows.count, 1).End(xlUp).Row i = Sheets("Gages").Cells(rows.count, 1).End(xlUp).Row + 1 For x = 2 To lastrow If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then Sheets("Gages").Cells(i, 1).Resize(, 7).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(, 7).Value i = i + 1 count = count + 1 End If Next x If count = 0 Then MsgBox ("Cannot Find Gage, Please check Gage ID") End If End Sub A: Somewhere the text/value isn't equal. I inserted a msgbox in your code so you can see exactly what's being compared. UPDATED WITH TRUE/FALSE DISPLAYED IN MESSAGE BOX TITLE Sub SearchBox() Dim lastrow As Long Dim i As Long, x As Long Dim count As Integer lastrow = Sheets("Charlotte Gages").Cells(Rows.count, 1).End(xlUp).Row i = Sheets("Gages").Cells(Rows.count, 1).End(xlUp).Row + 1 For x = 2 To lastrow 'try with this to test Dim anSwer As Integer Dim TrueOrFalse As String TrueOrFalse = Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") anSwer = MsgBox("your value in Charlotte Gauges Cell " & Sheets("Charlotte Gages").Cells(x, 1).Address & " is """ & Sheets("Charlotte Gages").Cells(x, 1).Value & _ """ while your other value in cell " & Sheets("Gages").Range("A1").Address & " is """ & Sheets("Gages").Range("A1").Value & """. Continue?", vbYesNo, Title:=TrueOrFalse) If anSwer = vbNo Then Exit Sub End If 'End of test code, this can be deleted once you figure out your issue If Sheets("Charlotte Gages").Cells(x, 1) = Sheets("Gages").Range("A1") Then Sheets("Gages").Cells(i, 1).Resize(, 7).Value = Sheets("Charlotte Gages").Cells(x, 1).Resize(, 7).Value i = i + 1 count = count + 1 End If Next x If count = 0 Then MsgBox ("Cannot Find Gage, Please check Gage ID") End If End Sub A: So I figured out what was wrong. The number-only ID's were stored as text in Sheet 1, therefore not allowing my search box to find it. All I had to do was convert them all to numbers and it fixed everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/45359543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write If statement and For loop programatically with Robot Framework API I have been exploring Robot framework and came across this example which I am trying to use. This example works great except I wanted to try adding a for loop and if statement. I haven't even began the if statement yet as I am stuck with the for loop. Please may I have help to suggest how to construct a for loop and if statement. This is a basic attempt of a for loop to add at the end of the script to test: test.keywords.create('For', args=['1','IN','10'], type='for') error - TypeError: __init__() got an unexpected keyword argument 'flavor' The code below just shows i am trying to add basic for loop but compiles with above error from robot.api import TestSuite suite = TestSuite('Activate Skynet') suite.imports.library('OperatingSystem') test = suite.tests.create('Should Activate Skynet', tags=['smoke']) test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup') test.keywords.create('Environment V`enter code here`ariable Should Be Set', args=['SKYNET']) test.keywords.create('For', args=['1','IN','10'], type='for') origin - https://robot-framework.readthedocs.io/en/2.8.1/autodoc/robot.running.html test.keywords.create('Create List', args=['a', 'b', 'c'], assign=['@{list}']) for_kw = ForLoop(['${l}'], ['@{list}'], flavor='IN') for_kw.keywords.create('log', args=['${l}']) test.keywords.create() test.keywords.append(for_kw) A: UPDATE: With Robot Framework this has changed and became easier to do. Release note: Running and result models have been changed. * *TestSuite, TestCase and Keyword objects used to have keywords attribute containing keywords used in them. This name is misleading now when they also have FOR and IF objects. With TestCase and Keyword the attribute was renamed to body and with TestSuite it was removed altogether. The keywords attribute still exists but it is read-only and deprecated. *The new body does not have create() method for creating keywords, like the old keywords had, but instead it has separate create_keyword(), create_for() and create_if() methods. This means that old usages like test.keywords.create() need to be changed to test.body.create_keyword(). For examples check out this other answer: How to write FOR loop and IF statement programmatically with Robot Framework 4.0?. BEFORE Robot Framework 4.0: IF statement The if statement should be a Run Keyword If keyword with the arguments you need. It is a keyword like any other so you should list everything else in its args list. * *The condition. *The keyword name for the True branch. *Separately any args to the keyword for the True branch if there is any. Listed separately. * *The ELSE IF keyword if needed. *The ELSE IF condition. *The keyword name for the ELSE IF branch. *Separately any args to the keyword for the ELSE IF branch if there is any. Listed separately. * *The ELSE keyword. *The keyword name for the ELSE branch. *Separately any args to the keyword for the ELSE branch if there is any. Listed separately. from robot.api import TestSuite suite = TestSuite('Activate Skynet') test = suite.tests.create('Should Activate Skynet', tags=['smoke']) test.keywords.create('Run Keyword If', args=[True, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE']) test.keywords.create('Run Keyword If', args=[False, 'Log To Console', 'Condition was TRUE', 'ELSE', 'Log To Console', 'Condition was FALSE']) suite.run() This is how it looks like in the logs: FOR loop As for the for loop. It is a special keyword implemented by robot.running.model.ForLoop class that bases on the robot.running.model.Keyword class. Here is the constructor: It has a flavor parameter, which is the loop type to be say. So it is IN, IN RANGE, IN ZIP, etc. Now you instantiating a robot.running.model.Keyword which despite you could set its type to for, it won't have flavor attribute. So when you execute your code it will throw the error you see. It is because the ForRunner will try to access the flavor attribute. File "/usr/local/lib/python3.7/site-packages/robot/running/steprunner.py", line 52, in run_step runner = ForRunner(context, self._templated, step.flavor) AttributeError: 'Keyword' object has no attribute 'flavor' So you have to use the ForLoop class. Also I am using Robot Framework 3.1.2 so the errors might be different in my case but the approach should be the same. Here is how it should look like: from robot.running.model import ForLoop for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE') test.keywords.append(for_kw) No this will still fail with error: FOR loop contains no keywords. So you have to populate it like: for_kw.keywords.create('No Operation') The complete example: from robot.api import TestSuite from robot.running.model import ForLoop suite = TestSuite('Activate Skynet') test = suite.tests.create('Should Activate Skynet', tags=['smoke']) test.keywords.create('Log Many', args=['SKYNET', 'activated'], type='setup') test.keywords.create('Log', args=['SKYNET']) for_kw = ForLoop(['${i}'], ['10'], flavor='IN RANGE') for_kw.keywords.create('No Operation') test.keywords.append(for_kw) suite.run() If you run this it will only produce an output XML, you have to run rebot manually to have a log and report HTML file.
{ "language": "en", "url": "https://stackoverflow.com/questions/66366453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get total from table input as grand total in jquery I have a table that makes automatically 2 calculations: * *Calculation of numbers of days after the selection of date started and date end from two input date field with calendar, result is stored is field (days) *Multiplication of 3 fields (horse* days* price), result is stored ind field (total). There is a button that when we click on it a new row is added. How can i calculate the grand total of numbers of days and the grand total of the total to display the results in a row below the table? And i want to grasp the input values in post so that i store them in table using php. 1- table <table class='table'> <tr> <th class='th'>Nbr/horses</th> <th class='th'>dateStart</th> <th class='th'>dateEnd</th> <th class='th'>Nbr/days</th> <th class='th'>Price</th> <th class='th'>Total</th> </tr> <tr> <td class='td'><input type='number' min='1' name='horse' class='horse'/></td> <td class='td'><input type='date' name='dateStart' class='datepicker dateStart'/></td> <td class='td'><input type='date' name='dateEnd' class='datepicker dateEnd'/></td> <td class='td days'><input type='text' name='days'/>0</td> <td class='td'><input type='number' min='1' name='price' class='price'/></td> <td class='td total'> <input type='text' name='total1'/></td> <td class='td'><button type='button' class='button'>+</button></td> </tr> 2- functions let update = function(lineNode){ let dateStart = $(lineNode).find('.dateStart').datepicker('getDate'); let dateEnd = $(lineNode).find('.dateEnd').datepicker('getDate'); let days = Math.floor( (dateEnd - dateStart) / (3600*24*1000) ); days = days >= 0 ? days : 0; $( lineNode ).find('.days').text( days ); let horse = parseInt( $(lineNode).find('.horse').val() ); let price = parseInt( $(lineNode).find('.price').val() ); let total = horse * days * price; $( lineNode ).find('.total').text( total+' €' ); } // add line after click let addRow = function(lineNode){ let clone = lineNode.cloneNode(true); $(clone).insertAfter(lineNode); reloadEffects(); } let reloadEffects = function(){ $('.hasDatepicker').removeClass('hasDatepicker').attr('id', ''); $('.datepicker').datepicker(); $('.horse, .price, .datepicker').change( e => { update(e.target.parentNode.parentNode); }); $('.button').click( e => { addRow(e.target.parentNode.parentNode); }); }; // Start reloadEffects(); A: for the total var sum = 0; $(".total").each(function(index,value){ sum = sum + parseFloat($(this).find('input[name="total1"]').val()); }); //Sum in sum variable console.log(sum); Apply the same for days ! Working Fiddle : Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/40952242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bad performance of MobileVLCKit? I have i problem. I builded MobileVLCKit and use in my project. All works, but video playing has bad performance (lagging). Where is the problem? Console says only: creating player instance using shared library shader program 1: WARNING: Output of vertex shader 'TexCoord1' not read by fragment shader WARNING: Output of vertex shader 'TexCoord2' not read by fragment shader Thanks! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/32796990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Collapsing multiple navbar bootstrap I have followed this example http://jsfiddle.net/rDN3P/98/ to create a collapsing navbar. It is working fine as long as I have one level in my menu. The collapsing seems not to work if I have multiple level of menu. In this example, if you open the collapsible menu and click on the second 'dropdown2' item in the menu you will know what I mean. This structure is the issue I assume <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Dropdown2 <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action sub</a></li> </ul> </li> A: Solved: jsfiddle Based on this answer to add the third level menu with a little modification of the js code to close the third level menu on click: $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) { // Avoid following the href location when clicking event.preventDefault(); // Avoid having the menu to close when clicking event.stopPropagation(); // If a menu is already open we close it if($(this).parent().hasClass('open')){ $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open'); }else{ // opening the one you clicked on $(this).parent().addClass('open'); var menu = $(this).parent().find("ul"); var menupos = menu.offset(); if ((menupos.left + menu.width()) + 30 > $(window).width()) { var newpos = - menu.width(); } else { var newpos = $(this).parent().width(); } menu.css({ left:newpos }); } }); A: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-submenu"> <a href="#"> Dropdown2 </a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action sub</a></li> </ul> </li> The nesting should be done properly I guess, with the correct classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/35889153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the CURRENT official/recommended MIME type for Javascript? I need to know what could be the correct current/future proof Javascript MIME type. References RFC 4329- April 2006, seems to say text/javascript is obsolete and recommends to use application/javascript : Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". HTML Living Standard — Updated 2 July 2019 I guess says text/javascript is fine : The term "JavaScript" is used to refer to ECMA-262, rather than the official term ECMAScript, since the term JavaScript is more widely known. Similarly, the MIME type used to refer to JavaScript in this specification is text/javascript, since that is the most commonly used type, despite it being an officially obsoleted type according to RFC 4329. [RFC4329] So at this point text/javascript is correct? Internet Draft - ECMAScript Media Types Updates to RFC4329, which is said to expire on December 21, 2019, says This document updates the existing media types for the ECMAScript programming language. It supersedes the media types registrations in [RFC4329] for "application/javascript" and "text/javascript". application/javascript - Intended usage: OBSOLETE The first version of the same draft on October 7, 2017, also says text/javascript has been moved intended usage from OBSOLETE to COMMON. Also MDN - Incomplete list of MIME types mention JavaScript MIME type ad text/javascript Question Part 1. What would be the correct MIME type at present/after December 21, 2019, if the draft expires/does not expire? Part 2. Should the drafts be followed before they are finalized? PS : This is NOT a duplicate of the following questions. I have gone through most of the main discussions in these questions. * *text/javascript vs application/javascript ~ 5+ years old. *When to use the JavaScript MIME type application/javascript instead of text/javascript? ~ 8+ years old. *When serving JavaScript files, is it better to use the application/javascript or application/x-javascript - 10+ years old *What is the javascript MIME type for the type attribute of a script tag? ~ 10+ years old.
{ "language": "en", "url": "https://stackoverflow.com/questions/56868320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unable to retrieve HTML form data running on Localhost:port python I am running a simple form input on my localhost:port using socket programming. Currently, I have a form running on my chrome, just a text box on localhost:2333, I am able to see the text box input on my wireshark like this The input message I typed is testesest. After which, I put the <form action="http://localhost:2333"> such that the entered form data can flow back to my localhost:port. However, my 2nd r= recv(1024)is not receiving anything. import socket import sys import os Addr = '' PORT = 2333 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((Addr, PORT)) s.listen() The above is the standard part. while(1): try: print("waiting for connection") conn, address = s.accept() print("New client connected from IP address {} and port number {}".format(*address)) received = conn.recv(1024) #print("Request received") #This is what i am hosting #A webpage with a form conn.send(b'\r\n') #This is the webpage content #The code will stuck here at recv print("Waiting for form input from client") r = conn.recv(1024) print(r.decode()) print("Form input received") print("HTTP response sent") except KeyboardInterrupt: conn.close() s.close() conn.close() s.close() break Can I get some help please? A: Input data sent via GET is attached to the URI (/?work=<data>), which is sent as a new request: import socket import sys import os Addr = '' PORT = 2333 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((Addr, PORT)) s.listen() while (1): try: print("waiting for connection") conn, address = s.accept() print( "New client connected from IP address {} and port number {}".format( *address ) ) request = conn.recv(1024) print("Request received") method, uri, _ = request.decode().split(' ', 2) print(method, uri) #This is what i am hosting #A webpage with a form response = "" conn.send(b'HTTP/1.1 200 OK\r\n') conn.send(b'Content-Type: text/html\r\n') conn.send(b'Host: localhost:2333\n') conn.send(b'\r\n') if uri == '/': response = """<html> <body><form action="http://localhost:2333/" method="GET"> <input type="text" name="work"></form></body> </html>""" elif uri.startswith('/?work'): response = f"<html><body><h2>recevied: {uri[uri.find('/?work=')+7:]}</h2></body></html>" conn.send(response.encode()) conn.send(b"\r\n") print("Form input received") #print("HTTP response sent") except KeyboardInterrupt: conn.close() s.close() #conn.close() #s.close() #break Out: waiting for connection New client connected from IP address 127.0.0.1 and port number 55941 Request received GET /?work=TestInput <html><body><h2>recevied: TestInput</h2></body></html> Form input received waiting for connection ... Note: You might want to have a look at the protocol specs and/or use any existing library to get rid of this low level stuff. A: Whenever we submit any form, browser makes new http request instead of using the existing connection, so you need to handle it in new http request/connection. Another thing is, r = conn.recv(1024) is not letting the current connection close, that's why pressing enter in textfield is also not working.
{ "language": "en", "url": "https://stackoverflow.com/questions/66950470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using WHERE with unknown amount of OR I have a table with some integer column A. I need to select rows where A equals 1 or 2 or 4 (for example), but i don't know how many values i need to compare. I have an array of values as input with unknown amount of values. I tried this: myTable.Where(x=> myArray.Contains(x.A)) but it doesn't work (i also tried Any) Then i tried to build SQL query with foreach cycle and then use .FromSqlRaw() but it throws an exception: 'FromSqlRaw' or 'FromSqlInterpolated' was called with non-composable SQL and with a query composing over it.
{ "language": "en", "url": "https://stackoverflow.com/questions/67196421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Performance groupBy I have a code similar to this: df = transformation(df) df = df.groupBy("f1").agg(agg1, agg2, agg3) df.collect() The aggregation functions do not contain any window (we could assume they are the F.sumof three different fields). Is there any case in which the operations in the method transformation are performed more than once if there is nothing persisted? A: You can use the link and perform groupby operation: * *https://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
{ "language": "en", "url": "https://stackoverflow.com/questions/61872435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ERROR: aggregate function calls cannot be nested I am trying to include one more column in my following query to show the average of two columns within. I am new to SQL and PostgreSQL, but referring the following link http://www.postgresql.org/docs/9.3/interactive/index.html select ad.col1, ad.col2, md.col3, ad.col4, mcd.col5, AVG(md.col3/mcd.col4) as cb from month_date as md JOIN active_date as ad ON ad.col1=md.col1 AND ad.col2=md.col2 JOIN mdata1 as mcd ON mcd.col1=md.col1 AND mcd.col2=md.col2; but I am getting the following error while performing the same ERROR: aggregate function calls cannot be nested LINE 1: ...col2,md.col3,ad.col4,mcd.col5, AVG(md.col3/m... ^ ********** Error ********** ERROR: aggregate function calls cannot be nested SQL state: 42803 Character: 77 can anyone guide where am I doing wrong and what I need to correct to make it work. Output needed: col1 | col2 | col3 |col4 | col5| cb| where cb is average column of other two columns. Any help would be appreciated. [EDIT] Tried to Group By but still getting the same error, can anyone correct me what wrong I am also doing in my below query select ad.col1, ad.col2, md.col3, ad.col4, mcd.col5, AVG(md.col3/mcd.col4) as cb from month_date as md JOIN active_date as ad ON ad.col1=md.col1 AND ad.col2=md.col2 JOIN mdata1 as mcd ON mcd.col1=md.col1 AND mcd.col2=md.col2 GROUP BY ad.col1,ad.col2,md.col3,ad.col4,mcd.col5; A: To use AVG() or any sort of aggregate functions in SQL, you need to have a GROUP BY for the other columns you're displaying. Think of it this way, when you SELECT a column, you display rows. When you show an average, you show a single output. You can't put rows and a single output together. You'll need to try something along the lines of: SELECT col1, col2, AVG(col3) FROM table1 GROUP BY col1, col2 A: I created a fiddle with your example, and you can see that the query as it is works. It is probably an error in a wrapping query, store procedure or function.
{ "language": "en", "url": "https://stackoverflow.com/questions/21250440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Observing Task exceptions within a ContinueWith There are various ways in which to observe exceptions thrown within tasks. One of them is in a ContinueWith with OnlyOnFaulted: var task = Task.Factory.StartNew(() => { // Throws an exception // (possibly from within another task spawned from within this task) }); var failureTask = task.ContinueWith((t) => { // Flatten and loop (since there could have been multiple tasks) foreach (var ex in t.Exception.Flatten().InnerExceptions) Console.WriteLine(ex.Message); }, TaskContinuationOptions.OnlyOnFaulted); My question: Do the exceptions become automatically observed once failureTask begins or do they only become observed once I 'touch' ex.Message? A: sample Task.Factory.StartNew(testMethod).ContinueWith(p => { if (p.Exception != null) p.Exception.Handle(x => { Console.WriteLine(x.Message); return false; }); }); A: They are viewed as observed once you access the Exception property. See also AggregateException.Handle. You can use t.Exception.Handle instead: t.Exception.Handle(exception => { Console.WriteLine(exception); return true; } );
{ "language": "en", "url": "https://stackoverflow.com/questions/11743756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Mongodb findOne - return value I need to fetch id of user from collection 'users' by calling a function and return it's value. fetchId = (name) => { User.findOne({name: name}, (err, user) => { return user._id; }); }; But this implementation returns null. What is the way to fix it? A: following your example, if you don't want to use promises, you can simply pass a callback from the caller and invoke the callback when you have the result since the call to mongo is asynchronous. fetchId = (name, clb) => { User.findOne({name: name}, (err, user) => { clb(user._id); }); }; fetchId("John", id => console.log(id)); Otherwise you can use the promise based mechanism omitting the first callback and return the promise to the caller. fetchId = name => { return User.findOne({name: name}).then(user => user.id); }; fetchId("John") .then(id => console.log(id)); A: A third way is a variation of suggestion #2 in @Karim's (perfectly good) answer. If the OP wants to code it as if results are being assigned from async code, an improvement would be to declare fetchId as async and await its result... fetchId = async (name) => { return User.findOne({name: name}).then(user => user.id); }; let someId = await fetchId("John"); console.log(id) edit For any method on an object -- including a property getter -- that works asynchronously, the calling code needs to be aware and act accordingly. This tends to spread upward in your system to anything that depends on caller's callers, and so on. We can't avoid this, and there's no syntactic fix (syntax is what the compiler sees). It's physics: things that take longer, just take longer. We can use syntax to partially conceal the complexity, but we're stuck with the extra complexity. Applying this to your question, say we have an object representing a User which is stored remotely by mongo. The simplest approach is to think of the in-memory user object as unready until an async fetch (findOne) operation has completed. Under this approach, the caller has just one extra thing to remember: tell the unready user to get ready before using it. The code below employs async/await style syntax which is the the most modern and does the most to conceal -- but not eliminate :-( -- the async complexity... class MyMongoUser { // after new, this in-memory user is not ready constructor(name) { this.name = name; this.mongoUser = null; // optional, see how we're not ready? } // callers must understand: before using, tell it to get ready! async getReady() { this.mongoUser = await myAsyncMongoGetter(); // if there are other properties that are computed asynchronously, do those here, too } async myAsyncMongoGetter() { // call mongo const self = this; return User.findOne({name: self.name}).then(result => { // grab the whole remote object. see below self.mongoUser = result; }); } // the remaining methods can be synchronous, but callers must // understand that these won't work until the object is ready mongoId() { return (this.mongoUser)? this.mongoUser._id : null; } posts() { return [ { creator_id: this.mongoId() } ]; } } Notice, instead of just grabbing the mongo _id from the user, we put away the whole mongo object. Unless this is a huge memory hog, we might as well have it hanging around so we can get any of the remotely stored properties. Here's what the caller looks like... let joe = new MyMongoUser('joe'); console.log(joe.posts()) // isn't ready, so this logs [ { creator_id: null } ]; await joe.getReady(); console.log(joe.posts()) // logs [ { creator_id: 'the mongo id' } ];
{ "language": "en", "url": "https://stackoverflow.com/questions/53287110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Overwrite data frame value I have two data frame df and ddff df data frame have 3 row and 5 columns import pandas as pd import numpy as np df = pd.DataFrame(np.array([[0,1,0,0,1], [1,0,0,1,0], [0,1,1,0,0]])) df 0 1 2 3 4 0 0 1 0 0 1 1 1 0 0 1 0 2 0 1 1 0 0 ddff data frame consist of neighbour columns of a particular columns which have 5 row and 3 column where the value of ddff data frame represent the column name of df ddff = pd.DataFrame(np.array([[3,2,1], [4,2,3], [3,1,4], [4,1,2], [2,3,1]])) ddff 0 1 2 0 3 2 1 1 4 2 3 2 3 1 4 3 4 1 2 4 2 3 1 Now I need a final data frame where where df column neighbour's set to 1 (overwrite previous value) expected output 0 1 2 3 4 0 0 1 1 1 0 1 1 0 0 1 0 2 0 1 1 0 0 A: You can filter the relevant column numbers from ddff, and set the values in those columns in the first row equal to 1 and set the values in the remaining columns to 0: relevant_columns = ddff.loc[0] df.loc[0,relevant_columns] = 1 df.loc[0,df.columns[~df.columns.isin(relevant_columns)]] = 0 Output: 0 1 2 3 4 0 0 1 1 1 0 1 1 0 0 1 0 2 0 1 1 0 0 A: You can use: s = ddff.loc[0].values df.loc[0] = np.where(df.loc[[0]].columns.isin(s),1,0) >>> df 0 1 2 3 4 0 0 1 1 1 0 1 1 0 0 1 0 2 0 1 1 0 0 Breaking it down: >>> np.where(df.loc[[0]].columns.isin(s),1,0) array([0, 1, 1, 1, 0]) # Before the update >>> df.loc[0] 0 0 1 1 2 0 3 0 4 1 # After the assignment back 0 0 1 1 2 1 3 1 4 0
{ "language": "en", "url": "https://stackoverflow.com/questions/70285768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Azure Functions functionAppScaleLimit of 1 isn't working as expected to limit concurrency on Queue Trigger I have a Function App with multiple queue triggers set up and am trying to limit concurrency by setting functionAppScaleLimit to 1. After testing this, I'm getting timeouts because two queue triggers will execute at around the same time, but only one is allowed to do work while the other one waits. For example, I have two queue triggers: QueueTrigger1 and QueueTrigger2 that are executed when blobs are created in two separate places in Azure Storage. I only want one of the queue triggers to be able to run at a time. I've already set the batchSize parameter to 1 so only one message is processed at a time. Each queue trigger can take up to 8 minutes for the scripts to complete execution. If both triggers are executed at around the same time, one will complete and the other will time out and then retry with a successful completion. Here's an example log from QueueTrigger1: 2020-10-26 07:37:49.201 Executing 'Functions.QueueTrigger1' (Reason='New queue message detected on 'etl-queue-items-1'.', Id=<queue-trigger-1-id>) //processes work in Python 2020-10-26 07:45:49.472 Executed 'Functions.QueueTrigger1' (Succeeded, Id=<queue-trigger-1-id>, Duration=480291ms) And QueueTrigger2: 2020-10-26 07:37:56.922 Executing 'Functions.QueueTrigger2' (Reason='New queue message detected on 'etl-queue-items-2'.', Id=<queue-trigger-2-id>) //8 minutes later 2020-10-26 07:45:49.439 Python queue trigger function processed a queue item: //attempts to process work in Python 2020-10-26 07:47:56.927 Timeout value of 00:10:00 exceeded by function 'Functions.QueueTrigger2' (Id: '<queue-trigger-2-id>'). Initiating cancellation. 2020-10-26 07:47:56.987 Executed '{functionName}' ({status}, Id={invocationId}, Duration={executionDuration}ms) 2020-10-26 07:47:56.987 Executed 'Functions.QueueTrigger2' (Failed, Id=<queue-trigger-2-id><queue-trigger-2-id>, Duration=600043ms) It seems unfair that the 10 minute limit is being applied to QueueTrigger2 before it even starts doing any work. How can I ensure that each queue trigger runs independently so I can be sure not to exceed the 1.5GB memory limit and not have to rely on retries? Edit: I'm on the Linux Consumption plan so my functionTimeout is limited to only 10 minutes. A: You have already set functionAppScaleLimit to 1, another thing you should do is setting the batch size to 1 in host.json file according to this document : If you want to minimize parallel execution for queue-triggered functions in a function app, you can set the batch size to 1. This setting eliminates concurrency only so long as your function app runs on a single virtual machine (VM).
{ "language": "en", "url": "https://stackoverflow.com/questions/64533529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to populate large file list in c# DataGridView I have a program which fills a DGV with file details such as name, date etc, and also a few extra custom columns that give info about the files. This works fine until there is a huge amount of files in which case the DGV seems to get slower as it populates. From reading about DGV, it seems the best way to fill these with large amounts of data is to bind the contents to a database source. So, the question is, would the most effective way for me to do this be to parse the files (and fill in my own custom data) then write these to a temp database, then use this to fill the DGV? Or am I making heavy work of something much simpler? Thanks for any advice. A: You can speed up the responsiveness of a DGV by using VirutalMode http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx A: If you have a huge amount of rows, like 10 000 and more, to avoid performance leak - do the following before data binding: dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders dataGridView1.RowHeadersVisible = false; // set it to false if not needed after data binding you may enable it.
{ "language": "en", "url": "https://stackoverflow.com/questions/12216695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding parameters of a system of non-linear equations in R using BB package I am trying to solve a system of equation to find parameters (x[1] and x[2]) using BB package but R outputs Unsuccessful convergence precisely it is: Iteration: 0 ||F(x0)||: 469.829 iteration: 10 ||F(xn)|| = 0.5105992 iteration: 20 ||F(xn)|| = 0.05530002 $`par` [1] 26.2772128 -0.9905601 $residual [1] 0.01809358 $fn.reduction [1] 664.413 $feval [1] 31 $iter [1] 25 $convergence [1] 3 $message [1] "Failure: Error in function evaluation" Warning message: In dfsane(par = p0, fn = f3) : Unsuccessful convergence. Simburr.f1 <- function(n, tau) { u=runif(n) x<- runif(n) lambda = exp(1+x) y= (1/(u^(1/lambda))-1)^(1/tau) y } y = Simburr.f1(300,0.5) x = runif(300) f3 <- function(x) { n=300 x1 <- x[1] x2 <- x[2] F <- rep(NA, 2) F[1] <- n/sum(log(1+y^(x[1]))) F[2] <- n/-sum(log(y))+(x[2]+1)*sum((log(y)*y^x[1])/(1+y^x[1])) return(F) } p0 <- c(0.5,1) dfsane(par=p0, fn=f3)
{ "language": "en", "url": "https://stackoverflow.com/questions/51431652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why won't the browser cache my http response? I have a REST api developed with django-tastypie. I have a couple of resources that are quite heavy but are not mutable, so I would like the browser to cache them to avoid unnecesary requests. I've set the HTTP Expire header to a date far two years in the future, this is what the browser gets: HTTP/1.1 200 OK Date: Wed, 16 May 2012 17:29:33 GMT Server: Apache/2.2.14 (Ubuntu) Vary: Cookie,Accept-Encoding,User-Agent Expires: Tue, 06 May 2014 17:29:33 GMT Cache-Control: no-cache, public Content-Encoding: gzip Access-Control-Allow-Origin: * Content-Length: 1051 Keep-Alive: timeout=15, max=82 Connection: Keep-Alive Content-Type: application/json; charset=utf-8 I'm using jQuery.ajax to issue the request. The expires header looks good, but the request is made each time I refresh the page. A: This is your problem: Cache-Control: no-cache from the spec: This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests. A: If this content can change, try to use ifModified: true in the jQuery.ajax A: In your .ajax call, set the cache: attribute to true, like this: $.ajax({ url: postUrl, type: 'POST', cache: true, /* this should be true by default, but in your case I would check this*/ data: stuff });
{ "language": "en", "url": "https://stackoverflow.com/questions/10623654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is it possible to embed a blogger comment? I have tow questions * *is it possible to embed a blogger comment ? *how can I call blogger comments automatically . I wont to make like this code : <script src='www.exemple.com/feeds/IDscomments/comments/default?alt=json&amp;callback=showtopcomment&amp;max-results=5' type='text/javascript'> using like this : ex : data:comments.id data:comments.url ... I use this api <script style=text/javascript src="http://helplogger.googlecode.com/svn/trunk/recent comments widget.js"></script> <script style=text/javascript> var a_rc = 5; var m_rc = false; var n_rc = true; var o_rc = 100; </script> <script src=http://helplogger.blogspot.com/feeds/comments/default?alt=json-in-script&callback=showrecentcomments></script> <style type="text/css"> .rcw-comments a { text-transform: capitalize; } .rcw-comments { border-bottom: 1px dotted; padding-top: 7px!important; padding-bottom: 7px!important; } </style> thanks in advance A: First, web APIs can not be called as script source. The output from a web API is the data as a string. Because the web API does not know (and doesn't want to assume) how the data is being called, it just dumps it. That way a CURL request can handle it just as well as an AJAX. It is up to you to determine how best to request the data for your needs. The blogger API for comments is very well handled. Check it out. If you update your question with some code and specific questions, I am positive the community will help with specific help. SO answer on PHP CURL jQUery documentation on getJson() function
{ "language": "en", "url": "https://stackoverflow.com/questions/33679648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scalacheck: lift custom random generator Is it possible to lift custom generating function into Gen? For example, generating ObjectIds for mongo. import org.mongodb.scala.bson.ObjectId import org.scalacheck.Gen val genObjectId: Gen[ObjectId] = Gen.lift(() => new ObjectId) The only possible solution I've found is to hack the generator like: val genObjectId: Gen[ObjectId] = Gen.numChar.map(_ => new ObjectId) Generating ObjectIds using Gen.hexChar is irrelevant because: * *I need unique value each time *Mongo could treat some of the generated hex strings as invalid A: Gen.delay(Gen.const(new ObjectId)) delay's argument is by-name, so every attempt to generate a value will construct a new ObjectId.
{ "language": "en", "url": "https://stackoverflow.com/questions/66750158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Color Changing on click tracker I added a color on the first click and disabled the color on the second click. What I want to be able to do is when the color is already changed I would like to be able to change the color and add that color like as though it is on its first click. For example, I already clicked on a cell and now have a black color. I want to able to change the color from black to red immediately, but also keep my functionality of being to click on something twice to remove the color. Here is my project: https://codepen.io/frederickalcantara/pen/XVqZep let color = 1; cell.addEventListener('click', () => { if (color) { cell.style.backgroundColor = colorPicker.value; color = 0; } else { cell.style.backgroundColor = ""; color = 1; } }); A: You could just check if the color match the colorPicker value or not if (cell.dataset.color !== colorPicker.value) { cell.style.backgroundColor = colorPicker.value; cell.dataset.color = colorPicker.value; } else { cell.style.backgroundColor = ""; cell.dataset.color = "" } https://codepen.io/anon/pen/EoLELd?editors=0010 Reason to why I'm setting a dataset color here is because backgroundColor converts the hexadecimal from the colorPicker value to RGB so a check between the two won't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/48216656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular ui Tour - not scrolling I just implemented Angular Ui Tour (https://github.com/benmarch/angular-ui-tour) on my site, everything seems to work, except scrolling to the opened dialog. I created and started the tour like that: uiTourService.createDetachedTour('myTour'); this._uiTourService.getTourByName('myTour').start(); And the tour steps are defined like so: <div tour-step tour-step-title="Main Menu" tour-step-content="Navigate the site using this menu." tour-step-order="0" tour-step-placement="bottom-left" tour-step-belongs-to="myTour"></div> <p tour-step tour-step-title="second step" tour-step-content="this is the second step" tour-step-order="1" tour-step-placement="bottom" tour-step-belongs-to="myTour"></p> Everything is shown correctly, i also managed to use my keyboard to navigate (arrow keys), setting useHotkeys to true. But the scrolling thing won't work, even if I try to set scrollIntoView to true manually. Does anybody know, what the issue could be? A: I just run into this. The scrolling part is the angular-smooth-scroll's job (angular-ui-tour uses it properly). The minified version is the problematic, also it shows no error :/ So I switched to the source version (/dist/angular-smooth-scroll.min.js -> /lib/angular-smooth-scroll.js) and it's working just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/38054430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linker errors after upgrade to xcode 3.2.3 for iphone app I've just upgraded to XCODE 3.2.3 and upgraded my base sdk from 3.0 to 3.2 iphone sdk. After doing this I started getting a bunch of link errors with barely any info, here's what I got: ".objc_class_name_CATransition", referenced from: ".objc_class_name_NSObject", referenced from: ".objc_class_name_NSFileManager", referenced from: ".objc_class_name_NSString", referenced from: ".objc_class_name_NSError", referenced from: ".objc_class_name_CABasicAnimation", referenced from: ".objc_class_name_NSOperation", referenced from: ".objc_class_name_CJSONDeserializer", referenced from: ".objc_class_name_UIWindow", referenced from: ".objc_class_name_NSException", referenced from: ".objc_class_name_UIColor", referenced from: ".objc_class_name_CATransaction", referenced from: ".objc_class_name_CLLocationManager", referenced from: ".objc_class_name_MPMoviePlayerController", referenced from: ".objc_class_name_NSMutableSet", referenced from: ".objc_class_name_UIFont", referenced from: ".objc_class_name_NSFileHandle", referenced from: ".objc_class_name_MFMailComposeViewController", referenced from: ".objc_class_name_CAKeyframeAnimation", referenced from: ".objc_class_name_UIImage", referenced from: ".objc_class_name_UIApplication", referenced from: ".objc_class_name_UILabel", referenced from: ".objc_class_name_UIView", referenced from: ".objc_class_name_CLLocation", referenced from: ".objc_class_name_NSMutableString", referenced from: ".objc_class_name_CJSONSerializer", referenced from: ".objc_class_name_NSTimer", referenced from: ".objc_class_name_NSValue", referenced from: ".objc_class_name_NSMutableData", referenced from: ".objc_class_name_NSNumber", referenced from: "_objc_exception_match", referenced from: ".objc_class_name_UINavigationItem", referenced from: ".objc_class_name_UIViewController", referenced from: ".objc_class_name_NSMutableArray", referenced from: ".objc_class_name_UIScreen", referenced from: ".objc_class_name_NSHTTPCookieStorage", referenced from: ".objc_class_name_MKPinAnnotationView", referenced from: ".objc_class_name_NSNotificationCenter", referenced from: "_OBJC_CLASS_$_QWAdView", referenced from: ".objc_class_name_NSProcessInfo", referenced from: ".objc_class_name_UITableViewCell", referenced from: ".objc_class_name_CAAnimationGroup", referenced from: ".objc_class_name_NSInvocation", referenced from: ".objc_class_name_NSURL", referenced from: ".objc_class_name_NSSet", referenced from: "_objc_exception_extract", referenced from: ".objc_class_name_UISearchBar", referenced from: ".objc_class_name_NSMutableURLRequest", referenced from: ".objc_class_name_NSRunLoop", referenced from: ".objc_class_name_NSData", referenced from: ".objc_class_name_NSDate", referenced from: ".objc_class_name_UIBarButtonItem", referenced from: ".objc_class_name_UITableView", referenced from: ".objc_class_name_NSURLRequest", referenced from: ".objc_class_name_NSOperationQueue", referenced from: ".objc_class_name_UIActionSheet", referenced from: ".objc_class_name_UIDevice", referenced from: ".objc_class_name_MKMapView", referenced from: ".objc_class_name_UIToolbar", referenced from: ".objc_class_name_NSXMLParser", referenced from: ".objc_class_name_NSHTTPCookie", referenced from: ".objc_class_name_UIImageView", referenced from: ".objc_class_name_CAMediaTimingFunction", referenced from: ".objc_class_name_NSScanner", referenced from: "_objc_exception_try_exit", referenced from: ".objc_class_name_NSDateFormatter", referenced from: ".objc_class_name_UIAccelerometer", referenced from: "_objc_exception_try_enter", referenced from: ".objc_class_name_NSCharacterSet", referenced from: ".objc_class_name_UIScrollView", referenced from: ".objc_class_name_UIButton", referenced from: ".objc_class_name_UINavigationBar", referenced from: ".objc_class_name_UIAlertView", referenced from: ".objc_class_name_NSUserDefaults", referenced from: ".objc_class_name_NSThread", referenced from: ".objc_class_name_NSPropertyListSerialization", referenced from: "_OBJC_CLASS_$_GANTracker", referenced from: ".objc_class_name_NSMutableDictionary", referenced from: ".objc_class_name_CALayer", referenced from: ".objc_class_name_UIWebView", referenced from: ".objc_class_name_NSBundle", referenced from: ".objc_class_name_NSURLConnection", referenced from: ".objc_class_name_NSAutoreleasePool", referenced from: ".objc_class_name_UIPageControl", referenced from: ".objc_class_name_NSAssertionHandler", referenced from: ".objc_class_name_MKAnnotationView", referenced from: ".objc_class_name_NSDictionary", referenced from: ".objc_class_name_NSLocale", referenced from: ".objc_class_name_NSArray", referenced from: ".objc_class_name_UIActivityIndicatorView", referenced from: "_OBJC_CLASS_$_AdMobView", referenced from: Any ideas? UPDATE: Seems like 3rd party libraries are causing the issues. These include libraries for admob, quattro, and Google Analytics. Only admob has updated their libraries so will have to remove the other ones A: Same problem. Tons of link errors when compiling for simulator; device works fine. Checked frameworks as suggested by Sim but looked fine. Edit: All of the problems seem to be with pre-compiled 3rd party libraries (in my case that means the Facebook Three20.a library and Occipital's libRedLaserSDK.a). Anybody know if I need to use versions of those libraries recompiled for 4.0, or if there is there another fix? Edit2: And one more clue, which suggests some of the other posters are on the right track: in my project "Groups & Files" list, all of my frameworks appear in red text. Yet if I check any one of them, the target checkbox is checked. A: I don't know why this suddenly started happening when you upgraded, but these link errors mean that your link line is missing some frameworks. It would be very helpful to see the full compiler output (expand the transcript in Build Results to get this). Looks like QuartzCore, Foundation, MediaPlayer, UIKit and others are missing, based on the symbols which are undefined. I figured this out by searching for the missing symbols (e.g. "NSOperation") in the iPhone developer site. The documentation for each function lists the framework that defines the function. A: Check Frameforks is checked for the new build target. Select UIkit.framework -> Get Info and check general and targets tabs A: I would try reinstalling XCode. Backup your /Developer folder first then give these steps a go. From the terminal use: sudo /Developer/Library/uninstall-devtools --mode=all to uninstall XCode and the iPhone SDKs, then delete the /Developer folder after you've done this to ensure that XCode and the iPhone SDK have been cleanly removed from your system. Reinstall Xcode afterwards. A: I had this same problem a couple of days ago, but for me just restarting Xcode fixed it, I could build my app without any problems. I have no idea what caused this to happen in the first place, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/3090889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why this 10 threads always output the same thread name? I ran this code NUM = 0 def count(): global NUM NUM += 1 time.sleep(1) print(t.getName()+":"+"NUM is "+str(NUM)) for i in range(10): t = threading.Thread(target=count) t.start() The output is Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 Thread-10:NUM is 10 I know why the NUM is always 10, but why is the thread name always the same? Every thread runs print(t.getName()+":"+"NUM is "+str(NUM)); the t should not be the thread that gets the cpu time's one? I think the name should not be the same. When I changed to this NUM = 0 def count(): global NUM NUM += 1 name = t.getName() time.sleep(1) print(name+":"+"NUM is "+str(NUM)) for i in range(10): t = threading.Thread(target=count) t.start() It works as I expect: Thread-1:NUM is 10 Thread-3:NUM is 10 Thread-2:NUM is 10 Thread-4:NUM is 10 Thread-5:NUM is 10 Thread-7:NUM is 10 Thread-10:NUM is 10 Thread-9:NUM is 10 Thread-6:NUM is 10 Thread-8:NUM is 10 A: It's because you're referencing the global name t. By the time the sleeps end, the loop is over, and t remains bound to the last thread (the 10th thread) the loop created. In your alternative, the results aren't actually defined. There you reference the global t while the loop is still running, so it's likely to be bound to the most recent thread created - but doesn't have to be. Note: if you don't have convenient access to the thread object currently running, you can use threading.currentThread() to get it. Then threading.currentThread().getName() will return the name of the thread running it. A: Your function queries for a t, but no t is defined in the function: def count(): global NUM NUM += 1 name = t.getName() # use outer t time.sleep(1) print(name+":"+"NUM is "+str(NUM)) The fallback mechanism of Python thus will look for a t in the direct outer scope. And indeed, you assign to a t in the outer scope, so it will take that value. Now since you write t = ... in a for loop, that t changes rapidly. It is very likely that the for loop has already reached the last value - especially because of the threading mechanism of Python - before the first thread actually fetches that t. As a result, all the threads fetch the t referring to the last constructed thread. If we however rewrite the function to: NUM = 0 def count(): name = t.getName() # t fetched immediately global NUM NUM += 1 time.sleep(1) print(name+":"+"NUM is "+str(NUM)) I get: Thread-11:NUM is 10 Thread-12:NUM is 10 Thread-13:NUM is 10 Thread-14:NUM is 10 Thread-15:NUM is 10 Thread-17:NUM is 10 Thread-16:NUM is 10 Thread-19:NUM is 10 Thread-18:NUM is 10 Thread-10:NUM is 10 on my machine. Of course this does not guarantee that every thread will grab the correct thread, since it is possible that only later in the process, the thread will start working and fetches the t variable. A: You have the same problem for both the thread name and the count NUM: by the time you get to the first print statement, all 10 threads have been started. You have only one global variable t for the thread, and one global NUM for the count. Thus, all you see is the last value, that for the 10th thread. If you want separate values printed, you need to supply your code with a mechanism to report them as they're launched, or keep a list through which you can iterate. A: I advice you to try this: NUM = 0 def count(): global NUM NUM += 1 num = NUM name = t.getName() time.sleep(1) print("t.getName: " + t.getName() + ", name: " + name + ":" + ", NUM: " + str(NUM) + ", num: " + str(num)) for i in range(10): t = threading.Thread(target=count) t.start() Result: t.getName: Thread-10, name: Thread-10:, NUM: 10, num: 10 t.getName: Thread-10, name: Thread-6:, NUM: 10, num: 6 t.getName: Thread-10, name: Thread-3:, NUM: 10, num: 3 t.getName: Thread-10, name: Thread-5:, NUM: 10, num: 5 t.getName: Thread-10, name: Thread-4:, NUM: 10, num: 4 t.getName: Thread-10, name: Thread-9:, NUM: 10, num: 9 t.getName: Thread-10, name: Thread-7:, NUM: 10, num: 7 t.getName: Thread-10, name: Thread-2:, NUM: 10, num: 2 t.getName: Thread-10, name: Thread-1:, NUM: 10, num: 1 t.getName: Thread-10, name: Thread-8:, NUM: 10, num: 8 t.getName() is a function call, which is a reference. By the time the print functions reached the console, t references to the latest thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/44641733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Printing numbers I am writing a program to display as below when n=3 1 2 3 7 8 9 4 5 6 when n=5 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 6 7 8 9 10 my program is #include<stdio.h> #include<conio.h> int main() { int n=5,r=1,c=1,i=1,mid=0; if(n%2==0) mid=(n/2); else mid=(n/2)+1; printf("mid = %d\n",mid); while(r<=n) { while(c<=n) { printf("%d ",i); c++; i++; } r++; if(r<=mid) i=i+n; else i=i-(2*n); printf("\n"); c=1; } getch(); return 0; } when I give n=3, I am getting my expected output. but when I give n=5 I am getting as below 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 11 12 13 14 15 Could someone please help how to achieve expected output. A: Using you code the solution is #include<stdio.h> #include<conio.h> int main() { int n=5,r=1,c=1,i=1,mid=0; int maxRow = n; if(n%2==0){ mid=(n/2); maxRow--; } else mid=(n/2)+1; printf("mid = %d\n",mid); while(r<=maxRow) { while(c<=n) { printf("%d ",i); c++; i++; } r++; if(r<=mid) i=i+n; else if (r >= n) i=n+1; else i=i-((1+(r-mid))*n); printf("\n"); c=1; } getch(); return 0; } As you can see: * *the i=i-(2*n); is changed. What you wrote wasn't generic, but specific for the n=3 case. *I added else if (r >= n). *Last thing you must use a specific variable for the outer while because of n must be decremented if n is even. Some tips: * *Give to your variables explanatory names *To make your code more readable declare variables 1 per line, if you want to init them. *Live empty lines between code chunks. int main () { int squareDim=5; int row=1; int col=1; int valueToPrint=1; int mid=0; int maxRow = squareDim; if(squareDim%2==0) { mid=(squareDim/2); maxRow--; } else { mid=(squareDim/2)+1; } printf("mid = %d\n",mid); while(row<=maxRow) { while(col<=squareDim) { printf("%d ",valueToPrint); col++; valueToPrint++; } row++; if(row<=mid) { valueToPrint=valueToPrint+squareDim; } else if (row >= squareDim) { valueToPrint=squareDim+1; } else { valueToPrint=valueToPrint-((1+(row-mid))*squareDim); } printf("\n"); col=1; } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/32525493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Return String value from Activity to a Fragment I'm trying to figure out how to get the value from a method in the Activity class into the Fragment of that Activity. I have set up three files: AsyncTaskActivity.java, EventsList.java, and ListFragment.java. AsyncTaskActivity.java has the method getOtakuEvents() that returns a string value. package com.leobee; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.android.maps.MapActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class AsyncTasksActivity extends MapActivity implements EventsList{ LocationManager locationManager; String stxtLat ; String stxtLong; double pLong; double pLat; String x; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Acquire a reference to the system Location Manager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { pLong=location.getLongitude(); pLat=location.getLatitude(); stxtLat=Double.toString(pLat); stxtLong=Double.toString(pLong); Toast.makeText(AsyncTasksActivity.this, stxtLong, Toast.LENGTH_SHORT).show(); Toast.makeText(AsyncTasksActivity.this, stxtLat, Toast.LENGTH_SHORT).show(); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; // Register the listener with the Location Manager to receive location updates locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); DownloadWebPageTask task = new DownloadWebPageTask(); double numRand = Math.floor(Math.random()*1000); String userLat= stxtLat; String userLong= stxtLong; task.execute(new String[] { "http://www.leobee.com/otakufinder/scripts/geoloco.php?userLat="+userLat+"&userLong="+userLong+"&randNum="+numRand }); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); //HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar"); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } @Override protected void onPostExecute(String result) { x =result; Log.v("values",x); } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } @Override public String getOtakuEvents() { // TODO Auto-generated method stub return x; } } EventsList.java is an interface that helps the classes to know getOtakuEvents() value is available to them. package com.leobee; public interface EventsList { String getOtakuEvents(); } Lastly, the fragment has a method that gets the value from the getOtakuEvents() called getStringfromActivity(). package com.leobee; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; // shows list view of items if fragment is not null this class will also show the item selected form Detailfragment class public class ListFragment extends android.app.ListFragment{ String events; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String events =getStringfromActivity(); } public String getStringfromActivity() { String i; i=EventsList.getOtakuEvents(); return i; } /* public String getStringfromActivity() { return getActivity().getOtakuEvents(); }*/ @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,values); setListAdapter(adapter); } @Override public void onListItemClick(ListView l, View v, int position, long id){ String item =(String)getListAdapter().getItem(position); DetailFragment fragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment); if (fragment != null && fragment.isInLayout()){ fragment.setText(item); }else{Intent intent = new Intent(getActivity().getApplicationContext(), DetailActivity.class); intent.putExtra("value", item); startActivity(intent); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.e("text","config change detail fragment"); // Checks the orientation of the screen } } I get error: Cannot make a static reference to the non-static method getOtakuEvents() from the type EventsList. This is confusing because I did not declare static type in getOtakuEvents() or in the fragment. Alternatively, I also tried this version of the method in the fragment : public String getStringfromActivity() { return getActivity().getOtakuEvents(); } I am getting an error :The method getOtakuEvents() is undefined for the type Activity. This is baffling to me because the method is defined in the parent activity. Specifically, I need to be able to send the string value from the activity to the fragment. I am trying to do it using an interface or the getActivity method. Can you look over my code and let me know where I'm going wrong and how to fix it? I've been at this for the majority of 2 days and can't seem to figure it out. Any help is appreciated. A: You could probably store and retrieve it from SharedPreferences
{ "language": "en", "url": "https://stackoverflow.com/questions/10036694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make a real purchase from my webapp from localhost:4200? I am using stripe checkout in an angular app. When I make a purchase from my app running in localhost using my stripe test account, everything works fine. When I switch to a production client token, my request is denied by stripe. The message says that localhost is not whitelisted for my account. I went to my account dashboard and tried to add localhost but it wouldn't allow it. Does anyone know how to make this happen. I want to do some testing on my localhost making real purchases before i publish my app. A: Stripe Checkout with your live mode keys only works over HTTPS (or security reasons [0]), it works in localhost only in test mode. You should swap in your live mode keys only when you are ready for production and have your web page/app deployed. There is a handy checklist that you can reference so that you're meeting all the requirements before going live [1] [0] https://stripe.com/docs/security#tls [1] https://stripe.com/docs/payments/checkout/live
{ "language": "en", "url": "https://stackoverflow.com/questions/60662685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Timer in winform with an iteration foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2 { makeSelfMoves = replay[item.Key]; codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]); PrintPieces(codeFile.PieceState()); // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a); } i want to execute this whole iteration, that i responsible for a game replay, in 1 second intervals. i put a timer in my form and set it to 1 second (this should make the pieces to be moved at 1 second intervals). i made an event, and before the loop i put the statement, timer1.enabled=true. The iteration will reach the end in a quick manner.. how do you use a timer to set iteration to execute each second using the timer? public void ReplayGame() { Class2.replayIsOn = true; replay=serializeMeh.giveBackDictionary(); int[] makeSelfMoves=new int[4]; //Timer t = new Timer(); //t.Interval = 1000; //t.Tick += timer1_Tick; //t.Enabled = true; //t.Start(); if (backgroundWorker1.IsBusy != true) { // Start the asynchronous operation. backgroundWorker1.RunWorkerAsync(); } //foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2 //{ // makeSelfMoves = replay[item.Key]; // codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]); // PrintPieces(codeFile.PieceState()); // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] ); //} } The above method is activated if i want a replay. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; int[] makeSelfMoves = new int[4]; foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2 { makeSelfMoves = replay[item.Key];// delivers an array of a single move location startrow,startcolumn,endrow,endcolun codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]); PrintPieces(codeFile.PieceState());// prints the code on the board System.Threading.Thread.Sleep(1000); } } it does the work, but the problem that i had is after the loop finishes, the pieces that existed disappear. is it because of the background worker, cause without it , i have no pieces disappear at the end of the process. The second time that i activate the method, it happens A: Run it in a background thread and put Thread.Sleep(1000) in the loop. This way it will be time based and not freeze your app. A: We need to see more of your code, but it's pretty simple: using System.Windows.Forms; SomeMethod(...) { Timer t = new Timer(); t.Interval = 1000; t.Tick += t_Tick; t.Enabled = true; t.Start(); } void t_Tick(...) { foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2 { makeSelfMoves = replay[item.Key]; codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]); PrintPieces(codeFile.PieceState()); // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a); } } A: Personally, I would put this into a seperate thread and use Thread.sleep(). In combination with accessing GUI-elements, I would suggest a BackgroundWorker instead (see MSDN, easy to implement). If you insist in using a timer, I would suggest you use the suggestion of 'Ed S.'. The timer could also be placed on your form, instead of creating it in code of course. Just what you prefer.
{ "language": "en", "url": "https://stackoverflow.com/questions/5375883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to predict the labels for the test set when using a custom Iterator in MXnet? I have a big dataset (around 20GB for training and 2GB for testing) and I want to use MXnet and R. Due to lack of memory, I search for an iterator to load the training and test set by a custom iterator and I found this solution. Now, I can train the model using the code on this page, but the problem is that if I read the test set with the save iterator as follow: test.iter <- CustomCSVIter$new(iter = NULL, data.csv = "test.csv", data.shape = 480, batch.size = batch.size) Then, the prediction command does not work and there is no prediction template in the page; preds <- predict(model, test.iter) So, my specific problem is, if I build my model using the code on the page, how can I read my test set and predict its labels for the evaluation process? My test set and train set is in this format. Thank you for your help A: It actually works exactly as you explained. You just call predict with model and iterator: preds = predict(model, test.iter) The only trick here is that the predictions are displayed column-wise. By that I mean, if you take the whole sample you are referring to, execute it and add the following lines: test.iter <- CustomCSVIter$new(iter = NULL, data.csv = "mnist_train.csv", data.shape = 28, batch.size = batch.size) preds = predict(model, test.iter) preds[,1] # index of the sample to see in the column position You receive: [1] 5.882561e-11 2.826923e-11 7.873914e-11 2.760162e-04 1.221306e-12 9.997239e-01 4.567645e-11 3.177564e-08 1.763889e-07 3.578671e-09 This show the softmax output for the 1st element of the training set. If you try to print everything by just writing preds, then you will see only empty values because of the RStudio print limit of 1000 - real data will have no chance to appear. Notice that I reuse the training data for prediction. I do so, since I don't want to adjust iterator's code, which needs to be able to consume the data with and without a label in front (training and test sets). In real-world scenario you would need to adjust iterator so it would work with and without a label.
{ "language": "en", "url": "https://stackoverflow.com/questions/43684975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble with WebClient and Thread management I've been scratching my hair out trying to figure out this problem. I'm using a WebClient control that reads in a dynamic URL. There is data that I am trying to extract that isn't in the HTML source when retrieved from the Server but is rendered later with Javascript/AJAX. I've used multiple methods including Thread.Join() and BackgroundWorker with zero results. I'm now trying to use a async method but to be honest I'm totally lost as to what I'm doing. Here is my code: protected void retrieveDataSource(int matchId_val) { ManualResetEvent completionEvent = new ManualResetEvent(false); WebClient wc = new WebClient(); wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { source = e.Result; completionEvent.Set(); }; wc.DownloadStringAsync(new Uri("http://na.lolesports.com/tourney/match/" + matchId_val)); } protected void LoadWebPage() { retrieveDataSource(matchId_val); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(source); } source is a global variable that is set to null initially. When I run this code the DownloadStringCompleted argument is never triggered and thus the source is never changed from null. When it reaches doc.LoadHtml(source) I'm given a null exception. IT SHOULD BE NOTED that if I hit 'Continue' then the breakpoint will arrive at the DownloadStringCompleted function which is beyond me. If anyone can help me I'd greatly appreciate it as I've already spent my entire morning trying to wrap my mind around the issue. A: There are ultimately a number of difficulties you may well run into as you attempt this. The bottom line is that to get at dynamically-generated content, you have to render the page, which is a lot different operation from simply downloading what the HTTP server gives you for a given URL. In addition, it's not clear what you're using to render the web page. You are using a class named HtmlDocument and a method named LoadHtml(). This suggests that you are using Html Agility Pack, but your question is silent on that point. To my recollection, that library doesn't render HTML; but I could be wrong or have out of date information. All that said, there is a very clear bug in your code. You create an event handle, which is apparently used to signal the completion of the asynchronous operation, but you never wait on it. This means that the thread that started the I/O will just keep going and attempt to retrieve the result before it is actually available. One way to address that would be to wait on the event handle: protected void retrieveDataSource(int matchId_val) { ManualResetEvent completionEvent = new ManualResetEvent(false); WebClient wc = new WebClient(); wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { source = e.Result; completionEvent.Set(); }; wc.DownloadStringAsync(new Uri("http://na.lolesports.com/tourney/match/" + matchId_val)); completionEvent.WaitOne(); } Of course, if you're just going to make the thread block while you wait for the operation to complete, that raises the question of why are you using asynchronous I/O at all? Why not just call DownloadString() instead, which will automatically block until the operation is done. I also advise against the use of a class field for the purpose of passing data from a called method to the caller. It would make more sense here for retrieveDataSource() to return the result to the caller directly. Were the code written in that way, the issue with the thread synchronization would have been more readily apparent, as you likely would have noticed the method returning before that value was actually available. But if you insist on using the asynchronous method, the above change should at least resolve your thread synchronization issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/31006602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto cell update with use of intersect So basically I have a column in my spreadsheet that tracks the status of bearing conditions. 800+ bearings spread across 8 or so sheets (different areas of a facility) and will continue to increase in the future. There is a corresponding column that tracks the date that the status last changed. I have several active x controls and user forms on a dashboard/homepage for the work book that allow the user to make these changes automatically, however I would like to be able to go into the sheets and manually change the status (drop down list) and have the date in corresponding cell change automatically. I found some code I modified and it appears to work which is good Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim xRg As Range, xCell As Range On Error Resume Next If (Target.Count = 1) Then If (Not Application.Intersect(Target, Me.Range("G5:G80")) Is Nothing) Then _ Target.Offset(0, 1) = Date Application.EnableEvents = False Set xRg = Application.Intersect(Target.Dependents, Me.Range("G5:G80")) If (Not xRg Is Nothing) Then For Each xCell In xRg xCell.Offset(0, 1) = Date Next End If Application.EnableEvents = True End If End Sub Having got the code working as I wanted I realised I would like it to to add the date to additional cells in that row but dependent on what the cell is changed to (for example if the cell is change to "Good" also add the current date in a cell offset by 4). I have modified the code further and it now also adding the date too cells dependent on what the change value was. Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim xRg As Range, xCell As Range Dim UpperIndex As Integer Dim LowerIndex As Integer Dim Rows As Integer Set tbl = ThisWorkbook.Worksheets("Route 1").ListObjects("Route_1_Table") Rows = tbl.Range.Rows.Count UpperIndex = 5 LowerIndex = Rows - 3 On Error Resume Next If (Target.Count = 1) Then If (Not Application.Intersect(Target, Me.Range("G" & UpperIndex & ":G" & LowerIndex)) Is Nothing) Then _ Target.Offset(0, 1) = Date If Target.Value = "Good" Then _ Target.Offset(0, 5) = Date If Target.Value = "Pending Baseline" Then _ Target.Offset(0, 4) = Date End If End Sub As you can see I removed the last section of the code but I don't know what it did, any ideas? Just wondering if it comes back to bite me later. Bit removed shown below Application.EnableEvents = False Set xRg = Application.Intersect(Target.Dependents, Me.Range("G5:G80")) If (Not xRg Is Nothing) Then For Each xCell In xRg xCell.Offset(0, 1) = Date Next End If Application.EnableEvents = True A: A Worksheet Change: Date Stamp To Multiple Columns Sheet Module e.g. Sheet1 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) AddDateStamp Target, "Route_1_Table", 7, 8, 3, 3, _ Array(11, "Pending Baseline"), Array(12, "Good") End Sub Standard Module e.g. Module1 Option Explicit Sub AddDateStamp( _ ByVal Target As Range, _ ByVal TargetTableName As String, _ ByVal TargetColumn As Long, _ ByVal DateColumn As Long, _ ByVal TopRowsSkipped As Long, _ ByVal BottomRowsSkipped As Long, _ ParamArray DateColumnCriteriaPairs() As Variant) On Error GoTo ClearError ' start error-handling routine Dim tws As Worksheet: Set tws = Target.Worksheet Dim trg As Range: Set trg = tws.ListObjects(TargetTableName).DataBodyRange ' Exclude top and bottom rows. Set trg = trg.Resize(trg.Rows.Count - TopRowsSkipped - BottomRowsSkipped) _ .Offset(TopRowsSkipped) ' Reference the intersecting cells. Dim irg As Range: Set irg = Intersect(trg.Columns(TargetColumn), Target) If irg Is Nothing Then Exit Sub ' no intersection Dim AnyDcPairs As Boolean AnyDcPairs = Not IsMissing(DateColumnCriteriaPairs) Dim dcIndex As Long, ccIndex As Long ' Date Column Index If AnyDcPairs Then dcIndex _ = LBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs))) ccIndex _ = UBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs))) End If Dim urg As Range, iCell As Range, dcPair, iString As String For Each iCell In irg.Cells Set urg = RefCombinedRange( _ urg, iCell.Offset(, DateColumn - TargetColumn)) iString = CStr(iCell.Value) If AnyDcPairs Then For Each dcPair In DateColumnCriteriaPairs If StrComp(iString, dcPair(ccIndex), vbTextCompare) = 0 Then Set urg = RefCombinedRange( _ urg, iCell.Offset(, dcPair(dcIndex) - TargetColumn)) Exit For ' match found, stop looping End If Next dcPair End If Next iCell Application.EnableEvents = False urg.Value = Date ProcExit: ' Exit Routine On Error Resume Next ' prevent endless loop if error in the following lines If Not Application.EnableEvents Then Application.EnableEvents = True On Error GoTo 0 Exit Sub ' don't forget! ClearError: ' continue error-handling routine Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description Resume ProcExit ' redirect to exit routine End Sub '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Purpose: References a range combined from two ranges. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function RefCombinedRange( _ ByVal urg As Range, _ ByVal arg As Range) _ As Range If urg Is Nothing Then Set urg = arg Else Set urg = Union(urg, arg) Set RefCombinedRange = urg End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/74961358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get image Height and Width I am displaying an image which if small, will fill the size of the control area. I want to display the actual original width and height of the image. How can I do that? A: ImageSource.Width and ImageSource.Height A: You actually kind of answered your own question. There are two dependency properties that you can use: ActualWidth and ActualHeight. This will give you the size that the picture is using on the screen, not what is currently set, which is what Width and Height give you. Also, these dependency properties are useable by any FrameworkElement I believe. FrameworkElement.ActualWidth FrameworkElement.ActualHeight A: You can set the Stretch property to "None" to have an Image element use the actual source image size: <Image Source="/Resources/MyImage.png" Stretch="None"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/1261237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why my app get different expiration time of Facebook access token? I have a web application, which needs user's Facebook permissions, and perform some actions in the background. For most users, this app can get an access token with 2 months expiration time through oAuth process. But today I found it gets only one day expiration time access token from a few people. Since the application is still under development, and testers are all my colleagues. So, I checked their Facebook permission settings, but I didn't find something particular which will affect the expiration time I get from oAuth. So, is there any possible reason why some people can get a longer expiration time, but some other people will only get a shorter one?
{ "language": "en", "url": "https://stackoverflow.com/questions/10632494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Html wrapper issue My Flex application is built using ant. The html wrapper task is as follows: <target name="wrapper"> <html-wrapper title="{$title}" file="login.htm" height="300" width="400" application="app" swf="Main.swf" version-major="9" version-minor="0" version-revision="0" history="true" template="express-installation" output="${APP_ROOT}"/> </target> My purpose is to display a message to the user in case their browser has JavaScript disabled. I modified the index.template.html file within the express-installation folder to include the following in the tag: <noscript><my message here/></noscript> The message does not get displayed. Is there a way I could find out which index.template.html file is used by ant task or is the file being overridden somehow? Can anyone resolve this? Any help would be appreciated. :) A: It should be coming from the SDK that you are using to build the wrapper. It'll be somewhere like... ${FLEX_HOME}/templates/express-installation/index.template.html A: As of Flex SDK 4.5: The template file used when building your project via html-wrapper ant task unfortunately does NOT come from ${FLEX_SDK_HOME}/templates/swfobject. The template file used by the ant task is actually baked into the flexTasks.jar file found in ${FLEX_SDK_HOME}/ant/lib. As you know, there is no convenient option you can apply on the task to use a different template. Because my needed changes were minor (and presumably useful on all of my projects) I simply unzipped flexTasks.jar and re-zipped it with my modified template. A: Since you did use the history="true" you need change the template inside P:\ath\to\sdks\X.Y.Z\templates\express-installation-with-history as documented here.
{ "language": "en", "url": "https://stackoverflow.com/questions/4042750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uploading in React and Redux I'm uploading multiples images and I wanted to display the correct percentage "50%". However I'm calling the API one by one. Meaning I upload the image one by one. The problem is the percentage keeps getting back and forth like 0 - 50%, then going back again to 0 and so on... The reason for this is because I'm dispatching the setProgress multiples times. What will be the correct calculation to achieve the correct percentage? Reducer case SET_UPLOAD_PROGRESS: return { ...state, uploadProgress: action.payload, } Actions export const uploadImages = ({ images }) => (dispatch) => { images.forEach(async (image) => { const formData = new FormData(); formData.append(image.name, image.imageFile); try { dispatch({ type: UPLOAD_IMAGES_REQUEST }); const response = await axios.post("http://test.com", formData, { onUploadProgress(progressEvent) { const { loaded, total } = progressEvent; const percentage = Math.floor((loaded / total) * 100); dispatch(setUploadProgress(percentage)); <- GETTING PERCENTAGE. IT IS WORKING ALREADY. EXAMPLE OUTPUT: 50 }, }); dispatch({ type: UPLOAD_IMAGES_SUCCESS, payload: [...(images || [])], }); } catch (error) { dispatch({ type: UPLOAD_IMAGES_FAILURE }); } }); }; Component const uploadProgress = useSelector(state => state.images.uploadProgress); <LinearProgress variant="determinate" value={uploadProgress} /> A: FormData can handle multiple files, even under the same field name. If the API supports it, build up your request payload and send it once export const uploadImages = ({ images }) => async (dispatch) => { // async here const formData = new FormData(); images.forEach(image => { formData.append(image.name, image.imageFile); }) // as per usual from here... }; Otherwise, you'll need to chunk the progress by the number of images, treating the average as the total progress. export const uploadImages = ({ images }) => async (dispatch) => { const imageCount = images.length; const chunks = Array.from({ length: imageCount }, () => 0); await Promise.all(images.map(async (image, index) => { // snip... await axios.post(url, formData, { onUploadProgress({ loaded, total }) { // for debugging console.log( "chunk:", index, "loaded:", loaded, "total:", total, "ratio:", loaded / total ); // store this chunk's progress ratio chunks[index] = loaded / total; // the average of chunks represents the total progress const avg = chunks.reduce((sum, p) => sum + p, 0) / chunks.length; dispatch(setUploadProgress(Math.floor(avg * 100))); } }); // snip... }); // snip... }; Note that the upload progress can reach 100% before the request actually completes. To handle that, you may want something in your store that detects when the uploadProgress is set to 100 and set another state (finalisingUpload = true for example) that you can clear after the request complete. Here's a quick demo using mocks showing how the logic works ~ https://jsfiddle.net/rtLvxkb2/
{ "language": "en", "url": "https://stackoverflow.com/questions/71507806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Enable only dates that are in the array I have just started using jQuery UI's datepicker and I am looking for a way to enable dates that are only in the data array... I tried everything but it doesn't seem to disable any dates. I checked data array and it display everything in the following format if I use console.log(data): ["2017-04-28", "2017-05-19", "2017-04-03", "2017-04-05", "2017-04-07", "2017-04-04", "2017-04-12"] $.ajax({ url: '/getDoctorsAppointments/'+doctor_id+'/', type: "GET", dataType: "json", success:function(data) { // enable only dates in the "data" array } }); Any ideas how I can achieve that only dates in the array are enabled/can be selected in the datepicker?
{ "language": "en", "url": "https://stackoverflow.com/questions/43346949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get (this) element's parent index and pass it as a value? In the following example,how would i get the parent <ol> index inside the wrapper div and pass it as a value in the li's innerText ? tried something like $(this).closest("ol").index() but did'nt work $("li").text("this ol's index is " + $(this).closest("ol").index()); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <div> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> </div> </body> </html> A: You are not in any event handling or callback context here, so $(this) simply refers to the window object (wrapped in jQuery.) Go through the li in a loop, then $(this) will have the proper context inside the callback function. $("li").each(function() { $(this).text("this ol's index is " + $(this).closest("ol").index()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <div> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> <ol><li class="li"></li></ol> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/66060680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }