text
stringlengths
15
59.8k
meta
dict
Q: Get all name values from html option tag in javascript I have this following html code <select> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button>Submit</button> what I want is, when I click the submit button it should store all the name values which are inside option tags to an array. so far I tried the following js code but it seems not working. document.getElementsByTagName('button').onclick = function() { var array = [document.getElementsByTagName('option').value]; console.log(array); }; any idea how can I achieve this? thanks in advance. ps: I'm quite new to javascript. A: Here's the solution. You have to iterate through all option elements, grab the value of every element and push inside an array. function getValues() { var array = document.getElementsByTagName('option'); var arr = []; for (var i = 0; i < array.length; i++) { arr.push(array[i].value) } console.log(arr); }; <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" onclick="getValues()">Submit</button> ES6 solution: function getValues() { var array = document.getElementsByTagName('option'); var arr = []; Array.from(array).forEach(v => arr.push(v.value)); console.log(arr); }; <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" onclick="getValues()">Submit</button> A: Assuming that ES6 is an option for you, then the following will do as you wish: // using a named function: function grabTextFrom() { // initialising the local variable using 'let', // converting the argument supplied to Array.from() // to convert the Array-like Object (in this case // a NodeList, or HTMLCollection, from // document.querySelectorAll()) into an Array: let texts = Array.from( document.querySelectorAll( // 'this' is passed automatically from the // later use of EventTarget.addEventListener(), // and the dataset.textFrom property value is // the value stored in the data-textfrom attribute: this.dataset.textfrom ) // iterating over that Array of elements using // Array.prototype.map() along with an arrow function: ).map( // 'opt' is a reference to the current Array-element // from the Array of elements over which we're iterating; // and here we return the value property-value of that // current element: opt => opt.value ); // logging to the console for demo purposes: console.log(texts); // returning to the calling context: return texts; } // finding the first element which matches the // supplied CSS selector, and adding the // grabTextFrom() function as the event-handler // for the 'click' event (note the deliberate // lack of parentheses in the function-name): document.querySelector('#submit').addEventListener('click', grabTextFrom); function grabTextFrom() { let texts = Array.from( document.querySelectorAll(this.dataset.textfrom) ).map( opt => opt.value ); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" data-textfrom="option">Submit</button> If, however, you have to provide for ES5 compatibility then the following will work identically: function grabTextFrom() { // here we use Array.prototype.slice(), along // with Function.prototype.call(), to apply // the slice() method to the supplied NodeList: var texts = Array.prototype.slice.call( document.querySelectorAll(this.dataset.textfrom) // here we use the anonymous function of the // Array.prototype.map() method to perform the // same function as above, returning the // opt.value property-value to the created Array: ).map(function(opt) { return opt.value; }); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); function grabTextFrom() { var texts = Array.prototype.slice.call( document.querySelectorAll(this.dataset.textfrom) ).map(function(opt) { return opt.value; }); console.log(texts); return texts; } document.querySelector('#submit').addEventListener('click', grabTextFrom); <select id="options"> <option>Joe</option> <option>Buckey</option> <option>Elen</option> <option>Rimzy</option> </select> <button id="submit" data-textfrom="option">Submit</button> A: You're close. document.getElementsByTagName('option') returns an array of <option> elements. You can't get .value on an array of elements - you can only call it on a single <option> element. How would you get .value for each element in your array?
{ "language": "en", "url": "https://stackoverflow.com/questions/42281222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: undefined method `params_require' - New into rails I try to code a small blog in rails and when I tried to save a post through the website i get an Error. I can create a post with the console but thats not the goal. this is my code for the create method: def create @post = Post.new(post_params) if post.save redirect_to post.path else render "new" end end def post_params params_require(:post).permit(:title, :content) end would be nice if someone can help me. Thanks A: def post_params params.require(:post).permit(:title, :content) end Change params_require to params.require
{ "language": "en", "url": "https://stackoverflow.com/questions/43070393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hive: Unable to insert data in table with 100 or more partition columns Error: in column "PART_NAME" that has maximum length of 767 I am working with hive, I needed to create a table with 'n' normal column and 100 or more as partition columns and I am able to create that table successfully. now When I come to load that table with data of another table with same schema and all columns are non-partition columns, I am getting error like this: Failed with exception MetaException(message:Attempt to store value Failed with exception MetaException(message:Attempt to store value "c1=v1/c2=v2/c3=v3/....c100=v100" in column "PART_NAME" that has maximum length of 767. Please correct your data!) By taking last line of error in consideration, I tried to reduce the column name and their values, so that the resultant partition path will get shorter and it worked!! but it should not be like that in real time scenario size of column name and their values could be anything and so of partition path. e.g. Here is my create table Query: CREATE TABLE xyz( c0 int) PARTITIONED BY ( c1 String,c2 String,c3 String,c4 String.......c100 String) ROW FORMAT DELIMITED FIELDS TERMINATED BY '|' STORED AS TEXTFILE And here is my insert into query: INSERT INTO TABLE xyz PARTITION (gc1,c2,c3....,c100) SELECT c0,c1,c2,c3,c4....,c100 FROM table123; Am I doing something wrong or should I have to set some properties to make use of so many partitions like 100 or more? Please give me any clue I am stuck on this. Thanks A: I agreed with the experts that we should not go for so many partitions in a table. Also I would like to quote this as most of the nodes are unix/linux based and we can not create folder or file name having length greater than 255 bytes. That may be the reason you are getting this error, as partition is a folder only. Linux has a maximum filename length of 255 characters for most filesystems (including EXT4), and a maximum path of 4096 characters. eCryptfs is a layered filesystem.
{ "language": "en", "url": "https://stackoverflow.com/questions/44714575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Adding behavior to LINQ to Entities models What's the preferred approach when using L2E to add behavior to the objects in the data model? * *Having a wrapper class that implements the behavior you need with only the data you need using (var dbh = new ffEntities()) { var query = from feed in dbh.feeds select new FFFeed(feed.name, new Uri(feed.uri), feed.refresh); return query.ToList(); } //Later in a separate place, not even in the same class foreach (FFeed feed in feedList) { feed.doX(); } *Using directly the data model instances and have a method that operates over the IEnumerable of those instances using (var dbh = new ffEntities()) { var query = from feed in dbh.feeds select feed; return query.ToList(); } //Later in a separate place, not even in the same class foreach (feeds feed in feedList) { doX(feed); } *Using extension methods on the data model class so it ends up having the extra methods the wrapper would have. public static class dataModelExtensions { public static void doX(this feeds source) { //do X } } //Later in a separate place, not even in the same class foreach (feeds feed in feedList) { feed.doX(); } Which one is best? I tend to favor the last approach as it's clean, doesn't interfere with the CRUD facilities (i can just use it to insert/update/delete directly, no need to wrap things back), but I wonder if there's a downside I haven't seen. Is there a fourth approach? I fail at grasping LINQ's philosophy a bit, especially regarding LINQ to Entities. A: The Entity classes are partial classes as far as i know, so you can add another file extending them directly using the partial keyword. Else, i usually have a wrapper class, i.e. my ViewModel (i'm using WPF with MVVM). I also have some generic Helper classes with fluent interfaces that i use to add specific query filters to my ViewModel. A: I think it's a mistake to put behaviors on entity types at all. The Entity Framework is based around the Entity Data Model, described by one of its architects as "very close to the object data model of .NET, modulo the behaviors." Put another way, your entity model is designed to map relational data into object space, but it should not be extended with methods. Save your methods for business types. Unlike some other ORMs, you are not stuck with whatever object type comes out of the black box. You can project to nearly any type with LINQ, even if it is shaped differently than your entity types. So use entity types for mapping only, not for business code, data transfer, or presentation models. Entity types are declared partial when code is generated. This leads some developers to attempt to extend them into business types. This is a mistake. Indeed, it is rarely a good idea to extend entity types. The properties created within your entity model can be queried in LINQ to Entities; properties or methods you add to the partial class cannot be included in a query. Consider these examples of a business method: public Decimal CalculateEarnings(Guid id) { var timeRecord = (from tr in Context.TimeRecords .Include(“Employee.Person”) .Include(“Job.Steps”) .Include(“TheWorld.And.ItsDog”) where tr.Id = id select tr).First(); // Calculate has deep knowledge of entity model return EarningsHelpers.Calculate(timeRecord); } What's wrong with this method? The generated SQL is going to be ferociously complex, because we have asked the Entity Framework to materialize instances of entire objects merely to get at the minority of properties required by the Calculate method. The code is also fragile. Changing the model will not only break the eager loading (via the Include calls), but will also break the Calculate method. The Single Responsibility Principle states that a class should have only one reason to change. In the example shown on the screen, the EarningsHelpers type has the responsibility both of actually calculating earnings and of keeping up-to-date with changes to the entity model. The first responsibility seems correct, the second doesn't sound right. Let's see if we can fix that. public Decimal CalculateEarnings(Guid id) { var timeData = from tr in Context.TimeRecords where tr.Id = id select new EarningsCalculationContext { Salary = tr.Employee.Salary, StepRates = from s in tr.Job.Steps select s.Rate, TotalHours = tr.Stop – tr.Start }.First(); // Calculate has no knowledge of entity model return EarningsHelpers.Calculate(timeData); } In the next example, I have rewritten the LINQ query to pick out only the bits of information required by the Calculate method, and project that information onto a type which rolls up the arguments for the Calculate method. If writing a new type just to pass arguments to a method seemed like too much work, I could have also projected onto an anonymous type, and passed Salary, StepRates, and TotalHours as individual arguments. But either way, we have fixed the dependency of EarningsHelpers on the entity model, and as a free bonus we've gotten more efficient SQL, as well. You might look at this code and wonder what would happen if the Job property of TimeRecord where nullable. Wouldn't I get a null reference exception? No, I would not. This code will not be compiled and executed as IL; it will be translated to SQL. LINQ to Entities coalesces null references. In the example query shown on the screen, StepRates would simply return null if Job was null. You can think of this as being identical to lazy loading, except without the extra database queries. The code says, "If there is a job, then load the rates from its steps." An additional benefit of this kind of architecture is that it makes unit testing of the Web assembly very easy. Unit tests should not access a database, generally speaking (put another way, tests which do access a database are integration tests rather than unit tests). It's quite easy to write a mock repository which returns arrays of objects as Queryables rather than actually going to the Entity Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/1370123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How I can fix the following error in replication RDF in virtuoso OpenSource? I'm trying to do replication RDF triples in Virtuoso, but I have an error when connecting with the pulbicador server via repl_server. function () says: Error 42S22: [OpenLink] [Virtuoso ODBC Driver] [Virtuoso Server] SR242: No system status variable st_repl_server_enable Please help with this error. A: You're trying to use a feature of the Commercial Edition, but you're running the Open Source Edition.
{ "language": "en", "url": "https://stackoverflow.com/questions/32042476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't this SVG fit inside its parent DIV for small DIV sizes? My expectation is that the triangle should be inside the container div. This works as expected for widths bigger than 14 pixels or so, but for small div sizes the SVG gets bumped down. <div id="square" style="width: 9px; height: 9px; background-color: red"> <svg viewBox="0 0 99 99" style="width:100%; height: 100%; fill: blue;"> <polygon id="triangle" points="0,99 49,0 99,99" /> </svg> </div> Fiddle here: https://jsfiddle.net/rpk6c6r0/4/ A: An <svg> element in HTML is set to display: inline by default. This can cause it to be affected by line-wrapping when space is constrained; the icon will wrap to the next line in the same way as a word in a paragraph. Easiest fix, if you are positioning the SVG precisely, is therefore to set display: block. https://jsfiddle.net/rpk6c6r0/6/
{ "language": "en", "url": "https://stackoverflow.com/questions/33746161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Fill program in C I am trying to create a program in C that, given the user's input of a character boarder for a shape, fills the shape in. http://pastebin.com/aax1dt0b #include <stdio.h> #include "simpio.h" #include "genlib.h" #define size 100 bool initArray(bool a[size][size]); bool getshape(bool a[size][size]); /* Gets the input of the boarder of the shape from the user */ void fill(int x, int y, bool a[size][size]); /* fills the shape */ void printarray(bool a[size][size]); /* prints the filled shape */ main() { int x, y; char i; bool a[size][size]; initArray(a); getshape(a); printf("Enter the coordinates of the point the shape should be filled.\n"); printf("x=n\n"); /* gets the coordinates of the array to begin the fill algorithm from */ x = GetInteger(); printf("y=\n"); y = GetInteger(); fill(x, y, a); printarray(a); printf("Scroll up to view your filled shape\n"); getchar(); } bool initArray(bool a[size][size]) { int i, j; for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { a[i][j] = FALSE; } } } bool getshape(bool a[size][size]) { int i, j, k; bool flag; char ch; ch = 1; printf("Enter your shape. When you are finished, type 'E'. \n"); for (i = 0; i < 100; i++) { flag = TRUE; for (j = 0; ch != 10; j++) { ch = getchar(); if (ch == 69) { return a; } if (ch != 32) a[i][j] = TRUE; } ch = 1; } } void fill(int x, int y, bool a[size][size]) { if (a[y][x] != TRUE) a[y][x] = TRUE; if (a[y][x - 1] != TRUE) fill(x - 1, y, a); if (a[y - 1][x] != TRUE) fill(x, y - 1, a); if (a[y][x + 1] != TRUE) fill(x + 1, y, a); if (a[y + 1][x] != TRUE) fill(x, y + 1, a); } void printarray(bool a[size][size]) { int i, j; printf("\n\n\n"); for (i = 0; i < 100; i++) { for (j = 0; j < 100; j++) { if (a[i][j] == FALSE) printf(" "); if (a[i][j] == TRUE) printf("*"); } printf("\n"); } } My program works for the most part, but when it prints the filled shape, it adds one additional character to each row. For example, if the user's input it *** * * *** Then the output will be **** **** **** (one extra row then it should be) whereas it should be *** *** *** anyone know how I can fix this? A: Although there are several potential problems in your code, I'm going to just identifying the problem of the 4th column *'s. In the code below, although you're checking ch!=10 in the for statement, the value of a[i][j] is getting assigned TRUE before terminating the loop. So you might want to do if(ch!=32 && ch!=10) a[i][j]=TRUE;. flag=TRUE; for(j=0;ch!=10;j++) { ch=getchar(); if(ch==69) { return a; } if(ch!=32) a[i][j]=TRUE; } ch=1;
{ "language": "en", "url": "https://stackoverflow.com/questions/10421398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why we use const array in a function, even the original array are not const? I hope that these code express my question more clearly. double xxxx(const double* const array){ //... } int main(){ double* array = new double [5]; xxxx(array); } Is it actually create a new const array in the stack and heap by the input of the function?
{ "language": "en", "url": "https://stackoverflow.com/questions/48798993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rangeHighlights not showing with bootstrap-slider bootstrap-slider working, displays as intended, however the rangeHighlights do not seem to be appearing. Copied the html/css/js code from http://seiyria.com/bootstrap-slider into my projects as it is on the site. What am i doing wrong here? $('#ex22').slider({ id: 'slider22', min: 0, max: 20, step: 1, value: 14, rangeHighlights: [{ "start": 2, "end": 5, "class": "category1" }, { "start": 7, "end": 8, "class": "category2" }, { "start": 17, "end": 19 }, { "start": 17, "end": 24 }, { "start": -3, "end": 19 } ] }); #slider22 .slider-selection { background: #2196f3; } #slider22 .slider-rangeHighlight { background: #f70616; } #slider22 .slider-rangeHighlight.category1 { background: #FF9900; } #slider22 .slider-rangeHighlight.category2 { background: #99CC00; } <!DOCTYPE html> <!-- saved from url=(0036)http://seiyria.com/bootstrap-slider/ --> <html lang="en" style="" class=" js flexbox flexboxlegacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="http://seiyria.com/bootstrap-slider/css/bootstrap.min.css" rel="stylesheet" /> <link href="http://seiyria.com/bootstrap-slider/css/bootstrap-slider.css" rel="stylesheet" /> </head> <body> <div id="example-22" class="slider-example"> <input id="ex22" type="text" data-slider-id="slider22" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="14" data-slider-rangeHighlights='[{ "start": 2, "end": 5, "class": "category1" }, { "start": 7, "end": 8, "class": "category2" }, { "start": 17, "end": 19 }, { "start": 17, "end": 24 }, //not visible - out of slider range { "start": -3, "end": 19 }]' /> </div> <script src="http://seiyria.com/bootstrap-slider/dependencies/js/jquery.min.js"></script> <script src="http://seiyria.com/bootstrap-slider/js/bootstrap-slider.js"></script> </body> </html> A: Probably you use bootstrap 4. For now it won't work with this version. Use bootstrap 3 or you have to adjust bootstrap-slider to new bootstrap.
{ "language": "en", "url": "https://stackoverflow.com/questions/47402564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Affecting Single Element with jQuery What I'm trying to do is when in my function user will hover over .yell-button then .yell-box-txt will disappear. The only problem is that I have more then one buttons on the site and whenever I'll hover over one of them all text fields are disappearing. this is my function: $('.yell-button').hover(function(){ $('.yell-box-txt').remove() }) Thank you for your help in advance A: Without knowing your markup, I'd suspect that your .yell-box-txt is in the same block as your .yell-button. So for markup like this: <div> <a class="yell-button">text button</a> <span class="yell-box-txt">text</a> </div> you'd want to use something like this: $('.yell-button').hover(function() { $(this).closest('div').find('.yell-box-txt').remove(); }); A: Classes are, by definition, accessors for, potentially, multiple elements. If you want to access this element on its own, consider using an id and accessing it via $('#idname') A: $('.yell-button:first').hover(function(){ $('.yell-box-txt').remove(); }) Of course it'd be better to make sure to only use this class once. It would be even better to use an ID instead, which is supposed to be unique (of course it's up to you and you have to check your code for inconsistencies such as multiple elements with the same id) A: Example of using id and class JS $('.yell-button').hover(function(){ $('#box2.yell-box-txt').remove() }) HTML <div id ="box1" class="yell-box-txt">Text in box 1</div> <div id ="box2" class="yell-box-txt">Text in box 2</div> <div id ="box3" class="yell-box-txt">Text in box 3</div> A: As others said, without an idea of your markup it's difficult to help you, however here are some ways to do it, depending on your markup: Ideally, you would be able to assign each button and associated text-box a unique identifier like yell-button-1 and make it remove the associated yell-box-txt-1 on hover. However, this method might be "difficult" to implement because you need to retrieve the ID # from the button. The second way to do this is to make use of jQuery traversing. Find where the text box is in relation to the button and navigate from the button to the text box using methods such as parent(), siblings(), etc. To make sure you only receive one element, append :first to your .yell-box-txt class. More info about jQuery Traversing. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/1859557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unknown error occurred while loading Library/Artifacts unity Unknown error occurred while loading 'Library/Artifacts/91/919a792b1979b62f241964f8b62a0554'. This error I get after download entities on unity A: Two suggestions: download the latest version of the package; Try deleting the entire "Library" folder, after having dubbed it to another location for safety.
{ "language": "en", "url": "https://stackoverflow.com/questions/72994705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fetching the frequency of a unique number within an array for a list of db queries in sqlalchemy/postgresql I am having a hard time figuring out a way to find a solution to the above question. Here are the details. Let's say we have Table X which contains different products, and each product has a unique integer id and a unique code. We also have Table Y, which contains different variants of each product in Table X who have slight variations in a product name, length, width etc. Therefore there's a one-many relationship defined between Table X and Table Y. The frontend displays all these product variants and allows them to be chosen from a list and export all of the chosen product details to a pdf. However, there's a weird way of choosing them, wherein if a user clicks on a product, then all the product variants who have the same unique code are selected if they are on the same list. That is, basically whenever a product variant is selected, the full product gets selected along with all its variants in the list. However, if the user wants, they can deselect each product variant individually as they please. Table Z contains a log of all the product variant ids exported. Hence it looks something like this id | exported_at | exported_by | product_variant_ids 1 | Some datetime | Some user | {1, 2, 3, 4} 2 | Some datetime | Some user | {3, 4} 3 | Some datetime | Some user | {6, 8, 9} 4 | Some datetime | Some user | {1, 6, 7} 5 | Some datetime | Some user | {3, 5, 7} And so on.. Here you will observe that: 1. On each row, a product variant id can appear only once in the array 2. However, a product variant id can appear at different rows I want to calculate, for each unique product variant id present across all the rows, the sum of the frequency of them appearing across each row. So for example, in the dummy table above, product variant id 1 appears exactly twice in the whole table, in row 1 and row 4. Similarly, product variant id 3, in rows 1, 2, and 5. I have tried to calculate it naively, something like Naive algorithm in words: From a set of all unique ids present across the table, for each row check if each of the unique id in the set is present in each single row and increase the counter each time it does. I don't know how to write a subquery for it and hence, I was not able to tryout any queries on the postgres console. It results in a very slow operation after only 15-20 logs when using an ORM like SQLAlchemy. Can anyone guide me in the right direction what may be a more efficient solution?
{ "language": "en", "url": "https://stackoverflow.com/questions/54499824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to stop AWS from starting CodePipeline automatically if I deploy it via CloudFormation? If you create a CodePipeline via CloudFormation. It starts it automatically, that can be a problem because the pipeline can rewrite the same stack... Is there any way to disable this behaviour? Thanks. A: Had same issue, I don't want a pipeline launch on pipeline creation (which is the default beahviour). Best solution I fount is : * *Create an EventBridge rule which catch the pipelineExecution on pipeline creation *Stop the pipeline execution from the lambda triggered Rule looks like this : { "source": ["aws.codepipeline"], "detail-type": ["CodePipeline Pipeline Execution State Change"], "detail": { "state": ["STARTED"], "execution-trigger": { "trigger-type": ["CreatePipeline"] } } } It works fine A: Sadly, there seem to be no way of this this. Docs clearly states that a newly created pipeline immediately starts running: Now that you've created your pipeline, you can view it in the console. The pipeline starts to run after you create it. The initial run will always happen. Subsequent runs depend on your source action. For example, if you use CodeCommit as your source, you can disable CloudWatch Event that triggers the pipeline. Thus if you want to use CodePipeline in your project, you have to design it so that it does not causes any issues due to immediate start. A: You can disable the Event rule from automatically starting your pipeline. Go to Amazon EventBridge -> Rules and disable the rule that notifies the CodePipeline. A: Further to Marcin's comment, it would seem there are 2 approaches you can take which would limit the run of the pipeline. * *Create a disabled StageTransition or Manual Approval stage directly after the Source stage. This would prevent the pipeline executing any other action aside from getting the source which would have no impact or capability to re-write anything. *Alternatively if your source stage is from a repository, you can opt to handle the pipeline triggers yourself by disabling the PollForSourceChanges parameter in your cloudformation template. Pipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: *NAME* RoleArn: *IAMROLE* Stages: - Name: Source Actions: - Name: CodeCommitSourceAction RunOrder: 1 ActionTypeId: Category: Source Provider: CodeCommit Owner: AWS Version: '1' OutputArtifacts: - Name: Source Configuration: RepositoryName: *REPOSITORYNAME* BranchName: *BRANCH* PollForSourceChanges: "false" #prevents codepipeline polling repository for changes. A: So the correct answer is... * *Commit your code before you deploy for the first time *Deploy only the pipeline *Let Code Pipeline do its thing 99% of cases it will finish sooner than your machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/62540778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: logback logging with maven-jetty-plugin I want to use logback logging with maven-jetty-plugin. Apparently, the system property logback.configurationFile is read after maven-jetty-plugin is started and has initialized slf4j, so the file ./src/test/resources/logback.xml isn't read by jetty. As a result, I get all log messages set to debug level and printed to console (a default logback configuration). Launching maven with -Dlogback.configurationFile=... resolves the problem. However, I'd prefer setting the property in the pom as it is possible with log4j and maven-jetty-plugin. Any ideas ? Here is my pom.xml: ... <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.0.4.v20111024</version> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> </dependencies> <configuration> <systemProperties> <systemProperty> <name>logback.configurationFile</name> <value>./src/test/resources/logback.xml</value> </systemProperty> </systemProperties> ... And here is logback.xml: <configuration> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="FILE" /> </root> </configuration> A: It works with Jetty 9 and the jetty-maven-plugin: <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> </dependencies> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webAppSourceDirectory>src/main/resources/htdocs</webAppSourceDirectory> <webApp> <descriptor>src/main/webapp/WEB-INF/web.xml</descriptor> </webApp> <systemProperties> <systemProperty> <name>org.eclipse.jetty.util.log.Log</name> <value>org.eclipse.jetty.util.log.Slf4jLog</value> </systemProperty> <systemProperty> <name>logback.configurationFile</name> <value>src/main/resources/logback.xml</value> </systemProperty> </systemProperties> </configuration> </plugin> A: Using the older maven-jetty-plugin rather than the jetty-maven-plugin works for me: <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.26</version> <configuration> <systemProperties> <systemProperty> <name>logback.configurationFile</name> <value>${project.build.outputDirectory}/jetty-logback.xml</value> </systemProperty> </systemProperties> </configuration> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.4</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.0</version> </dependency> </dependencies> </plugin> A: you can use the Properties-Maven-Plugin: <project> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0-alpha-2</version> <executions> <execution> <goals> <goal>set-system-properties</goal> </goals> <configuration> <properties> <property> <name>logback.configurationFile</name> <value>src/test/resources/logback.xml</value> </property> </properties> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> Documentation: http://mojo.codehaus.org/properties-maven-plugin/usage.html It's not perfect, but it should work. A: I've encountered this same problem. As a workaround, I used slf4j-simple in place of logback. The slf4j-simple has a default configuration set to INFO level, but is not very configurable otherwise, so it may or may not meet your needs. In the plugin configuration, replace logback-classic with: <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.4</version> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/8087794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Vue wait for render template and display it I have a problem with rendering in vue.js. I made a simple login/registration app. When the user is logged in, the register link should be hidden. It works but when I reload page there is small delay. I try to use v-cloak but it's not working. How can I fix it? I recorded loading on gif. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>michael-client</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <style type="text/css"> [v-cloak] { display:none; } </style> <div class="container"> <div class="col-lg-8"> <div id="app"> <!-- built files will be auto injected --> </div> </div> </body> </html> App.vue <template> <div class="panel panel-default" v-cloak> <div class="panel-heading"> <nav> <ul class="list-inline"> <li> <router-link :to="{ name: 'home' }">Home</router-link> </li> <li v-if="!$auth.check()" class="pull-right"> <router-link :to="{ name: 'login' }">Login</router-link> </li> <li v-if="!$auth.check()" class="pull-right" v-cloak> <router-link :to="{ name: 'register' }">Register</router-link> </li> <li v-if="$auth.check()" class="pull-right"> <a href="#" @click.prevent="$auth.logout()">Logout</a> </li> </ul> </nav> </div> <div class="panel-body"> <router-view></router-view> </div> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style> and main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import Home from './components/Home' import Login from './components/Login' import Register from './components/Register' import Dashboard from './components/Dashboard' import VueRouter from 'vue-router' import axios from 'axios' import VueAxios from 'vue-axios' Vue.config.productionTip = false /* eslint-disable no-new */ Vue.use(VueRouter); Vue.use(VueAxios, axios); axios.defaults.baseURL = 'http://127.0.0.1:8888/api'; const router = new VueRouter({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/login', name: 'login', component: Login, meta: { auth: false } }, { path: '/register', name: 'register', component: Register, meta: { auth: false } } ] }); Vue.router = router Vue.use(require('@websanova/vue-auth'), { auth: require('@websanova/vue-auth/drivers/auth/bearer.js'), http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'), router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'), }); App.router = Vue.router new Vue({ el: '#app', router, components: { App }, template: '<App/>', render: function(createElement) { return createElement(App); } }); In which way are you guys waiting for page is read to display? A: Instead of making Vue do the same work over and over, You could make use of the v-else directive, which may work better for you: <li v-if="!$auth.check()" class="pull-right" v-cloak> <router-link :to="{ name: 'register' }">Register</router-link> </li> <li v-else class="pull-right"> <a href="#" @click.prevent="$auth.logout()">Logout</a> </li> A: v-cloak is not helping because that gets taken away as soon as the Vue app is ready. Apparently there's a delay from when Vue is ready and when the $auth function returns a response. I'd recommend hiding all of the login/logout links until $auth returns something. You'd have to hook into what $auth returns somehow, and use that hook to change the authCheckDone to true. Vue { data: { authCheckDone: false ... } } <ul class="list-inline"> <li> <router-link :to="{ name: 'home' }">Home</router-link> </li> <span v-if="authCheckDone"> <li v-if="!$auth.check()" class="pull-right"> <router-link :to="{ name: 'login' }">Login</router-link> </li> <li v-if="!$auth.check()" class="pull-right" v-cloak> <router-link :to="{ name: 'register' }">Register</router-link> </li> <li v-if="$auth.check()" class="pull-right"> <a href="#" @click.prevent="$auth.logout()">Logout</a> </li> </span> </ul> A: You have to wait a bit until vue-auth is actually ready. From the docs: ready * *Get binded ready property to know when user is fully loaded and checked. *Can also set a single callback which will fire once (on refresh or entry). <div v-if="$auth.ready()"> <vue-router></vue-router> </div> <div v-if="!$auth.ready()"> Site loading... </div> created() { this.$auth.ready(function () { console.log(this); // Will be proper context. }); } In other words, instead of v-cloak use: <div class="panel panel-default" v-if="$auth.ready()"> Note: this can do some quick "flashing" of a white page. In that case you may want to add a loading image or something, like: <div v-if="!$auth.ready()"> <img src="loading.gif"> </div> Naturally, if this div is close to the other v-else can be used.
{ "language": "en", "url": "https://stackoverflow.com/questions/49578349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a better design for sending and returning data objects from a service layer I am probably thinking about this too much but was wondering if there was a more efficient way to do the following. Please note that my main concern is the use of the Data Transfer Object. This works excellent just seems messy to me. Example DTO: public class UserDto:DtoBase { public Guid UserId { get; set; } public Guid NamedIdentifier { get; set; } public string ProviderIdentifier { get; set; } public string ProviderName { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Salt { get; set; } public DateTime PasswordExpirationDate { get; set; } public int InvalidLoginAttempts { get; set; } public int AccountLocked { get; set; } public int AccountValidated { get; set; } public string AccountKey { get; set; } public IList<string> Roles { get; set; } public DateTime LastLoginDate { get; set; } public ProfileDto Profile { get; set; } } Example Service Method. public CreateUserResult CreateUser(UserDto userDto) { ISession session = _sessionManager.OpenSession(); int accountValidated = 1; try { if (_applicationConfiguration.AccountValidationEnabled) { accountValidated = 0; } if (session.QueryOver<User>().Where(x => x.UserName == userDto.UserName).RowCount() > 0) { return new CreateUserResult { CreateUserStatus = CreateUserStatus.UserExists }; } string accountKey = _encryption.GenerateMd5HashString(_encryption.GenerateRandomString(8)); string hash; string salt; _encryption.GethashAndSaltString(userDto.Password, out hash, out salt); IList<Role> roles = session.QueryOver<Role>().Cacheable().CacheMode(CacheMode.Normal).Take(10).List<Role>(); var userEntity = new User { UserName = userDto.UserName, Password = hash, Salt = salt, PasswordExpires = _applicationConfiguration.PasswordExpirationDays, InvalidLoginAttempts = 0, AccountLocked = 0, AccountValidated = accountValidated, AccountKey = accountKey, Active = 1, LastLoginDate = DateTime.UtcNow, DateCreated = DateTime.UtcNow, LastUpdated = DateTime.UtcNow, Profile = new Profile { DisplayName = userDto.Profile.DisplayName, EmailAddress = userDto.Profile.EmailAddress, Bio = userDto.Profile.Bio, Active = 1, DateCreated = DateTime.UtcNow, LastUpdated = DateTime.UtcNow }, }; foreach (Role roleEntity in userDto.Roles.Where(role => roles.Any(x => x.Name == role)) .Select(role => roles.SingleOrDefault(x => x.Name == role)) .Where(roleEntity => roleEntity != null)) { userEntity.Roles.Add(roleEntity); } session.Save(userEntity); return new CreateUserResult { CreateUserStatus = CreateUserStatus.Success, User = new UserDto { UserId = userEntity.UserId, NamedIdentifier = userEntity.UserId, UserName = userEntity.UserName, Password = userEntity.Password, Salt = userEntity.Salt, PasswordExpirationDate = userEntity.PasswordExpires, InvalidLoginAttempts = userEntity.InvalidLoginAttempts, AccountLocked = userEntity.AccountLocked, AccountValidated = userEntity.AccountValidated, AccountKey = userEntity.AccountKey, Active = userEntity.Active, LastLoginDate = userEntity.LastLoginDate, DateCreated = userEntity.DateCreated, LastUpdated = userEntity.LastLoginDate, Profile = new ProfileDto { ProfileId = userEntity.Profile.ProfileId, DisplayName = userEntity.Profile.DisplayName, EmailAddress = userEntity.Profile.EmailAddress, Bio = userEntity.Profile.Bio, Active = userEntity.Profile.Active, DateCreated = userEntity.Profile.DateCreated, LastUpdated = userEntity.Profile.LastUpdated }, Roles = userEntity.Roles.Select(x => x.Name).ToList() } }; } catch (Exception exception) { _logger.Error(exception.Message); return new CreateUserResult { CreateUserStatus = CreateUserStatus.Failed }; } } Controller ActionResult: [AllowAnonymous] [ValidateAntiForgeryToken] [HttpPost] public ActionResult SignUp(UsersSignUpViewModel usersSignUpViewModel) { if (!ModelState.IsValid) { return View(usersSignUpViewModel); } string userName = usersSignUpViewModel.UserName; string password = usersSignUpViewModel.Password; string displayName = usersSignUpViewModel.DisplayName; string returnUrl = usersSignUpViewModel.ReturnUrl; if (!Url.IsLocalUrl(returnUrl) || string.IsNullOrEmpty(returnUrl)) { returnUrl = "/"; } var user = new UserDto { UserName = userName, Password = password, Roles = new[] {_applicationConfiguration.DefaultRole, "Admin"}, Profile = new ProfileDto { DisplayName = displayName, EmailAddress = userName } }; CreateUserResult createUserResult = _userService.CreateUser(user); switch (createUserResult.CreateUserStatus) { case CreateUserStatus.Success: UserDto userResult = createUserResult.User; ClaimsIdentity identity = _identityManager.GetIdentity(createUserResult.User); _owinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); return Json(new {authenticated=true,returnUrl=returnUrl}); case CreateUserStatus.Failed: break; case CreateUserStatus.UserExists: ModelState.AddModelError("UserName", "Unable to create account"); break; default: throw new ArgumentOutOfRangeException(); } return PartialView("_SignUp", usersSignUpViewModel); } A: Of course you should only return the properties required. If you wind up with several objects which only differ in a few properties, then that's ok. But don't include properties in the DTO that are not used in a particular situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/25656421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graphics.DrawLine lags when PictureBox SizeMode is set to Zoom I have a winforms app where I draw on an image in a picturebox. The drawing part works really well, except for lag when PictureBox.SizeMode = PictureBoxSizeMode.Zoom. The reason I set the SizeMode to Zoom is so I could zoom in and out of the image while preserving memory. Is there any way to speed up the drawing process? The code for the PictureBox's Paint method looks like so: pen = new Pen(color, 5); solidBrush = new SolidBrush(solid); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.ScaleTransform(PictureScale, PictureScale); foreach (List<Point> polygon in Polygons) { e.Graphics.DrawLines(pen, polygon.ToArray()); } if (NewPolygon != null) { Pen pp = new Pen(color, 5); if (NewPolygon.Count > 1) { e.Graphics.DrawLines(pp, NewPolygon.ToArray()); } if (NewPolygon.Count > 0) { using (Pen dashed_pen = pp) { dashed_pen.DashPattern = new float[] { 3, 3 }; e.Graphics.DrawLine(dashed_pen, NewPolygon[NewPolygon.Count - 1], NewPoint); } } } The code allows the user to draw a series of points connected by some solid lines. After adding the first point, there is a dotted line going from the previous point to the mouse's current position. The program 'fills' in the line when the user adds a new Point NewPolygon is a List<Point> object, and the program adds a point every time the user clicks. Pol is a List<List<Point>> object which holds NewPolygon. I attached a GIF of the drawing process because an image is worth 1000 words. The lag in the gif is not noticeable at all in different size modes. The if (NewPolygon.Count > 1) loop draws solid lines between at least 2 points. The if (NewPolygon.Count > 0) draws a dotted line between spot and NewPoint when there is at least one point. EDIT : full drawing code int x = 0; int y = 0; bool drag = false; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { Point spot = new Point((int)((float)(e.Location.X) / PictureScale), (int)((float)(e.Location.Y) / PictureScale)); if (e.Button == MouseButtons.Middle) { x = e.X; y = e.Y; drag = true; } else { if (NewPolygon != null) { if (e.Button == MouseButtons.Right) { if (NewPolygon.Count > 1) { int counter = NewPolygon.Count; Polygons.Add(NewPolygon); } NewPolygon = null; } else if (e.Button == MouseButtons.Left) { if (NewPolygon[NewPolygon.Count - 1] != spot) { NewPolygon.Add(spot); scaffolds.Add(new Rectangle(spot.X - 3, spot.Y - 3, 6, 6)); } } } else { NewPolygon = new List<Point>(); NewPoint = spot; NewPolygon.Add(spot); scaffolds.Add(new Rectangle(spot.X - 3, spot.Y - 3, 6, 6)); } } //this.Capture = true; pictureBox1.Refresh(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (drag) { pictureBox1.Top += e.Y - y; pictureBox1.Left += e.X - x; this.Cursor = Cursors.SizeAll; } else { if (NewPolygon == null) return; NewPoint = new Point((int)((float)(e.Location.X) / PictureScale), (int)((float)(e.Location.Y) / PictureScale)); pictureBox1.Refresh(); } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.ScaleTransform(PictureScale, PictureScale); foreach (Rectangle rect in scaffolds) { e.Graphics.DrawEllipse(pen, rect); } foreach (List<Point> polygon in Polygons) { e.Graphics.DrawLines(pen, polygon.ToArray()); } if (NewPolygon != null) { Pen pp = new Pen(color, 5); if (NewPolygon.Count > 0) { if (NewPolygon.Count > 1) { e.Graphics.DrawLines(pp, NewPolygon.ToArray()); } using (Pen dashed_pen = pp) { dashed_pen.DashPattern = new float[] { 3, 3 }; e.Graphics.DrawLine(dashed_pen, NewPolygon[NewPolygon.Count - 1], NewPoint); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/59850734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ipad Javascript slider I'm looking to create a slider/scroller with javascript for the iPad. I created one using JQuery UI, but it's not supported on iPad. I'm looking to create something simple, where the user can drag an image left and right along a track. I've looked all over the place for some simple insight on how to do that, all I find are tutorials or links to jquery plugins. I'm not sure I can use the built-in slider from jquery-mobile, as I have specific images to use, and it doesn't look like it can be skinned. Any help is welcome. A: jQuery Tools Scrollable is iPad/touch friendly. As an example, checkout the custom scrollable slider on trekk.com (works on iPad) that I built with jQuery Tools. A: I recently used a plugin called Flexslider (http://flex.madebymufffin.com/) that supports swiping between images on iOS.
{ "language": "en", "url": "https://stackoverflow.com/questions/9185138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do post request to external api using rest template? While I am executing this i getting an error like this ("Content type 'text/plain;charset=UTF-8' not supported]"). Please help me to get this problem resolved. public String saveCourse(CourseEntity courseDetails ) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<CourseEntity> entity = new HttpEntity<CourseEntity>(courseDetails,headers); return restTemplate.exchange( "http://localhost:8062/courses", HttpMethod.POST, entity, String.class).getBody(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/73412891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I queue and execute multiple promises asynchronously with a single callback? I am using the http request library got. With this package, http connections are asynchronous, fast, and easy to type out. The "got"cha is that got is a promisified package, which brings up several challenges for me. One is that I don't know how to pass around a reference to the got. What I need to do is use got together with file streams to download the page contents of several url's. Upon completion of all of these streams, I want to continue in the code. In this example instead of making an array of promises I am getting an array of response objects. const getFile = (fileUrl) => { return new Promise((resolve) => { got.stream(fileUrl).pipe(fs.createWriteStream(path.basename(fileUrl))) .on('finish', () => { successMessage('downloaded ' + fileUrl + '!'); resolve(); }); }); }; // create an array of these got promises let promises = [] for (let file of body.files) { promises.push(getFile(file)); } The reason the getFile helper exists is to wrap the got in a promise so that after performing all of the gots, I can use a promise.all call: // after all got's have executed promises.all(promises).then(() => { console.log('all promises resolved'); } Looking for assistance understanding how to change the first snippet so that promises.all behaves as anticipated. A: The Promise aggregation function is called Promise.all() not promises.all().
{ "language": "en", "url": "https://stackoverflow.com/questions/36700240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simulate ring (algebra) in SQL I'm creating small profile viewer and I want to simulate ring in SQL. How it works? For simple: I have 5 users on my table. When I get one from middle to my experiment (like user number 2,3,4) next and previous user is CURRENT_USER_ID +- 1. But when I choose user number 1 or 5 it's not that simply like before. So if I have some tool like algebra ring it's easy. Can I simulate it? Oh, I'm using MySQL. A: Like this: SQLFIDDLE set @curr_user = 1; set @maxid = (select max(u1.id) maxid from users u1); set @minid = (select min(u2.id) minid from users u2); set @next_user = (if(@curr_user = @maxid ,@minid ,@curr_user +1)); set @prev_user = (if(@curr_user = @minid ,@maxid ,@curr_user - 1)); SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser FROM users t1 join users t2 on 1=1 JOIN users t3 on 1=1 WHERE t1.id = @prev_user AND t2.id = @curr_user and t3.id = @next_user EDIT: I made a slight adjustment so it would work even if there are missing id's, let's say you have user 1,3,4,5,7 this would get user 4,5,7 if current is 5 SQLFIDDLE set @curr_user = 3; set @maxid = (select max(u1.id) maxid from users u1); set @minid = (select min(u2.id) minid from users u2); set @nextid = (select min(id) from users where id > @curr_user ); set @previd = (select max(id) from users where id < @curr_user ); set @next_user = (if(@curr_user = @maxid ,@minid ,@nextid)); set @prev_user = (if(@curr_user = @minid ,@maxid ,@previd)); SELECT t1.name as prevuser, t2.name as curruser, t3.name as nextuser FROM users t1 join users t2 on 1=1 JOIN users t3 on 1=1 WHERE t1.id = @prev_user AND t2.id = @curr_user and t3.id = @next_user
{ "language": "en", "url": "https://stackoverflow.com/questions/30574647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TransactionScope in MVC application I have an MVC 4 application, and while registering I have come across issue where data is saved in usertable but not in other table i.e user_detail etc.., to avoid that I tried to use tranascationScope well it worked for the registemethod as below. public ActionResult Register(model model) { using (var scope = new TransactionScope()) { WebSecurity.CreateUserAndAccount(model.RegUserName, randomPassword,....) // other table commit. // other table commit. } } Once after register a call is being made to any action method as below private void AuthenticateUser(string userName) { int userId = WebSecurity.GetUserId(userName); } The current TransactionScope is already complete. I am getting the above error and the connection is a single and using EF5. A: I'm not an expert on StructureMap, but from the error I guess, you're creating a single instance (Singleton) from the DBContext. which will give you this error. Once you start a transaction, the context will be aware of it and handle your work, but after the transaction is complete you can't resuse the same dbcontext instance, you need to create a new one. A preferred method in web apps is to use a Context Per Request. Here is an example I found on SO.
{ "language": "en", "url": "https://stackoverflow.com/questions/24739388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the possible solutions to make an application compatible with updated versions of Windows from XP to 8.1? Regarding the use of .NET Framework versions, what are the possible solutions to make an application compatible with updated versions (only with high-priority and important updates - not the optional updates because they may or may not be installed) of Windows from XP to 8.1? A: An application written in .NET C# should always be compatible with any version of windows that has the .NET Framework installed, there's only a small difference between the .NET Framework Client and Full versions (Has to do with certain features that the client version doesn't have, see it as a lightweight version of the .NET Framework, also since 4.5 it is discontinued => http://msdn.microsoft.com/en-us/library/cc656912.aspx)
{ "language": "en", "url": "https://stackoverflow.com/questions/22375382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Typecasting in WSO2 I have a property in my wso2 integration studio that stores the result of an arithmetic operation. The value of this property that is displayed in the logs is 12.0, how can I convert this property to integer type and make it 12?
{ "language": "en", "url": "https://stackoverflow.com/questions/73231316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What type of input does ResNet need? I am new to deep learning, and I am trying to train a ResNet50 model to classify 3 different surgical tools. The problem is that every article I read tells me that I need to use 224 X 224 images to train ResNet, but the images I have are of size 512 X 288. So my questions are: * *Is it possible to use 512 X 288 images to train ResNet without cropping the images? I do not want to crop the image because the tools are positioned rather randomly inside the image, and I think cropping the image will cut off part of the tools as well. *For the training and test set images, do I need to draw a rectangle around the object I want to classify? *Is it okay if multiple different objects are in one image? The data set I am using often has multiple tools appearing in one image, and I wonder if I must only use images that only have one tool appearing at a time. *If I were to crop the images to fit one tool, will it be okay even if the sizes of the images vary? Thank you. A: * *Is it possible to use 512 X 288 images to train ResNet without cropping the images? I do not want to crop the image because the tools are positioned rather randomly inside the image, and I think cropping the image will cut off part of the tools as well. * *Yes you can train ResNet without cropping your images. you can resize them, or if that's not possible for some reason, you can alter the network, e.g. add a global pooling at the very end and account for the different input sizes. (you might need to change kernel sizes, or downsampling rate). If your bigest issue here is that resnet requires 224x224 while your images are of size 512x228, the simplest solution would be to first resize them into 224x224. only if that`s not a possibility for you for some technical reasons, then create a fully convolutional network by adding a global pooling at the end.(I guess ResNet does have a GP at the end, in case it does not, you can add it.) *For the training and test set images, do I need to draw a rectangle around the object I want to classify? *For classification no, you do not. having a bounding box for an object is only needed if you want to do detection (that's when you want your model to also draw a rectangle around the objects of interest.) *Is it okay if multiple different objects are in one image? The data set I am using often has multiple tools appearing in one image, and I wonder if I must only use images that only have one tool appearing at a time. 3.Its ok to have multiple different objects in one image, as long as they do not belong to different classes that you are training against. That is, if you are trying to classify apples vs oranges, its obvious that, an image can not contain both of them at the same time. but if for example it contains anything else, a screwdriver, key, person, cucumber, etc, its fine. *If I were to crop the images to fit one tool, will it be okay even if the sizes of the images vary? It depends on your model. cropping and image size are two different things. you can crop an image of any size, and yet resize it to your desired dimensions. you usually want to have all images with the same size, as it makes your life easier, but its not a hard condition and based on your requirements you can have varying images, etc as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/67995015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using PDO to return a single set of values rather than an array A very nice person on this site helped me with the following script (and it worked a treat) <?php $db = new PDO('mysql:host=HOST;dbname=DATABASE', $user, $pass); $stmt = $db->prepare(' SELECT yeast, rating, description, weblink, image, sideimage FROM dowdb_yeast_selector WHERE fruit = :fruit ORDER BY rating DESC '); $stmt->bindParam(':fruit',$_POST['fruit'],PDO::PARAM_STR,50); $stmt->execute(); How do I just echo side image (not as part of a while loop)? I think (?) I need something like echo '$row[sideimage]' // how simple am I All of the examples I have looked at so far do not fit my needs :-( A: Use PDO::fetchAll, for example; $stmt->execute(); $arrResults = $stmt->fetchAll(); //$arrResults will be multidimensional //This will echo the first sideimage echo $arrResults[0]['sideimage']; If you want to echo all values of sideimage (ie: all rows), you'd have to iterate through the results; foreach($arrResults as $arrRow) { echo $arrRow['sideimage'] . PHP_EOL; } Links * *pdo::fetchAll A: You should use loop pdo::fetch() while($abc = $stmt->fetch()) { print_r($abc); } If you don't want to use loop try pdo::fetchAll() $data = $stm->fetchAll(); A: You could use FETCH_ASSOC $res = $stmt->fetchAll(PDO::FETCH_ASSOC); echo $res[0]['sideimage']; or foreach($res as $key=>$value) { $image_val = $value['sideimage']; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25991775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tensorflow theano.tensor.set_subtensor equivalent I am implementing an operation in keras, such that it can work on both theano and tensorflow backend. Suppose the input of the operation is: array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]], dtype=int64) then its output should be: array([[ 0, 1, 2, 3, 4, 5], [ 3, 4, 5, 0, 1, 2], [ 6, 7, 8, 9, 10, 11], [ 9, 10, 11, 6, 7, 8]], dtype=int64) My codes are as follows: from keras import backend as K def pairreshape(x,target_dim,input_shape): x1, x2 = x[0::2,], x[1::2,] x1_concate = K.concatenate((x1,x2), axis=target_dim) x2_concate = K.concatenate((x2,x1), axis=target_dim) if K.image_dim_ordering() == 'th': import theano.tensor as T x_new = T.repeat(x,2,axis=target_dim) x_new = T.set_subtensor(x_new[0::2], x1_concate) x_new = T.set_subtensor(x_new[1::2], x2_concate) elif K.image_dim_ordering() == 'tf': import tensorflow as tf repeats = [1] * len(input_shape) repeats[target_dim] = 2 x_new = tf.tile(x, repeats) x_new[0::2] = x1_concate #TypeError: 'Tensor' object does not support item assignment x_new[1::2] = x2_concate #TypeError: 'Tensor' object does not support item assignment I have successfully implemented it by theano, but I can not figure out how to assign a tensor by tensorflow. The last two lines of tensor assignment in tensorflow will report error. Is there a T.set_subtensor equivalence in tensorflow? or can you please recommend a better implementation of the operation? Thanks. A: TensorFlow tensors are read-only. In order to modify things you need to use variables and .assign (= can not be overriden in Python) tensor = tf.Variable(tf.ones((3,3))) sess.run(tf.initialize_all_variables()) sess.run(tensor[1:, 1:].assign(2*tensor[1:,1:])) print(tensor.eval()) Output [[ 1. 1. 1.] [ 1. 2. 2.] [ 1. 2. 2.]] A: It took a lot of searching, but the closest functions to theano.tensor.set_subtensor are gather, gather_nd, scatter, and scatter_nd. If you are trying to perform sparse updates to a variable, the other answers could work. But if you're trying to dynamically create a tensor from indexing another tensor, those are the functions to use. The point of these functions is to be able to dynamically create a tensor (not a variable) from something else. My use-case is I am generating a flat tensor and I am trying to reshape it into various triangular matrices. gather is what you use if you're trying to create a smaller matrix from a large sparse matrix. scatter is what you use if you're trying to embed a smaller matrix into a large zero matrix. Some combination of gather, scatter and addition and multiplication can recreate theano.tensor.set_subtensor. https://www.tensorflow.org/api_docs/python/tf/scatter_nd https://www.tensorflow.org/api_guides/python/array_ops#Slicing_and_Joining You could also use a very complicated set of slicing and concatenation, but gather and scatter would be preferred. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/41516058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: cannot find symbol:method getFactory() symbol: method getFactory() location: variable mapper of type org.codehaus.jackson.map.ObjectMapper I already added below jar Below is how I import them <%@ page import="java.io.*,java.util.*, javax.servlet.*,java.text.*" %> <%@ page import="javax.swing.*" %> <%@page import="java.text.DateFormat"%> <%@page import="java.text.SimpleDateFormat"%> <%@page import="java.sql.PreparedStatement"%> <%@ page language="java"%> <%@page import="java.sql.ResultSet"%> <%@page import="java.sql.Statement"%> <%@ include file="dbconfig.jsp" %> <%@page import="java.io.File"%> <%@page import="org.codehaus.jackson.map.ObjectMapper"%> <%@page import="java.net.*"%> <%@page import="org.codehaus.jackson.annotate.JsonIgnoreProperties" import=" org.codehaus.jackson.JsonEncoding" import=" org.codehaus.jackson.JsonFactory" import=" org.codehaus.jackson.JsonGenerationException" import=" org.codehaus.jackson.JsonGenerator" import=" org.codehaus.jackson.map.JsonMappingException" %> and below is my code ObjectMapper mapper = new ObjectMapper(); mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true); String jsonStr = mapper.writeValueAsString( jsonMap ); response.getOutputStream().print( jsonStr ); I get error in getFactory() and ESCAPE_NON_ASCII How to get rid of error in getFactory() and ESCAPE_NON_ASCII A: Your imports look like you are using Jackson 1.9.x which doesn't have a method getFactory() in ObjectMapper. There is a method getJsonFactory(), but you'd probably not need it. Just call mapper.configure( JsonGenerator.Feature.ESCAPE_NON_ASCII, true );
{ "language": "en", "url": "https://stackoverflow.com/questions/38630974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get download link after upload photo to firebase storage I tried to get a download URL like this but it is not getting correct URL. I am a beginner in Firebase, how can I do it? A: You can get the download URL like this fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { final Uri download_url = uri; } }): A: You can get your download path after uploading the file as follows (you need to call a second method on your reference object (getDownloadUrl): profilePicUploadTask = fileRef.putFile(imgUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // note: you can get the download path only after the file is uploaded successfully. // To get the download path you have to call another method like follows: fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { // uri is your download path } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/54177632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Lazy List with Images. How to cancel thread? I have found this example Lazy load of images in ListView from Fedor which is absolutely great for what I need. I have a question. if beside the Clear Cache button there would be a button with Cancel. How could I in onClick cancel the image download thread from the UI ? Thank you. Edit: I think that it already has this method implemented: public void stopThread() { photoLoaderThread.interrupt(); } But I don't know how to access it from the UI Thread. In UI Thread I only do this: adapter=new LazyAdapter(ctx, someString); setListAdapter(adapter); in LazyAdapter: public View getView(int position, View convertView, ViewGroup parent) { ... imageLoader.DisplayImage(imagePath, activity, holder.image); return vi; } and in ImageLoader public void DisplayImage(String url, Activity activity, ImageView imageView) { if(cache.containsKey(url)) imageView.setImageBitmap(cache.get(url)); else { queuePhoto(url, activity, imageView); imageView.setImageResource(stub_id); } } private void queuePhoto(String url, Activity activity, ImageView imageView) { //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. photosQueue.Clean(imageView); PhotoToLoad p=new PhotoToLoad(url, imageView); synchronized(photosQueue.photosToLoad){ photosQueue.photosToLoad.push(p); photosQueue.photosToLoad.notifyAll(); } //start thread if it's not started yet if(photoLoaderThread.getState()==Thread.State.NEW) photoLoaderThread.start(); } But I think an clear way is to download the sources from link text Thank you for your help. A: Just put adapter.imageLoader.stopThread(); to "Cancel" button click handler A: You can write your own custom class which extends the Java Thread class. There you implement a public stop-method which stop the thread itself. When you create and start your thread you hold a reference to it and call the public stop-method in the OnClickEventHandler of the cancel button.
{ "language": "en", "url": "https://stackoverflow.com/questions/3837277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: disable y-axis max and min values on nvd3 boxplot I am using nvd3 boxplot and would like to remove the max and min values being shown in the plot. For example, I do not want the values 7 and 68 to be displayed on the y-axis for the chart below. Any suggestions as to how I can do it. Thanks. A: An alternative to the object property and deletion methods is calling the showMaxMin method on the chart object itself: chart.yAxis.showMaxMin(false); A: After rendering the chart do: d3.selectAll(".nv-axisMaxMin-y").remove(); //it will remove the max min Working code here Hope this helps! A: set chart : { yAxis: { showMaxMin : false } }
{ "language": "en", "url": "https://stackoverflow.com/questions/34500985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to coalesce when all records are missing a column? I'm reading multiple JSON files into a dataframe in Scala. A few files are missing a column (e.g. the column header) while other files have it. I want to add the column for those records where it doesn't exist and populate with a default value "Missing". How to do it without impacting the records which already have the column? I tried the below code, however, it only works if atleast one record has the column. If none of the records have the column, it errors out saying column Seq_num not found: df.withColumn("Seq_num", coalesce(col("Seq_num"),lit("0"))) Error: cannot resolve 'Seq_num' given input columns A: Define a function that first check if the column exists in the dataframe. If the column does not exist, simply add it. In the case it already exists then use coalesce as before. This can be done as follows: def coalesceColumn(df: DataFrame, column: String, default: String) = { Try(df(column)).toOption match { case Some(_) => df.withColumn(column, coalesce(col(column), lit(default))) case _ => df.withColumn(column, lit(default)) } } val df2 = coalesceColumn(df, "Seq_num", "0") Note that it's possible to use df.columns.contains(column) to do the column check but in that case nested columns are not supported.
{ "language": "en", "url": "https://stackoverflow.com/questions/54111196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Persistent volume claim - mount path I have a pv like below apiVersion: v1 kind: PersistentVolume metadata: name: azurefile spec: capacity: storage: 5Gi accessModes: - ReadWriteMany storageClassName: azurefile azureFile: secretName: azure-secret shareName: cloudshare readOnly: false and a pvc like below apiVersion: v1 kind: PersistentVolumeClaim metadata: name: azurefile spec: accessModes: - ReadWriteMany storageClassName: azurefile resources: requests: storage: 2Gi on deployments i have the following volumes: - name: my-storage persistentVolumeClaim: claimName: azurefile volumeMounts: - name: my-storage mountPath: "/home/myapp/newapp/" My understanding is that under the path /home/myapp/newapp/ in the containers ,the azure fileshare cloudshare's content will be accessible. So, whatever i have in cloudshare will be visible here. Does pvc or pv creates folders under the cloudshare? , the reason i ask is , I have a WORKDIR in my dockerimage which is actually in the same mountpath like below WORKDIR /home/myapp/newapp/reta-app/ . For some reason reta-app folder is getting created inside the cloudshare. Is this a normal behaviour or i am doing something wrong. A: Does pvc or pv create folders under the cloudshare? No. A Kubernetes PersistentVolume is just some storage somewhere, and a PersistentVolumeClaim is a way of referencing a PV (that may not immediately exist). Kubernetes does absolutely no management of any of the content in a persistent volume; it will not create directories on startup, copy content from the image into a volume, or anything else.
{ "language": "en", "url": "https://stackoverflow.com/questions/61034079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to change values of a dropdown on key press using jquery i need to change values of a "Focused" dropdown on keypress using jquery. i need, * *how i get a foucsed drop down or how i can check whether the drop down has focus. *how to change this drop down values in key press like 1,2,3 etc. using JQUERY. thanks in advance. A: To see if object is selected: if($(".foo").is(':focus')){ // do something } To change values on keypress: $(".foo").bind("keypress", function(e){ $(this).attr('value', 'bar'); }) Though not sure what you mean by changing the values of a drop down, or why you'd want to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/5101835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What can be the possible causes for "Unknown path components"? I created a Facebook app and some custom Open Graph Actions and Types. When i use the sample code from the Open Graph Dashboard to create an action i get the following error: {"error":{"message":"Unknown path components: \/NAMESPACE:ACTION","type":"OAuthException","code":2500}} I am sure i authenticated the app for my account and it has the right permissions to publish actions for that app. What else can i check or do i have to make sure of that i don't get this error?
{ "language": "en", "url": "https://stackoverflow.com/questions/13513249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Filtering Products by an Option in Spree With Spree Commerce 3.0-stable, I need to write a custom product filter to show only products where at least one variant matches the selected OptionValue. I've got a filter that displays the correct list of options in the checkboxes, but selecting an option doesn't change which products are returned. For this example, Products are available in multiple "Metal" options (platinum, white gold, yellow gold, silver, etc.). I've got the price range filter set up, and it's working correctly. How can I get the products to filter by an Option? My lib/spree/product_filters.rb module Spree module Core module ProductFilters # Example: filtering by price # The named scope just maps incoming labels onto their conditions, and builds the conjunction # 'price' is in the base scope's context (ie, "select foo from products where ...") so # we can access the field right away # The filter identifies which scope to use, then sets the conditions for each price range # # If user checks off three different price ranges then the argument passed to # below scope would be something like ["$10 - $15", "$15 - $18", "$18 - $20"] # Spree::Product.add_search_scope :price_range_any do |*opts| conds = opts.map {|o| Spree::Core::ProductFilters.price_filter[:conds][o]}.reject { |c| c.nil? } scope = conds.shift conds.each do |new_scope| scope = scope.or(new_scope) end Spree::Product.joins(master: :default_price).where(scope) end def ProductFilters.format_price(amount) Spree::Money.new(amount) end def ProductFilters.price_filter v = Spree::Price.arel_table conds = [ [ Spree.t(:under_price, price: format_price(1000)) , v[:amount].lteq(1000)], [ "#{format_price(1000)} - #{format_price(1500)}" , v[:amount].in(1000..1500)], [ "#{format_price(1500)} - #{format_price(1800)}" , v[:amount].in(1500..1800)], [ "#{format_price(1800)} - #{format_price(2000)}" , v[:amount].in(1800..2000)], [ Spree.t(:or_over_price, price: format_price(2000)) , v[:amount].gteq(2000)]] { name: Spree.t(:price_range), scope: :price_range_any, conds: Hash[*conds.flatten], labels: conds.map { |k,v| [k, k] } } end # Test for discrete option values selection def ProductFilters.option_with_values(option_scope, option, values) # get values IDs for Option with name {@option} and value-names in {@values} for use in SQL below option_values = Spree::OptionValue.where(:presentation => [values].flatten).joins(:option_type).where(OptionType.table_name => {:name => option}).pluck("#{OptionValue.table_name}.id") return option_scope if option_values.empty? option_scope = option_scope.where("#{Product.table_name}.id in (select product_id from #{Variant.table_name} v left join spree_option_values_variants ov on ov.variant_id = v.id where ov.option_value_id in (?))", option_values) option_scope puts option_scope.inspect end # multi-option scope Spree::Product.scope :option_any, lambda { |*opts| option_scope = Spree::Product.includes(:variants_including_master) opts.map { |opt| # opt is an array => ['option-name', [value1, value2, value3, ...]] option_scope = option_with_values(option_scope, *opt) } option_scope } # metal filter def ProductFilters.metal_filter metals = Spree::OptionValue.where( :option_type_id => Spree::OptionType.find_by!(name: "Metal") ).order("position").map(&:presentation).compact.uniq { :name => "Metal Type", :scope => :option_any, :conds => nil, :option => 'metal', :labels => metals.map { |k| [k, k] } } end end end end My app/views/spree/home/index.html.erb <% content_for :sidebar do %> <div data-hook="homepage_sidebar_navigation"> <%= render :partial => 'spree/shared/filters' %> <%= render :partial => 'spree/shared/taxonomies' %> </div> <% end %> <h2>Test!</h2> <div data-hook="homepage_products"> <% cache(cache_key_for_products) do %> <%= render :partial => 'spree/shared/products', :locals => { :products => @products } %> <% end %> </div> My app/views/spree/shared/_filters.html.erb <% filters = [Spree::Core::ProductFilters.metal_filter,Spree::Core::ProductFilters.price_filter] %> <% unless filters.empty? %> <%= form_tag '', :method => :get, :id => 'sidebar_products_search' do %> <%= hidden_field_tag 'per_page', params[:per_page] %> <% filters.each do |filter| %> <i><%= filter[:name] %> </i> <% labels = filter[:labels] || filter[:conds].map {|m,c| [m,m]} %> <% next if labels.empty? %> <div class="navigation" data-hook="navigation"> <h4 class="filter-title"> <%= filter[:name] %> </h4> <ul class="list-group"> <% labels.each do |nm,val| %> <% label = "#{filter[:name]}_#{nm}".gsub(/\s+/,'_') %> <li class="list-group-item"> <input type="checkbox" id="<%= label %>" name="search[<%= filter[:scope].to_s %>][]" value="<%= val %>" <%= params[:search] && params[:search][filter[:scope]] && params[:search][filter[:scope]].include?(val.to_s) ? "checked" : "" %> /> <label class="nowrap" for="<%= label %>"> <%= nm %> </label> </li> <% end %> </ul> </div> <% end %> <%= submit_tag Spree.t(:search), :name => nil, :class => 'btn btn-primary' %> <% end %> <% end %> A: David Gross's answer above worked for me, although I am using the option of colour. Here's what my code looks like and the steps I took to get it to work. 1) Copy an unedited version of product_filters.rb to lib/product_filters.rb 2) Initialise it: in initializers/spree.rb, add in: require 'product_filters' # Spree.config do |config| etc........ 3) Add this code to product_filters.rb: def ProductFilters.option_with_values(option_scope, option, values) # get values IDs for Option with name {@option} and value-names in {@values} for use in SQL below option_values = Spree::OptionValue.where(:presentation => [values].flatten).joins(:option_type).where(OptionType.table_name => {:name => option}).pluck("#{OptionValue.table_name}.id") return option_scope if option_values.empty? option_scope = option_scope.where("#{Product.table_name}.id in (select product_id from #{Variant.table_name} v left join spree_option_values_variants ov on ov.variant_id = v.id where ov.option_value_id in (?))", option_values) option_scope end # option scope Spree::Product.add_search_scope :option_any do |*opts| option_scope = Spree::Product.includes(:variants_including_master) option_type = ProductFilters.colour_filter[:option] opts.map { |opt| # opt is an array => ['option-name', [value1, value2, value3, ...]] option_scope = ProductFilters.option_with_values(option_scope, option_type, *opt) } option_scope end # colour option - object that describes the filter. def ProductFilters.colour_filter # Get an array of possible colours (option type of 'colour') # e.g. returns ["Gold", "Black", "White", "Silver", "Purple", "Multicoloured"] colours = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("colour")).order("position").map(&:presentation).compact.uniq { :name => "Colour", :scope => :option_any, :conds => nil, :option => 'colour', # this is MANDATORY :class => "colour", :labels => colours.map { |k| [k, k] } } end 4) Add your new filter to app/models/spree/taxons.rb so it appears on the front end: def applicable_filters fs = [] # fs << ProductFilters.taxons_below(self) ## unless it's a root taxon? left open for demo purposes fs << Spree::Core::ProductFilters.price_filter if Spree::Core::ProductFilters.respond_to?(:price_filter) fs << Spree::Core::ProductFilters.brand_filter if Spree::Core::ProductFilters.respond_to?(:brand_filter) fs << Spree::Core::ProductFilters.colour_filter if Spree::Core::ProductFilters.respond_to?(:colour_filter) fs end That should be it. I hope that helps - let me know if I can help further. Unfortunately the Spree filtering docs are nonexistent so we have to make do. A: I dont know exactly what Spree::Product.scope is doing but try changing it to Spree::Product.add_search_scope. You are also missing an argument OptionType in option_with_values, you can use ProductFilters.metal_filter[:option]. Spree::Product.add_search_scope :option_any do |*opts| option_scope = Spree::Product.includes(:variants_including_master) option_type = ProductFilters.metal_filter[:option] opts.map { |opt| # opt is an array => ['option-name', [value1, value2, value3, ...]] option_scope = ProductFilters.option_with_values(option_scope, option_type, *opt) } option_scope end
{ "language": "en", "url": "https://stackoverflow.com/questions/35190934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unwanted (meta?) data in Ruby/Rails I have two models (questions and answers) that slightly follow the popular Railscasts: class Question < ActiveRecord::Base has_many :answers accepts_nested_attributes_for :answers, :allow_destroy => true end class Answer < ActiveRecord::Base belongs_to :question attr_accessible :content end The answers are built (for the purposes of my application) inside the edit method of my question_controller.rb: 2.times do @question.answers.build end and rendered inside the edit view - edit.html.haml as: = f.fields_for :answers do |builder| = render "answer_fields", :f => builder The problem appears when I want to show the answers. Inside show.html.haml, I do: = for answer in @question.answers = answer.content The answer contents are shown, but I also get this (unwanted) HTML code: [#&lt;Answer id: 11, question_id: 22, content: &quot;100&quot;, created_at: &quot;2012-04-02 08:34:50&quot;, updated_at: &quot;2012-04-02 08:34:50&quot;&gt;,] Any thoughts on how to remove this? I can't find any reason for the presence of this additional data. Many thanks in advance! A: Replace = for answer in @question.answers = answer.content With - for answer in @question.answers = answer.content (The first version prints out the content of @question.answers, the second just runs the loop) See the haml documentation for inserting ruby vs running ruby
{ "language": "en", "url": "https://stackoverflow.com/questions/9973476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PrimeFaces Datatable Column Sorting is not working in IE8 but it works fine in Firefox PrimeFaces Datatable Column Sorting is not working in IE8 but it works fine in Firefox. Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Timestamp: Thu, 17 Feb 2011 17:56:48 UTC Message: Unexpected call to method or property access. jquery.js.jsf Line: 23 Char: 21078 Code: 0 URI: http://localhost:8080/PrimeFacesTutorial/javax.faces.resource/jquery/jquery.js.jsf?ln=primefaces&v=2.2.1 A: You might have: <h:form id="form1"> ..... <h:form id="form2"> ... </h:form> ... </h:form> I got the same error, I remove the nested Form. I removed Form2 and it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/5033224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Report item width of items in TreeView via NM_CUSTOMDRAW? Is there a WM_MEASUREITEM type item for custom drawing treeview items via NM_CUSTOMDRAW? I'd like to be able to report the width the item will actually be once I paint it in the post paint so a horizontal scrollbar doesn't show up when not needed (because I truncate the text with a ...). Thanks. A: AFAIK, there is no equivalent of WM_MEASUREITEM for a TreeView control.
{ "language": "en", "url": "https://stackoverflow.com/questions/74911059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IONIC 3 how to get current date/time from google servers for specific country? I'm working on IONIC 3 app, I have a button When it is pressed, some informations about the user location are sent to firebase .. i want to send the current date/time too with the geolocation informations .. but not the device's date/time of course. any help ? this is my function to send informations : addAgentCoords(){ this.gpsCoordsRef$.push({ latitude: this.lat, longitude: this.long, accuracy: this.acc, altitude: this.alt, altitudeAccuracy: this.altacc, speed: this.spd //dateTime: ?? }); A: You can use something like this: var d = new Date(); var dd = d.getDate(); var mm = d.getMonth() + 1; var yy = d.getFullYear(); var myDateString = dd + '_' + mm + '_' + yy; And change the last variable to anything you want. A: Firstly you need to timestamp from geolocation plugin in a variable like lat let us consider timestamp in timestamp variable Then Try it this.gpsCoordsRef$.push({ latitude: this.lat, longitude: this.long, accuracy: this.acc, altitude: this.alt, altitudeAccuracy: this.altacc, speed: this.spd, dateTime: new Date(timestamp) }); Check converting timestamp to dateTime click here
{ "language": "en", "url": "https://stackoverflow.com/questions/49242974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read from text file C++ (fname, lname, class, seat number), store and verify I have a text file of the classlook like this: FName LName Class SeatNum FName2 LName2 Class2 SeatNum2 ... and the list goes on. How to read lines of strings and store them into different variables? How to combine Class & SeatNum to be an ID (3D-20)? How to verify for every input name and ID has to be matched? For example, input > FName LName Class2-SeatNum2 is wrong, please try again. Your help is greatly appreciated. Thanks! A: Just a note for next time - because you didn't detail the problem, it was hard to figure out what you mean. Anyhow: in order to do what you asked you need to: a) read the data from the file b) split the data based on the character which is between the cells. In C++, The split string algorithm is in boost - if you dont know what that is, make sure you take a look in here: http://www.boost.org/ Soltion: I`m modifying various cPlusPlus guides here to fit your purpouse: #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> using namespace std; vector<string> getData (string filePath) { vector<string> Cells; // In the end, here we will store each cell's content. stringstream fileContent(""); // This is a string stream, which will store the database as a string. ofstream myfile; // the file which the database is in myfile.open (filePath); // Opening the file while ( getline (myfile,line) ) // Reading it until it's over { fileContent << line; // adding each line to the string } split(Cells, fileContent.str(), is_any_of(" "));// Here, insert the char which seperates the cells from each other. myfile.close() return Cells; // returning the split string. } Hope i helped :)
{ "language": "en", "url": "https://stackoverflow.com/questions/27836150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: I have a PHP problem like I have update my code, but now it shows error like SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected users.php: ''' class users { private $id; private $name; private $email; private $login_status; private $last_login; private $db_conn; function setID($id){ $this->id = $id; } function getID($id){ return $this->id; } function setName($name){ $this->name = $name; } function getName($name){ return $this->name; } function setEmail($email){ $this->email = $email; } function getEmail($email){ return $this->email; } function setLoginStatus($login_status){ $this->login_status = $login_status; } function getLoginStatus($login_status){ return $this->login_status; } function setLastLogin($last_login){ $this->last_login = $last_login; } function getLastLogin($last_login){ return $this->last_login; } public function __construct() { require_once("db_conn.php"); $db = new db_conn(); $this->db_conn = $db->connect(); } public function save() { $sql = "INSERT INTO users ('id', 'name', 'email', 'login_status', 'last_login') VALUES (null, :name, :email, :login_status, :last_login)"; $stmt = $this->db_conn->prepare($sql); $stmt->bindParam(":name", $this->name); $stmt->bindParam(":email", $this->email); $stmt->bindParam(":login_status", $this->login_status); $stmt->bindParam(":last_login", $this->last_login); try{ if($stmt->execute()){ return true; }else{ return false; } }catch(Exception $e){ echo $e->getMessage(); } } } ''' db_conn.php ''' class db_conn{ private $host = 'localhost'; private $db = 'webapp'; private $user = 'root'; private $pass = ''; public function connect(){ try{ $conn = new PDO('mysql:host=' . $this->host . '; db=' . $this->db, $this->user, $this->pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; }catch(PDOException $e){ echo 'Database Error: ' . $e->getMessage(); } } } ?> ''' When I run my file, it shows error like this : I have update my code, but now it shows error like SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected. I have search at Stackoverflow but still not find the right solution. Please help me. A: Your code must use backticks for all columns and not apostrophes $sql = "INSERT INTO `users` (`id`, `name`, `email`, `login_status`, `last_login`) VALUES (null, :name, :email, :login_status, :last_login)"; For your Problem with no database selected check your connection string, if there is a Databasename . But you can always send a sql query use Databasename; Or use the correct sy code instead old db= it must be dbname= class db_conn{ private $host = 'localhost'; private $db = 'webapp'; private $user = 'root'; private $pass = ''; public function connect(){ try{ $conn = new PDO('mysql:host=' . $this->host . '; dbname=' . $this->db, $this->user, $this->pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; }catch(PDOException $e){ echo 'Database Error: ' . $e->getMessage(); } } A: You have single quotes arround table name users Change this line : $sql = "INSERT INTO 'users' ('id', 'name', 'email', 'login_status', 'last_login'); To : $sql = "INSERT INTO users (id, name, email, login_status, last_login) VALUES (null, :name, :email, :login_status, :last_login)";
{ "language": "en", "url": "https://stackoverflow.com/questions/59349317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Error while writing pixel values in a raster file using node gdal Using the following code to raster file: const gdal = require('gdal'); const dataset = gdal.open('raster.bip'); const band = dataset.bands.get(1); band.pixels.write(0, 0, 1, 1, new Float32Array([-1111])); But getting following error: /Users/alok/Smart Market/Code/OpenNetwork/node_modules/gdal/lib/gdal.js:681 return write.apply(this, [x, y, width, height, data, options.buffer_width, options.buffer_height, options.pixel_space, options.line_space]); ^ Error: Failed to write 4 bytes to file. 0 bytes written at RasterBandPixels.write (/Users/alok/Smart Market/Code/OpenNetwork/node_modules/gdal/lib/gdal.js:681:16) at Object.<anonymous> (/Users/alok/Smart Market/Code/OpenNetwork/coverage/WriteTest.js:99:15) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:422:7) at startup (bootstrap_node.js:143:9) Please help. A: Instead of const dataset = gdal.open('raster.bip'); use const dataset = gdal.open('raster.bip', gdal.GA_Update); to allow writing to raster.bip
{ "language": "en", "url": "https://stackoverflow.com/questions/44105609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using DNS SRV records with C# Is there a built in (to the .net framework) class or function to resolve a SRV entry to the corresponding records? IE: _dmsc._tcp.network.local to an array of information (host, port, weight, priority) A: Alternative solution: P/Invoke to the DnsQuery function and pass DNS_TYPE_SRV. An example can be found in this excellent post by Ruslan. I reproduce the code below in case the link breaks, but emphasize it is taken directly from his blog. public class nDnsQuery { public nDnsQuery() { } [DllImport("dnsapi", EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] private static extern int DnsQuery([MarshalAs(UnmanagedType.VBByRefStr)]ref string pszName, QueryTypes wType, QueryOptions options, int aipServers, ref IntPtr ppQueryResults, int pReserved); [DllImport("dnsapi", CharSet = CharSet.Auto, SetLastError = true)] private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType); public static string[] GetSRVRecords(string needle) { IntPtr ptr1 = IntPtr.Zero; IntPtr ptr2 = IntPtr.Zero; SRVRecord recSRV; if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new NotSupportedException(); } ArrayList list1 = new ArrayList(); try { int num1 = nDnsQuery.DnsQuery(ref needle, QueryTypes.DNS_TYPE_SRV, QueryOptions.DNS_QUERY_BYPASS_CACHE, 0, ref ptr1, 0); if (num1 != 0) { if (num1 == 9003) { list1.Add("DNS record does not exist"); } else { throw new Win32Exception(num1); } } for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recSRV.pNext) { recSRV = (SRVRecord)Marshal.PtrToStructure(ptr2, typeof(SRVRecord)); if (recSRV.wType == (short)QueryTypes.DNS_TYPE_SRV) { string text1 = Marshal.PtrToStringAuto(recSRV.pNameTarget); text1 += ":" + recSRV.wPort; list1.Add(text1); } } } finally { nDnsQuery.DnsRecordListFree(ptr1, 0); } return (string[])list1.ToArray(typeof(string)); } private enum QueryOptions { DNS_QUERY_ACCEPT_TRUNCATED_RESPONSE = 1, DNS_QUERY_BYPASS_CACHE = 8, DNS_QUERY_DONT_RESET_TTL_VALUES = 0x100000, DNS_QUERY_NO_HOSTS_FILE = 0x40, DNS_QUERY_NO_LOCAL_NAME = 0x20, DNS_QUERY_NO_NETBT = 0x80, DNS_QUERY_NO_RECURSION = 4, DNS_QUERY_NO_WIRE_QUERY = 0x10, DNS_QUERY_RESERVED = -16777216, DNS_QUERY_RETURN_MESSAGE = 0x200, DNS_QUERY_STANDARD = 0, DNS_QUERY_TREAT_AS_FQDN = 0x1000, DNS_QUERY_USE_TCP_ONLY = 2, DNS_QUERY_WIRE_ONLY = 0x100 } private enum QueryTypes { DNS_TYPE_A = 0x0001, DNS_TYPE_MX = 0x000f, DNS_TYPE_SRV = 0x0021 } [StructLayout(LayoutKind.Sequential)] private struct SRVRecord { public IntPtr pNext; public string pName; public short wType; public short wDataLength; public int flags; public int dwTtl; public int dwReserved; public IntPtr pNameTarget; public short wPriority; public short wWeight; public short wPort; public short Pad; } } A: Open source, BSD licensed library here: http://dndns.codeplex.com/ A: This looks like another great candidate and is Apache 2.0 licensed. Latest build was Thu Dec 17, 2015 at 3:00 AM
{ "language": "en", "url": "https://stackoverflow.com/questions/1126664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PostgreSQL: How to avoid divide by zero? I am trying to get the average occupation rate from table occu_cap but I am getting the error "ERROR: division by zero". There are 0 values in both columns. I've been looking at using NULLIF(column_name,0) but I can't figure out how to implement this into the code below. SELECT *, AVG((occupancy/capacity) * 100)) AS avg_occupancy_rate FROM occu_cap GROUP BY 1,2,3 Sample data and expected result: occupancy capacity avg_occupancy_rate 1232 1630 75.58 0 658 null 0 0 null A: The error was caused that capacity was 0 value (which might not allow from math divide), if your expected result is 0 when capacity is 0 from occupancy/capacity AVG((COALESCE(occupancy / NULLIF(capacity,0), 0) * 100)) Edit You can try to use CASE WHEN expression to judge the value whether zero then return NULL AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) If you want to show all of columns you can try to use the window function. SELECT *,AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) OVER(PARTITION BY id) FROM occu_cap NOTE If your occupancy or capacity is not a type of a float-point number we need to CAST that as a float-point number before doing AVG sqlfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/71806757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Robot Framework and Django I am trying to use Robot Framework to acceptance testing my django app. The thing is, that to test my django app I need to call ./manage.py runserver To start the server. Can I make Robot Framework to do it for me? And stop it after the tests of course. Or, even better, it is possible to make that the tests suites runs under the django LiveServerTestCase? A: Take a look at https://github.com/kitconcept/robotframework-djangolibrary which seems to handle exactly this. Or, even better, it is possible to make that the tests suites runs under the Django LiveServerTestCase? This is a much more interesting approach as we could then mix robot tests with other tests. I'll post here if I figure out how to do it. A: Robot has a library named Process which is specifically designed for starting and stopping processes. You can use the Start Process and Terminate Process keywords to start and stop the webserver via a suite setup and suite teardown. It would look something like this: *** Settings *** | Library | Process | Suite Setup | Start the webserver | Suite Teardown | Stop the webdserver *** Keywords *** | Start the webserver | | ${django process}= | Start process | python | manage.py | | Set suite variable | ${django process} | Stop the webserver | | Terminate Process | ${django process} Of course, you'll want to add some bullet proofing such as making sure the process actually starts, and possibly catching errors if it doesn't exit cleanly. You will also probably need to give an explicit path to manage.py, but hopefully this gives the general idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/27056510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Jquery how do I add +1 to a number in a table So I am generating a table with php/mysql, and in this table are numbers in rows. I have a button that when clicked, adds +1 to this number value in the MySQL database. The problem is, I have to refresh the page for the new number to show up in the table. I am attempting to show the new number immediatly through a function on the success of the jquery button click event. So essentially I need to identify the HTML generated number in the table, then add +1 to it. The problem is, the table is generated with a while function in php, so each row gets its own ID on the fly. Hope this all makes sense. Here is my Jquery code so far. $('.upArrow').click(function(){ //this is finding the uparrow button that adds +1 var row = $(this).attr('rowid'); $.ajax({ type: "GET", url: "upArrow.php?id="+row, cache: false, async: false, success: function(result){ //this is tricky part, how do I select the displayed number part of the // table, then Add 1? }, error: function(result){ alert('Error, please try again.'); } }); }); Edit: Here is a piece of my HTML table: <td id="musicDisplay" colspan="2"> <div id="newUpArrow"> <a href="javascript:void(0)" class = "upArrow" rowid="' . $row['id'] . '"><img src="../Img/upArrow.gif"/> </a> </div> <!--Here is the number I want to change.--> <div>'. $row['points'] . '</div> </td> A: In theory, you'll want to set the context of your ajax request to the element containing the text you want. Then on success, you would increase the number in that context. $.ajax({ /* everything else as before */ context: $('selector for element containing number to increase'), success: function(result) { $(this).html(parseInt($(this).html(), 10) + 1); } }); This assumes that the content of the context element will always be a single integer If you need to select a cell by it's column and row, you could do the following: var column = 1; var row = 1; var $cell = $('table tr:eq(' + row + ') td:eq(' + column + ')'); $cell.html(parseInt($cell.html(), 10) + 1); See fiddle: http://jsfiddle.net/xixionia/4HLp9/ Although, you would need to change "table" to a table's id, otherwise you'll end up selecting all of the cells from every table at that row in and column. Note: Having seen your html, we would be able to provide a much more detailed description of how to select the desired cell. A: How many rows do you have? It might make sense just to re-generate the table from the AJAX call and reload the html on it's way back.
{ "language": "en", "url": "https://stackoverflow.com/questions/5982603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass a cython allocated buffer to python I am aware of this post about passing over Cython malloc'ed data to Python. I however wonder if casting to a memoryview before returning avoids the memory leak: def someCythonFunction(): try: mPtr = <double *>PyMem_Malloc(N * M * sizeof(double) for n in range(N): for m in range(M): mPtr[m + n*M]= ... return <double[:N,:M]> mPtr finally: print("In cython %d" % <int>mPtr) PyMem_Free(mPtr) then in Python: mView = someCythonFunction() Is this safe and correct ? A: This is unsafe and incorrect. It deallocates the memory as the function ends which means the pointer that you return is immediately invalid. You need to tie the lifetime of the memory to the lifetime of a Python object (as in the example you linked to, the memory is freed in the destructor). The simplest and recommended way of doing this is to use a numpy array or a standard library array array (or other library of your choice). If you can't avoid using malloc one option is to use the cython.view.array class. You can assign it a callback function of your choice to use on destruction and it can be happily assigned to memoryviews: cdef double[:,:] mview cdef double* mPtr = <double *>PyMem_Malloc(N * M * sizeof(double)) a = cython.view.array(shape=(N, M), itemsize=sizeof(double), format="d", mode="C", allocate_buffer=False) a.data = <char *> mPtr a.callback_free_data = PyMem_Free mview = a You can safely return either a or mview (if you return a then there's no need to bother with mview) and they will get correctly at the right time.
{ "language": "en", "url": "https://stackoverflow.com/questions/44436046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multiple successes in Coq branching and backtracking? I am having trouble understanding the concept of multiple successes in Coq's (8.5p1, ch9.2) branching and backtracking behavior. For example, from the documentation: Backtracking branching We can branch with the following structure: expr1 + expr2 Tactics can be seen as having several successes. When a tactic fails it asks for more successes of the prior tactics. expr1 + expr2 has all the successes of v1 followed by all the successes of v2. What I don't understand, is why do we need multiple successes in the first place? Isn't one success good enough to finish a proof? Also from the documentation, it seems that there are less costly branching rules that are somehow "biased", including first [ expr1 | ::: | exprn ] and expr1 || expr2 Why do we need the more costly option + and not always use the latter, more efficient tacticals? A: The problem is that you are sometimes trying to discharge a goal but further subgoals might lead to a solution you thought would work to be rejected. If you accumulate all the successes then you can backtrack to wherever you made a wrong choice and explore another branch of the search tree. Here is a silly example. let's say I want to prove this goal: Goal exists m, m = 1. Now, it's a fairly simple goal so I could do it manually but let's not. Let's write a tactic that, when confronted with an exists, tries all the possible natural numbers. If I write: Ltac existNatFrom n := exists n || existNatFrom (S n). Ltac existNat := existNatFrom O. then as soon as I have run existNat, the system commits to the first successful choice. In particular this means that despite the recursive definition of existNatFrom, when calling existNat I'll always get O and only O. The goal cannot be solved: Goal exists m, m = 1. Fail (existNat; reflexivity). Abort. On the other hand, if I use (+) instead of (||), I'll go through all possible natural numbers (in a lazy manner, by using backtracking). So writing: Ltac existNatFrom' n := exists n + existNatFrom' (S n). Ltac existNat' := existNatFrom' O. means that I can now prove the goal: Goal exists m, m = 1. existNat'; reflexivity. Qed.
{ "language": "en", "url": "https://stackoverflow.com/questions/38256705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Positioning an input rotated 90 degrees inside a div I made input range vertical via javascript like this: var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)"; range_pitch.style.oTransform = "rotate(90deg)"; range_pitch.style.msTransform = "rotate(90deg)"; range_pitch.style.transform = "rotate(90deg)"; But I cannot place it into created <div> (doesn't work for me): vertical_slider.appendChild( range_pitch ); document.body.appendChild( vertical_slider ); Here is My fiddle Is there any solution, please? A: Fixed fiddle Check the DOM in your browser console you can see that the input is already inside the div, you should just adjust CSS, check example bellow. Hope this helps. var vertical_slider = document.createElement('div'); vertical_slider.id = 'vertical_slider'; var osa_y_panorama = 0.6; var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)"; range_pitch.style.oTransform = "rotate(90deg)"; range_pitch.style.msTransform = "rotate(90deg)"; range_pitch.style.transform = "rotate(90deg)"; range_pitch.min = "0"; range_pitch.max = "218"; range_pitch.step = "0.6"; range_pitch.defaultValue = osa_y_panorama; vertical_slider.appendChild( range_pitch ); document.body.appendChild( vertical_slider ); #vertical_slider { float: left; width: 40px; height: 218px; border: 1px solid blue; } input{ position: relative; top:93px; right: 83px; width:200px; } A: The problem come from your css rotation to the input, if you check the DOM, your element is inside but the rotation make it look outside. You can use this css to hot fix it : input { position: relative; right: 70px; top: 100px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/34485570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: spring-boot 404 error in serving .js, .css files to html templates I am using spring boot and was trying to host HTML pages that use angular js. My folder structure is : I referred to a lot of other question on SO and even spring.io guide on spring boot and what I understood was that we are supposed to keep our html templates in templates folder and all the .css, images, .js files in static folder. I have done the same, but whenever the page loads , only the html is rendered and browser get 404 for all .css and .js files. I have include .css and .js in my HTML in the following manner : <script src="/js/socket.io/socket.io.js"></script> <script src="/js/moment.min.js"></script> <script src="/js/demoApp.js"></script> I tried all the combinations like : src="../static/js/socket.io/socket.io.js" or src="js/socket.io/socket.io.js" but always I am getting 404 for these files, in the browser. I checked the spring boot logs and this is what it says : 2016-07-24 21:08:05 WARN PageNotFound:1139 - No mapping found for HTTP request with URI [/js/demoApp.js] in DispatcherServlet with name 'dispatcherServlet' 2016-07-24 21:08:05 DEBUG DispatcherServlet:997 - Successfully completed request I am unable to understand how to solve the issue, please help !!! Note : I have not written view resolver code because according to my understanding spring boot automatically picks up static content from static folder. Please correct me if I am wrong. Edit : Adding my pom file : <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> </dependency> <!--Alexa Dependencies --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.directory.studio</groupId> <artifactId>org.apache.commons.io</artifactId> <version>2.4</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.amazon.alexa</groupId> <artifactId>alexa-skills-kit</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-core</artifactId> <version>1.0.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-dynamodb</artifactId> <version>1.9.40</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <verbose>true</verbose> <source>1.8</source> <target>1.8</target> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </build> A: I see you are using thymeleaf so try to access your resources like this : <script th:src="@{/js/socket.io/socket.io.js}"></script> <script th:src="@{/js/moment.min.js}"></script> <script th:src="@{/js/demoApp.js}"></script> Also and if this does not work can you add your index.html. A: I have found the problem , everything was correct but : 1) I was not extending my Application class from WebMvcAutoConfiguration. @SpringBootApplication @EnableWebMvc public class HLACUIApplication extends WebMvcAutoConfiguration { public static void main(String[] args) { SpringApplication.run(HLACUIApplication.class, args); } } This is how the application class should be. 2) I don't need to use templates folder because I am using angularjs and not thymeleaf. I have put everything in static folder. A: I was facing the same issue. I think you are having html code like below: <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Insert title here</title> <!-- Main Styles --> <link rel="stylesheet" href="/css/bar.css" /> <script src="/js/foo.js"></script> </head> <body> <div>Welcome to Foo!</div> </body> </html> I solved the problem by adding type="text/javascript" to the <script> element. In Spring Boot applications it's required to define type="text/javascript", otherwise it's not going to load. The solution for your example would look like this: <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Insert title here</title> <!-- Main Styles --> <link rel="stylesheet" href="/css/bar.css" /> <script type="text/javascript" src="/js/foo.js"></script> </head> <body> <div>Welcome to Foo!</div> </body> </html> A: In my case with thymeleaf, helped when I skipped '/' before 'js'. Example, instead of <script src="/js/demoApp.js"></script> I've put <script src="js/demoApp.js"></script> A: If you are using Eclipse IDE right click on Project Properties/Project Facets
{ "language": "en", "url": "https://stackoverflow.com/questions/38553929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Kotlin's Dukat is generating code with a tons of error Here's my current gradle.build.kts plugins { kotlin("js") version "1.5.31" } group = "me.fan87" version = "1.0-SNAPSHOT" repositories { jcenter() mavenCentral() } dependencies { implementation("org.jetbrains.kotlinx:kotlinx-nodejs:0.0.7") implementation(npm("ascii-art", "2.8.5")) runtimeOnly(npm("electron", "18.0.2", true)) implementation(npm("electron", "18.0.2")) } (electron is duplicated because I tried using implementation(npm("electron", "18.0.2", true)) before and doesn't work, I'm just testing out if it works and that's not happening) I know that dukat is still in beta/alpha, but isn't there really a way to do this? I'm using kotlin because I want code completion, so using dynamic is not happening. Just wondering if there's any alternative option, if not then RIP I guess (It took me 5 hours on googling it, trying different things already : ( ) Here's a screenshot (I can't send it now cuz I'm a new user so I'll provide an URL) Screenshot Edit: The worst part is everything is broken, literally everything. I realized that -Xerror-tolerance-policy was a thing, and guess what? It isn't working either lmao YouTrack, and What it supposed to be
{ "language": "en", "url": "https://stackoverflow.com/questions/71776082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concatenate two dataframes of different sizes (pandas) I have two dataframes with unique ids. They share some columns but not all. I need to create a combined dataframe which will include rows from missing ids from the second dataframe. Tried merge and concat, no luck. It's probably too late, my brain stopped working. Will appreciate your help! df1 = pd.DataFrame({ 'id': ['a','b','c','d','f','g','h','j','k','l','m'], 'metric1': [123,22,356,412,54,634,72,812,129,110,200], 'metric2':[1,2,3,4,5,6,7,8,9,10,11] }) df2 = pd.DataFrame({ 'id': ['a','b','c','d','f','g','h','q','z','w'], 'metric1': [123,22,356,412,54,634,72,812,129,110] }) df2 The result should look like this: id metric1 metric2 0 a 123 1.0 1 b 22 2.0 2 c 356 3.0 3 d 412 4.0 4 f 54 5.0 5 g 634 6.0 6 h 72 7.0 7 j 812 8.0 8 k 129 9.0 9 l 110 10.0 10 m 200 11.0 11 q 812 NaN 12 z 129 NaN 13 w 110 NaN A: In this case using combine_first df1.set_index('id').combine_first(df2.set_index('id')).reset_index() Out[766]: id metric1 metric2 0 a 123.0 1.0 1 b 22.0 2.0 2 c 356.0 3.0 3 d 412.0 4.0 4 f 54.0 5.0 5 g 634.0 6.0 6 h 72.0 7.0 7 j 812.0 8.0 8 k 129.0 9.0 9 l 110.0 10.0 10 m 200.0 11.0 11 q 812.0 NaN 12 w 110.0 NaN 13 z 129.0 NaN
{ "language": "en", "url": "https://stackoverflow.com/questions/54427502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating form fields from user input I found a code that creates some form fields based on a number chose by the user. <script type='text/javascript'> function addFields(){ var number = document.getElementById("member").value; var container = document.getElementById("container"); while (container.hasChildNodes()) { container.removeChild(container.lastChild); } for (i=0;i<number;i++){ container.appendChild(document.createTextNode("Member " + (i+1))); var input = document.createElement("input"); input.type = "text"; input.name = "Member["+i+"]"; container.appendChild(input); container.appendChild(document.createElement("br")); } } </script> <input type="text" id="member" name="member" value="">Number of Members: <br /> <input type="button" id="enterdetails" value = "Enter Details"onclick="addFields()"> <div id="container"/> </div> It works fine. But I want to create elements with names/values imported from a database. In php I do like this: <SELECT name='smth'> <OPTION value=""></OPTION> <?php $qry = $dbh->query("select * FROM table"); while ($a = $qry->fetch(PDO::FETCH_ASSOC)) { $smth = $a['smth']; echo "<OPTION value='$smth'>".$smth."</OPTION>"; } ?> </SELECT> Need help on how to do it in javascript. A: You cant get database fields with javascript. You must use php or something like this. Maybe this can help you. Here is the link. choose your database and table, and select your field names, and choose field's type of form (text area, text, radio button groups, etc) and push create. You will have a bootstrap designed form and php insert code writed with medoo (medoo.in). you can use this. create your database first and make form automaticly. Copy code and paste to your pages. Also i offer you to use meddo to connect and use sql with it. There is a sample in that link form.min.php, includes your database and user and pass information.
{ "language": "en", "url": "https://stackoverflow.com/questions/23063908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Security concerns regarding unique JWT token in asp.net web api c# I have created an asp.net MVC web API application which uses JWT token to authorise the users after normal login. I am able to implement it correctly but I have following concerns regarding security: * *If someone copies the token of valid user and tries to access the api (my current implementation not able to identify it). *How to detect if someone logins from two different machines? *What are the other things needed to be included in JWT token generation? (I have now used userid in my current implementation) I need some guidance. Thanks In advance!! A: * *Copying the token is not easy as you will store it in local storage of browser. It will be more secure than stealing cookie. *You can add one more claim : Mac Address. Then on each request compare the Mac Address of Request with Mac of Claim. *Use a long random string, it should be enough. I would recommend 25 characters as standard. Don't store the key in web.config. Your token is as secure as the secrecy of your key.
{ "language": "en", "url": "https://stackoverflow.com/questions/41037410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawstring on a panel change when other panel move over I draw a rectangle panel with every button click. After that add a line on the edge of the rectangle and text on the center. But when I drag a panel move over other panel. The panel string will change. Please advice. I can't upload an image. How can I upload an image like that can show my problem more clearly. This link http://i3.photobucket.com/albums/y53/ctkhai/1-4.png show the gui of my software. The upper left and lower left are picturebox. User add a "box" when click on button once and the "box" will show on upper left. User can drag the box to lower right and arrange all the box. now the problem is when user drag the new added "box" and move over some other "box", the text i draw on previous box will change. like this http://i3.photobucket.com/albums/y53/ctkhai/2-4.png. Update: I try to create a class for the tag. but it won't work, the number change again. It is the way I create class for the tag and read is wrong? code like below Product _box = new Product(); List<Panel>product = new List<Panel>(); public class Product { public float X { set; get; } //box coordinate public float Y { set; get; } //box coordinate public int rotate { set; get; } public int entryP { set; get; } public int boxName { set; get; } } private void button_RecAdd_Click(object sender, EventArgs e) { locX = pictureBox_conveyor.Left + (pictureBox_conveyor.Width / 2 - box_y / 2); locY = pictureBox_conveyor.Top + (pictureBox_conveyor.Height / 2 - box_x / 2); _box.boxName = panelBoxNo; _box.entryP = 1; _box.rotate = 0; _box.X = locX; _box.Y = locY; Panel box = new Panel(); box.Location = new Point(locX, locY); box.Name = "box" + panelBoxNo; box.Tag = _box; box.Size = new Size(box_y, box_x); box.BackColor = boxColor; pbW = box.Width; pbH = box.Height; box.MouseDown += panelBox_MouseDown; box.MouseMove += panelBox_MouseMove; box.Paint += new PaintEventHandler((s, m) => { Graphics g = m.Graphics; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;] Product b = box.Tag as Product; string text = b.boxName.ToString(); SizeF textSize = m.Graphics.MeasureString(text, Font); PointF locationToDraw = new PointF(); locationToDraw.X = (pbW / 2) - (textSize.Width / 2); locationToDraw.Y = (pbH / 2) - (textSize.Height / 2); g.DrawString(text, Font, Brushes.Black, locationToDraw); g.DrawRectangle(new Pen(Color.Black), 0, 0, pbW - 1, pbH - 1); g.DrawLine(drawLine, 0, 0, 0, pbH); }); product.Add(box); panel_pelletLayout.Controls.Add(box); box.BringToFront(); label_boxNo.Text = panelBoxNo.ToString(); panelBoxNo++; } private void panelBox_MouseDown(object sender, MouseEventArgs e) { Panel p = sender as Panel; if (e.Button == MouseButtons.Left) { xPos = e.X; yPos = e.Y; if (p != null) { activePnlBox = p.Name; textBox_selectedName.Text = p.Name; textBox_selectedX.Text = p.Left.ToString(); textBox_selectedY.Text = p.Top.ToString(); } } } private void panelBox_MouseMove(object sender, MouseEventArgs e) { Panel p = sender as Panel; if (p != null) { if (e.Button == MouseButtons.Left) { p.Left = ((e.X + p.Left - (p.Width / 2)) / gripGap) * gripGap; p.Top = ((e.Y + p.Top - (p.Height / 2)) / gripGap) * gripGap; textBox_selectedX.Text = p.Left.ToString(); textBox_selectedY.Text = p.Top.ToString(); } } } A: Your Paint event handler has to be responsible for drawing everything each time. Your code looks like it only draws one object. When you drag something over your box, the box becomes invalid and needs to be painted from scratch which means it erases everything and calls your Paint handler. Your Paint event handler then just draws one object. I suspect that what you want to do is keep a data structure of each item you draw and then have a loop in your Paint event handler that will draw all the objects you add. A: Don't use variables that you defined outside a loop, in the paint event. That might be your problem. Try to paint ((Panel)s).Name. Does this work properly? A: Your title has got all of us confused.. You don't draw Rectangles, you create new Panels on each ButtonClick, right? The code for the Paint event is not quite right, though. Just like in any Paint event you should use the built-in Graphics object. And as Hans has noted, you should not destroy/dispose things you didn't create. The main problem you describe seems to be that your boxes have to paint themselves without referring to their real numbers. You should store their numbers e.g. in their Tags.. (Or you could extract it from their Names, like you do it in the MouseDown!) box[panelBoxNo].Name = "box" + panelBoxNo; box[panelBoxNo].Tag = panelBoxNo; // < === !! //.. box[panelBoxNo].Paint += new PaintEventHandler((s, m) => { Graphics g = m.Graphics; // < === !! g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; string text = box[panelBoxNo].Tag.ToString(); // < === SizeF textSize = g.MeasureString(text, Font); PointF locationToDraw = new PointF(); locationToDraw.X = (pbW / 2) - (textSize.Width / 2); locationToDraw.Y = (pbH / 2) - (textSize.Height / 2); g.DrawString(text, Font, Brushes.Black, locationToDraw); g.DrawRectangle(new Pen(Color.Black), 0, 0, pbW - 1, pbH - 1); g.DrawLine(drawLine, 0, 0, 0, pbH); // g.Dispose(); // < === !! // m.Graphics.DrawImageUnscaled(drawBox, new Point(0, 0)); // < === !! // m.Dispose(); // < === !! }); And, as I have noted you should only use arrays if you (or the code) really knows the number of elements. In your case a List<Panel> will be flexible to hold any number of elements without changing any other part of the code, except the adding. You can access the List just like an Array. (Which it is behind the scenes..) Update: The way I see it now, your problems all are about scope in one way or another. Scope in its most direct meaning is the part of your code where a variable is known and accessible. In a slightly broader meaning it is also about the time when it has the value your need. Your original problem was of the latter kind: You accessed the partNo in thr Paint event of the Panels, when it had long changed to a new, probably higher value. Your current problem is to understand the scope of the variables in the ButtonClick event. Usually this is no problem; looking at the pairs of braces, the scope is obvious. But: Here we have a dynamically created Lambda event and this is completely out of the scope of the Click event!! Behind the scenes this Paint event is removed from the Click code, placed in a new event and replaced by a line that simply adds a delegate to the Paint handler just like any regular event. So: nothing you declare in the ButtonClick is known in the Paint code! To access these data you must place them in the Panel properties, in our case in the Tag and access them via casting from the Sender parameter s! So you need to change this line in the Paint event Product b = box.Tag as Product; to something like this: Product b = ( (Panel) s ).Tag as Product;
{ "language": "en", "url": "https://stackoverflow.com/questions/27638710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can extract points which are formed a convex hull of 3 dimensions polygon in Matlab by using convexhull functions? I use different convex hull functions in Matlab to find points coordinates which are formed the convex hull. however, these functions return the matrix of triangles. How can I specify those points? Thanks. Sepideh A: I'm not sure I fully understand your question. Maybe if the following doesn't clarify things you can edit your post to include the name of the MATLAB function you are using and a snippet of code? The convhull function in MATLAB does return the index of coordinates in the convex hull. In the following example, (x(k), y(k)) are the coordinates. (taken straight from convhull doc) xx = -1:.05:1; yy = abs(sqrt(xx)); [x,y] = pol2cart(xx,yy); k = convhull(x,y); plot(x(k),y(k),'r-',x,y,'b+') It's the same thing if you are using convexhull instead (convexhull doc). x = rand(10,1); y = rand(10,1); dt = DelaunayTri(x,y); k = convexHull(dt); plot(x,y, '.', 'markersize',10); hold on; plot(x(k), y(k), 'r'); hold off;
{ "language": "en", "url": "https://stackoverflow.com/questions/11850771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert of generic values in HashMap C I have a function(create) in order to create an hashmap. My hashmap is bigger than 11 , but this is an example and I'm searching to make code more clearly as possible. The hashmap will contain a couple KEY-VALUE in each node. My aim is to create a generic Insert function in which I can insert int, char etc... from an array. In my example I insert Int Insert Function takes as parameters Table t (where I insert int that i created before), two pointers to values that I must insert, the position in which I have to insert values in the hashmap and compare function passed by user, in order to compare two keys and return 1 if they are equal. The trouble is : when I try to print the hashmap (print(t)) it return in each position last couple inserted. input My arr[11] and arr2[11] expected output key: 1,val: 11 key: 2,val: 10 key: 3,val: 9 key: 4,val: 8 key: 5,val: 7 key: 6,val: 6 key: 7,val: 5 key: 8,val: 4 key: 9,val: 3 key: 10,val: 2 key: 11,val: 1 real output key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 key: 11, val: 1 main.c int compare(void *key,void *key2){ int k = *(int*)key; int k2 = *(int*)key2; if(k==k2){ return 1; }else return 0; } int main(){ struct table*t = create(11); int arr[11]={1,2,3,4,5,6,7,8,9,10,11}; int arr2[11]={11,10,9,8,7,6,5,4,3,2,1}; for(int p=0;p<11;p++){ int i = arr[p]; int *key= &i; int i2 = arr2[p]; int *value= &i2; insert(t,key,value,p, compare); } print(t); function.c struct node{ void* key; void* val; struct node *next; struct node *prev; }; struct table{ int size; struct node **list; }; struct table *create(int size){ struct table *t = (struct table*)malloc(sizeof(struct table)); t->size = size; t->list = (struct node**)malloc(sizeof(struct node*)*size); int i; for(i=0;i<size;i++) t->list[i] = NULL; return t; } void insert(struct table *t,void* key,void* val,int pos, int(*comp)(void*, void*)){ struct node *list = t->list[pos]; struct node *newNode = (struct node*)malloc(sizeof(struct node)); struct node *temp = list; while(temp){ if(((*comp)(temp->key, key))==1){ printf("%s", "key already create."); return; } temp = temp->next; } newNode->next = t->list[pos]; newNode->key = key; newNode->val = val; if(list!=NULL){ list->prev = newNode; } t->list[pos] = newNode; newNode->prev = NULL; } void print(struct table *t){ for (int i = 0; i < t->size; ++i) { struct node *list = t->list[i]; while(list){ if(list->key!=NULL) { printf("key: %d, val: %d\n",*(int*)list->key, *(int*)list->val); } list = list->next; } } } A: you are passing the same address for all the values and key here, so by the time you reach the end, the last value is replicated in all the pointers int i = arr[p]; int *key= &i; int i2 = arr2[p]; int *value= &i2; instead you can copy the number of bytes from the location like below. //newNode->key = key; newNode->key = malloc(sizeof(int)); memcpy(newNode->key, key,sizeof(int) ); //newNode->val = val; newNode->val = malloc(sizeof(int)); memcpy(newNode->val, val,sizeof(int) ); NOTE: you will have to handle error checks for malloc and free the memory once done. A: the problem came from the main function. int i = arr[p]; int *key= &i; Your key is a pointer to the i variable, not to the value in arr. The right way: int * key = &arr[p]; (same problem for the value)
{ "language": "en", "url": "https://stackoverflow.com/questions/65130924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to display command line arguments in a single line? I want to write a program that would display my command-line arguments in the console one after another. I found in oracle tutorials that you can surround passed arguments with "" to put them in one line, but how can I do the same with code? I made something like this but cant keep space between two arguments. public class Printargs { public static void main(String[] args) { for(String s: args){ System.out.print((' ' + s).trim()); } } } A: You can join the elements of args[] with space using String#join: public class Main { public static void main(String[] args) { System.out.println(String.join(" ", args)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65025820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: C# Custom Object Validation Design I currently have to validate custom Field Objects for my application. Simply put, each Field object consists of information about the validation for the field, as well as the value of the field. I am validating fields in bulk, so currently, I have a validation class, that has a method for each validation. For required fields, it looks something like this: private void RequiredFields() { foreach (Field field in allFields) { if ((field.Required == true) && (field.Value == string.Empty)) { field.isValid = false; } } } Now my problem is that I feel like I should a layer of abstraction to the validation, so instead of saying: if ((field.Required == true) && (field.Value == string.Empty)) ... I would add a validation class, to accept the values and turn it into this: if (!validater.RequiredFields(field.Required, field.Value)) If I were to do this, it would allow me to reuse the validation class without use of the field objects, and it would also allow better unit testing... However, it seems like and unnecessary layer of abstraction and also somewhat repetitive... Keep in mind, this is the most simple of all the validation. Suggestions? A: Why not have make Field objects responsible for their own validation? class Field { public bool Required { get; } public string Value { get; set; } // assuming that this method is virtual here // if different Fields have different validation logic // they should probably be separate classes anyhow and // simply implement a common interface of inherit from a common base class. public override bool IsValid { get { return Required && Value != String.Empty; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/1290251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Have a method for INPUT without using FORM in PHP I'm being creative and making something new. I am wanting to use <input> without <form> but don't think it's possible to make the input a method (POST) without using <FORM>. I'm currently trying to use if(isset($_POST['name'])) { // Do Something } but having my input <input type="button" name="name" /> does not activate the isset I have when using PHP to listen for that event. Is there something I'm doing wrong? Is there another way I should do this? I'm really lost, and don't have no idea what to do now. I do not want to use <form> since I'm currently not interested in using that. Should the input type be "submit"? What else is there I could do? A: This is possible with a javascript onclick or onsubmit event, using GET rather than POST, but it's definitely not best practice. Use a form or AJAX, as recommended by other posters: <input type="text" id="name" /> <button id="submit" onclick="javascript:window.location='http://yoururl.com/?name='+document.getElementById('name').value">Submit</button> A: You are not able to send a form data without using <form>. The only way to do this is to use ajax instead of a classic HTML form. A: You can take inputs from STDIN in PHP's latest versions like: fscanf(STDIN, "%s\n", $value); Here $value will contain the input.
{ "language": "en", "url": "https://stackoverflow.com/questions/26049605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: gstreamer plugin library not linking against opencv shared object library - “undefined symbol” on CentOS I have a plugin that uses OpenCV and it works perfectly on Kubuntu. Now I am trying to run the code on CentOS but when I run the pipeline, I get: $ gst-launch videotestsrc ! opencvelement ! ximagesink WARNING: erroneous pipeline: no element "opencvelement" When I run ldd in Kubuntu, I get: $ ldd .libs/libOPENCVELEMENT.so linux-gate.so.1 => (0x0060f000) libgstbase-0.10.so.0 => /usr/lib/libgstbase-0.10.so.0 (0x00a74000) libgstreamer-0.10.so.0 => /usr/lib/libgstreamer-0.10.so.0 (0x00474000) libgobject-2.0.so.0 => /usr/lib/i386-linux-gnu/libgobject-2.0.so.0 (0x006a2000) libglib-2.0.so.0 => /lib/i386-linux-gnu/libglib-2.0.so.0 (0x00110000) libopencv_core.so.2.3 => /usr/local/lib/libopencv_core.so.2.3 (0x00730000) libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0x00209000) libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0x002f4000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00acd000) libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0x0031e000) libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0x0033c000) libgthread-2.0.so.0 => /usr/lib/i386-linux-gnu/libgthread-2.0.so.0 (0x00357000) libgmodule-2.0.so.0 => /usr/lib/i386-linux-gnu/libgmodule-2.0.so.0 (0x0035d000) libxml2.so.2 => /usr/lib/libxml2.so.2 (0x00c9c000) librt.so.1 => /lib/i386-linux-gnu/librt.so.1 (0x00362000) libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0x0036b000) libffi.so.6 => /usr/lib/i386-linux-gnu/libffi.so.6 (0x00370000) libpcre.so.3 => /lib/i386-linux-gnu/libpcre.so.3 (0x00e52000) libz.so.1 => /lib/i386-linux-gnu/libz.so.1 (0x00377000) /lib/ld-linux.so.2 (0x00a10000) But when I run it on CentOS, I don't see opencv $ ldd .libs/libOPENCVELEMENT.so linux-vdso.so.1 => (0x00007fff7a1fd000) libgstvideo-0.10.so.0 => /usr/lib64/libgstvideo-0.10.so.0 (0x00002ba0ac9b7000) libgstcontroller-0.10.so.0 => /usr/lib64/libgstcontroller-0.10.so.0 (0x00002ba0acbc4000) libgstbase-0.10.so.0 => /usr/lib64/libgstbase-0.10.so.0 (0x00002ba0acdeb000) libgstreamer-0.10.so.0 => /usr/lib64/libgstreamer-0.10.so.0 (0x00002ba0ad03c000) libgobject-2.0.so.0 => /lib64/libgobject-2.0.so.0 (0x00002ba0ad326000) libgmodule-2.0.so.0 => /lib64/libgmodule-2.0.so.0 (0x00002ba0ad569000) libgthread-2.0.so.0 => /lib64/libgthread-2.0.so.0 (0x00002ba0ad76c000) librt.so.1 => /lib64/librt.so.1 (0x00002ba0ad970000) libxml2.so.2 => /usr/lib64/libxml2.so.2 (0x00002ba0adb7a000) libz.so.1 => /lib64/libz.so.1 (0x00002ba0adeb7000) libglib-2.0.so.0 => /lib64/libglib-2.0.so.0 (0x00002ba0ae0cb000) libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00002ba0ae3a8000) libm.so.6 => /lib64/libm.so.6 (0x00002ba0ae6a8000) libc.so.6 => /lib64/libc.so.6 (0x00002ba0ae92b000) libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00002ba0aec83000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00002ba0aee91000) libdl.so.2 => /lib64/libdl.so.2 (0x00002ba0af0ac000) /lib64/ld-linux-x86-64.so.2 (0x0000003f6c800000) Here is my makefile.am, which is the same on both OS plugin_LTLIBRARIES = libOPENCVELEMENT.la # Plugin source files: libOPENCVELEMENT_la_SOURCES = opencv_chain.c opencv_chain.h datasetup.h libOPENCVELEMENT_la_CFLAGS = \ $(GST_PLUGINS_BASE_CFLAGS) \ $(GST_CFLAGS) \ $(OPENCV_CFLAGS) libOPENCVELEMENT_la_CXXFLAGS = \ $(GST_PLUGINS_BASE_CFLAGS) \ $(GST_CFLAGS) \ $(OPENCV_CFLAGS) libOPENCVELEMENT_la_LIBADD = \ $(GST_PLUGINS_BASE_LIBS) \ $(GST_LIBS) \ $(OPENCV_LIBS) \ -lopencv_core \ -lopencv_highgui libOPENCVELEMENT_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS) libOPENCVELEMENT_la_LIBTOOLFLAGS = --tag=disable-static Let me know if you need more information. Any help will be appreciated. Thank you. A: Do you have all the opencv development files installed on centos as well. Run a: grep "OPENVC_" Makefile to check what the Make variables contain. Also you can pipe the linker (undefined symbol) output through c++filt to see the real function name instead of the mangled name. A: I was able to solve this by going to /usr/lib64/pkgconfig and modified opencv.pc to explicitly have all libraries. I also had to move the plugins from /usr/lib/gstreamer-0.10 to /usr/lib64/gstreamer-0.10
{ "language": "en", "url": "https://stackoverflow.com/questions/11728951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to get the local maven repository path? I have the problem that when using the windows maven under cygwin, the local repository path is not /home/user/.m2/repository, it is /cygdrive/c/Users/user/.m2/repository. Is there a way, with some python library or Aether or something like that, to find out the path that the actual maven binary uses?
{ "language": "en", "url": "https://stackoverflow.com/questions/29798889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use jQuery with in xhtml? i am using facelets,richfaces,and ajax, in XHTML i am facing error while creating datepicker! What is the solution for my problem? the code is: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" xmlns:rich="http://richfaces.ajax4jsf.org/rich"> <head> <a4j:loadScript src="jquery/jquery-1.4.2.min.js" /> <a4j:loadScript src="jquery/jquery-ui-1.8.5.custom.min.js" /> </head> <body> <h:form> <rich:panel> <h:inputText id="mydate" value="" label="test" size="20"/> <rich:jQuery selector="#mydate" name="mydate" query="datepicker({changeMonth:true,changeYear:true})" timing="onload"/> </rich:panel> </h:form> </body> </html> error i am getting is: INFO: Added Library from: jar:file:/D:/WS/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/RichTest/WEB-INF/lib/richfaces-ui-3.3.3.Final.jar!/META-INF/ajax4jsf.taglib.xml Oct 8, 2010 1:51:30 PM com.sun.facelets.FaceletViewHandler handleRenderException SEVERE: Error Rendering View[/jquery/jquery-1.4.2.min.js] com.sun.facelets.FaceletException: Error Parsing /jquery/jquery-1.4.2.min.js: Error Traced[line: 1] Content is not allowed in prolog. at com.sun.facelets.compiler.SAXCompiler.doCompile(SAXCompiler.java:234) at com.sun.facelets.compiler.Compiler.compile(Compiler.java:105) at com.sun.facelets.impl.DefaultFaceletFactory.createFacelet(DefaultFaceletFactory.java:197) at com.sun.facelets.impl.DefaultFaceletFactory.getFacelet(DefaultFaceletFactory.java:144) at com.sun.facelets.impl.DefaultFaceletFactory.getFacelet(DefaultFaceletFactory.java:95) at com.sun.facelets.FaceletViewHandler.buildView(FaceletViewHandler.java:517) at com.sun.facelets.FaceletViewHandler.renderView(FaceletViewHandler.java:567) at org.ajax4jsf.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:100) at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:176) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Oct 8, 2010 1:51:30 PM com.sun.faces.lifecycle.LifecycleImpl phase WARNING: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@19e733e) threw exception com.sun.facelets.FaceletException: Error Parsing /jquery/jquery-1.4.2.min.js: Error Traced[line: 1] Content is not allowed in prolog. at com.sun.facelets.compiler.SAXCompiler.doCompile(SAXCompiler.java:234) at com.sun.facelets.compiler.Compiler.compile(Compiler.java:105) at com.sun.facelets.impl.DefaultFaceletFactory.createFacelet(DefaultFaceletFactory.java:197) at com.sun.facelets.impl.DefaultFaceletFactory.getFacelet(DefaultFaceletFactory.java:144) at com.sun.facelets.impl.DefaultFaceletFactory.getFacelet(DefaultFaceletFactory.java:95) at com.sun.facelets.FaceletViewHandler.buildView(FaceletViewHandler.java:517) at com.sun.facelets.FaceletViewHandler.renderView(FaceletViewHandler.java:567) at org.ajax4jsf.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:100) at org.ajax4jsf.application.AjaxViewHandler.renderView(AjaxViewHandler.java:176) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Oct 8, 2010 1:51:30 PM org.ajax4jsf.webapp.BaseXMLFilter doXmlFilter SEVERE: Exception in the filter chain javax.servlet.ServletException: Error Parsing /jquery/jquery-1.4.2.min.js: Error Traced[line: 1] Content is not allowed in prolog. at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) Please tell me the reason. A: According to http://seamframework.org/Community/HowToWriteJavaScriptInXHTML you only need to: <a4j:loadScript src="resource://jquery.js"/> A: My problem is : How to use jQuery with in xhtml? My Answer is: 1.Create an xhtml page using code given below. <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:a4j="https://ajax4jsf.dev.java.net/ajax" xmlns:rich="http://richfaces.ajax4jsf.org/rich"> <head> <link type="text/css" href="css/flick/jquery-ui-1.8.5.custom.css" rel="stylesheet" /> <a4j:loadScript src="resource:///jquery/jquery-1.4.2.min.js" /> <a4j:loadStyle src="/jquery/jquery-ui-1.8.5.custom.css" /> <a4j:loadScript src="resource:///jquery/jquery-ui-1.8.5.custom.min.js" /> </head> <body > <h:form> <rich:panel> <h:inputText id="dp1" value="" label="test" /> <rich:jQuery selector="#dp1" name="dp1" rendered="true" timing="onload" query="datepicker({chosendate:'01/05/2005',minYear:'-20Y',maxDate: '+1Y +1M',appendText: '(dd-mm-yyyy)',changeMonth:true,changeYear:true})" ></rich:jQuery> </rich:panel> </h:form> </body> </html> 2.then try to place JQuery.xx.js & css files below order! ---WebContent +themes +.... ...jquery-1.4.2.min.js ...jquery-ui-1.8.5.custom.css ...jquery-ui-1.8.5.custom.min.js all these are configured in .xhtml file like above. 3.General things we need to configure for facelets, richfaces and ajax in web.xml is common,in all the way. 4.At last it worked Perfectly... Thank You Guy's..
{ "language": "en", "url": "https://stackoverflow.com/questions/3888881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the meaning of "system environment" in IntelliJ's golang plugin? I was attempting to use intellij's golang plugin, but it sais there is no GOPATH defined. * *the plugin allows you to configure some sort of "GO Libraries" window, however *Its not clear what the configuration is meant to do, and there are no tool tips regarding what should be entered. *There are "global libraries", "project libraries", and so on defined. In my case, I simply want to use a GOPATH. Screenshot attached: The primary question here: How and where should I set GOPATH when using intellij's Golang plugin? Some context: I don't mind setting gopath globally on my mac, but it seems that is a heavy-handed approach for an IDE to use** A: the Go plugin currently uses the term Go Libraries for different GOPATH values. If you have a single GOPATH that you'd like to use for all the projects, then you can add it to the "Global Libraries". For example, my $GOPATH is /home/florin/golang and in the plugin I've set the Global Libraries from the Go Libraries setting to reflect that (see this screenshot). If the plugin can automatically detect the GOPATH, and you have the check box ticked for that, then the plugin will try and use that value as the GOPATH value, see the next screenshot Also, the plugin has three different types of GOPATH values right now: * *the Global Libraries -> you should set GOPATH entries here for GOPATH values that you want to share between different projects (most use-cases) *Project Libraries -> you should set the GOPATH entries here for GOPATH values that are specific to the current project only (when you want to have a single GOPATH per project approach) *Module Libraries -> this is a very specific setting, it's only used in case you have different modules in your project and you want to have a different GOPATH configuration for each of the modules. The module in this case is a specific logical grouping of the source code in the IDE, not in the packages that the Go project uses (think of the ability to have a Python module, a Go module and an Android module all in the same project). There's a ticket that plans to simplify this further and your input will be included. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/33831719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how i can access session in route.php in codeigniter 3.0 how i can access session in route.php in codeigniter 3.0 my application is multi language support so i can used session for language change my application data , lable,static captions language change now i want to extend my application means when language change that time url also change means for example http://localhost/test/en/controller/method when change language in spainsh that time url change like below http://localhost/test/es/controller/method so how i can do this please help me thanks A: You always can access to the $_SESSION variable. However, I'm not sure if it's compatible with CodeIgniter Session library. session_start(); if(isset($_SESSION['lang'])) { // define your routing here } A: Upto the level I understand,You're using Codeigniter's session data as an identity to indicate lang and its associated data..? Codeigniter uses similar way of superglobal session maintainence like using session_start() and $_SESSION. But It is advised not to use session data anywhere else than that of controllers. Try writing a Super-controller which extends to all of your controllers. class SuperController extends MY_Controller { public function __construct() { // Ensure you run parent constructor parent::__construct(); $this->checkSess(); } public function checkSess() { //Your session check and its associated redirects //eg. if $this->session->en==1 redirect to eng lang controller } } Class YourController extends SuperController{ //Your code } Or You can use multilang suppport in Codeigniter as of in Codexworld Or If you want to still use session in routes.php . You can try as of in a standard PHP way as Alexander said.But I doubt whether it works properly. A: Initialize session in autoload.php like: $autoload['libraries'] = array('session'); and then in routes.php you can access the sessions as: session_start(); print_r($_SESSION);
{ "language": "en", "url": "https://stackoverflow.com/questions/39696871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loading image while form loads php script to an iframe I have a form which submits a php file to an iframe. Here is the form: <form action="del.php" method="post" target="output" > Server: <input type="text" name="server_id" value="" /> Name:<input type="text" name="name" value="" /> Password:<input type="password" name="password" value="" /> <br> Create Log? <input type="checkbox" name="log" value="" /> Output list of files? <input type="checkbox" name="out" value="" /><br> <input type="submit" name="delete" value="Delete FTP!" /></td><br> <iframe id="output" ></iframe> del.php deletes files on a romote ftp. That recursive funcion takes a while. Now I want to show a loading image by loading the del.php to the iframe. A: I hope this answer helps you or anyone else looking for a solution. This one worked for me. I'm trying to do the same. I have a page that calculates shipping on an iframe and i want it to show a loading gif image while the shipping cost loads as an xml from my shipping provider. The IFRAME is covered with a DIV where the loading image (or any image) is found. The image is at the center of the DIV area and its size can be up to 950x633 pixels. When the IFRAME page is loaded, the loading image will be hidden. What you need to change is the image URL for your site. You might also want to change the DIV background color (currently set to #FFF). <style> #loadImg{position:absolute;z-index:999;} #loadImg div{display:table-cell;width:950px;height:633px;background:#fff;text- align:center;vertical-align:middle;} </style> <div id="loadImg"><div><img src="loading.gif" /></div></div> <iframe border=0 name=iframe src="html/wedding.html" width="950" height="633" scrolling="no" noresize frameborder="0" onload="document.getElementById('loadImg').style.display='none';"></iframe> This worked for me. It shows a loading Gif animation before the page is loaded in my iframe box. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/14820888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How I can leave the counter code? My Problem: I don't know, how I can leave my counter-code (CountDownTimer), IF the user click the imageButton within the counter of 2 seconds My Code: final ImageButton avatarScroll = (ImageButton) findViewById(R.id.imgBtnAvatarback); avatarScroll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ursprungAvatar = !ursprungAvatar; if(ursprungAvatar) { //image change with arrow ImageButton avatarScroll = (ImageButton) findViewById(R.id.imgBtnAvatarback); avatarScroll.setImageResource(R.drawable.avatarback_pfeil); new CountDownTimer(2000, 1000) { public void onTick(long millisUntilFinished) { // } public void onFinish() { //image change without arrow ImageButton avatarScroll = (ImageButton) findViewById(R.id.imgBtnAvatarback); avatarScroll.setImageResource(R.drawable.avatarback); ursprungAvatar = !ursprungAvatar; } }.start(); } else { //image change without arrow ImageButton avatarScroll_ursprung = (ImageButton) findViewById(R.id.imgBtnAvatarback); avatarScroll_ursprung.setImageResource(R.drawable.avatarback); } } }); A: If I get the behavour right, all you need to do, is adding timer.cancel() in the else case and keep a reference to the created timer (eg make it a field).
{ "language": "en", "url": "https://stackoverflow.com/questions/39203996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: accordion, tab menus, assign select class for both I have two menus: the Accordion menu and Tab menu, for the Tab menu, there is an assigned class selected to a link that is opened, I want to assign the class (for example) open_menu, in the same way for the accordion menu. actually if the class open_menu will be given from the condiotion that in its ul there is an A link with class Selected, it would be much better, because the class selected given to a link is taken from the cookies, and even if the page is refreshed it comes to this link Selected. Anyway, u can see all the source here: http://jsfiddle.net/bq6tA/6/ actually the end product i want, after the refresh of the page, there will be opened the accordion's tab, as well as the Tab's menu link selected that is in this accordion's tab A: See a working demo of the following code here. I've modified your initMenu function to add the open_menu class to the appropriate accordion (and added a CSS class to indicate that it was added by changing the background to green): function initMenu() { // SNIP ... $('#menu li a').click(function() { // SNIP ... if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) { $('#menu ul:visible').slideUp('normal') .siblings('a').removeClass('open_menu'); checkElement.slideDown('normal') .siblings('a').addClass('open_menu'); return false; } }); } I then created a function to be called after initMenu that will trigger a click on the accordion with the same rel as the id of the currently selected item: function showCurrentTab() { var curId = $('.tabcontent:visible')[0].id, $curLink = $('a[rel="'+curId+'"]'); $curLink.closest('ul') .parent('li') .children('a').click(); } To figure out what's going on here, see the API docs for closest, parent and children and relate that to your HTML structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/4836433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What methodology/process/tools support remote and "on the bench" development? I work for an IT services company that develops products as enablers for further services consulting. We have technical consultants/developers that need to be able to develop remotely and when back in the office "on the bench". What methodology/process/tools support development by consultants when they are remote, or "on the bench", in particular how to support the management of the deliverables. I have looked at DVCS systems, along with KanBan board tools, but I'd like to get opinions in the best way to handle this style of product development when it's not a traditional back room development situation. A: There are several leaders in the ALM space, including VersionOne, Rally, ThoughtWorks Studios Mingle + Go + Twist, Jira Greenhopper, and others. These are all fundamentally iterative in nature, supporting Scrum+XP. There is a new crop of tools coming up that support Kanban, if that's your preference. The key, though, is to decide what approach you plan to take. Iterative or flow? Beyond that, if you're using a continuous integration server - whether open source like Jenkins or commercial like Go - then that combined with an SCM system (git, for instance) gives you visibility into what's been produced and the ability to distribute that work. Back to your specific challenge, it seems to me that iterative wouldn't suit you, since you have people coming and going as they enter and leave the bench. Mingle supports this quite nicely, as do a few of the others. In fact, I'd suggest that the leading methodologies don't really lend themselves to your situation, as you will have neither iterations nor flow, most likely. A: Here's my TFS pitch. Your developers/consultants need to be able to work in house, remotely or offline. That means local workspaces. TFS 2012 has that. With the high rate of turnover, you need managers to be able to easily and quickly assign specific tasks to developers. With TFS you can create work items, break them into subtasks and easily assign them to any team member. When the developer begins working, you'll be able to see it and any check ins can be quickly associated (semi-automatically) with the subtask. So you'll know who did what task, and be able to see the exact code they implemented to accomplish it. If you have managers maintaining the product backlog, all a developer needs to do is select one of the tasks assigned to him, get the latest from the source and start developing. Minimal overhead for him/her. With Web Access you can see/edit your entire product backlog, get burndown charts (and other reports), see who completed what and when, assign tasks to team members, change team members, etc. All without VS installed, so no need to have a license for a manager if they don't develop. Finally, fully integrated automated builds will allow you to ensure that consultants don't break your source. Gated check ins are great for this kind of team. The changeset is stored, and a build is ran. If the changeset would break the build, the check in is denied. You can also automate builds on the other side, post check in. Any file created outside of VS can be easily added to source control. Once the file is added, TFS monitors the file for changes and you can easily add the changes to a changeset. Once in source control, its fully in source control and available to everyone. You never really mentioned any database requirements, but the new SSDT is awesome for declarative SQL development. So far, I've not had to write a single ALTER script, which makes me very happy. There is also fully integrated support for code reviews, build verification tests, automated deployments, architecture tools (with rules that can be enforced) and more. The rabbit hole goes pretty deep, but if you don't need it, none of it is forced on you. So, the methodology I would suggest is a KanBan style set up, with managers pushing tasks rather than developers pulling them. This way you can reduce the impact of your high turnover rates without overly micromanaging your consultants. You'll be able to easily give them a task, let them accomplish it, and have complete visibility of the work they perform. I'm not sure how you gather your requirements, and how much input in the dev process your customers have, so its hard to go into more detail. TFS supports storyboards associated with work items, so you can give detailed specs to your developers. Also the Feedback Manager can facilitate in getting feedback on working software from product owners. You could go Scrum with defined sprints, but I think a lot of the overhead of sprint reviews and sprint planning may be a waste for you, if you consultant turnover rate is high, and/or you don't need/want a lot of input from your consultants on user story breakdowns/requirements gathering.
{ "language": "en", "url": "https://stackoverflow.com/questions/11998864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AS3 & XML - How do I construct xml data in as3? I am playing around with saving .xml files from data in my game. I know how to convert an xml object to a ByteArray and write that to a FileReference. What I need to know now is how to go from an empty xml object (using var xml:XML = new XML()) to a fully populated xml object. Can someone show me what functions to use to add nodes and values? Specifically I need to know how to make several of the same type of node. Here's a sample of what the final xml should look like: <data> <player> <money>15831</money> <shipType>1</shipType> <ship> <fuelCur>450</fuelCur> <energyCur>160</energyCur> <shieldCur>100</shieldCur> <armorCur>40</armorCur> <structCur>15</structCur> </ship> </player> <currentSystem>3</currentSystem> <currentPlanet>3</currentPlanet> <date> <year>2012</year> <month>10</month> <day>15</day> </date> <missionFlag>true</missionFlag> <planet id="0"> <population>0</population> </planet> <planet id="1"> <population>29827632</population> </planet> <planet id="2"> <population>0</population> </planet> </data> It might be useful to know how to remove and how to alter nodes and values, too. Also, do I need to import something from the flash library to do this with XML? I'm using FlashDevelop, but when I type xml., FlashDevelop doesn't bring up suggestions like it normally does. A: Editing XML in AS3 is actually pretty easy and pretty basic - it's a core part of AS3. AS3 automatically adds nodes as you call them, like so: var xml:XML = <data />; xml.player.money = 15831; xml.player.shiptype = 1; xml.player.ship.fuelCur = 450; Will result in: <data> <player> <money>15831</money> <shiptype>1</shiptype> <ship> <fuelCur>450</fuelCur> </ship> </player> </data> Then to add multiples of the same node, just start a new XML object of the type you want, and append it to the XML object you're working on. Or skip the separate xml object entirely. Repeat as many times as needed: var segment:XML = <planet />; xml.appendChild(segment); // xml.planet[0] xml.appendChild(segment); // xml.planet[1] xml.appendChild(<planet />); // xml.planet[2] //etc... Then you can add values to them by their indexes. //Assuming this is the 4th planet you've added... xml.planet[3].population = 29827632; A: In FlashDevelop, try creating a separate XML file entirely. That will give you better code prompting. For XML, though, I have found that Adobe's rudimentary docs on their XML class has a wealth of useful examples and tools for creating and using XML objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/8691028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program that would ask for min, hours , AM and PM I would like to create a Program that would ask for min, hours , AM and PM but what I want it to do is add one to the current entered mint when it it displaying the curent time. For example : I will enter the hour: 5, enter the minute: 23 enter AM or PM: AM and gives me the new time as 5:24 AM, I also would like it to change the time and AM or PM if entered some thing lik this, enter the hour: 11 enter the minute: 59 enter AM or PM: AM The new time is 12 00 PM . Also changing the time If I got to 12:59AM to 1:00AM. This is what I have done so far but have no Idea how to make time loop around. I also would like to make this with out any classes. This thing is frustrating me and going no where . #include <iostream> using namespace std; int main(int argc, char *argv[]) { int hr = hr; int min = min; int period = period; currentTime int time; time = hr * 60 + min + 1; hr = time / 60; min = time % 60; currentTime = currentTime(5, 59, "AM"); cout<<currentTime .hr +" : "+currentTime .min +" "+currentTime .period; cin>>hrs; } A: I think this code, would produce a similar output to what you're looking for, but without the loop you wanted to create, because I'm sure that would require a fair few if statements. I was curious as what this line was doing currentTime because it doesn't look to me like it would do anything at all. #include <iostream> #include <conio.h> using namespace std; int main() { int hr, min; char period; cout << "Enter Hour" << endl; cin >> hr; cout << "Enter Minute" << endl; cin >> min; min++; cout << "Enter Period (A or P)" << endl; cin >> period; cout << "Current Time: " << hr << ":" << min << " " << period << "M" << endl; _getch(); } A: Here is an idea of how to accomplish this in C#. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication { class Program { static void Main(string[] args) { double hrs=0; double mins=0; DateTime dt = new DateTime(2013, 10, 20, 3, 59, 00); //dt = DateTime.Now; Console.WriteLine(dt.ToShortTimeString()); Console.WriteLine("Enter hours:"); hrs = Convert.ToDouble(Console.ReadLine()); dt = dt.AddHours(hrs); Console.WriteLine("Enter minutes:"); mins = Convert.ToDouble(Console.ReadLine()); dt = dt.AddMinutes(mins); if (dt.Minute == 59) dt = dt.AddMinutes(1); Console.WriteLine(dt.ToShortTimeString()); Console.ReadLine(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19473365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Perform a task after all UI tasks are done As written in the title, I'm trying to write a piece of code that executes after all UI tasks. I've tried to use the Dispatcher with no success, and ended up using a BackgroundWorker with Thread.Sleep(1000) which feels risky to me. Code snippet - using BackgroundWorker: BackgroundWorker bw2 = new BackgroundWorker(); bw2.DoWork += (o, e) => Thread.Sleep(1000); bw2.RunWorkerCompleted += (o, e) => MyMethod(); bw2.RunWorkerAsync(); Code snippet - using Dispatcher (which is not executed when I want it to): Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => MyMethod())); I also tried to use DispatcherPriority.Background
{ "language": "en", "url": "https://stackoverflow.com/questions/38324606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google tag manager events not appearing in google analytics A client has requested that we implement google tag manager on to track submission of all the forms on his website. We have set up all of the tags and triggers per the instructions that we found online but it appears that only 1 tag is actually working. We the Solids Conveying Case Studies event appear in the behavior > events> overview screen of analytics but not in the Real Time screen. All other tags do not appear to fire at all. We did view the preview/debug mode and see what appears to be a glimpse of a tag after the form submits and the page reloads. Also during our debugging process we tried setting the action to trigger on the form id, and we tried checking Wait for Tags. Any assistance would be greatly appreciated. Here is a link to the website: https://foxvalve.com Here is an example of a tag that we set up. Tag Type: Universal Analytics Track Type: Event Category: Air Gas Ejectors (Different Depending on the Form) Action: Submit Label: Form Value: empty Non-Interaction Hit: True Google Analytics Settings: Google Analytics Variable Trigger Configuration Trigger Type: Form Submission Trigger Fires On Page URL equals (the page URL of the form)
{ "language": "en", "url": "https://stackoverflow.com/questions/46587982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to automatically run a VB6 compiled software as Administrator and in Compatibility mode We have an ERP application which is built in VB6 and it was running just fine till a few of our customer upgraded all their systems to Win7. This software is programmed in such a way that it registers a few plugins (found in plugin folder) which are COM based at runtime. Now when the software is run by user without setting Compatibility Mode and Run as Administrator setting it fails and crashes. I know we can manually set both Compatibility Mode as well as Run a Administrator by right clicking on program executable and then going to its properties. But this looks very unprofessional. I think there will be some way to tell Win 7 to automatically run a software in Compatibility Mode and Run as Administrator. Please help me. A: Compatibility is an administrative function, not a development or deployment function. It is better to fix the application where possible, especially to remove any requirement for elevation. There are plenty of tools for investigating the issues so you can correct them. However globally registering "plug ins" at runtime is a nasty one. VB6 component self-registration is always global unless registry virtualization can redirect it. Why not create installers for the plug-ins that can run elevated once during installation? There are ways to set compatibility less manually, even as part of installation - though Microsoft discourages this. Maybe take a look at: Compatibility Fix Database Management Strategies and Deployment However the effort required might be better spent on remediating the problem. Support costs will be less over time. A: As the other answers have said, you shouldn't need to run all the time elevated. If you want to register the plugins after its started (as a normal user), you can use ShellExecute() with the "runas" verb to run regsvr32.exe, or use COM elevation which has been discussed many times before. A: You can indicate that an application must run as admin by specifying it in the Application Manifest, which in an xml file that you can either embed or deploy with your application. Once your application is running with admin rights it should be able to register and load the plugins. You should not need to run in compatibility mode to access the COM plugins.
{ "language": "en", "url": "https://stackoverflow.com/questions/7074476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to render parts of form from ActionListener in JSF I have a simple file upload mechanism in one of my jsf pages. Once the file has been uploaded, I have an ActionListener that fires. At this point, I have access to the name of the file that the user uploaded, and I want to add this to an outputText component. How can I re-render the form from java code so that the file is displayed? Can I call some ajax function? /** * Called when a file is uploaded * @param event The FileUploadEvent that contains info on the file uploaded */ public void handleFileUpload(FileUploadEvent event){ data = event.getFile().getContents(); name = event.getFile().getFileName(); } Above is the code that runs once the file has been uploaded. You can see I get the name of the file. I need now to re-render the outputText so that the name is displayed. A: This is usually to be declared in the view side. Even though you didn't mention anything about it (which is bad; you should always mention in the question which JSF implementation and component libraries exactly you're using and for sure not overgeneralize everything as "standard JSF"), the listener method code which you've there is recognizeable as the one specific to PrimeFaces <p:fileUpload>. In that case, you should actually be using component's own update attribute which should reference the (relative) client ID of the component you'd like to update on complete of the ajax request. <p:fileUpload ... update="text" /> ... <h:outputText id="text" value="#{bean.text}" /> That's all. You'd in this particular example just have to assign the filename to the text property. See also: * *<p:fileUpload> VDL documentation — lists all available attribtues.
{ "language": "en", "url": "https://stackoverflow.com/questions/13427444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent replacement annotation from changing position and text size? I'm using iTextSharp to replace Typewriter annotations with Textboxes that have the same content and position, but some of the resulting Textboxes end up in different positions with different text sizes, despite seemingly having exactly the same data in their hashMap. The problem is that when I create these new annotations on this sample PDF, and then view the PDF in Adobe Acrobat XI, the new Textboxes have the following problems: * *They have moved from their original positions (adjacent to the arrows) to lower on the page *The text has changed in size *There is no Properties available when the new Textbox is right-clicked I suspect that all 3 problems are due to a single underlying issue with how I'm creating the new Textbox. When I check the /Rect key in the hashMap for annot, it has the same rectangle coordinates in the same order as the original freeTextAnnot, so I don't understand why some of the annotations end up displaced. Here's my code for creating the new Textboxes with the existing Typewriter annotation data. Note that you'll need to set inputPath and outputPath to the actual location of the PDF and its destination path: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp; using iTextSharp.text.pdf; using System.IO; namespace PDFConverterTester { public class PdfModifierTester { public void testWithPaths() { //set to location of test PDF string inputPath = @"C:\InputPath\Before Conversion Dummy.pdf"; //set to destination of new PDF string outputPath = @"C:\OutputPath\Before Conversion Dummy.pdf"; test(inputPath, outputPath); } public void test(string inputPath, string outputPath) { PdfReader pdfReader = new PdfReader(inputPath); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(outputPath, FileMode.Create)); //get the PdfDictionary of the 1st page PdfDictionary pageDict = pdfReader.GetPageN(1); //get annotation array PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS); //iterate through annotation array int size = annotArray.Size; for (int i = size - 1; i >= 0; i--) { PdfDictionary dict = annotArray.GetAsDict(i); PdfName ITName = dict.GetAsName(new PdfName("IT")); if (ITName != null) { if (ITName.Equals(new PdfName("FreeTextTypewriter"))) { PdfAnnotation annot = copyToNewAnnotation_SSCCE(dict,pdfStamper); pdfStamper.AddAnnotation(annot, 1); annotArray.Remove(i); } } } pdfStamper.Close(); pdfReader.Close(); } private PdfAnnotation copyToNewAnnotation_SSCCE(PdfDictionary freeTextAnnot,PdfStamper pdfStamper) { //need Rectangle for CreateFreeText() iTextSharp.text.Rectangle rect; PdfArray rectArray = freeTextAnnot.GetAsArray(PdfName.RECT); if (rectArray == null) { rect = null; } else { rect = new iTextSharp.text.Rectangle(getFloat(rectArray, 0), getFloat(rectArray, 1), getFloat(rectArray, 2), getFloat(rectArray, 3)); } //create new annotation PdfContentByte pcb = new PdfContentByte(pdfStamper.Writer); PdfAnnotation annot = PdfAnnotation.CreateFreeText(pdfStamper.Writer, rect, "", pcb); //make array of all possible PdfName keys in dictionary for freeTextAnnot string pdfNames = "AP,BS,C,CA,CL,CONTENTS,CREATIONDATE,DA,DS,F,IT,LE,M,NM,P,POPUP,Q,RC,RD,ROTATE,SUBJ,SUBTYPE,T,TYPE"; string[] pdfNameArray = pdfNames.Split(','); //iterate through key array copying key-value pairs to new annotation foreach (string pdfName in pdfNameArray) { //get value for this PdfName PdfName key = new PdfName(pdfName); PdfObject obj = freeTextAnnot.Get(key); //if returned value is null, maybe key is case-sensitive if (obj == null) { //try with first letter only capitalized, e.g. "Contents" instead of "CONTENTS" string firstCappdfName = char.ToUpper(pdfName[0]) + pdfName.Substring(1); key = new PdfName(firstCappdfName); obj = freeTextAnnot.Get(key); } //set key-value pair in new annotation annot.Put(key, obj); } //change annotation type to Textbox annot.Put(PdfName.SUBTYPE, PdfName.FREETEXT); annot.Put(new PdfName("Subj"), new PdfString("Textbox")); //set a default blank border annot.Put(PdfName.BORDER, new PdfBorderArray(0, 0, 0)); return annot; } private float getFloat(PdfArray arr, int index) { return float.Parse(arr[index].ToString()); } } } EDIT: It seems that part of the problem may be in the call to pdfStamper.AddAnnotation(annot,1), because annot's values for the /Rect key change after this call is made. E.g.: before AddAnnotation() call: {[2401, 408.56, 2445.64, 693]} after call: {[1899, 2445.64, 2183.44, 2401]} So maybe the following code from PdfStamper.AddAnnotation() (link to source), lines 1463-1493, is responsible, I'm currently investigating this possibility: if (!annot.IsUsed()) { PdfRectangle rect = (PdfRectangle)annot.Get(PdfName.RECT); if (rect != null && (rect.Left != 0 || rect.Right != 0 || rect.Top != 0 || rect.Bottom != 0)) { int rotation = reader.GetPageRotation(pageN); Rectangle pageSize = reader.GetPageSizeWithRotation(pageN); switch (rotation) { case 90: annot.Put(PdfName.RECT, new PdfRectangle( pageSize.Top - rect.Top, rect.Right, pageSize.Top - rect.Bottom, rect.Left)); break; case 180: annot.Put(PdfName.RECT, new PdfRectangle( pageSize.Right - rect.Left, pageSize.Top - rect.Bottom, pageSize.Right - rect.Right, pageSize.Top - rect.Top)); break; case 270: annot.Put(PdfName.RECT, new PdfRectangle( rect.Bottom, pageSize.Right - rect.Left, rect.Top, pageSize.Right - rect.Right)); break; } } } } A: The cause You have yourself found the cause for the change of position and dimension of the annotation: It seems that part of the problem may be in the call to pdfStamper.AddAnnotation(annot,1), because annot's values for the /Rect key change after this call is made. ... code from PdfStamper.AddAnnotation() (link to source), lines 1463-1493, is responsible Indeed, that code changes the annotation rectangle if the page is rotated. The rationale behind this is that for rotated pages iText attempts to lift the burden of adding the rotation and translation to page content required to draw upright text and have the coordinate system origin in the lower left of the page of the users' shoulders, so that the users don't have to deal with page rotation at all. Consequently, it also does so for annotations. For page content there is a PdfStamper property RotateContents defaulting to true which allows to switch this off if one explicitly does not want this rotation and translation. Unfortunately there isn't a similar property for annotations, their positions and sizes always get "corrected", i.e. rotated and translated. A work-around As the page rotation is the trigger for iText to rotate and translate the rectangle, one can simply remove the page rotation before manipulating the annotations and add it again later: PdfDictionary pageDict = pdfReader.GetPageN(1); // hide the page rotation PdfNumber rotation = pageDict.GetAsNumber(PdfName.ROTATE); pageDict.Remove(PdfName.ROTATE); //get annotation array PdfArray annotArray = pageDict.GetAsArray(PdfName.ANNOTS); //iterate through annotation array int size = annotArray.Size; for (int i = size - 1; i >= 0; i--) { ... } // add page rotation again if required if (rotation != null) pageDict.Put(PdfName.ROTATE, rotation); pdfStamper.Close(); With this addition the annotations stay in place. The missing Properties You also observed: There is no Properties available when the new Textbox is right-clicked This is because you have not changed the intent (IT) entry, so they still contained FreeTextTypewriter, so Adobe Reader is not sure what kind of object that is and, therefore, offers no Properties dialog. If you also change the intent: //change annotation type to Textbox annot.Put(PdfName.SUBTYPE, PdfName.FREETEXT); annot.Put(new PdfName("IT"), PdfName.FREETEXT); // <====== annot.Put(new PdfName("Subj"), new PdfString("Textbox")); you'll get the Properties dialog. As an aside Your method getFloat first caused weirdest changes in coordinate systems for me because my locale does not use dots as decimal separator. I changed it to this to make it locale-independent: private float getFloat(PdfArray arr, int index) { return arr.GetAsNumber(index).FloatValue; } An alternative approach Is there a specific reason why you replace the original annotation instead of simply editing it? E.g.: public void AlternativeReplaceFreetextByTextbox(string InputPath, string OutputPath) { PdfName IT = new PdfName("IT"); PdfName FREETEXTTYPEWRITER = new PdfName("FreeTextTypewriter"); using (PdfReader Reader = new PdfReader(InputPath)) { PdfDictionary Page = Reader.GetPageN(1); PdfArray Annotations = Page.GetAsArray(PdfName.ANNOTS); foreach (PdfObject Object in Annotations) { PdfDictionary Annotation = (PdfDictionary)PdfReader.GetPdfObject(Object); PdfName Intent = Annotation.GetAsName(IT); if (FREETEXTTYPEWRITER.Equals(Intent)) { // change annotation type to Textbox Annotation.Put(IT, PdfName.FREETEXT); } } using (PdfStamper Stamper = new PdfStamper(Reader, new FileStream(OutputPath, FileMode.Create))) { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/40878364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Bioconductor package development S3 vs S4 I'm working with a lab developing a package for consideration submission to Bioconductor. Currently, it uses S3 class objects. Everything that I've seen so far in bioncoductor uses S4. Before we attempt to submit, we are wondering if the S3 would disqualify the package. Looking for advice.
{ "language": "en", "url": "https://stackoverflow.com/questions/63496282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: D3 - How to bind the same data to multiple object? I am trying to draw multiple shapes using the same data in a selection, so let's say I have: myData = [ { shape: 'rect', attr: { width: 100, height: 100, x: 100, y:100 } } , { shape: 'circle', attr: {cx, cy, etc...} } ] node.selectAll('*').data([myData]); myData.obj.forEach(function(obj) { // Append different shapes based on data var shape = node.enter().append(obj.shape); Object.keys(obj.attrs).forEach(function(attr) { // Bind attrs to shapes based on data shape.attr(attr, obj.attrs[attr]); }); }); Here node is a 'g' element, myData is a single data object. My goal is to modify the child shapes inside the g based on myData, so later if I bind another myData and call this function again, they can be updated. But I believe somehow myData is only bound to the first appended shape. Is there a way to easily bind the same data to multiple shapes? A: I would create a g element for entry in myData: groups = d3.select('body').append('svg') .selectAll('g').data(myData).enter() .append('g'); and append shapes to those group elements individually: groups.append('rect') groups.append('circle') A: Perhaps, what you want here is the .datum() function in d3. One of it's specific use-cases is to bind the same datum to multiple DOM elments (i.e. bind one datum to an entire d3 selection). For example, d3.selectAll('div').datum({foo: 'bar'}) would bind the same object {foo: 'bar'} to all of the <div>...</div> elements currently existing on the document. Quoting directly from https://github.com/mbostock/d3/wiki/Selections#datum selection.datum([value])...If value is specified, sets the element's bound data to the specified value on all selected elements. If value is a constant, all elements are given the same data [sic] (Somewhat ironically, he refers to the constant datum as "data" in the explanation of the .datum() function!) However, this is a literal answer to your question; there may be a more design-oriented answer to your question which might explain the "conventional" d3-way of handling your overall objective... In which case, you should probably consult some tutorials like http://mbostock.github.io/d3/tutorial/circle.html A: TLDR; Use Selection.data "key" argument function. A key function may be specified to control which datum is assigned to which element «This function is evaluated for each selected element, in order, […] The key function is then also evaluated for each new datum in data, […] the returned string is the datum’s key. (Search «If a key function is not specified…» paragraph) More details … D3 binds data to elements. By default is uses the «join-by-index» method (first found element maps to datum at index 0 and so forth…). If join-by-index is not enough to appropriately identify elements, Selection.data "key" should be used in order for D3 to appropriately synchronise input dataset during rendering phases: "update" (result of data() method call), "creation" enter selection, "removal" (exit selection). Let's say we need to draw some legend, given the following dataset … const dataSet = [ [ 15, "#440154" ] [ 238.58, "#414487" ] // ... ] we first decide to draw the coloured square using <rect> element. const updateSelection = d3.select('rect').data(dataSet); // join-by-index strategy is enough here so there is no need to supply the key fn arg // Key function could be `d => d[0]` (given data source cannot produce two entries // with value at index 0 being the same, uniqness is garanteed) updateSelection.enter() .append('rect') .attr('width', 15).attr('height', 15) .merge(updateSelection) .style('fill', d => d[1]) ; // Dispose outdated elements updateSelection.exit().remove(); We now need a <text> element to be drawn for each given datum to visually expose numeric values. Keeping join-by-index (default) strategy would cause D3 to first draw both rect and text elements but since there can only be a single element bound to a specific datum key, only the first found element will be considered upon update phase and any other element having same datum key will end up in the exit selection and removed from the DOM as soon as the Selection remove method is called. … If multiple elements have the same key, the duplicate elements are put into the exit selection … A solution is to concatenate the numeric value with the element nodeName. // Notice how the selector has changed const updateSelection = d3.select('rect, text').data(dataSet, function(d) { // Concatenate the numeric value with the element nodeName return `${d[0]}:${this.nodeName}`; }) , enterSelection = updateSelection.enter() ; // Add rect element enterSelection .append('rect').attr('width', 15).attr('height', 15) .merge(updateSelection) .style('fill', d => d[1]) ; // Add text label enterSelection .append('text') .merge(updateSelection) .text(d => d[0]) ; // Dispose outdated elements updateSelection.exit().remove();
{ "language": "en", "url": "https://stackoverflow.com/questions/17731263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to prevent updating/deleting a MySQL record when not using a primary key? I have a MySQL table containing information about songs, which has a primary key and a secondary unique key. In my web-application the song's primary key is not 'sent' to the client, but a secondary unique key is that is not displayed by the browser, so that the web-app can update and delete each of the songs, one at a time. Is there a way, possibly using a delete trigger and/or a stored procedure, to prevent a song's data row from being updated/deleted except when both the primary key AND the secondary unique key are specified in the MySQL command? In my web-app the user can update/delete a song's data row, but they should only do this by 'posting' a request to the server that contains a command parameter with the values 'update' or 'delete' and the secondary unique key of the song to be deleted, plus any other necessary data in the case of an update. Then the server looks up the song's primary key and performs the update/delete, which is 'caught' by the update/delete trigger, and only allowed to perform the actual update/delete when both the primary and secondary keys are specified, sort of a 'two-factor' protection mechanism. This way a malicious user who tries to perform some sort of SQL injection attack to change or delete a song's data records won't likely be able to do so because they won't know both of the required keys, where as injecting SQL commands with a guessed primary keys might otherwise get past the SQL injection prevention code. It's either this or a switch that must be turned on before deletes or updates of the song data are permitted, which also rely on update/delete triggers. I know about using prepared SQL statements and not letting using the user entered data be used directly in a SQL update/delete command as a means to protect against SQL injection attacks, but I'm not sure that these always work and the song data is so critical that I want to extra protection against malicious changes/deletes in case a user tries to update/delete song data without using the permitted means provided by the web-app. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/62267189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a (cheap) way to check if a entity exists? I have some keys and the only thing I want to know is if there is a matching entity in datastore. currently I'm doing: entities = db.get(keys) for entity in entities: if entity: # some stuff else: # some other stuff While this works, I just need a boolean to be passed, not the entier object. Is there a way to make this bit of code a bit cheaper? A: Compare the speed of what you're doing now against querying the keys one-at-a-time using a keys-only query. If there isn't a clear winner, take the keys-only query, since it costs less.
{ "language": "en", "url": "https://stackoverflow.com/questions/7745246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Controller's Post method always has null property values on parameter (ASP.Net Core WebAPI & F#: ) My Controller's Post method always has null property values on parameter when triggered. Environment: I'm using ASP.Net Core WebAPI with F#. Attempt: I tried to apply a suggestion from this link to my Startup.fs file: GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver <- Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() However, GlobalConfiguration is an unrecognized type. Here's a larger view of my attempt: type Startup private () = new (configuration: IConfiguration) as this = Startup() then this.Configuration <- configuration // *** I INSERTED THIS BELOW *** // GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver <- Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() Similar questions: I did review this link. However, nothing worked. HTTP Post: This is the Post method where I keep observing null property values on my parameter: [<HttpPost>] member x.Post(request:DataTransfer.Request) = (* "request" parameter is always null *) request |> Query.carriers |> function | Error _ -> x.StatusCode(500) :> IActionResult | Ok carriers -> x.Ok(carriers) :> IActionResult The actual type is defined here: [<CLIMutable>] type Request = { RequestId : string Customer : Customer ItemQtys : ItemQty seq } Client: My client app makes the following call: let client = WebGateway.httpClient APIBaseAddress let response = client.PostAsJsonAsync("carriers", request) |> toResult Here's the request type on the client: [<CLIMutable>] type Request = { RequestId : string Customer : Customer ItemQtys : ItemQty seq } UPDATE: I then attempted to apply a suggestion from this link and also using this reference. It didn't work though. member this.ConfigureServices(services: IServiceCollection) = // Add framework services. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(fun opt -> let resolver = Newtonsoft.Json.Serialization.DefaultContractResolver() resolver.NamingStrategy <- null opt.SerializerSettings.ContractResolver <- resolver ) |> ignore Postman: Screenshots: Partial Success: The following seems promising: Hence, the code above results in actual values sent from the client. However, I haven't found a way to convert the object into the data transfer type that I need. A: You don't need to mess with Contract Resolvers in ASP.NET Core to use camel-case and F# record types, as you did with ASP.NET. I would take all of that out, or try creating a simple test project to get it working, then go back and make the appropriate changes to your real project. With no additional configuration, you should be able to get something working just by following these steps: * *Run dotnet new webapi -lang F# *Add the following type to ValuesController.fs: [<CLIMutable>] type Request = { Name: string Value: string } *Change the Post method to be something like this: [<HttpPost>] member this.Post([<FromBody>] request:Request) = this.Created(sprintf "/%s" request.Name, request) *Debug the service to validate that it works by sending the following request in PostMan: { "name": "test", "value": "abc" } You should see the request object echoed back with a 201 response.
{ "language": "en", "url": "https://stackoverflow.com/questions/57165150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Project '' is not up to date. Input file '' is modified after output file '' I'm creating a typescript project (Project type - Web Application with Typescript), that includes typescript, javascript and other static files. I'm using the Visual Studio 2015 build environment, and the Microsoft.TypeScript.MSBuild.1.8.11 nuget package for the actual compilation (i.e. not using tsconfig.json). I have a Post-build event task which has the side effect of 'touch'ing some of these static files. When I subsequently trigger another build, I get a warning in the output*: Project '<project name>' is not up to date. Input file '<static file>' is modified after output file ''.` and the project is forced to rebuild. Can anyone think how I can work out what VS2015 is referring to when it talks about "output file ''"? * *I've got MSBuild set to output Diagnostic information in the Tools->Options->Build And Run settings. A: To answer my own question - in the hope that it assists someone else. The file VS reports as "output file ''", appears to relate to the output dll/pdb files in the bin folder, but also to the obj/$(Configuration) files that get built during the compilation process. So, if I perform: touch obj\Debug\myProj.dll obj\Debug\myProj.pdb touch bin\myProj.dll bin\myProj.pdb within my post-build task, then this seems to solve the problem and gets the compiler back to what I'd expect: ========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ========== A: I just deleted .vs folder & cleaned solution then worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/39530644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to write two media quires in a single css file? I have the following code in my css file @media (max-width:1000px) and (min-width:400px) { .tooltiptext { margin-left: 10em !important; } .homeInternetToolTip .tooltiptext i { left: 9% !important; } }​ @media (min-width:1000px) and (max-width:1400px) { .tooltiptext { margin-left: 3em !important; } }​ I am getting a error at 2nd query stating '{'} is needed. A: I don't seem to have an issue. Please find the code below <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> @media (max-width: 1000px) and (min-width: 400px) { .tooltiptext { margin-left: 10em !important; } .homeInternetToolTip .tooltiptext i { left: 9% !important; } } @media (min-width: 1000px) and (max-width: 1400px) { .tooltiptext { margin-left: 3em !important; } } </style> </head> <body></body> </html> A: You can use as many @media queries as you want in a single css file, or also inside style tag. But when I copied your code in editor your } bracket at the end have some character code issue, either it is some other character that looks like }, or it have an invisible whitespace character after it making it not actually a }. So in your code remove the last bracket and type again from keyboard, don't copy from anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/64288828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ping ip in js or node js I create electron app which check availability of ip. To check availability you should ping ip. I use fetch api and with domens it work all right, but if i try to ping ip in local network like 192.168.1.190 i getting rejecting, but if i ping it by cmd ping it getting me successful result. I found library ping but it working like fetch and getting rejecting local ips. How should i ping? P.S ip like 8.8.8.8 also return rejecting in fetch api, but in cmd ping all right. A: Using icmp package: const icmp = require('icmp'); icmp.send('8.8.8.8', "Hey, I'm sending a message!") .then(obj => { console.log(obj.open ? 'Done' : 'Failed') }) .catch(err => console.log(err)); A: if you use nodejs, you could use exec to call system ping command. const exec = require('child_process').exec; function process(error, stdout, stderr) { //TODO: process result or logging. } exec("ping -c 3 localhost", process); Or you can use 3rd party libraries. https://github.com/nospaceships/node-net-ping
{ "language": "en", "url": "https://stackoverflow.com/questions/65576395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gwt-rpc deserialization rpc string I have gwt-rpc response string, for example: //OK[1,["19.04.2011 10:49"],0,5] I need to deserialize it. In the best way I want to do it with php, but as I know there are no ready solutions. So, is gwt-rpc serialization algorithm is open source and I can try implement it in php? Or may be I can to develope some java application ( as proxy ) to deserialize it and send to php?
{ "language": "en", "url": "https://stackoverflow.com/questions/5712831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Type issue when using data from php with Swift I try to fill a table view with data downloaded from my database with Alamofire. I created a new NSObject class as followed : class Repas: NSObject { var date: String var choix: String var note: Int init(date: String, choix: String, note: Int) { self.date = date self.choix = choix self.note = note super.init() } } The downloaded date respect this model format but when I try to insert them I got an error: cannot assign a value of type 'String?' to a value of type '[Repas]'. I tried to force casting but it doesn't work. I don't understand how I can access my data with this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/30714622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Message from paypal sandbox: "The currency of this PayPal transaction must match the currency of the merchant account" Paypal mobile SDKs are deprecated, people suggested to use braintree. I'm creating a demo iOS app. This the error message i'm getting from server side: "The currency of this PayPal transaction must match the currency of the merchant account". The currency code i'm passing is PHP. Paypal automatically converts some currencies and PHP is not one of them. Is there any additional setup i need to do for this currency conversion? Here is the code on client side: class ViewController: UIViewController { var btClient: BTAPIClient? var dataCollector: BTDataCollector? override func viewDidLoad() { super.viewDidLoad() self.btClient = BTAPIClient(authorization: tokenizationKey) self.dataCollector = BTDataCollector(apiClient: btClient!) } @IBAction func buttonTouchUpInside(_ sender: Any) { startCheckout() } @objc func startCheckout() { let payPalDriver = BTPayPalDriver(apiClient: self.btClient!) payPalDriver.viewControllerPresentingDelegate = self payPalDriver.appSwitchDelegate = self let payPalRequest = BTPayPalRequest(amount: "1000.00") payPalRequest.currencyCode = "PHP" payPalRequest.lineItems = [.init(quantity: "1", unitAmount: "1000", name: "Item name", kind: .debit)] payPalRequest.isShippingAddressEditable = true payPalRequest.isShippingAddressRequired = true //Shipping address let postalAddress = BTPostalAddress() postalAddress.streetAddress = "1234 Main St." postalAddress.countryCodeAlpha2 = "PH" postalAddress.extendedAddress = "Unit 1" postalAddress.locality = "Chicago" postalAddress.postalCode = "60652" postalAddress.recipientName = "Jhon doe" postalAddress.region = "IL" payPalRequest.shippingAddressOverride = postalAddress payPalDriver.requestOneTimePayment(payPalRequest) { (tokenizedPayPalAccount, error) -> Void in if let tokenizedPayPalAccount = tokenizedPayPalAccount { print("nonce: \(tokenizedPayPalAccount.nonce)") self.dataCollector?.collectDeviceData() { deviceData in self.sendRequestPaymentToServer(nonce: tokenizedPayPalAccount.nonce, amount: "1000.00", deviceData: deviceData) } } else if let error = error { print(error.localizedDescription) } else { print("cancelled") } } } func sendRequestPaymentToServer(nonce: String, amount: String, deviceData: String) { print("payment_method_nonce=\(nonce)&amount=\(amount)&deviceData=\(deviceData)") let paymentURL = URL(string: "http://localhost/newServer/pay.php")! var request = URLRequest(url: paymentURL) request.httpBody = "payment_method_nonce=\(nonce)&amount=\(amount)&deviceData=\(deviceData)".data(using: String.Encoding.utf8) request.httpMethod = "POST" URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) -> Void in guard let data = data else { print(error!.localizedDescription) return } print(String(decoding: data, as: UTF8.self)) guard let result = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let success = result["success"] as? Bool, success == true else { print("Transaction failed. Please try again.") return } print("Successfully charged. Thanks So Much :)") }.resume() } } This is the code on server side: $paymentMethodNonce = $_POST['payment_method_nonce']; $amount = $_POST['amount']; $deviceData = $_POST['deviceData']; $result = $gateway->transaction()->sale([ 'amount' => $amount, 'paymentMethodNonce' => $paymentMethodNonce, 'options' => [ 'submitForSettlement' => true ], 'deviceData' => $deviceData ]); echo json_encode($result); A: self.btClient = BTAPIClient(authorization: tokenizationKey) A tokenization key can only be used for a full Braintree gateway integration. Such an integration requires setting up the new currency, PHP, on the gateway sandbox and later production accounts that you are using for processing. If you want to use the Braintree gateway in production, your business needs to apply and be approved for this. So basically, you need to set up PHP in your gateway interface if you are going to use that new currency with the above integration method. To instead use the Braintree SDK with PayPal more directly (no gateway account), the credential you need to use for authentication first is an access token. Use the access token on your server to obtain a client token, which your client will fetch as needed: https://developers.braintreepayments.com/guides/authorization/client-token A sandbox PayPal Braintree access token can be obtained from the bottom of: https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Fapplication (For live mode, via https://www.paypal.com/api )
{ "language": "en", "url": "https://stackoverflow.com/questions/64798664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculated measure which returns average number of site key per day I am trying to create a calculated measure which returns average number of site keys per day. Fact table looks like below. Formula for measure is sum of number of distinct keys of each day divided by number of days for that month.. Calculated Measure = SUM(Distinct Keys of Day1, Distinct Keys of Day2,....Distinct Keys of last day of month)/ Number of days of month. Any suggestion is appreciated and Thanks in Advance. A: From my point of view your calculated member will be something like: SET [Used Keys] AS NONEMPTY([Key].[Key].[Key], [Measures].[Count]) MEMBER [AVG Keys] AS AVG( [Date].[Month].&[2017-01].Children, DistinctCount([Used Keys]) )
{ "language": "en", "url": "https://stackoverflow.com/questions/47714086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image upload endpoint using jax-rs WITHOUT Jersey How do you create an endpoint for someone to upload a image using jax-rs without jersey? this is the code I have written: @POST @Path("/uploadImage/") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile(@QueryParam("uan") String uan, InputStream stream) { try { byte[] attachmentBytes = IOUtils.toByteArray(stream); BufferedImage image = ImageIO.read(new ByteArrayInputStream(attachmentBytes)); return Response.ok().build(); } catch (IOException e) { System.out.print(e); return Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build(); } } When I hit the endpoint with or without file I get a 200 OK response. There are many examples of creating an file upload endpoint using Jersey however i do not want to have to import Jersey just for this one task. This post has an answer using Jersey that does what I want to do: FileUpload with JAX-RS
{ "language": "en", "url": "https://stackoverflow.com/questions/48502369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to have use vanilla CSS files in Magento 2 via a child theme? I understand that it's built to compile .less files, but I'd really like to be able add vanilla CSS files in a nice way. A: Yes this is absolutely possible. The less files just get compiled into css in the pub directory. To add your own static css files you will just put them in your css directory (/app/design/frontend/{vendor}/{theme}/web/css) and they will be accessed just like any less compiled css file. Depending on your magento configuration you may need to first run bin/magento setup:static-content:deploy from your magento installation's root directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/34748829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: angular Manually trigger validation on input I have a template-driven form with an <input> bound to [(ngModel)] and would like to manually trigger all Validators I placed on it, would it be possible ? If you're interested to know why I would like this kind of behavior I would say that in the case of a custom Validator with dynamics rules (or dependent of variables) when a rules change we would need to check the <input> to seek for errors. <input type="text" customValidator [(ngModel)]="onlyLetters" required />
{ "language": "en", "url": "https://stackoverflow.com/questions/49305098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Request explanation on the behaviour of pointers in array I m running this using rextester (online compiler). I followed a tutorial but there is something I don't understand. I thought it would be better to write my question directly inside the code. //gcc 5.4.0 #include <stdint.h> #include <stdio.h> uint8_t var1 = 17; uint8_t var2 = 23; uint8_t arr[] ={7,9,11}; uint64_t *ptr1;//pointer uint64_t *ptr2; uint64_t *ptr3; int main(void) { printf("var1: %d\n", var1) ; //connecting pointer to address ptr1 = &var1; printf("address of ptr1: %d\n", ptr1) ; printf("value of ptr1: %d\n\n", *ptr1) ; //connecting pointer to address + 1 ptr2 = &var1 +1; printf("address of ptr2: %d\n", ptr2) ; //assign value to pointer *ptr2 = var2; printf("value of ptr2: %d\n\n", *ptr2) ; //try on array ptr3= &arr;//no need to point element 0, or yes? printf("address of ptr3: %d\n", ptr3) ; printf("value of ptr3: %d\n\n", *ptr3) ;//i expect 7 return 0; } Any help would be very appreciate to help me understand the right behaviour of pointers in c and cpp I made a lot of tries but i m not able to link a pointer to an array Edit after response of mato: Do you think this is a clean way to work with pointer and array? Or there are better solution which take care of not overwriting memory? //gcc 5.4.0 #include <stdint.h> #include <stdio.h> uint16_t var = 17; uint16_t arr[] ={3,5,7,11,13}; uint16_t *ptr; int main(void) { printf("var: %d\n", var) ; //connecting pointer to address ptr = &var; printf("address of ptr: %d\n", ptr) ; printf("value of ptr: %d\n\n", *ptr) ; //try on array for (uint16_t n =0;n<5;n++){ ptr= &arr[n] ; printf("item: %d value: %d ads: %d pointer: %d\n", n, arr[n], ptr, *ptr) ; } return 0; } A: You are doing many mistakes. Up to the point, that g++ does not compile the code and explains why pretty good. Pointer is an address. There is no "connecting pointer to address". ptr1 = &var1; means literally "store address of var1 in variable named ptr1" You use incompatible pointer types. So as long as you dereference it (e.g. using *) you are going into undefined behaviour. I am pretty sure you can reinterpret any type of data as char* or unsigned char*, I image this is true for equivalent types like uint8_t, i.e. single byte types. You, however, are going the other way, you declare 1-byte data, and are pretending it's a 4 byte int. Basically you force the program to read memory out the variable bounds. Fact, that *ptr1 and *ptr2 give result you expect is a rather lucky coincidence. Probably memory behind them was zeroed. For ptr3 it isn't because you have filled it with other element of the array (7 and 9). I believe you also use wrong type specifier for printing. %d is for int, uint8_t should be described as hhu and uint64_t as lu. I am not 100% convinced how fatal this is, because of platform specific widths and integer promotions. You should use matching types for your pointers and variables. A: It seems that you do understand what pointers are and you can use them with basic types. There are two problems in your code. First is this part: //connecting pointer to address + 1 ptr2 = &var1 + 1; Here you assigned some address to variable ptr2. Up to this point there is nothing dangerous about that. But then you assign a value to memory at that address //assign value to pointer *ptr2 = var2; This is dangerous because you, as a developer, don't know what is stored at that address. Even if you are lucky right now, and that part of memory isn't being used for anything else, it will most likely change once your program gets longer and then you will have hard time searching for the bug. Now arrays usually are a bit confusing, because when you create an array like this: uint8_t arr[] = {7,9,11}; three things happen. * *Your program allocates continual block of memory, that fits 3 variables of type uint8_t. The 3 variables in this context are called elements. *The elements will get the provided initial values 7, 9 and 11. *An address of first element (the one that contains value 7) will be stored in arr. So arr is actually of type uint8_t *. In order to get the last part do what you expect, you just need to change this one line (remove the &): ptr3 = arr; EDIT: BTW watch and understand this course and you will be expert on C memory manipulation. Video is a bit dated, but trust me, the guy is great. EDIT2: I just realised the other answer is absolutely correct, you really need to match the types.
{ "language": "en", "url": "https://stackoverflow.com/questions/46534693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Query to conditionally select a row from a table depending on join existence I have a query that joins 3 tables and I am trying to retrieve a conditional set of rows depending on whether the record exists in the third table. If there is a match in the 3rd table then I just want the matching records from the 1st table. if there isn't a match from the 3rd table then I just want one record from the first table. select o.Object_ID, reqCon.Connector_ID, req.Object_ID as Requirement_ID from t_object o left join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt' left join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement' This produces the following type of result, but the ones highlight with in Bold are the actual rows that are required. Object_ID Connector_ID Requirement_ID 40936 43259 40936 43260 **40936 43299 38013** 40943 43264 40943 43265 **40943 43298 38014** **44088 46245** 44088 46246 **42669 44655** 42669 44656 **42670 44657** 42670 44658 A: One solution is union all: select o.Object_ID, reqCon.Connector_ID, req.Object_ID as Requirement_ID from t_object o join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt' join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement' union all select o.Object_ID, min(reqCon.Connector_ID), null as Requirement_ID from t_object o left join t_connector reqCon on reqCon.End_Object_ID = o.Object_ID and reqCon.Stereotype = 'deriveReqt' left join t_object req on reqCon.Start_Object_ID = req.Object_ID and req.Stereotype = 'functionalRequirement' group by o.Object_Id having sum(req.Object_Id is not null) = 0; The first query brings in the matches. The second brings in the one row per object that has no match.
{ "language": "en", "url": "https://stackoverflow.com/questions/51455691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Chart.js time scale not showing data I have a Chart.js chart which was displaying fine, until I added a time scale to it. The configuration looks like this: this.chart = new Chart(this.ctx, { type: 'line', data: data, options: { legend: { display: false }, scales: { xAxes: [{ type: 'time', time: { unit: 'month', format: 'timeFormat' } }] } } }); And the data object looks like this: let data = { labels: ["1485903600", "1490738400"], datasets: [{ label: '', data: [120, 30], lineTension: 0 }] }; The x-axis displays the two dates correctly, and the y-axis is bounded by the correct limits (i.e. 120 and 30), but the data is not displaying on the graph. A: The reason your chart is not displaying data when you converted to the time scale is because you are passing string values for your labels that the Date constructor is not able to parse. The time scale expects either an integer (number of milliseconds since epoch), a Date object, a moment.js object, or a string representation of a date that is in a format that Date.parse() can understand. So in your case, when the chart is rendered it can not create Date objects for the X axis (because of your label values), so it creates 2 date objects using new Date() (this is why the X axis still displays some date data...notice that it is 2017 dates because new Date() returns a Date initialized to right now). To correct this, just convert the label values to integers (e.g. remove the quotes) and the chart will then display your data points. The chart still looks funny however because the X scale is configured in units of month but your data values are only 1 day apart (1485903600 = Jan 17, 1970 10:45 PM and 1490738400 = Jan 18, 1970 12:05 AM). Here is a codepen example that shows your original chart and the correct chart so you can see the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/43118452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: writing and adding newline after every line in json first = (str(personaggio["data"]["Character"]["name"]["first"])) last = (str(personaggio["data"]["Character"]["name"]["last"])) immagine = (str(personaggio["data"]["Character"]["image"]["large"])) print (f"{first} {last} {id}") data = {} data["personaggi"] = [] data["personaggi"].append({ "id":id, "character": [ {'nome': first, 'cognome': last, 'img': immagine} ] }) id += 1 with open('idch.txt', 'w') as outfile: json.dump(data , outfile) example output: {"personaggi": [{"id": 65, "character": [{"nome": "Pinako", "cognome": "Rockbell", "img": "https://s4.anilist.co/file/anilistcdn/character/large/65.jpg"}]}]} and the output is right. i just need to add new character in newline, like: {"personaggi": [{"id": 65, "character": [{"nome": "Pinako", "cognome": "Rockbell", "img": "https://s4.anilist.co/file/anilistcdn/character/large/65.jpg"}]}] [{"id": 66, "character": [{"nome": "x", "y": "x", "img": "y"}]}] [{"id": 67, "character": [{"nome": "x", "y": "x", "img": "y"}]}]} im getting the data for every character via a get request, and there isn't a list of all the id's. so i need to loop through every id. the loop is working and everything but i don't know how to print them in the .txt :(
{ "language": "en", "url": "https://stackoverflow.com/questions/70416437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to build an iPad app on the iPad? I would like to minimize the number of devices I would have to purchase to do iPad development so it would be nice if it did :) I suspect the answer is no because I really doubt apple was kind enough to put an objective c compiler on the device. I guess an alternate question would be what is the cheapest apple platform I could use to build apps? A: No, there is neither a compiler nor and IDE available for the iPad. You need a Mac to do iOS development, but even a cheap used Mac Mini will do (and no, you cannot do iOS development on Windows, I'm afraid). A: You are correct. Apple wants you to develop your apps on a Mac. A: Here is a link to Apple's site describing what you need. A mac with xcode is a requirement. A: First to answer your "subject question": As far as I know, NO you cannot install Xcode development kit on an iPad and thereby producing new iPad software... Apple also would like you to buy a real Apple computer if you want to do real business with the platform. BUT With some effort and research, you can just buy an orignal Mac OSX 10.6 or newer. Then with some tweaking and fixes, you install this on ordinary PC hardware. This is because the Apple computers today also are running on Intel CPU's and PC motherboards. Its not officially supported nor "okay" from Apple's licensing point of view, but once you get it running the computer / OS thinks its a real Mac and then you can run and compile Mac software as its running 100% as a Mac. I've seen tests where the owner connected iPod and iPhones to iTunes and AppStore which didnt see anything unusual, so the owner was able to buy movies and music and applications as normally. Same goes for installing pure Apple software such as Xcode and other Mac-Only software. You can even install some boot-manager and be able to run Windows 7 and Mac OSX on a partioned harddrive I've been told. The "thing" is called a Hackintosh. But I was warned that it is far from every piece of PC hardware that you can make run with Mac OSX, so a lot of studying is needed before succeeding I guess. A: I am not sure if this app is compatible with ipad, but it can certainly MAKE your app. You still need the SDK to compile the code it generates, and you still need to purchase the dev program to release your app to the store. Not to mention the functionality you can add is very limited, but it is the closest to developing on the device itself that you can get. A: You could use the Notes app on an iPad, or a Javascript editing app, or a cloud hosted text editor from iPad Safari, to write HTML5/CSS/Javascript for a web app. Upload the resulting web app source text plus a manifest to some web server, go to it in Safari with your iPad, test it, and save it as a web clipping web app. That's for a web app. If you want to build native iOS/iPad apps you need an Intel Mac running OS X 10.6.x (but even a cheaper old used Mini or iMac will do, as long as it can run Snow Leopard 10.6). Or at least fast network access to a Mac. You could remote access a Mac using one of the many VNC or other remote viewing apps for the iPad, and develop native iPad apps from an iPad that way, but it would still involve a Mac.
{ "language": "en", "url": "https://stackoverflow.com/questions/5425785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: repeating a button in a php while loop The following is a markup I have for displaying my database: $html = ''; $database_enquiry = tep_db_query("(relevant database enquiry in here)"); while ($database = tep_db_fetch_array($database_enquiry)){ $html .= '<tr>'; $html .= ' <td>'.$myV['myVariable goes here'].'</td>'; $html .= ' <td><button id="editDriver"></button><button id="timeDriver"></button></td>'; $html .= '</tr>'; } echo $html; For some reason, the rows, are displaying in the loop, but the buttons are only showing up for the first row. Anyone know why? A: IDs, as their name imply, should be unique to a document, you are duplicating the buttons IDs for every row. Normaly most browsers don't make a fuss if you have dulicates (though they should), but it seems in your case, it's causing problems. So, give your buttons unique IDs accross rows, or use classes to see if it helps: $html .= ' <td><button class="editDriver"></button><button class="timeDriver"></button></td>'; A: Could you write something between the button tag and add type attribute? <button type="button">Something</button> ref A: There are 3 things you need to fix/check: * *The id attribute id unique. You should not have more than one per page *<tr></tr> tags should be inside a <table></table> element. *Maybe your query return a single row, in which case your code is working properly. Also, you should check the official documentation for the button element: http://www.w3.org/wiki/HTML/Elements/button
{ "language": "en", "url": "https://stackoverflow.com/questions/15159964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery calculated result should show image due to result I have a calculation which should show different images or text due to the result that is given. for example, if the result is between 3 and 7 there should be image 1, if it is between 8 and 12 -> image 2. i made a jsfiddle with the actual state: http://jsfiddle.net/utSYb/ <form id="calx"> <table> <tbody> <tr><td>Variable 1 </td><td><input id="th" type="text" name="th[]" value="77" /></td></tr> <tr><td>Variable 2 </td><td><input id="ah" type="text" name="ah[]" value="132" /></td></tr> <tr><td>Variable 3</td><td><select name="ih" id="ih"><option value="45">1"</option><option value="51">2"</option></select></td></tr> <tr><td>Result</td><td><input id="x" type="text" name="x[]" value="" data-formula="($ah-$th-$ih+2)" /></td></tr> </tbody> </table> </form> for your info, i am using this script: http://www.xsanisty.com/project/calx/ thanks A: Try this $('input').on('change', function () { var x = $('#x').val(); if (x > 3 && x < 7) { //code to show image } //elseif for other statements and so on... }); A: Something like this will sort you out: if( result >= 3 && result <= 7 ){ ... show image 1 ... }else if( result >= 8 && result <= 12){ ... show image 1 ... }else{ ... show default image . . . }
{ "language": "en", "url": "https://stackoverflow.com/questions/20655242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate a wsdl using zend soap I'm trying to generate a wsdl file using the autodiscover class from the Zend framework. The resulting definition doesn't seem to become available and subsequent functionality doesn't work. Below is the code that I'm using... <?php /** * Returns Hello World as a string. * * @return string */ function hello( ) { return "Hello World"; } if( isset( $_GET['wsdl'] ) ) { $autodiscover = new Zend_Soap_AutoDiscover(); $autodiscover->addFunction( 'hello' ); $autodiscover->handle(); } else if( isset( $_GET['client'] ) ) { $client = new Zend_Soap_Client( "http://localhost/service.php" ); echo $client->hello(); } else { $server = new Zend_Soap_Server( "http://localhost/service.php?wsdl" ); $server->addFunction( 'hello' ); $server->handle(); } ?> This all weems to fail silently, calling http://localhost/service.php?wsdl just dies silently and generates no WSDL definition. Could someone please give me an idea of what I'm doing wrong :) Many thanks A: I tried the code you posted, except that I added: require('Zend/Soap/AutoDiscover.php');. It worked. A: Try adding docblocking to the hello function. the WSDL generator relies on it to generate proper WSDL file. http://framework.zend.com/manual/en/zend.soap.autodiscovery.html See the important notes in that link. A: Yep, you are missing require('Zend/Soap/AutoDiscover.php'); that's all.
{ "language": "en", "url": "https://stackoverflow.com/questions/4680651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }