text
stringlengths
15
59.8k
meta
dict
Q: Add a dot (marker) without y-axis value on the existing graph I have a graph of my stocks portflio over some period of time, which looks like this: I have a price for every 5 minutes of time, so x data is timestamps and y data is just numbers. I also have a dataframe with times of operations, which contains a time of operation and its type (bought or sold) and looks like this: I want to add a dot or some kind of a marker for every operation on my graph, but i don’t know how to do this, I don’t have y-values for it. And timestamps x-values are different from operations x-values, so i can’t just take y-values from an existing graph. This is how I imagine it ideally, but for starters i just want to understand how to add my points on the graph: . I'm using plotly, but i don't care if the solution requries matplotlib or anything else. A: This is definitely doable in Plotly using annotations. There don't have to be y-values for the operations DataFrame because you can use the corresponding y-value from the stock data at the operations x-values. To plot the red markers, you can plot the operations_df and set the marker attributes as you like. Then you can loop through the operations_df and place an annotation on the scatterplot based on the date of the entry, and its corresponding y-value on the stocks portfolio. Here is an example with some made up data, so you may need to tweak this code for your DataFrames. import numpy as np import pandas as pd import plotly.graph_objs as go ## create some random data np.random.seed(42) df = pd.DataFrame( data=500*np.random.randint(0,1000,24), columns=['price'], index=pd.date_range(start='12/1/2020', end='12/1/2020 23:00:00', freq='H') ) operations_df = pd.DataFrame( data=['Buy','Sell','Buy'], columns=['Operation_type'], index=pd.to_datetime(['12/1/2020 08:00:00', '12/1/2020 12:00:00', '12/1/2020 16:00:00']) ) fig = go.Figure(data=[go.Scatter( x=df.index, y=df.price )]) fig.add_trace(go.Scatter( x=operations_df.index, y=[df.loc[date, 'price'] for date in operations_df.index], mode='markers', marker=dict( size=16, color="red") )) for date, row in operations_df.iterrows(): # print(date, df.loc[date, 'price'], row['Operation_type']) fig.add_annotation( x=pd.to_datetime(date), y=df.loc[date, 'price'], xref="x", yref="y", font=dict( size=16, color="red" ), text=row['Operation_type'], bordercolor="red", width=80, height=60, arrowcolor="red", ax=0, ay=-150 ) fig.update_layout(showlegend=False) fig.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/65100088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Minute by minute breakdown of log data I have a table (Excel sheet, whatever...) containing PeopleSoft login information with three columns: Login Time, Logout Time, Time Spent. My manager has been asked to use that to provide a minute by minute run down of concurrent logins for the entire data set (day). So, the SELECT for the table is like so: SELECT LOGIN.Login, LOGIN.[Log out], LOGIN.[Time in] FROM LOGIN; Output looks like this: Login Log out Time in 11/1/10 12:36 AM 11/1/10 12:42 AM 0:06 ... What I need is: Time Concurrent_Logins 11/1/10 12:36 AM 16 ... So, this is quite complicated. Any thoughts? A: What you'll want to do is build a table that contains every minute for the day. There are a number of ways you can do this, just search for "tally table", etc. Once you have a table containing all of your minutes (in datetime format), it should be straightforward. Join your login table to the minutes table on minute between login/logout and do a count(*) for each minute. A: Derek's solution is the way to go. http://www.ridgway.co.za/archive/2007/11/23/using-a-common-table-expression-cte-to-generate-a-date.aspx explain a way to generate on the fly the timetable SET DATEFORMAT DMY GO DECLARE @STARTDATE DATETIME DECLARE @ENDDATE DATETIME SELECT @STARTDATE = '02/01/2011 01:00', @ENDDATE = '03/01/2011 01:00' ; WITH DateRange(MyDateTime) AS ( SELECT @STARTDATE AS MyDateTime UNION ALL SELECT DATEADD(minute, 1, MyDateTime) AS MyDateTime FROM DateRange WHERE MyDateTime < @ENDDATE ) SELECT MyDateTime, ConcurrentConnections = COUNT(*) FROM DateRange INNER JOIN [LOGIN] ON MyDateTime >= [LogIn] AND MyDateTime <= [Log Out] OPTION (MaxRecursion 10000); A: To solve this problem I would first get the min and the max datetime values from the dataset. This would provide the time range from which we will need to determine the count of concurrent logins. After getting the time range, I would do a loop to populate a table with each minute in the range and the count of concurrent logins for that minute. After populating the table I would select from it where concurrent login count > 0, this would be my result set. I use SQL Server, you may need to convert some of the syntax to another DBMS. -- To get the min and max of the time range DECLARE @min datetime, @max datetime SELECT @min = MIN(l.[Login]), @max = MAX(l.[Log out]) FROM [LOGIN] l -- now make a table to how the minutes and the counts CREATE TABLE #Result ( [Time] datetime, [count] int ) -- now do a loop to fill each minute between @min and @max DECLARE @currentTime datetime, @count int SELECT @currentTime = @min, @count = 0 -- go from @min to @max WHILE @currentTime < @max BEGIN -- get the count of concurrent logins for @currentTime SELECT @count = COUNT(*) FROM [LOGIN] l WHERE @currentTime between l.[Login] and l.[Log out] -- insert into our results table INSERT #Result ([Time], [count]) VALUES (@currentTime, @count) -- increment @currentTime for next pass SELECT @currentTime = DATEADD(minute, 1, @currentTime) END -- select final result (where count > 0) SELECT * FROM #Result WHERE [count] > 0 -- clean up our temp table DROP TABLE #Result
{ "language": "en", "url": "https://stackoverflow.com/questions/7917380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: React DnD drags whole list of cards instead of single card I am trying to use react DnD in my react Project. In my render method I define a variable named Populate like show below, which returns a list of cards like this render() { var isDragging = this.props.isDragging; var connectDragSource = this.props.connectDragSource; var Populate = this.props.mediaFiles.map((value) => { return( <div> <MuiThemeProvider> <Card style= {{marginBottom: 2, opacity: isDragging ? 0 : 1}} id={value.id} key={value.id} onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut} //onTouchTap={() => {this.handleClick(value.id)}} zDepth={this.state.shadow}> <CardHeader title={value.Episode_Name} //subtitle={value.description} actAsExpander={false} showExpandableButton={false} /> </Card> </MuiThemeProvider> </div> ) }); And my return of render method looks like this return connectDragSource ( <div> <MuiThemeProvider> <div className="mediaFilesComponent2"> {Populate} </div> </MuiThemeProvider> </div> ) Problem is when I try using drag, then the whole list of cards gets selected for drag. I want all the cards having individual drag functionality. A: If you want each card to have drag functionality than you'll have to wrap each card in a DragSource, and not the entire list. I would split out the Card into it's own component, wrapped in a DragSource, like this: import React, { Component, PropTypes } from 'react'; import { ItemTypes } from './Constants'; import { DragSource } from 'react-dnd'; const CardSource = { beginDrag: function (props) { return {}; } }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() } } class CardDragContainer extends React.Component { render() { return this.props.connectDragSource( <div> <Card style= {{marginBottom: 2, opacity: this.props.isDragging ? 0 : 1}} id={value.id} key={value.id} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} zDepth={this.props.shadow}> <CardHeader title={props.title} actAsExpander={false} showExpandableButton={false} /> </Card> </div> ) } } export default DragSource(ItemTypes.<Your Item Type>, CardSource, collect)(CardDragContainer); Then you would use this DragContainer in render of the higher level component like this: render() { var Populate = this.props.mediaFiles.map((value) => { return( <div> <MuiThemeProvider> <CardDragContainer value={value} onMouseOver={this.onMouseOver} onMouseOut={this.onMouseOut} shadow={this.state.shadow} /> </MuiThemeProvider> </div> ) }); return ( <div> <MuiThemeProvider> <div className="mediaFilesComponent2"> {Populate} </div> </MuiThemeProvider> </div> ); } That should give you a list of Cards, each of which will be individually draggable.
{ "language": "en", "url": "https://stackoverflow.com/questions/40649732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add multiple route filters in Laravel 4.2 while using role:permission pattern? I am having issues with using multiple route filters in Laravel 4.2 while using the pattern role:permission. I've attached my code below. This doesn't work at all. When I change roles, it always give one 403 unauthorized. I want both moderator and administrator to access this route. Perhaps there's a way to tell Laravel, "if the logged in user is either an administrator OR a moderator, then let them access this route". Route::get('engage', [ 'as' => 'engage_path', 'before' => 'role:administrator', 'before' => 'role:moderator', 'uses' => 'ManagementController@showEngagement' ]); This is my role filter. Route::filter('role', function($route, $request, $role) { if (Auth::guest() or ! Auth::user()->hasRole($role)) { return Response::make('Unauthorized', 403); } }); A: I suggest you use some kind of delimiter, like a ; to pass in multiple roles. 'before' => 'role:administrator;moderator' And change the filter: Route::filter('role', function($route, $request, $value) { if(Auth::check()){ $user = Auth::user(); $roles = explode(';', $value); foreach($roles as $role){ if($user->hasRole($role)){ return; } } } return Response::make('Unauthorized', 403); });
{ "language": "en", "url": "https://stackoverflow.com/questions/27714784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I populate a MemoryCache without instantiating the object to be cached unneccesarily? The MemoryCache class exposes a method called .AddOrGetExisting which is a threadsafe way to get if exists, and add if it doesn't exist. This method returns NULL if the cached object didn't already exist. I think I understand the value of this because it provides feedback to the user regarding its existence in the cache. My cache resolver looks like this: private static T GetCachedCollection<T>(Guid cacheKey, Lazy<T> initializer) { return (T) (MemoryCache.Default.AddOrGetExisting(cacheKey.ToString(), initializer.Value, _policy) ?? initializer.Value); } What I am trying to accomplish is that the object is not created unless it is needed, and if it is needed I don't want to construct it twice. The concern I have is that when I pass the .Value of my Lazy type as a parameter it may invoke the initializer regardless of whether the item is found in cache or not. However, if I understand JIT properly it will pass the delegate of the method and not invoke it. How should I accomplish these goals: * *Do not invoke the object initializer if it already exists in cache *If it is not in the cache then invoke it only one time. A: Don't store the object in the cache, store the Lazy. private static T GetCachedCollection<T>(Guid cacheKey, Lazy<T> initializer) { var cachedValue = (Lazy<T>)(MemoryCache.Default.AddOrGetExisting( cacheKey.ToString(), initializer, _policy) ?? initializer); return cachedValue.Value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/26533612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Resizing images and displaying side by side with justification I have created an HTML template, to which I will push data from SQL using python and print it as pdf. The document needs to be printed always in landscape. I have achieved the functionality, but the logo on the right gets offset by an awkward amount and looks odd. Please find the image as below: However, if I don't resize the image, the spaces are somewhat even but the image is too big, as below: My code is as below <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> <style> body { background-color: powderblue; } @media print { @page { size: landscape; } }/*required because this page will always have to be printed in landscape */ .Row{ display: flex; } .Cell{ align-items: center; } .Cell h1{ align-items: center; text-align: center; } .Cell h2{ text-align: center; } .Cell .logo{ width: 30%; height: auto; } </style> </head> <body> <div class="Row"> <div class="Cell"> <img src="logo1.jpg" alt="logo1" class="logo"> </div> <div class="Cell"> <h1>THIS IS A VERY LONG MAIN HEADING XXX</h1> <h2>THIS IS A SUBHEADING</h2> <br> <h2>ANOTHER SUB HEADING</h2> </div> <div class="Cell"> <img src="logo2.jpg" alt="logo2" class="logo"> </div> </div> </body> </html> If anyone could point out to me how to make the logo equidistant from the headings, it would be much appreciated. A: I have reconstructed your code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> <style> body { background-color: powderblue; } @media print { @page { size: landscape; } }/*required because this page will always have to be printed in landscape */ .Row{ display: flex; flex-direction: row; /* align-items: center; */ justify-content: center } .Cell{ /* justify-content: center */ align-items: center; text-align:center; } .Cell .logo{ width: 30%; height: auto; } </style> </head> <body> <div class="Row"> <div class="Cell"> <img src="https://i.picsum.photos/id/173/200/200.jpg?hmac=avUVgEVHNuQ4yZJQhCWlX3wpnR7d_fGOKvwZcDMLM0I" alt="logo1" class="logo"> </div> <div class="Cell"> <h1>THIS IS A VERY LONG MAIN HEADING XXX</h1> <h2>THIS IS A SUBHEADING</h2> <br> <h2>ANOTHER SUB HEADING</h2> </div> <div class="Cell"> <img src="https://i.picsum.photos/id/173/200/200.jpg?hmac=avUVgEVHNuQ4yZJQhCWlX3wpnR7d_fGOKvwZcDMLM0I" alt="logo2" class="logo"> </div> </div> </body> </html> This below link will guide you much better way: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ A: Setting the width of <img> elements to percentage value is a little confusing because their containers don't have a specified width, so it isn't clear what the width should be. I assume you wanted the first and last .Cell to be 30% wide, but logos smaller and pushed to the opposite ends of the page. I set the width of the logos to be 100px, but you can tweak that as you like. The key part is pushing the logo in the last .Cell to the right, one way to do it using Flexbox: .Cell:last-child { display: flex; align-items: flex-start; justify-content: flex-end; } The align-items declaration is there so that the logo doesn't stretch to take up the height of the container. I also removed some of the the align-items declarations from your code that weren't doing anything because they weren't Flex containers. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> <style> body { background-color: powderblue; } @media print { @page { size: landscape; } } .Row { display: flex; justify-content: center } .Cell h1{ text-align: center; } .Cell h2{ text-align: center; } .Cell:first-child, .Cell:last-child { width: 30%; } .Cell:last-child { display: flex; align-items: flex-start; justify-content: flex-end; } .Cell img { width: 100px; height: auto; } </style> </head> <body> <div class="Row"> <div class="Cell"> <img src="https://i.picsum.photos/id/173/200/200.jpg?hmac=avUVgEVHNuQ4yZJQhCWlX3wpnR7d_fGOKvwZcDMLM0I" alt="logo1" class="logo"> </div> <div class="Cell"> <h1>THIS IS A VERY LONG MAIN HEADING XXX</h1> <h2>THIS IS A SUBHEADING</h2> <br> <h2>ANOTHER SUB HEADING</h2> </div> <div class="Cell"> <img src="https://i.picsum.photos/id/173/200/200.jpg?hmac=avUVgEVHNuQ4yZJQhCWlX3wpnR7d_fGOKvwZcDMLM0I" alt="logo2" class="logo"> </div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/73157422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't WebAPI2 with Entity Framework automatically create a transaction for me? I have a WebAPI2 Restful services API and I am using SQL Server database with Entity Framework. I have PUT methods like this /* * This changes the Study Status. */ [HttpPut, Route("ResponseSetStatus/{id:int}")] public IHttpActionResult UpdateResponseSetStatus(int id, [FromUri] string status = null) { var db = new MyContext(MyContext.EntityContextString); var responseSet = db.ResponseSets.FirstOrDefault(x => x.ResponseSetId == id); if (responseSet == null) { return NotFound(); } // ADD ONE SECOND DELAY HERE FOR TESTING Thread.Sleep(1000); responseSet.Status = status; db.SaveChanges(); return Ok(); } I thought this would work! But it fails. One of the columns in the database is a rowVersion (to prevent lost updates). When I call this function from multiple clients I get exception... An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code because of rowVersion mismatch. Do I really need an explicit transaction for all my update apis? I thought the framework is supposed to do that for me. A: Since no one has answered, I will. Yes, WebAPI2 does not wrap the call in a transaction. That would be silly, if you think about it. Also the code using (var db = new MyContext()) { // do stuff } does not implicitly create a transaction. Therefore, when you implement a RESTFUL PUT method to update your database, you have three options: (1) call db.SaveChanges() one time only and hope for the best, as the OP code, or (2) you can add a rowVersion column, and call db.SaveChanges() with try-catch in a loop, or (3) you can create an explicit transaction. In my opinion, option 1 is evil, and option 2 is a terrible hack that was invented because transactions did not exist prior to EF6. The correct way to implement Update: [HttpPut, Route("ResponseSetStatus/{id:int}")] public IHttpActionResult UpdateResponseSetStatus(int id, [FromUri] string status = null) { using (var db = new MyContext(MyContext.EntityContextString)) { using (var tran = db.Database.BeginTransaction()) { var responseSet = db.ResponseSets.FirstOrDefault(x => x.ResponseSetId == id); if (responseSet == null) { return NotFound(); } // ADD ONE SECOND DELAY HERE FOR TESTING Thread.Sleep(1000); responseSet.Status = status; tran.Commit(); } } return Ok(); } Please note that try-catch is not necessary. If anything fails, the using tran will automatically rollback, and the WebAPI2 will send a nice 500 response to the client. p.s. i put the db = new MyContext also in using, because it's the right way to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/36803359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rewrite multiple rules in .htaccess / remove .html extension I am trying to add another RewriteRule in my .htaccess file in addition to one I have in there. Currently I have: RewriteEngine On RewriteCond %{HTTP_HOST} websitename\.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://websitename.com/$1 [R,L] and I would like to add this rule in there: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.html [NC, L] I left out the additional 'RewriteEngine On' and pasted the other 3 lines underneath, but it is not working. The code I have initially is to direct my website to https:// so the security shows up no matter how you type in the address. But I also ran into the issue of my pages having .html after them in the index bar. Upon looking up how to remove that I read that one way is to remove the .html in all my href's in my code, and then to add this mod rewrite to my .htaccess, but so far with no success.
{ "language": "en", "url": "https://stackoverflow.com/questions/61331904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add a new column to each dataset in a list I have looked at some similar questions but they haven't really helped. I have a list with 4 datasframes and I would like to add a column to each of the 4 dataframes. below are a few of the commands that I've tried. they all just result in a list of 4 vectors (just the diversity). abundance_tables<-lapply(abundance_tables,function(tab) tab$diversity<-diversity(tab) ) abundance_tables<-mapply(function(tab) tab$diversity<-diversity(tab),abundance_tables,SIMPLIFY = F ) any help is appreciated. thanks A: You don't provide sample data, so I'm generating a sample list of 4 data.frames. lst <- lapply(1:4, function(x) data.frame(one = LETTERS[1:4], two = 1:4)) We add a third column to every data.frame in the list. lapply(lst, function(x) { x$three = letters[11:14]; x }) #[[1]] # one two three #1 A 1 k #2 B 2 l #3 C 3 m #4 D 4 n # #[[2]] # one two three #1 A 1 k #2 B 2 l #3 C 3 m #4 D 4 n # #[[3]] # one two three #1 A 1 k #2 B 2 l #3 C 3 m #4 D 4 n # #[[4]] # one two three #1 A 1 k #2 B 2 l #3 C 3 m #4 D 4 n Note that we need to return x, to get the data.frame with the added column.
{ "language": "en", "url": "https://stackoverflow.com/questions/50615909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Large infinity symbol in matplotlib Im creating a plot which has a subsript infinity symbol: Plot with infinity symbol import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) plt.rcParams.update({'font.size':16}) plt.title('U$_\infty$') plt.show() I want to make the infinity symbol larger, but without changing the size of U. Is there a unicode for a large infinity symbol or some other method that I can use? A: you can use the unicode character ‘U+221E’ to represent the large infinity symbol. To use this unicode in your plot, you can use the following code: import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,10)) plt.rcParams.update({'font.size':16}) plt.title(u'U\u221E') plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/74725162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep the same precision in these two numpy array procedures? Using f and x, In [173]: f Out[173]: array(1387) In [174]: x Out[174]: array([ 20404266.1330007]) exponent1 and exponent2 are computed and compared. exponent1 is computed as follows: In [183]: exponent1 = 1j * 2 * np.pi * f[..., np.newaxis, np.newaxis] * x exponent2 is computed as follows: In [186]: exponent2 = np.array([[[ 1.+0.j]]]) In [187]: exponent2 *= x[np.newaxis, ...] In [188]: exponent2 *= f[..., np.newaxis, np.newaxis] In [192]: exponent2 *= 1j * 2 * np.pi exponent1 and exponent2 are close: In [195]: np.allclose(exponent1, exponent2) Out[195]: True But their exponentials are not: In [196]: np.allclose(np.exp(exponent1), np.exp(exponent2)) Out[196]: False Is there a way to make their exponentials close as well? I would like the latter to be closer to the former because In [198]: np.allclose(np.exp(exponent1), np.exp(1j * 2 * np.pi * 1387 * 20404266.1330007)) Out[198]: True A: Your problem is finite precision and, as presented, there is nothing you can do about it. In your problem you are calculating 2*pi*f*x. Since this appears in a function with period 2*pi, the complex exponential, the only significant part of f*x are the digits after the decimal point. In other words, the information in f*x is only contained in the values in the interval [0,1) so we can think of really needing to calculate f*x modulo 1.0. If we look at the values you provide we find f*x = 28300717126.4719(73) where I have put the "extra" digits, beyond the first 15, in parenthesis. (Roughly we expect about 15 digits of precision, you can be more careful with this if you care but this is sufficient to get the point across.) We thus see that we are only calculating f*x to 4 significant digits. If we now compare the values calculated in your question we find exponent1 = 177818650031.694(37) exponent2 = 177818650031.694(4) where I again have used parenthesis for the extra digits. We see these values agree exactly as we expected them to. For the exponential version we are interested in these values modulo 2*pi, exponent1%(2*pi) = 2.965(4796216371864) exponent2%(2*pi) = 2.965(5101392153114) where now the parenthesis are for the extra digits beyond the 4 significant ones we expected. Again, perfectly good agreement to the level we can expect . We cannot do better unless x and f are calculated in such a way to not have all these extra, unnecessary digits "wasting" our precision.
{ "language": "en", "url": "https://stackoverflow.com/questions/17930148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: apply with ifelse statement and is.na does not 'sum' but outputs matrix - where is my logical mistake? probably a stupid question but I clearly can't see it and would appreciate your help. Here is a fictional dataset: dat <- data.frame(ID = c(101, 202, 303, 404), var1 = c(1, NA, 0, 1), var2 = c(NA, NA, 0, 1)) now I need to create a variable that sums the values up, per subject. The following works but ignores when var1 and var2 are NA: try1 <- apply(dat[,c(2:3)], MARGIN=1, function(x) {sum(x==1, na.rm=TRUE)}) I would like the script to write NA if both var1 and var2 are NA, but if one of the two variables has an actual value, I'd like the script to treat the NA as 0. I have tried this: check1 <- apply(dat[,2:3], MARGIN=1, function(x) {ifelse(x== is.na(dat$var1) & is.na(dat$var2), NA, {sum(x==1, na.rm=TRUE)})}) This, however, produces a 4x4 matrix (int[1:4,1:4]). The real dataset has hundreds of observations so that just became a mess...Does anybody see where I go wrong? Thank you! A: Here's a working version: apply(dat[,2:3], MARGIN=1, function(x) { if(all(is.na(x))) { NA } else { sum(x==1, na.rm=TRUE) } } ) #[1] 1 NA 0 2 Issues with yours: * *Inside your function(x), x is the var1 and var2 values for a particular row. You don't want to go back and reference dat$var1 and dat$var2, which is the whole column! Just use x. *x== is.na(dat$var1) & is.na(dat$var2) is strange. It's trying to check whether x is the same as is.na(dat$var1)? *For a given row, we want to check whether all the values are NA. ifelse is vectorized and will return a vector - but we don't want a vector, we want a single TRUE or FALSE indicating whether all values are NA. So we use all(is.na()). And if() instead of ifelse.
{ "language": "en", "url": "https://stackoverflow.com/questions/65939225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cannot compile on mint 20.1: stdlib.h: No such file or directory I am running a fresh install of Linux Mint 20.1 and I'n trying to compile a program for a GPS tracker, but it won't compile: In file included from /usr/include/c++/9/bits/stl_algo.h:59, from /usr/include/c++/9/algorithm:62, from /usr/include/x86_64-linux-gnu/qt5/QtCore/qglobal.h:142, from /usr/include/x86_64-linux-gnu/qt5/QtCore/QtCore:4, from pch.h:27: /usr/include/c++/9/cstdlib:75:15: fatal error: stdlib.h: No such file or directory 75 | #include_next <stdlib.h> | ^~~~~~~~~~ compilation terminated. I have installed a number of additional libraries (libusb, libmarble and a few others) and qmake. Of course, stdlib.h is present on the system: $ find /usr -name stdlib.h /usr/include/x86_64-linux-gnu/bits/stdlib.h /usr/include/bsd/stdlib.h /usr/include/stdlib.h /usr/include/c++/9/tr1/stdlib.h /usr/include/c++/9/stdlib.h /usr/include/tcl8.6/tcl-private/compat/stdlib.h After looking at the other questions about this, I re-installed build-essential, which didn't help. I re-installed the g++ compiler, no luck either. I copied /usr/include/c++/9/stdlib.h to /usr/local/include, but it still complains about a missing stdlib.h I changed the #include_next <stdlib.h> in cstdlib into #include <stdlib.h> only to find that the next include cannot find stdlib.h; changing that one produced the third include and so on. So that does not work either. The program compiles and works on Slackware 14.2 by the way. What am I missing? Hello-world compiles normally; a simple program that does a malloc also compiles and runs. A: I used to @anastaciu 's solution. As it was a fresh install without much customization, I resorted to the option of a complete re-install. Bizarre that that works a bit, as it was already a fresh install. I still had to copy stdlib.h and a few others (math.h etc.) to /usr/local/lib` to get to the point where it would at least compile.
{ "language": "en", "url": "https://stackoverflow.com/questions/66967315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a return keyword in bash? In the code below I need a return keyword in the first if statement. I need to exit the function after the echo.b push() { a=$1 b=$2 if [ $# -eq 0 ] then echo "Enter git shortname for first argument" fi if [ $# -eq 1 ] then b=$(timestamp) fi git add -A . git commit -m $b git push $a echo "push() completed." } Research Google pulls up SO article A: BASH does have return but you may not need it in your function. You can use: push() { a="${1?Enter git shortname for first argument}" [[ $# -eq 1 ]] && b=$(timestamp) b=$2 git add -A . git commit -m $b git push $a echo "push() completed." } a="${1?Enter git shortname for first argument}" will automatically return from function with given error message if you don't pass any argument to it. A: Rewrite it such that it always exits at the bottom. Use nested if constructs so yo don't have to bail out in the middle. A: What's wrong with bash's return statement? push() { a=$1 b=$2 if [ $# -eq 0 ] then echo "Enter git shortname for first argument" return fi if [ $# -eq 1 ] then b=$(timestamp) fi git add -A . git commit -m $b git push $a echo "push() completed." } A: push() { local a="$1" b="$2" #don't overwrite global variables [ "$#" -eq 0 ] && { 1>&2 echo "Enter git shortname for first argument" #stderr return 64 #EX_USAGE=64 } : "${b:=`timestamp`}" #default value git add -A . git commit -m "$b" #always quote variables, unless you have a good reason not to git push "$a" 1>&2 echo "push() completed." } The above should run in dash as well as bash, if case you want to make use of the faster startup time. Why quote? If you don't quote, variables will get split on characters present in $IFS, which by default is the space, the newline, and the tab character. Also, asterisks within the contents of unquoted variables are glob-expanded. Usually, you want neither the splitting nor the glob expansion, and you can unsubscribe from this behavior by double quoting your variable. I think it's a good practice to quote by default, and comment the cases when you don't quote because you really want the splitting or the globbing there. (Bash doesn't split or glob-expand in assignments so local a=$1 is safe in bash, however other shells (most prominently dash) do. a="$1" is ultra-safe, consistent with how variables behave elsewhere, and quite portable among shells.)
{ "language": "en", "url": "https://stackoverflow.com/questions/34118372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make a 'for' loop in the command prompt? I'm working with a command-line program that does image-processing, and I need to run the same command on an entire folder of images. I have heard that I can run loops in the command prompt, but I have seen all sorts of different examples online and can't figure out the syntax. The images in the folder are labled "single0.pgm, single1.pgm, single2.pgm,..." all the way to single39.pgm. The command I need to run is: DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single0.pgm -o single0.ppm And I need to do that for every picture. In C it is just a simple for loop like for (int j = 0; j<40; j++) { DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i singlej.pgm -o singlej.ppm } How do I do that in the command prompt? A: I figured it out! For anyone curious, the loop is: for %a in (0 1 2 3 4 5 6 7 8 9 10 11 1 2 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39) do DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single%a..pgm -o si ngle%a.ppm A: for /l %a in (0,1,39) do DebayerGPU.exe -demosaic DFPD_R -CPU -pattern GRBG -i single%a..pgm -o single%a.ppm is less prone to typos. This command runs happily directly from the prompt, but if it's a line within a batch file, you'd need to double the % for each instance of the metavariable %a (i.e. %a becomes %%a within a batch file. A: Here is a good short explanation of for loops, with examples. http://www.robvanderwoude.com/for.php Take a note of the 2 important key points: * *The code you write in command prompt will not work when you put it in batch files. The syntax of loops is different in those 2 cases due to access to variables as %%A instead of %A *Specifically for your problem it is easier do do dir *.pgm and than run a for loop over all the files. Thus your program will work for any amount of files and not just hard coded 40. This can be done as explained here: Iterate all files in a directory using a 'for' loop
{ "language": "en", "url": "https://stackoverflow.com/questions/18070292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to match view by RegExp in Javascript named.conf options { listen-on port 53 { 127.0.0.1;}; listen-on-v6 port 53 { ::1; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; }; view lan { match-clients {localhost;}; zone "home.com" IN { type master; file "home.zone"; }; zone "test.com" IN { type master; file "test.com.zone"; }; zone "demo.local" IN { type master; file "f.demo.local"; allow-update { none; }; }; zone "1.168.192.in-addr.arpa" IN { type master; file "r.demo.local"; allow-update { none; }; }; }; view wireless{ match-clients {localhost;}; zone "home.com" IN { type master; file "home2.zone"; }; }; include "/etc/rndc.key"; In the future may be more views and zone. How to use RegExp to match separate view in named.conf file Group 1 : view lan { ... }; Group 2 : view wireless { ... }; Thank You! A: Assuming node.js environment var namedConf = fs.readFileSync('named.conf'); var matches = namedConf.match(/view lan {(.*)};\s*view wireless{(.*)}/); A: Try this one var regexp = /(?:\n| )*view[\s\S\n\r ]+?(?=\n+ *view|$)/g
{ "language": "en", "url": "https://stackoverflow.com/questions/44772400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: 2D matrix value difference I have 2 columns in excel, parameter A1:A5 and value D1:D5: 1 2.0 2 1.5 3 3.5 4 2.3 5 7.7 Please let me know how to create a 2D matrix using iPython notebook. For both rows and columns the parameter (column A) should be used, and the cells should have the difference of the values. E.g.: 1 2 3 1 0.0 0.5 -1.5 2 -0.5 0.0 -2.0 3 1.5 2.0 0.0 Or can be just one sided matrix. Or if this is easier to do with excel, please suggest. A: I suggest using one of the scientific python distributions, see scipy.org, Install section. I use Anaconda. If you use the IPython notebook installed from one of the scientific python distributions, then you are ready to use it right away. You get many useful packages, specifically, pandas package. You do import pandas as pd then data = pd.read_excel(filename) you get a data frame, with all the data. You can set the data frame column names by supplying a list of names with the keyword argument 'names' in the above function. See here: pd.read_excel
{ "language": "en", "url": "https://stackoverflow.com/questions/38703374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel Eloquent relationship between 3 tables I am doing a school project on logistics and am using laravel for it. I have a delivery table and returns table which has all the deliveries inside and returns inside respectively. The delivery and returns table has a type which is Normal Delivery or Return Delivery and has a address id which is mapped to the address table. Both the delivery and return table has a tracking Id which is the same If its a Normal delivery, i have to refer to the customer table to get the customer details, if its a Return Delivery, i have to refer to the driver table to get the driver details. My delivery model as below class Delivery extends Eloquent { public function address() { return $this->hasOne('Address','id', 'address_id'); } public function customer() { return $this->hasOne('Customer', 'id', 'customer_id'); } public function driver() { return $this->hasOne('Driver', 'id', 'driver_id'); } public function return() { return $this->hasOne('Return', 'id', 'delivery_id'); } } My Return model as below class Return extends Eloquent { public function address() { return $this->hasOne('Address','id', 'address_id'); } public function customer() { return $this->hasOne('Customer', 'id', 'customer_id'); } public function driver() { return $this->hasOne('Driver', 'id', 'driver_id'); } public function delivery() { return $this->hasOne('Delivery', 'id', 'return_id'); } } My Customer model as below class Customer extends Eloquent { public function addresses() { return $this->hasMany('Address', 'client_id', 'client_id'); } public function delivery() { return $this->belongsTo('Delivery', 'customer_id', 'id'); } My Driver model as below class Driver extends Eloquent { public function addresses() { return $this->hasMany('Address', 'client_id', 'client_id'); } public function delivery() { return $this->belongsTo('Delivery', 'driver_id', 'id'); } My Address model as below class Address extends Eloquent { public function customer() { return $this->belongsTo('Customer', 'client_id', 'client_id'); } public function driver() { return $this->belongsTo('Driver', 'client_id', 'client_id'); } public function return() { return $this->belongsTo('Return', 'address_id', 'id'); } public function delivery() { return $this->belongsTo('Delivery', 'address_id', 'id'); } So right now, given a tracking id, I need to grab all the deliveries and return rows, along with the correct address. Currently I am doing it as below for deliveries $deliveries = Delivery::select(array('*', DB::raw('COUNT(id) as count')))->with('address','address.customer','customer')->whereIn('tracking_id', $tracking_id) and for returns $returns= Return::select(array('*', DB::raw('COUNT(id) as count')))->with('address','address.driver','customer')->whereIn('tracking_id', $tracking_id) When I combine these two together, I have to check whether it is a delivery or return before I can access the address.customer for the delivery and address.driver for the return. Is there any way to resolve this that when I combine these two sets of results togther, i can still access a address.contact for example which returns me the details for that address?
{ "language": "en", "url": "https://stackoverflow.com/questions/22075381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Simple style swicher with less I want to create a simple style swicher using less. I created a set of colored squares, and I would like by clicking on one of those, you can select a file. Css or even better, you can set the variable in the less file and generate a new style The HTML-CSS code : jsfiddle.net/AASH2/1/ Thanks in advance to those who will help me A: You can change the href attribute of your link tag when click on the button So using your example $('li').on('click', function() { $('link').attr('href','new_file_path_here'); }); This is a basic example, you can give your link tag an id and target it that way Also see How do I switch my CSS stylesheet using jQuery?
{ "language": "en", "url": "https://stackoverflow.com/questions/17943350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: right click event on URLs in richtext box I have a link in a richtextbox in C#. When I right on a url link, I want to show a menu. if it is not a url, then I do not want to show anything. Right now I am tapping into the mouse down event and selecting the line based on the mouse pointer position and if the selected line is a valid url, I show the menu. it works great, but when I have some text next to the url, still the line is detected as a valid url and the menu appears. Also I am unable to tap into the mouse changed event as well. Any ideas on how I could accomplish what I am trying to do? Thanks, A: Not sure if this is what you are looking for, but I believe that you'll find better than this You may try this when the MouseDown is called private void richTextBox1_MouseDown(object sender, MouseEventArgs e) { // Continue if the Right mouse button was clicked if (e.Button == MouseButtons.Right) { // Check if the selected item starts with http:// if (richTextBox1.SelectedText.IndexOf("http://") > -1) { // Avoid popping the menu if the value contains spaces if (richTextBox1.SelectedText.Contains(' ')) { // Show the menu contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y); } } } } Or this when a Link is Clicked, but this won't apply for Mouse Right-Click private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e) { contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y); } Thanks, I hope this helps :)
{ "language": "en", "url": "https://stackoverflow.com/questions/12679459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Regular Expressions for CSS Coloring I'm currently using the FastColoredTextBox to create a simple HTML/CSS editor. While FastColoredTextBox comes with some predefined formatting rules for HTML, etc. There is not one for CSS. It does support custom ones though. This is where my problem is. I'm trying to write three Regular expressions to select the selector e.g. "div", the attribute e.g. "color" and the value e.g. "#fff" but I can't get them to work quite right. Does anybody have any example of CSS regular expressions? Or does anybody know what they should be? Thanks a lot
{ "language": "en", "url": "https://stackoverflow.com/questions/32287471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a standalone command line app with the Symfony2 ClassLoader and Console I am trying to write a command line app using the Symfony2 Console and ClassLoader Components. This is a screenshot of my code hierarchy and the script being called Here is the CLI script: #!/usr/bin/env php <?php require_once(dirname(__FILE__) . '/code/ClassLoader/UniversalClassLoader.php'); use Symfony\Component\ClassLoader\UniversalClassLoader; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\ArgvInput; use BlueHeadStudios\Command\Deployer; $loader = new UniversalClassLoader(); $loader->register(); $input = new ArgvInput(); $debug = $input->hasParameterOption(array('--debug', '')); $console = new Application(); $console->add(new Deployer()); $console->run(); I get this when running the script dev@server:~/sites/pd/deployer$ php deployer.php PHP Fatal error: Class 'Symfony\Component\Console\Input\ArgvInput' not found in /home/dev/sites/pd/deployer/deployer.php on line 13 I know it must be a simple registerNamespace call or something similar, but I've tried multiple registrations but cannot get it to work. Any help is greatly appreciated. A: I would recommend you to use composer, which will generate autoload.php for you to include at the top of the file: #!/usr/bin/env php <?php require_once './vendor/autoload.php'; use Symfony\Component\ClassLoader\UniversalClassLoader; $loader = new UniversalClassLoader(); $loader->registerNamespace('BlueHeadStudios', __DIR__.'/src/'); $loader->register(); // write your code below A: You should run the application with app/console check the example here
{ "language": "en", "url": "https://stackoverflow.com/questions/20040480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CUDA Compute Capability 2.0. Global memory access pattern From CUDA Compute Capability 2.0 (Fermi) global memory access works through 768 KB L2 cache. It looks, developer don't care anymore about global memory banks. But global memory is still very slow, so the right access pattern is important. Now the point is to use/reuse L2 as much as possible. And my question is, how? I would be thankful for some detailed info, how L2 works and how should I organize and access global memory if I need, for example, 100-200 elements array per thread. A: L2 cache helps in some ways, but it does not obviate the need for coalesced access of global memory. In a nutshell, coalesced access means that for a given read (or write) instruction, individual threads in a warp are reading (or writing) adjacent, contiguous locations in global memory, preferably that are aligned as a group on a 128-byte boundary. This will result in the most effective utilization of the available memory bandwidth. In practice this is often not difficult to accomplish. For example: int idx=threadIdx.x + (blockDim.x * blockIdx.x); int mylocal = global_array[idx]; will give coalesced (read) access across all the threads in a warp, assuming global_array is allocated in an ordinary fashion using cudaMalloc in global memory. This type of access makes 100% usage of the available memory bandwidth. A key takeaway is that memory transactions ordinarily occur in 128-byte blocks, which happens to be the size of a cache line. If you request even one of the bytes in a block, the entire block will be read (and stored in L2, normally). If you later read other data from that block, it will normally be serviced from L2, unless it has been evicted by other memory activity. This means that the following sequence: int mylocal1 = global_array[0]; int mylocal2 = global_array[1]; int mylocal3 = global_array[31]; would all typically be serviced from a single 128-byte block. The first read for mylocal1 will trigger the 128 byte read. The second read for mylocal2 would normally be serviced from the cached value (in L2 or L1) not by triggering another read from memory. However, if the algorithm can be suitably modified, it's better to read all your data contiguously from multiple threads, as in the first example. This may be just a matter of clever organization of data, for example using Structures of Arrays rather than Arrays of structures. In many respects, this is similar to CPU cache behavior. The concept of a cache line is similar, along with the behavior of servicing requests from the cache. Fermi L1 and L2 can support write-back and write-through. L1 is available on a per-SM basis, and is configurably split with shared memory to be either 16KB L1 (and 48KB SM) or 48KB L1 (and 16KB SM). L2 is unified across the device and is 768KB. Some advice I would offer is to not assume that the L2 cache just fixes sloppy memory accesses. The GPU caches are much smaller than equivalent caches on CPUs, so it's easier to get into trouble there. A general piece of advice is simply to code as if the caches were not there. Rather than CPU oriented strategies like cache-blocking, it's usually better to focus your coding effort on generating coalesced accesses and then possibly make use of shared memory in some specific cases. Then for the inevitable cases where we can't make perfect memory accesses in all situations, we let the caches provide their benefit. You can get more in-depth guidance by looking at some of the available NVIDIA webinars. For example, the Global Memory Usage & Strategy webinar (and slides ) or the CUDA Shared Memory & Cache webinar would be instructive for this topic. You may also want to read the Device Memory Access section of the CUDA C Programming Guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/13834651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Play YouTube videos from an array of video IDs : React import React, { Component } from 'react'; import YouTube from 'react-youtube'; let videoIdList=["XM-HJT8_esM","AOMpxsiUg2Q"]; var videoId = videoIdList[0]; let i=0; class YoutubePlayer extends Component { render() { const opts = { height: '390', width: '640', playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 1 } }; return ( <YouTube videoId={videoId} opts={opts} onReady={this._onReady} onEnd={this._onEnd} /> ); } _onReady(event) { // access to player in all event handlers via event.targe event.target.playVideo(videoIdList[i]) } _onEnd(event) { videoId = videoIdList[i] event.target.playVideo(videoIdList[++i]); console.log(videoId); } } export default YoutubePlayer; So I am trying to play youtube videos from a array of video ids. When a video ends I want to change the video to next video in the list. How can I do this? A: You will have to maintain inner state with currently played video, and as soon as video is over, you will have to set next video in state which will re render the component again and start with next video. Below code should work. import React from "react"; import ReactDOM from "react-dom"; import YouTube from '@u-wave/react-youtube'; import "./styles.css"; let videoIdList=["AOMpxsiUg2Q","XM-HJT8_esM","AOMpxsiUg2Q"]; class App extends React.Component { constructor(props){ super(props); this.state = {}; this.i = 0; } componentDidMount() { this.setState({videoId: videoIdList[this.i]}); } render() { const opts = { height: '390', width: '640', playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 1 } }; return ( <YouTube video={this.state.videoId} opts={opts} onReady={this._onReady} onEnd={this._onEnd} /> ); } _onEnd = () => { this.setState({videoId: videoIdList[++this.i]}); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); You can check working code here - https://codesandbox.io/s/7yk0vrzr36
{ "language": "en", "url": "https://stackoverflow.com/questions/52014021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invoking .Net COM assembly from Powerbuilder application (without registration) We have a Powerbuilder 10 application that is using .Net COM assemblies. We are trying to embed the manifest in the PB application (to invoke COM assemblies without registration). The merged manifest file has added sections for dependecies on the .Net COM assemblies. We have tries various tools to inject the new manifest with different results - using GenMan32 to inject truncates the application from 6MB to 45KB. - using ResourceTuner, the file size looks okay, but trying to launch application gives "Fatal Disk Error". Any suggestions on invoked .Net ComEnabled assembly from PB without registration? A: Have you tried it with an external manifest and ensured that works? If an external manifest doesn't work, then the manifest information isn't correct. Once you have a valid external manifest, you might try the Manifest Tool (MT.EXE) from the .Net SDK. It works well with true EXE files. As Terry noted though, the PB generated executable contains additional information that tools that manipulate the EXE need to respect or they will break it. http://blogs.msdn.com/patricka/archive/2009/12/09/answers-to-several-application-manifest-mysteries-and-questions.aspx A: This is more a redirection than an answer. One thing you need to be aware of is that PowerBuilder produces executables that do not follow standards for Windows executable files. Essentially they are a bootstrap routine to load the PowerBuilder virtual machine, plus a collection of class definitions (objects). The cases you've brought up are not the first I've heard of where utilities meant to modify executables don't work on PowerBuilder executables. As for a positive contribution on what other directions to follow, I don't really know enough to give qualified advice. If it were me, I'd try to register the COM object if ConnectToNewObject() fails, but I've got no idea if that possible or if that route is a dead end. Good luck, Terry.
{ "language": "en", "url": "https://stackoverflow.com/questions/2526369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Invalid use of group function in MySQL 4 (not in 5) Any idea why query SELECT m.* FROM products_description pd, products p left join manufacturers m on p.manufacturers_id = m.manufacturers_id, products_to_categories p2c WHERE p.products_carrot = '0' and p.products_status = '1' and p.products_id = p2c.products_id and pd.products_id = p2c.products_id and pd.language_id = '4' and p2c.categories_id = '42' GROUP BY manufacturers_id ORDER BY COUNT(*) might give following error: #1111 - Invalid use of group function at MySQL 4.0.24 and not on MySQL 5.0.51 ? A: Self response. Mentioning column that I want to order by in SELECT clause and aliasing it did the trick: SELECT m.*, COUNT(*) as cnt FROM products_description pd, products p left outer join manufacturers m on p.manufacturers_id = m.manufacturers_id, products_to_categories p2c WHERE p.products_carrot = '0' and p.products_status = '1' and p.products_id = p2c.products_id and pd.products_id = p2c.products_id and pd.language_id = '4' and p2c.categories_id = '42' GROUP BY p.manufacturers_id ORDER BY cnt
{ "language": "en", "url": "https://stackoverflow.com/questions/2665461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ref to find a nested element I'm using the gridjs-react library to create a table as follows: <Grid columns={['Name', 'Email']} data={[ ['John', '[email protected]'], ['Mike', '[email protected]'] ]} ref={tableRef} search={true} pagination={{ enabled: true, limit: 1, }} /> However, I want to ultimately add an item to the dom to get this: I thought about using ref but I couldn't get access to the following div since it is only rendered after the component Grid is mounted: (As far as I know) A: You can access the grid reference in useEffect block when all it's content is rendered: useEffect(()=> { const grid = ref.current.wrapper.current; //--> grid reference const header = grid.querySelector(".gridjs-head"); //--> grid header const itemContainer = document.createElement("div"); //--> new item container header.appendChild(itemContainer); ReactDOM.render(<Input />, itemContainer); //--> render new item inside header }, []); You will need to use css to get the desired position inside the element. Working example: https://stackblitz.com/edit/react-r5gsvw A: Or just use a CSS solution for that component you want. e.g. <div style={{ position: 'relative'}}> <Grid .... /> <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/65858393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: $stmt->fetch() is not fetching the data I don't understand why my function is not getting the results and just getting null value. I'm using PhpStorm; all my connections are fine (Apache, MySQL, PhpMyAdmin) I've check them, also the other rest services are working. This is my dbhandler.php file: public function getRating($rating_id, $user_id) { $stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?"); $stmt->bind_param("ii", $rating_id, $user_id); if ($stmt->execute()) { $stmt->bind_result( $restaurant_id, $service_rating, $food_rating, $music_rating); // TODO //$rating_id = $stmt->get_result()->fetch_assoc(); $stmt->fetch(); $res = array(); $res["user_id"] = $user_id; $res["rating_id"] = $rating_id; $res["restaurant_id"] = $restaurant_id; $res["service_rating"] = $service_rating; $res["food_rating"] = $food_rating; $res["music_rating"] = $music_rating; $stmt->close(); return $res; } else { return NULL; } } and this is my index.php file $app->get('/userRatings/:rating_id', 'authenticate', function($rating_id) { global $user_id; $response = array(); $db = new DbHandler(); // fetch rating $result = $db->getRating($rating_id, $user_id); if ($result != NULL) { $response["user_id"] = $result["user_id"]; $response["rating_id"] = $result["rating_id"]; $response["restaurant_id"] = $result["restaurant_id"]; $response["service_rating"] = $result["service_rating"]; $response["food_rating"] = $result["food_rating"]; $response["music_rating"] = $result["music_rating"]; echoRespnse(200, $response); } else { $response["error"] = true; $response["message"] = "The requested resource doesn't exists"; echoRespnse(404, $response); } }); The response of the request is: {"user_id":19, "rating_id":"171", "restaurant_id":null, "service_rating":null, "food_rating":null, "music_rating":null} A: There is a problem in param values. Change param values as follows. $stmt = $this->conn->prepare("SELECT ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id AND ur.rating_id = ?"); $stmt->bind_param("ii", $user_id,$rating_id); According to your sql first param should be $user_id. Not the $rating_id. According to your parameter settings there is no record to fetch.
{ "language": "en", "url": "https://stackoverflow.com/questions/40405221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift: press button in external app via accessibility In my function, I run the following code, when a specific event shows up and Safari is in foreground: if win.safariIsForeground() { let el = AXUIElementCreateApplication(win.getSafariPid()) var ptr: CFArray? _ = AXUIElementCopyAttributeNames(el, &ptr) } The pointer returns an array that looks like this: ["AXFunctionRowTopLevelElements", "AXFrame", "AXChildren", "AXFocusedUIElement", "AXFrontmost", "AXRole", "AXExtrasMenuBar", "AXMainWindow", "AXFocusedWindow", "AXTitle", "AXChildrenInNavigationOrder", "AXEnhancedUserInterface", "AXRoleDescription", "AXHidden", "AXMenuBar", "AXWindows", "AXSize", "AXPosition"] I'd like to make Safari go one site back in the history. I think I will need AXUIElementCopyAttributeValue and AXUIElementPerformAction to do that but how do I find out the button's attribute and how do I call check AXUIElementCopyAttributeValue for that? A: The easiest way to do that is by accessing the menu item. Using AXUIElementCopyAttributeValue works best with the provided constants: // get menu bar var menuBarPtr: CFTypeRef? _ = AXUIElementCopyAttributeValue(safariElement, kAXMenuBarRole as CFString, &menuBarPtr) guard let menuBarElement = menuBarPtr as! AXUIElement? else { fatalError() } Accessibility Inspector shows me, what items are child of the menu bar: so lets get the children using kAXChildrenAttribute: // get menu bar items var menuBarItemsPtr: CFTypeRef? _ = AXUIElementCopyAttributeValue(menuBarElement, kAXChildrenAttribute as CFString, &menuBarItemsPtr) guard let menuBarItemsElement = menuBarItemsPtr as AnyObject as! [AXUIElement]? else { fatalError() } And so on all the way down to the menu item. Items also have an unique identifier that can look like _NS:1008. I'm not sure how to access them directly but by using AXUIElementPerformAction I can simply simulate pressing the menu item (action will be kAXPressAction). I can use kAXRoleAttribute to identify the type of the item and where it occurs in the Accessibility hierarchy (see "Role:") As I'm still a beginner at Swift, that was a quite challenging task as this is also not documented very well. Thanks a lot to Dexter who also helped me to understand this topic: kAXErrorAttributeUnsupported when querying Books.app A: In your case you don't need necessarily need to use AXUI accessibility API. It's arguably simpler to send key strokes. You can go back in Safari history to previous page with CMD[. As an added bonus Safari does not need to be in foreground anymore. let pid: pid_t = win.getSafariPid(); let leftBracket: UInt16 = 0x21 let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState) let keyDownEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: true) keyDownEvent?.flags = CGEventFlags.maskCommand let keyUpEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: false) keyDownEvent?.postToPid(pid) keyUpEvent?.postToPid(pid) Your app running on Mojave and newer MacOS versions will need the System Preferences -> Security & Privacy -> Accessibility permisions granted to be eligible for sending keystrokes to other apps. The keyboard codes can be looked up: here & here visually
{ "language": "en", "url": "https://stackoverflow.com/questions/72674287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert decimal to binary value of rows in multindex dataframe (python)? Could you let me know how to onvert decimal to binary value of rows in multindex dataframe? below is dataframe I used from pandas import Series, DataFrame raw_data = {'Function': ['env', 'env', 'env', 'func1', 'func1', 'func1'], 'Type': ['In', 'In', 'In', 'In','In', 'out'], 'Name': ['Volt', 'Temp', 'BD#', 'Name1','Name2', 'Name3'], 'Val1': ['Max', 'High', '1', '3', '5', '6'], 'Val2': ['Typ', 'Mid', '2', '4', '7', '6'], 'Val3': ['Min', 'Low', '3', '3', '6', '3'], 'Val4': ['Max', 'High', '4', '3', '9', '4'], 'Val5': ['Max', 'Low', '5', '3', '4', '5'] } df = DataFrame(raw_data) df= df.set_index(["Function", "Type","Name"]) print (df) below is printed dataframe Val1 Val2 Val3 Val4 Val5 Function Type Name env In Volt Max Typ Min Max Max Temp High Mid Low High Low BD# 1 2 3 4 5 func1 In Name1 3 4 3 3 3 Name2 5 7 6 9 4 out Name3 6 6 3 4 5 I want to convert decimal to binary values of rows(func1 - In - Name1, Name2) in multi-index dataframe. below is expected df I want. Val1 Val2 Val3 Val4 Val5 Function Type Name env In Volt Max Typ Min Max Max Temp High Mid Low High Low BD# 1 2 3 4 5 func1 In Name1 11 100 11 11 11 Name2 101 111 110 1001 100 out Name3 6 6 3 4 5 I have tried to get right results but I failed. TT Plz let me know how to resolve it simply. A: Use MultiIndex.get_level_values for create conditions, chain together and set new values by f-strings: m1 = df.index.get_level_values(0) == 'func1' m2 = df.index.get_level_values(1) == 'In' df[m1 & m2] = df[m1 & m2].astype(int).applymap(lambda x: f'{x:b}') print (df) Val1 Val2 Val3 Val4 Val5 Function Type Name env In Volt Max Typ Min Max Max Temp High Mid Low High Low BD# 1 2 3 4 5 func1 In Name1 11 100 11 11 11 Name2 101 111 110 1001 100 out Name3 6 6 3 4 5 A: By creating mask of the dataframe: mask = ((df.index.get_level_values('Function') == 'func1')& (df.index.get_level_values('Type') == 'In')& (df.index.get_level_values('Name').isin(['Name1', 'Name2']))) df[mask] = df[mask].astype(int).applymap(lambda x: format(x, 'b')) print(df[mask]) Val1 Val2 Val3 Val4 Val5 Function Type Name env In Volt Max Typ Min Max Max Temp High Mid Low High Low BD# 1 2 3 4 5 func1 In Name1 11 100 11 11 11 Name2 101 111 110 1001 100 out Name3 6 6 3 4 5
{ "language": "en", "url": "https://stackoverflow.com/questions/54980815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: numberOfRowsInSection running in infinite loop - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { int rows; // Return the number of rows in the section. switch (section) { case 0: rows = 1; break; case 1: rows = 3; break; case 2: rows = 2; break; case 3: rows = 1; break; default: rows = 1; break; } return rows; } this code is running in infinite loop. for the first it returns right no of rows. but after that starts running on infinite loop. and one more thing, why section starts from the highest no and den come to 0 and den in ascending order?? A: There is no infinite loop in your code above. It's quite possible that it is being called from an infinite loop. To find this, place a breakpoint in the method, continue a few times (to ensure you're in the loop rather than just the normal calls) and then look at the stack trace on the side. This should give you a pretty clear idea of where the looping is coming from. You are probably calling reloadData from within one of your datasource or delegate methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/21620577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Form_Shown and mouse click I have c# code which moves and clicks mouse, i must press button on form to start code, but i need that my code would start himself, not when button is pressed i tried to achieve this with formshown. It shows form but dont start the code. Its just a bit of code: private void Form1_Shown(object sender, EventArgs e) { Thread.Sleep(5000); RightClick(28, 132); Thread.Sleep(2000); LeftClick(35, 137); } Any ideas how my form could start doing things after it is opened? Every time i open my windowsform application i have to press start button and after that my mouse starts clicking coordinates. I want that mouse would start moving without me clicking button its like autostart or something i dont know how to explain. A: Simply Call your code on Form Load Event private void Form1_Load(object sender, System.EventArgs e) { Thread.Sleep(5000); RightClick(28, 132); Thread.Sleep(2000); LeftClick(35, 137); } you can also call your code into constructor but it would be better if you call it inside form_load event public yourform() { Thread.Sleep(5000); RightClick(28, 132); Thread.Sleep(2000); LeftClick(35, 137); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28526391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SensorManager.getRotationMatrix gravity parameter or accelerometer parameter values in android? In Android Documentation is specified the third parameter as float[] gravity then is specifies [0 0 g] = R * gravity (g = magnitude of gravity) Now, in most of the examples online I can see everyone sending accelerometer values to getRotationMatrix, but, Isn't suppose that I should send only gravity values? For example, if the mobile phone has the gravity sensor, Should I send it raw output to getRotationMatrix? If it hasn't one, Should I send accelerometer values? Should I extract non gravity components first? (as accelerometer values are Acceleration minus G). Will the use of gravity sensor values be more reliable than using accelerometer values in mobile phones that have that sensor? Thanks in advance! Guillermo. A: I think the reason you only see examples using the accelerometer values is because the gravity sensor was only launched in API 9 and also because most phones might not give this values separated from the accelerometer values, or dont have the sensor, etc, etc.. Another reason would be because in most of the cases the result tend to be the same, since what the accelerometer sensor outputs is the device linear acceleration plus gravity, but most of the time the phone will be standing still or even moving at a constant velocity, thus the device acceleration will be zero. From the setRotationMatrix Android Docs: The matrices returned by this function are meaningful only when the device is not free-falling and it is not close to the magnetic north. If the device is accelerating, or placed into a strong magnetic field, the returned matrices may be inaccurate. Now, you're asking if the gravity data would me more reliable? Well, there is nothing like testing, but I suppose it wouldn't make much difference and it really depends on which application you want. Also, obtaining the simple gravity values is not trivial and it requires filtering, so you could end up with noisy results.
{ "language": "en", "url": "https://stackoverflow.com/questions/9112078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Associate custom uri schemes with Java self contained application for windows I have a self contained JavaFX application. For an improved user experience, I would like the user to click on a button/link on the browser and start the application. Just like magnet URI for torrent, the link contains metadata that is required to start up the application. Is there a way to generate the executable for JavaFX application to associate with custom URI just like magnet URIs associated with torrent applications. A: Here is how to associate custom URIs with an application. I already have a task that generates the native bundles. First step is to enable verbose in your ant task so you can locate the build path. As mentioned here, in 6.3.3 enable verbose and look for <AppName>.iss file in the build directory, which is usuablly AppData/Local/Temp/fxbundler*. Make sure you have the directory that contains package directory in the classpath. Here is an example of how you can add that to the classpath: <taskdef resource="com/sun/javafx/tools/ant/antlib.xml" uri="javafx:com.sun.javafx.tools.ant" classpath="${build.src.dir}:${JAVA_HOME}/lib/ant-javafx.jar"/> In my example I have package/windows with Drop-In Resources in src directory. If you have file association, you will see something like this: [Registry] Root: HKCR; Subkey: ".txt"; ValueType: string; ValueName: ""; ValueData: "AppNameFile"; Flags: uninsdeletevalue Just after this line you can add lines to add custom URI's registry entries. If you don't have file association then you will add entries after ArchitecturesInstallIn64BitMode=ARCHITECTURE_BIT_MODE You can find the template of how AppName.iss file is generated at this location: C:\Program Files (x86)\Java\jdk1.8.0_60\lib\ant-javafx.jar\com\oracle\tools\packager\windows\template.iss Here you will find how to write lines like the one above Here you can find what registry keys and entries that needs to be added for custom URI association.
{ "language": "en", "url": "https://stackoverflow.com/questions/32505471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does MonetDB support parallel query execution when using merge tables? I have partitioned my data set into two separate sets of 5M rows. Each partition is loaded into a table on a machine of its own. I use a central monetdb instance where I register both tables as remote tables and add them to a merge table. When I run a query on the merge table I would expect MonetDB to distribute the query, in parallel, to both partition tables. However, when looking at results created with tomograph I see that each remote table is queried sequentially. I've compiled MonetDB myself using a recent source tarball. I've disabled geom and made sure embedded python was available. Other than that I've not changed any settings or configure flags. The two machine holding the partitions are 1 core VMs with 4GB memory. The central machine is my laptop, which has 4 cores and 16GB of memory. I have also run this experiment using a central node with the same configuration as the partitions. I created the tables like this: -- On each partition (X = {1, 2}): CREATE TABLE responses_pX ( r_id int primary key, r_date date, r_status tinyint, age tinyint, movie varchar(25), score tinyint ); -- On central node: CREATE MERGE TABLE responses ( r_id int primary key, r_date date, r_status tinyint, age tinyint, movie varchar(25), score tinyint ); -- For both partitions CREATE REMOTE TABLE responses_pX ( r_id int primary key, r_date date, r_status tinyint, age tinyint, movie varchar(25), score tinyint ) ON 'mapi:monetdb://partitionX:50000/partitionX'; ALTER TABLE responses ADD TABLE responses_pX; I'm running the following queries on the central node: SELECT COUNT(*) FROM responses; SELECT COUNT(*), SUM(score) FROM responses; SELECT r_date, age, SUM(score)/COUNT(score) as avg_score FROM responses GROUP BY r_date, age; For all queries the parallelism reported by the tomograph tool is no higher than 2.11%. A: yes, MonetDB uses parallel processing where possible. See the documentation https://www.monetdb.org/Documentation/Cookbooks/SQLrecipes/DistributedQueryProcessing
{ "language": "en", "url": "https://stackoverflow.com/questions/38655237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting error when I try to fetch rows using entity EF6 I use linq to entity 6 code first. Here is two entities class: public class Site { public int Id { get; set; } public int UID { get; set; } public string Name { get; set; } public string Description { get; set; } public int? ContractId { get; set; } public int? SiteTypeId { get; set; } public virtual ICollection<SiteRegion> Regions { get; set; } } public class SiteRegion { public int Id { get; set; } public int UID { get; set; } public int? SiteId { get; set; } public string Name { get; set; } public int? RegionTypeId { get; set; } [ForeignKey("SiteId")] public virtual Site Site { get; set; } } As you can see above Regions field is constraint and I have one-to-many relation between to tables. I have created this LINQ query to fetch desired rows from Sites table: int?[] ContractId = [1,2]; int?[] siteTypeId = [1,2,3]; var result = (from sites in context.Set<Site>() where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId) && select sites).AsNoTracking<Site>(); And It works fine. Now I have new requirement and I need to filter my query also by RegionTypeId column in SiteRegion table here is my new query: int?[] ContractId = [1,2]; int?[] siteTypeId = [1,2,3]; int?[] regionTypeId = [1,2,3]; var result = (from sites in context.Set<Site>() where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId) && regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray()) select sites).AsNoTracking<Site>(); But I get error: Error 36 'int?[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource)' has some invalid arguments On this row: regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray()) How to fix my query above to get the desired rows? A: You need to do it as shown below. Note : Wrong : regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray()) Correct : regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item)) Working sample : int?[] contractsIDList = { 1, 2}; int?[] siteTypeId = { 1, 2, 3}; int?[] regionTypeId = { 1, 2, 3}; var result = (from sites in db.Set<Site>() where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId) && regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item)) select sites).AsNoTracking<Site>(); Result :
{ "language": "en", "url": "https://stackoverflow.com/questions/40284189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spatializer not available on a pixel 6 with android 13 I just updated to Android 13 and one of the advertised features is the spatial audio, but when I access the spatializer class to check if it's available, I get a false. Also, in the settings there is nothing regarding the spatial audio. Is it already implemented or not?
{ "language": "en", "url": "https://stackoverflow.com/questions/73429760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I open the A TAB at 768px? I apologize first, my English is not very good, but I will try to describe my problem. I'm implementing an RWD effect, and this is it! When the screen is below 768px, I want to wrap an A tag around the demo block to make the whole block clickable, but when the screen resolution is above 768px, I want to add an A tag to cover the demo block. I have tried using display:none in the initial a tag; .demo{ background-color: #ccc; padding:20px; } a{ text-decoration:none; color:#222; } .link{ display: none; } @media(max-width:768px){ .link{ display: block; } } <a class="link" href="#"> <div class="demo"> <h1><object><a href="javascript:;">我是標題</a></object></h1> <p> <object><a href="javascript:;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab voluptatum v</a></object> </p> </div> </a> However, this will cause the whole picture to disappear at the beginning, which is not the effect I want. I would like to ask you how to write this better? .demo{ background-color: #ccc; padding:20px; } a{ text-decoration:none; color:#222; } .link{ display: none; } @media(max-width:768px){ .link{ display: block; } } <a class="link" href="#"> <div class="demo"> <h1><object><a href="javascript:;">我是標題</a></object></h1> <p> <object><a href="javascript:;">9999999999999999</a></object> </p> </div> </a> A: This is only a workaround Do not use display: none;. Instead write: ... .link{ display: block; cursor: default; } @media(max-width:768px){ .link{ cursor: pointer; } } This will make the mouse cursor appear normal in desktop and appear clickable on mobile. In reality you can still click, but 99+% of visitors will not realize or attempt to check. See: https://developer.mozilla.org/de/docs/Web/CSS/cursor
{ "language": "en", "url": "https://stackoverflow.com/questions/67776024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome prevents the site due to ads I'm facing a problem just with google chrome. My website home page works properly, but when trying to open a post on the site, it shows this message: Security Wrror The site is based on the latest WordPress version, and it works properly with all other browsers. I tried to remove ads (the only way to get the required fund). but nothing changed. It still doesn't open on Google Chrome. I tried to update the sitemap, but nothing changed. I hope you can help. Most of the visitors use Google Chrome as a default browser, and this is a major problem because we earn money due to ads viewed on the site. here a link to my website
{ "language": "en", "url": "https://stackoverflow.com/questions/34138214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a string to a List inside of a List> Im trying to add a string object to a list inside of list> in a for & while loop, trying to use var i as the list object i wish to use. here is the code of the class, any help on what im doing wrong would be very much appreciated :) public class GenClass { private static int _genCount; private static bool _filesLoadedToLists; private static List<string> _nounSetOne = new List<string>(); private static List<string> _nounSetTwo = new List<string>(); private static List<List<string>> _toLoad = new List<List<string>>(); private string _emotionMidTrim = ""; public const string FileOne = "NounSetOne.txt"; public const string FileTwo = "NounSetTwo.txt"; public GenClass() { while (_filesLoadedToLists == false) { TextToList(FileOne,FileTwo); _filesLoadedToLists = true; } _genCount++; } the problem is withing this part of the class public void TextToList(string fileOne, string fileTwo) { List<string> filesToRead = new List<string>(); filesToRead.Add(fileOne); // Add the text files to read to a list filesToRead.Add(fileTwo); // Add the text files to read to a list _toLoad.Add(_nounSetOne); // Add a list of words to this list _toLoad.Add(_nounSetTwo); // Add a list of words to this list for (int i = 0; i <= filesToRead.Count; i++) { using (var reader = new StreamReader(filesToRead[i])) { string line; while ((line = reader.ReadLine()) != null) { _toLoad[i.Add(line)]; // the error is here } } } A: You are correct, with the error, you need to understand that the List<List<string>> will take a List<string> and NOT A String. Try something like this; List<string> listOfString = new List<string>; for (int i = 0; i <= filesToRead.Count; i++) { using (var reader = new StreamReader(filesToRead[i])) { string line; while ((line = reader.ReadLine()) != null) { listOfString.add(line); } } } Then, _toLoad.add(listOfStrings); A: Try using File.ReadAllLines(). Replace the for loop with: foreach(var file in filesToRead) { _toLoad.Add(File.ReadAllLines(file).ToList()); } A: You can cut this down considerably using LINQ: List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"}; List<List<string>> _toLoad = new List<List<string>>(); _toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() )); Note that there's no extraneous variables for the filename (why have FileOne/FileTwo if their only purpose is to get added to a list?) and that we're letting the AddRange take care of creating the List<string>s for us automatically. A: for (int i = 0; i <= filesToRead.Count; i++) { using (var reader = new StreamReader(filesToRead[i])) { string line; while ((line = reader.ReadLine()) != null) { _toLoad[i].Add(line); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/18323444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Powershell Mysql Error This code is: $cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand $sql = "Select * FROM onaylanan Order by onaylanma_id ASC" $cm.Connection = $Connection $cm.CommandText = $sql $dr = $cm.ExecuteReader() while ($dr.Read()) { $cm2 = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand $sql2 = "Delete FROM onaylanan Where onaylanma_id=4" $cm2.Connection = $Connection $cm2.CommandText = $sql2 $dr2 = $cm2.ExecuteNonQuery() $dr2.Close(); } $dr.Close(); $Connection.Close() This Error is: Exception calling "ExecuteNonQuery" with "0" argument(s): "There is already an open DataReader associated with this Connection which must be closed first." A: As the error indicates, you can't execute two queries concurrently over the same connection. Open a second connection (you could name it Connection2) and assign that to $cm2: $cm2.Connection = $Connection2
{ "language": "en", "url": "https://stackoverflow.com/questions/48932539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove PHP extension using .htaccess methods (Keeping Link Juice) I'm trying to remove the .php extension on my URLs to make it Search Engine Friendly using the .htaccess file Redirect 301, to keep the "rank juice" and I as much I've tried almost every example around - It just doesn't seem to work. Here are some of the methods I've unsuccessfully tried already: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php This is the most common solution given but nothing happens and there is no changes. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /$1.php [L] Nothing happens and there is no changes. RewriteEngine On # RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php # RewriteRule (.*)\.php$ /$1 [L,R=301] # RewriteRule (.*)/$ $1.php [L] I get a Not Found : The requested URL /AMENPTHOME/hostnd/3/9/9/399fc7b78/www/htdocs/web/dive-sites.php was not found on this server. Amen is my host and the file dive-sites.php in this specific real example is on the root. My goal is to have: www.domain.com/dive-sites and not www.domain.com/dive-sites.php using a Redirect 301 because this url is already ranked for a while. Can someone please help ? Thank you very much, all help appreciated. A: If I didn't missed anything: RewriteEngine On RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC] RewriteRule ^ /%1 [R=301,NE,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L] Requests to /dive-sites.php will issue a 301 redirect to /dive-sites, appending query-strings if any. Requests to /dive-sites will get a 200 response with /dive-sites.php as Content-Location, appending query-strings if any. A: try this: RewriteEngine on RewriteRule ^/(.+)(($|#)*(.*)) /$1.php$2 If removing only the .php this will work. $1 = for the name of the page, e.g foo $2 = take note of the hashtag or the get request eg. <domain>/example ----> <domain>/example.php <domain>/example?get=this ----> <domain>/example.php?get=this <domain>/example#hash ----> <domain>/example.php#hash A: Try this code for .php extension removal: RewriteEngine On ## hide .php extension # To externally redirect /dir/file.php to /dir/file RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC] RewriteRule ^ /%1 [R=301,L,NE] # To internally forward /dir/file to /dir/file.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^(.+?)/?$ /$1.php [L]
{ "language": "en", "url": "https://stackoverflow.com/questions/19904911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mustache (Nustache) arbitrarily rendering some of list inline I'm using the code: {{#Object}} {{{Name}}} - {{{Property}}} {{/Object}} to render a list, but halfway through the list, it'll start printing the list on the same line, which it will continue doing until the end of the list. We use this within emails, and our preview pane renders it within a <pre> tag, and it looks fine. When it's set as the body of an email, we get the line breaking problem. It'll render like the following: Object1Name - Object1Property Object2Name - Object2Property Object3Name - Object3Property Object4Name - Object4Property Object5Name - Object5Property Object6Name - Object6Property There are also instances where it puts the entire list on the same line, and there are instances where it doesn't happen, most of the time it starts about halfway through the list and continues. any help or ideas are welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/18073219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: knockout.js and property not being found in Jquery Template I am getting "caseStudy is not defined" with the below code. I have to add the full prefix app.viewModel.caseStudy.showFlawDetails to not error. app.viewModel.caseStudy = {}; app.viewModel.caseStudy.cases = ko.observableArray(); app.viewModel.caseStudy.selectedCaseId = ko.observable(0); app.viewModel.caseStudy.selectedCase = ko.mapping.fromJS(caseModel); app.viewModel.caseStudy.showFlawDetails = function (index) { console.log(index); }; ko.applyBindings(app.viewModel); <div class="Flaws" data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws }'> </div> <script id="flawTemplate" type="text/html"> {{each(index, value) $data}} <div class="flaw"> <div class="Title" data-bind="click: caseStudy.showFlawDetails(index)"> ${value.Title} </div> <div class="Items"> <div>Title: <input type="text" data-bind="value: value.Title" /></div> <div>Check: <input type="text" data-bind="value: value.Check" /></div> <div>Instructor: <input type="text" data-bind="value: value.Instructor" /></div> <div>Keys: <input type="text" data-bind="value: value.Keys" /></div> <div>Opponent Init: <input type="text" data-bind="value: value.OpponentInit" /></div> <div>Opponent Justification: <input type="text" data-bind="value: value.OpponentJustif" /></div> <div>Opponent Communication: <input type="text" data-bind="value: value.OpponentComm"/></div> <div>Hint: <input type="text" data-bind="value: Hint"/></div> <div>Opponent Incorrect Hint: <input type="text" data-bind="value: value.OpponentIncorrectHint"/></div> <div>Prompt: <input type="text" data-bind="value: Prompt" /></div> <div>PromptCompletion: <input type="text" data-bind="value: value.PromptCompletion"/></div> <div>Opponent Incorrect Prompt: <input type="text" data-bind="value: value.OpponentIncorrectPrompt"/></div> </div> </div> {{/each}} </script> A: Inside of your flawTemplate the scope is caseStudy.selectedCase.Flaws, so when you put caseStudy.showFlawDetails, it is not found as a property of Flaws or globally. So, you can either reference it with app.viewModel.caseStudy.showFlawDetails, if app has global scope (which it seems to since it works for you). Otherwise, a good option is to pass the function in via templateOptions. So, you would do: data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws, templateOptions: showFlawDetails: caseStudy.showFlawDetails } }'> Then, you would access it using $item.showFlawDetails The click (and event) bindings also expect that you pass it a reference to a function. In your case you are passing it the result of executing the function. Answered it further here: knockout.js calling click even when jquery template is rendered
{ "language": "en", "url": "https://stackoverflow.com/questions/7014260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to link through bootstrap tabs Hello the code which i am posting here is just a w3schools example. Its a bootstrap links tabs. All my problem is when i want for example just to link to the second tab i can't i want when i put a link like that http://127.0.0.1:61330/test2.html#menu2 i want it to work to go to menu2 section or div what ever but it doesn't work i want at the link up tp be like /test2.html#menu2 /test2.html#menu3 like that but it doesn't happen i found also this here on stackoverflow but it just show the link up in the browser but when i change the link like http://127.0.0.1:61330/test2.html#menu3 for example it don't work // Javascript to enable link to tab var url = document.location.toString(); if (url.match('#')) { $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show'); } // Change hash for page-reload $('.nav-tabs a').on('shown.bs.tab', function (e) { window.location.hash = e.target.hash; }) main <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Case</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Dynamic Tabs</h2> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#home">Home</a></li> <li><a data-toggle="tab" href="#menu1">Menu 1</a></li> <li><a data-toggle="tab" href="#menu2">Menu 2</a></li> <li><a data-toggle="tab" href="#menu3">Menu 3</a></li> </ul> <div class="tab-content"> <div id="home" class="tab-pane fade in active"> <h3>HOME</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> <div id="menu1" class="tab-pane fade"> <h3>Menu 1</h3> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div id="menu2" class="tab-pane fade"> <h3>Menu 2</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> <div id="menu3" class="tab-pane fade"> <h3>Menu 3</h3> <p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> </div> </div> </div> </body> </html> A: $(document).ready(function(){ if (location.hash) { $('a[href=' + location.hash + ']').tab('show'); } }); this is the solution i found it here here
{ "language": "en", "url": "https://stackoverflow.com/questions/38274033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert data to table row using Angular I am new to angular, and currently working on my personal project. I have a question about how to insert new data to table row. Can anyone give me snippet/example how to do this? Here is the form and the table headers: <!--app.component.html--> <!--show modal--> <a href="#" (click)="smModal.show()" popover="Tambah Data Mhs" placement="bottom" triggers="mouseenter:mouseleave">ADD</a> <!--Modal--> <div class="container"> <div bsModal #smModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="myModal"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">Add</h4> <button type="button" class="close pull-right" aria-label="Close" (click)="smModal.hide()"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <label>ID</label> <input type="text" class="form-control" placeholder="id"> <label>name</label> <input type="text" class="form-control" placeholder="name"> <label>year</label> <input type="text" class="form-control" placeholder="year"> <label>major</label> <input type="text" class="form-control" placeholder="major"> <label>address</label> <input type="text" class="form-control" placeholder="address"> <label>Email</label> <input type="text" class="form-control" placeholder="email"> <label>phone</label> <input type="text" class="form-control" placeholder="phone"><br> <button type="submit" class="btn btn-primary">Simpan</button> <button class="btn btn-danger">Batal</button> </form> </div> </div> </div> </div> <!--enf of modal--> <!--table--> <div class="container"> <table class="table table-responsive table-striped"> <tr> <th>id</th> <th>name</th> <th>year</th> <th>major</th> <th>address</th> <th>email</th> <th>phone</th> </tr> </table> <div> <!--end of table--> Here is the typescript file: //app.component.ts import { Component } from '@angular/core'; import { TemplateRef } from '@angular/core'; import { BsModalService } from 'ngx-bootstrap/modal'; import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class'; import { NgIf } from '@angular/common'; @Component({ selector: 'app-root', styleUrls:['app.component.css'], templateUrl:'app.component.html', //template:`<h1 align="center">template</h1>` }) export class AppComponent { title = 'title'; } What I need to do is simply insert the user input from that from into a table row. Please let me know if more snippets are needed. A: You can declare custom object array in your app.component.ts file like this import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-root', template: ` <div class="container"> <table class="table table-responsive table-striped"> <tr> <th>id</th> <th>name</th> <th>year</th> </tr> <tr *ngFor="let row of rows"> <td>{{row.id}}</td> <td>{{row.name}}</td> <td>{{row.year}}</td> </tr> </table> <div> <hr /> <input type="text" [(ngModel)]="id" placeholder="id" /> <input type="text" [(ngModel)]="name" placeholder="name" /> <input type="text" [(ngModel)]="year" placeholder="year" /> <button (click)="buttonClicked()">Click to Insert New Row</button> `, styles: [] }) export class AppComponent { title = 'app'; public id: number; public name: string; public year: number; public rows: Array<{id: number, name: string, year: number}> = []; buttonClicked() { this.rows.push( {id: this.id, name: this.name, year: this.year } ); //if you want to clear input this.id = null; this.name = null; this.year = null; } } A: // html data// <table border="1"> <thead> <tr> <th>Type</th> <th>Name</th> <th>Batters</th> <th>Toppings</th> </tr> </thead> <tbody> <tr *ngFor="let data of Newjson;"> <td > {{data.type}} </td> <td> {{data.name}} </td> <td> <ul *ngFor="let item of data.batters.batter;" [ngClass]="{'devils-find':item.type==='Devil\'s Food'}"> <li [ngClass]="item.type"> {{item.type}} </li> </ul> </td> <td> <ul *ngFor="let y of data.topping;"> <li> {{y.type}} </li> </ul> </td> </tr> </tbody> </table> //component.ts file// export class AppComponent { public newtext:any; public rows:any=[]; public url:any=["../assets/images/image.jpeg","../assets/images/danger.jpeg","../assets/images/crab.jpeg", "../assets/images/aws.png","../assets/images/error404.jpg","../assets/images/night.jpg"]; public displayimage:any=["../assets/images/image.jpeg"]; public setimage:boolean=true; public i:any=1; Newjson=[ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"}, { "id": "1002", "type": "Chocolate"}, { "id": "1003", "type": "Blueberry"}, { "id": "1004", "type": "Devil's Food"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5007", "type": "Powdered Sugar" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] }, { "id": "0002", "type": "donut", "name": "Raised", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5005", "type": "Sugar" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] }, { "id": "0003", "type": "donut", "name": "Old Fashioned", "ppu": 0.55, "batters": { "batter": [ { "id": "1001", "type": "Regular"}, { "id": "1002", "type": "Chocolate"} ] }, "topping": [ { "id": "5001", "type": "None" }, { "id": "5002", "type": "Glazed" }, { "id": "5003", "type": "Chocolate"}, { "id": "5004", "type": "Maple" } ] } ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/46929589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Program on GD32f103 microcontroller runs only with debugger attached, won't run after reset I'm using a J-Link EDU Mini debugger/programmer, to upload a simple test program to a GD32f103 microcontroller (the ST32f103 clone/copy). The program is a mere test program, meant to turn an LED on. It's written in SMT32CubeIDE, and here, it is based on the ST32f103. After uploading the compiled .elf file to the GD32f103 using the J-Kink, the LED turns on just fine. However, once I detach the J-Link and reset the processor, the program appears not to boot, because the LED won't turn on. What can the source of this problem be?
{ "language": "en", "url": "https://stackoverflow.com/questions/71307058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to combine multiple querysets in django Suppose there is an event model and for each event there is one client and one consultant. Also, one consultant can have multiple events. Each event has number of different documents. I am trying to display list of events when a consultant logs in and in that list od events it should display their respective documents. Models.py: class Client_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Consultant_Profile(models.Model): user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) # Field name made lowercase. first_name = models.CharField(db_column='First_name', max_length=50) # Field name made lowercase. last_name = models.CharField(db_column='Last_name', max_length=50) # Field name made lowercase. phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10) # Field name made lowercase. # role_id = models.ForeignKey(Role, on_delete=models.CASCADE) def __str__(self): return self.first_name class Event(models.Model): event_id = models.AutoField(db_column='event_id', primary_key=True) client_id = models.ForeignKey(Client_Profile, db_column='Client_ID', on_delete=models.CASCADE) # Field name made lowercase. consultant_id = models.ForeignKey(Consultant_Profile, db_column='Consultant_ID', on_delete=models.CASCADE) # Field name made lowercase. def __str__(self): return str(self.event_id) class Document(models.Model): document_id = models.AutoField(db_column='document_id', primary_key=True) document_name = models.CharField(db_column='document_name', max_length=50, null=True, blank=True) # Field name made lowercase. path = models.FileField(null=True, upload_to='files/') date_uploaded = models.DateTimeField(default=timezone.now, null=True, blank=True) event_id = models.ForeignKey(Event, db_column='Client_ID', on_delete=models.CASCADE) # Field name made lowercase. def __str__(self): return self.document_name + ": " + str(self.path) # this specifies how should instance of this class should be printed. views.py @login_required def consultant_home(request): consultant_pr = Consultant_Profile.objects.get(user_id=request.user) event_id = Event.objects.filter(consultant_id=consultant_pr.pk) for id in event_id: doc = Document.objects.filter(event_id=id) context = {'id': event_id, 'doc': doc, 'consultant_pr': consultant_pr} return render(request, 'Consultant/consultant_documents.html', context) document.html {% for eve in id %} <p>Event id: {{ eve.event_id }}</p> {% for dox in doc %} <p>document name: {{ dox.document_name }}</p> <p>path: <a href="/media/{{dox.path}}">{{ dox.path}} </a> </p> {% endfor%} {% endfor %} A: You can simply loop over the related Document objects from the Event object itself by using document_set (the default related_name for Document i.e. the model name in lowercase with _set appended). Also you can optimise the number of queries made by using prefetch_related [Django docs]: In your view: @login_required def consultant_home(request): consultant_pr = Consultant_Profile.objects.get(user_id=request.user) events = Event.objects.filter(consultant_id=consultant_pr.pk).prefetch_related('document_set') context = {'events': event, 'consultant_pr': consultant_pr} return render(request, 'Consultant/consultant_documents.html', context) In your template: {% for event in events %} <p>Event id: {{ event.event_id }}</p> {% for document in event.document_set.all %} <p>document name: {{ document.document_name }}</p> <!-- Use document.path.url instead of manually rendering its url --> <p>path: <a href="{{ document.path.url }}">{{ document.path }} </a></p> {% endfor%} {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/67555730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Randomly SSLException Unsupported record version Unknown-0.0 Sometimes the code below fails and sometimes it work. I'm using Java8. Is it a server side problem? Exception in thread "main" javax.net.ssl.SSLException: Unsupported record version Unknown-0.0. EDIT: I downgrade to JDK7 from JDK8 and it works. The only solution i found that works. public static void main(String[] args) throws Exception { URL u = new URL("https://c********.web.cddbp.net/webapi/xml/1.0/"); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + 140); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); } A: I got the same error message in a new java installation when trying to use an SSL connection that enforces 256-bit encryption. To fix the problem I found I needed to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html) A: I had this line SSLContext sc = SSLContext.getInstance("SSL"); Had to change it to SSLContext sc = SSLContext.getInstance("TLSv1"); And now it works on both, java 7 and java 8 Note: (In java 7 SSL and TLS both worked with the same url, in java 8 just tried TLSv1 but I guess SSLv1 also works) A: Download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files according to your JDK/JRE version and put it in lib/security folder By default,Java Cryptographic Extension is limited in accessing function and algorithm usage.We need to make it unlimited. A: According to the stack trace, the RecordVersion Unknow-0.0 is produced from here => referenced from here => which is invoked in InputRecord.readV3Record most of the time, these two values should not be 0, the reason for this happening is probably the wrong response from server while handshaking. (This is not an answer though, just some information for easier figuring out the problem and solution) A: This error is fixed in latest jre's, just upgrade the version of jre. This issue is caused by SNI
{ "language": "en", "url": "https://stackoverflow.com/questions/23324807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: File Upload not working in IE and Firefox I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem? PHP: // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762) $POST_MAX_SIZE = ini_get('post_max_size'); $unit = strtoupper(substr($POST_MAX_SIZE, -1)); $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1))); if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) HandleError('File exceeded maximum allowed size. Your file size <b>MUST NOT</b> be more than 100kb.'); // Settings $save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment) $upload_name = 'userfile'; // change this accordingly $max_file_size_in_bytes = 102400; // 100k in bytes $whitelist = array('jpg', 'png', 'gif', 'jpeg'); // Allowed file extensions $blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions $valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format) // Other variables $MAX_FILENAME_LENGTH = 260; $file_name = $_FILES[$upload_name]['name']; //echo "testing-".$file_name."<br>"; //$file_name = strtolower($file_name); ////////$file_extension = end(explode('.', $file_name)); $parts = explode('.', $file_name); $file_extension = end($parts); $uploadErrors = array( 0=>'There is no error, the file uploaded with success', 1=>'The uploaded file exceeds the upload max filesize allowed.', 2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3=>'The uploaded file was only partially uploaded', 4=>'No file was uploaded', 6=>'Missing a temporary folder' ); // Validate the upload if (!isset($_FILES[$upload_name])) **HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) HandleError($uploadErrors[$_FILES[$upload_name]['error']]); else if (!isset($_FILES[$upload_name]['tmp_name']) || !@is_uploaded_file($_FILES[$upload_name]['tmp_name'])) HandleError('Upload failed.'); else if (!isset($_FILES[$upload_name]['name'])) HandleError('File has no name.'); HTML: <form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata"> <table border="0" cellpadding="3" cellspacing="3" class="forms"> <tr> <tr> <td style="height: 26px" align="center"> <font class="font_upload_picture">'.MSG142.': <input class="font_upload_picture" type="file" name="userfile"> <input type=hidden name=MAX_FILE_SIZE value=102400 /> </td> </tr> <tr> <td colspan="2"> <p align="center"> <input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" /> </p> <p>&nbsp;</p> <td><a href="/picturecamerasettings"><img src="/img/layout/takepicture.gif" border="0" /><br> '.MSG143.'</a></td> </tr> </table> </form> A: The enctype of the form should be multipart/form-data A: You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />. A: Some of your logic is off: if (!isset($_FILES[$upload_name])) will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4. else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0) You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong. You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename. So, your upload validation should look something like: if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) { $fi = finfo_open(FILE_INFO_MIME_TYPE); $mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']); if (!in_array($valid_mime_type, $mime)) { HandleError("Invalid file type $mime"); } etc... } else { HandleError($uploadErrors[$_FILES[$upload_name]['error']]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/5682108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaFX 2 Window Icon not working I'm trying to add an Icon to my JavaFX 2 application, but the ways I have found don't seem to work. Image icon = new Image(getClass().getResourceAsStream("/images/icon.png")); stage.getIcons().add(icon); The icon is 32x32 in size. When I try Image icon = new Image("http://goo.gl/kYEQl"); It does work, in Netbeans and in the runnable jar. I hope this can be fixed. A: The problem was in the icon itself. It did load it like it should, but for some reason it didn't display like it should. I remade the icon I was trying to use to different sizes (16x16 up to 512x512) and added them all to the icon list. stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_16.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_32.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_64.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_128.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_256.png"))); stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_512.png"))); Now it uses the icon like it should.
{ "language": "en", "url": "https://stackoverflow.com/questions/27017031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unset one Array on the basis of another array value in php? How can I remove one array index on the basis of another array value. For example- Array1 ( [0] => @@code [1] => @@label [2] => @@name [3] => @@age ) Array2 ( [0] => 123jj [1] => test [2] => john [3] => 45 ) Array3 ( [0] => 2 #2 is index to be unset in array1 and array2 [1] => 3 #3 is index to be unset in array1 and array2 ) I have 3 arrays , I want to unset array1 and array2 index on the basis of value of array3 using php.How can I use unset() Method for this? unset($array1,$array3) #this is wrong, but some thing like that unset($array2,$array3) With Out for loop. I should get Array1 ( [0] => @@code [1] => @@label ) Array2 ( [0] => 123jj [1] => test ) A: You asked similar question and removed it after getting the answer : unset array indexs from value of another array? $firstArray = array( 0 => '@@code' ,1 => '@@label' ,2 => '@@name' ,3 => '@@age' ); $keysArray = array( 0 ,1 ); $resultArray = array_diff_key( $firstArray ,array_flip( $keysArray ) ); var_dump( $resultArray ); A: Maybe you need this? foreach($array3 as $tmp){ unset($array1[$tmp]); unset($array2[$tmp]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/19684476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: executing two queries in firebase and finding the difference of the two My Firebase has two children * *expenditure *sales I want to find the difference between sales and expenditure. Currently i am able to find the total of both children. However i am stuck trying to find the difference between the two. Below is the code I have executed to compute the sum. dref = FirebaseDatabase.getInstance().getReference(); DatabaseReference dref = FirebaseDatabase.getInstance().getReference(); dref= dref.child("LukenyaExpenditure"); dref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { int totalAmount = 0; for (DataSnapshot postSnapshot : snapshot.getChildren()) { DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class); totalAmount += dogExpenditure.getAmount(); } textView4.setText("Your total expenses for Lukenya Unit is:" +Integer.toString(totalAmount)); } @Override public void onCancelled(DatabaseError databaseError) { } public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); } }); Any help will be appreciated
{ "language": "en", "url": "https://stackoverflow.com/questions/43188295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add trace to plotly scatter plot p <- plot_ly(data = bData, x = ~`Maturity Date`, y = ~YVal, type = 'scatter', mode='markers', symbol = ~Sym, symbols = c('circle-open','x-open','diamond-open','square-open') , text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "<br>") ,hoverinfo = 'text' ) Above code produces this plot. Now to this chart I want to add a trace with scatter plot with color depending on Currency column. I tried this but it produces combination of two field as the legend. Basically I want to classify the plot based on currency type but also add overlay or trace based on column SYM as the symbol. p <- plot_ly(data = bData, x = ~`Maturity Date`, y = ~YVal, type = 'scatter', mode='markers', symbol = ~Sym, symbols = c('circle-open','x-open','diamond-open','square-open') , text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "<br>") ,hoverinfo = 'text' ) %>% add_trace(x = ~`Maturity Date`, y = ~YVal , color=~Crncy) data: bData <- structure(list(Crncy = structure(c(9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 3L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 6L, 5L, 9L, 9L, 3L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 7L, 6L, 7L, 6L, 9L, 7L, 7L, 3L, 2L, 7L, 9L, 9L, 9L, 9L, 8L, 9L, 9L, 9L, 10L, 9L, 9L, 4L, 4L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 4L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 5L, 9L, 5L, 9L, 2L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 2L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L, 5L, 1L, 9L, 9L, 9L, 9L, 9L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 9L, 9L, 9L, 9L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 1L, 9L, 9L), .Label = c("AUD", "CAD", "CHF", "COP", "EUR", "GBP", "JPY", "PEN", "USD", "ZAR" ), class = "factor"), `Maturity Date` = structure(c(20772, 19689, 18969, 18969, 20815, 20119, 20865, 20864, 20134, 20873, 20873, 20887, 20011, 20897, 20162, 19797, 20908, 20908, 20923, 19841, 19107, 19107, 20941, 20935, 20936, 20936, 20953, 20049, 19138, 19860, 21005, 21027, 19562, 19562, 21014, 19222, 21047, 19950, 19264, 19285, 19292, 19292, 19323, 19382, 19381, 20000, 19404, 20176, 19437, 19875, 19875, 19508, 20635, 19555, 19555, 20658, 19038, 19628, 18946, 19745, 19746, 19021, 19042, 19042, 20545, 20623, 19047, 19412, 19415, 20178, 20178, 19611, 19807, 20168, 20551, 20640, 20957, 20223, 19858, 19692, 19158, 20258, 19720, 20269, 20999, 20999, 20290, 20278, 20300, 20300, 21029, 19753, 20318, 20328, 20423, 20120, 20223, 20240, 19335, 20594, 19510, 19905, 20073, 20347, 20392, 18897, 20962, 20994, 21009, 21043, 19287, 19505, 18899, 19006, 19081, 19323, 19373, 19203, 19417, 19415, 19430, 19469, 19492, 19527, 19599, 20344, 19638, 19655, 19675, 19688, 20068, 19711, 19780, 19803, 19838, 19865, 19892, 19890, 19940, 19962, 20706, 20011, 18927, 20041, 18949, 20777, 20116, 20145, 19041, 20156, 20177, 20174, 20173, 20205, 20208, 20235, 20248, 20249, 19523, 20521, 20588, 20574, 20465, 20482, 19400, 20588, 21021, 20649, 20389, 20409, 19950, 19600, 19601, 20346, 19658, 20747, 19657, 19656, 19657, 20307, 20347, 19259, 20087, 20810, 20077, 19349, 20118, 20483, 20112, 20109, 19392, 19594, 20144, 21056, 19407, 20749, 20573, 19296, 19300, 19300, 19310, 20041, 19346, 20907, 19976, 20744, 20202, 19132, 19132, 19132), class = "Date"), Sym = structure(c(4L, 3L, 4L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 1L, 4L, 3L, 2L, 1L, 4L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 3L, 2L, 1L, 4L, 1L, 4L, 1L, 2L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 2L, 3L, 4L, 3L, 4L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 4L, 4L, 4L), .Label = c("Axe", "Axe, Owned", "None", "Owned"), class = "factor"), YVal = c(20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229)), class = "data.frame", row.names = c(NA, -210L)) A: Maybe is this what you are looking for? (I have used split from plotly): library(plotly) #Code plot_ly(data = bData, x = ~`Maturity Date`, y = ~YVal, type = 'scatter', mode='markers', symbol = ~Sym, symbols = c('circle-open','x-open','diamond-open','square-open') , split = ~Crncy, text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "<br>") , hoverinfo = 'text') Output: Update: Here somo other options for OP: #Option 1 plot_ly(data = bData, x = ~`Maturity Date`, y = ~YVal, type = 'scatter', mode='markers', symbol = ~Sym, symbols = c('circle-open','x-open','diamond-open','square-open') , text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "<br>") , hoverinfo = 'text',legendgroup = 'group1' ) %>% add_trace(x = ~`Maturity Date`, y = ~YVal , symbol=~Crncy,legendgroup = 'group2') Output: Option 2: #Option 2 plot_ly(bData, x = ~`Maturity Date`, y = ~YVal, type = 'scatter', mode='markers', legendgroup = 'group1',color = ~Sym) %>% add_trace(y = ~YVal, legendgroup = 'group2',type = 'scatter', mode='markers', color=~Crncy) Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/63934125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: define parameter in update query in python psycopg2 This my python code which is used to perform update operation from reading the csv file. I tried with this also. It doesn't work out. for i in cin: try: conn=psycopg2.connect("dbname=pharmaflare user=postgres") cursor=conn.cursor() cursor.execute("UPDATE pharmaflare_drug_interaction SET se_interaction ='%s' WHERE primary_drug ='%s' AND secondary_drug ='%s' AND side_effect ='%s'"%(i[3],i[0],i[1],i[2])) conn.commit() cursor.close() conn.close() #print "done",i[0],i[1],i[2],i[3] except Exception as e: cerr.writerow(i) ferr.flush() traceback.print_exc(file=sys.stdout) continue Here I am facing the exception like syntax error due to the QUOTE's problem: Wherever the single quotes presents this exception arises. Traceback (most recent call last): File "<ipython console>", line 5, in <module> ProgrammingError: syntax error at or near "S" LINE 1: ...secondary_drug ='NEUER' AND side_effect ='MENIERE'S DISEASE' Is there any alternative way available to define query statement without troubling the Quotes problem? A: There are a couple ways to solve it. The easy/hack way to do it is to employ the re.escape() function. That function can be thought of as an equivalent to PHP's addslashes() function, though it pains me to make that comparison. Having said that, my reading indicates psycopg2 takes advantage of PEP 249. If that's true, then you should be able to pass in parameterized queries and have it escape them for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/11690306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php form won't send or go to header location after submit I have a simple php form for contact purposes. However, it won't send the email or go to the correct page after submit. It redirects to the mail.php instead. My contact form named contact.php is as follows: <form id="contact-form" action="mail.php" method="POST"> <fieldset> <label><span class="text-form">Your Name:</span> <input type="text" name="name"></label> <label><span class="text-form">Your Email:</span><input type="text" name="email"></label> <label><span class="text-form">Your Contact No:</span><input type="text" name="contact"></label> <div class="wrapper"> <div class="text-form">Your Message:</div> <textarea name="message" rows="6" cols="25"></textarea><br /> <div class="clear"> </div> <div class="buttons"> <a class="button" href="#"><input class="button" type="submit" value="Send"></a> <a class="button" href="#"><input class="button" type="reset" value="Clear"></a> </div> </fieldset> </form> And the php code named mail.php is as follows: <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; &contact = $_POST['contact']; $formcontent="From: $name \n Message: $message"; $recipient = "[email protected]"; $subject = "Contact form message"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); header("Location:contact.php"); ?> What am i doing wrong. It just wont send the message to email or redirect to the correct page?? A: Your syntax is ever so slightly wrong. &contact on line 5 should be $contact. I assume you're on a production server, so error reporting would be disabled and you wouldn't get any warnings. A: Try using @ before mail function <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $contact = $_POST['contact']; $formcontent="From: $name \n Message: $message"; $recipient = "[email protected]"; $subject = "Contact form message"; $mailheader = "From: $email \r\n"; @mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); header("location: contact.php"); ?> this will let you pass even if mail function produce any issue. Also please check if there are any other header are not sent using http://php.net/manual/en/function.headers-sent.php function. I would strongly suggest to use PHPMailer or some other class to send any kind of email. A: Please check the contact.php file whether some redirection is happening from contact.php to mail.php A: I think there may be an issue sending mail from your server. The mail.php file is probably tripping up on the mail function and not doing the redirect. Create a new file with just the php mail function in there (with your email address and a test message) and browse it from your web browser, does it send? A: Try to use ob_start() at the start of script, and exit(); after header("Location: contact.php"); smth like this ... <?php ob_start(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; &contact = $_POST['contact']; $formcontent="From: $name \n Message: $message"; $recipient = "[email protected]"; $subject = "Contact form message"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); header("Location: contact.php"); exit(); ?> A: Change the mail.php to the following: <?php mail("[email protected]", "Contact form message", $_POST['message'], "From: ".$_POST['name']." <".$_POST['email'].">"); header("Location: contact.php"); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/14955320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTP Status 500 - Servlet.init() for servlet appServlet threw exception Spring - beans are not created org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reorderLevelController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.bvas.insight.service.ExcelService com.bvas.insight.controller.BaseController.excelService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'excelService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.bvas.insight.service.ExcelService.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'localSessionFactory' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot resolve reference to bean 'localDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'localDataSource' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot create inner bean 'com.zaxxer.hikari.HikariConfig#73d35ee2' of type [com.zaxxer.hikari.HikariConfig] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.zaxxer.hikari.HikariConfig#73d35ee2' defined in ServletContext resource [/WEB-INF/servlet-context.xml]: Cannot create inner bean '${jdbc.driver}#3f778a58' of type [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for bean with name '${jdbc.driver}#3f778a58' defined in ServletContext resource [/WEB-INF/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: com.mysql.jdbc.jdbc2.optional.MysqlDataSource org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:160) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) java.lang.Thread.run(Unknown Source) Here it is the pom.xml <properties> <java-version>1.8</java-version> <org.springframework-version>4.2.4.RELEASE</org.springframework-version> <hibernate.version>4.2.2.Final</hibernate.version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> <mysql.connector.version>8.0.17</mysql.connector.version> <jackson.version>1.9.10</jackson.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> <exclusions> <!-- Exclude Commons Logging in favor of SLF4j --> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.5</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.2.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${org.aspectj-version}</version> </dependency> <!-- IText --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.5</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j-version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <exclusions> <exclusion> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> </exclusion> <exclusion> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> </exclusion> <exclusion> <groupId>com.sun.jdmk</groupId> <artifactId>jmxtools</artifactId> </exclusion> <exclusion> <groupId>com.sun.jmx</groupId> <artifactId>jmxri</artifactId> </exclusion> </exclusions> <scope>runtime</scope> </dependency> I just change the mysql driver version. Project is ruuning smoothly on server but am getting error on my local. Eclipse verion is 2019-09. I also change the JDK 1.7 to 1.8. Any one can please help me. also i need to know is we need any spring plugin or ide in eclipse or just declared jar files are enough. A: I don't see mysql driver dependency in your pom, it could be running fine on the server because your server may have the driver jar, in that case adding mysql driver dependency in provided scope should solve the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/59097729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: function adding in an extra line break? I have a function which sanitizes input from a form and another function which decodes it. It's kind of like bbcode which also converts line breaks into <br /> when storing it in the database (using the nl2br() function), and then converts the <br /> back into line breaks whenever it is put back into a field for the "edit page" where the user can edit their post (using str_replace('<br />',"\n",$data)). The problem is that every time a post is decoded for editing and then coded again for storage, each <br /> turns into two <br /><br />. Is a \n or \r equal to two HTML line breaks? Here is the code for the two functions. function sanitize2($data) { $patterns = array(); $patterns[0] = '/</'; $patterns[1] = '/>/'; $data1 = preg_replace($patterns, "", $data); $bopen = substr_count($data1, '[b]') + substr_count($data1, '[B]'); $bclosed = substr_count($data1, '[/b]') + substr_count($data1, '[/B]'); $iopen = substr_count($data1, '[i]') + substr_count($data1, '[I]'); $iclosed = substr_count($data1, '[/i]') + substr_count($data1, '[/I]'); $uopen = substr_count($data1, '[u]') + substr_count($data1, '[U]'); $uclosed = substr_count($data1, '[/u]') + substr_count($data1, '[/U]'); $bx = $bopen - $bclosed; $ix = $iopen - $iclosed; $ux = $uopen - $uclosed; if ($bx > 0) { for ($i = 0; $i < $bx; $i++) { $data1 .= "[/b]"; } } if ($ix > 0) { for ($i = 0; $i < $ix; $i++) { $data1 .= "[/i]"; } } if ($ux > 0) { for ($i = 0; $i < $ux; $i++) { $data1 .= "[/u]"; } } $newer = sanitize($data1); $search = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[B]', '[/B]', '[I]', '[/I]', '[U]', '[/U]'); $replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<b>', '</b>', '<i>', '</i>', '<u>', '</u>'); $newest = str_replace($search, $replace, $newer ); $final = nl2br($newest); return $final; } function decode($data) { $new = str_replace('<br />',"\n",$data); $search = array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]'); $replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>'); $newer = str_replace($replace, $search, $new ); return $newer; } UPDATE: I found this page which gives a workaround. Apparently this is a problem with the nl2br() function. :-/ http://websolstore.com/how-to-use-nl2br-and-its-reverse-br2nl-in-php/ A: From the documentation for nl2br: nl2br — Inserts HTML line breaks before all newlines in a string (emphasis mine). It doesn't replace the newlines, it just inserts linebreaks. So if you try to revert nl2br by replacing <br />, you will get two \n, the old one and the one you inserted when replacing the <br />. The easiest fix would be removing all \n in the string you get from nl2br, the right thing would be storing the text without the <br /> and convert when you display it.
{ "language": "en", "url": "https://stackoverflow.com/questions/31254774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Launch screen doesn't show first after the first launch time? I am developing App with React native. I set an image in the launchScreen.Xib. The first time, the launch screen works well. After the launch screen hide, then I will see the View MainView. I shut up the App in the background. A moment later, I tap the App icon to launch the App again. To my surprise, the App will show the MainView first, the MainView continue show 0.2 seconds. After the MainView flash, the launch screen show now. A few seconds later, the MainView show again. My issue is the MainView will show before the launch screen in the later launch time. In my opinion, the launch screen should show first and the MainView show later. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"patient" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } This is my code above in the AppDelegate.m. This is the initial code of React native. One more thing, the MainView show a moment, and the screen shows a white view instead of the MainView, a moment later, the MainView show again. A: Well, you’re trying to instantiate and show with timer your own launch screen (not good!) while also asking iOS to do one. Just get rid of most or all of this code. Use the standard approach of having a launch storyboard then set up your main VC as normal in your appDelegate. Using that timer is making assumptions about the timing of each app launch that iOS can’t guarantee.
{ "language": "en", "url": "https://stackoverflow.com/questions/46846556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is this embedded iframe video not playing? I want to add this video on my website. I added this code but it’s not working. Please help me. <div id="container"> <iframe id="vid" width="560" height="315" src="https://www.youtube.com/watch?v=NhxVR2Szu3k&noredirect=1" frameborder="0" allowfullscreen></iframe> </div> <style> #container { border: 1px solid red; width: 560px; text-align: center; } #vid { margin-bottom: 25px; } </style> A: UPDATED Please replace this with your code <div id="container"> <iframe width="560" height="315" src="https://www.youtube.com/embed/NhxVR2Szu3k" frameborder="0" allowfullscreen></iframe> </div> and css #container { border: 1px solid red; text-align:center; width: 80%; margin-left:auto; margin-right:auto; } as you are not using correct code for video..go in video link..then share and then embed code and take that code and it will work..hope this help. Updated : now your video is responsive..change width according to your need. A: I didn't clearly understand what you're trying to achieve but try this example: <html> <head> </head> <body> <div style="text-align:center"> <button onclick="playPause()">Play/Pause </button> <br> <video id="video" width="420"> <source src="video.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> </div> <script> var myVideo = document.getElementById("video "); function playPause() { if (myVideo.paused) myVideo.play(); else myVideo.pause(); } </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/32003452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple plots sharing one datasource Core Plot In case of real time data ; I am maintaining a single datasource and multiple plots each having unique identifier and linestyles having unique colour. Inserting data in every plot using the insertDataAtIndex and then in the numberForPlot function returning the appropriate value else returning nil. However only one of the plots gets successfully plotted though it still enters the numberForPlot and symbolForPlot accordingly.Is it possible for multiple plots to share the same datasource or am I missing something here.
{ "language": "en", "url": "https://stackoverflow.com/questions/52400402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using NOIP with RPI node.js server Im no expert in networks so sorry if something seems stupid. I'm having a problem connecting to RPI node.js server located in my home externally. I used NO-IP and configured it on router with specific host-name. I have port forwarded to 8888 port. var express = require("express"); var app = express(); var http = require("http").Server(app); var io = require('socket.io')(http); var path = require('path'); http.listen(8888, "0.0.0.0"); /*app.use(function (req, res, next){ res.setHeader('Access-Control-Allow-Origin', 'http://hostname:port'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true); next(); });*/ app.use(express.static(path.join(__dirname, '/'))); app.get("/home",function(req,res,next){ res.sendFile(path.join(__dirname + "/index.html")); }); console.log("server ubi jeza"); If I try to connect to http://hostanme.org it connect to my router. If I try connect to http://hostanme.org:8888 it times-off. Port forward check works fine and says that port 8888 is working when I run the server. When server is not running it say that connection is closed. I also tried with sudo nano /etc/sysctl.conf and net.ipv4.ip_forward=1 but it doesn't work ither. Am I doing something wrong? A: I can access page from outside world. When I'm on local network I can not access it with external IP.
{ "language": "en", "url": "https://stackoverflow.com/questions/43400345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving Data with jQuery AJAX Without Reloading Page in php I have try to stop refresh page on click on select option but when I stop refresh page then data can not get. here code echo "<form name='frmtopdevotees' method='post' action='topuser_load.php'> <h4>select month <select id='seldrp' name='themonth' OnChange ='document.frmtopdevotees.submit()'> $optionsmonths </select> <select name='topdevotees' id='seldrp' OnChange ='document.frmtopdevotees.submit()'> <option value=10 $M10>Top 10</option> <option value=20 $M20>Top 20</option> <option value=50 $M50>Top 50</option> <option value=100 $M100>Top 100</option> </select> </h4> </form>"; ?> <script> $('frmtopdevotees').submit(function (e) { e.preventDefault(); return false; }); $('themonth').onchange(function () { $.ajax({ var value = $('themonth').val(); type: 'post', data: { topdevotees: topdevotees, themonth: themonth }, url: "topuser_load.php?topdevotees=" + topdevotees + "&themonth=" + themonth, success: function (response) { $('themonth').append(response); } }); }); </script> when I remove Onchange = 'document.frmtopdevotees.submit()' then page stop to refresh but not data change. A: Change name to id in ajax, $('#seldrp').onchange(function(){ ^ ^ // ajax here }); And you have syntax errors in ajax. var themonth = $('#seldrp').val(); var topdevotee = $('#topdevotees').val();//topdevotess should be the id of 2nd select box. $.ajax({ type: 'post', data: { topdevotees: topdevotees, themonth: themonth }, async:false,// this line for waiting for the ajax response. url: "topuser_load.php?topdevotees=" + topdevotees + "&themonth=" + themonth, success: function (response) { $('themonth').append(response); $('#frmtopdevotees').submit(); } }); A: From your code what I can understand is you want to trigger a server call without refreshing the page (AJAX) whenever your any one the select option changes. There are errors in the code posted. Following is my observation - * *There can be only one ID in entire page. You have used 'seldrp' in couple of places. *If you want the AJAX functionality, you should avoid calling submit() function of the form. *The AJAX syntax is wrong which should be as follows - $.ajax({ url : "topuser_load.php?topdevotees=" + topdevotees + "&themonth=" + themonth, method: "post", data: { topdevotees: topdevotees, themonth: themonth }, // can even put this in variable and JSON stringify it success: function (response) { $('themonth').append(response); } }); Now coming to the solution part of it: I would do this as follows - 1. Will just listen on the select change in JQUERY 2. Once a select change is triggered, AJAX call is made and which returns the response. The modified code is - <script> $('select').on('change', function (e) { var month = $('#seldrp1').val(); var topdevotee = $('#seldrp2').val(); // call ajax here - $.ajax({ url: "topuser_load.php?topdevotees=" + topdevotee + "&themonth=" + month, method: "post", data : JSON.stringify({ topdevotees: topdevotee, themonth: month }), success : function(response){ $('themonth').append(response); }, error : function(err){ // handle error here } }); }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> echo "<form name='frmtopdevotees'> <h4>select month <select id='seldrp1' name='themonth'> $optionsmonths </select> <select name='topdevotees' id='seldrp2'> <option value=10 $M10>Top 10</option> <option value=20 $M20>Top 20</option> <option value=50 $M50>Top 50</option> <option value=100 $M100>Top 100</option> </select> </h4> </form>"; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/33840424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Write new value of a key in an already defined JSON file I have a JSON file of every user in my database. I want to change the value of a key from true to false on an action. How can I write it in the file? Below is the JSON file: { "name": "hi", "email": "[email protected]", "secFactorType": "microsoftTotpAuth", "loginid": "9867033239", "timezone": "+5.5", "workStartHours": "0900", "workEndHours": "1700", "ifRegenerateQR": true } I want to change the value of ifRegenerateQR to false in file. JSON.parse(fs.readFileSync(userInfoFile)).ifRegenerateQR = false; This is not writing in the file. How do I use fs.writeFile() to write changes to file? A: Read file and store in JS object. const obj = JSON.parse(fs.readFileSync(userInfoFile)); Change whatever you want to change. obj.ifRegenerateQR = false; Write obj back to file. fs.writeFile(JSON.stringify(obj));
{ "language": "en", "url": "https://stackoverflow.com/questions/59528474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WinJS List GridLayout header above list How to put header in listview with GridLayout. When I put header above listview my header take some height and last row in listview is not showed, because of header. I also found a way to set header in listview directly: data-win-options="{ header: select('.header') }"> With this my header is positioned on the left side of list, not above the list, like normal header should be. I did not see any example with listview GridLayout and header section above (for instance I wanna put search box and heading in header). Any example of this ? A: Two solutions are here: 1) This is answer I get from Microsoft: In the list view the WinJS.UI.GridLayout's viewport is loaded horizontally. You need to change the viewport's orientation to vertical. You can do this by attaching the event onloadingstatechanged event. args.setPromise(WinJS.UI.processAll().then(function () { listview.winControl.onloadingstatechanged = function myfunction() { if (listview.winControl.loadingState == "viewPortLoaded") { var viewport = listview.winControl.element.getElementsByClassName('win-viewport')[0]; viewport.className = 'win-viewport win-vertical'; } } })); and change the class win-horizontal to win-vertical. 2) Problem could be also solved adding standard html header and list below header, without data-win-options="{ header: select('.header') }" attribute. In that case we need to calculate height of the list: .list { height: calc(100% - headerHeight); }
{ "language": "en", "url": "https://stackoverflow.com/questions/36812166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to show the menu button in place of back button in Ionic I am working on the Ionic app and I have used navbar in my ionic app. When I move to other page, In place of menu button it is showing the back button. I don't want to show the back button, I always want to show the menu button in the navbar. This is page1.html: <ion-header> <ion-navbar hideBackButton="true"> <button ion-button menuToggle start> <ion-icon name="menu"></ion-icon> </button> </ion-navbar> </ion-header> It is only hiding the back button and not showing the menu button. I want to show the menu button in place of back button. This is page1.html: Another Try. <ion-header> <ion-navbar swipeBackEnabled="false"> <button ion-button menuToggle start> <ion-icon name="menu"></ion-icon> </button> </ion-navbar> </ion-header> This is not working. In this case, It is showing the back button. This is page1.ts: ionViewWillEnter() { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.navCtrl.setRoot(MerchandisePage); } So I decided the make the page as a root page but It is continuously loading. This is not working. This is my page.html: <button (click)="merchandisepage2()" class="mybtn22" ion-button round>View All</button> In this page, I have the button that will push to the other page. This is my page.ts: movetopage1() { this.navCtrl.push(Page1); } I don't want to show the back button, it should always show the menu button in the navbar. Any help is much appreciated. A: There is an issue with ionic when you have a custom button in the navbar and the page is not root. You can find a quick fix here.. Ionic 3: Menutoggle keeps getting hidden A: The solution is that, set the page to the root page. page.ts: movetopage1() { this.navCtrl.setRoot(Page1); } This is the method that comes in the Ionic sidebar theme. This is the one that comes in the Ionic sidebar theme: openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); }
{ "language": "en", "url": "https://stackoverflow.com/questions/54458571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: finding prime numbers c# the program should ask for a number and print all the primes numbers between 1 to the number the user entered... why isn't it working? bool isPrime = true; int primes = 0; Console.WriteLine("Enter a number"); int N = int.Parse(Console.ReadLine()); for (int i = 2; i <= N; i++) { for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { isPrime = false; } } if (isPrime) { Console.WriteLine(i + " is a prime number"); primes++; } } Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers"); A: You have put the boolean out of the loops. So, once it is false, it will never be true in other loops and this cause the issue. int primes = 0; Console.WriteLine("Enter a number"); int N = int.Parse(Console.ReadLine()); for (int i = 2; i <= N; i++) { bool isPrime = true; for (int j = 2; j <= Math.Sqrt(i); j++) { if (i % j == 0) { isPrime = false; } } if (isPrime) { Console.WriteLine(i + " is a prime number"); primes++; } } Console.WriteLine("Between 1 to " + N + " there are " + primes + " prime numbers"); A: First define this class: public static class PrimeHelper { public static bool IsPrime(int candidate) { if ((candidate & 1) == 0) { if (candidate == 2) { return true; } else { return false; } } for (int i = 3; (i * i) <= candidate; i += 2) { if ((candidate % i) == 0) { return false; } } return candidate != 1; } } then call it in your application: var finalNumber = int.Parse(Console.ReadLine()); for (int i = 0; i < finalNumber; i++) { bool prime = PrimeHelper.IsPrime(i); if (prime) { Console.Write("Prime: "); Console.WriteLine(i); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/52700891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Attempting to pull concatenated Q-urls, using data-type in a table Will try and explain as concisely as I can. Below is a dummy query based on one I'm attempting to edit. I'm trying to return two different types which are pulled from the same table. The first type of data is a numeric (a score from 1-10) The next type of data is a both numbers and letters, used to complete a URL. My problem is that the concat statement to return only null values. when I use the and statement to specify only URL data, the other column returns only null values. Is there a way I can change this, to pull only one type of data in one column separate to the other? Cheers select concat("example.com/",rs.answer,"/415x380.png") as Q_URL, Ease_of_use.score as "Ease_Of_use" from customer_feedback c left join response_data Ease_of_use on (Ease_of_booking_use.response_overall_id=c.id and Ease_of_use.data_type_id=1536) left join response_data rs on rs.customer_review_id=c.id join data_type dt on dt.id=rs.data_type_id where c.retailer_id in (678,1651) and rs.answer is not null and dt.response_type="photo_URL" group by c.id A: I'm not sure what you mean by "I use the and statement to specify only URL data", but I would use isnull function to provide a default value for NULLS concat("example.com/",isnull(rs.answer,"default value"),"/415x380.png") rather than using rs.answer is not null
{ "language": "en", "url": "https://stackoverflow.com/questions/34883199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement "array type" grammar like typescript with pegjs? my problem is in the implementation of "array type" like typescript. according to my grammar. In "array type" you can use "[]" after any type (eg string or int or even array again like int[][]). this is simplified version of my grammar: start = type type = array / bool / string / int string = "string" int = "int" bool = "bool" // problem array = t:type "[]" { return { kind: "array",type: t }} the above code throw an syntax error: Error: Maximum call stack size exceeded
{ "language": "en", "url": "https://stackoverflow.com/questions/75618800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python equivalent of matlab corr2 I want to know what is the python equivalent of the matlab function corr2 that gives the correlation coefficient between 2 matrices, return only one value. http://www.mathworks.com/help/images/ref/corr2.html I only found that the equivalent in python is scipy.signal.correlate2d but this returns an array. Thanks. A: Maybe this can be help you def mean2(x): y = np.sum(x) / np.size(x); return y def corr2(a,b): a = a - mean2(a) b = b - mean2(b) r = (a*b).sum() / math.sqrt((a*a).sum() * (b*b).sum()); return r A: import numpy print numpy.corrcoef(x,y) Where x and y can be 1-d or 2-d like arrays. Take a look at the docs here.
{ "language": "en", "url": "https://stackoverflow.com/questions/29481518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I know if I need to alloc and if I need to release? Completely new to Objective-C, trying to find out when I need to alloc and release objects. For example, I want to fetch some data from the Web. I found an article at Apple which has this code: NSURLRequest *theRequest=[NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; What I don't understand is: Why do they need to call alloc on the connection but not on the request? How do I know when I need alloc and when not? Similar questions for release. From what I read, I only ever need to release objects that were initialized using alloc/init. But all "initWithXXX" functions return autoreleased objects instead. Is this a hard rule, or just convention? Is there a way to find out if I need to release an object or not? A: Read the Cocoa Memory Management guide. You own an object only if the methods used to obtain it contains one of: * *new *alloc *retain *copy ... and you only need to release (i.e. relinquish ownership) if you own it. If you obtain an instance through a method not containing any of these, you don't own it and have to take ownership explicitly (using retain) if you need it. So, you need to alloc if you: * *want ownership or *if there is no convenience constructor available (and you thus have to use alloc/init) The initializer methods don't return autoreleased instances, they only initialize an allocd instance. A: initWithXXX: methods do not return autoreleased objects! somethingWithXXX: class methods, however, do. This is a convention (in that it's not compiler-enforced), but it's followed so closely that you can treat it as a hard rule. The Clang static analyzer will also complain if you don't follow it. requestWithURL: doesn't have "init" in the name. Also, requestWithURL: is called on the NSURLRequest class, whereas initWithRequest:delegate: is called on the NSURLConenction object returned by calling alloc on the NSURLConnection class. (I hope that all makes sense.) A: Please read the Memory Management Programming Guide. All of these are explained there. Also check out Learn Objective-C. Why do they need to call alloc on the connection but not on the request? Whenever you need to own an object to make it live longer than the function's scope, the object needs to be -retained. Of course you could use NSURLConnection* theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self]; but the connection will be -autoreleased. But because there's time for a connection to finish, this variable should be -retained to prevent the connection becoming invalid. Of course, then, you could do NSURLConnection* theConnection = [[NSURLConnection connectionWithRequest:theRequest delegate:self] retain]; But this is equivalent to +alloc → -init → -autorelease → -retain, the last two steps are redundant. Probably that's why Apple chooses to use +alloc/-init here. (BTW, this style would cause the static analyzer to complain. It's better to store theConnection as an ivar somewhere, e.g. in the delegate object.) On the other hand, the NSURLRequest is just a temporary object, so it needs to be -released when the function ends. Again, you could use NSURLRequest* theRequest = [[NSURLRequest alloc] initWithURL:...]; ... [theRequest release]; this is even more efficient, as the autorelease pool won't be filled up, but using this method one may forget to -release and cause a leak. But all "initWithXXX" functions return autoreleased objects instead. No, -init… should never return an -autoreleased object.
{ "language": "en", "url": "https://stackoverflow.com/questions/3328547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Drag and Drop function order var li = document.getElementsByTagName('li'); var ziel = document.getElementsByClassName('ziel'); var dragItem = null; for (var i of li) { i.addEventListener('dragstart', dragStart); i.addEventListener('dragend', dragEnd); } function dragStart() { dragItem = this; setTimeout(() => (this.style.display = 'none'), 0); } function dragEnd() { setTimeout(() => (this.style.display = 'block'), 0); dragItem = null; } for (j of ziel) { j.addEventListener('dragover', dragOver); j.addEventListener('dragenter', dragEnter); j.addEventListener('drop', Drop); } function Drop() { this.append(dragItem); } function dragOver(e) { e.preventDefault(); } function dragEnter(e) { e.preventDefault(); } Codepen I have the problem, every time I take a list item and drop it in the same <ul> it gets thrown to the bottom of the list every time. I want it to stay in the same place if I let it go in the same <ul> but if I drop it in another <ul> it should be listed at the bottom of course. Does anyone have any idea how I do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/70106950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: function && qualifier behaviour I'm confused by the following code: struct test { void f() & { std::cout << "&" << std::endl; } void f() const& { std::cout << "const&" << std::endl; } void f() && { std::cout << "&&" << std::endl; } void f() const&& { std::cout << "const&&" << std::endl; } void g() & { std::cout << "& -> "; f(); } void g() const& { std::cout << "const& -> " ; f(); } void g() && { std::cout << "&& -> "; f(); } void g() const&& { std::cout << "const&& -> "; f(); } test() {} //allow default const construction }; int main(int, char**) { test value; const test constant; value.g(); constant.g(); std::move(value).g(); std::move(constant).g(); } When I compile with clang 3.5 I get this output: & -> & const& -> const& && -> & const&& -> const& Why is the r-value qualifier being dropped here? And is there any way to call f from g with the right qualifier? A: It is because dereferencing1 this always produces an lvalue, irrespective of the fact that it is pointing to a temporary object or not. So when you write this: f(); it actually means this: this->f(); //or (*this).f() //either way 'this' is getting dereferenced here So the overload of f() which is written for lvalue is invoked from g() — and const-correctness is applied accordingly as well. Hope that helps. 1. Note that this is a prvalue; only after dereferencing it produces an lvalue. A: ref-qualifiers affect the implicit object parameter, §13.3.1/4: For non-static member functions, the type of the implicit object parameter is * *“lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier *“rvalue reference to cv X” for functions declared with the && ref-qualifier where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. Overload resolution is, roughly speaking, performed on the object argument to object parameter conversion just as any other argument->parameter conversion. However, f() is transformed into (*this).f() (§9.3.1/3), and *this is an lvalue. §5.3.1/1: The unary * operator performs indirection: […] and the result is an lvalue referring to the object or function to which the expression points. Hence the overloads of f with the & qualifier are preferred - in fact, the rvalue overloads are entirely ignored since initializers of rvalue object references must be rvalues (last bullet point in §8.5.3/5). Also, non-const references are preferred over const ones in overload resolution (§13.3.3.2/3, last bullet point concerning standard conversions). A: The call f() is interpreted as (*this).f(). The result of dereferencing a pointer is always an lvalue, so *this is an lvalue and the lvalue-qualified function is called. This behaviour even makes sense, at least to me. Most of the time the object referred to by an rvalue expression will either be destroyed at the end of the full-expression (a temporary) or at the end of the current scope (an automatic local variable that we choose to std::move). But when you're inside a member function, neither of those is true, so the object should not treat itself as an rvalue, so to speak. This is also why it makes sense for the name of an rvalue reference function parameter to be an lvalue within the function. If you want the rvalue-qualified f to be called, you can do this: std::move(*this).f(); A: Well, for f() the right qualifier is always lvalue reference since you use it on this. All your f calls are nothing else than this->f() and this is always lvalue. It doesn't matter that for the outside world the object is rvalue this is lvalue for the object insides.
{ "language": "en", "url": "https://stackoverflow.com/questions/30093923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Gradient Fill in Swift for iOS-Charts I am trying to create a nice gradient fill as seen in the demos on the ios-charts page. However, I cannot figure this out in swift vs obj-c. Here is the obj-c code: NSArray *gradientColors = @[ (id)[ChartColorTemplates colorFromString:@"#00ff0000"].CGColor, (id)[ChartColorTemplates colorFromString:@"#ffff0000"].CGColor ]; CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil); set1.fillAlpha = 1.f; set1.fill = [ChartFill fillWithLinearGradient:gradient angle:90.f]; Now here is my version of that in swift: let gradColors = [UIColor.cyanColor().CGColor, UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)] let colorLocations:[CGFloat] = [0.0, 1.0] let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradColors, colorLocations) What I am missing is the : Chart Fill fillWithLinearGradient I can't find the fillWithLinearGradient in the pod anywhere so I am a bit confused. Thanks in advance for any help! Rob A: For Swift 5 use the following: yourDataSetName.fill = LinearGradientFill(.... or yourDataSetName.fill = ColorFill(... More details you can read here: Charts A: I believe this is the code that you are looking for. You should be able to use the same ChartFill class in Swift to set set1.fill. let gradColors = [UIColor.cyanColor().CGColor, UIColor.clearColor.CGColor] let colorLocations:[CGFloat] = [0.0, 1.0] if let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradColors, colorLocations) { set1.fill = ChartFill(linearGradient: gradient, angle: 90.0) } A: This works perfectly (Swift 3.1 and ios-charts 3.0.1) let gradientColors = [UIColor.cyan.cgColor, UIColor.clear.cgColor] as CFArray // Colors of the gradient let colorLocations:[CGFloat] = [1.0, 0.0] // Positioning of the gradient let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) // Gradient Object yourDataSetName.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0) // Set the Gradient set.drawFilledEnabled = true // Draw the Gradient Result A: For swift4 let colorTop = UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor let colorBottom = UIColor(red: 255.0/255.0, green: 94.0/255.0, blue: 58.0/255.0, alpha: 1.0).cgColor let gradientColors = [colorTop, colorBottom] as CFArray let colorLocations:[CGFloat] = [0.0, 1.0] let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) // Gradient Object yourDataSetName.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0) A: Fill.fillWithLinearGradiant has been updated to LinearGradientFill A: Make sure to use the latest version of ios-charts. If you use CocoaPods to install ios-charts change this: pod 'Charts' to this pod 'Charts', '~> 2.2'
{ "language": "en", "url": "https://stackoverflow.com/questions/35133314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Are there any scope that escape all special characters in mysql query? I have a set of queries with randoms data that i want to insert in database. Randoms data may have any special characters. for example: INSERT INTO tablename VALUES('!^'"twco\dq'); Are there any scope that escape all special characters? please help. A: You can use \ character to escape special characters like below. See this DEMO if in doubt. INSERT INTO tablename VALUES('\!\^\'\"twco\\dq'); Per MySQL documentation, below are the defined escape sequences Table 9.1 Special Character Escape Sequences \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character. \b A backspace character. \n A newline (linefeed) character. \r A carriage return character. \t A tab character. \Z ASCII 26 (Control+Z). See note following the table. \\ A backslash (“\”) character. \% A “%” character. See note following the table. \_ A “_” character. See note following the table. A: No, there is no "scope" in MySQL to automatically escape all special characters. If you have a text file containing statements that were created with potentially unsafe "random values" like this: INSERT INTO tablename VALUES('!^'"twco\dq'); ^^^^^^^^^^^ You're basically screwed. MySQL can't unscramble a scrambled egg. There's no "mode" that makes MySQL work with a statement like that. Fortunately, that particular statement will throw an error. More tragic would be some nefariously random data, x'); DROP TABLE students; -- if that random string got incorporated into your SQL text without being escaped, the result would be: INSERT INTO tablename VALUES('x'); DROP TABLE students; --'); The escaping of special characters has to be done before the values are incorporated into SQL text. You'd need to take your random string value: !^'"twco\dq And run it through a function that performs the necessary escaping to make that value safe for including that as part of the the SQL statement. MySQL provides the real_escape_string_function as part of their C library. Reference https://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html. This same functionality is exposed through the MySQL Connectors for several languages. An even better pattern that "escaping" is to use prepared statements with bind placeholders, so your statement would be a static literal, like this: INSERT INTO tablename VALUES ( ? )
{ "language": "en", "url": "https://stackoverflow.com/questions/30575905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get the list of "jar's" used by an android application? I would like to find the list of "libraries" (not "shared libraries") that are in used by an Application ? Thanks a lot. A: You have to go trough analyzer tool like this. Quoting introduction: The purpose of this tool is to analyze Java™ class files in order to learn more about the dependencies between those classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/9885654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle Fusion Middleware Encryption / Decryption Sensitive Payload Data Does anyone know of a encryption / decryption technique for sensitive data in a message payload to prevent the information from showing up in audit logs? For example, a payload containing a password. The password should not appear in any logs. When the payload is received, the password needs to be encrypted and then just before the payload is forwarded the password needs to be decrypted. I'm looking for a generic solution that will work with OSB and BPEL. A: What you can do is create an Encryption/Decryption Web Service and use it in BPEL, OSB and you ADF application if you want, there are many Encryption Algorithms with this solution you should be able to choose what you want to use. A: Found the answer. It was in the Oracle code examples all along. See bpel-310 Partial Message encryption https://java.net/projects/oraclesoasuite11g/pages/BPEL
{ "language": "en", "url": "https://stackoverflow.com/questions/18619248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding Python mock's patch decorator I have a Python TestCase class where all test methods, except one, need to patch an object the same way. The other method need some other behavior from the same object. I'm using mock, so I did: @mock.patch('method_to_patch', mock.Mock(return_value=1)) class Tests(TestCase): @mock.patch('method_to_patch', mock.Mock(return_value=2)) def test_override(self): (....) But that's not working. When test_override is run, it still calls the patched behavior from the class decorator. After a lot of debugging, I found out that during the TestSuite build, the @patch around test_override is being called before the one around Tests, and since mock apply the patches in order, the class decorator is overriding the method decorator. Is this order correct? I was expecting the opposite and I'm not really sure how to override patching... Maybe with a with statement? A: Well, turns out that a good night sleep and a cold shower made me rethink the whole issue. I'm still very new to the concept of mocking, so it still hasn't sunk in quite right. The thing is, there's no need to override the patch to a mocked object. It's a mocked object and that means I can make it do anything. So my first try was: @mock.patch('method_to_patch', mock.Mock(return_value=1)) class Tests(TestCase): def test_override(self): method_to_patch.return_value = 2 (....) That worked, but had the side effect of changing the return value for all following tests. So then I tried: @mock.patch('method_to_patch', mock.Mock(return_value=1)) class Tests(TestCase): def test_override(self): method_to_patch.return_value = 2 (....) method_to_patch.return_value = 1 And it worked like a charm. But seemed like too much code. So then I went the down the road of context management, like this: @mock.patch('method_to_patch', mock.Mock(return_value=1)) class Tests(TestCase): def test_override(self): with mock.patch('method_to_patch', mock.Mock(return_value=2): (....) I think it seems clearer and more concise. About the order in which the patch decorators were being applied, it's actually the correct order. Just like stacked decorators are applied from the bottom up, a method decorator is supposed to be called before the class decorator. I guess it makes sense, I was just expecting the opposite behavior. Anyway, I hope this help some poor newbie soul like mine in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/12753909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Python object attributes as variables I am trying to assign a python object attribute a variable. Here is what I have been trying to do: from read import * import matplotlib.pyplot as plt import numpy as np data=table('data.txt') semi=data['data']['a'] ecc = data['data']['e'] incl= data['data']['i'] bias = data['data']['bias'] fig = plt.figure() ax1 = fig.add_axes([0.06, 0.1, 0.4, 0.35]) ax2 = fig.add_axes([0.06, 0.6, 0.4, 0.35]) ax3 = fig.add_axes([0.55, 0.6, 0.4, 0.35]) ax4 = fig.add_axes([0.55, 0.1, 0.4, 0.35]) aaa = getattr(ax1,'xaxis') nax={'ax1':ax1,'ax2':ax2,'ax3':ax3,'ax4':ax4} for a in sorted(nax): aax = {'xaxis':nax[a].get_xaxis()} for axis in ['bottom','left']: nax[a].spines[axis].set_linewidth(0.5) for axis in ['right','top']: nax[a].spines[axis].set_visible(False) for b in sorted(aax): nax[a].b.set_tick_position('bottom') When I run my code it says: Traceback (most recent call last): File "./test1.py", line 35, in <module> ax1.b.set_ticks_position('bottom') AttributeError: 'Axes' object has no attribute 'b' Originally it works when: ax1.xaxis.set_tick_position('bottom') but I need to make the XAxis attribute a variable for the sake of creating plotting templates. Any idea how to make the above thing work? A: Try x.set_tick_position('bottom') instead of ax1.x.set_tick_position('bottom'). x is already an attribute off of the ax1 object, so you don't need to access ax1 again. Furthermore, no need for getattr if you know the name of the attribute statically. You can just do x = ax1.xaxis. A: I would suggest to work on the objects directly. nax=[ax1,ax2,ax3,ax4] for ax in nax: for axis in ['bottom','left']: ax.spines[axis].set_linewidth(0.5) for axis in ['right','top']: ax.spines[axis].set_visible(False) ax.xaxis.set_tick_position('bottom')
{ "language": "en", "url": "https://stackoverflow.com/questions/52240927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript: Delete all iframe in DOM I would like to delete all iframe tags using JavaScript. Already tried using for and while but none of my attempts at deleting all iframe elements work for me. For example, let's use this RANDOM web page's HTML: <ul> <li>Sugar</li> <li>Fruits</li> </ul> <iframe src="">hello</iframe> <iframe src="">hello</iframe> <iframe src="">hello</iframe> <iframe src="">hello</iframe> <p>Click the button to delete the HTML elements</p> <button onclick="myFunction()">Try it</button> </body> </html> I tried these JavaSrcipts Attempt 1: function myFunction() { var elements = document.getElementsByTagName('iframe'); elements.parentNode.removeChild(elements); } Attempt 2: function myFunction() { var elements = document.getElementsByTagName("iframe"); while (elements.hasChildNodes()) { elements.removeChild(elements.lastChild); } } A: On modern browsers, you can use querySelectorAll and iterate over the NodeList directly, .remove()ing every iframe: document.querySelectorAll('iframe') .forEach(iframe => iframe.remove()); Or, for ES5 compatibility: Array.prototype.forEach.call( document.querySelectorAll('iframe'), function(iframe) { // can't use .remove: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove iframe.parentElement.removeChild(iframe); } ); A: A loop is the right way. Here's a simple version that will work cross-browser: function myFunction() { var elements = document.getElementsByTagName("iframe"); while (elements.length) { elements[0].parentNode.removeChild(elements[0]); } } That continually removes the last entry in the HTMLCollection. The HTMLCollection is live, so removing an element that's in that collection from the DOM also removes it from the collection, so that will reduce the length until eventually length is zero.
{ "language": "en", "url": "https://stackoverflow.com/questions/57073291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google API PHP Client library for Youtube is NOT connecting to Youtube I have been trying to work in youtube php client library but was unable to connect it. I have read and tried the google documentation (google developers) and github repository documentation (https://github.com/google/google-api-php-client#installation) for its installation using composer or cloning directly using git. But whenever I tried to surf the webpage, it always show a blank page. I tried to debug it; in which I came to know that the at the require_once 'vendor/autoload.php' line, it is stucking. My directory structure is: /var/www/html/test/index.php (My logical code) /var/www/html/test/google-php-api-client (Php client API folder) Try 1: Downloaded Directly from RELEASE (google-php-api-client-2.0.2) or by using Composer -- NOT WORKING require_once 'google-api-php-client/vendor/autoload.php'; $client = new Google_Client(); $client->setApplicationName("Client_Library_Examples"); $client->setDeveloperKey("MY_API_KEY"); $service = new Google_Service_Books($client); $optParams = array('filter' => 'free-ebooks'); $results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); foreach ($results as $item) { echo $item['volumeInfo']['title'], "<br /> \n"; } Try 2: Cloning from GitHub (git clone -b v1-master https://github.com/google/google-api-php-client.git ) -- NOT WORKING Please, help. Thanks set_include_path('google-api-php-client/src'); require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; In this try, the code is not executing after this line require_once 'Google/Service/YouTube.php'; Please, help.
{ "language": "en", "url": "https://stackoverflow.com/questions/38816350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Boost named_semaphore ownerwship in shared library I have a shared library where I created some functionality with semaphores. I am using boost::interprocess::named_semaphore with a thin wrapper around it. This library I am now linking dynamically with a small program. The problem I am experiencing is that the semaphores are not deleted after I run my application. This problem only happens on Windows, on Linux the semaphores do get deleted. Now, I am calling boost::interprocess::named_semaphore::remove in the destructor of the wrapper I mentioned because the named_semaphore does not do that itself. Also, if I call boost::interprocess::named_semaphore::remove directly in my application and not inside the library code the semaphore does get deleted! Strange! Any ideas of what could be going wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/55172707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In pygtk, why does importing the gtk module change my locale settings? I was surprised to find out that in a Pygtk program, merely importing the gtk module will change the currently loaded locale. If I run the following test program I get two different results in the print statements: import locale import pygtk print "Locale before:", locale.setlocale(locale.LC_ALL, None) import gtk print "Locale after:", locale.setlocale(locale.LC_ALL, None) The output: Locale before: C Locale after: LC_CTYPE=pt_BR.UTF-8;LC_NUMERIC=en_US.utf8;LC_TIME=en_US.utf8;LC_COLLATE=en_US.utf8;LC_MONETARY=en_US.utf8;LC_MESSAGES=en_US.utf8;LC_PAPER=en_US.utf8;LC_NAME=en_US.utf8;LC_ADDRESS=en_US.utf8;LC_TELEPHONE=en_US.utf8;LC_MEASUREMENT=en_US.utf8;LC_IDENTIFICATION=en_US.utf8 After the import gtk line the locale is configured according to my LC_xxx environment variables, as if someone had called locale.setlocale(locale.LC_ALL, ""). Is this intentional behavior from pygtk or gtk? Is it documented somewhere? If I do not want to use the locale settings from the LC_xxx family of environment variables, where should I be calling locale.setlocale? I want to be sure that the locale I set in my program will not be overwritten by by one of the libraries that I am using. A: One should use gtk_disable_setlocale() or whatever the language analogue is to bypass locales from GTK. Should be called prior to any subsequent calls of functions that enter the gtk main loop. That is the intended behavior of GTK, because it supports internationalization, but I am not sure why it changes the locale globally.
{ "language": "en", "url": "https://stackoverflow.com/questions/38753130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Avoiding duplicating graph in tensorflow (LSTM model) I have the following simplified code (actually, unrolled LSTM model): def func(a, b): with tf.variable_scope('name'): res = tf.add(a, b) print(res.name) return res func(tf.constant(10), tf.constant(20)) Whenever I run the last line, it seems that it changes the graph. But I don't want the graph changes. Actually my code is different and is a neural network model but it is too huge, so I've added the above code. I want to call the func without changing the graph of model but it changes. I read about variable scope in TensorFlow but it seems that I've not understand it at all. A: You should take a look at the source code of tf.nn.dynamic_rnn, specifically _dynamic_rnn_loop function at python/ops/rnn.py - it's solving the same problem. In order not blow up the graph, it's using tf.while_loop to reuse the same graph ops for new data. But this approach adds several restrictions, namely the shape of tensors that are passing through in a loop must be invariant. See the examples in tf.while_loop documentation: i0 = tf.constant(0) m0 = tf.ones([2, 2]) c = lambda i, m: i < 10 b = lambda i, m: [i+1, tf.concat([m, m], axis=0)] tf.while_loop( c, b, loop_vars=[i0, m0], shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])
{ "language": "en", "url": "https://stackoverflow.com/questions/49114306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to find Interaction effect(by generating impulse response for low and high regimes) in non linear Structural VAR framework? imagine we have five variable X1, X2, X3, X4, X5. what I am looking to find is the effect of X1 on X3,X4,X5 when the X2 is at its lowest and highest periods. for this, I applied the TVAR function in TsDyn package in r > data <- cbind(X5,X4,X3,X2,X1) > model <- TVAR(data, lag=1, nthresh=2, thDelay=1, trim=0.1, mTh=4, plot=TRUE) > plot(irf(model, regime = "L", boot = TRUE)) > plot(irf(model, regime = "H", boot = TRUE)) > plot(irf(model, regime = "M", boot = TRUE)) but i want modify the relationship among variables that X2,X3,X4,X5 affects X1 contemporously and X1 affects X3,X4,X5 in lag. So what I am looking for is to model this effect X1 on other variables in the high and low regimes of X2(interaction effect) with the ability to modify the relationship between the other Variables in the system. is there any package that is able to do Structural Vector autoregression Method in a non-linear framework? or how can I find out the effect of X1 on others when interacted with X2(when x2 is in its lowest decile and the highest decile)
{ "language": "en", "url": "https://stackoverflow.com/questions/74976720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get a content from textboxes in a database table with a Button click event? IWhat i wanna do So I tried this code but it coudnt get a connection with the Database. I the connection string is correct SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator"); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "insert into [kunde]Vorname()values(@nm)"; cmd.Parameters.AddWithValue("@nm", Vorname.Text); cmd.Connection = con; SqlCommand cmdd = new SqlCommand(); cmdd.CommandText = "insert into [kunde]Nachname()values(@nmm)"; cmdd.Parameters.AddWithValue("@nmm", Nachname.Text); cmdd.Connection = con; int a = cmd.ExecuteNonQuery(); if (a == 1) { MessageBox.Show("Dateien bitte"); } A: follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation. try { SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator"); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "insert into tableName(column1,column2) values(@nm,@nmm)"; cmd.Parameters.AddWithValue("@nm", Vorname.Text); cmd.Parameters.AddWithValue("@nmm", Nachname.Text); cmd.Connection = con; int a = cmd.ExecuteNonQuery(); if (a == 1) { MessageBox.Show("Dateien bitte"); } } catch (Exception ex) { MessageBox.Show("Error:"+ex.ToString()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/67850423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: creating dynamic menu using json, Html, JS & css for mobile platforms Am creating a dynamic menu from json object(downloaded from server) using html, js & css for mobile platforms without using libraries like JQuery i read like "document.write should not be used in event handlers like onLoad() or onclick() . its better to use DOM" plz give your valuable suggestions. A: You can create elements in javascript using DOM by using the .createElement() method. Example: Create a div for your menu and give it a css class name. menudiv = document.createElement('div'); menudiv.className = 'menu'; Now you can plug your json data into it by creating other elements. For example if you would like to create a link using DOM. link = document.createElement('a'); link.setAttribute('href', 'urlFromYourJsonData'); link.appendChild(document.createTextNode('Your Link Description')); menudiv.appendChild(link); and so on ... I suggest you have a look at: https://developer.mozilla.org/en/DOM/document.createElement and make your way from there. Edit: After seeing your second comment I also suggest you have a look at http://json.org to look up what JSON is. If you want to copy HTML code into your page you should use the innerHTML attribute. Example: div = document.createElement('div'); div.className = 'menu'; div.innerHTML = yourAjaxResponseHere;
{ "language": "en", "url": "https://stackoverflow.com/questions/6381827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can't access submenu link using mouseover i am trying to access submenu link "WHAT IS Flex?" under "About Flex" from http://flex.apache.org/ using selenium Web Driver. Whenever a mouseover is performed submenu is highlighted and disappears before i can access submenu. *Imported a few unnecessary packages.Please don't mind. Code: package com.ram.workingtitle; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.By; import org.openqa.selenium.Alert; import org.openqa.selenium.interactions.Actions; import static org.testng.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.testng.annotations.*; public class Mouseover { public static void main(String[] args) throws Exception { WebDriver driver= new FirefoxDriver(); driver.navigate().to("http://flex.apache.org/"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); /* Used Firepath for generating xpath */ WebElement element=driver.findElement(By.xpath(".//*[@id='nav']/li[2]/a")); WebElement sub=driver.findElement(By.xpath(".//*[@id='nav']/li[2]/ul/li[1]/a")); Actions action=new Actions(driver); action.moveToElement(element).build().perform(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); action.moveToElement(sub).build().perform(); System.out.println("executed"); } } Please help. Thanks&Regards, Ram. A: Actions action = new Actions(webDriver); action.moveToElement(webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/a"))) .build() .perform(); Thread.sleep(5000); webDriver.findElement(By.xpath("//*[@id='nav']/li[2]/ul/li[1]/a")).click(); Note: Thread.sleep is not a good practice. Just use implicit wait in your program or/and WebDriverWait.
{ "language": "en", "url": "https://stackoverflow.com/questions/26361971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clean double lines from joint statement in R? Having done a join operation to compare addresses with itself. library(tidyverse) library(lubridate) library(stringr) library(stringdist) library(fuzzyjoin) doTheJoin <- function (threshold) { joined <- trimData(d_client_squashed) %>% stringdist_left_join( trimData(d_client_squashed), by = c(address_full="address_full"), distance_col = "distance", max_dist = threshold, method = "jw" ) } The structure of d_client_squashed is the following and contains string values: Client_Reference adress_full C01 Client1 Name, Street, Zipcode, Town C02 Client2 Name, Street2, Zipcode2, Town2 ... ... The following operation: sensible_matches <- doTheJoin(0.2) View(sensible_matches %>% filter(Client_Reference.x != Client_Reference.y)) Results in the following output: Client_Reference.x address_full.x Client_Reference.y address_full.y Distance C01 Client1 Name, Street, Zipcode, Town C02 Client2 Name, Street2, Zipcode2, Town2 0.05486 C02 Client2 Name, Street2, Zipcode2, Town2 C01 Client1 Name, Street, Zipcode, Town 0.05486 ... ... ... ... ... The output of this join operation is double with reversed client information. The distance value is not unique. How can I subset the data frame to avoid those double lines? A: In order to remove the rows containing the same data, you can order them based on the contained elements, so there is not difference between rows containing the same pair of Client_Reference, and then delete the duplicates. After that you can filter the ones containing the same Client_Reference as you did. sensible_matches <- sensible_matches[!duplicated(t(apply(sensible_matches,1,sort))),] View(sensible_matches %>% filter(Client_Reference.x != Client_Reference.y))
{ "language": "en", "url": "https://stackoverflow.com/questions/68469139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OSX SSH tunnel from remote port to local I've created SSH tunnels in the past, but I'm having trouble on OSX. I'm looking to take a website's port 80, and direct it to my localhost:8080. When I run this command ssh -L 8080:<cloud_ip_address>:80 root@<cloud_ip_address> -N I get the default apache 'it works!' page. Why am I not getting the port 80 of the remote machine (which is running a web app)? UPDATE I still do not have a solution yet, but I have some more information. The page I am getting is the default page in /var/www/html but I am serving a Flask app which does not have static pages. A: Because HTTP protocol contains not only the IP address, but also the hostname (the URL you type into your browser), which differs between the <cloud_hostname> and localhost. The easiest way to trick it is to create /etc/hosts (there will be some OSX alternative -- search ...) entry redirecting the hostname of your remote machine to localhost. 127.0.0.1 <cloud_hostname> But note that in this case you will not be able to access the remote machine using the hostname!
{ "language": "en", "url": "https://stackoverflow.com/questions/41711596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating object in django model form with foreign key I am inserting a new record in my model form where my model is child form containing a foriegn key. When I am submitting the form it give error it should be instance of the foriegn key. Here is my model class MMEditidState(models.Model): state_id = models.IntegerField(primary_key = True) state_dremelid = models.ForeignKey(MMDremelDump, db_column = 'state_dremelid') assignee = models.CharField(max_length = 50) state = models.CharField(max_length = 50) role = models.CharField(max_length = 50) date = models.DateTimeField() class Meta: db_table = u'mm_editid_state' def __unicode__(self): return u'%s %s' % (self.state_dremelid, self.assignee) class MMEditidErrors(models.Model): error_id = models.IntegerField(primary_key = True) error_stateid = models.ForeignKey(MMEditidState, db_column = 'error_stateid') feature_type = models.CharField(max_length = 20) error_type = models.CharField(max_length = 20) error_nature = models.CharField(max_length = 50, null = True) error_details = models.CharField(max_length = 50) error_subtype = models.CharField(max_length = 200) date = models.DateTimeField() class Meta: db_table = u'mm_editid_errors' def __str__(self): return "%s" % (self.error_dremelid) def __unicode__(self): return u'%s' % (self.error_dremelid) Here is my View def qcthisedit(request, get_id): if request.method == "POST": form = forms.MMEditidErrorForm(get_id, request.POST) if form.is_valid(): form.save() return http.HttpResponseRedirect('/mmqc/dremel_list/') else: form = forms.MMEditidErrorForm(get_id) return shortcuts.render_to_response('qcthisedit.html',locals(), context_instance = context.RequestContext(request)) Here is my form class MMEditidErrorForm(forms.ModelForm): def __init__(self,get_id, *args, **kwargs): super(MMEditidErrorForm, self).__init__(*args, **kwargs) dremel = MMEditidState.objects.filter(pk=get_id).values('state_id') dremelid = int(dremel[0]['state_id']) self.fields['error_stateid'] = forms.IntegerField(initial = dremelid, widget = forms.TextInput( attrs{'readonly':'readonly'})) feature_type = forms.TypedChoiceField(choices = formfields.FeatureType) error_type = forms.TypedChoiceField(choices = formfields.ErrorType) error_nature = forms.TypedChoiceField(choices = formfields.ErrorNature) error_details = forms.TypedChoiceField(choices = formfields.ErrorDetails) error_subtype = forms.TypedChoiceField(choices = formfields.ErrorSubType) class Meta: model = models.MMEditidErrors exclude = ('error_id','date') When I submit the form I am getting the error Cannot assign "1": "MMEditidErrors.error_stateid" must be a "MMEditidState" instance. So I have added line get_id = MMEditidState.objects.get(pk = get_id) Now I am getting the below mentioned error int() argument must be a string or a number, not 'MMEditidState' in form = forms.MMEditidErrorForm(get_id, request.POST) Can someone help on this Thanks Vikram A: I have solved this problem by simply using the custom forms instead of model forms. While storing the data in the database, I managed myself in the views.py
{ "language": "en", "url": "https://stackoverflow.com/questions/5814789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: symfony in a home directory on debian with apache & userdir.conf After installing symfony in a user's directory (/home/user/public_html/my-project), the web directory does not appear by querying http://nameserver.com/~user/my-project and the following apache error appears by querying http://nameserver.com/~user/my-project/web : Internal Server Error If the installation is done in /var/www/html/my-project, everything works well. However, I have to install it in the user's directory :( Should I change/adapt the web/.htaccess if symfony is in /home/user/public_html ? Server is a debian with apache 2.4.25 /etc/apache2/mods-enabled/userdir.conf : <IfModule mod_userdir.c> UserDir public_html UserDir disabled root <Directory /home/*/public_html> AllowOverride FileInfo AuthConfig Limit Indexes Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Require method GET POST OPTIONS Require all granted </Directory> </IfModule> error.log apache2: AH01630: client denied by server configuration: /home/user/public_html/symfony/src/, referer: https://nameserver.com/~user/ /home/user/public_html/symfony/web/.htaccess: Options not allowed here, referer: https://nameserver.com/~user/ AH01630: client denied by server configuration: /home/user/public_html/symfony/app/, referer: https://nameserver.com/~user/ Symfony : -------------------- ------------------------------------------- Symfony -------------------- ------------------------------------------- Version 3.4.8 End of maintenance 11/2020 End of life 11/2021 -------------------- ------------------------------------------- Kernel -------------------- ------------------------------------------- Type AppKernel Name app Environment dev Debug true Charset UTF-8 Root directory ./app Cache directory ./var/cache/dev (773 KiB) Log directory ./var/logs (41 KiB) -------------------- ------------------------------------------- PHP -------------------- ------------------------------------------- Version 7.0.27-0+deb9u1 Architecture 64 bits Intl locale n/a Timezone Europe/Berlin (2018-04-24T16:37:05+02:00) OPcache true APCu false Xdebug false -------------------- ------------------------------------------- A: Probably Symfony .htaccess tries to change some settings that is not allowed by your configuration. At first I suggest change line: AllowOverride FileInfo AuthConfig Limit Indexes into AllowOverride all. Or if you can't do this for security reasons, look into symfony .htaccess, and try to change tihs AllowOverride directives list to work with this used in symfony .htacces.
{ "language": "en", "url": "https://stackoverflow.com/questions/50005119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to properly cancel MediaPlayer.prepare()? I am using the Android MediaPlayer to play a Video in my app. I use MediaPlayer.prepare() instead of MediaPlayer.prepareAsync() deliberately, because I want to be able to know when the statement is finished so that I can, for example, hide a progress bar. I realize that I could do this with a MediaPlayer.prepareAsync(), but since this would create an ugly overhead in my code, would only be used for this detection and probably wouldn't help in this situation anyway, I don't want to do that. When I start my activity with the video loading and I try to go back to the previous activity before it finished MediaPlayer.prepare(), it throws an IllegalStateException. All the steps I take before that are synchronized, so just catching the Exception and ignoring it would be possible here, however, I don't want to have throwing and catching an Exception as expected behavior if I can avoid it. I've already tried to call MediaPlayer.reset() while MediaPlayer.prepare() is running, but the same thing happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/55157082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sort the elements in java using priority queue I want to sort the elements using Priority Queue in Java. Here is my code. What is wrong in it? import java.io.*; import java.util.*; class PQ { static class IntCompare implements Comparator<Integer>{ @Override public int compare(Integer arg0, Integer arg1) { if(arg0 > arg1) return -1; else if(arg0 < arg1) return 1; else return 0; } } public static void main (String[] args) { int a[] = { 1, 3, 8, 5, 2, 6 }; Comparator<Integer> c = new IntCompare(); PriorityQueue<Integer> pq=new PriorityQueue<>(c); for(int i = 0; i < a.length; i++) pq.add(a[i]); System.out.println(pq); } } my output is: 8, 5, 6, 1, 2, 3 correct output: 8, 6, 5, 3, 2, 1 A: When you call System.out.println(pq), the toString method is called implicitly. The toString method of PriorityQueue extends from AbstractCollection, which Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). While the iterator of PriorityQueue is not guaranteed to traverse in particular order: The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. since the queue is based on heap. You can poll elements one by one to get ordered elements: while (pq.size() != 0) { System.out.print(pq.poll() + ","); // 8,6,5,3,2,1, } A: You should poll() all the elements until the queue is empty and save them somewhere to get them ordered. A: Try the following, list contains items in sorted order. The priority key by itself not maintain the elements in sorted order, it just keeps the top element as minimum or maximum based on your implementation of the PQ. public static void main (String[] args) { int a[]={1,3,8,5,2,6}; Comparator<Integer> c = new IntCompare(); PriorityQueue<Integer> pq=new PriorityQueue<>(c); for(int i=0;i<a.length;i++) pq.add(a[i]); ArrayList<Integer> list = new ArrayList<>(); while(!pq.isEmpty()){ list.add(pq.poll()); } for(Integer i : list) System.out.println(i); }
{ "language": "en", "url": "https://stackoverflow.com/questions/50796741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Case when SQL statement into variable I need to create a variable for a case when statement on sybase sql. I have this error from my sql client A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations. What do I need to do to use this variable the right way? DECLARE @OutputName CHAR(50) SELECT @OutputName= (case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW' when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS' when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then (case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then (case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) end), case when @OutputName='XSW' and (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST then 0 else a.M_NB end as 'NBI' from TP_COMPL_PL_REP b join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA) left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA) A: The problem is that you can't combine a SELECT which sets a variable with a SELECT which returns data on the screen. You set @OutputName to (case when (a.M_TRN_TYPE='XSW' .. ) but in the same SELECT you're also trying to display the results of: case when @OutputName='XSW' and (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST then 0 else a.M_NB end as 'NBI' You can't have these two in the same SELECT, in the format you're using. My recommendation is to split them, one for assigning the variable: DECLARE @OutputName CHAR(50) SELECT @OutputName= (case when (a.M_TRN_TYPE='XSW' or a.M_TRN_TYPE='SWLEG') then 'FXSW' when (a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS='C') then 'DCS' when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)='+1' then (case when b.M_DTE_SKIP_1>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) when a.M_TRN_TYPE<>'SWLEG' and a.M_TP_DVCS<>'C' and SUBSTRING(c.M_SP_SCHED0,1,2)<>'+1' then (case when b.M_DTE_SKIP_2>=a.M_TP_DTEEXP then 'SPOT' else 'OUTR' end) end) from TP_COMPL_PL_REP b join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA) left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA) and one for returning the data: SELECT case when @OutputName='XSW' and (case when c.M_DATESKIP='+1OD' then b.M_DTE_SKIP_1 else b.M_DTE_SKIP_2 end)=a.M_TP_DTEFST then 0 else a.M_NB end as 'NBI' from TP_COMPL_PL_REP b join TP_ALL_REP a on (a.M_NB=b.M_NB and a.M_REF_DATA=b.M_REF_DATA) left join DM_SPOT_CONTRACT_REP c on (a.M_NB=c.M_NB and a.M_REF_DATA=c.M_REF_DATA)
{ "language": "en", "url": "https://stackoverflow.com/questions/38003693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read JSON Object in PHP send with Android I´m currently having problems with exchanging JSON Objects between my Android Appliction and my Server Backend. For whatever reason $json = file_get_contents('php://input'); doesn´t work. $json always is null. The App sends the JSON Object with: url = new URL("www.example.com/app/request.php"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setChunkedStreamingMode(0); OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); OutputStreamWriter wr = new OutputStreamWriter(out); wr.write(request.toString()); Log.i(TAG, "OUT: " + request.toString()); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; StringBuilder stringbuilder = new StringBuilder(); while ((line = br.readLine()) != null){ stringbuilder.append(line); Log.i(TAG, "Stringline: " + line); } in.close(); Log.i(TAG, "Server responds: " + stringbuilder.toString()); The php-Script simply runs: <?php echo file_get_contents('php://input'); ?> So it simply returns the JSONObject back to the sender. Anyway the Logs says: OUT: {"firstname":"Foo"} Server responds: then breaks down on JSONObjection cause of course null can´t be parsed to JSONOBject. Appache error_log doesn´t display a error, otherwise the Android Log would also crash into a FileNotFoundException. access_ssllog logs POST on correct file by correct device. What did I do wrong? I rembember that php://input doesn´t work under some Server Conditions... What would be the alternatives? Any help is appreciated
{ "language": "en", "url": "https://stackoverflow.com/questions/42008988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to import/convert a CRA app into Razzle JS I'm new to Razzle and I'm trying to learn it. I took a Material-UI dashboard app and am trying to "import" or "convert" it into my blank-ish razzle app. I copied the contents of the CRA app's ./src into my razzle source at the right spot, referenced the right components, etc. At first, Razzle didn't like the @import statements in the CRA repo. I fixed that by using npm to install razzle-plugin-scss, which got me past that issue. But now I'm hitting something I don't understand at all (nor even how to go about finding a resolution): { Error: Cannot find module 'css-loader/locals' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:649:15) at Function.resolve (internal/modules/cjs/helpers.js:19:19) at module.exports (/home/user/my-project/node_modules/razzle-plugin-scss/index.js:106:31) at runPlugin (/home/user/my-project/node_modules/razzle/config/runPlugin.js:26:10) at plugins.forEach.plugin (/home/user/my-project/node_modules/razzle/config/createConfig.js:549:16) at Array.forEach (<anonymous>) at module.exports (/home/user/my-project/node_modules/razzle/config/createConfig.js:548:13) at main (/home/user/my-project/node_modules/razzle/scripts/start.js:48:22) at processTicksAndRejections (internal/process/next_tick.js:81:5) code: 'MODULE_NOT_FOUND' } I looked in css-loader and found that you (maybe?) need to instruct it to export locals with the exportOnlyLocals: true webpack directive. I'm not sure how to do that in Razzle. I found this page that shows an example of how to configure it through razzle.config.js, but it assumes more knowledge than I have. How can I configure webpack in Razzle to ... do something? ... to tell the underlying webpack plugin css-loader to load locals? Any help is much appreciated. Update It looks like this is caused by a breaking change in css-loader when it moved to v2.0.0. I still don't know what the solution is, but that's getting me closer. A: I ended up reverting to css-loader version 1.0.1 to fix the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/56211855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect HTTP to HTTPS in Spring Security or Tomcat Currently my Spring application only accepts request on HTTPS protocol. Below is a portion of the security-context.xml <http auto-config="false" use-expressions="true" disable-url-rewriting="true"> <intercept-url pattern="/signup*" access="permitAll" requires-channel="https" /> <intercept-url pattern="/login*" access="permitAll" requires-channel="https" /> <intercept-url pattern="/logout" access="permitAll" requires-channel="https" /> <form-login authentication-success-handler-ref="myAuthenticationSuccessHandler" login-page="/login" authentication-failure-url="/loginFailed" /> <intercept-url pattern="/**" access="isFullyAuthenticated()" requires-channel="https" /> <session-management session-authentication-error-url="/loginFailed"> <concurrency-control error-if-maximum-exceeded="true" max-sessions="2" /> </session-management> <logout invalidate-session="true" delete-cookies="JSESSIONID" /> </http> Now, I also would like the application to be able to redirect HTTP GET request to HTTPS when user visit the domain e.g from http://mydomain.com to https://mydomain.com. How can I achieve that ? Should I apply the changes in the security-context.xml, the controller or perhaps Tomcat itself ? A: I configured the redirection from HTTP(port 80) to HTTPS(port 443) within server.xml as <Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/17057219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regarding the using expressjs on Apache web server Can i use server side scripting language i.e expressjs on Apache web server for web site development ..?? Plz suggest tutorial for that any help about that is valuable to me... A: Read about node.js and expressjs. Node.js is server and Expressjs - web framework under Node.js. Apache is also web server and you don't need to use them together. You can place Node.js app behind Nginx or HAproxy if you want. A: You can use a Node.js app (built with Express or whatever you like) standalone, you don't need to use something in front of it. If you want to use something in front of it though, I suggest you use something like Nginx better than Apache, since Nginx is also asynchronous (like Node) and it's performs really well at serving static files. A: All you have to do is set node.js as proxy pass inside your site config here is text on it http://httpd.apache.org/docs/2.0/mod/mod_proxy.html Just decided which port to use and which framework :) eg. http://www.expressjs.com
{ "language": "en", "url": "https://stackoverflow.com/questions/8102776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Getting data from Php session I have created a php session and have assigned data like so session_start(); $_SESSION['desd']=$imgD; When i try to retrieve it on other page i get nothing. this is what i have done on second page, session_start(); $_imgname = $_SESSION['desd']; How to do that? A: The code is valid, assuming that the variable $imgD is defined (var_dump is one way of checking this, but print or echo may also work). Check to ensure that cookies are enable in your browser. Also, be sure that session_start() comes near the top of your script, it should be the first thing sent to the client each time. To test a session, create "index.php" with the following code: <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = " . $_SESSION['views']; ?> Reload the page several times and you should see an incrementing number. An example of passing session variables between two pages is as follows: PageOne.php <?php session_start(); // makes an array $colors=array('red', 'yellow', 'blue'); // adds it to our session $_SESSION['color']=$colors; $_SESSION['size']='small'; $_SESSION['shape']='round'; print "Done"; ?> PageTwo.php <?php session_start(); print_r ($_SESSION); echo "<p>"; //echo a single entry from the array echo $_SESSION['color'][2]; ?> For simplicity put PageOne.php and PageTwo.php in the same directory. Call PageOne.php and then PageTwo.php. Try also tutorials here, here, and here. A: If you call session_start(), the server gets the session ID from cookies. Maybe something is wrong with the cookies because the code is valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/12514331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }