text
stringlengths
15
59.8k
meta
dict
Q: how to snip or crop or white-fill a large. expanded (by 10%) rectangle outside of a polygon with ggplot2 this question is a follow-up of my prior SO question and is related to this question. i'm just trying to white-fill an area 10% bigger than a simple polygon with ggplot2. maybe i'm grouping things wrong? here's a photo of the spike with reproducible code below # reproducible example library(rgeos) library(maptools) library(raster) shpct.tf <- tempfile() ; td <- tempdir() download.file( "ftp://ftp2.census.gov/geo/pvs/tiger2010st/09_Connecticut/09/tl_2010_09_state10.zip" , shpct.tf , mode = 'wb' ) shpct.uz <- unzip( shpct.tf , exdir = td ) # read in connecticut ct.shp <- readShapePoly( shpct.uz[ grep( 'shp$' , shpct.uz ) ] ) # box outside of connecticut ct.shp.env <- gEnvelope( ct.shp ) ct.shp.out <- as( 1.2 * extent( ct.shp ), "SpatialPolygons" ) # difference between connecticut and its box ct.shp.env.diff <- gDifference( ct.shp.env , ct.shp ) ct.shp.out.diff <- gDifference( ct.shp.out , ct.shp ) library(ggplot2) # prepare both shapes for ggplot2 f.ct.shp <- fortify( ct.shp ) env <- fortify( ct.shp.env.diff ) outside <- fortify( ct.shp.out.diff ) # create all layers + projections plot <- ggplot(data = f.ct.shp, aes(x = long, y = lat)) #start with the base-plot layer1 <- geom_polygon(data=f.ct.shp, aes(x=long,y=lat), fill='black') layer2 <- geom_polygon(data=env, aes(x=long,y=lat,group=group), fill='white') layer3 <- geom_polygon(data=outside, aes(x=long,y=lat,group=id), fill='white') co <- coord_map( project = "albers" , lat0 = 40.9836 , lat1 = 42.05014 ) # this works plot + layer1 # this works plot + layer2 # this works plot + layer1 + layer2 # this works plot + layer2 + co # this works plot + layer1 + layer3 # here's the problem: this breaks plot + layer3 + co # this also breaks, but it's ultimately how i want to display things plot + layer1 + layer3 + co # this looks okay in this example but # does not work for what i'm trying to do- # cover up points outside of the state plot + layer3 + layer1 + co A: Here's how I'd go about it with base plotting functions. It wasn't entirely clear to me whether you need the "background" polygon to be differences against the state polygon, or whether it's fine for it to be a simple rectangle that will have the state poly overlain. Either is possible, but I'll do the latter here for brevity/simplicity. library(rgdal) library(raster) # for extent() and crs() convenience # download, unzip, and read in shapefile download.file(file.path('ftp://ftp2.census.gov/geo/pvs/tiger2010st/09_Connecticut/09', 'tl_2010_09_state10.zip'), f <- tempfile(), mode='wb') unzip(f, exdir=tempdir()) ct <- readOGR(tempdir(), 'tl_2010_09_state10') # define albers and project ct # I've set the standard parallels inwards from the latitudinal limits by one sixth of # the latitudinal range, and the central meridian to the mid-longitude. Lat of origin # is arbitrary since we transform it back to longlat anyway. alb <- CRS('+proj=aea +lat_1=41.13422 +lat_2=41.86731 +lat_0=0 +lon_0=-72.75751 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs') ct.albers <- spTransform(ct, alb) # expand bbox by 10% and make a polygon of this extent buf <- as(1.2 * extent(ct.albers), 'SpatialPolygons') proj4string(buf) <- alb # plot without axes par(mar=c(6, 5, 1, 1)) # space for axis labels plot(buf, col='white', border=NA) do.call(rect, as.list(c(par('usr')[c(1, 3, 2, 4)], col='gray90'))) # the above line is just in case you needed the grey bg plot(buf, add=TRUE, col='white', border=NA) # add the buffer plot(ct.albers, add=TRUE, col='gray90', border=NA) title(xlab='Longitude') title(ylab='Latitude', line=4) Now, if I understand correctly, despite being in a projected coordinate system, you want to plot axes that are in the units of another (the original) coordinate system. Here's a function that can do that for you. [EDIT: I've made some changes to the following code. It now (optionally) plots the grid lines, which are particularly important when plotting axis in units that are in a different projection to the plot.] axis.crs <- function(plotCRS, axisCRS, grid=TRUE, lty=1, col='gray', ...) { require(sp) require(raster) e <- as(extent(par('usr')), 'SpatialPolygons') proj4string(e) <- plotCRS e.ax <- spTransform(e, axisCRS) if(isTRUE(grid)) lines(spTransform(gridlines(e.ax), plotCRS), lty=lty, col=col) axis(1, coordinates(spTransform(gridat(e.ax), plotCRS))[gridat(e.ax)$pos==1, 1], parse(text=gridat(e.ax)$labels[gridat(e.ax)$pos==1]), ...) axis(2, coordinates(spTransform(gridat(e.ax), plotCRS))[gridat(e.ax)$pos==2, 2], parse(text=gridat(e.ax)$labels[gridat(e.ax)$pos==2]), las=1, ...) box(lend=2) # to deal with cases where axes have been plotted over the original box } axis.crs(alb, crs(ct), cex.axis=0.8, lty=3) A: This is because `coord_map', or more generally non-linear coordinates, internally interpolates vertices so that line is draw as a curve corresponding the coordinate. In your case, interpolation will be performed between a point of the outer rectangle and a point of inner edge, which you see as the break. You can change this by: co2 <- co class(co2) <- c("hoge", class(co2)) is.linear.hoge <- function(coord) TRUE plot + layer1 + layer3 + co2 You can also find the difference of behavior here: ggplot(data.frame(x = c(0, 90), y = 45), aes(x, y)) + geom_line() + co + ylim(0, 90) ggplot(data.frame(x = c(0, 90), y = 45), aes(x, y)) + geom_line() + co2 + ylim(0, 90)
{ "language": "en", "url": "https://stackoverflow.com/questions/26359909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I update a value in a view in Yii Framework? Hi I have a question about yii Framework.I want to update a value in view.php and I use the following code in BilgiformuController public function actionView($id) { $this->loadModel($id)->okunma=1; $this->render('view',array( 'model'=>$this->loadModel($id), )); } But the code, I used not working.How can I update "okunma" value in actionView.Thanks A: This code: $this->loadModel($id)->okunma=1; $this->render('view',array( 'model'=>$this->loadModel($id), )); retrieves the model (object), changes the okunma property and throws it away (because the return value of loadModel() call is not being stored anywhere) and the other loadModel() call simply retrieves the model again. I think what you meant was: $model = $this->loadModel($id); $model->okunma=1; $this->render('view',array( 'model' => $model, )); this way the retrieved object is stored in a variable, allowing you to modify it and pass it to render() once modified. And if you want this change to propagate to database as well, you need to save() the model: $model = $this->loadModel($id); $model->okunma=1; $model->save(); A: You shouldn't perform update operation in views. I think you want to set model attribute and show this on view - then solution presented by @Liho is correct. If you want to save data to DB, you should assing $_POST attributes to your model: $model = $this->loadModel($id); $model->okunma=1; if(isset($_POST['yourModelName')) { $model->attributes = $_POST['yourModelName']); if($model->validate()) { $model->save(false); // other operations, eg. redirect } } $this->render('view',array( 'model' => $model, )); A: $model = YourModel::model()->findByPk($id); $model->okunma=1; $model->save(false); $this->render('view',array( 'model' => $model, ));
{ "language": "en", "url": "https://stackoverflow.com/questions/33498060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular Library Project - how to build and use a library with own dependencies (not peerDependencies)? I have created an Angular Library Project, and a simple application next to it where i show the usage of it. The structure looks like this: This is how it looks in the library's package.json: "@angular/cdk" is used in a component in the library, where i have an import like this: import { LiveAnnouncer } from '@angular/cdk/a11y'; Everything is fine until now. Now when i want to run my demo application (ui-components-showcase) which imports (in its app.module) the library directly from the folder structure (without actually building the library itself), everything works as it should be. But when i want to do it in the correct way, by building the library first (ng build ui-components), and importing the build lib folder in app.module, by starting the server with i get this error: And this is actually how app.module looks in webstorm: When i open the component.d.ts file in the dist folder, i see the error also in the place where i import the LiveAnnouncer from @angular/cdk/a11y. So the dependency is really not there in the build lib. What is going on here and how can i fix it? I appreciate for any help. Edit: this is how it looks again with 2 node_modules folders. 1 is for the library itself, the other one in the root is for the whole library project incl. sample app (showcase). This is created by angular/cli, did not make any structural changes. The root package.json which is seen here, is also as created from angular/cli, did not change anything there. And since the dependency angular/CDK is just needed from the library itself, i just included it in the inner package.json of the library itself, as it should be. The showcase itself does not have any CDK dependency. A: Usually the showcase would be an application project in the same Angular workspace as the library project, with both sharing node_modules Here's an example (picked at random) of an Angular npm component library, with the showcase/demo app as part of the same repo (the same Angular CLI workspace) * *https://github.com/zefoy/ngx-color-picker/tree/master/projects
{ "language": "en", "url": "https://stackoverflow.com/questions/72453231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Securing uploaded files in PHP I have a site with user logins and sessions. I'd like to allow my users to upload files to the webserver, but only have them available for their login. I understand if I upload to some sort of public web directory that the file would be still accessible via: http://www.mydomain.com/files/thefile.pdf However, I'm thinking I can store the files in the directories just above my public HTML root (say it's /mnt/content/web/html). So, I could make a directory called (/mnt/content/web/uniqueidfortheuser) and store my files there, then reference the files via PHP with the syntax: (../uniqueidfortheuser/thefile.pdf). My question - is this secure enough or is there something I'm overlooking? The name of the uniqueidfortheuser would be stored in a database and unknown to users, and they'd have to have a valid session to gain access the their unique name of their folder. And I don't think they'd be able to call any of the files in the folder from the web. A: Even better - when the user uploads the file, include the user_ID for the file. Then, when you try to retrieve the file, make sure it belongs to the user. So therefore even if they guess another file - it wont matter! You need to use readfile: function user_files($file_name = "") { // Check user is logged in if ($user->logged_in()) { // Check file_name is valid and only contains valid chars if ((preg_match('^[A-Za-z0-9]{1,32}+[.]{1}[A-Za-z]{3,4}$^', $file_name)) { // Now check file belongs to user - PSUEDOCODE if ($filename == $user->records) { header('Content-Type: '.get_mime_by_extension(YOUR_PATH.$file_name))); readfile(YOUR_PATH.$file_name); } else { echo 'You do not have access to this file'; } } } } There is some issues around directory traversal etc - so you'll need to check the $file_name first like I have using the preg_match
{ "language": "en", "url": "https://stackoverflow.com/questions/14008652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NGRX and the tsconfig strict flag Perusing the ngrxplatform repo here, I was pleased to see that the strict flag is enabled in the tsconfig.json file. This ensures that the strict typechecking is enforced during the compile. However, looking at the sample applications listed on the Ngrx website here, none of these sample applications make use of the strict flag (a few apps have one or two flags enabled, but most have no flags enabled). In fact I couldn't find a single ngrx application on github that uses the strict flag (if you know of one please post the link). I'm worried I'm missing something here. Is there a reason NOT to use the strict flag for an enterprise level production application? If not, why not a good example of its use? A: Answering my own question. Should have done a bit more digging. All three example apps in the ngrx platfrom repo's projects folder have the strict flag enabled: https://github.com/ngrx/platform/tree/master/projects
{ "language": "en", "url": "https://stackoverflow.com/questions/59128727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My code in JS isn't coming out with a letter grade I wrote a function in JS towards the end that is suppose to give you a letter grade once you get the average of 5 subjects, but it's not showing me anything I'm lost right now The forth function I wrote doesn't seem to produce any letter grade. I believe everything else is right function getHandleValue(idName) { const value = parseInt(document.getElementById(idName).value); console.log(value); return value; } function getTotal() { //console.log("app js starts loading") let english = getHandleValue('english'); let math = getHandleValue('math'); let physics = getHandleValue('physics'); let computer = getHandleValue('computer'); let science = getHandleValue('science'); //console.log("app js ends loading") let total = english + math + physics + computer + science; document.getElementById('total').innerHTML = total; return total; } function getAverage() { // option 1 // const total = parseInt(document.getElementById('total').innerHTML); // const average = total / 5; // document.getElementById('average').innerHTML = average; // option 2 const average = getTotal() / 5; document.getElementById('average').innerHTML = average; } function letterGrade() { letterGrade; if (grade >= 90 && grade <= 100) letterGrade = 'A'; else if (grade >= 80 && grade <= 89) letterGrade = 'B'; else if (grade >= 70 && grade <= 79) letterGrade = 'C'; else if (grade >= 60 && grade <= 69) letterGrade = 'D'; else if (grade > 1 && grade <= 59) letterGrade = 'F'; let average = letterGrade; document.getElementById('Grade').innerHTML = Grade; } A: letterGrade isn't declared properly, do: let letterGrade = ' ' This declares the letterGrade variable. A: You haven't declared the lettergrade variable. To do this, replace letterGrade; with let letterGrade; In your code, this will look like: function getHandleValue(idName) { const value = parseInt(document.getElementById(idName).value); console.log(value); return value; } function getTotal() { //console.log("app js starts loading") let english = getHandleValue('english'); let math = getHandleValue('math'); let physics = getHandleValue('physics'); let computer = getHandleValue('computer'); let science = getHandleValue('science'); //console.log("app js ends loading") let total = english + math + physics + computer + science; document.getElementById('total').innerHTML = total; return total; } function getAverage() { // option 1 // const total = parseInt(document.getElementById('total').innerHTML); // const average = total / 5; // document.getElementById('average').innerHTML = average; // option 2 const average = getTotal() / 5; document.getElementById('average').innerHTML = average; } function letterGrade() { let letterGrade; if (grade >= 90 && grade <= 100) letterGrade = 'A'; else if (grade >= 80 && grade <= 89) letterGrade = 'B'; else if (grade >= 70 && grade <= 79) letterGrade = 'C'; else if (grade >= 60 && grade <= 69) letterGrade = 'D'; else if (grade > 1 && grade <= 59) letterGrade = 'F'; let average = letterGrade; document.getElementById('Grade').innerHTML = Grade; } A: Problems I assume comments and answers have already stated, that the function letterGrade() doesn't use the correct variable letterGrade but instead uses an undefined variable Grade. Also, the variable grade is neither defined nor is it passed as a parameter or is within scope. Figure I is a breakdown of letterGrade(). Figure I function letterGrade() { /** * ISSUE 1 * Naming a Variable * Do not name a variable with the same name as the function in which it * resides within * ISSUE 2 * Declaring or Defining a Variable * Use identifier var (not recommended), let, or const * ex. let letter; */ letterGrade; /** * ISSUE 3 * Declaring or Defining Variables * grade isn't declared * ex. let grade; * grade isn't defined * ex. let grade = 0; * grade isn't a parameter * ex. function letterGrade(grade) {... * grade isn't within scope * ex. let grade = 0; * function letterGrade() {... */ if (grade >= 90 && grade <= 100) letterGrade = 'A'; else if (grade >= 80 && grade <= 89) letterGrade = 'B'; else if (grade >= 70 && grade <= 79) letterGrade = 'C'; else if (grade >= 60 && grade <= 69) letterGrade = 'D'; else if (grade > 1 && grade <= 59) letterGrade = 'F'; /** * ISSUE 4 * Passing by Value * average is never used. If average is a reference to the value calculated * by function getAverage(), then... * - getAverage() should return that value, * - then that value must be defined outside of getAverage() * - or passed as a parameter of letterGrade() (recommennded). * ex. ..::OUTSIDE OF letterGrade()::.. * function getAverage() { * ... * return average; * } * // Option A * let average = getAverage() * letterGrade(average) * // Option B (recommended) * letterGrade(getAverage) * * ..::INSIDE OF letterGrade()::.. * function letterGrade(average) { * let grade = typeof average === "number" ? grade : 0; * ... * } * Even if average was to be used, it would be useless as the value of * letterGrade, there's no point in reassigning it to another variable * unless it's to create a copy of another variable declared or defined * outside of the function. */ let average = letterGrade; /** * ISSUE 5 * Defining or Declaring Variables * Grade variable has the same problem as ISSUE 3 */ document.getElementById('Grade').innerHTML = Grade; } Solutions Provided are two examples (Example A and Example B) that require familiarity with a few methods, properties, events, and techniques, please refer to Appendix located at the end of this answer. Both examples have step-by-step details commented within the source. Example A Example A is a working example that comprises of: * *a <form> tag *an <input type="range"> *two <output> tags *an event handler getGrade(e) *a functional letterGrade(score) /** * Reference <form> * Bind the "input" event to <form> */ const grade = document.forms.grade; grade.oninput = getGrade; /** * Event handler passes (e)vent object by default * Reference the tag the user is currently typing into * Reference all form controls (<fieldset>, <input>, <output>) * Reference both <output> * If the tag the user is currently using is NOT <form> * AND the tag is #score... * Assign the value of the currently used <input> as the * value of the first <output> * Next pass the same value to letterGrade(score) and assign * it's value to the second <output> */ function getGrade(e) { const dataIN = e.target; const io = this.elements; const number = io.number; const letter = io.letter; if (dataIN !== this && dataIN.id === "score") { number.value = dataIN.value; letter.value = letterGrade(dataIN.value); } } /** * Convert a given number in the range of 0 to 100 to a * letter grade in the range of "A" to "F". * @param {Number} score - A number in the range of 0 to 100 * @returns {String} - A letter in the range of "A" to "F" * @default {String} - A "" if the @param is out of the * range of 0 to 100 */ function letterGrade(score) { if (score >= 0 && score < 60) return "F"; if (score >= 60 && score < 70) return "D"; if (score >= 70 && score < 80) return "C"; if (score >= 80 && score < 90) return "B"; if (score >= 90 && score < 101) return "A"; return ""; } label { display: flex; align-items: center; margin: 0.5rem 0; } input { cursor: pointer; } <form id="grade"> <label for="score">Set Score: </label> <label> 0&nbsp; <input id="score" type="range" min="0" max="100" value="0"> &nbsp;100 </label> <label>Score:&nbsp;<output id="number"></output></label> <label>Grade:&nbsp;<output id="letter"></output></label> </form> Note the pattern of the flow control statements in Example A: if (CONDITION) return LETTER; if (CONDITION) return LETTER; if (CONDITION) return LETTER; if (CONDITION) return LETTER; if (CONDITION) return LETTER; return ""; If a CONDITION is true then a LETTER is returned. Whenever a value (LETTER) is returned, the function will terminate, so for example the third CONDITION is true, then the third LETTER is returned, the function ends, and the rest of the function doesn't execute. This technique is called a short circuit Example B Example B is a working example comprising of: * *a <form> *five <input type="number"> *two <output> *an event handler calc(e) *a terse version of letterGrade(avg) that uses ternary expressions /** * Reference <form> * Bind the "input" event to <form> */ const ga = document.forms.ga; ga.oninput = calc; /** * Event handler passes the (e)vent object by default * Reference the tag the user is entering text into * Reference all form controls (<fieldset>, <input>, <output>) * Collect all tags with [name="subject"] into an array * Reference the <output> * If the <input> that the user is currently using is NOT <form>... * AND if it is [name="subject"]... * convert the value of each <input> of the >subs< array into a * number, then use .reduce() to get the sum of all of them (>total<) * Next divide >total< by the .length of >subs< * Then get the letter grade determined by the given >average< * Then display the quotient as the value of the first <output> * Finally, display the letter grade as the value of the second <output> */ function calc(e) { const dataIN = e.target; const io = this.elements; const subs = Array.from(io.subject); const avg = io.avg; const grd = io.grd; if (dataIN !== this && dataIN.name === "subject") { const total = subs.reduce((sum, add) => +sum + parseInt(add.value), 0); const average = total / subs.length; const letter = grade(average); avg.value = average; grd.value = letter; } } /** * Given a number in the range of 0 to 100 return The letter grade equivalent. * @param {Number} avg - A number in the range of 0 to 100 * @returns {String} - A letter grade "A" to "F" * @default {String} - If avg ts not within the range of 0 to 100, * a "" is returned */ function grade(avg) { return avg >= 0 && avg < 60 ? "F" : avg >= 60 && avg < 70 ? "D" : avg >= 70 && avg < 80 ? "C" : avg >= 80 && avg < 90 ? "B" : avg >= 90 && avg < 101 ? "A" : ""; } :root { font: 300 ch2/1.15 "Segoe UI" } fieldset { display: flex; flex-flow: column nowrap; width: 50vw; max-width: 60ch; margin: auto; } legend { font-weight: 500; font-size: 1.15rem; } label { display: flex; justify-content: space-between; align-items: center; margin: 0.25rem 1rem; } .last+label { margin-top: 1.25rem; } input, output { display: inline-block; width: 6ch; font: inherit; line-height: normal; text-align: center; } output { text-align: left; } <form id="ga"> <fieldset> <legend>Subjects</legend> <label>English: <input id="eng" name="subject" type="number" min="0" max="100" value="0"></label> <label>Math: <input id="mat" name="subject" type="number" min="0" max="100" value="0"></label> <label>History: <input id="his" name="subject" type="number" min="0" max="100" value="0"></label> <label>Science: <input id="sci" name="subject" type="number" min="0" max="100" value="0"></label> <label class="last">Art: <input id="art" name="subject" type="number" min="0" max="100" value="0"></label> <label>Average: <output id="avg"></output></label> <label>Grade: <output id="grd"></output></label> </fieldset> </form> Appendix * *Events *Event Delegation *Inline Event Handlers are Garbage *HTMLFormElement Interface *HTMLFormControlsCollection Interface *List of Form Controls *Scope and Closures A: NOTES * *This is a fully working example of how you can go about calculating the grades in a generic way without having to use ids for each subject input. *By building it this way, you can add more subjects without changing the calculation logic. *Also if you do not put a value for a subject than it will not be used in the calculations. HTML <div> <section><label>Total:</label><span id="total">0</span></section> <section><label>Average:</label><span id="average">0</span></section> <section><label>Grade:</label><span id="grade">-</span></section> </div> <br /> <form onsubmit="return false;"> <label>English:</label><input type="number" min="0" max="100" step="1" name="english" value="0" /><br /> <label>Math:</label><input type="number" min="0" max="100" step="1" name="math" value="0" /><br /> <label>Physics:</label><input type="number" min="0" max="100" step="1" name="physics" value="0" /><br /> <label>Computer:</label><input type="number" min="0" max="100" step="1" name="computer" value="0" /><br /> <label>Science:</label><input type="number" min="0" max="100" step="1" name="science" value="0" /><br /> <br /> <button onclick="calculateGrades(this)">Calculate Grade</button> </form> CSS label { display: inline-block; width: 4rem; margin-right: 2rem; padding: 0.25rem 1rem; } JS const totalElement = document.getElementById("total"); const averageElement = document.getElementById("average"); const gradeElement = document.getElementById("grade"); // Calculate the grades function function calculateGrades(btn) { // find inputs const form = btn.closest("form"); const inputs = form.getElementsByTagName("input"); // define variables let total = 0; let used = 0; let average = 0; // loop over inputs for (const input of inputs) { // if value = 0, then do not use in calculation if (input.value == 0) continue; // convert input to number and add it to total total += Number( input.value ); // increment number of subjects used used++; } // calculate average grade average = total / used; // display the values totalElement.innerText = total; averageElement.innerText = average; // get letter grade letterGrade( average ); } // Calculate the grade letter function function letterGrade(value) { // define variables let letterGrade = null; // if there is no value return if ( !value ) return letterGrade; // determine letter from value switch (true) { case value >= 90: letterGrade = "A"; break; case value >= 80: letterGrade = "B"; break; case value >= 70: letterGrade = "C"; break; case value >= 60: letterGrade = "D"; break; default: letterGrade = "F"; break; } // display the grade letter gradeElement.innerText = letterGrade; }
{ "language": "en", "url": "https://stackoverflow.com/questions/74323511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Infinite scroll with angularfire2 I'm attempting to recreate this simple example for infinite scroll with a firebase backend: https://angularfirebase.com/lessons/infinite-scroll-with-firebase-data-and-angular-animation/ The problem is that i want to use the latest version of angularfire2, and I just can't figure out how to rewrite 1 method. I'm stuck at the movies-list.components.ts file's getMovies() method, since in the latest version of angularfire2 there's no 'do()' method on AngularFireList objects. Is there a way to run arbitrary code before .take(1).subscribe() ? private getMovies(key?) { if (this.finished) return this.movieService .getMovies(this.batch+1, this.lastKey) .do(movies => { /// set the lastKey in preparation for next query this.lastKey = _.last(movies)['$key'] const newMovies = _.slice(movies, 0, this.batch) /// Get current movies in BehaviorSubject const currentMovies = this.movies.getValue() /// If data is identical, stop making queries if (this.lastKey == _.last(newMovies)['$key']) { this.finished = true } /// Concatenate new movies to current movies this.movies.next( _.concat(currentMovies, newMovies) ) }) .take(1) .subscribe() } A: do() is called tap() in RxJS 6+.
{ "language": "en", "url": "https://stackoverflow.com/questions/49081614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CollectD server system load look scary Please excuse my poor server skill here. However, I just installed collectD on Linux (web server) about minutes ago and found that the system load look a bit scary. All graphs (cpu, memory) look fine except this one. Can you guys let me know if everything is ok given by the graph below? http://oi43.tinypic.com/2q8ocht.jpg If so, can you direct me how to read this graph or point me the source to do further research from here. (does red line graph and the 100m dash look like something it's not suppose to be on the stable server?) A: 100m (milli) means a loadavg of 0.1: your server is pretty fine!
{ "language": "en", "url": "https://stackoverflow.com/questions/21134297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating which compiler is faster in terms of cycling I just have a simple question, a bit silly, but I just need some clarification for an upcoming exam so I don't make a stupid mistake. I am currently taking a class in computer organization and design and am learning about execution time, CPI, clock cycles, etc. For a problem, I have to calculate the amount of cycles for 2 compilers and find out which one is faster and by how much given the number of instructions and the cycles for each instruction. My main problem is figuring how much faster the faster compiler is. For example lets say their are two compilers: Compiler 1 has 3 load instructions, 4 store instructions, and 5 add instructions. Compiler 2 has 5 load instructions, 4 store instructions, and 3 add instructions A load instruction takes 2 cycles, a store instruction takes 3 cycles and a add instruction takes 1 cycle So what I would do this add up to the instructions (3+4+5) and (5+4+3) which both equal to 12 instructions. I'd then calculate the cycles by multiplying the number of instructions by the cycles and adding them all together like this Compiler 1: (3*2)+(4*3)+(5*1) = 23 cycles Compiler 2: (5*2)+(4*3)+(3*1) = 25 cycles So obviously compiler 1 is faster because it requires less cycles. To find out how much faster compiler 1 is against compiler 2 would I just divide the ratio of the cycles? My calculation was 23/25 = 0.92, so compiler 1 is 0.92 times faster than compiler 2 (92% faster). A classmate of mine was discussing this with me and claims that it would be 25/23 which would mean it is 1.08 times faster. I know I can also calculate this by dividing the cycles by the instructions like: 23 cycles/12 instructions = 1.91 25 cycles/12 instructions = 2.08 and then 1.91/2.08 = 0.92 which is the same as the above answer. I'm not sure which way would be correct. I was also wondering if the amount of instructions are difference for the second compiler, let's say 15 instructions. Would calculating the ratio of the cycles be sufficient enough? Or would I have to divide the cycles with the instructions (cycles/instructions) but put 15 instructions for both? (ex. 23/15 and 25/15?) and then divide the quotients of both to get the times faster? I also get the same number(0.92) in that case. Thank you for any clarification. A: The first compiler would be 1.08 times the speed of the second compiler, which is 8% faster (because 1.0 + 0.08 = 1.08). A: Probably both calculations are innacurate, with modern/multi-core processors a compiler that generates more instruction may actually produce faster code.
{ "language": "en", "url": "https://stackoverflow.com/questions/55567336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CKEditor ReadOnly I got a problem since I use the CKEditor (http://ckeditor.com/). The problem is that I can't find a way to make the editor ReadOnly and I can't just use a textarea since I want to keep consistency. I've already seen lots og questions like this at StackOwerflow, but none of them work or are too old. My code so far is only to display/initialize the editor: $(document).ready(function(){ CKEDITOR.replace( 'ckeditor', { on: { // Check for availability of corresponding plugins. pluginsLoaded: function( evt ) { var doc = CKEDITOR.document, ed = evt.editor; if ( !ed.getCommand( 'bold' ) ) doc.getById( 'exec-bold' ).hide(); if ( !ed.getCommand( 'link' ) ) doc.getById( 'exec-link' ).hide(); } } }); }); I use the newest CKEditor version(v.4.1.1 Full package) Thanks in advance! :) A: In the docs readOnly you can set the config to readOnly config.readOnly = true; There is also an example that shows setting it via a method editor.setReadOnly( true); A: try with following lines, <textarea id="editor1" name="editor1" ></textarea> <textarea id="editor2" name="editor2" ></textarea> <input type="button" onclick="EnableEditor2()" value="EnableEditor2" /> <script> $(document).ready(function () { //set editor1 readonly CKEDITOR.replace('editor1', {readOnly:true}); CKEDITOR.replace('editor2'); //set editor2 readonly CKEDITOR.instances.editor2.config.readOnly = true; }); function EnableEditor2() { CKEDITOR.instances.editor2.setReadOnly(false); } </script> A: have you tried this ? they say, that this should work var editor; // The instanceReady event is fired, when an instance of CKEditor has finished // its initialization. CKEDITOR.on( 'instanceReady', function( ev ) { editor = ev.editor; // Show this "on" button. document.getElementById( 'readOnlyOn' ).style.display = ''; // Event fired when the readOnly property changes. editor.on( 'readOnly', function() { document.getElementById( 'readOnlyOn' ).style.display = this.readOnly ? 'none' : ''; document.getElementById( 'readOnlyOff' ).style.display = this.readOnly ? '' : 'none'; }); }); function toggleReadOnly( isReadOnly ) { // Change the read-only state of the editor. // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#setReadOnly editor.setReadOnly( isReadOnly ); } and html <form action="sample_posteddata.php" method="post"> <p> <textarea class="ckeditor" id="editor1" name="editor1" cols="100" rows="10">&lt;p&gt;This is some &lt;strong&gt;sample text&lt;/strong&gt;. You are using &lt;a href="http://ckeditor.com/"&gt;CKEditor&lt;/a&gt;.&lt;/p&gt;</textarea> </p> <p> <input id="readOnlyOn" onclick="toggleReadOnly();" type="button" value="Make it read-only" style="display:none" /> <input id="readOnlyOff" onclick="toggleReadOnly( false );" type="button" value="Make it editable again" style="display:none" /> </p> </form> A: In version 5 i do this: ClassicEditor .create( document.querySelector( '.editor' ), { removePlugins: ['Title'], licenseKey: '', } ) .then( editor => { window.editor = editor; editor.isReadOnly = true; } ) .catch( error => { console.error( 'Oops, something went wrong!' ); console.error( 'Please, report the following error on https://github.com/ckeditor/ckeditor5/issues with the build id and the error stack trace:' ); console.warn( 'Build id: efxy8wt6qchd-qhxgzg9ulnyo' ); console.error( error ); } ); A: Sources : http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.readOnly http://rev.ckeditor.com/ckeditor/trunk/7657/_samples/readonly.html CKEDITOR.config.readOnly = true; A: Check this one out. The idea is if a user logs in a system with a classification other than 'BPPA', the CK editor shall be disabled and read-only. If the classification of a user is BPPA, thus the CK editor is editable. Note that these code fractions are actually in PHP. They need a working database to work but I figured you might get the idea and be able to work your own magic. <?php //This line is to disable PART A if classification != 'BPPA' $bppa = mysql_query("SELECT * from roles WHERE username = '$_SESSION[username]'"); $bppa_row = mysql_fetch_array($bppa); if($bppa_row['classification'] != 'BPPA'){ $disabled = 'disabled = "disabled"'; }else{ $disabled = ""; } //ends here ?> Then, apply $disable to your text area: <?php echo '<textarea class="ckeditor" '.$disabled.' name="content' . $n . '" id="content' . $n . '">' . $saved . '</textarea>'; ?> A: with version 4.5.4 you can do it with: $('#idElement).ckeditorGet().setReadOnly(true); A: In case you have several editors on the same page and you want to disable all of them on the page display : CKEDITOR.on('instanceReady', function (ev) { ev.editor.setReadOnly(true); }); Documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/16237093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android pin activity on boot I've got an app that registers itself as the default launcher and pins itself automatically when started. This all works fine when installing the app. It pins itself and only the back button is visible. The problem is that when the device first boots up, it does not pin properly. I see a series of toasts "Screen pinned" and "Screen unpinned" multiple times. The "Home" and "Recent Tasks" buttons are still visible as well. -- Running "adb shell dumpsys activity activities" - the last lines indicate that it is not pinned: mLockTaskModeState=NONE mLockTaskPackages (userId:packages)= 0:[com.example.myapp] mLockTaskModeTasks[] -- Testing device Asus ZenPad running Marshmallow/6.0/23 I'm relying on the MainActivity manifest attribute "lockTaskMode" to pin (rather than activity.startLockTask()): <activity android:name=".MainActivity" android:configChanges="keyboardHidden|orientation|screenSize" android:label="@string/launcher_main" android:launchMode="singleTask" android:lockTaskMode="if_whitelisted" android:screenOrientation="landscape"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.HOME"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> Any help or pointers would be appreciated A: I had the same problem and I could really only find one solution. I'm not sure why but yeah, something in android prevents task locking when booting up which boggles my mind since the task lock was designed to create these "kiosk" type of applications. The only solution I could find was to detect for a case when it didn't lock then restart the application. Its a little "hacky" but what else can you do? To detect for the case where it didn't lock I created a state variable and assigning states (Locking, Locked, Unlocking, Unlocked). Then in the device admin receiver in onTaskModeExiting if the state isn't "Unlocking" then I know it unlocked on its own. So if this case happened where it failed, I then restart the application using this method (which schedules the application in the alarm manager then kills the application): how to programmatically "restart" android app? Here is some sample code: DeviceAdminReceiver @Override public void onLockTaskModeEntering(Context context, Intent intent, String pkg) { super.onLockTaskModeEntering(context, intent, pkg); Lockdown.LockState = Lockdown.LOCK_STATE_LOCKED; } @Override public void onLockTaskModeExiting(Context context, Intent intent) { super.onLockTaskModeExiting(context, intent); if (Lockdown.LockState != Lockdown.LOCK_STATE_UNLOCKING) { MainActivity.restartActivity(context); } Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKED; } MainActivity public static void restartActivity(Context context) { if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { Intent intent = pm.getLaunchIntentForPackage(context.getPackageName()); if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); int pendingIntentId = 223344; PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent); System.exit(0); } } } } private void lock() { Lockdown.LockState = Lockdown.LOCK_STATE_LOCKING; startLockTask(); } private void unlock() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) { Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKING; stopLockTask(); } } In truth this is a simplified version of what I implemented. But it should hopefully get you pointed towards a solution. A: The only solution I found as for now : make another launcher app, without locktask, which will trigger main app every time when launcher appears. This prevent user for waiting few more seconds before LockTasked app is being called with on BOOT_COMPLETED receiver. So we can meet this problem only when lockTask app has launcher properties for some activity in manifest. A: Sorry for late answering, but... Anyone has this problem can do this tricky work in first (LAUNCHER/HOME) activity (e.g. MainActivity): @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mSharedPreferences.getBoolean(KEY_PREF_RECREATED, false)) { mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, false).apply(); // start LOCK TASK here } else { mSharedPreferences.edit().putBoolean(KEY_PREF_RECREATED, true).apply(); finish(); // close the app startActivity(new Intent(this, MainActivity.class)); // reopen the app return; } setContentView(R.layout.activity_main); // other codes }
{ "language": "en", "url": "https://stackoverflow.com/questions/39965124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Connecting to remote HBase service using Java I have a small sample code in which I try to establish a connection to a remote HBase entity. The code runs on a windows machine without HBase installed and I try to connect to a remote Ubuntu Server that has it installed and running. The IP in the below snippet is of course just a placeholder. The code is as follows: public static void main(String[] args) { Configuration conf = HBaseConfiguration.create(); HBaseAdmin admin = null; String ip = "10.10.10.10"; String port = "2181"; conf.set("hbase.zookeeper.quorum", ip); conf.set("hbase.zookeeper.property.clientPort", port); try { admin = new HBaseAdmin(conf); boolean bool = admin.tableExists("sensor_data"); System.out.println("Table exists? " + bool); } catch (IOException e) { e.printStackTrace(); } } But for some reason I get this error: org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocator at org.apache.hadoop.hbase.client.RpcRetryingCaller.translateException(RpcRetryingCaller.java:229) at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:202) at org.apache.hadoop.hbase.client.ClientScanner.call(ClientScanner.java:320) at org.apache.hadoop.hbase.client.ClientScanner.nextScanner(ClientScanner.java:295) at org.apache.hadoop.hbase.client.ClientScanner.initializeScannerInConstruction(ClientScanner.java:160) at org.apache.hadoop.hbase.client.ClientScanner.<init>(ClientScanner.java:155) at org.apache.hadoop.hbase.client.HTable.getScanner(HTable.java:811) at org.apache.hadoop.hbase.MetaTableAccessor.fullScan(MetaTableAccessor.java:602) at org.apache.hadoop.hbase.MetaTableAccessor.tableExists(MetaTableAccessor.java:366) at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:303) at org.apache.hadoop.hbase.client.HBaseAdmin.tableExists(HBaseAdmin.java:313) at com.twoBM.Tests.HBaseWriter.main(HBaseWriter.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from class org.apache.hadoop.hbase.zookeeper.MetaTableLocator at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:596) at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:580) at org.apache.hadoop.hbase.zookeeper.MetaTableLocator.blockUntilAvailable(MetaTableLocator.java:559) at org.apache.hadoop.hbase.client.ZooKeeperRegistry.getMetaRegionLocation(ZooKeeperRegistry.java:61) at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateMeta(ConnectionManager.java:1185) at org.apache.hadoop.hbase.client.ConnectionManager$HConnectionImplementation.locateRegion(ConnectionManager.java:1152) at org.apache.hadoop.hbase.client.RpcRetryingCallerWithReadReplicas.getRegionLocations(RpcRetryingCallerWithReadReplicas.java:300) at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call(ScannerCallableWithReplicas.java:153) at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas.call(ScannerCallableWithReplicas.java:61) at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:200) ... 15 more I am using Gradle to build my project and currently I am only using the two following dependencies: compile 'org.apache.hive:hive-jdbc:2.1.0' compile 'org.apache.hbase:hbase:1.1.6' Does anyone know to fix this problem? I have tried googling this problem, but without any of the found links providing an actual solution. Best regards A: This is definitely Google Guava's dependency conflict. The default constructor of Stopwatch class became private since Guava v.17 and marked deprecated even earlier. So to HBase Java client works properly you need Guava v.16 or earlier. Check the way you build your application (Maven/Gradle/Classpath) and find the dependency which uses Guava v.17+. After that, you can resolve the conflict. A: I received the same error and had to spend for 5 days to know the issue. I added following dependency and its gone. <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version> </dependency> A: You can use maven shade plugin to solve this issue. That a look at this blog post. Here is an example (actually a snippet from my working pom.) <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>assemble-all</id> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <!--<finalName>PROJECT_NAME-${project.version}-shaded</finalName>--> <relocations> <relocation> <pattern>com.google.common</pattern> <shadedPattern>shaded.com.google.common</shadedPattern> </relocation> <relocation> <pattern>com.google.protobuf</pattern> <shadedPattern>shaded.com.google.protobuf</shadedPattern> </relocation> </relocations> <artifactSet> <includes> <include>*:*</include> </includes> </artifactSet> </configuration> </execution> </executions> </plugin>
{ "language": "en", "url": "https://stackoverflow.com/questions/39725234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Trying to use hashmap to count frequency of words in array This is my code: public static void main(String args[]) throws Exception { BufferedReader infile = new BufferedReader(new FileReader(args[0])); HashMap<String,Integer> histogram = new HashMap<String,Integer>(); while ( infile.ready() ) { String SPACE = " "; String [] words = infile.readLine().split(SPACE); for (String word : words) { Integer f = histogram.get(word); histogram.put(word,f+1); } } infile.close(); printHistogram( histogram ); } private static void printHistogram( HashMap<String,Integer> hm ) { System.out.println(hm); } I keep getting a NullPointerException for the " histogram.put(word,f+1);" part. why is this? A: This happens because f will be null if the value is not found in the map. Try this, inside the for loop. Integer f = histogram.get(word); if (f == null) { histogram.put(word, 1); } else { histogram.put(word, f+1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/22927184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: No "Location" header in JMeter for Auth 2.0 Auth 2.0. "code" parameter is required to perform POST /.../oauth2/v2.0/token with code value. In Fiddler code value could be found in Location header of response to /kmsi request: However, here is no Location header in JMeter for the same request: Why? Are there any tip to get Location header in JMeter too? A: If you're seeing different response it means that * *Either you're sending a different request. In this case inspect request details from JMeter and from the real browser using a 3rd-party sniffer tool like Fiddler or Burp, identify the inconsistencies and amend your JMeter configuration so it would send exactly the same request as the real browser does (apart from dynamic values which need to be correlated) *Or one of the previous requests fails somewhere somehow, JMeter automatically treats HTTP responses with status codes below 400 as successful, it might be the case they are not really successful, i.e. you're continuously hitting the login page (you can check it by inspecting response data tab of the View Results Tree listener). Try adding a Response Assertions to the HTTP Request samplers so there will be another layer of explicit checks of the response data, this way you will get confidence that JMeter is doing what it is supposed to be doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/68358295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Text file with columns and records, analyze Python I have text file with some columns and records(<1000 records). Name Surname Age Grade Faculty Chris M 20 5 Electronics Jack A 22 3 Computer science Michael J 21 4 Computer science ... Now I want type a functions with dicitionary. * *1) Show students names with 22 age . *2) Show students of Electronics. Example 1) 'Chris': 20, My code: a = {} with open("file.txt") as f: for line in f: k,v = line.split(' ') #spacebar in file a[k.strip()] = v.strip() But of course not working because I have not idea. What would be the best way to do this in Python? Thanks in advance. A: The easiest way is Pandas. Read data from file into DataFrame: import pandas as pd df = pd.read_csv('file.txt', sep=' ') 1) Show students names with 22 age. result = df[df['Age'] == 22] 2) Show students of Electronics. result = df[df['Faculty'] == 'Electronics'] A: I can give you a hint on building a dictionary: a = [] with open("file.txt") as f: keys = f.readline().strip().split(' ', 4) for line in f: val = line.strip().split(' ', 4) # spacebar in file a.append(dict(zip(keys, val))) Now a contains a list of dictionaries like this one: {'Name': 'Chris', 'Surname': 'M', 'Age': '20', 'Grade': '5', 'Faculty': 'Electronics' }
{ "language": "en", "url": "https://stackoverflow.com/questions/44508036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: r-value Reference Casting and Temporary Materialization The output for the code below produces: void doit(const T1 &, const T2 &) [T1 = unsigned long, T2 = int] t1 == t2 t1 == (T1)t2 t1 != (T1&)t2 t1 == (T1&&)t2 I understand that the t1 == t2 case is simply an integral promotion. The second case t1 == (T1)t2 is the same thing, just explicit. The third case t1 == (T1&)t2 must be a reinterpret_cast of some sort... Though, further explanation would be helpful. The fourth case t1 == (T1&&)t2 is what I am stuck on. I put in the term 'Temporary Materialization' in the question's title as this is the closest I could come to some sort of answer. Could someone go over these four cases? Code: #include <iostream> template <typename T1, typename T2> void doit(const T1& t1, const T2& t2) { std::cout << __PRETTY_FUNCTION__ << '\n'; if (t1 == t2) { std::cout << "t1 == t2" << '\n'; } else { std::cout << "t1 != t2" << '\n'; } if (t1 == (T1)t2) { std::cout << "t1 == (T1)t2" << '\n'; } else { std::cout << "t1 != (T1)t2" << '\n'; } if (t1 == (T1&)t2) { std::cout << "t1 == (T1&)t2" << '\n'; } else { std::cout << "t1 != (T1&)t2" << '\n'; } if (t1 == (T1&&)t2) { std::cout << "t1 == (T1&&)t2" << '\n'; } else { std::cout << "t1 != (T1&&)t2" << '\n'; } } int main() { const unsigned long a = 1; const int b = 1; doit(a, b); return 0; } A: The compiler attempts to interpret c-style casts as c++-style casts, in the following order (see cppreference for full details): * *const_cast *static_cast *static_cast followed by const_cast *reinterpret_cast *reinterpret_cast followed by const_cast Interpretation of (T1)t2 is pretty straightforward. const_cast fails, but static_cast works, so it's interpreted as static_cast<T1>(t2) (#2 above). For (T1&)t2, it's impossible to convert an int& to unsigned long& via static_cast. Both const_cast and static_cast fail, so reinterpret_cast is ultimately used, giving reinterpret_cast<T1&>(t2). To be precise, #5 above, since t2 is const: const_cast<T1&>(reinterpret_cast<const T1&>(t2)). EDIT: The static_cast for (T1&)t2 fails due to a key line in cppreference: "If the cast can be interpreted in more than one way as static_cast followed by a const_cast, it cannot be compiled.". Implicit conversions are involved, and all of the following are valid (I assume the following overloads exist, at a minimum): * *T1 c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1)) *const T1& c1 = t2; const_cast<T1&>(static_cast<const T1&>(c1)) *T1&& c1 = t2; const_cast<T1&>(static_cast<const T1&>(std::move(c1))) Note that the actual expression, t1 == (T1&)t2, leads to undefined behavior, as Swift pointed out (assuming sizeof(int) != sizeof(unsigned long)). An address that holds an int is being treated (reinterpreted) as holding an unsigned long. Swap the order of definition of a and b in main(), and the result will change to be equal (on x86 systems with gcc). This is the only case that has undefined behavior, due to a bad reinterpret_cast. Other cases are well defined, with results that are platform specific. For (T1&&)t2, the conversion is from an int (lvalue) to an unsigned long (xvalue). An xvalue is essentially an lvalue that is "moveable;" it is not a reference. The conversion is static_cast<T1&&>(t2) (#2 above). The conversion is equivalent to std::move((T1)t2), or std:move(static_cast<T1>(t2)). When writing code, use std:move(static_cast<T1>(t2)) instead of static_cast<T1&&>(t2), as the intent is much more clear. This example shows why c++-style casts should be used instead of c-style casts. Code intent is clear with c++-style casts, as the correct cast is explicitly specified by the developer. With c-style casts, the actual cast is selected by the compiler, and may lead to surprising results. A: Let's look at (T1&&)t2 first. This is indeed a temporary materialization; what happens is that the compiler performs lvalue-to-rvalue conversion on t2 (i.e. accesses its value), casts that value to T1, constructs a temporary of type T1 (with value 1, since that is the value of b and is a valid value of type T1), and binds it to an rvalue reference. Then, in the comparison t1 == (T1&&)t2, both sides are again subject to lvalue-to-rvalue conversion, and since this is valid (both refer to an object of type T1 within its lifetime, the left hand side to a and the right hand side to the temporary) and both sides have value 1, they compare equal. Note that a materialized temporary of type T1 (say) can bind either to a reference T1&& or T1 const&, so you could try the latter as well in your program. Also note that while the T1 converted from t2 is a temporary, it would be lifetime extended if you bound it to a local variable (e.g. T1&& r2 = (T1&&)t2;). That would extend the lifetime of the temporary to that of the local reference variable, i.e. to the end of the scope. This is important when considering the "with its lifetime" rule, but here the temporary is destroyed at the end of the expression, which is still after it is accessed by the == comparison. Next, (T1&)t2 should be interpreted as a static_cast reference binding to a temporary T1 followed by a const_cast; that is, const_cast<T1&>(static_cast<T1 const&>(t2)). The first (inner) cast materializes a temporary T1 with value converted from t2 and binds it to a T1 const& reference, and the second (outer) cast casts away const. Then, the == comparison performs lvalue-to-rvalue conversion on t1 and on the T1& reference; both of these are valid since both refer to an object of type T1 within its lifetime, and since both have value 1 they should compare equal. (Interestingly, the materialized temporary is also a candidate for lifetime extension, but that doesn't matter here.) However, all major compilers currently fail to spot that they should do the above (Why is (int&)0 ill-formed? Why does this C-style cast not consider static_cast followed by const_cast?) and instead perform a reinterpret_cast (actually a reinterpret_cast to T1 const& followed by a const_cast to T1&). This has undefined behavior (since unsigned long and int are distinct types that are not related by signedness and are not types that can access raw memory), and on platforms where they are different sizes (e.g. Linux) will result in reading stack garbage after b and thus usually print that they are unequal. On Windows, where unsigned long and int are the same size, it will print that they are equal for the wrong reason, which will nevertheless be undefined behavior. A: Technically all four variants are platform dependent t1 == t2 t2 gets promoted to 'long', the casted to unsigned long. t1 == (T1)t2 signed int gets converted to its representation as unsigned long, in order being casted to long first. There were debates if this must be considered an UB or not, because result is depending on platform, I honestly not sure how it is defined now, aside from clause in C99 standard. Result of comparison would be same as t1 == t2. t1 == (T1&)t2 The cast result is a reference, you compare reference ( essentially a pointer) to T1, which operation yields unknown result. Why? Reference js pointing to a different type. t1 == (T1&&)t2 The cast expression yields an rvalue, so you do compare values, but its type is rvalue reference. Result of comparison would be same as t1 == t2. PS. Funny thing happen (depends on platform, essentially an UB) if if you use such values: const unsigned long a = 0xFFFFFFFFFFFFFFFF; const int b = -1; Output might be: t1 == t2 t1 == (T1)t2 t1 == (T1&)t2 t1 == (T1&&)t2 This is one of reasons why you should be careful in comparing unsigned to signed values, especially with < or >. You'll be surprised by -1 being greater than 1. if unsigned long is 64bit int and pointer is equal to 64-bit int. -1 if casted to unsigned, becomes its binary representation. Essentially b would become a pointer with address 0xFFFFFFFFFFFFFFFF.
{ "language": "en", "url": "https://stackoverflow.com/questions/48796854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: how to make an operation wait until the other operation finish in swift I'm working on an application which fetches data from api's I'm using alamofire to fetch data my question is how could I make an application wait until the data fetching finish I'm using following code to fetch data class abc:NSOperation{ static let sharedInstance = abc() func main() { Alamofire.request(.GET, "http://playground.dzireinfotech.com/admin/event/getallevents", parameters: nil).response{ (request, response, data, error) in if(error == nil){ let jsn = JSON(data: data!) if let nn = jsn.array{ let a = nn.count print("a\(a)") for(var i=0; i<a; i++){ self.e_Id.append(jsn[i]["e_id"].string!) self.e_date.append(jsn[i]["e_date"].string!) self.e_time.append(jsn[i]["e_time"].string!) self.e_title.append(jsn[i]["e_title"].string!) self.e_image.append(jsn[i]["e_image"].string!) self.e_description.append(jsn[i]["e_description"].string!) self.e_num_table.append(jsn[i]["e_num_table"].string!) self.imgx.append(self.ImgURL + (jsn[i]["e_image"].string!)) // self.e_latitude.append(jsn[i]["e_latitude"].string!) // self.e_longitude.append(jsn[i]["e_longitude"].string!) //self.e_status.append(jsn[i]["e_status"].string!) } } if(self.imgx.count>0){ FirstViewController.sharedInstance.loadData(self) } }else{ print("Error") } } } The above code works fine but it gives problem in following code class pqr: UIViewController{ override func viewDidLoad() { super.viewDidLoad() abc.sharedInstance.main() //I want to make wait here imageUrls = abc.sharedInstance.imgx let ab = abc.sharedInstance.img_number print("ImageUrl\(imageUrls)") print("Image Number\(ab)") let urlx:NSURL = NSURL(string: imageUrls[ab])! self.imageView.sd_setImageWithURL(urlx) } } A: Move all the code in viewDidLoad that depends on the long running operation to another method and then call that method in the completion handler of the long-running process. A: You could put all of this code into your viewdidload so that the app won't open until that code is finished running. Are you trying to make it so the app stays on the launch screen until the the data has been fetched. If I am correct you should just put the code in the viewdidload function it should say. View did appear and then in the put the code correct me if I am wrong I am new to this. Can you share the top of your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/34063789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Process functions from a list of strings in Python I have a module that I import to my main application called pageprocs.py with a collection of functions in it that generate different content and return it in a string. pageprocs is supposed to be a way of allowing authenticated users to create plugins for the different content type. I then have a list of strings: ['check_stats', 'build_table', 'build_ace'] which are the names of some functions in pageprocs. I need to execute the functions in the order they are in the list and can't find a way of doing this without using exec(): for i in list_of_funcs: exec('pageprocs.%s()' % i) This just seems like a seriously bad idea to me and not easy to catch any exceptions in users code. Is there an alternative to running code this way or does anybody have suggestions on user-defined content generation (I ask this because I maybe approaching the whole situation wrong). A: for i in list_of_stats: getattr(pageprocs, i, lambda: None)() The lambda: None part is optional, but will prevent AttributeError being raised if the specified function doesn't exist (it's an anonymous do-nothing function).
{ "language": "en", "url": "https://stackoverflow.com/questions/11705546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Removing duplicates from a list of lists based on a comparison of an element of the inner lists I have a large list of lists and need to remove duplicate elements based on specific criteria: * *Uniqueness is determined by the first element of the lists. *Removal of duplicates is determined by comparing the value of the second element of the duplicate lists, namely keep the list with the lowest second element. [[1, 4, 5], [1, 3, 4], [1, 2, 3]] All the above lists are considered duplicates since their first elements are equal. The third list needs to be kept since it's second element is the smallest. Note the actual list of lists has over 4 million elements, is double sorted and ordering needs to be preserved. The list is first sorted based on the second element of the inner lists and in reverse (descending) order, followed by normal (ascending) order based on the first element: sorted(sorted(the_list, key=itemgetter(1), reverse=True), key=itemgetter(0)) An example of three duplicate lists in their actual ordering: [... [33554432, 50331647, 1695008306], [33554432, 34603007, 1904606324], [33554432, 33554687, 2208089473], ...] The goal is to prepare the list for bisect searching. Can someone provide me with insight on how this might be achieved using Python? A: You can group the elements using a dict, always keeping the sublist with the smaller second element: l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]] d = {} for sub in l: k = sub[0] if k not in d or sub[1] < d[k][1]: d[k] = sub Also you can pass two keys to sorted, you don't need to call sorted twice: In [3]: l = [[1,4,6,2],[2,2,4,6],[1,2,4,5]] In [4]: sorted(l,key=lambda x: (-x[1],x[0])) Out[4]: [[1, 4, 6, 2], [1, 2, 4, 5], [2, 2, 4, 6]] If you wanted to maintain order in the dict as per ordering needs to be preserved.: from collections import OrderedDict l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]] d = OrderedDict() for sub in l: k = sub[0] if k not in d or sub[1] < d[k][1]: d[sub[0]] = sub But not sure how that fits as you are sorting the data after so you will lose any order. What you may find very useful is a sortedcontainers.sorteddict: A SortedDict provides the same methods as a dict. Additionally, a SortedDict efficiently maintains its keys in sorted order. Consequently, the keys method will return the keys in sorted order, the popitem method will remove the item with the highest key, etc. An optional key argument defines a callable that, like the key argument to Python’s sorted function, extracts a comparison key from each dict key. If no function is specified, the default compares the dict keys directly. The key argument must be provided as a positional argument and must come before all other arguments. from sortedcontainers import SortedDict l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]] d = SortedDict() for sub in l: k = sub[0] if k not in d or sub[1] < d[k][1]: d[k] = sub print(list(d.values())) It has all the methods you want bisect, bisect_left etc.. A: If I got it correctly, the solution might be like this: mylist = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [7, 3, 6], [7, 1, 8]] ordering = [] newdata = {} for a, b, c in mylist: if a in newdata: if b < newdata[a][1]: newdata[a] = [a, b, c] else: newdata[a] = [a, b, c] ordering.append(a) newlist = [newdata[v] for v in ordering] So in newlist we will receive reduced list of [[1, 2, 3], [7, 1, 8]].
{ "language": "en", "url": "https://stackoverflow.com/questions/34334381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Downloading files from expressJS (sendFile) server to VueJS, is returning corrupted files? I have an API written in expressjs, that sends a file when provided with a fileID. The backend is working fine, as it sends the correct file (uncorrupted) when the route url is typed directly int the browser. ex. http://localhost:8080/download?id=1234 (downloads all files just fine ie.txt, xlsx, jpg, zip) My express route actually uses res.download, which is really jsut a wrapper for sendFile. When I try calling these route urls from a Vue http get request, it only returns txt files uncorrupted. All other files download, but they can be opened, due to corruption. Can anyone please point me in the right direction as to why its not working in Vue? For clarity, "item" is passed as an argument to this function. this.$http.get("http://localhost:8000/files/download", {params:{id:item._id}}, {responseType: 'arraybuffer'}) .then(response => { var blob = new Blob([response.data], {type:response.headers.get('content-type')}); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = item.filename; link.click(); }) For reference, this is my express route A: Shout out to @Helpinghand for helping me troubleshoot this. "I found the solution within the link you posted. The problem is that i was explicitly sending params in its own object before assigning "content-type". The example you posted concatenates the query params to the url. After making this switch, its working perfectly". this.$http.get(`http://localhost:8000/files/download?id=${item._id}`, {responseType: 'arraybuffer'}) .then(response => { console.log(response.headers.get('content-type')); console.log(response); var blob = new Blob([response.body], {type:response.headers.get('content-type')}); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = item.filename_version; link.click(); })
{ "language": "en", "url": "https://stackoverflow.com/questions/51810331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Continuous subset and ranking using sql I have a dataset like below: Now, I need the output as below: start_time end_time count 10:01 10:04 3 10:05 10:07 2 For this purpose, I wrote a query but it is not giving me the desired sequence. My query is as below: with on_off as ( select time,status,case when status!=lag(status) over(order by time) then 1 else 0 end as continuous_count from time_status ) , grp as ( select *, row_number() over(partition by continuous_count order by time) rnk from on_off ) select * from grp order by time It generates the output as below: But in the rank section I need something as below: So, what exactly am I doing wrong here? Here are the PostgresSQL DDLs: create table time_status(time varchar(10) null, status varchar(10) null); INSERT into time_status(time,status) values('10:01','ON'); INSERT into time_status(time,status) values('10:02','ON'); INSERT into time_status(time,status) values('10:03','ON'); INSERT into time_status(time,status) values('10:04','OFF'); INSERT into time_status(time,status) values('10:05','ON'); INSERT into time_status(time,status) values('10:06','ON'); INSERT into time_status(time,status) values('10:07','OFF'); A: Try this query: SELECT min(time) as start_time, max(time) as end_time, sum(case when status = 'ON' then 1 else 0 end) as cnt FROM (SELECT time, status, sum(case when status = 'OFF' then 1 else 0 end) over (order by time desc) as grp FROM time_status) _ GROUP BY grp ORDER BY min(time); ->Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/72221504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: load a url after a specific amount of time I have a single url that I need to open it after a specific amount of time. I think this can be done using js/jquery and I see it working like this: I open the page created with the js code inside and the url loads automatic in a new tab and after 5 minutes this same url is opened in a new tab or in the same tab that was previously opened. It's a trick I am working on and the problem is that I don't know much in js/jquery that's why I need your help. You might ask me: Hey, this code will open a new tab each 5 minutes so you'll have a lot of them running, are you sure you need this?.. and I say yes, that's what I need, a new tab for a single url each 5 minutes. Thanks. A: You could use setTimeout() which will wait a specified amount of time (ms) then execute the declared function. Example: setTimeout(openUrl, 5000); // Wait 5 seconds function openUrl(){ window.open('http://google.com'); } To repeat an action on a timer you can use setInterval() setInterval(openUrl, 5000); A: check out the setTimeout and setInterval methods for JS http://www.w3schools.com/js/js_timing.asp http://www.w3schools.com/jsref/met_win_setinterval.asp A: You need to call settimeout inside openUrl again to repeat it endlessly
{ "language": "en", "url": "https://stackoverflow.com/questions/9186574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use parameters for lambda expressions correctly in C#? I was wondering, if I use Lambda expressions correctly in the following short code snippet? I want to store function calls over time and then execute them all together in Update_Calls(). Most importantly, I am asking whether the parameters var1-3 keep their value (the value they had when calling Extern_Func()) in ANY case? static List<Action> callsForUpdate = new List<Action>(); public static void Extern_Func(int var1, int var2, float var3) { Action callToStore = () => Func(var1, var2, var3); // Remember in call list callsForUpdate.Add(callToStore); } public static void Update_Calls() { for (int i = 0; i < callsForUpdate.Count; i++) { callsForUpdate.ElementAt(i); } callsForUpdate.Clear(); } A: Yes. They will be retained. Your Update_Calls has an issue. public static void Update_Calls() { for (int i = 0; i < callsForUpdate.Count; i++) { callsForUpdate.ElementAt(i)(); } callsForUpdate.Clear(); } You were only referring the element. Not calling it. A: What you are creating is called Closure, which means that Action will be called with the current values of var1, var2, var3, in this case they are local variables of Extern_Func, so unless you change them in that method (Extern_Func) they will keep their value. A: What you are doing is creating an expression pointed to by each item in the callsForUpdate list. Expressions are immutable. In order to change the values you supplied in an expression, the expression must be replaced by a new expression with new values. In my best estimation of what you are asking is true for most any case because your list is simply a list of expressions to be executed with the values supplied at the time they were created by Etern_Func. A: Closures capture variables, not values. Make sure that is clear. In your case, var1, var2 and var3 are passed by value arguments that can only be changed locally. Therefore if you don't change them inside Extern_Func you are good to go. To understand the difference between capturing values or variables, consider the following snippet: var funcs = new List<Action>(); for (var i = 0; i < 5; i++) { var temp = i; funcs.Add(() => Console.WriteLine(i)); funcs.Add(() => Console.WriteLine(temp)); } foreach (var f in funcs) { f(); } Can you guess the output?
{ "language": "en", "url": "https://stackoverflow.com/questions/41792395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery image slider auto play and click Please suggest any change where i need to make in this code in order to make this slider auto play after 4000 milliseconds.right not it is working fine on click.i made few changes after following few suggestions but its not working <script type="text/javascript"> $(function() { var Page = (function() { var $navArrows = $( '#nav-arrows' ), $nav = $( '#nav-dots > span' ), slitslider = $( '#slider' ).slitslider( { onBeforeChange : function( slide, pos ) { $nav.removeClass( 'nav-dot-current' ); $nav.eq( pos ).addClass( 'nav-dot-current' ); } } ), init = function() { initEvents(); }, initEvents = function() { // add navigation events $navArrows.children( ':last' ).on( 'click', function() { slitslider.next(); return false; } ); $navArrows.children( ':first' ).on( 'click', function() { slitslider.previous(); return false; } ); $nav.each( function( i ) { $( this ).on( 'click', function( event ) { var $dot = $( this ); if( !slitslider.isActive() ) { $nav.removeClass( 'nav-dot-current' ); $dot.addClass( 'nav-dot-current' ); } slitslider.jump( i + 1 ); return false; } ); } ); }; return { init : init }; })(); Page.init(); }); </script> A: Just looking at the slitslider docs I think you need to add these two lines to the following excerpt of your code: .slitslider({ // slideshow on / off autoplay : true, // time between transitions interval : 4000, onBeforeChange : function(slide, pos) { $nav.removeClass('nav-dot-current'); $nav.eq(pos).addClass('nav-dot-current'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/15675590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reject a transition based on user input, without confirm() EmberJS: reject an upcoming transition How would I reject an upcoming transition via willTransition, but using a custom pop up or jQuery .dialog box such as this: willTransition: function(transition) { //Some conditional logic would go here to determine if they need to be prompted to save $("#confirmTransition").dialog({ resizable: false, modal: true, draggable: false, buttons: { "Yes": function() { self.transitionTo(transition.targetName); $(this).dialog( "close" ); }, "No": function() { transition.abort(); $(this).dialog( "close" ); } } }); } Rather than using confirm() which would actually wait until the user enters something. I can use a .then, but it fires after the transition completes. Would I be better off using beforeModel on all routes to handle a conditional abort, and then rely on willTransition to provide the popup to confirm? Updated per accepted question: willTransition: function(transition) { //Some conditional logic would go here to determine if they need to be prompted to save var self = this; if(!self._transitioning){ $("#confirmTransition").dialog({ resizable: false, modal: true, draggable: false, buttons: { "Yes": function() { self._transitioning = true; transition.retry().then(self._transitioning = false); $(this).dialog( "close" ); }, "No": function() { transition.abort(); $(this).dialog( "close" ); } } }); } } A: You could use the same approach to animate route transitions: You can take a look at the relatebase blog (as well as the jsbin example referred by the blog). Essentially you handle a little state machine in the willTransition action: You abort the original transition and as soon as the user closes the dialog you retry the original transition. Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/22459898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do I need an iOS developer license for TestFlight I am going to be creating an iOS app to run on an iPad using the PhoneGap framework. Instead of putting my app on the App Store I'm going to use TestFlight. If I'm not going to be using the App Store do I still need to purchase an iOS developer license? A: Yes, you need an iOS Developer Account in order to create the provisioning profiles and certificates you need for your app to actually run on a real device. A: Yes, it is mandatory to have a certificate and provisioning profile to build your app for device. You have to enroll for developer program/enterprise developer program if you wish to install your app on a device. It does not matter if you choose to use TestFlight or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/18569959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery error after setting anchor tag dynamically I am trying to set the href property of an anchor tag using jquery, by writing this code: myPage.URL != null ? $pages.find("#myPage").attr("href", myPage.URL.Url) : $pages.find("#myPage").attr("href", "#") ; Where myPage object contains an object called URL 2 properties: Url and Description. If URL is not null, then for sure it will have a Url value. After running this code, I try to click on the link, but it's giving this error: jquery-1.11.3.min.js:2 Uncaught Error: Syntax error, unrecognized expression: http://yourlink.com(…) Here's myPage object structure: pageType : "publishing", pageCategory: null Steps : null pageOwner: null audience: "All" audienceDescription: "description goes here for the audience" Title : "my page title" URL : Object > Description "any link goes here" > Url "http://google.com" What am I doing wrong? Thanks. A: You need also to check if your object myPage.URL has the property Url then assign it : if( myPage.URL != null ) if( myPage.URL.hasOwnProperty("Url") ) $pages.find("#myPage").attr("href", myPage.URL.Url); else $pages.find("#myPage").attr("href", "#") Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/41045382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Populate second dropdown based on first dropdown using CodeIgniter I need to select first the source_type and then it automatically populate the location based on the source_type view file <select name="source_type" id="source_type"> <option value="">Source Type</option> <option value="Internal">Internal</option> <option value="External">External</option> </select> <select name="location" id="location"> <option value="">Select</option> </select> $('#source_type').change(function(){ $.ajax({ type: 'post', data: 'source_type'+$(this).val(), url: 'get_sources_location', success: function(data) { $('#source_location').val(data); } }); }); ..controller public function get_sources_location() { $source_type = $this->input->post('source_type'); $this->load->model('documents_model'); $results = $this->documents_model->get_locations(); echo $results; } ..model public function get_locations() { $query = $this ->db ->select('location') ->where('classification', $source_type = $this->input->post('source_type')) ->get('sources_location'); $data = array(); foreach ($query->result() as $row) { $data = $row->location; } return $data; } A: try something like this HTML CODE <select name="source_type" id="source_type" onchange="populateLocation(this.value)"> <option value="">Source Type</option> <option value="Internal">Internal</option> <option value="External">External</option> </select> <select name="location" id="location"> <option value="">Select</option> </select> JAVASCRIPT CODE USING JQUERY function populateLocation(source_type_value){ if(source_type_value !=''){ /* Pass your source type value to controller function which will return you json for your loaction dropdown */ var url = 'controller/function/'+ source_type_value; // $.get(url, function(data) { var $select = $('location'); // removing all previously filled option $select.empty(); for (var propt in data) { $select.append($('<option />', { value: propt, text: data[propt] })); } } } JSON FORMAT to be returned from controller {"":"Select","1":"New york","2":"London","3":"Mumbai"} A: Put an AJAX Function like this, $("#source_type").change(function(){ $.ajax({ type : 'POST', data : 'source_id='+ $(this).val(), url : 'controller/method', success : function(data){ $('#location').val(data); } }); }); In controller, put a method to get the values, public function getLocations() { $source_id = $this->input->post('source_id'); // Call the model function and get all the locations based on the source type id // Populate the dropdown options here echo $result; } A: attach a change event handler to your first DD and send an ajax call to the server to fetch data. In the success callback of the ajax call populate the second DD. Below is a simple proof of concept $("#source_type").change(function(e) { $.ajax({ url:'/echo/json', success:function(data){ console.log("success"); $("<option/>",{text:'google',value:'google'}).appendTo("#location"); } }); DEMO
{ "language": "en", "url": "https://stackoverflow.com/questions/15061348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Will I get a postback each month when using subscriptions? I am using Google Wallet For Digital Goods. Will I get a callback each month when money gets transferred or will the postback URL only get called once when setting up the subscription? A: I'm afraid at this very moment Google Wallet only notifies the user when the subscription is cancelled. I asked the same myself on google wallet for digital goods forum : https://groups.google.com/forum/?fromgroups=#!topic/in-app-payments/YFaCBDwaF9g See the 2nd answer from Mihai Ionescu from Google EDIT: As suggested by Qix below, I'm quoting the answer given by Google below: * *After the subscription is setup, you will receive a postback only when the subscription is cancelled: https://developers.google.com/in-app-payments/docs/subscriptions#6 *Currently the merchant can cancel or refund a subscription from the Merchant Center. We are working on adding API support for cancellations and refunds. Please note that the forum entry is from late 2012, however as of May 2014 things doesn't seem to have changed much, as Google still postbacks only for Subscription Cancellations
{ "language": "en", "url": "https://stackoverflow.com/questions/14758031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Enctype issue when I try to upload a file with a Coldfusion webservice Can't get to work a Coldfusion webservice that uploads a file in an external server. My application runs in "Server A" and the file repository (external server) is in "Server B" The template (inicio.cfm) which contains the form with the <cfinput type="file"> to select the client's file to be uploaded, is stored in "Server A". This template performs more tasks than just show the upload form. It performs calculations, queries, etc. outside the form's code block. Also, the action page of this form is the template itself (because of my application's needed tasks). The first code line of my form definition is (inside inicio.cfm): <cfform method="post" name="AltaConvocatoria" enctype="multipart/form-data"> Which demonstrate that I'm using the right enctype definition. In the other hand, stored in "Server B" is my Coldfusion component or webservice (alta_ga.cfc) which only task is to upload the file selected by user in "inicio.cfm" form and rename it. Here's alta_ga.cfc code: <cfcomponent> <cffunction access="remote" returntype="void" name="cargaAnuncio"> <cfargument name="destinoAnuncio" required="yes" type="string"> <cfargument name="PrefijoNvoNombre" required="yes" type="string"> <cffile action="upload" fileField="str_ArchivoAnuncio" destination="#destinoAnuncio#" nameconflict="Overwrite"> <cfset NvoNomAnuncio = #PrefijoNvoNombre# & #Right(cffile.ClientFile, 5)#> <cfset viejoNombre1 = #destinoAnuncio# & #cffile.ClientFile#> <cffile action = "rename" destination = "#NvoNomAnuncio#" source = "#viejoNombre1#"> </cffunction> </cfcomponent> For that pupose, I invoke the webservice from the form's action code block in inicio.cfm with this: <cfinvoke webservice="http://192.168.208.128/podi/mgmt/alta_ga.cfc?wsdl" method="cargaAnuncio" > <cfinvokeargument name="destinoAnuncio" value="#form.destinoAnuncio#" /> <cfinvokeargument name="PrefijoNvoNombre" value="#form.PrefijoNvoNombre#" /> </cfinvoke> When I try to load a file using my form's template inicio.cfm I get this message: Cannot perform web service invocation cargaAnuncio. The fault returned when invoking the web service operation is: '' podi.mgmt.PodiMgmtAlta_gaCfcCFCInvocationExceptionException: coldfusion.tagext.io.FileUtils$CFFileNonMultipartException : Invalid content type: application/soap+xml; charset=UTF-8; action="urn:cargaAnuncio".The files upload action requires forms to use enctype="multipart/form-data".] All the arguments and variables that I'm using are correct, because I tested the webservice as a local component (stored in Server A and uploading the file in the same server) and worked fine. Here's the code of the succesful test (invoked as a component instead of a webservice): <cfinvoke component="alta_ga" method="cargaAnuncio" destinoAnuncio="#form.destinoAnuncio#" PrefijoNvoNombre="#form.PrefijoNvoNombre#"> ¿What could be wrong? There's a lack of documentation about this functionality. Adobe's user guide doesn't explain this functionality in depht. Ben Forta's books... same. Or I couldn't find the information. Thanks in advance. A: When a form is posted to a CFML server, the posted file is saved in a temporary directory before any of your code runs. All <cffile action="upload"> does is to copy a file from that temporary directory to the location you want it to be. Your remote server ServerB has no idea about any file posted on ServerA, so <cffile action="upload"> will not help you. The action is misleading. It's not upload-ing anything. It's just copying from a predetermined temp directory. The web server handles the uploading before the CF server is even involved. You will likely need to <cffile action="upload"> on ServerA to a specific place, and then it needs to post that file to your web service on ServerB. Then ServerB should be able to use <cffile action="upload"> to transfer it from the upload temp directory to wherever you need it to be. That said I have never tried this when posting to a web service. Alternatively you could just post the file directly to ServerB in the first place, to save needing ServerA to be an intermediary. This might not be possible, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/67544009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to update a table using cursor I need to write a procedure to update a column of a table Xyz if today date is between the start_date and end_date of table ABC. table ABC fin_cycle start_date end_date account_class ---------------------------------------------------- F2018 27-05-2020 29-05-20 2003 table xyz account_no account_class ac_no_dr 1234 2003 Y when I run the procedure today and if today's date is between start_date and end date of table ABC then the procedure will update column ac_no_dr as Y, else it will update the column as N. I have prepared this skeleton. Create Or Replace PROCEDURE pr_no_debit Cursor c_Today(start_date, end_Date) is Select Today from sttm_branch where today between start_Date and end_Date; l_No_Debit_List ABC%ROW_TYPE; Begin For c_Today(l_No_Debit_List.start_Date,l_No_Debit_List.end_Date) Loop Update XYZ set ac_no_DR='Y' where account_class=l_No_Debit_List.account_class; End Loop; -- At the end of the period Change No_Debit to 'N' End pr_no_debit; A: Here's one option: merge. (Today is 27.05.2020 which is between start and end date stored in the abc table). Sample data: SQL> select * From abc; FIN_C START_DATE END_DATE ACCOUNT_CLASS ----- ---------- ---------- ------------- F2018 27.05.2020 29.05.2020 2003 SQL> select * From xyz; ACCOUNT_NO ACCOUNT_CLASS A ---------- ------------- - 1234 2003 Merge statement: SQL> merge into xyz a 2 using (select account_class, 3 case when sysdate between start_date and end_date then 'Y' 4 else 'N' 5 end ac_no_dr 6 from abc 7 ) x 8 on (a.account_class = x.account_class) 9 when matched then update set a.ac_no_dr = x.ac_no_dr; 1 row merged. Result: SQL> select * From xyz; ACCOUNT_NO ACCOUNT_CLASS A ---------- ------------- - 1234 2003 Y SQL> The bottom line: you don't need a procedure nor a loop (which is inefficient) as everything can be done with a single SQL statement. If - as you commented - has to be a procedure, no problem either: create or replace procedure p_merge as begin merge into xyz a using (select account_class, case when sysdate between start_date and end_date then 'Y' else 'N' end ac_no_dr from abc ) x on (a.account_class = x.account_class) when matched then update set a.ac_no_dr = x.ac_no_dr; end; /
{ "language": "en", "url": "https://stackoverflow.com/questions/62049450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you view HTML entities in Firefox Developer Edition's inspector Firefox Developer Edition was showing HTML entities (e.g.  ) in the DOM inspector. For some reason it stopped. I've created a fresh Firefox profile but I still can't see them. Anyone got any ideas how to view them in Firefox? A: @luke-h I'm fairly certain it makes sense to piggyback https://bugzilla.mozilla.org/show_bug.cgi?id=1256756 I just did.
{ "language": "en", "url": "https://stackoverflow.com/questions/31713076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is binding events in jQuery very expensive, or very inexpensive? I just wrote a $().bind('event') function and then got concerned that this kind of a call might be very expensive if jQuery has to run through each element in the DOM to bind this event. Or maybe, it's just about as efficient as an event could be. The jQuery docs I've read aren't making this clear. Any opinions? A: There are two things that can make your event binding code slow: the selector and the # of bindings. The most critical of the two is the # of bindings, but the selector could impact your initial performance. As far as selectors go, just make sure you don't use pure class name selectors like .myclass. If you know that the class of myclass will always be in a <div> element, make your selector be div.myclass as it will help jQuery find the matching elements faster. Also, don't take advantange of jQuery letting you give it huge selector strings. Everything it can do with string selectors it can also do through functions, and this is intentional, as it is (marginally, admittedly) faster to do it this way as jQuery doesn't have to sit around to parse your string to figure out what you want. So instead of doing $('#myform input:eq(2)'); you might do $('input','#myform').eq(2);. By specifying a context, we are also not making jQuery look anywhere it doesn't have to, which is much faster. More on this here. As far as the amount of bindings: if you have a relatively medium-sized amount of elements then you should be fine - anything up to 200, 300 potential element matches will perform fine in modern browsers. If you have more than this you might want to instead look into Event Delegation. What is Event Delegation? Essentially, when you run code like this: $('div.test').click(function() { doSomething($(this)); }); jQuery is doing something like this behind the scenes (binding an event for each matched element): $('div.test').each(function() { this.addEventListener('click', function() { doSomething(this); }, false); }); This can get inefficient if you have a large amount of elements. With event delegation, you can cut down the amount of bindings done down to one. But how? The event object has a target property that lets you know what element the event acted on. So you could then do something like this: $(document).click(function(e) { var $target = $(e.target); if($target.is('div.test')) { // the element clicked on is a DIV // with a class of test doSomething($target); } }); Thankfully you don't actually have to code the above with jQuery. The live function, which is advertised as an easy way to bind events to elements that do not yet exist, is actually able to do this by using event delegation and checking at the time an action occurs if the target matches the selector you specify to it. This has the side effect, of course, of being very handy when speed is important. The moral of the story? If you are concerned about the amount of bindings your script has just replace .bind with .live and make sure you have smart selectors. Do note, however, that not all events are supported by .live. If you need something not supported by it, you can check out the livequery plugin, which is live on steroids. A: Basically, you're not going to do any better. All it is doing is calling attachEventListener() on each of your selected elements. On parse time alone, this method is probably quicker than setting inlined event handlers on each element. Generally, I would consider this to be a very inexpensive operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/905883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Is there a function to select a group of hours from different days? I'm looking for a way to select in Amazon Athena a selection of hours for different days. I have a table with visitors to a specific location for every half hour, I now want to know the visitors during opening hours for a store, for the period of a month. I now used this but doing it day by day is quite a job. Was trying to split datetime with Datepart but didn't get it working properly. SELECT visitors, datetime FROM corrected_scanners_per_half_hour WHERE datetime BETWEEN CAST('2020-05-25 08:30:00' AS timestamp) AND CAST('2020-05-25 17:30:00' AS timestamp) ; A: Here you go select visitors, date(datetime) from corrected_scanners_per_half_hour where date_format(datetime, '%H:%i') between '08:30' and '17:30'
{ "language": "en", "url": "https://stackoverflow.com/questions/63050452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding CURL as static library to a C++ CMake project I have a problem with adding CURL library to CMake project. In my CMakeList.txt I have the following lines for adding CURL: #option(CURL_STATICLIB "Set to ON to build libcurl with static linking." ON) if(WIN32) add_definitions("-DCURL_STATICLIB") endif() option(LIBCURL_ENABLE "Enable or disable the requirement of libcurl" ON) if(LIBCURL_ENABLE) find_path(LCURL_INCLUDE_DIR NAMES curl.h PATHS /usr/include/curl ENV "PROGRAMFILES(X86)" ENV "LIBCURL_ROOT" PATH_SUFFIXES include) find_library(LCURL NAMES libcurl.a libcurl.lib PATHS /usr/lib/x86_64-linux-gnu /usr PATH_SUFFIXES lib lib/x86_64-linux-gnu) if(LCURL STREQUAL "LCURL-NOTFOUND") message(FATAL_ERROR "libcurl NOT found: use `-DLIBCURL_ENABLE=OFF` to build without libcurl support") else() set(LIBS ${LIBS} ${LCURL}) include_directories(AFTER ${LCURL_INCLUDE_DIR}) endif() else() add_definitions("-DCONF_NO_LIBCURL") endif() ... if(LIBCURL_ENABLE) target_link_libraries(app ${ZLIB_LIBRARIES} ${LCURL}) endif() Everything is okay on Windows. But on Linux, I got this message from the make install command: /usr/bin/ld: /usr/lib/x86_64-linux-gnu/libcurl.a(libcurl_la-content_encoding.o): undefined reference to symbol 'inflateInit2_' /usr/lib/x86_64-linux-gnu/libz.so: error adding symbols: DSO missing from command line A: The compilation was resolved with the following replacement. #option(CURL_STATICLIB "Set to ON to build libcurl with static linking." ON) if(WIN32) add_definitions("-DCURL_STATICLIB") endif() set(CURL_LIBRARY "-lcurl") find_package(CURL REQUIRED) include_directories(${CURL_INCLUDE_DIR}) if(LIBCURL_ENABLE) target_link_libraries(app ${CURL_LIBRARIES}) endif()
{ "language": "en", "url": "https://stackoverflow.com/questions/50783730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert string date to Datetime C# How can I convert 1-2-2016 to Datetime format dd-MMM-yyyy For Example : The output of 1-2-2016 should be 1-Feb-2016 I've tried the following code but it's returing 2-Jan-2016. Updated_Value = Convert.ToDateTime(Updated_Value).ToString("dd-MMM-yyyy"); The Data in Update_Value variable is coming from database whose datatype is varchar. Kindly Help me to resolve this . Thanks in advance . A: Try this: DateTime dt; DateTime.TryParseExact(Updated_Value, "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); var newdate = dt.ToString("d-MMM-yyyy");
{ "language": "en", "url": "https://stackoverflow.com/questions/39160102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visitor pattern. Is void* an acceptable return type for a completely abstract interface? I have an AST, represented in the usual way (a tree of nodes of an abstract type). I have several uses cases for traversing this tree (an optimizer, which returns another AST; IR code generation, which returns a llvm::Value*; and a debug analyzer, which simply outputs to stdout and returns nothing). A visitor feels like the right way to go here, but the differing return types through each use case of the visitor make it hard to see how to implement an interface for this. I considered this: class Visitor; class ASTNode { public: virtual void accept(Visitor *visitor); }; class Visitor { public: virtual void visit(CallNode *node) = 0; virtual void visit(BinExprNode *node) = 0; // etc }; Because of the lack of return value, each Visitor implementation would need to build up internal state and provide a result() method with a suitable return type. That is complex, however, since each call to visit() needs some context around the expression being visited (i.e. the call standing alone, or is it being used as part of a binary expression?). It makes it tricky for things like binary expression code generation to collect return values from visiting the nodes of the operands (I could do it with an internal temporary state variable or some such, but it feels over-engineered) and hard to reason about (the state keeps changing). class OptimizingVisitor : public Visitor { ASTNode *m_result; public: ASTNode *result() { return m_result; } void setResult(ASTNode *node) { m_result = node; } void visit(CallNode *node) { node->left()->accept(this); ASTNode *optimizedL = result(); node->right()->accept(this); ASTNode *optimizedR = result(); setResult(new CallNode(optimizedL, optimizedR)); } // ... snip ... }; I could make it even more complex to avoid the "state keeps changing" issue by passing in a new visitor for each node. It just feels like this problem warrants a more functional solution. Really, I'd like to write the above much more simply and easier to read: class OptimizingVisitor : public Visitor { public: ASTNode* visit(CallNode *node) { ASTNode *optimizedL = node->left()->accept(this); ASTNode *optimizedR = node->right()->accept(this); return new CallNode(optimizedL, optimizedR); } // ... snip ... }; Of course now I've changed the return type, so it doesn't fit my Visitor contract. Far from defining completely separate interfaces for each possible implementation of a a Visitor and making the AST aware of those visitor types, it seems the only really logical thing to use is a void*. Does this sort of API warrant the use of void*? Is there a better way to do this? A: If I get this right, I might have something useful. Referring to your sample at https://gist.github.com/d11wtq/9575063, you cannot have class ASTNode { public: template <class T> virtual T accept(Visitor<T> *visitor); }; because there are no template virtual functions. However, you may have a generic class template <class D, class T> struct host { virtual T accept(Visitor<T> * visitor); // I guess, { return visitor->visit(static_cast <D*>(this)); } }; and a collection template <class D, class... T> struct hosts : host <D, T>... { }; so that, when the set of possible return types is limited, you can say e.g. class ASTNode : public hosts <ASTNode, T1, T2, T3> { public: // ... }; Now you have three different Visitor contracts of return types T1,T2,T3. A: Maybe this is helpful. Using return type covariance to make accept() calls type-safe: class Visitor; class ASTNode { public: virtual ASTNode* accept(Visitor* visitor); }; class CallNode; class BinaryExpressionNode; class Visitor { public: virtual CallNode* visit(CallNode* node) = 0; virtual BinaryExpressionNode* visit(BinaryExpressionNode* node) = 0; }; Implementations: class CallNode : public ASTNode { public: CallNode(BinaryExpressionNode* left, BinaryExpressionNode* right); // return type covariance CallNode* accept(Visitor* visitor) override { return visitor->visit(this); } BinaryExpressionNode* left(); BinaryExpressionNode* right(); }; class BinaryExpressionNode : public ASTNode { public: BinaryExpressionNode* accept(Visitor* visitor) override { return visitor->visit(this); } } class OptimizingVisitor : public Visitor { public: CallNode* visit(CallNode* node) override { // return type covariance will make this operation type-safe: BinaryExpressionNode* left = node->left()->accept(this); auto right = node->right()->accept(this); return new CallNode(left, right); } BinaryExpressionNode* visit(BinaryExpressionNode* node) override { return new BinaryExpressionNode(node); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/22430211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Intellij Accessing file from hadoop cluster As part of my intellij environment set up I need to connect to a remote hadoop cluster and access the files in my local spark code. Is there any way to connect to hadoop remote environment without creating hadoop local instance? A connection code snippet would be the ideal answer. A: If you have a keytab file to authenticate to the cluster, this is one way I've done it: val conf: Configuration: = new Configuration() conf.set("hadoop.security.authentication", "Kerberos") UserGroupInformation.setConfiguration(conf) UserGroupInformation.loginUserFromKeytab("user-name", "path/to/keytab/on/local/machine") FileSystem.get(conf) I believe to do this, you might also need some configuration xml docs. Namely core-site.xml, hdfs-site.xml, and mapred-site.xml. These are somewhere usually under /etc/hadoop/conf/. You would put those under a directory in your program and mark it as Resources directory in IntelliJ.
{ "language": "en", "url": "https://stackoverflow.com/questions/43791120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery loading other html pages, but how to revert to original content So i have done this small piece of jQuery code to load html files into a DIV but I'm struggling to work out how i can for example place a back button on the loaded content and once clicked will revert to the original content any ideas? Ideally i would like to use a ajax effect when loading the content with a throbber but reading up online loasd is the best way? $('.load-page').on("click", function() { var href = $(this).attr("href"); $('#in-the-news').load(href); return false }); link: <a href="/page-to-load-into-div" class="load-page">link</a> html: <div id="in-the-news"> <p>original content</p> </div> A: You have to cache the original content into another object when the user presses the link, and then take it back when the user press the original link. somethin like this (untested) $('.load-page').on("click", function() { var href = $(this).attr("href"); if ($('#hidden-cache').html() == ''){ $('#hidden-cache').html($('#in-the-news').html()); } $('#in-the-news').load(href); return false }); $('.original-page').on("click", function() { $('#in-the-news').html($('#hidden-cache').html()); return false }); <div id="in-the-news" class="original-page"> <p>original content</p> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/25207106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AEM: How common component injected in multiple components can have dynamic value I have a common component which is injected in multiple components via data-sly-resource. componentA <div data-sly-resource="${ 'abc' @ resourceType = 'btplayer-cms/components/content/some-common-component' }"> </div> componentB <div data-sly-resource="${ 'xyz' @ resourceType = 'btplayer-cms/components/content/some-common-component' }"> </div> In some-common-component.html a "class" need to be added to the div which will be dynamic and specific to the component it is injected from. For example, when this component is added in componentA the html wuld be: <div class="componenta-button"></div> and when added in componentB it would be <div class="componentb-button"></div> How can I achieve this? How would I know who is injecting this component or it possible to send extra parameters from the parent component which I can access from some-common-component.html A: For this use case it’s probably best to use HTL templates: <sly data-sly-use.common="common.html" data-sly-call="${common.myTemplate @ buttonClass='myClassA'}"></sly> A: You can make use of requestAttributes (refer here) Component A (passing the value): Sightly : <sly data-sly-use.compA = "com.mysite.core.models.CompA"/> <div data-sly-resource="${ 'abc' @ resourceType = 'btplayer-cms/components/content/some-common-component', requestAttributes = compA.attribute }"> </div> Sling Model : package com.realogy.sir.core.models; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.models.annotations.Model; @Model(adaptables = SlingHttpServletRequest.class) public class CompA { public Map<String, Object> attribute = new HashMap<>(); @PostConstruct protected void init() { attribute.put("attributeVal", "componenta"); } } Component B (passing the value): Sightly : <sly data-sly-use.compB = "com.mysite.core.models.CompB"/> <div data-sly-resource="${ 'xyz' @ resourceType = 'btplayer-cms/components/content/some-common-component', requestAttributes = compB.attribute }"> </div> Sling Model : package com.realogy.sir.core.models; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.models.annotations.Model; @Model(adaptables = SlingHttpServletRequest.class) public class CompB { public Map<String, Object> attribute = new HashMap<>(); @PostConstruct protected void init() { attribute.put("attributeVal", "componentb"); } } Common Component (consuming the value): Sightly : <sly data-sly-use.commonComp= "com.mysite.core.models.CommonComp"/> <div class="${[commonComp.attributeVal, 'button'] @ join='-'}"></div> Sling Model: package com.mysite.core.models; import javax.inject.Inject; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.models.annotations.Model; @Model(adaptables = SlingHttpServletRequest.class) public class CommonComp { @Inject @Optional @Default(values="component") private String attributeVal; public String getAttributeVal() { return attributeVal; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/63980155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reset a variable after 3 seconds in Android? I am trying to create a Service. In this Service I ahve this variable: String command="Go" I want to design a function that does this: Within 3 seconds, the command will return value "Go" If the time is bigger than 3 seconds, the command will be reset to "". My current solution is using a Thread. Do you think it is a safe and good solution? public String command; public String getValue(){ command="GO"; try { Thread.sleep(3000); command=""; } catch (InterruptedException e) { e.printStackTrace(); } return command; } A: As you are doing it at MainThread the app will not response to user and it's the worst thing can happen! I suggest you to use RXJava and be aware of blocking UI Thread! Observable.just(comment) .delay(3, TimeUnit.SECONDS) /*for doing at background*/ .subscribeOn(Schedulers.io()) /*for responsing at maint thread*/ .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<String>() { @Override public void call(String s) { comment = ""; // and other stuffs you wand after resetting the val } }); A: A good approach(based on you having a thread already) would be this: long elapsed = (System.nanoTime()-startTime)/1000000; if(elapsed>3000) { //reset your variable //Allow this to repeat: startTime = System.nanoTime(); } In order to initialize, do startTime = System.nanoTime(); where you would initialize the activity. Now this method has a big drawback: You have to use it with a thread. It cannot be used alone as a listener if you want it to update after 3 seconds and not after 3 seconds on a button press. Using a thread is a good idea if you want something done repeatedly, but beware of background memory hogging. You may want to create an async thread A: A better approach would be to use handlers and postDelayed instead of Thread.sleep(). postDelayed puts the Runnable in the handler thread's message queue. The message queue is processed when control returns to the thread's Looper. Thread.sleep() blocks the thread. final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Do stuff every 3000 ms handler.postDelayed(this, 3000); } }, 1500);
{ "language": "en", "url": "https://stackoverflow.com/questions/40189075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Wix Burn bootstrapper doesn't detect MSI install state I'm creating a custom wizard-style bootstrapper based on Wix/Burn (3.6 release version). I've based in on the Wix 3.6 bootstrapper code. The problem is that I cannot get the bootstrapper to detect the install state of my setup.msi that is part of the bundle. As I understand it, all that's required is to call Engine.Detect(), where Engine is an instance of the Wix Engine from the Bootstrapper Application. At that point I should be able to look in Bootstrapper.Command.Action to see what the required launch action is. My bundle contains two items: .NET 4 (web install) and my setup.msi. I suspect that I'm missing a step to determine whether I should put my wizard into maintenance mode vs. install mode. A: First, to determine if the package is being detected or not you can check the log files in the temp directory of the current user. It will tell you whether or not the package has been detected. Now to determine whether or not to go into maintenance mode vs. install mode, you can check the package state by subscribing to the DetectPackageComplete event. In the example below, my UI uses two properties, InstallEnabled and UninstallEnabled to determine what "mode" to present to the user. private void OnDetectPackageComplete(object sender, DetectPackageCompleteEventArgs e) { if (e.PackageId == "DummyInstallationPackageId") { if (e.State == PackageState.Absent) InstallEnabled = true; else if (e.State == PackageState.Present) UninstallEnabled = true; } } The code sample above is from my blog post on the minimum pieces needed to create a Custom WiX Managed Bootstrapper Application. A: An easy way to determine if your Bundle is already installed is to use the WixBundleInstalled variable. That will be set to non-zero after your Bundle is successfully installed. Additionally, in WiX v3.7+ the OnDetectBegin callback now tells you if the bundle is installed so you don't have to query the variable normally. These changes were made to make it easier to detect maintenance mode to avoid the completely reasonable solution that @BryanJ suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/14238488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Plotting population density map in R with geom_point I'm working on a simple population density plot of Canada. I have data for population based on postal code and latitude/longitude here I want to improve the plot to show color change as the density of points increases. This is the code I have: library(maptools) library(gdata) library(RColorBrewer) library(classInt) library(maps) library(ggplot2) library(ggmap) Canada <- get_map(location="Canada", zoom=3, maptype="terrain") ggmap(Canada, extent="normal") + geom_point(data=PopDensity, aes(x=LONG,y=LAT,size=POPULATION), alpha = 0.3)+scale_size_continuous(range=c(1,6)) which produces a plot like What I'd really like is a way to keep the data points the same size, but instead of making the points transparent, changing the color as a function of point density. A: You have to calculate the densities first, then assign the values to the points so you can map that aesthetic: library(ggplot2) library(ggthemes) library(scales) library(ggmap) library(MASS) library(sp) library(viridis) pop <- read.csv("~/Dropbox/PopulationDensity.csv", header=TRUE, stringsAsFactors=FALSE) # get density polygons dens <- contourLines( kde2d(pop$LONG, pop$LAT, lims=c(expand_range(range(pop$LONG), add=0.5), expand_range(range(pop$LAT), add=0.5)))) # this will be the color aesthetic mapping pop$Density <- 0 # density levels go from lowest to highest, so iterate over the # list of polygons (which are in level order), figure out which # points are in that polygon and assign the level to them for (i in 1:length(dens)) { tmp <- point.in.polygon(pop$LONG, pop$LAT, dens[[i]]$x, dens[[i]]$y) pop$Density[which(tmp==1)] <- dens[[i]]$level } Canada <- get_map(location="Canada", zoom=3, maptype="terrain") gg <- ggmap(Canada, extent="normal") gg <- gg + geom_point(data=pop, aes(x=LONG, y=LAT, color=Density)) gg <- gg + scale_color_viridis() gg <- gg + theme_map() gg <- gg + theme(legend.position="none") gg
{ "language": "en", "url": "https://stackoverflow.com/questions/32622174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to open a file and remove certain characters based on args passed from command line So I have a function which will essentially run and generate a report and save it with args.current_date filename. The issue I am having is to remove the extension .json from the filename being saved which really is not readable. Since I am passing dict as args, I cannot use the strip() method in order to do this. So far my function is follows : parser = argparse.ArgumentParser() parser.add_argument("-c", "--current-date", action="store", required=False) parser.add_argument("-p", "--previous-date", action="store", required=False) args = parser.parse_args() def custom_report(file_names, previous_data , current_data): reporting = open('reports/' + args.current_date+ "-report.txt", "w") reporting.write("This is the comparison report between the directories" " " + args.current_date + " " "and" " " + args.previous_date + "\n\n") for item in file_names: reporting.write(item + compare(previous_data.get(item), current_data.get(item)) + "\n") reporting.close() It has saved the file as '2019-01-13.json-report.txt'. I want to be able to get rid of the '.json' aspect and leave it as '2019-01-13-report.txt' A: To remove a file name extension, you can use os.path.splitext function: >>> import os >>> name = '2019-01-13.json' >>> os.path.splitext(name) ('2019-01-13', '.json') >>> os.path.splitext(name)[0] '2019-01-13'
{ "language": "en", "url": "https://stackoverflow.com/questions/54278087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SCM choice for a new user? Real easy one here guys. Best justification gets the win. I'm a computer science student at a school you've heard of, and have been programming for several years now (about 8), so I've written a fair few lines of code. But since I've never really been distributing - source or binaries - nor doing team developing (though I'm sure I will!), I've never needed to learn source code management systems. I have a tremendously boring hierarchy of folders along the lines of src/project_name or src/class_code/hw_or_project_name and if I need to send the code to a friend or for grading, it's just a tarball away. A few things have changed in recent years, as my projects have gotten bigger. My Mac, with Time Machine, now does hourly backups - this has saved me a fair few times, most recently when I made major changes over SSH... then saved and closed the stale copy in my editor a few hours later. But, out of a sort of professional interest - along with an overwhelming sense that it could be useful - I've decided to learn SCMS. Now, I have plenty of experience as a source code 'consumer' - git clone, svn checkout, cvs co, that sort of thing - but none as a maintainer, committer, or updater. My question to you is: what should I learn? Now, a bunch of you are screaming "why one? you'll use many!" but I'd like to learn the basics of SCM, and get in the habits of actually using it, on the most straightforward system. There are a number of concepts I'd do well to internalize - branches, tags, merging, collaboration, etc - before I really need them. To be clear, I'm no Linus Torvalds. I will be mantaining one, or perhaps a few branches. On my dozens of files, I don't mind if some operations take a few hundred ms more on one system than on others. Now what do I have? I do have a webhost. They offer Subversion hosting a click away, or I could store other repositories there no problem. For reasons I can't explain, I'm rather partial to Subversion. But that's exactly why I'm reluctant to just jump in. I know Mercurial, Git, and so forth are the hot new things, being distributed, but I'm not sure why this is a benefit. In fact, I'm not quite sure how it could work. So, what should I start with? Subversion or Git? Mercurial or CVS? Visual Source Safe or Perforce? (that last pair was a joke) And why one over the other? Thanks for your time, and if this in the wrong section I apologize. EDIT Thanks all! I appreciate your comments. Given the choice between Git and Hg, I'd probably go with Git - any disagreement? Second, why not Subversion? It seems to be the consensus (not just here) that it's old or otherwise obsolete. Why's that? EDIT 2 So after reading all the responses and doing some more reading, I've decided to go with Git. "Answer" goes to the best justification, as stated above. Git seems to be more popular than Mercurial, even if it is a bit less clean. I'm pushing changes to my webserver, where I have viewgit installed, and it's working great. The impetus for storing a copy on my webserver is that I'd like to be working from several of my machines, and I expect them to get out of sync. I also expect to have the several working copies out of sync with each other and my server, and I now understand that Subversion is pretty weak at that. There's a lot I'm still trying to work out, but I've got it set up now so that I can pull/clone from http and push over ssh (next step is to set up Gitosis). To a newbie looking to do what I'm doing - you'll find that your "push" commands will work the first time, but any "cloned" copies won't track the changes you make. Git considers this a safety feature... I only slightly understand why, but it has to do with merging. The trick is to use this post-update hook on the server to merge the newly-pushed copy into the server's working copy. A: The Mercurial over subversion case is pretty convincingly made in the first section at http://hginit.com/ Git and Mercurial can each read and write one another's repos over the wire now, so it really comes down to whichever interface you prefer. A: One thing's for sure, don't start with CVS. A: I've been using Mercurial and enjoy it very much. You can get a free Bitbucket account and start storing your repos in the cloud. It's also being used on some codeplex projects if you ever have the desire/opportunity to work on an OSS project that's on codeplex. The basic gist I have found/heard is Mercurial is a little easier to work with but not as powerful as Git. However, both are excellent choices. There's a really good free video on tekpub for Mercurial and Codeplex. It takes you through all the basics. As already mentioned the http://hginit.com link is another good resource. It's also made by the same team who made FogBugz & Kiln. Kiln is an integrated environment for Mercurial and FogBugz with extras like code review. I was using SVN on my local box to store my personal work but no more. With Bitbucket & Mercurial I won't have to worry about my local box dying and making sure I had everything backed up.... Bottom line is you can't go wrong with either Hg or Git but I would go with Hg unless you needed some of the advanced features which sounds like you don't. Learning SVN isn't necessarily bad as there are a lot of Organizations using it but I would really concentrate on Distributed VCS instead. They really are the future. :-) A: Given the choice between Git and Hg, I'd probably go with Git - any disagreement? Warning, I'm a mercurial fanboy. Git is not bad, but it has some quirks you have to know when you use it: * *You can push into a non-bare git repo, but this will screw up the working copy there (It moves the branch HEAD to the pushed revision, but does not update the working copy. When you are not aware of this push, the next commit will undo the changes which were pushed into the repo, mixed with the changes you just introduced.). In hg a push to a non-bare repo just add the new history to the repo, and you get a new head on your next commit, which you then can merge with the pushed head. *You can't easily switch between a bare and a non-bare repo (you can make a hg repo bare with hg up -r null, and get a working copy with hg up [some-revision] from a bare one). *When you check out an older revision by a tag, remote branch name or commit-hash you get a detached head (I really like the title of that question). This means commits there are on no branch, and can get removed by the garbage collector. In hg a commit on an old state create a permanently stored anonymous head (You get a warning on the commit). *When you come from SVN you have to know that git revert and svn revert do completely different things. *Git has all features enabled, also the ones which can cause data loss (rebase, reset). In hg these features are there, but must be enabled prior use. *git tag makes local tags by default, when you want a globally visible tag you need git tag -a or git tag -s. On the opposite hg tag creates a global visible tag, local tags are created with hg tag -l. Some things many don't like about mercurial: * *Branches are stored permanent in the project history, for git-like local branches bookmarks can be used *There are no git-like remote tracking branches (although bookmarks can be shared, and recently there's been work on them to work more like git's branch labels) *Creating a tag creates a new commit in the project history (technically git does it the same way, but is much better at hiding this commit) *You have to enable features that modify history, or are experimental (hg comes pre-packed with many, ... but they are disabled by default). This is why many think that mercurial has less features than git. *There is no git rebase -i equivalent packaged with mercurial, you have to get the third-party histedit extension yourself. Second, why not Subversion? It seems to be the consensus (not just here) that it's old or otherwise obsolete. Why's that? Svn has no clue what a branch or a tag is, it only know copies. Branches and tags are simulated by having the convention that a svn repo contains a trunk/, branches/ and tags/ folder, but for svn they are only folders. Merging was a pain in svn, because older versions (prior svn 1.5) dit not track the merge history. Since svn1.5 subversion can track merge history, but I don't know if the merging part is better now. Another thing is that in svn every file and folder has it's own version number. In git and hg there is one version for the entire directory structure. This means that in svn you can check out an old revision an one file, and svn will say that there are no local changes in your working copy. When you check out an old revision of one file in git or hg, both tools will say your working copy is dirty, because the tree is not equal to their stored tree. With subversion you can get a Frankenstein version of your sources, without even knowing it. A minor nastiness in svn is that it places a .svn folder in every checked out folder (I heard rumors that they want to change this behavior in 1.7), where the clean reference files for the checked out ones live. This makes tools like grep -r foo not only list the real source files, but also files from these .svn folders. Svn has an advantage when you have big or unrelated projects, since you can check out only subtrees of a repository, while in git and hg you can get only the whole tree at once. Also does svn support locking, which is an interesting feature if you have files which can't easily be merged. Keyword substitution is also supported by svn, but I wouldn't call this a feature. A: I'd pick mercurial. * *The set of commands are limited so there's not a lot to remember. *http://www.hginit.com *Mercurial's hg serve command lets you setup a repo server for small operations in 5 seconds. *Cross platform *You can use it locally, without branches and be quite successful until you want to get deeper into the advanced stuff. A: Being a newbie myself , I've used git and found it remarkably easy to use and intuitive, while the others have been a bit too overwhelming.Coupled with GitHub it makes for a wonderful little tool for source control,sharing and backing up code. A: The best open-source choice is GIT. Check Git documentation. you Would also find lots of tutos over internet (youtube, and some developers blogs). A must not do is (start using CVS or Subsversion). Well at least is my personal opinion. A: Use git and github Once upon a time, cvs almost completely replaced its competition and ruled the world of version control. Then it was itself replaced by svn. And now, svn is being replaced by git. Git is more complex than svn, so there might still be reasons to pick svn for a new project. But its days are numbered. Git, Mercurial, and some proprietary systems are clearly the future of the VCS world. Both git and svn can be used in a cvs-like checkout/pull/commit mode, so the bottomless pit of complexity (it's a lifestyle) that is git won't affect you unless you jump in the deep end.
{ "language": "en", "url": "https://stackoverflow.com/questions/4420566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: is it possible to give margin-left css/scss dynamically to its Childs element on the basics of position (nth + 2px) I have a form which show Package Hierarchy, Package Input depend on package type so is it possible to give margin-left dynamically by css/sass to its Childs element on the basics of position enter code here <div class="parent"> <div class="child"> child one </div> <div class="child"> child two </div> </div> <div class="parent"> <div class="child"> child one </div> <div class="child"> child two </div> <div class="child"> child three </div> </div> child may differ by type so feel unsuitable to give static :nth-child() css A: You can do this with sass. You just need to take maximum amount of Childs into $elements. <div class="parent"> <div class="child"> child one </div> <div class="child"> child two </div> <div class="child"> child three </div> </div> <style> $elements: 15; @for $i from 0 to $elements { .parent .child:nth-child(#{$i + 1}){ margin-left: ($i * 2)+px; } } </style>
{ "language": "en", "url": "https://stackoverflow.com/questions/65573239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python recursive function to dump a tree in Excel I have a very simple directed traversal graph structure in a Django models.py file that translates into the following two Python classes : class Node(models.Model): position = models.IntegerField() # from 1 to 3 name = models.CharField(max_length=255) value = models.FloatField(default=0.0) class Edge(models.Model): source = models.ForeignKey("Node", related_name="__to") destination = models.ForeignKey("Node", related_name="__from") weight = models.FloatField(default=0.0) I need to dump the content of that tree into an Excel file. Writing to the Excel document is easy thanks to xlwt - I can write to any cell using a simple write(x, y, content) function - but I what I'm having difficulties with right now is to go through the entire tree (recursively) and fetching each possible path to write in the Excel file. Considering I have 3 nodes (A1, A2, A3) in the first position that are each one linked to one node (B1) in the second position which is finally linked to 1 node (C1) in third position, I would need to go through all possible paths and translate that into the following structure in Excel ( is for your understanding but it's actually a separate cell in Excel) : Node A1 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3 Node A2 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3 Node A3 in position 1 <links to> Node B1 in position 2 <links to> Node C1 in position 3 In the aforementioned example, I have 5 instances of Node, and 5 instances of Edge. In any idea on how I could do that? Thanks! J A: Strictly speaking, this is a directed graph traversal not a directed tree. A simple algorithm, that ignores the edges but based on position, and gives the expect output is: >>> positions = [Node.objects.filter(position=i) for i in range(1,3+1)] >>> import itertools >>> list(itertools.product(positions)) [(<Node: A1>, <Node: B1>, <Node: C1>), (<Node: A2>, <Node: B1>, <Node: C1>), (<Node: A3>, <Node: B1>, <Node: C1>)]
{ "language": "en", "url": "https://stackoverflow.com/questions/21759721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any protocol that all Swift SIMD float types conform to? Most of the Swift SIMD float types have +-*/ operators, so we can just calculator the sum like below: import simd float2(2.0) + float2(2.0) // float2(4.0, 4.0) float4(2.0) + float4(2.0) // float4(4.0, 4.0, 4.0, 4.0) Now, Lets say I have a generic function that takes a pair of float2, float3 or float4 as arguments and returns the sum of them: func calculateSum<T: SomeProtocolCoversThoseFloats>(a: T, b: T) -> { return a + b } Is there any protocol that functions like this "SomeProtocolCoversThoseFloats" or is there any way that I can create such a protocol? A: David is going the right direction, such a protocol doesn't exist (simd is from C and C doesn't have protocols, no surprise), but you can just declare one yourself. To make it so you can use +-*/, you have to add them to the protocol: import simd protocol ArithmeticType { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } extension float4 : ArithmeticType {} extension float3 : ArithmeticType {} extension float2 : ArithmeticType {} func sum<T: ArithmeticType>(a: T, b: T) -> T { return a + b } You can also extend Double, Float, Int, etc. if you need to A: If there isn't (and there doesn't appear to be), it's easy enough to add your own: protocol SimdFloat {} extension float2 : SimdFloat {} extension float3 : SimdFloat {} extension float4 : SimdFloat {} This doesn't really directly solve your problem, however as it doesn't declare that two SimdFloat's implement +.
{ "language": "en", "url": "https://stackoverflow.com/questions/33537666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open simple JQM dialog from codebehind I'm using the dialog script for JQM 1.0 below. It Works fine, but I want to open it from asp.net codebehind on page_load. How could I accomplish that? Something like, but I can't make it work: Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "open", "opendialog", True) // The JS: <script type="text/javascript"> $(document).delegate('#opendialog', 'click', function () { $('<div>').simpledialog2({ mode: 'blank', headerText: 'Some Stuff', headerClose: true, blankContent: "<ul data-role='listview'><li>Some</li><li>List</li><li>Items</li></ul>" + "<a rel='close' data-role='button' href='#'>Close</a>" }) }) </script> <a href="#" id="opendialog" data-role="button">Open Dialog</a> A: Assuming the JavaScript in your example is already in the HTML, in your code behind just use RegisterStartupScript (http://msdn.microsoft.com/en-us/library/bb310408.aspx) to fire the button click: Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder() sb.Append("<script>") sb.Append("$('#opendialog').click();") sb.Append("</script>") If (Not ClientScript.IsStartupScriptRegistered("open")) Then ClientScript.RegisterStartupScript(Me.GetType(), "open", sb.ToString()) End If Here is a discussion onRegisterStartupScript vs RegisterClientScriptBlock: Difference between RegisterStartupScript and RegisterClientScriptBlock?
{ "language": "en", "url": "https://stackoverflow.com/questions/19403541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using MAYA 3D Model in a .Net application If I want to render a 3D model created by Maya and do some animation with it in a .net application what should be my choice of platform - plain WPF or XNA? A: XNA is an interesting platform, but I have noticed it having some performance issues when loading in models. I have not used WPF to do this, but XNA does also require installing of its framework, to run the application. I suggest you avoid it, for the hurdles you must jump to get what you want out of it. DirectX libraries are a good way to accomplish this, there are thousands of examples of this being used out there. Very Good,Good, Ok You can also use a .X exporter for Maya to import your models. Something like this DirectX Maya Exporter
{ "language": "en", "url": "https://stackoverflow.com/questions/3625919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Login script registers in database but I can't login (PHP &MYSQL in easy steps, Mike Mcgrath) The script has 5 pages. Registration, Login, Login tools,Login action and Home. PHPMYADMIN registers the registration form but the login page keeps saying "enter your email" even though it is entered and matching the registered user in the database. Can anyone see what is wrong. This script is copied from the book cited above.(I will post the script for the three function pages) /////////////////////////////////////////login.php (page1)//////////////////////////////////////// if (isset($errors) &&!empty($errors)) { echo'<p id="err_msg">oops! there was a problem:<br>'; foreach ($errors as $msg) { echo"-$msg<br>"; } echo'please try again or <a href="register.php">Register</a></p>'; } ?> <h1>Login</h1> <form action ="login_action.php" method ="POST"> <P> EMAIL ADDRESS:<input type="text" name="email"> </p><p> password<input type="password" name ="pwd"> </p><p> <input type="submit" value ="login"> </p> </form> <?php include ('includes/footer.html');?> //////////////////////////////////login-action.php (page2)///////////////////////////////////// require ('../connect_db.php'); require('login_tools.php'); list($check, $data)= validate($dbc, $_POST['email'] ,$_POST['pass']); if($check) { session_start(); $_SESSION['user_id']=$data['user_id']; $_SESSION['first_name']=$data['first_name']; $_SESSION['last_name']=$data['last_name']; load('home.php'); } else{$errors =$data;} mysqli_close($dbc); } include('login.php'); ?> //////////////////////////////login_tools.php (page3)///////////////////////////////////////// function load($page='login.php') { #statements to be inserted here. $url ='http://' . $_SERVER['HTTP_HOST']. dirname($_SERVER['PHP_SELF']); $url = rtrim($url,'/\\'); $url .= '/'.$page; header("Location:$home.php"); exit(); } function validate($dbc, $email = '', $pwd = '') { #statements to be added here $errors=array(); if(empty($email)) {$errors[] ="Enter your email address";} else { $e = mysqli_real_escape_string($dbc, trim($email));} if (empty($pwd)) { $errors[]= "enter your password.";} else {$p = mysqli_real_escape_string($dbc, trim($pwd));} if (empty($errors)) { $q = "SELECT user_id, first_name, last_name FROM users WHERE email = '$e' AND pass = SHA1('$p')"; $r= mysqli_query($dbc,$q); if(mysqli_num_rows($r) == 1) { $row=mysqli_fetch_array($r,MYSQLI_ASSOC); return array(true,$row); } else {$errors[]='email address and passwprd not found';} } return array(false,$errors); } ?> /////////////////////////////////////////////////////////////////////////////////////////////////
{ "language": "en", "url": "https://stackoverflow.com/questions/21383912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FirebaseApp is not initialized on real devices Please advice, I'm trying to add push notifications in PCL Xamarin.Forms. On emulator Genymotion it's work fine but on real devices i have an error: Default FirebaseApp is not initialized.Make shure to call FirebaseApp.initializeApp(Context) google-services.json is present in Android project with GoogleServicesJson BuildAction My MainActivity: public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { internal static MainActivity Instance { get; private set; } internal static FirebaseInstanceId FirebaseInstance { get; private set; } public static int CurrentUserId { get; set; } protected override async void OnCreate(Bundle bundle) { base.OnCreate(bundle); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; VideoViewRenderer.Init(); global::Xamarin.Forms.Forms.Init(this, bundle); string dbPath = FileAccessHelper.GetLocalFilePath("LocalDataBase.db"); LoadApplication(new App()); Xamarin.Forms.Application.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize); UserDialogs.Init(this); CachedImageRenderer.Init(); //on real devices it return null var app = Firebase.FirebaseApp.InitializeApp(this.ApplicationContext); Instance = this; } A: Problem solved after downgrade NuGet package version Xamarin.Firebase.Messaging and Xamarin.GooglePlayServices.Base to 42.1001.0 A: My solution was the other way round, I did not have Xamarin.Firebase.Messaging installed at first. But after installing it from Nuget, it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/49222799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert faker data via knex I want to insert data via knex using a for look to create an object to insert data. I tried the following: const faker = require('faker'); const dataLength = 10 const obj = [] exports.seed = function (knex, Promise) { // Deletes ALL existing entries return knex('posts').del() .then(function () { //create entries for (var index = 0; index < dataLength; index++) { obj[index] = { title: faker.lorem.sentence(), description: faker.lorem.paragraph(), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), deletedAt: faker.date.recent(), deleted: faker.random.boolean(), tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"]) } knex('posts').insert([, obj[index] ]); } // Inserts seed entries return }); }; My problem is that no data get saved to the db. Any suggestions what I am doing wrong here? A: Your call to knex.insert() returns a promise. You need to include this promise in the promise chain by returning it inside the handler you pass to the then method. By returning a promise inside the then handler, you are effectively telling it to wait for that promise to resolve. Because you are returning nothing (specifically, undefined), your seed function deletes the posts but does not need to know it has to wait for any other operations to finish before completing. In the future, if you had multiple promises to return, you could use Promise.all() to return all of them: exports.seed = function (knex, Promise) { return knex('posts').del() .then(function () { return Promise.all([ knex('bar').insert(), knex('foo').insert(), ]) }) }; Then your promise chain would wait for all the promises inside Promise.all() to resolve before continuing. In this particular case, however, there's no need to call knex.insert() multiple times because it can accept an array of objects instead of a single object: exports.seed = function (knex, Promise) { return knex('posts').del() .then(function () { const posts = [] for (let index = 0; index < dataLength; index++) { posts.push({ title: faker.lorem.sentence(), description: faker.lorem.paragraph(), createdAt: faker.date.recent(), updatedAt: faker.date.recent(), deletedAt: faker.date.recent(), deleted: faker.random.boolean(), tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"]) }) } return knex('posts').insert(posts) }); };
{ "language": "en", "url": "https://stackoverflow.com/questions/46381900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python version shipping with Mac OS X Snow Leopard? I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version") Thanks! A: bot:nasuni jesse$ python Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> Probably the biggest reason I went and upgraded this morning, it's not 2.6.2, but it's close enough. A: Python 2.6.1 (according to the web) Really good to know :) A: http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html A: It ships with both python 2.6.1 and 2.5.4. $ python2.5 Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24) $ python Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) A: You can get an installer for 2.6.2 from python.org, no reason to go without.
{ "language": "en", "url": "https://stackoverflow.com/questions/1347376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Getting 500 | Internal Server Error when using getServerSideProps in NextJS after deploying in Vercel I'm using server rendered pages in NextJS using getServerSideProps. It's in index.js (root page). When I'm making build locally, website working fine. But when i'm hosting this site in Vercel, it's showing 500 | Internal Server error. export async function getServerSideProps(context) { let params = context.query; const job_col = await collection(db, "job_list"); const job_snap = await getDocs(job_col); let jobData = job_snap.docs.map((doc) => ({ ...doc.data(), id: doc.id, })); return { props: { jobs: jobData, params }, }; } A: It's because of the large payload. Move the large payload code portion to the client-side(useEffect) and it will be resolved. A: I had the same issue. But when I changed getserversideprops to getstaticprops it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/72158672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Sheets pivot data with multiple values I'm trying to display sample data as follows. I'm able to do this using pivot tables and multiple values with no problem but would like to find a way using either Query or some other method. This problem was partly solved using the formula below but does not include the 'Other' column. =Index({"",Transpose(Unique(Filter(B2:B,B2:B<>"")));Flatten({Sort(Unique(C2:C)),IFError(Unique(C2:C)/0)}),IFNA(VLookup(Transpose(Unique(Filter(B2:B,B2:B<>"")))&Flatten({Text(Sort(Unique(C2:C)),"hh:mm"),Text(Sort(Unique(C2:C)),"hh:mm")&".1"}),{Flatten({B2:B&Text(C2:C,"hh:mm"),B2:B&Text(C2:C,"hh:mm")&".1"}),Flatten({A2:A,D2:D})},2,0))}) Sample data: Desired result: A: use: =ARRAYFORMULA({"", TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>""))); FLATTEN({SORT(UNIQUE(C2:C)), IFERROR(TEXT(UNIQUE(C2:C), {"@", "@"})/0)}), IFNA(VLOOKUP(TRANSPOSE(UNIQUE(FILTER(B2:B, B2:B<>"")))&FLATTEN({TEXT(SORT(UNIQUE(C2:C)), "hh:mm"), TEXT(SORT(Unique(C2:C)), "hh:mm")&{".1", ".2"}}), {FLATTEN({B2:B&TEXT(C2:C, "hh:mm"), B2:B&TEXT(C2:C, "hh:mm")&{".1", ".2"}}), FLATTEN({A2:A, D2:D, E2:E})}, 2, ))})
{ "language": "en", "url": "https://stackoverflow.com/questions/71079986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: phpThumb creating corrupted/oversized thumbnails I'm having a very strange problem with the phpThumb library, for some reason when the thumbnails are generated they are being created very large in size (550k for a 150x65 image) and in many cases do not load at all. I have narrowed the issue down to the phpThumb library but I am unsure of what the actual problem is. Here is an example of one of the images: http://www.justsunnies.com.au/image/product/small/nitro_cr-c.jpg Any help would be much appreciated as I am at my wits end as to why this problem is occurring. Thanks A: you can use timthumb.php if would like <img src="<?php echo path/to/timthumb.php?src="path"&h=100&w=100&q=500 ?>"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/25847002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to load image to imageview with url without downloading image I'm trying to load following image link to imageview. https://pbs.twimg.com/profile_banners/169252109/1422362966 Can't it problem to image size to load imageview ? activity_profile.xml <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/container_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="140dp" android:layout_alignParentTop="true" android:background="@color/background_material_dark"> <ImageView android:id="@id/profile_banner" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:scaleType="centerCrop" /> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:scaleType="fitCenter" android:layout_centerInParent="true" /> </RelativeLayout> </LinearLayout> <fragment android:id="@+id/fragment_navigation_drawer" android:layout_width="@dimen/nav_drawer_width" android:name="activity.FragmentDrawer" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" /> </android.support.v4.widget.DrawerLayout ActivityProfile.java public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer); drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar); drawerFragment.setDrawerListener(this); final ImageView imgView =(ImageView)findViewById(R.id.profile_banner); TwitterSession session = Twitter.getSessionManager().getActiveSession(); final long userID = session.getUserId(); MyTwitterApiClients apiclients = new MyTwitterApiClients(session); final Bitmap bmp = null; apiclients.getProfileBannerService().show(userID, null, new Callback<User>() { @Override public void success(Result<User> result) { String imageUrl = result.data.profileBannerUrl; URL url = null; Bitmap bmp = null; try { url = new URL(imageUrl); bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); imgView.setImageBitmap(bmp); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } App stops working at this line bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); What's my wrong ? A: Why don't you try Picasso? It's as simple as this: Picasso .with(context) .load("https://pbs.twimg.com/profile_banners/169252109/1422362966") .into(imgView); And, you can also transform the Bitmap, applying tint, resizing to prevent memory issues, all that stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/32319209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check if the matched EMPTY line is the LAST line of a file in a while IFS read I have a while IFS read loop to check for different matches in the lines. I check for and empty/blank line like this: while IFS= read -r line; do [[ -z $line ]] && printf some stuff I also want to check if the matched empty/blank is also the last line of the file. I am going to run this script on a lot of files, they all: -end with an empty line -they are all a DIFFERENT LENGTH so I cannot assume anything -they have other empty lines but not necessarily at the very end (this is why I have to differentiate) Thanks in advance. A: As chepner has noted, in a shell line-reading loop the only way to know whether a given line is the last one is to try to read the next one. You can emulate "peeking" at the next line using the code below, which allows you to detect the desired condition while still processing the lines uniformly. This solution may not be for everyone, because the logic is nontrivial and therefore requires quite a bit of extra, non-obvious code, and processing is slowed down as well. Note that the code assumes that the last line has a trailing \n (as all well-formed multiline text input should have). #!/usr/bin/env bash eof=0 peekedChar= hadEmptyLine=0 lastLine=0 while IFS= read -r line || { eof=1; (( hadEmptyLine )); }; do # Construct the 1-2 element array of lines to process in this iteration: # - an empty line detected in the previous iteration by peeking, if applicable (( hadEmptyLine )) && aLines=( '' ) || aLines=() # - the line read in this iteration, with the peeked char. prepended if (( eof )); then # No further line could be read in this iteration; we're here only because # $hadEmptyLine was set, which implies that the empty line we're processing # is by definition the last one. lastLine=1 hadEmptyLine=0 else # Add the just-read line, with the peeked char. prepended. aLines+=( "${peekedChar}${line}" ) # "Peek" at the next line by reading 1 character, which # we'll have to prepend to the *next* iteration's line, if applicable. # Being unable to read tells us that this is the last line. IFS= read -n 1 peekedChar || lastLine=1 # If the next line happens to be empty, our "peeking" has fully consumed it, # so we must tell the next iteration to insert processing of this empty line. hadEmptyLine=$(( ! lastLine && ${#peekedChar} == 0 )) fi # Process the 1-2 lines. ndx=0 maxNdx=$(( ${#aLines[@]} - 1 )) for line in "${aLines[@]}"; do if [[ -z $line ]]; then # an empty line # Determine if this empty line is the last one overall. thisEmptyLineIsLastLine=$(( lastLine && ndx == maxNdx )) echo "empty line; last? $thisEmptyLineIsLastLine" else echo "nonempty line: [$line]" fi ((++ndx)) done done < file
{ "language": "en", "url": "https://stackoverflow.com/questions/43483560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to randomize points on a sphere surface evenly? Im trying to make stars on the sky, but the stars distribution isnt even. This is what i tried: rx = rand(0.0f, PI*2.0f); ry = rand(0.0f, PI); x = sin(ry)*sin(rx)*range; y = sin(ry)*cos(rx)*range; z = cos(ry)*range; Which results to: img http://img716.imageshack.us/img716/3320/sphererandom.jpg And: rx = rand(-1.0f, 1.0f); ry = rand(-1.0f, 1.0f); rz = rand(-1.0f, 1.0f); x = rx*range; y = ry*range; z = rz*range; Which results to: img2 http://img710.imageshack.us/img710/5152/squarerandom.jpg (doesnt make a sphere, but opengl will not tell a difference, though). As you can see, there is always some "corner" where are more points in average. How can i create random points on a sphere where the points will be distributed evenly? A: you can do z = rand(-1, 1) rxy = sqrt(1 - z*z) phi = rand(0, 2*PI) x = rxy * cos(phi) y = rxy * sin(phi) Here rand(u,v) draws a uniform random from interal [u,v] A: You don't need trigonometry if you can generate random gaussian variables, you can do (pseudocode) x <- gauss() y <- gauss() z <- gauss() norm <- sqrt(x^2 + y^2 + z^2) result = (x / norm, y / norm, z / norm) Or draw points inside the unit cube until one of them is inside the unit ball, then normalize: double x, y, z; do { x = rand(-1, 1); y = rand(-1, 1); z = rand(-1, 1); } while (x * x + y * y + z * z > 1); double norm = sqrt(x * x + y * y + z * z); x / norm; y /= norm; z /= norm; A: It looks like you can see that it's the cartesian coordinates that are creating the concentrations. Here is an explanation of one right (and wrong) way to get a proper distribution.
{ "language": "en", "url": "https://stackoverflow.com/questions/8839086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help on implementing NMS (Non-Max-Suppression) python I save the results of my object detection model in a .json file and it has the score, box coordinated, the detected class of multiple objects. There are multiple overlapped detections on the image and I heard that NMS can help do exactly that. I found a code that does that but I am not seeing any results and I think I am implementing it wrong. Can someone help me with it as it is much appreciated. Or if there is a better way to get it of overlapping detection (boxes) ? The code is as follows, # import the necessary packages import numpy as np from PIL import Image, ImageFont, ImageDraw import cv2 import json import pandas as pd json_path2 = "A3_detections.json" # Opening JSON file f = open(json_path2) # Reading into string whole_text = f.read() # Editing the text to fit JSON format whole_text = "{'items':"+whole_text[1:-1]+'}' whole_text = whole_text.replace("'",'"') data = json.loads(whole_text) count = 0 for i in data['items']: count+=1 # Iterating through JSON and add for i in range(count): x2 = data['items'][i]['box'][2] y2 = data['items'][i]['box'][3] x1 = data['items'][i]['box'][0] y1 = data['items'][i]['box'][1] boxes = [(x1, y1, x2, y2)] # Felzenszwalb et al. def non_max_suppression_slow(boxes, overlapThresh): # if there are no boxes, return an empty list if len(boxes) == 0: return [] # initialize the list of picked indexes pick = [] pick.append(boxes[index]) # grab the coordinates of the bounding boxes x1 = boxes[:,0] y1 = boxes[:,1] x2 = boxes[:,2] y2 = boxes[:,3] # compute the area of the bounding boxes and sort the bounding # boxes by the bottom-right y-coordinate of the bounding box area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = np.argsort(y2) # keep looping while some indexes still remain in the indexes # list while len(idxs) > 0: # grab the last index in the indexes list, add the index # value to the list of picked indexes, then initialize # the suppression list (i.e. indexes that will be deleted) # using the last index last = len(idxs) - 1 i = idxs[last] pick.append(i) suppress = [last] # loop over all indexes in the indexes list for pos in range(0, last): # grab the current index j = idxs[pos] # find the largest (x, y) coordinates for the start of # the bounding box and the smallest (x, y) coordinates # for the end of the bounding box xx1 = max(x1[i], x1[j]) yy1 = max(y1[i], y1[j]) xx2 = min(x2[i], x2[j]) yy2 = min(y2[i], y2[j]) # compute the width and height of the bounding box w = max(0, xx2 - xx1 + 1) h = max(0, yy2 - yy1 + 1) # compute the ratio of overlap between the computed # bounding box and the bounding box in the area list overlap = float(w * h) / area[j] # if there is sufficient overlap, suppress the # current bounding box if overlap > overlapThresh: suppress.append(pos) # delete all indexes from the index list that are in the # suppression list idxs = np.delete(idxs, suppress) # return only the bounding boxes that were picked return boxes[pick] The .json file looks like this, "[{'score': 0.9994423, 'box': [371, 108, 451, 165], 'class': 1, 'area': 4560.0}, {'score': 0.9993526, 'box': [309, 383, 393, 438], 'class': 1, 'area': 4620.0}, {'score': 0.9989114, 'box': [408, 336, 482, 394], 'class': 1, 'area': 4292.0}, {'score': 0.9980921, 'box': [276, 443, 359, 510], 'class': 1, 'area': 5561.0}, {'score': 0.99784064, 'box': [276, 144, 352, 198], 'class': 1, 'area': 4104.0}, {'score': 0.99754494, 'box': [399, 494, 492, 550], 'class': 2, 'area': 5208.0}, {'score': 0.9967483, 'box': [414, 403, 493, 474], 'class': 3, 'area': 5609.0}, {'score': 0.99523735, 'box': [359, 194, 456, 267], 'class': 1, 'area': 7081.0}, {'score': 0.99133027, 'box': [258, 238, 346, 313], 'class': 1, 'area': 6600.0}, {'score': 0.9883846, 'box': [223, 361, 279, 460], 'class': 3, 'area': 5544.0}, {'score': 0.9849324, 'box': [480, 318, 543, 381], 'class': 3, 'area': 3969.0}, {'score': 0.972732, 'box': [456, 108, 520, 195], 'class': 3, 'area': 5568.0}, {'score': 0.967366, 'box': [505, 39, 544, 140], 'class': 1, 'area': 3939.0}, {'score': 0.9157209, 'box': [441, 222, 482, 318], 'class': 3, 'area': 3936.0}, {'score': 0.9959129, 'box': [559, 22, 624, 103], 'class': 1, 'area': 5265.0}, {'score': 0.9946513, 'box': [541, 374, 630, 425], 'class': 1, 'area': 4539.0}, {'score': 0.99179137, 'box': [537, 420, 584, 525], 'class': 1, 'area': 4935.0}, {'score': 0.94723177, 'box': [529, 205, 563, 308], 'class': 1, 'area': 3502.0}, {'score': 0.9857883, 'box': [244, 476, 285, 575], 'class': 1, 'area': 4059.0}, {'score': 0.8887795, 'box': [185, 514, 226, 623], 'class': 1, 'area': 4469.0}, {'score': 0.7980404, 'box': [382, 546, 427, 640], 'class': 3, 'area': 4230.0}, {'score': 0.99635565, 'box': [515, 542, 605, 595], 'class': 1, 'area': 4770.0}, {'score': 0.998, 'box': [595, 310, 663, 389], 'class': 1, 'area': 5372.0}, {'score': 0.9968482, 'box': [582, 442, 659, 494], 'class': 1, 'area': 4004.0}, {'score': 0.9964861, 'box': [626, 487, 680, 579], 'class': 1, 'area': 4968.0}, {'score': 0.9919488, 'box': [618, 1, 665, 99], 'class': 1, 'area': 4606.0}, {'score': 0.99128747, 'box': [574, 172, 658, 220], 'class': 1, 'area': 4032.0}, {'score': 0.99087024, 'box': [580, 594, 639, 639], 'class': 1, 'area': 2655.0}, {'score': 0.9883312, 'box': [639, 277, 728, 329], 'class': 1, 'area': 4628.0},
{ "language": "en", "url": "https://stackoverflow.com/questions/72948093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LARAVEL: All elements from foreach have the id 1, which makes deleting them impossible I'm in a difficult situation. I'm building a birthlist clone with a scraper but it's difficult to code it because I'm not that experienced. I've managed to create an admin page with multiple forms to insert websites, categories and a link form where you can specify on what link the scraping should be done and to what site and category it will be linked. However, adding such things is no problem, but deleting them is not working.. My sites, categories en links are displayed on my admin page with for each element a scrape and delete button. When I delete the last item in the row, it deletes the first element. When I want to delete something else, laravel throws an exception that it tries to attempt to read property on null, which means that it no longer exists. When I dump and die before the delete function, every item in every list has the id '1'. That is why it deletes the first item in a row. Can anyone help me please? I assume it's because the id that is requested to delete the item, is retrieved from the url and the id that is given in the url is the user id which is 1. So if anyone can give me tips to make sure I can give the id of the user but in a different way. Let me know! My code: Admincontroller: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Website; use App\Models\Category; use App\Models\Link; use Goutte\Client; class AdminController extends Controller { public function showAdmin($id) { $categories = Category::all(); $websites = Website::all(); $links = Link::all(); return view('admin', compact('categories', 'websites', 'links')); } public function storeWeb(Request $request) { $web = Website::create([ 'title' => $request->input('site'), 'url' => $request->input('url') ]); return back(); } public function destroyWeb(Request $request, $id) { $web = Website::find($id); $web->delete(); return back(); } public function storeCat(Request $request) { $cat = Category::create([ 'title' => $request->input('title') ]); return back(); } public function destroyCat(Request $request, $id) { $cat = Category::find($id)->first(); $cat->delete(); return back(); } public function storeLink(Request $request) { $link = Link::create([ 'url' => $request->input('scrapeUrl'), 'main_filter_selector' => $request->input('filter'), 'website_id' => $request->input('website_id'), 'category_id' => $request->input('category_id'), ]); return back(); } public function destroyLink(Request $request, $id) { $link = Link::find($id); dd($link); $link->delete(); return back(); } public function scrape(Request $request) { $link = Link::find($request->link_id); $scraper = new Scraper (new Client()); $scraper->handle($link); if($scraper->status == 1) { return response()->json(['status' => 1, 'msg' => 'Scraping done']); } else { return response()->json(['status' => 2, 'msg' => $scraper->status]); }; } } My adminpage: <body class="relative min-h-screen"> @include('partials.header') <main class="pb-20"> <div class="text-center m-auto text-2xl p-4 w-fit border-b"> <h2>Welkom <strong>{{ auth()->user()->name }}</strong></h2> </div> <div class="gap-10 m-auto xl:w-3/5"> <div class="mt-8"> <h3 class="bg-gray-100 p-4"><strong>Winkels</strong></h3> <div class=""> <div class="p-4 m-auto"> <form action="{{ route('newWeb', Auth()->user()) }}" method="POST"> @csrf <div class="flex wrap flex-row items-center justify-left my-4"> <label for="shop" class="w-2/12">Webshop:</label> <input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="site" id="titel" placeholder="Dreambaby"> </div> <div class="flex wrap flex-row items-center justify-left"> <label for="url" class="w-2/12"> Voeg een url toe: </label> <input type="url" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="url" id="url" placeholder="http://dreambaby.com/"> <button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" name="shop" value="add" type="submit">Voeg link toe</button> </div> </form> <div class="flex wrap flex-row items-center mt-12"> <div class="flex flex-row flex-wrap w-full"> <table class="table-auto"> @foreach ($websites as $web) <form action="{{ route('delWeb', Auth()->user()) }}" method="POST"> @csrf @method('DELETE') <tr class="border-b"> <td class="p-4">{{ $web->title }}</td> <td class="p-4">{{ $web->id }}</td> <td class="p-4"><button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button> </td> </tr> </form> @endforeach </table> </div> </div> </div> </div> </div> </div> <div class="gap-10 m-auto xl:w-3/5"> <div class="mt-8"> <h3 class="bg-gray-100 p-4"><strong>Categorieën</strong></h3> <div class="mt-4"> <div class="p-4 m-auto"> <form action="{{ route('newCat', Auth()->user()) }}" method="POST"> @csrf <div class="flex wrap flex-row items-center justify-left"> <label for="url" class="w-2/12"> Voeg een categorie toe: </label> <input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="title" id="cat" placeholder="Eten en Drinken"> <button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" name="category_submit" type="submit">toevoegen</button> </div> </form> <div class="flex wrap flex-row items-center mt-12"> <div class="flex flex-row flex-wrap w-full"> <table class="table-auto"> @foreach ($categories as $category) <form action="{{ route('delCat', Auth()->user()), $category->id }}" id="{{ $category->id }}" method="POST"> @csrf @method('DELETE') <tr class="border-b"> <td class="p-4">{{ $category->title }}</td> <td class="p-4">{{ $category->id }}</td> <td class="p-4"><button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button> </td> </tr> </form> @endforeach </table> </div> </div> </div> </div> </div> </div> <div class="gap-10 m-auto xl:w-3/5"> <div class="mt-8"> <h3 class="bg-gray-100 p-4"><strong>Scrapes</strong></h3> <div class=""> <div class="p-4 m-auto"> <form action="{{ route('newLink', Auth()->user()) }}" method="POST"> @csrf <div class="flex wrap flex-row items-center justify-left my-4"> <label for="scrape" class="w-2/12">Url:</label> <input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="scrapeUrl" id="scrapetitel" placeholder="https://www.thebabyscorner.be/nl-be/baby_eten_en_drinken/"> </div> <div class="flex wrap flex-row items-center justify-left my-4"> <label for="text" class="w-2/12"> Filter: </label> <input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="filter" id="url" placeholder=".1-products-item"> </div> <div class="flex wrap flex-row items-center justify-left my-4"> <label for="webpicker" class="w-2/12">Winkel:</label> <select name="website_id" id="" class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100"> <option value="#" disabled selected>Kies je winkel</option> @foreach ($websites as $web) <option value="{{ $web->id }}" >{{ $web->title }}</option> @endforeach </select> </div> <div class="flex wrap flex-row items-center justify-left my-4"> <label for="webpicker" class="w-2/12">Categorie:</label> <select name="category_id" id="" class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100"> <option value="#" disabled selected>Kies je categorie</option> @foreach ($categories as $cat) <option value="{{ $cat->id }}" >{{ $cat->title }}</option> @endforeach </select> <button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" type="submit" name="scrape_submit">toevoegen</button> </div> </form> <div class="flex wrap flex-row items-center mt-12 w-full"> <div class="flex flex-row flex-wrap w-full"> <form action="{{ route('delLink', Auth()->user()) }}" method="POST"> @csrf @method('DELETE') <table class="table-auto w-full"> <tr class="bg-slate-300"> <td class="p-4"><strong>Url</strong></td> <td class="p-4"><strong>Filter selector</strong></td> <td class="p-4"><strong>Website</strong></td> <td class="p-4"><strong>Categorie</strong></td> <td></td> <td></td> </tr> @foreach ($links as $link) <tr data-id="{{ $link->id }}" class=""> <td class="p-4 border-r">{{ $link->url }}</td> <td class="p-4 border-r">{{ $link->main_filter_selector }}</td> <td class="p-4 border-r">{{ $link->website->title }}</td> <td class="p-4 border-r">{{ $link->category->title }}</td> <td class="p-4 border-r"><button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white block m-auto" type="submit">Scrape</button></td> <td class="p-4"><button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button> </td> </tr> @endforeach </table> </form> </div> </div> </div> </div> </div> </main> @include('partials.footer') </body> My routes: <?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\HomeController; use App\Http\Controllers\DashController; use App\Http\Controllers\ListviewController; use App\Http\Controllers\NewlistController; use App\Http\Controllers\BabyController; use App\Http\Controllers\ScrapeController; use App\Http\Controllers\AdminController; use App\Http\Controllers\ItemsController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ require __DIR__.'/auth.php'; Route::get('/', [HomeController::class, 'home'])->name('home'); Route::get('/home', [HomeController::class, 'home']); Route::get('/listview', [ListviewController::class, 'listview']) ->name('lists'); Route::middleware('auth')->group (function () { Route::get('/create', [NewlistController::class, 'newlist']) ->name('create'); Route::get('/dashboard/{role}/{id?}', [DashController::class, 'dashboard']) ->name('dashboard'); Route::post('/dashboard/{role}/{id}', [NewlistController::class, 'store']); Route::get('/dashboard/{user_id}/{baby}', [BabyController::class, 'show']) ->name('baby'); Route::get('/dashboard/{user_id?}/{baby}/catalogus', [ScrapeController::class, 'show']); Route::get('/admin/{id}', [AdminController::class, 'showAdmin']) ->name('admin'); Route::post('/admin/{id}/websites/', [AdminController::class, 'storeWeb']) ->name('newWeb'); Route::delete('/admin/{id}/websites/', [AdminController::class, 'destroyWeb']) ->name('delWeb'); Route::post('/admin/{id}/categories/', [AdminController::class, 'storeCat']) ->name('newCat'); Route::delete('/admin/{id}/categories/', [AdminController::class, 'destroyCat']) ->name('delCat'); Route::post('/admin/{id}/links/', [AdminController::class, 'storeLink']) ->name('newLink'); Route::delete('/admin/{id}/links/', [AdminController::class, 'destroyLink']) ->name('delLink'); }); A: Replace this code <form action="{{ route('delLink', Auth()->user()) }}" method="POST"> @csrf @method('DELETE') <table class="table-auto w-full"> <tr class="bg-slate-300"> <td class="p-4"><strong>Url</strong></td> <td class="p-4"><strong>Filter selector</strong></td> <td class="p-4"><strong>Website</strong></td> <td class="p-4"><strong>Categorie</strong></td> <td></td> <td></td> </tr> @foreach ($links as $link) <tr data-id="{{ $link->id }}" class=""> <td class="p-4 border-r">{{ $link->url }}</td> <td class="p-4 border-r">{{ $link->main_filter_selector }}</td> <td class="p-4 border-r">{{ $link->website->title }}</td> <td class="p-4 border-r">{{ $link->category->title }}</td> <td class="p-4 border-r"><button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white block m-auto" type="submit">Scrape</button></td> <td class="p-4"><button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button> </td> </tr> @endforeach </table> </form> With this <table class="table-auto w-full"> <tr class="bg-slate-300"> <td class="p-4"><strong>Url</strong></td> <td class="p-4"><strong>Filter selector</strong></td> <td class="p-4"><strong>Website</strong></td> <td class="p-4"><strong>Categorie</strong></td> <td></td> <td></td> </tr> @foreach ($links as $link) <tr data-id="{{ $link->id }}" class=""> <td class="p-4 border-r">{{ $link->url }}</td> <td class="p-4 border-r">{{ $link->main_filter_selector }}</td> <td class="p-4 border-r">{{ $link->website->title }}</td> <td class="p-4 border-r">{{ $link->category->title }}</td> <td class="p-4 border-r"><button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white block m-auto" type="submit">Scrape</button></td> <td class="p-4"> <form action="{{ route('delLink', $link->id) }}" method="POST"> @csrf @method('DELETE') <button class="w-fit h-full p-2 bg-red-400 h-fit rounded hover:bg-red-600 hover:text-white block m-auto" type="submit">Verwijderen</button> </form> </td> </tr> @endforeach </table> Your destroyLink() method should contain this public function destroyLink(Request $request) { $id = $request->id; $link = Link::find($id); $link->delete(); return back(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/72448253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .click() triggering twice and also results in having to click the browser back button twice to return to the previous page The code below represents two sets of radio buttons. One button in each set must be clicked at all times. Clicking on one button in each set will navigate the user to a new page where they'll have the same radio buttons on that new page. To achieve this I used a combination of useRef and .current.click() but the issue of doing it this way is that it triggers two clicks every time something on the page changes and that results in having to click the browser back button twice for each time a change is made. This wouldn't be very practical. I've tried the defaultchecked property for radio buttons and it doesn't work properly for this case (needs to be manually clicked on again even though the visual shows it to be clicked on by default). I know local Storage is another option but my coding skills are very limited and I'm not sure how to properly integrate it with my current code. Any help would be greatly appreciated! import React, { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; export default function DisplayHomeOptions() { let navigate = useNavigate(); const [formData, setFormData] = useState({ location: "", selector: "" }) const globalRef = useRef(null); const messagesRef = useRef(null); useEffect(() => { globalRef.current.click(); messagesRef.current.click(); }, []); function handleChange(event) { const { name, value, type, checked } = event.target setFormData(prevFormData => { return { ...prevFormData, [name]: type === "checkbox" ? checked : value } }) } useEffect(() => { const { location, selector } = formData; if (location && selector) { const target = navTarget[location][selector]; if (target) { navigate(target); } } }, [formData]); const navTarget = { National: { Messages: "/national/messages", Polls: "/national/polls", Questions: "/national/questions", }, Global: { Messages: "/global/messages", Polls: "/global/polls", Questions: "/global/questions", } } return ( <div> <fieldset> <legend>Option #1</legend> <input type="radio" name="location" value="Global" onChange={handleChange} ref={globalRef} /> <label htmlFor="Global">Global</label> <input type="radio" name="location" value="National" onChange={handleChange} /> <label htmlFor="National">National</label> </fieldset> <fieldset> <legend>Option #2</legend> <input type="radio" name="selector" value="Messages" onChange={handleChange} ref={messagesRef} /> <label htmlFor="Messages">Messages</label> <input type="radio" name="selector" value="Questions" onChange={handleChange} /> <label htmlFor="Questions">Questions</label> <input type="radio" name="selector" value="Polls" onChange={handleChange} /> <label htmlFor="Polls">Polls</label> </fieldset> </div> ) }
{ "language": "en", "url": "https://stackoverflow.com/questions/71382751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modify errors in Redux-form from 'outside' I got a random component with Redux-form, e.g.: {code...} <form> <Field component={TextField} name="firstName" /> </form> export default connect(mapStateToProps)(reduxForm({ form: 'myForm', validate, })(injectIntl(myForm))); And a validate.js file: {code...} const firstName = trim(values.get('firstName')); if (!(firstName)) { errors.firstName = 'Required'; } Im able to modify the error message, it can be Required, or anything else I want. But my question is: am I able to change the error or even add a new one condition but outside the validate.js file? For example inside the component. So I could change the Required name to another one, without modifying the validate.js file? Thanks! Edit: How can I reference to specified field in the component holding the form? Is there a way to fix it globally? Simple example: globalComponent.js { form: 'myForm', error: { field: 'firstName', errorMsg: 'Use a capital letter!', }, } A: You could use a separate object to define the validation messages: export const validationMessages = { required: 'Field is required' } // ...code errors.firstName = validationMessages.required Then, if you need to change the messages for required, just set the validationMessages.required, like this: validationMessages.required = 'First name is required' However, mutate an object with the validation messages isn't a good solution. I strongly recommend you to use a module called redux-form-validators. With this module, you can easily override the validation message: import { required, email } from 'redux-form-validators' <Field ... validate={required()} // Will use the default required message > <Field ... validate={required({ message: 'Hey, the first name is required!' })} // Will override the default message />
{ "language": "en", "url": "https://stackoverflow.com/questions/46077544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'class' object has no attribute 'object' What am i doing wrong here. I have been trying to figure this out for hours. I think i am having issues with Django get_context_data function. Error is 'PatientBedAllotmentList' object has no attribute 'object' views.py @method_decorator(login_required, name='dispatch') class PatientBedAllotmentList(ListView): model = BedAllotment template_name = 'room/bed_allotment_list.html' def get_context_data(self, **kwargs): context = super(PatientBedAllotmentList, self).get_context_data(**kwargs) start = BedAllotment.objects.get(id=self.object.id).allotment_date end = BedAllotment.objects.get(id=self.object.id).departure_date amount = BedCreate.objects.get(id=self.object.id).cost days_number = abs((end - start).days) days_number = int(days_number) amount_due = amount * days_number context['account_type'] = AccountUser.objects.get(user_id=self.request.user.id) hospital_id = AccountUser.objects.get(user_id=self.request.user.id).hospital_id allotment_details = BedAllotment.objects.filter(hospital_id=hospital_id) context['allotment'] = allotment_details context['amount'] = amount_due return context urls.py from django.conf.urls import url from medisaver.room import views urlpatterns = [ url(r'^room-category/create/$', views.RoomCategoryCreate.as_view(), name='room_category_create'), url(r'^room-category/list/$', views.RoomCategoryList.as_view(), name='room_category_list'), url(r'^room-category/update/(?P<hospital_id>[0-9A-Fa-f-]+)/(?P<category_id>[0-9]+)/$', views.RoomCategoryUpdate.as_view(), name='room_category_update'), url(r'^room-category/delete/(?P<hospital_id>[0-9A-Fa-f-]+)/(?P<category_id>[0-9]+)/$', views.RoomCategoryDelete.as_view(), name='room_category_delete'), url(r'^hospital-rooms/list/$', views.RoomList.as_view(), name='room_list'), url(r'^hospital-rooms/create/$', views.RoomCreateView.as_view(), name='room_create'), url(r'^hospital-rooms/update/(?P<category_id>[0-9]+)/(?P<room_id>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'), url(r'^hospital-rooms/delete/(?P<category_id>[0-9]+)/(?P<room_id>[0-9]+)/$', views.RoomDelete.as_view(), name='room_delete'), url(r'^hospital-rooms/beds/create/$', views.BedCreateView.as_view(), name='bed_create'), url(r'^hospital-rooms/beds/list/$', views.BedList.as_view(), name='bed_list'), url(r'^hospital-rooms/beds/update/(?P<room_id>[0-9]+)/(?P<bed_id>[0-9]+)/$', views.BedUpdate.as_view(), name='bed_update'), url(r'^hospital-rooms/beds/delete/(?P<room_id>[0-9]+)/(?P<bed_id>[0-9]+)/$', views.BedDelete.as_view(), name='bed_delete'), url(r'^hospital-rooms/beds/patient-bed-allotment/$', views.BedAllotmentCreate.as_view(), name='bed_allotment'), url(r'^hospital/discharge-patient/(?P<allotment_id>[0-9]+)/(?P<patient_id>[0-9A-Fa-f-]+)/$', views.BedDischarge.as_view(), name='patient_bed_discharge'), url(r'^hospital/bed-allotment-list/$', views.PatientBedAllotmentList.as_view(), name='patient_bed_list'), ] A: self.object does not make any sense in ListView. If you want to get stay_time then you can do it in your model and access in template using object.stay_time and even you can calculate the amount in template by multiplying. But I You can even do it in detailview. Create a method in that model like @property def stay_time(self): return (self.departure_date-self.allotment_date) A: I was able to fix it by calling on form_valid function. I used the function on my BedDischarge class in my views. And was able to use self.object. Then made a template call in my templates. @method_decorator(login_required, name='dispatch') class BedDischarge(UpdateView): model = BedAllotment template_name = 'room/bed_discharge.html' form_class = BedAllotmentUpdateForm pk_url_kwarg = 'allotment_id' success_url = reverse_lazy('patient_bed_list') def get_context_data(self, **kwargs): context = super(BedDischarge, self).get_context_data(**kwargs) context['account_type'] = AccountUser.objects.get(user_id=self.request.user.id) return context def form_valid(self, form): get_allot_id = self.object.id bed_allot = BedAllotment.objects.get(id=get_allot_id) start_time = bed_allot.allotment_date end_time = form.instance.departure_date cost = BedCreate.objects.get(id=self.object.bed_id).cost days_spent = (end_time - start_time).days amount = cost * days_spent form.instance.days = days_spent form.instance.amount = amount return super(BedDischarge, self).form_valid(form)
{ "language": "en", "url": "https://stackoverflow.com/questions/51574458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove timezone information from datetime object What is the fastest way to trim datetime object of this form 2016-12-14 15:57:16.140645 to become like this: 2016-12-14 15:57:16? doing str('2016-12-14 15:57:16.140645').strip(".")[0] is painfully slow for large datasets and besides I need the returned format to be a datetime object A: For those that came here for the actual question 'Remove timezone information from datetime object', the answer would be something like: datetimeObject.replace(tzinfo=None) from datetime import datetime, timezone import time datetimeObject = datetime.fromtimestamp(time.time(), timezone.utc) print(datetimeObject) datetimeObject = datetimeObject.replace(tzinfo=None) print(datetimeObject) A: use strftime if you already have a datetime object dt.strftime('%Y-%m-%d %H:%M:%S') If you need a datetime object from a string, the fastest way is to use strptime and a slice: st = '2016-12-14 15:57:16.140645' dt = datetime.strptime(st[:19], '%Y-%m-%d %H:%M:%S')
{ "language": "en", "url": "https://stackoverflow.com/questions/41166093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: NgRx redirect to dashboard on loginSuccess Action I'm learning NgRx and I have a basic question. I've been looking at sample projects and other answers and they are all from 2017 where the architecture was a bit different. I'm implementing a login feature, everything so far is working fine, actions are being called, rest Api request been made, etc. My only question is: where do I redirect the user to the dashboard? Actions: export const loginAction = createAction( '[Login Page] User Login', props<{ login: string; password: string }>() ); export const loginSuccessAction = createAction( '[Auth] Login Complete', props<{user: UserModel}>() ); export const loginFailAction = createAction('[Auth] Login Fail', props<{error: any}>()); Reducers: export interface AuthState{ isLoggedIn: boolean; user: UserModel | null; } export const initialState: AuthState = { isLoggedIn: false, user: null }; const _authReducer = createReducer( initialState, on(loginAction, (state) => ({...state, isLoggedIn: false, user: null})), on(loginSuccessAction, (state, {user}) => ({...state, isLoggedIn: true, user: user})), on(loginFailAction, (state) => ({ isLoggedIn: false, user: null })) ); // tslint:disable-next-line:typedef export function authReducer(state, action) { return _authReducer(state, action); } Effects: @Injectable() export class AuthEffects { constructor( private actions$: Actions, private authService: AuthService ) {} @Effect() login$ = createEffect(() => this.actions$.pipe( ofType(loginAction), exhaustMap(action => this.authService.login(action.login, action.password).pipe( map(user => loginSuccessAction({user: user.redmine_user})), catchError(error => of(loginFailAction({ error }))) ) ) ) ); } In my component: ngOnInit(): void { this.loginForm = this._formBuilder.group({ login : ['', Validators.required], password: ['', Validators.required] }); } onLogin(): void{ this._store.dispatch(loginAction(this.loginForm.value)); } ngOnDestroy(): void { } As I said, actions are being triggered successfully. I can see the loginSuccessAction being called in the Redux Dev Tools. I've seen people doing the redirect inside the effect, but is that the right place to do it? If not, where should I do? Is there something like listen to actions? A: If I understand correctly, you're asking where to perform redirection after a user logs in, but not in the technical sense of how to do it but in an architectural sense of where is the right place to do it. Let's go over the options you have: * *Redirect in the effect - This is your first option, redirecting in the effect before or after dispatching a success action to the reducer. *Redirecting from the service - You can also redirect after the service for example like this: myService(): void { return this.http.get(url).pipe( tap(() => this.router.navigate([navigationURL])) ) } *Other options - other options are possible, in your question you asked if there's something that allows to listen to actions, well that's pretty much what effects are for, to listen to actions, but you could also listen to Observable emittions with subscribe, and redirect when that happens, I DO NOT recommend that approach. I think that adding subscriptions is adding unnecessary complexity to the project, because subscriptions have to be managed. So what to do? Honestly, this is up to you, both options seems valid and I wouldn't say either is a bad practice. I personally prefer to keep my effects clean and do it in the service. I feel like the service is better suited to handle side effects, and it makes it a bit cleaner also when testing, but this is my personal opinion. The important thing to remember is, both options are valid and don't add unnecessary complexity. There's also one small case which might apply to you, if you need that the user will be in the store before redirecting, it might be better to put this in the effects after dispatching an actions to the reducer. If you're working with Observables it will work either way, but it might be easier to understand if they have tight relationship.
{ "language": "en", "url": "https://stackoverflow.com/questions/65620804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write sublime text snippet to make setters and getters and instance variable for ruby? I want to learn how to create snippets for future, and want a snippet that can create setter and getter for instance variable in Ruby files. Something like this name:= {TAB KEY} it becomes like this def name=(n) @name = n end def name @name end A: Its pretty useless to create getters and setters with snippets for ruby. Using attr_accessor & attr_reader is the fastest and cleanest way to declare these properties and NOT having to create snippets for it. attr_accessor :name is the same as def name @name end def name=(n) @name = n end 99% of the time this is what you want. Just declare an attribute accessor for the given instance variable. The remaining 1% is when you actually want a custom attribute with some extra validations inside. And even then you could declare attr_reader :custom_attribute def custom_attribute=(value) # some validation code here ... @custom_attribute = value end
{ "language": "en", "url": "https://stackoverflow.com/questions/31921020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I added a CSS animation but it doesn't work and everything looks fine So I tried to add a simple vibration animation to a link from my website but it simply doesn't work. Anyone see anything wrong with my code? I took the animation code from animista.net and there they were working Here is my code: a { text-decoration: none; animation: vibrate 1s linear infinite both; } @keyframes vibrate { 0% { transform: translate(0); } 20% { transform: translate(-2px, 2px); } 40% { transform: translate(-2px, -2px); } 60% { transform: translate(2px, 2px); } 80% { transform: translate(2px, -2px); } 100% { transform: translate(0); } } <a href="mailto:[email protected]" id="cta">Drop me a line and let’s do cool things together!</a> A: You can set position: absolute or change display value to block-level (because a is inline by default) for transform to work. a { text-decoration: none; display: block; /* Or inline-block */ animation: vibrate 1s linear infinite both; } @keyframes vibrate { 0% { transform: translate(0); } 20% { transform: translate(-2px, 2px); } 40% { transform: translate(-2px, -2px); } 60% { transform: translate(2px, 2px); } 80% { transform: translate(2px, -2px); } 100% { transform: translate(0); } } <a href="mailto:[email protected]" id="cta">Drop me a line and let’s do cool things together!</a> A: The CSS animation is not used to target anchor. so please use div for easy animation effects <!DOCTYPE html> <html> <head> <style> .div { text-decoration: none; position:relative; animation:vibrate 1s linear infinite both; } @keyframes vibrate { 0% { transform: translate(0,0); } 20% { transform: translate(-2px, 2px); } 40% { transform: translate(-2px, -2px); } 60% { transform: translate(2px, 2px); } 80% { transform: translate(2px, -2px); } 100% { transform: translate(0); } } </style> </head> <body> <div class="div"> <a href="mailto:[email protected]" id="cta">Drop me a line and let’s do cool things together!</a> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/46264543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: nhibernate : how to query collection inside parent entity I have the following method. This works fine if i remove the following line .Add(Restrictions.Eq("Product.IsPopItem", true)) The error message is could not resolve property: Product.IsPopItem of: EStore.Domain.Model.ProductCategory I'm confident the "Product.IsPopItem" is mapped correctly as i can call this property. Do i need to add a few criteria. public ICollection<ProductCategory> FindByCompanyIdAndCategoryIdAndIsPop(int companyId, int id) { var products = _session .CreateCriteria(typeof(ProductCategory)) .Add(Restrictions.Eq("CompanyId", companyId)) .Add(Restrictions.Eq("CategoryId", id)) .Add(Restrictions.Eq("Product.IsPopItem", true)) .List<ProductCategory>(); return products; } A: Yes you need to add an .CreateAleas .CreateAlias("Product", "product", JoinType.InnerJoin) please change JoinType to your need, and use "product" alias instead of property name "Product" so final should be something like: .CreateCriteria(typeof(ProductCategory)) .CreateAlias("Product", "product", JoinType.InnerJoin) .Add(Restrictions.Eq("CompanyId", companyId)) .Add(Restrictions.Eq("CategoryId", id)) .Add(Restrictions.Eq("product.IsPopItem", true)) .List<ProductCategory>()); return products;
{ "language": "en", "url": "https://stackoverflow.com/questions/2996294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii - CGridView activerecord relation I need to print out the result in CActiveDataProvider with CGridView and with pagination The following is my function in model public function getCompaniesJobsByCompanyId ( $companyId ) { $criteria = new CDbCriteria(array( 'with'=>array( 'jobs'=>array( 'scopes' => array( 'offline' => array(0), ), 'vacancies'=>array( 'scopes'=>array( 'removed' => array(0), 'archived' => array(0), ), ), ), ), 'condition' => $this->getTableAlias(false) . '.company_id = ' . (int) $companyId, ) ); $criteria->together = true; $dataProvider = new CActiveDataProvider($this, array( 'criteria' => $criteria, 'pagination' => array( 'pageSize' => 20, //Yii::app()->params['pageSize'], ), )); return $dataProvider; } How could be the CGridView to render my data? By this way I iterate the result $dataProvider = Employers::model() -> getCompaniesJobsByCompanyId(2); foreach ( $dataProvider->getData() as $data ) { echo $data['name']; foreach ( $data->jobs as $jobs ) { echo ' ---- ' .($jobs->employer_id) . ' ---- '; foreach ( $jobs->vacancies as $vacancies ) { echo '<br />' . ($vacancies->id) . '<br />'; } } } And My view $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'user-grid', 'dataProvider' => $dataProvider, 'columns'=>array( 'title', // display the 'title' attribute 'id', // d array( 'name'=>'job id', //'value'=> '$data->jobs[0]["id"]', //'value'=> 'jobs.id', //'type' => 'raw' ), array( 'name'=>'vacancy id', //'value'=> '$data->jobs[0]->vacancies[0]->id', //'value'=> 'print_r($data->jobs[0])', 'value'=> '$data->jobs["id"]', //'type' => 'raw' ), array( 'name'=>'employer name', 'type'=>'raw', // to encode html string 'value'=>'$data->name', ), ), )); Any one can help me to print the values in jobs and vacancies relations? UPDATE I tried adding 'value' => '$data->jobs->id' but get an error Trying to get property of non-object Update : I tried 'value' => '$data->jobs[0]["id"]' and it display the the result correctly, but if there are only 1 record on the table. When there is more than 1 record on the table, I need to print all result, how to loop on it ? A: This line 'value' => '$data->jobs->id' raised an error Trying to get property of non-object because you have been permitted to accessed the property of object instead of array of objects (jobs) The workaround is you declare a function to do the task on the controller which rendered your gridview $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( ... array( 'name'=>'newColumn', //call the method 'gridDataColumn' from the controller 'value'=>array($this,'gridDataColumn'), 'type'=>'raw' ) ), )); class MyController extends Controller { //called on rendering the column for each row protected function gridDataColumn($data,$row) { $cellResult = ""; //do your loop here //example foreach ( $data->children as $child ) { $cellResult .=$child->id . "<br/>"; $cellResult .=$child->name . "<br/>"; } return $cellResult ; } ... } Yii Tutorial CGridView: Render customized/complex datacolumns
{ "language": "en", "url": "https://stackoverflow.com/questions/18189323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save changes failing, but no exception thrown I have a case where I am calling SaveChanges, it is failing, throwing out of the try block, but not being caught. I have never heard of this happening, and your help would be appreciated. I am using C# in Visual Studio 2008, with .net framework 3.5SP1. The code in question is: try { using (EntityConnection conn = new EntityConnection(_connName)) { MWDPLCEntities contxt = new MWDPLCEntities(conn); plcstatusmessage psmn = plcstatusmessage.CreatePLCStatusMessage(plcID, smID); contxt.AddToplcstatusmessage(psmn); contxt.SaveChanges(); } } catch(Exception ex) { LogService.addLog(ex.ToString(), LogService.LOG_EXCEPTION) ; } I have placed log statements before and after the SaveChanges line, and the one directly following does not get printed. However, the Exception does not get logged either, nor does the data get saved. I am honestly puzzled as to how the error is happening without throwing an exception. I can only think that there is some other way that C# is reporting the error that I am not 'catching'. If anyone has a pointer or suggestion, I would greatly appreciate it. Bruce.
{ "language": "en", "url": "https://stackoverflow.com/questions/5227465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML parser for phrase and case sensitive searches, in Java I would like to know if there are any HTML Parsers in Java that would support phrase and case sensitive searches. All I need to know is number of hits in a html page for searched phrase and support for case sensitivity. Thanks, Sharma A: Have you tried this? You can search the text using regular expressions. A: does not it help, if you take html page as text, strip html tags: String noHTMLString = htmlString.replaceAll("\\<.*?\\>", ""); and now count what you need in noHTMLString ? It could be helpful, if you have html page with markup like: this is <span>cool</span> and you need to look for text "is cool" (because prev html page will be transformed into "this is cool" string). To count you can use StringUtils from Apache Commons Lang, it has special method called countMatches. Everything together should work as: String htmlString = "this is <span>cool</span>"; String noHTMLString = htmlString.replaceAll("\\<.*?\\>", ""); int count = StringUtils.countMatches( noHTMLString, "is cool"); I would go with that approach, at least give it a try. It sounds better than parsing html, and then traversing it looking for words you need...
{ "language": "en", "url": "https://stackoverflow.com/questions/4750871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make these Flexbox columns work simply? When width >960px, this element looks great with a row of three columns, but when I go smaller than 960 the cards default to one column. I am unsure how to style this so that it has a desired behavior of going form three columns, to two columns and then one column What does the community suggest? Note: this was lifted from https://vuetifyjs.com/en/components/item-groups code pen: https://codepen.io/gene-yllanes/pen/gJYqzq?editors=1010 <v-item-group> <v-container grid-list-md> <v-layout wrap> <v-flex v-for="n in 9" :key="n" xs12 md4 > <v-item> <v-card slot-scope="{ active, toggle }" :color="active ? 'primary' : ''" class="d-flex align-center" dark height="200" @click="toggle" > <v-scroll-y-transition> <div v-if="active" class="display-3 text-xs-center" > Active </div> </v-scroll-y-transition> </v-card> </v-item> </v-flex> </v-layout> </v-container> </v-item-group>
{ "language": "en", "url": "https://stackoverflow.com/questions/55983346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending email with different domain name While sending the mail it showing Mailer Error: SMTP connect() failed It was not working properly.Please check the code and give me valuable answer. require 'PHPMailerAutoload.php'; if(isset($_POST['send'])) { $email = $_POST['email']; $password = $_POST['password']; $to_id = $_POST['toid']; $message = $_POST['message']; $subject = $_POST['subject']; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = 'smtp.domain.com'; $mail->Port = 465; $mail->SMTPSecure = 'ssl'; $mail->SMTPAuth = true; $mail->Username = $email; $mail->Password = $password; $mail->addAddress($to_id); $mail->Subject = $subject; $mail->msgHTML($message); var_dump($mail->send()); if (!$mail->send()) { $error = "Mailer Error: " . $mail->ErrorInfo; echo '<p id="para">'.$error.'</p>'; } else { echo '<p id="para">Successfully sent mail</p>'; } } ?> A: It looks like an authentication problem. control your host, port, username and password.
{ "language": "en", "url": "https://stackoverflow.com/questions/40084048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Global Match Anchors \G: rolling lover over an input file See: https://www.oreilly.com/library/view/mastering-perl/9780596527242/ch02.html I'm having some trouble getting the perl Global Match Anchors \G to work with my input file proved below with my perl code... I would have thought \G keeps picking up where it left off in the previous match and matches from that position in the string? note, if i uncomment these two line it works: #!/bin/perl $vlog = "out/tb_asc.sv"; open(my $F, "$vlog") || die("cannot open file: $vlog\n"); @lines = <$F>; chomp(@lines); $bigline = join("\n", @lines); close($F); $movingline = $bigline; print ">> << START\n"; $moving = $bigline; $moving =~ s|//.*$||mg; $moving =~ s|\s+$||mg; while(1) { # Blank Linke if ($moving =~ /\G\n/g) { #$moving = substr $moving, $+[0]+1; # <= doesn't \G anchor imply this line? next; } # Precompiler Line if ($moving =~ /\G\s*`(\w+)(\s+(.*))?\n/g) { $vpccmd = $1; $vpcarg1 = $3; #$moving = substr $moving, $+[0]+1; print "vpc_cmd($vpccmd) vpc_arg1($vpcarg1)\n"; next; } $c = nextline($moving); print "\n=> processing:[$c]\n"; die("parse error\n"); } sub nextline($) { @c = split(/\n/, $moving); $c = $c[0]; chomp($c); return $c; } sample input file: out/tb_asc.sv `timescale 1ns / 1ps `define DES tb_asc.DES.HS86.CORE `ifdef HS97_MODE `define SER_DUT HS97 `ifndef HS78_MODE `define SER_DUT HS78 `else //1:HS78_MODE `define SER_DUT HS89 `define SER tb_asc.SER.`SER_DUT.CORE `ifdef MULTIPLE_SERS `define SER_1 tb_asc.SER_1.`SER_DUT.CORE `define SER_2 tb_asc.SER_2.`SER_DUT.CORE `define SER_3 tb_asc.SER_3.`SER_DUT.CORE `else //1:MULTIPLE_SERS `define SER_1 tb_asc.SER.`SER_DUT.CORE `define SER_2 tb_asc.SER.`SER_DUT.CORE `define SER_3 tb_asc.SER.`SER_DUT.CORE `define REPCAPCAL DIGITAL_TOP.RLMS_A.REPCAL.U_REPCAPCAL_CTRL `define MPU_D POWER_MGR.Ism.por_pwdnb_release `define DFE_OUT RXD.EC.Eslicer.QP `define DFE_OUT_SER RXD.EC.Eslicer.QP //beg-include-1 ser_reg_defs_macros.sv //FILE: /design/proj/hs89/users/HS89D-0A/digital/modules/cc/src/ser_reg_defs_macros.sv `define CFG_BLOCK "CFG_BLOCK" `define DEV_ADDR "DEV_ADDR" `define RX_RATE "RX_RATE" `define TX_RATE "TX_RATE" `define DIS_REM_CC "DIS_REM_CC" `define DIS_LOCAL_CC "DIS_LOCAL_CC" NOTE: this version works but doesn't use \G: while(1) { # Blank Linke if ($moving =~ /\A$/m) { $moving = substr $moving, $+[0]+1; next; } # Precompiler Line if ($moving =~ /\A\s*`/) { $moving =~ /\A\s*`(\w+)(\s+(.*))?$/m; $vpccmd = $1; $vpcarg1 = $3; $moving = substr $moving, $+[0]+1; print "vpc_cmd($vpccmd) vpc_arg1($vpcarg1)\n"; next; } $c = nextline($moving); print "\n=> processing:[$c]\n"; die("parse error\n"); } I prefer to do this using \G because substr uses a lot of CPU time with a large input file. A: The bit you're missing is that is that an unsuccessful match resets the position. $ perl -Mv5.14 -e'$_ = "abc"; /./g; /x/g; say $& if /./g;' a Unless you also use /c, that is. $ perl -Mv5.14 -e'$_ = "abc"; /./gc; /x/gc; say $& if /./gc;' b A: When your match fails, In the link to Mastering Perl that you provide, I wrote: I have a way to get around Perl resetting the match position. If I want to try a match without resetting the starting point even if it fails, I can add the /c flag, which simply means to not reset the match position on a failed match. I can try something without suffering a penalty. If that doesn’t work, I can try something else at the same match position. This feature is a poor man’s lexer. My example that I think you are trying to use has /gc on all the matches using \G.
{ "language": "en", "url": "https://stackoverflow.com/questions/74349631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Append "i" tag plus text to span I have this angular script to build out a div. the problem i'm having is that it appends the .text inside the i tag and not as a sibling of i. Hope this makes sense. var body = placeWrapper .append('div') .attr('class', 'thm-listing__body'); body.append('span') .attr('class', 'thm-listing__location') .append('i') .attr('class', 'fa fa-map-marker') .text(function (d) { return d.Address; }); this dive is suppose to render out as follows: <div class="thm-listing__body"> <span class="thm-listing__location"> <i class="fa fa-map-marker"></i> The text here </span> </div> But it currently renders out: <div class="thm-listing__body"> <span class="thm-listing__location"> <i class="fa fa-map-marker">The text here</i> </span> </div> A: You are setting text to i tag and you want a text for span right so set text just after append span instead of after append i as below var body = placeWrapper .append('div') .attr('class', 'thm-listing__body'); body.append('span') .attr('class', 'thm-listing__location') .text(function (d) { return d.Address; }) .append('i') .attr('class', 'fa fa-map-marker'); Update Set icon before span text use prepend() as per below var body = placeWrapper .append('div') .attr('class', 'thm-listing__body'); body.append('span') .attr('class', 'thm-listing__location') .text(function (d) { return d.Address; }) .prepend('i') .attr('class', 'fa fa-map-marker');
{ "language": "en", "url": "https://stackoverflow.com/questions/41822453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If Statement Condition If Element Exists Using PHP I want to check if an element exist then show the div, if it doesn't then hide the div. I'm lost as to exactly how to place it. If I add for both divs combined or each div has to have an IF. <?php if() ?> //if there is no content or image don't show this entire div <div class="row-fullsize archive-header"> <div class="small-12 large-6 columns"> <?php $category_header_src = woocommerce_get_header_image_url(); if( $category_header_src != "" ) { echo '<div class="woocommerce_category_header_image"><img src="'.$category_header_src.'" /> //This is waiting for an image to be uploaded. If it is uploaded show the entire div. Even if nothing is in the other div. </div>'; } ?> </div> <div class="small-12 large-6 columns"> //This is the other div. With a H1 Heading and paragraph. It doesn't need a condition but needs to be a part of the entire row-fullsize. <div class="hd-woocom-description"> <div class="hd-woo-content"> <h1><?php echo $productCatMetaTitle = get_term_meta( get_queried_object_id(), 'wh_meta_title', true); ?></h1> <p><?php echo $productCatMetaDesc = get_term_meta( get_queried_object_id(), 'wh_meta_desc', true); ?></p> </div> </div> </div> </div> <?php endif; ?> // end it here?? A: If I understand your question correctly, this is what you wanted to achieve? Assuming your code works properly just that the if statement is wrong/incorrect. <div class="row-fullsize archive-header"> <?php $category_header_src = woocommerce_get_header_image_url(); ?> <?php if( $category_header_src ) : ?> <div class="small-12 large-6 columns"> <?php echo '<div class="woocommerce_category_header_image"><img src="' . $category_header_src . '" /></div>'; ?> </div> <?php endif; ?> <div class="small-12 large-6 columns"> <div class="hd-woocom-description"> <div class="hd-woo-content"> <h1><?php echo get_term_meta( get_queried_object_id(), 'wh_meta_title', true); ?></h1> <p><?php echo get_term_meta( get_queried_object_id(), 'wh_meta_desc', true); ?></p> </div> </div> </div> </div> Thanks everybody for assisting me with this. I ended up coding it a different way. It's not clean but it works until I can figure out a cleaner way to do it. Appreciate all the help. <?php $category_header_src = woocommerce_get_header_image_url(); if( $category_header_src != "" ) { echo '<div class="row-fullsize archive-header">'; echo '<div class="small-12 large-6 columns">'; echo '<div class="woocommerce_category_header_image"><img src="'.$category_header_src.'" /></div>'; echo '</div>'; echo '<div class="small-12 large-6 columns">'; echo '<div class="hd-woocom-description">'; echo '<div class="hd-woo-content">'; echo '<h1>',esc_attr ( get_term_meta( get_queried_object_id(), 'wh_meta_title', true )),'</h1>'; echo '<p>', esc_attr( get_term_meta( get_queried_object_id(), 'wh_meta_desc', true )),'</p>'; echo '<p><?php echo $productCatMetaDesc = get_term_meta( get_queried_object_id(), wh_meta_desc, true); ?></p>'; echo '</div></div></div></div>'; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/58544286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to show pdf in webview in flutter How to show pdf in webview in flutter. I have already uploaded pdf fle to fireabse database and storage. . Now I want to download and open te pdf in retrieving page or homescreen I have recieved the downloadURL of the pdf uploaded too Container( child: PDfFile1 != null && WCardPDFURL == null ? PDF.file( PDfFile1, height: 600, width: MediaQuery.of(context).size.width * 0.90, ) : PDfFile1 == null && WCardPDFURL == null? FlatButton( onPressed: (){ _getLocalImage4(); }, child: Icon(Icons.picture_as_pdf,size: 80,color:Colors.red,) ) : //Image.file(PDfFile1, width: 200, height: 100,), Image.file( PDfFile1, fit: BoxFit.cover, height: 250, ), ), A: If your PDF file is in firebase storage you can create a url for your PDF with firebase storage. Then open this URL in a Web_view with webview_flutter plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/65625416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get a percentage to 1 decimal place as a string when I divide two integers? Here's what I am using right now: var pc = (p * 100/ c).ToString(); Both p and c are integers but I am not sure how to get the answer as for example something like: 43.5% Would appreciate some advice on what I can do. A: You need to either explicitly cast a value to a non-integer form, e.g. double, or use a non-integer in the calculation. For example: var pc = (p * 100/ (double)c).ToString(); or this (not 100.0 rather than 100): var pc = (p * 100.0/ c).ToString(); Next you need to round the result: var pc = Math.Round(p * 100 / (double)c, 1).ToString(); But as Tetsuya states, you could use the P1 format string (which would output something like 5.0% - culture dependent - for p = 5, c = 100): var pc = (p / (double)c).ToString("P1");
{ "language": "en", "url": "https://stackoverflow.com/questions/53148482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Speech Recognition using service I have an Android application that uses speech recognition in an Activity. I would like to port this over to a service so I can talk to the application while it's running in the background. However, as far as I know, the speech recognition service has to use onActivityResult, which is unavailable for Services. Is there a way to either contain an Activity in a Service such that its GUI is not displayed, or perform speech recognition in a service instead of an activity?
{ "language": "en", "url": "https://stackoverflow.com/questions/13420967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flutter plugin develoment: importing libraries I'm trying to create a Facebook login plugin for Flutter and already got the native code running. There is one thing I don't get though. Where do the dependencies, uses permissions and meta data go? I guess the dependencies and permissions could be added to the plugin's android folder. But the meta data needs a key that only the user can provide. So I can not put it in the android folder of my plugin, only in an android folder in projects using the plugin. But I need the meta data to make the plugin work. So I'm kinda stuck atm. Any one who has experience with this? A: Dependencies can be added in the build.gradle and podspec of the plugin. Though if it depends on a non-standard Maven or CocoaPods repo, users will need to specify that in their project. Permissions are added by the user if needed. Same with configuration files. Use the README of the plugin to explain what needs to be done. If the configuration info is the same across iOS and Android (API keys etc), passing it from Dart to native is a good practice to avoid duplication. If the configuration info is different for each platform, having it be read out of a file by the plugin (or specified in the AppDelegate/Activity) allows the Dart to be agnostic to which platform it's on. Check out the google_sign_in plugin for inspiration.
{ "language": "en", "url": "https://stackoverflow.com/questions/44707548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with rpath in CMAKE I'm having a problem with cmake, like One of the libraries which I want to link to my shared library which I'm compiling is boost. So, I tried like: target_link_libraries(my_project ${Boost_FILESYSTEM_LIBRARY} ${Boost_SYSTEM_LIBRARY} ${Boost_CHRONO_LIBRARY} ${Boost_DATE_TIME_LIBRARY} ${Boost_REGEX_LIBRARY} ${Boost_SIGNALS_LIBRARY} ${Boost_THREAD_LIBRARY}) However, when I execute in the terminal to check the linkage ldd libmy_project.so libboost_system.so.1.66.0 => not found libboost_chrono.so.1.66.0 => not found libboost_date_time.so.1.66.0 => not found libboost_regex.so.1.66.0 => not found libboost_signals.so.1.66.0 => not found libboost_thread.so.1.66.0 => not found But the boost library was found by the cmake in the CMakeList. Anybody know how to fix this? Edit: The problem was to set properly the rpath, I tried to follow the cmake documentation. However, it didn't work for me. The only thing which worked was adding this line before the target_link_libraries(...) in CMkaeLists.txt: set_target_properties(YOUR_PROJECT PROPERTIES LINK_FLAGS "-Wl,-rpath, YOUR_LIB_LOCATION_HERE")
{ "language": "en", "url": "https://stackoverflow.com/questions/50408029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change text of buttons after clicking on them for multiple buttons? I am using multiple buttons and my problem is when i am clicking on any button then the text changes of first button, but not that button on which i am clicking. I am using here same button id for all buttons but it is hard to use different button id's for such multiple buttons so what is any other simple way without using different id's. I want to change only one button at a time on which i am clicking but not other buttons. PLEASE HELP..! html code user1 <input type="button" value="Connect" id="toggle" onclick="myFunction()"> user2 <input type="button" value="Connect" id="toggle" onclick="myFunction()"> user3 <input type="button" value="Connect" id="toggle" onclick="myFunction()"> and so on... and js function is function myFunction() { var change = document.getElementById("toggle"); if (change.value=="Connected") change.value = "Connect"; else change.value = "Connected"; } A: You can do it like this as well? You can change your onclick events as follows: Change onlick functions to this: onclick ="myFunction(this)" And Update your javascript function to be like the following: function myFunction(obj) { if (obj.value == "Connected") obj.value = "Connect"; else obj.value = "Connected"; } A: You cant use same Id for multiple elements. Simply you can use class instead of Id. Then your code will look like that : $(".toggle").click(function(){} $(this).text("Whatever"); })
{ "language": "en", "url": "https://stackoverflow.com/questions/41047226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the "Use Trait Body" setting for? Recently I've started using PHP (worked for MS shops since graduating, and that was mostly what I used in college too). To help with this, I'm using Netbeans and am in the process of configuring it so that it's more similar to Visual Studio. Under Options -> Editor -> Formatting, I've found this setting highlighted in the red box: Any setting I pick for that value makes no difference in the sample file on the right. I copied the text from when I use the "Same Line" value and did a diff on it against the text when using "New Line" and they're identical. So, what is this setting? In the example to the right of the options, I thought this would impact the (new Example())->alignParamsExample(... and push anything after the -> onto a New Line, but that's not the case. I've also read the documentation about traits but I'm still unclear exactly as to what the "trait body" would be. I typed out the code they provided in "Example #2 Precedence Order Example" but noticed no behavioral difference in the IDE. I've tagged this question with both Netbeans and php tags; if I select other languages this option isn't present (but I only have HTML, JSON, Javascript, and PHP to chose from) so I wasn't sure if this is a "PHP thing" or a "Netbeans thing." If it's explicitly one or the other, let me know and I'll remove the tag. A: I think this is about that block in class: class ExampleClass { /** Start of Use Trait Body **/ use TraitOne; use TraitTwo; use TraitThree; /** End of Use Trait Body **/ }
{ "language": "en", "url": "https://stackoverflow.com/questions/42275235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I find which Dlls contain specific W32 functions? My app is a WPF application and it already has code for the older type of System DPI awareness that works well in every version of windows except 8.1. It turns out that Microsoft added a number of functions to Windows 8.1 as part of their implementation of per-monitor DPI awareness. I need to implement code in my program to support this type of DPI awareness. I have documentation that lists the per-monitor DPI awareness functions and what their parameters are. I need to import those into C# and call them from my window class. But I don't know which DLLs contain those functions! The documentation for the GetProcessDpiAwareness function, for example, does not indicate which DLL it's in. How do I find what the exports in the DLLs are? A: Right out of head, a dumb method: a binary search in C:\Windows\System32 for GetProcessDpiAwareness, then studying each occurrence with Dependency Walker for exports. This produces the result: GetProcessDpiAwareness is exported by SHCore.dll. One may also search the Windows SDK headers and libs, but in my case I haven't found GetProcessDpiAwareness, to my surprise. Another idea, run the following from the command line prompt: for %f in (%windir%\system32\*.dll) do dumpbin.exe /exports %f >>%temp%\__exports Then search %temp%\__exports for the API. A: I know it's been asked a while back. (Every time I Google it, this question comes up. So let me share my method.) If anyone wants to search for functions in DLLs, there's this tool that will do it for you. In case of the GetProcessDpiAwareness on my Windows 10 (64-bit) it is exported from shcore.dll like someone had already mentioned above. Here's the screenshot: Although I need to preface it by saying that it would be always prudent to refer to the function's documentation on MSDN instead. Currently you can find it at the bottom of each page: If you play around with the search that I showed above, you will notice that many of the system functions are exported from multiple DLLs (some of which are undocumented.) So if you just blindly go with whatever you find in a search app, you may run a risk of breaking your program in the future if Microsoft changes one of those undocumented functions. So use it only for your own research or curiosity. A: Usually functions that work with the same resources are in the same dll's. Look at another dpi function like GetDpiForMonitor and you will see it is in Shcore.dll Edit: After you find the dll this way you can double check using dependency walker to see what functions are exported from that dll.
{ "language": "en", "url": "https://stackoverflow.com/questions/21565739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Shiny dashboard, user authentication I am trying to include a shiny dashboard inside a code snippet I found (https://github.com/treysp/shiny_password) that wraps a shiny app inside functions to set up user authentication. This snippets works perfectly with fluidPage() but I noticed that it is not working when I wrap a dhasboardPage(): I try to log in, type in my username and my password, click on log in and then nothing happens, I am stuck on the login page. No error message in the console I use to fire up the server by calling runApp() Do you have any idea of what might cause this particular problem? Thanks in advance A: Here is a working example for you to start. This is a very basic implementation. * *In the test case the stored passwords are visible. You do not want to authenticate in this way. It is unsafe. You need to find a way to hash the passwords and match. There are some clues on Huidong Tian github link *I implemented the majority of the ui.r code in server.r. Not sure if there is a workaround. The drawback I notice is too many lines of code. It will be nice to break each side tab into a separate file. Did not try it myself yet. However, here is @Dean Attali superb shiny resource to split code ui.r require(shiny) require(shinydashboard) header <- dashboardHeader(title = "my heading") sidebar <- dashboardSidebar(uiOutput("sidebarpanel")) body <- dashboardBody(uiOutput("body")) ui <- dashboardPage(header, sidebar, body) server.r login_details <- data.frame(user = c("sam", "pam", "ron"), pswd = c("123", "123", "123")) login <- box( title = "Login", textInput("userName", "Username"), passwordInput("passwd", "Password"), br(), actionButton("Login", "Log in") ) server <- function(input, output, session) { # To logout back to login page login.page = paste( isolate(session$clientData$url_protocol), "//", isolate(session$clientData$url_hostname), ":", isolate(session$clientData$url_port), sep = "" ) histdata <- rnorm(500) USER <- reactiveValues(Logged = F) observe({ if (USER$Logged == FALSE) { if (!is.null(input$Login)) { if (input$Login > 0) { Username <- isolate(input$userName) Password <- isolate(input$passwd) Id.username <- which(login_details$user %in% Username) Id.password <- which(login_details$pswd %in% Password) if (length(Id.username) > 0 & length(Id.password) > 0){ if (Id.username == Id.password) { USER$Logged <- TRUE } } } } } }) output$sidebarpanel <- renderUI({ if (USER$Logged == TRUE) { div( sidebarUserPanel( isolate(input$userName), subtitle = a(icon("usr"), "Logout", href = login.page) ), selectInput( "in_var", "myvar", multiple = FALSE, choices = c("option 1", "option 2") ), sidebarMenu( menuItem( "Item 1", tabName = "t_item1", icon = icon("line-chart") ), menuItem("Item 2", tabName = "t_item2", icon = icon("dollar")) ) ) } }) output$body <- renderUI({ if (USER$Logged == TRUE) { tabItems( # First tab content tabItem(tabName = "t_item1", fluidRow( output$plot1 <- renderPlot({ data <- histdata[seq_len(input$slider)] hist(data) }, height = 300, width = 300) , box( title = "Controls", sliderInput("slider", "observations:", 1, 100, 50) ) )), # Second tab content tabItem( tabName = "t_item2", fluidRow( output$table1 <- renderDataTable({ iris }), box( title = "Controls", sliderInput("slider", "observations:", 1, 100, 50) ) ) ) ) } else { login } }) } A: I recently wrote an R package that provides login/logout modules you can integrate with shinydashboard. Blogpost with example app Package repo the inst/ directory in the package repo contains the code for the example app. A: @user5249203's answer is very useful, but as is will produce a (non-breaking) due to the passwords being the same. Warning in if (Id.username == Id.password) { : the condition has length > 1 and only the first element will be used A better (and simpler) solution may be to replace the 6 lines after: Password <- isolate(input$passwd) with if (nrow(login_details[login_details$user == Username & login_details$pswd == Password,]) >= 1) { USER$Logged <- TRUE }
{ "language": "en", "url": "https://stackoverflow.com/questions/44708473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to let excel VBA only run the next codes after the queries for data connection have finished refreshing? I realized that even if the Refresh of the query is done first and foremost, the code below the refresh query will run even before the database information is extracted completely. This will leave a gap on my analysis. A sample code is shown below: ActiveWorkbook.Connections("Query - Entries").Refresh Total_rows_OCVoucher = Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Range("B" & Rows.Count).End(xlUp).Row Total_rows_AccSummary = Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Range("A" & Rows.Count).End(xlUp).Row x = 1 For j = 2 To Total_rows_OCVoucher Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 1) = Format(Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 2), "Short Date") Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 2) = Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 3) Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 3) = Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 9) Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 4) = "Outflow" Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 5) = Application.WorksheetFunction.Text(Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 2), "mmmm") Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 6) = Year(Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 2)) Workbooks("Accounting Summary.xlsm").Worksheets("Compiled Expenses").Cells(Total_rows_AccSummary + x, 7) = Workbooks("Accounting Summary.xlsm").Worksheets("Voucher").Cells(j, 1) x = x + 1 Next j How do I let all queries to finish computing first before moving on to the next line of code? A: Replace: ActiveWorkbook.Connections("Query - Entries").Refresh with: With ActiveWorkbook.Connections("Query - Entries") .OLEDBConnection.BackgroundQuery = False .Refresh End With
{ "language": "en", "url": "https://stackoverflow.com/questions/49994127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TypeScript: Constant array as type definition I am working on a typescript project and struggle a bit with defining a fitting type. Context: I got the following constant inside my project: export const PROPERTYOPTIONS = [ { value: "tag", label: "Tag" }, { value: "composition", label: "Composition" }, { value: "solvent", label: "Solvent" }, { value: "allergen", label: "Allergen" }, { value: "category", label: "Category" }, { value: "other", label: "Other" }, ]; Now I want to define an interface: interface CreatePropertyModalState { type: { value: string; label: string }; } How can I define that the type of the type field is a member of PROPERTYOPTIONS? I want to dodge a type definition like: type: { value: "tag" | "composition" | ..... A: If you're not planning to change the contents of PROPERTYOPTIONS at runtime, you can mark it as immutable (as const) and define a type alias for it using typeof: export const PROPERTYOPTIONS = [ { value: 'tag', label: 'Tag' }, { value: 'composition', label: 'Composition' }, { value: 'solvent', label: 'Solvent' }, { value: 'allergen', label: 'Allergen' }, { value: 'category', label: 'Category' }, { value: 'other', label: 'Other' }, ] as const type PropertyOptions = typeof PROPERTYOPTIONS type PropertyOption = PropertyOption[number] interface CreatePropertyModalState { // if the type should be exactly one of the options type: PropertyOption, // if you want to combine an allowed value with an arbitrary label type: { value: PropertyOption['value'], label: string }, } A: You can use a generic identity function to constrain the type of the array, and then typeof with an indexed access type to extract the type you want. function checkArray<T extends string>(arr: {value: T, label: string}[]) { return arr; } export const PROPERTY_OPTIONS = checkArray([ { value: "tag", label: "Tag" }, { value: "composition", label: "Composition" }, { value: "solvent", label: "Solvent" }, { value: "allergen", label: "Allergen" }, { value: "category", label: "Category" }, { value: "other", label: "Other" }, ]); type PropertyOption = typeof PROPERTY_OPTIONS[number] // type PropertyOption = { // value: "tag" | "composition" | "solvent" | "allergen" | "category" | "other"; // label: string; // } interface CreatePropertyModalState { type: PropertyOption } Playground Link
{ "language": "en", "url": "https://stackoverflow.com/questions/72700877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: laravel custom command to generate file I came across this article on Spatie Actions https://freek.dev/1371-refactoring-to-actions and I would like to make a command to generate the files for me, similar how you can generate Model or livewire components etc. php artisan make:action PublishPostAction Post This is as far as I got <?php namespace App\Console\Commands; use Illuminate\Console\Command; class GenerateActionTemplate extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:action {name} {model}'; /** * The console command description. * * @var string */ protected $description = 'Create a new action file.'; /** * Execute the console command. * * @return int */ public function handle() { $name = $this->argument('name'); $model = $this->argument('model'); $fileContents = <<<'EOT' <?php namespace App\Actions; class PublishPostAction // name { private $post; public function execute(Post $post) // model { $this->post = $post; } } EOT; $this->info($name . 'has been created successfully!'); } } * *How would I do the logic, so if I do like make:action post.PublishPostAction would create a new folder called post in App\Actions\Post\ *In the EOT how would I pass in the variables? Any help or link to an example would be great! I have looked through a few tutorials and was able to scrap this up and laravel docs don't really show any example to generate a new file. A: Here is the full code to get this working. You need to create 2 files. // action.stub <?php namespace {{ namespace }}; use {{ namespacedModel }}; class {{ class }} { private ${{ modelVariable }}; public function execute({{ m }} ${{ modelVariable }}) { $this->{{ modelVariable }} = ${{ modelVariable }}; } } // makeAction.php <?php namespace App\Console\Commands; use Illuminate\Console\GeneratorCommand; use InvalidArgumentException; use Symfony\Component\Console\Input\InputOption; class makeAction extends GeneratorCommand { protected $signature = 'make:action {name} {--m=}'; protected $description = 'Create action file'; protected $type = 'Action file'; protected function getNameInput() { return str_replace('.', '/', trim($this->argument('name'))); } /** * Build the class with the given name. * * @param string $name * @return string */ protected function buildClass($name) { $stub = parent::buildClass($name); $model = $this->option('m'); return $model ? $this->replaceModel($stub, $model) : $stub; } /** * Replace the model for the given stub. * * @param string $stub * @param string $model * @return string */ protected function replaceModel($stub, $model) { $modelClass = $this->parseModel($model); $replace = [ '{{ namespacedModel }}' => $modelClass, '{{ m }}' => class_basename($modelClass), '{{ modelVariable }}' => lcfirst(class_basename($modelClass)), ]; return str_replace( array_keys($replace), array_values($replace), $stub ); } /** * Get the fully-qualified model class name. * * @param string $model * @return string * * @throws \InvalidArgumentException */ protected function parseModel($model) { if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) { throw new InvalidArgumentException('Model name contains invalid characters.'); } return $this->qualifyModel($model); } /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return app_path().'/Console/Commands/Stubs/action.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Actions'; } /** * Get the console command arguments. * * @return array */ protected function getOptions() { return [ ['model', 'm', InputOption::VALUE_OPTIONAL, 'Model'], ]; } } Command to run PHP artisan make:action task.AddTaskAction --m=Task it will create the following file <?php namespace App\Actions\task; use App\Models\Task; class AddTaskAction { private $task; public function execute(Task $task) { $this->task = $task; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/73656148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPF listbox is causing a stackoverflow when it has a button as a child When trying to add a button as the datatemplate to a listbox, I ran into a stackoverflow. When using a textbox instead, there is no stackoverflow. What is causing this? I'm using Visual Studios 2012 Update 4. XAML code: <Window x:Class="StackOverflowTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <ListBox ItemsSource="{Binding CausesStackOverflow}"> <ListBox.Resources> <DataTemplate DataType="{x:Type sys:String}"> <Button Content="{Binding Path=.}"/> </DataTemplate> </ListBox.Resources> </ListBox> </Window> C# code: namespace StackOverflowTest { public partial class MainWindow { public string[] CausesStackOverflow { get; set; } public MainWindow() { CausesStackOverflow = new string[] { "Foo" }; InitializeComponent(); DataContext = this; } } } A: Button is a ContentControl, which also uses a DataTemplate for its Content. A default DataTemplate ends up in recursively creating Buttons to display the "outer" Button's Content. You should set the ListBox's ItemTemplate explicitly: <ListBox ItemsSource="{Binding CausesStackOverflow}"> <ListBox.ItemTemplate> <DataTemplate> <Button Content="{Binding}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
{ "language": "en", "url": "https://stackoverflow.com/questions/35846917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Reflection dynamic path: ClassNotFoundException I'm trying to create an object dynamically using java reflection and when I try to execute Class.forName() it returns me the ClassNotFoundException, this is my code: Class cls = Class.forName("foo.bar.baz.turn."+ nextStateName); where nextStateName is the class name which I want to create. The strange thing is that if I try to do Class cls = Class.forName("foo.bar.baz.turn.nameclass"); it works. EDIT: this is the StackTrace java.lang.ClassNotFoundException: foo/bar/baz/turn/IncDecValue at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at foo.bar.baz.turn.Turn.setDynamicState(Turn.java:83) at foo.bar.baz.turn.ChooseDice1.receiveMove(ChooseDice1.java:47) at foo.bar.baz.turn.turn.Turn.receiveMove(Turn.java:286) at foo.bar.baz.turntest.ToolCard1Test.TestingCard(ToolCard1Test.java:158) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436) at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170) at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113) at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112) at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120) at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120) at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120) at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120) at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79) at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55) at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154) at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90) at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) EDIT*: This is a screenshot of my Maven project files using IntelliJ: Screenshot What am I doing wrong? A: In your stacktrace seem to be a lot of trailing spaces. Maybe something like this could help: //removes spaces as seen here: https://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java Class cls = Class.forName("foo.bar.baz.turn."+ (nextStateName.replaceAll("\\s+",""))); A: Your stacktrace reads: java.lang.ClassNotFoundException: foo/bar/baz/turn/IncDecValue. I have quickly tried to reproduce your problem and the exception which I had received has read java.lang.ClassNotFoundException: foo.bar.baz.turn.IncDecValue. Slashes being displayed instead of dots might indicate that your classes are located in directories instead of packages. Or at least it was so when the exception has occured.
{ "language": "en", "url": "https://stackoverflow.com/questions/50683111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Database design, how to setup tables I have a simple ecommerce type site that will have users with accounts, orders, and contact/billing information for those users. I just wanted to know the best way to setup these tables from an efficiency and logical point of view. So far I have basically two different entities, users and orders. Users will have basic account information like name and password, Orders will contain all the information about the certain order. My question is, should I include all contact/billing information within the User table or make two separate tables to contain contact and billing information? A: You might have to think about this a little more: Users have a contact and billing address, what about shipping and other addresses? Is it possible to have two users from one company, each with different contact addresses but the same billing address? Is it possible for one user to have multiple billing addresses that they will choose at the time of order? Then when it comes to your orders, what happens if a customer updates his billing address, and then you pull up an order from before the billing address changed. Should the billing address on the old order be the new one, or the one from the time of the order? If the problem is as simple as you describe, and a user simply has contact and billing addresses, and there are no other "what ifs", then it makes sense to just put those addresses in the user's table. From my limited experience in this domain, however, you may very well find that addresses need to be entities in their own right, separate from specific users. In fact, it may be that you think of a "user" as a "contact address". A: Contact, billing, and shipping (if needed) information are logically separate. From a pure normalization point of view, an address should be a separate entity, and you should have a relationship between Customers and Addresses. The most 'correct' approach from a normalization point of view would have a many-to-many relationship between Customers and Addresses, with a Type for differentiation between billing, contact and shipping addresses (assuming it's allowable to have more than one of each). You also need to consider your products as well. A common approach is to have an Order table, with a Lines table below it (one-to-many relationship from Order to Lines). Each Line will reference a single Product, with a Quantity, a Price and any other relevant information (discount, etc.). Simple pricing can be accomodated with a price entry in the products table; more complex pricing strategies will require more effort, obviously. Before anyone says I've gone too far: 'simple' sites often evolve. Getting your data model right beforehand will save you untold agony down the road. A: I think the contact information should be in the users table, there's no need to normalize it down to dedicated zip code tables etc. Its the same with the billing information, if they are perhaps creditcard number or something like this. If billing information means a certain plan, then i would put the different available plans into a seperate table and "link" it by a foreign key. A: If you'll be looking up contact and billing information at the same time and you'll rarely be using just one of them then there is no use separating them into different tables since you'll be joining them anyway. On the other hand, if you often only lookup one of contact or billing then performance might benefit from the separation. I, personally, would not separate them since I can't foresee many times where I don't want both of them. A: Will you have cases where a "user" could have multiple contacts? I've had database designs where a "customer" could have multiple contacts, and in such cases you should maintain a separate table for contacts. Otherwise, as the others said, you can keep the users and their contact information in the same table since you'll always be querying them together.
{ "language": "en", "url": "https://stackoverflow.com/questions/651450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ngx-translate failed to translate all keys The translations fails on some words (found at least 2 keys that don't work - 'Home' and 'Currency'). The funny thing is that the translation works, but not with all the items... I've checked the files, no duplicates found for those 2 items that i mentioned above Home and Currency don't work. The EN json: { "Dashboard": "Dashboard", "Sellers": "Sellers", "Products": "Products", "VAT": "VAT", "ProductCategory": "Product Categories", "ProductDispatch": "Product Dispatch", "ProductDispatchSellers": "Product Dispatch Sellers", "MeasurementUnits": "Measurement Units", "ProductsMasterData": "Products Master Data", "ConsignationProducts": "Consignation Products", "Documents": "Documents", "Orders": "Orders", "Invoices": "Invoices", "Cashings": "Cashings", "Customers": "Customers", "CustomerOffices": "Customer Offices", "PriceLists": "Price Lists", "Currencies": "Currencies", "CustomerCategories": "Customer Categories", "Routes": "Routes", "SalePromotions": "Sale Promotions", "Trucks": "Trucks", "TruckStocks": "Truck Stocks", "Storages": "Storages", "Calendar": "Calendar", "Consignation": "Consignation", "SalesByAgents": "Sales By Agents", "SalesByClients": "Sales By Clients", "SalesByRegion": "Sales By Region", "TransactionSales": "Transaction Sales", "Expenses": "Expenses", "Surveys": "Surveys", "Designer": "Designer", "TakeSurvey": "Take Survey", "ViewAnswers": "View Answers", "Messages": "Messages", "SendMessages": "Send Messages", "MessageLists": "Message Lists", "Activities": "Activities", "Target": "Target", "ClientActivities": "Client Activities", "Admin": "Admin", "Users": "Users", "Roles": "Roles", "XMLLayout": "XML Layout", "Reports": "Reports", "Settings": "Settings", "Add new record": "Add new record", "Add user": "Add user", "Add role": "Add role", "Login": "Login", "Password": "Password", "Confirm": "Confirm", "Person": "Person", "Role": "Role", "Save": "Save", "Close": "Close", "Info": "Info", "Success": "Success", "Warning": "Warning", "Error": "Error", "msgFillMandatory": "Please fill the mandatory fields", "Home": "Home", "Currency": "Currency" } The RO json: { "Dashboard": "Panou de bord", "Sellers": "Agenti", "Products": "Produse", "VAT": "TVA", "ProductCategory": "Categorii produse", "ProductDispatch": "Livrare produse", "ProductDispatchSellers": "Livrare produse vanzatori", "MeasurementUnits": "Unitati de masura", "ProductsMasterData": "Produse", "ConsignationProducts": "Produse de consignatie", "Documents": "Documente", "Orders": "Comenzi", "Invoices": "Facturi", "Cashings": "Incasari", "Customers": "Clienti", "CustomerOffices": "Sedii clienti", "PriceLists": "Liste de preturi", "Currencies": "Valute", "CustomerCategories": "Categorii de clienti", "Routes": "Rute", "SalePromotions": "Promotii", "Trucks": "Vehicule", "TruckStocks": "Stoc vehicule", "Storages": "Gestiuni", "Calendar": "Calendar", "Consignation": "Consignatii", "SalesByAgents": "Vanzari agenti", "SalesByClients": "Vanzari clienti", "SalesByRegion": "Vanzari regiuni", "TransactionSales": "Tranzactii vanzari", "Expenses": "Cheltuieli", "Surveys": "Sondaje", "Designer": "Designer", "TakeSurvey": "Completare sondaj", "ViewAnswers": "Vizualizare raspuns", "Messages": "Mesaje", "SendMessages": "Trimitere mesaj", "MessageLists": "Liste mesaje", "Activities": "Activitati", "Target": "Target", "ClientActivities": "Activitati la clienti", "Admin": "Admin", "Users": "Useri", "Roles": "Roluri", "XMLLayout": "XML Layout", "Reports": "Rapoarte", "Settings": "Setari", "Add new record": "Adauga inregistrare noua", "Add user": "Adaugare utilizator", "Add role": "Adaugare rol", "Login": "Login", "Password": "Parola", "Confirm": "Confirmare", "Person": "Persoana", "Role": "Rol", "Save": "Salveaza", "Close": "Inchide", "Info": "Info", "Success": "Succes", "Warning": "Avertizare", "Error": "Eroare", "msgFillMandatory": "Completati campurile obligatorii", "Home": "Acasa", "Currency": "Valuta" } The html sections are: <div class="title-div"> <label translate>Currency</label> </div> and also: <div class="breadcrumb-div"> <mat-icon>home</mat-icon> <label>{{'Home' | translate:param }}</label> </div> A: Apparently the issue was caused by the fact that an old version of the translation jsons was cached in the dist folder of my Angular project. Once I deleted it it all went fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/55377212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create checkboxes dynamically for selected dates of a calendar With JavaScript or with Ajax I need to enter the start date with the start time, and the end date with end time. And create four checkboxes for each day of the selected date range, in-line with the date mentioned in front. BUT the last checkbox of the last raw should not be clickable/selectable IF it is not a complete day with 24 hours in full. Which means if the difference between two entered times are lesser than 1 minute. Please help. It’s complicated for me. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script> <strong>Start</strong> <br>Date: <input id="fromDate" type='date' />&nbsp;&nbsp;Time: <input type="time" id="start-time" placeholder="HH:MM"> <br><br><br> <strong>End</strong> <br>Date: <input id="toDate" type='date' />&nbsp;&nbsp;Time: <input type="time" id="end-time" placeholder="HH:MM"> <button id="btn">Submit</button><hr /> <p id="result"></p> <script> $("#btn").on('click', function(e) { var fromDate = $('#fromDate').val(), toDate = $('#toDate').val(), from, to, druation; from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date to = moment(toDate, 'YYYY-MM-DD'); // format in which you have the date /* using diff */ duration = to.diff(from, 'days') /* show the result */ $('#result').text(duration + ' days'); }); </script> <br> <input type="text" id="total-hours" placeholder="Total Hours"> <script> document.querySelector("#end-time").addEventListener("change", myFunction); function myFunction() { function split(time) { var t = time.split(":"); return parseInt((t[0] * 60), 10) + parseInt(t[1], 10); //convert to minutes and add minutes } //value start var start = split($("input#start-time").val()); //format HH:MM //value end var end = split($("input#end-time").val()); //format HH:MM totalHours = NaN; if (start < end) { totalHours = Math.floor((end-start)/60); } $("#total-hours").val(totalHours); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/72778212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selenium python how I preform a click on toggle button I am trying to click in call loop toggle with Selenium with the WebDriver on Python. the html code: this is the button: I have tried few options: button_element = driver.find_element_by_class_name("iPhoneCheckContainer") button_element.click() the filed message: Traceback (most recent call last): File "C:\Users\kosti\PycharmProjects\test1\main.py", line 50, in <module> element = driver.find_element_by_xpath("//input[@id='on_off_on']").click() File "C:\Users\kosti\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "C:\Users\kosti\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute return self._parent.execute(command, params) File "C:\Users\kosti\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\kosti\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <input type="checkbox" id="on_off_on" value="1" name="AllowReset" checked=""> is not clickable at point (171, 261). Other element would receive the click: <div class="iPhoneCheckHandle" style="width: 30px; left: 30px;">...</div> (Session info: chrome=88.0.4324.150) A: elem=driver.find_element_by_id("on_off_on") driver.execute_script("arguments[0].click();",elem) Try targeting the input id instead. A: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC elem=WebDriverWait(driver,5000).until(EC.visibility_of_element_located( (By.XPATH, "//input[@id='on_off_on']"))) driver.execute_script("arguments[0].scrollIntoView();",elem) element.click() Try using webdriver wait
{ "language": "en", "url": "https://stackoverflow.com/questions/66179401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Splashscreen orientation wrong since iOS 9.x As described in 34942234 and 34919547 I am fighting with a wrong splashscreen orientation since longer. I am pretty sure I have nailed down the root cause, which has to do with iOS 9.x (I am using iOS 9.2). When running the identical code in XCode/iOS simulator with iOS 8.4 the splashscreen is shown in Landscape orientation as expected. Testing the entire project as .ipa-file on my iPhone 5 with iOS 9.2 provides the same problem (unfortunately I have no device with ioS 8.x installed). My questions are: What to do next? In case of opening a support ticket with Apple - will it be free of charge in case it turns out to be a bug (which is my educated guess)? A: I have opened a bug report with Apple now; will see what their answer is...
{ "language": "en", "url": "https://stackoverflow.com/questions/35172244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing .NET framework from USB drive when necessary We have a .NET application that will be distributed through USB drive. End users will connect the drive and double click on the EXE (a .NET exe) to run it WITHOUT installing it. Now the problem is, if .NET is not installed we would like to trigger the .NET installer instead of showing the default download message that MS has put there. The installer will be distributed with the application through the USB. One way to do it might be by replacing the PE stub file in the .NET executable. But I am not seeing and /STUB switch in C# compiler (though C compilers had it). Anything else anyone can think of? Update: Thanks to Tim Robinson, I understand that Windows doesn't process the PE stub file. Therefore the ClickOnce solution seems the only viable one left. I shall be checking ClickOnce. A: Why not use ClickOnce, and it will do all that for you. A: You may want to check out this Episode of Hanselminutes http://www.hanselman.com/blog/HanselminutesPodcast138PaintNETWithRickBrewster.aspx He talks with the creator of Paint.NET who ends up doing some pretty creative things with the installer.
{ "language": "en", "url": "https://stackoverflow.com/questions/852550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prestashop localization fail to Import a localization pack Prestashop (1.6.1.10) localization fail to Import a localization pack (Israel) I get [PrestaShopException] Property Currency->decimals is not valid at line 909 in file classes/ObjectModel.php 904. } 905. 906. $message = $this->validateField($field, $this->$field); 907. if ($message !== true) { 908. if ($die) { 909. throw new PrestaShopException($message); 910. } 911. return $error_return ? $message : false; 912. } 913. } 914. ObjectModelCore->validateFields - [line 299 - classes/LocalizationPack.php] LocalizationPackCore->_installCurrencies - [line 97 - classes/LocalizationPack.php] - [1 Arguments] LocalizationPackCore->loadLocalisationPack - [line 203 - controllers/admin/AdminLocalizationController.php] - [4 Arguments] AdminLocalizationControllerCore->postProcess - [line 178 - classes/controller/Controller.php] ControllerCore->run - [line 367 - classes/Dispatcher.php] DispatcherCore->dispatch - [line 58 - admin/index.p This is used to work in the passed, I think something is broken in the language page A: Here is how I by-pass the issue: In the IMPORT A LOCALIZATION PACK form, uncheck Currency. Import the pack, and create the currency manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/42249756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS span wrap with padding I've got a pretty annoying problem. I have to make a "table" fwhich containes 3 elements next to each other. The first 2 elements are simple divs, floated left, but the third is a little bit complicated. It must have padding on each sides. By the way, it's a text which can be wrapped by the end of the line. My problem is that when this element breaks at the end of the first line and the beginning of the second line do not have padding attributes. I've made a simple example page here. Do you have any solutions for me? I've tried so many different ways... When the space next to the third element is empty, it's OK, but when I prepend the boxes its completely broken. A: Do you need the width to be dynamic or can it be fixed in size? I would remove the spans, float div.inner and hardcode its width. Something like this: .container { overflow: hidden; } .inner { float: left; padding: 7px; width: 106px; /* you could use percentages to fix the widths if you'd like to keep things dynamic. */ } You could just adjust the padding and avoid setting the border all together. Setting overflow to hidden on the container will force the container element to fit all of the floated elements inside of it. This allows you to avoid inserting a div to clear the floated elements. You could also express this as a nested list as it's best to avoid unnecessary divs: <ol id="examples_list"> <li> <ul class="container"> <li class="box">...</li> <li class="box">...</li> <li class="inner">...</li> </ul> </li> </ol> with... #examples_list, #examples_list ul { list-style: none; margin: 0; padding: 0; } To style it in a similar fashion. A: Ok, based on @b_benjamin response to a comment above, I think I might have one possible solution but I also think it will rely on some CSS that might not play well in older browsers, but it's a simple concept that can probably be adjusted with other tricks. This seems to work in the latest FF, Chrome and IE9. First, the HTML: <div style="width:340px;"> <!-- a list of text, with some time's marked up --> <ul class="sched"> <li><b>17:55</b><b>18:10</b> <a href="#">Lorem ipsum dolor</a> sit posuere.</li> <li><b>18:20</b><b>18:30</b> <a href="#">Lorem ipsum dolor</a> sit amet orci aliquam.</li> <li><b>18:20</b><b>18:30</b> <a href="#">Class aptent</a> taciti sociosqu ad sed ad.</li> <li><b>19:05</b><b>19:17</b> <a href="#">Mauris et urna et</a> ante suscipit ultrices sed.</li> <li><b>19:05</b><b>19:17</b> <a href="#">Proin vulputate pharetra tempus.</a> Quisque euismod tortor eget sapien blandit ac vehicula metus metus.</li> </ul> </div> Now some CSS: (I used a simple color theme based on b_benjamin's sample photo) /* reset default list styles */ .sched, .sched li{ list-style:none; font-size:14px; padding:0; margin:0; } .sched li{ position:relative; padding:0 10px; margin:10px 0; background:#631015; color:#FFF; } .sched b{ position:relative; left:-10px; display:inline-block; padding:2px 10px; font-weight:none; background:#FFF; color:#666; } /* some light styling for effect */ body{ background:#cc222c; } .sched li a{ color:#FF9; } Explanation: The box model requires a certain thought process on how to achieve padding on inline elements (text). One thing you can do is simply put padding around the entire containing box. In my concept, I used a UL list and each LI element is the container. I used a 10px padding on the container. .sched li{ padding:0 10px; } This will give us our padding, but it will cause our "time" elements to also have this padding. My "trick" is to "fix" this by using a negative relative position equal to the padding: .sched b{ display:inline-block; /* make these items act like block level elements */ position:relative; /* give the b elements a relative position*/ left:-10px; /* offset them equal to the padding */ } There's one last thing to do and that's to make sure the parent element is also position:relative so the child element will use it's containing dimensions: .sched li{ position:relative; /* needed for B elements to be offset properly */ padding:0 10px; } Here's a snip of what it looks like on Chrome. You can, of course, play around with padding. There's probably also some solutions to make the "B" elements float, but this seemed to work well. I hope that helps! A: Ben, I don't understand why you would use two spans wrapped around the same element. Also, I rarely use spans because of their fickleness. From what I understand you want 3 blocks sitting side by side with the last element to be padded a little bit. I would suggest simply adding an extra class to the padded div (or an id). Try this... [HTML] <h2>double span with floated elements next to it</h2> <div class="box">box #1</div> <div class="box">box #2</div> <div class="box boxPadded"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus laoreet. </div> <div class="cleaner"></div> [CSS] .cleaner{clear: left; line-height: 0; height: 0;} .box{margin-right: 5px; width: 100px; min-height: 25px; float: left;} .boxPadded{padding: 3px 3px 9px 3px; word-wrap: break-word;} So, now the third element has the attributes of the "box" class as well as it's own separate attribute "boxPadded". The "min-height" is mainly for the third element. You can actually put it in the boxPadded class, but I'm a bit lazy. It will allow the element to stretch long if the text is larger than the element. The "cleaner" is something I use after I float elements. Its' usually not needed unless you have elements in the floated element. The "word-wrap" will allow a non space string that is longer than the element to wrap around the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/9115757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }