text
stringlengths
15
59.8k
meta
dict
Q: How to check session timeout configured in Jboss application I am using a spring based application with MS SQL server and using hibernate or native sql to fetch data from the database. However one of the problems I am facing is session timeout after around 2 minutes. The session timeout configured for the application in web.xml is 20 minutes. Ideally if session is idle it does not get logged out. But whenever there is a database related operation that would take more than 2 minutes to execute the session is killed. Can someone help me with this? Using Jboss 7.3
{ "language": "en", "url": "https://stackoverflow.com/questions/73257788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create grid data in SAS using info from another dataset I need to get a dataset of a uniform grid 20x20 using info from SASHELP.CARS so that x and y variables are obtained as follows: do y = min(weight) to max(weight) by (min(weight)+max(weight))/20; do x = min(horsepower) to max(horsepower) by (min(horsepower)+max(horsepower))/20; output; end; end; Weight and HorsePower are variables of SASHELP.CARS. Furthermore the grid dataset has to have two more columns EnginSizeMean LengthMean with the same value in each row that equals mean(EnginSize) and mean(Length) from SASHELP.CARS (need all this to build dependency graph for regression model). A: First calculate the statistics you need to use. proc summary data=sashelp.cars ; var weight horsepower enginesize length ; output out=stats min(weight horsepower)= max(weight horsepower)= mean(enginesize length)= / autoname ; run; Then use those values to generate your "grid". data want; set stats; do y = 1 to 20 ; weight= weight_min + (y-1)*(weight_min+weight_max)/20; do x = 1 to 20 ; horsepower = horsepower_min + (x-1)*(horsepower_min+horsepower_max)/20; output; end; end; run;
{ "language": "en", "url": "https://stackoverflow.com/questions/65360598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML to Powershell Hashtable <Test> <TLC>FWE</TLC> <Crew3LC>KMU</Crew3LC> <MyText>Hello World</MyText> </Test> Hello there, above you see me .xml with the name "test.xml". Down below you see my powershell beginnings. What I want do to is the following, but I don't know where exactly to begin. I want to retrieve the data from the .xml file and save the values into my hashtable. The hashtable itself is more like a template, which needs to be filled. The XML has got the same naming like the hashtable TLC = TLC etc, but I need the Value from the XML in my hashtable. I would do it with foreach and a -matching operator and my filtered selections (Hashkey, XML Name, XML Name Value). Matching the Hashkey with XML Name and if $true save XML.Name.Value to Hashtable. I Hope you get my point... I tried some of my knowledge but everything faild so far. My you guys could help me?! # XML Path $XMLSource = "C:\Test\Test.xml" # Tempalte Hashtable $XMLTemplatevalues = @{ TLC = 'TLC' Crew3LC = 'Crew3LC' MyText = 'MyText' } # Get XML Content [xml]$GetXMLContent = Get-Content $XMLSource #HashKey $XMLTemplatevalues.Keys #XML Name $GetXMLContent.DocumentElement.ChildNodes.Name #XML Name - Value $GetXMLContent.DocumentElement.ChildNodes.'#text' A: A simple solution that works with simple documents such as the one in your question (PSv4+): $xmlDoc = [xml] (Get-Content -Raw "C:\Test\Test.xml") # Initialize the results hashtable; make it ordered to preserve # input element order. $ht = [ordered] @{} # Loop over all child elements of <Test> and create matching # hashtable entries. $xmlDoc.Test.ChildNodes.ForEach({ $ht[$_.Name] = $_.InnerText }) # Output the resulting hashtable. $ht With your sample document this yields: Name Value ---- ----- TLC FWE Crew3LC KMU MyText Hello World
{ "language": "en", "url": "https://stackoverflow.com/questions/50859778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I render an image to the browser rather than force it to download? I'm using Azure blob storage to house images and DOMPdf to create PDF files. The issue I'm facing is that DOMPdf will not "Download files" to display them. My current controller, contacts Azure blob storage, grabs the file and spits it out as a download. Instead, I have tried to use the response()->file() method in Laravel to display the image instead: // Assume $file holds the file content from Azure Blob Storage \Illuminate\Support\Facades\File::append(Storage::disk('local')->path("chunks/{$fileToken}"), $file); $mimeType = mime_content_type(Storage::disk('local')->path("chunks/{$fileToken}")); # Check if we can render this as an image if (in_array($mimeType, ['image/jpeg','image/gif','image/png','image/bmp','image/svg+xml'])) { $headers = [ 'Content-Type' => $mimeType, 'Content-Disposition' => sprintf('inline; filename="%s"', $realPath->filename) ]; $response = response()->file(Storage::disk('local')->path("chunks/{$fileToken}"), $headers); # Delete from local disk \Illuminate\Support\Facades\File::delete(Storage::disk('local')->path("chunks/{$fileToken}")); return $response; } # Delete from local disk \Illuminate\Support\Facades\File::delete(Storage::disk('local')->path("chunks/{$fileToken}")); // Do normal download functionality Now, the mime_content_type successfully identifies the PNG I am trying, it creates the file in the chunks directory and if I remove the delete, I can open it as the PNG perfectly fine. The issue I'm getting is the browser is not rendering the image. Infact, it is rendering the headers? How can I render this image out to the browser so I can then access the image in DOMPdf?
{ "language": "en", "url": "https://stackoverflow.com/questions/74053042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Develop PhoneGap app for old android device I have a simple, but useful app for an old android device I want to develop with Cordova PhoneGap. Going through their tutorial, by default, the current version of cordova requires android level 14 api to build apps, but I've done the following to get the app to build on my old 2.3.6 device... In /config.xml add the following in the platform->android tag <platform name="android"> <allow-intent href="market:*" /> <preference name="android-minSdkVersion" value="10" /> <preference name="android-targetSdkVersion" value="10" /> </platform Edit these lines in the /platforms/android/AndroidManifest.xml file <manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="fi.blogspot.codinginthecold" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" tools:overrideLibrary="org.apache.cordova" /> Like I said, the HelloWorld app compiles on the device without error, but when I actually run the app, it says the app has unfortunately stopped. My question: As the above method failed to run the simplest app, what is best way to develop PhoneGap apps for old android devices? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/46541855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting data from JSON with React mapping I know this is probably a question that is easily answered, but I cannot figure it out after a few hours. I am trying to map over this JSON but it keeps saying "props.shows.map" is not a function, however the same works for another bit of data. I am trying to get things like 'id' and 'name' from the data. The mapping works with this link: https://api.tvmaze.com/search/shows?q=\%22Terrance%20House\%22 Here is the JSON that doesn't work/can't seem to get the information from: https://api.tvmaze.com/shows/34275/episodes import Layout from '../components/MyLayout' import fetch from 'isomorphic-unfetch' import Link from 'next/link' const ShowLink = ({ show }) => ( <li key={show.id}> <Link as={`/episode/${show.id}`} href={`/episodes/id=${show.id}`}> <a>{show.name}</a> </Link> <style jsx>{` li { list-style: none; margin: 5px 0; } a { text-decoration: none; color: blue; font-family: "Arial"; } a:hover { opacity: 0.6; } `}</style> </li> ) /* <h1>{props.show.name}</h1> <p>{props.show.summary.replace(/<[/]?p>/g, '')}</p> <img src={props.show.image.medium}/> */ const Post = (props) => ( <Layout> <h1>Terrace House Episodes</h1> <ul> {props.shows.map(({show}) => ( <ShowLink key={show} value={show} /> ))} </ul> </Layout> ) Post.getInitialProps = async function () { //const { id } = context.query //const res = await fetch(`https://api.tvmaze.com/shows/${id}`) //const show = await res.json() //const res = await fetch(`http://api.tvmaze.com/seasons/34275/episodes`); const res = await fetch('https://api.tvmaze.com/shows/34275/episodes'); const data = await res.json() return { shows: data } } export default Post A: The problem is you are attempting to destructure a property (namely the 'show' property) which doesnt exist in your json object when you make your map call. Heres an example of destructuring (in case you arent familiar): const example= { show: 'Seinfeld', }; const { show } = example; In the last line the show property is being taken from the example object and assigned to a variable named show (so the variable show would hold the value 'Seinfeld'). In your code below you are also destructuring a property named show from each json object in the map function call: props.shows.map(({show}) => ( <ShowLink key={show} value={show} /> )); In the working json each object has a show: property which itself is an object containing data you want. In the not working json there is no show: property so you are attempting to access a property that doesnt exist which would return null. So to solve the issue in the case of the not working url, you simply need to remove the destructuring: props.shows.map((show) => ( <ShowLink key={show} value={show} /> ));
{ "language": "en", "url": "https://stackoverflow.com/questions/49581141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I debug the vim part of the poshcomplete vim plugin? As I love vim, I found two posts that are interesting in order to use PS with vim: * *Help starting vim from PSISE with the file edited in PSISE. * *I found this following line: $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("edit with Vim",{$cur=$psISE.CurrentFile; saps "C:\Program Files (x86)\vim\vim74\gvim.exe" $cur.FullPath -wait; $psise.currentpowershelltab.files.remove($cur); $psISE.currentpowershelltab.files.add($cur.fullpath) },'Ctrl+Alt+v') *open PSISE: psise> ise $profile Paste the line in the file that PSISE opens. After that you can open the current file with vim by pressing Ctrl-Alt-V. *poshcomplete helps to complete PowerShell language once in vim. * *I've installed the poshcomplete vim plugin. I've installed webapi-vim and vimproc.vim as per this link. PROBLEM: After starting the server with the command :call poshcomplete#StartServer() everything is OK. The function is found in poshcomplete, the variables for port or other detail were declared. If then I try to call the completion Ctrl-X,Ctrl-O after, for instance, the word "write" I receive the following error: : omni completion(^O^N^P) Pattern not found. But if I check what poshcomplete is returning from server (I use httprequester with the line "http://localhost:1234/poshcomplete?text=write") I can see that the answer from the web server is correct. Indeed I can see all the commands that have "write" in it. I don't understand what's going on from the vim side that recover that data to show it for completion, because I had two times the plugin working, but then it stopped working. I think there's a problem of sync between the moment the result is exposed by the server and the moment vim try to get it. I'm probably wrong, but I'd like to correct this if someone can help. A: Could you modify autoload/poshcomplete.vim in your vimfiles directory like this? let res = webapi#http#post("http://localhost:" . g:PoshComplete_Port . "/poshcomplete/", \ {"text": buffer_text}, {}, s:noproxy_option) + echo 'Response: ' . res.content return webapi#json#decode(res.content) Press <C-X><C-O> with this code, show response from server.
{ "language": "en", "url": "https://stackoverflow.com/questions/32732966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating and Resolving Comments in Google Sheet I would like to update/resolve comments on google spreadsheets using a service account. Currently following the GDrive V3 API guide; The API explorer on the page works well but I am unable to replicate it on Python. GET and LIST methods work fine but PATCH keeps returning the old content and wouldn't update. Heres my code: from googleapiclient.discovery import build from google.oauth2 import service_account credentials_file = './.config/gspread/service_account.json' scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata'] credentials = service_account.Credentials.from_service_account_file(credentials_file, scopes=scope) service = build('drive', 'v3', credentials = credentials) service.comments().update(commentId=<<commentId>>, fileId=<<fileId>>, fields='content', body={'content': 'new comment', 'resolved': True}).execute() >>> returns {'content': 'old comment'} Any idea what's wrong? Appreciate your help! A: As suggested by Mateo, patching of comments works when using the OAuth 2.0 Client Credentials (Secret key file)
{ "language": "en", "url": "https://stackoverflow.com/questions/65677850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: find time shift between two similar waveforms I have to compare two time-vs-voltage waveforms. Because of the peculiarity of the sources of these waveforms, one of them can be a time shifted version of the other. How can i find whether there is a time shift? and if yes, how much is it. I am doing this in Python and wish to use numpy/scipy libraries. A: This function is probably more efficient for real-valued signals. It uses rfft and zero pads the inputs to a power of 2 large enough to ensure linear (i.e. non-circular) correlation: def rfft_xcorr(x, y): M = len(x) + len(y) - 1 N = 2 ** int(np.ceil(np.log2(M))) X = np.fft.rfft(x, N) Y = np.fft.rfft(y, N) cxy = np.fft.irfft(X * np.conj(Y)) cxy = np.hstack((cxy[:len(x)], cxy[N-len(y)+1:])) return cxy The return value is length M = len(x) + len(y) - 1 (hacked together with hstack to remove the extra zeros from rounding up to a power of 2). The non-negative lags are cxy[0], cxy[1], ..., cxy[len(x)-1], while the negative lags are cxy[-1], cxy[-2], ..., cxy[-len(y)+1]. To match a reference signal, I'd compute rfft_xcorr(x, ref) and look for the peak. For example: def match(x, ref): cxy = rfft_xcorr(x, ref) index = np.argmax(cxy) if index < len(x): return index else: # negative lag return index - len(cxy) In [1]: ref = np.array([1,2,3,4,5]) In [2]: x = np.hstack(([2,-3,9], 1.5 * ref, [0,3,8])) In [3]: match(x, ref) Out[3]: 3 In [4]: x = np.hstack((1.5 * ref, [0,3,8], [2,-3,-9])) In [5]: match(x, ref) Out[5]: 0 In [6]: x = np.hstack((1.5 * ref[1:], [0,3,8], [2,-3,-9,1])) In [7]: match(x, ref) Out[7]: -1 It's not a robust way to match signals, but it is quick and easy. A: scipy provides a correlation function which will work fine for small input and also if you want non-circular correlation meaning that the signal will not wrap around. note that in mode='full' , the size of the array returned by signal.correlation is sum of the signal sizes minus one (i.e. len(a) + len(b) - 1), so the value from argmax is off by (signal size -1 = 20) from what you seem to expect. from scipy import signal, fftpack import numpy a = numpy.array([0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 0, 0, 0, 0]) b = numpy.array([0, 0, 0, 0, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0]) numpy.argmax(signal.correlate(a,b)) -> 16 numpy.argmax(signal.correlate(b,a)) -> 24 The two different values correspond to whether the shift is in a or b. If you want circular correlation and for big signal size, you can use the convolution/Fourier transform theorem with the caveat that correlation is very similar to but not identical to convolution. A = fftpack.fft(a) B = fftpack.fft(b) Ar = -A.conjugate() Br = -B.conjugate() numpy.argmax(numpy.abs(fftpack.ifft(Ar*B))) -> 4 numpy.argmax(numpy.abs(fftpack.ifft(A*Br))) -> 17 again the two values correspond to whether your interpreting a shift in a or a shift in b. The negative conjugation is due to convolution flipping one of the functions, but in correlation there is no flipping. You can undo the flipping by either reversing one of the signals and then taking the FFT, or taking the FFT of the signal and then taking the negative conjugate. i.e. the following is true: Ar = -A.conjugate() = fft(a[::-1]) A: It depends on the kind of signal you have (periodic?…), on whether both signals have the same amplitude, and on what precision you are looking for. The correlation function mentioned by highBandWidth might indeed work for you. It is simple enough that you should give it a try. Another, more precise option is the one I use for high-precision spectral line fitting: you model your "master" signal with a spline and fit the time-shifted signal with it (while possibly scaling the signal, if need be). This yields very precise time shifts. One advantage of this approach is that you do not have to study the correlation function. You can for instance create the spline easily with interpolate.UnivariateSpline() (from SciPy). SciPy returns a function, which is then easily fitted with optimize.leastsq(). A: Here's another option: from scipy import signal, fftpack def get_max_correlation(original, match): z = signal.fftconvolve(original, match[::-1]) lags = np.arange(z.size) - (match.size - 1) return ( lags[np.argmax(np.abs(z))] ) A: If one is time-shifted by the other, you will see a peak in the correlation. Since calculating the correlation is expensive, it is better to use FFT. So, something like this should work: af = scipy.fft(a) bf = scipy.fft(b) c = scipy.ifft(af * scipy.conj(bf)) time_shift = argmax(abs(c)) A: Blockquote (A very late answer) to find the time-shift between two signals: use the time-shift property of FTs, so the shifts can be shorter than the sample spacing, then compute the quadratic difference between a time-shifted waveform and the reference waveform. It can be useful when you have n shifted waveforms with a multiplicity in the shifts, like n receivers equally spaced for a same incoming wave. You can also correct dispersion substituting a static time-shift by a function of frequency. The code goes like this: import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, ifft, fftshift, fftfreq from scipy import signal # generating a test signal dt = 0.01 t0 = 0.025 n = 512 freq = fftfreq(n, dt) time = np.linspace(-n * dt / 2, n * dt / 2, n) y = signal.gausspulse(time, fc=10, bw=0.3) + np.random.normal(0, 1, n) / 100 Y = fft(y) # time-shift of 0.235; could be a dispersion curve, so y2 would be dispersive Y2 = Y * np.exp(-1j * 2 * np.pi * freq * 0.235) y2 = ifft(Y2).real # scan possible time-shifts error = [] timeshifts = np.arange(-100, 100) * dt / 2 # could be dispersion curves instead for ts in timeshifts: Y2_shifted = Y2 * np.exp(1j * 2 * np.pi * freq * ts) y2_shifted = ifft(Y2_shifted).real error.append(np.sum((y2_shifted - y) ** 2)) # show the results ts_final = timeshifts[np.argmin(error)] print(ts_final) Y2_shifted = Y2 * np.exp(1j * 2 * np.pi * freq * ts_final) y2_shifted = ifft(Y2_shifted).real plt.subplot(221) plt.plot(time, y, label="y") plt.plot(time, y2, label="y2") plt.xlabel("time") plt.legend() plt.subplot(223) plt.plot(time, y, label="y") plt.plot(time, y2_shifted, label="y_shifted") plt.xlabel("time") plt.legend() plt.subplot(122) plt.plot(timeshifts, error, label="error") plt.xlabel("timeshifts") plt.legend() plt.show() See an example here
{ "language": "en", "url": "https://stackoverflow.com/questions/4688715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: SCSS + Vue Components I am using <style lang="scss"> inside my single file Vue components. But in every single component using my color variables, I need to import the file, ie: @import "./../../../sass/variables";. I am using Laravel Mix to compile the sass + js. Is there any way to make the varaible accessible without needing to import them? A: Please check this related issue on github, I think it has the right answer for you: https://github.com/vuejs/vue-loader/issues/328 Specially look for mister shaun-sweet's answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/47990915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Access to the webpage was denied Django template <span style="float: left; padding-top: 5px;"><a href="/media/{{image.path}}">{{image.name|slice:":25"}}</a></span> settings.py MEDIA_ROOT = '/tmp/' MEDIA_URL = '/media/' urls.py (r'^media/(?P<path>.*)$', 'incident.views.media_serve_protected'), def media_serve_protected(request, path): if path.startswith("{id}/".format(id=request.user.id)): return serve(request, path, settings.MEDIA_ROOT) else: return HttpResponseForbidden() I am able to upload the images.The uploaded images are get saved in tmp folder.I can see the image name with image url,but for viewing if i click the image url i am getting the error "Access to the webpage was denied You are not authorized to access the webpage at http://192.168.100.12/media/root/16/20130816235304-photo0015.jpg. You may need to sign in." A: Your media_serve_protected function is returning a Forbidden response if the url does not start with media/<id>. But your url is in the form media/root/<id>.
{ "language": "en", "url": "https://stackoverflow.com/questions/18277911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't access parent form's button properties through user control form I have parent form called MainBackground and a user control named LoginUI. LoginUI is docked into the MainBackground. I need to change enability of a button (InfoButton) located in parent form to "true" when user clicks on the button "Log in" in the control form. But I can't access the parent button's properties. Control form's button clicking event code: private void button1_Click(object sender, EventArgs e) { MainBackground.infoButton.Enabled = true; } I tried solving it with parent controls, but still it doesn't seem to work. Thanks for any help! A: You can't access MainBackground.infoButton from LoginUI because infoButton is not static. to solve this you could inject MainBackground trough a property like the example below public partial class LoginUI : UserControl { public MainBackground MainBackground { get; set; } ... } in MainBackground you should initalize your LoginUI.MainBackground propery loginUI1.MainBackground = this; Make sure to make infoButton public by setting the modifiers property to public Now you can access MainBackground.loginUI1 private void login_Click(object sender, EventArgs e) { MainBackground.InfoButton.Enabled = true; } A: The method described in your question of Enabling the MainBackground forms InfoButton when the Login button is pressed is a common action. However, instead of directly binding the two items where the LoginUI Control is now forever bound to the MainBackground Form, you should de-couple the two by using Events. The LoginUI Control should publish an event, perhaps called, LoginClicked. The MainBackground form can then subscribe to this event and execute whatever actions are required when the Login button is clicked. In the LoginUI Control, declare an event: public event EventHandler LoginClicked; And, raise it whenever the Login button is pressed: private void login_Click(object sender, EventArgs e) { OnLoginClicked(EventArgs.Empty); } protected virtual void OnLoginClicked(EventArgs e) { EventHandler handler = LoginClicked; if (handler != null) { handler(this, e); } } Finally, in the MainBackground form class, subscribe to the LoginClicked event loginUI.LoginClicked += this.loginUI_LoginClicked; Handle the LoginClicked event like this: private void loginUI_LoginClicked(object sender, EventArgs e) { InfoButton.Enabled = true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/49378726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How can I handle some special character being returned as such on my razor page? I have the following razor syntax on my view page that will return a label as the following format: "Recherce d & # 3 9 ; address" but it should be: "Recherce d'address". This is caused by a é in my translation file. <div class="form-group"> <label class="col-sm-2 control-label"> @xxx.Tools.Language.Translate(xxx.Tools.Language.Keys.Address_Search, ViewBag):</label></div> I'm not sure how to resolve the following syntax to prevent this. My intuition was to use HTML.Encode.Text but I'm getting lost with the syntax... A: @Html.Raw() is your friend here. See: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.2 Note that this presents a bit of a security risk in that if a user enters an address containing JavaScript, iFrame, etc they can produce an undesired effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/55957273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LoadLibrary fails with lasterror 0x43 The network name cannot be found My program dynamically loads a number of DLL's using LoadLibrary and (on literally all machines) these load successfully, on one machine some of these DLL's do not get loaded. I added code to trace lasterror and this reports "0x43 The network name cannot be found.". The machine in question is running Windows 7 Enterprise x64, the DLL is a 32 bit DLL, this shouldn't be an issue and (in fact) this is my development environment. I also tried converting the name of the DLL (which includes the path) to a short filename and used that in the call to LoadLibrary, I still got the same error. Any ideas? //*eggbox A: Download Procmon let it run and filter for you dll name. This will immediately give you the locations where the dll was searched and which access path did return 0x43. You get even the call stacks if you have the pdbs for your code as well (C/C++ only no managed code). A: Run the program through Dependency Walker in its Profile mode and let that fine tool tell you exactly what is going wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/10541328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lengthy Japanese Filenames sent as attachment using javamail are getting corrupted We are sending files with lengthy Japanese filenames ( >30 characters) as attachments with mails. We are using Javamail to send mails. Before adding the attchment to the mail, the fielnames are being encoded in Shift-JIS using the following piece of code. fileName=MimeUtility.encodeText(fileName,"SJIS",null); This however works fine if the name of the file is small (Japanese). It works fine in windows, not in unix. Even I tried with utf-8 encoding as well. Any pointers/solutions to the above problem? Thank you,
{ "language": "en", "url": "https://stackoverflow.com/questions/27127303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix layout management I'm doing a clone of Minesweeper in Java. Everything was fine, but I wanted to add a counter at the top. And now, some buttons are off the screen. What layouts I have to change to repair it? Before adding counter: (https://i.imgur.com/cSKmCGr.jpg) After adding "counter" (https://i.imgur.com/fbMQqQz.jpg) And here's my code: public static JPanel generate() { i2w = row*row-ilosc_min; przyc = new Sap[row][row]; JPanel all = new JPanel(); //panel that contains counter and buttons JPanel licznik = new JPanel(); //Counter licznik.setBackground(Color.red); licznik.setPreferredSize(new Dimension(MyFrame.wym-50, 50)); //counter takes 50 px height and full width of frame all.add(licznik); JPanel panel = new JPanel(); //Buttons panel panel.setVisible(true); panel.setLayout(new GridLayout(row, row)); for(int x = 0; x < row; x++) { //creating buttons for(int y = 0; y < row; y++) { Sap sp = new Sap(x, y); //My buttons that extends JButton przyc[x][y] = sp; panel.add(sp); //Adding button to panel } } all.add(panel); //All contains counter and buttons return all; //Returning it } When I don't create a counter panel, buttons are like in the second photo. Sorry for any mistakes, English is not my main language. A: first do you know what was the default layout for both of your panel's ? and the shortest work solution is to make the root panel use BorderLayout and when adding the counter call on your root panel object add(BorderLayout.NORTH,theCounterObject); and for the button's panel call this on the root panel too add(BorderLayout.CENTER,theButtonsPanel); this would solve it in shortened version but it's better to learn not a sip or part but all about layout managers as they are very important for swing , here is start A Visual Guide to Layout Managers. the pack() method is not necessary but it's a great way to fetch the perfect size it was a good idea from the comment but the problem was about your layout witch was FlowLayout and it's the default for panel but you should do it after changing the layout .
{ "language": "en", "url": "https://stackoverflow.com/questions/55781063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Presenting a new window/view controller in Swift import UIKit class StartUp: UIViewController { var window: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds) var window2: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds) var window3: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds) var window4: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds) var startController: UIViewController? var startController2: UIViewController? var startController3: UIViewController? var startController4: UIViewController? var newViewController = false let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) override func viewDidLoad() { super.viewDidLoad() var currentUser = PFUser.currentUser() //Get current app config (position codes and check if app is active) if (checkInternetConnection() == true) { PFConfig.getConfigInBackgroundWithBlock { (parseConfig: PFConfig?, error: NSError?) -> Void in //Determine where to start app //Already logged in if (currentUser != nil) { self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("TabBar") as TabBar } //Not logged in else { self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("loginStart") as UINavigationController } self.window.rootViewController = self.startController self.window.makeKeyAndVisible() //If the app is disabled, display the inactive/disabled/error screnen. if (parseConfig?["active"] as Bool? == false) { self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("block") as AppBlock self.window2.rootViewController = self.startController self.window2.makeKeyAndVisible() } } } else { //Already logged in if (currentUser != nil) { self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("TabBar") as TabBar } //Not logged in else { self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("loginStart") as UINavigationController } self.window3.rootViewController = self.startController self.window3.makeKeyAndVisible() self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("block") as AppBlock self.window4.rootViewController = self.startController self.window4.makeKeyAndVisible() } } } I have what I think is a weird situation. If the first if statement ,checkInternetConnection(), is true, I go on to continue figuring out what window/view to present. Everything here works perfectly. However, in the else part, no windows/views are presented. I can't figure out why this is happening....it's really weird that it works in one section but not the other.... Any ideas? Also in some cases two windows/views are created. Would this be a problem? I don't think so since if the parseConfig is false, the two windows are created and displayed correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/30429774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WampServer HTTPS Hello I want to learn more about WampServer an HTTPS. I have this website. But if i give the command: openssl genrsa -des3 -out server.key 1024 it will give me an error called: he ordinal 3807 could not be located in the dynamic link libary LIBEAY32.dll I have Look on my directory: wamp\bin\apache\Apache2.4.4\bin there was a file called libeay.dll. What coud be the problem? A: The openssl executable that is distributed with Apache for Windows and therefore WAMPServer does not seem to work very well. I have never had the time to work out exactly why! My solution was to download OpenSSL from Shining Light Products They are linked to from the Openssl Binaries page so I assume it is a stable and unhacked distribution of a windows binary etc that does the job for windows users.
{ "language": "en", "url": "https://stackoverflow.com/questions/23263127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 8078 bytes in 8060 B datapage (SQL Server)? It is written everywhere that data in SQL Server is written in pages of 8K (8192 B) each with 8060 bytes for data and the rest is overhead (system info). Though, the recent article [1] gives code example illustrating, as I understood, that 8078 bytes of data fit into a page. What do I miss in understanding 8,060 B per per page? I verified the code on x86 SQL Server 2008 R2... Update: Did I see an answer telling about follow-ups to [1]? I pity that I did not mark that as helpful (to me) and comment immediately... I just wanted to investigate more myself before responding... Update2: I posted subquestion [2] [1] How table design can impact your SQL Server performance? http://sqlserver-training.com/how-table-design-can-impact-your-sql-server-performance/- [2] How to come to limits of 8060 bytes per row and 8000 per (varchar, nvarchar)? How do you get to limits of 8060 bytes per row and 8000 per (varchar, nvarchar) value? A: Long answer short, the limit is 8060 bytes per row, but 8096 bytes per page. The rows in the article you linked have a row size of ~4000 bytes, so they are well under the limit per row. However, that does not answer the question of how many such rows fit on a page. See "Estimating the size of a heap" in Books Online: http://msdn.microsoft.com/en-us/library/ms189124.aspx If you do the calculation for the tables in the article, you'll see that the first table has a physical row size of 4048 bytes, which is exaclty half the 8096 limit for a page. A: * *The maximum row size is 8060 bytes *In this case, there are two rows each of 4039 bytes
{ "language": "en", "url": "https://stackoverflow.com/questions/3778721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Walking (tic-toc) clock with js and php Have a script with "walkin" clock on javascript and php (i need server-side time - it's important), but it's stop and don't count until refresh a page. What i'm doing wrong, please help. Thank you. <?php $Hour = date("H"); $Minute = date("i"); $Second = date("s"); $Day = date("d"); $Month = date("m"); ?> <script type="text/javascript"> function clock() { var d = new Date(); var month_num = d.getMonth(); var day = d.getDate(); var hours = <?php echo $Hour;?>; var minutes = <?php echo $Minute;?>; var seconds = <?php echo $Second?>; month=new Array("января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"); if (day <= 9) day = "0" + day; if (hours <= 9) hours = "0" + hours; if (minutes <= 9) minutes = "0" + minutes; if (seconds <= 9) seconds = "0" + seconds; date_time = "Today - " + day + " " + month[month_num] + " " + d.getFullYear() + " y. &nbsp;&nbsp;&nbsp;Now - "+ hours + ":" + minutes + ":" + seconds; if (document.layers) { document.layers.doc_time.document.write(date_time); document.layers.doc_time.document.close(); } else document.getElementById("doc_time").innerHTML = date_time; setTimeout("clock()", 1000);} </script> <span id="doc_time">Date & time</span> <script type="text/javascript">clock();</script> A: Your issue: * *PHP serves on page request the respective date values. *You store those values into JS *You loop all over again the same values. Therefore the loop works but the values are unchanged. Instead what you should: * *Create a var D = new Date("<?php echo date('D M d Y H:i:s O');?>"); outside of your function. *On every timeout, add one second to your initial PHP Date DATE = PHP:initial + JS:now - JS:initial function zero(n) { return n > 9 ? n : "0" + n; } var months = [ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря", ]; var jsDate = new Date(); // Store JS time // I'll hardcode a date string for demo purpose: var phpDate = new Date("Sun Sep 09 2018 23:59:55 +0000"); // You, use this instead: // var phpDate = new Date("<?php echo date('D M d Y H:i:s O');?>"); function clock() { var diff = +new Date() - +jsDate; // Get seconds difference var date = new Date(+phpDate + diff); // Add difference to initial PHP time var y = date.getFullYear(), M = date.getMonth(), d = zero(date.getDate()), h = zero(date.getHours()), m = zero(date.getMinutes()), s = zero(date.getSeconds()); document.getElementById("doc_time").innerHTML = ` Дата: ${d} ${months[M]} ${y}. &emsp; Время: ${h}:${m}:${s} `; setTimeout(clock, 1000); } clock(); <div id="doc_time"></div> A: The php code runs once on page load so hour, minute and seconds will always remain same in each call of clock() function. If you really need to do such a thing, you have to use AJAX to request a php script each second to get current time from server but remember these requests will have delay and also can put a huge load on server if multiple users open the page at the same time.
{ "language": "en", "url": "https://stackoverflow.com/questions/52249232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with NSMutableArray Why do I get this warning in Xcode 4.3.1? Thanks. A: You are allocating an NSArray instead of an NSMutableArray ? A: Just change NSMutableArray *array = [[NSArray alloc] initWithObjects:@"About", nil]; With NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"About", nil]; A: You should instead be creating your array like this: NSMutableArray *array = [NSMutableArray arrayWithObjects:@"About", nil]; Notice we send the message to NSMutableArray's class, not NSArray's, so we get a mutable version of the array created. A: Just Replace the convenience constructor for NSArray with NSMutableArray.. [[NSMutableArray alloc] initWithObjects:@"About", nil;
{ "language": "en", "url": "https://stackoverflow.com/questions/9807609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do i deal with this? trying to get the outcome to produce the names of the hostvars #!/usr/bin/env python3 ''' Custom dynamic inventory script for ansible, in python ''' # Importing modules needed import os import sys import argparse try: import json except ImportError: import simplejson as json class ExampleInventory(object): def __init__(self): self.inventory = {} self.read_cli_args() # Called with --list if self.arg.list: self.inventory = self.example_inventory() # Called with --host [hostname] elif self.arg.host: # Not implemented, since we return _meta info --list self.inventory = self.empty_inventory() # If no groups or vars are present, return an empty inventory else: self.inventory = self.empty_inventory() print: json.dumps(self.inventory); # Example inventory for testing # This is hard coded, a more elegant one will probe an API which might be provided by cloud providers def example_inventory(self): return { "group": { "hosts": [ "172.31.30.220" "172.31.28.102" "172.31.32.33" "172.31.41.111" ], "vars": { "example_variable": "value" } }, "_meta":{ "hostvars": { "172.31.30.220": { "host_specific_vars": "web1" }, "172.31.28.102": { "host_specific_vars": "web2" }, "172.31.32.33": { "host_specific_vars": "db1" }, "172.31.41.111": { "host_specific_vars": "db2" } } } } # Empty inventory for testing: def empty_inventory(self): return {'_meta': {'hostvars': {}}} # Read the command line args passed to the script # Every inventory must provide this def read_cli_args(self): parser = argparse.ArgumentParser() parser.add_argument('--list', action = 'store_true') parser.add_argument('--hosts', action = 'store') self.args = parser.parse_args() # Get the inventory. ExampleInventory() > Keep getting this error ... Traceback (most recent call last): File "dynamic_inventory_example.py", line 84, in <module> ExampleInventory() File "dynamic_inventory_example.py", line 26, in __init__ if self.arg.list: AttributeError: 'ExampleInventory' object has no attribute 'arg' A: Used as self.arg but set as self.args. Use the same name in both places.
{ "language": "en", "url": "https://stackoverflow.com/questions/70048064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: error in google map integration i am trying to integrate the google api i have found some codes for that API Script <!-- Dependencies: JQuery and GMaps API should be loaded first --> <script src="js/jquery-2.1.1.min.js"></script> <script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <!-- CSS and JS for our code --> <link rel="stylesheet" type="text/css" href="css/jquery-gmaps-latlon-picker.css"/> <script src="js/jquery-gmaps-latlon-picker.js"></script> html code <fieldset class="gllpLatlonPicker"> <input type="text" class="gllpSearchField"> <input type="button" class="gllpSearchButton" value="Search"> <br/><br/> <div class="gllpMap">Google Maps</div> <br/> lat/lon: <input type="text" name="gllpLatitude" class="gllpLatitude" value="30.44867367928756"/> / <input type="text" name="gllpLatitude" class="gllpLongitude" value="70.6640625"/> zoom: <input type="text" name="gllpZoom" class="gllpZoom" value="4"/> <input type="button" class="gllpUpdateButton" value="update map"> <br/> </fieldset> this code working fine separately but when i integrate in my application it shows me that error A: <script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> In the above script the tag sensor is not required in "src" instead of that please provide a googlemapapi key, it will work!! eg: <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=paste your key here"></script> Get your key: https://developers.google.com/maps/documentation/javascript/get-api-key#key Thanks!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/34286878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QProcess not emitting its signals when not waitForFinished() In the following code omitting the waitForFinished() makes the QProcess stop emitting its signal. What the heck is wrong with it? Is this a Qt Bug? (5.7). Note this code is run parallel with QtConcurrent run. But this should not change anything, should it? Afaik sending signals in other threads is fine, though they will be queued. QProcess *process = new QProcess; process->setReadChannel(QProcess::StandardOutput); connect(process, &QProcess::readyReadStandardOutput, [](){ qDebug()<< "readyReadStandardOutput"; }); connect(process, &QProcess::stateChanged, [](QProcess::ProcessState state){ qDebug()<< "stateChanged"<< state; }); connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), [=](){ qDebug()<< "finsished"; }); connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), [this, process](int exitCode, QProcess::ExitStatus exitStatus){ qDebug()<< "finsished"; if (exitStatus == QProcess::NormalExit && exitCode == 0){ while (process->canReadLine()) { QString line = QString::fromLocal8Bit(process->readLine()); QRegularExpression regex("\"(.*)\" {(.*)}"); QRegularExpressionMatch match = regex.match(line); names_.push_back(match.captured(1)); uuids_.push_back(match.captured(2)); } } process->deleteLater(); }); process->start("VBoxManage", {"list", "vms"}); process->waitForFinished(); // This line changes everything qDebug()<< "leftWaitForFinished"; A: You're not running an event loop in the thread where the QProcess instance lives. Any QObject in a thread without an event loop is only partially functional - timers won't run, queued calls won't be delivered, etc. So you can't do that. Using QObjects with QtConcurrent::run requires care. At the very least, you should have a temporary event loop for as long as the process lives - in that case you should hold QProcess by value, since deleteLater won't be executed after the event loop has quit. QProcess process; ... QEventLoop loop; connect(process, &QProcess::finished, &loop, &QEventLoop::quit); loop.exec(); Otherwise, you need to keep the process in a more durable thread, and keep that thread handle (QThread is but a handle!) in a thread that has an event loop that can dispose of it when it's done. // This can be run from a lambda that runs in an arbitrary thread auto thread = new QThread; auto process = new QProcess; ... connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), [this, process](int exitCode, QProcess::ExitStatus exitStatus){ ... process->deleteLater(); process->thread()->quit(); }); process->start("VBoxManage", {"list", "vms"}); process->moveToThread(thread); // Move the thread **handle** to the main thread thread->moveToThread(qApp->thread()); connect(thread, &QThread::finished, thread, &QObject::deleteLater); thread->start(); Alas, this is very silly since you're creating temporary threads and that's expensive and wasteful. You should have one additional worker thread where you take care of all low-overhead work such as QProcess interaction. That thread should always be running, and you can move all QProcess and similar object instances to it, from concurrent lambdas etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/39036458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dialog not pulling info from EditText box Hello I am trying to write a small app and when the day is Sunday on the system it is supposed to pull up a dialog box which it is doing just fine. However when I put info in the boxes in the dialog and click submit it is still showing the second dialog for the emptyBox I have set up. So to recap all items of the dialog box are working except the system is still seeing the EditText boxes as empty but there is a value in there. The value will only ever be numbers. final Dialog sundayDialog = new Dialog(this); sundayDialog.setContentView(R.layout.sunday_dialog); Button sundaySubmitBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogSubmitBtn); Button sundayCancelBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogCancelBtn); sundaySubmitBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Submit Button setContentView(R.layout.sunday_dialog); final EditText etAmountBought = (EditText) findViewById(R.id.amountBoughtET); final EditText etCost = (EditText) findViewById(R.id.pricePaidET); String amountBought = etAmountBought.getText().toString(); String cost = etCost.getText().toString(); if (amountBought.isEmpty() || cost.isEmpty()) { //sundayDialog.dismiss(); emptyETDialogCall(); } else { try { mAmountBought = Integer.parseInt(amountBought); mPricePaid = Integer.parseInt(cost); } catch (NullPointerException e) { Log.e(TAG, "Error in sunday dialog in try/catch"); } } if (mPricePaid >= 250) { costTooHighDialogCall(); mPricePaid = 0; } // textBlockDisplay(); // Update the text block with input. } }); sundayCancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Cancel Button sundayDialog.dismiss(); sundayCancelDialog(); } }); sundayDialog.show(); } this is the only this that shows in logcat: 08-04 11:42:44.780: W/IInputConnectionWrapper(1209): finishComposingText on inactive InputConnection A: I'm not sure if this is the reason, but each time, you're resetting the contentview. This should only be called once in onCreate, otherwise just remove the elements and use an inflater to add new ones. I think every time it resets the contentview, it will reset the textboxes. A: I think, i got your problem . sundayDialog.setContentView(R.layout.sunday_dialog); this is View you are setting for your custom Dialog. this is fine. And after sunday click button again you are resetting your Layout which again creates all views and you are getting everything reset. final Dialog sundayDialog = new Dialog(this); sundayDialog.setContentView(R.layout.sunday_dialog); Button sundaySubmitBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogSubmitBtn); Button sundayCancelBtn = (Button) sundayDialog .findViewById(R.id.sundayDialogCancelBtn); sundaySubmitBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Submit Button // Here i have removed setContent View.... final EditText etAmountBought = (EditText) findViewById(R.id.amountBoughtET); final EditText etCost = (EditText) findViewById(R.id.pricePaidET); String amountBought = etAmountBought.getText().toString(); String cost = etCost.getText().toString(); if (amountBought.isEmpty() || cost.isEmpty()) { //sundayDialog.dismiss(); emptyETDialogCall(); } else { try { mAmountBought = Integer.parseInt(amountBought); mPricePaid = Integer.parseInt(cost); } catch (NullPointerException e) { Log.e(TAG, "Error in sunday dialog in try/catch"); } } if (mPricePaid >= 250) { costTooHighDialogCall(); mPricePaid = 0; } // textBlockDisplay(); // Update the text block with input. } }); sundayCancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Cancel Button sundayDialog.dismiss(); sundayCancelDialog(); } }); sundayDialog.show(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/18071950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ declaration is incompatible These are the code files for my swapchain, I am using dx11 BTW, so you guys dont get lost on why I'm using d3d device, etc. //Header #pragma once class SwapChain { public: SwapChain(); bool init(HWND hwnd, UINT width, UINT height); bool release(); ~SwapChain(); private: IDXGISwapChain* m_swap_chain; }; //cpp #include "SwapChain.h" #include "GraphicsEngine.h" SwapChain::SwapChain() { } bool SwapChain::init(HWND hwnd, UINT width, UINT height) { ID3D11Device*device= GraphicsEngine::get()->m_d3d_device; DXGI_SWAP_CHAIN_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.BufferCount = 1; desc.BufferDesc.Width = width; desc.BufferDesc.Height = height; desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.BufferDesc.RefreshRate.Numerator = 60; desc.BufferDesc.RefreshRate.Denominator = 1; desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; desc.OutputWindow = hwnd; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Windowed = TRUE; HRESULT hr=GraphicsEngine::get()->m_dxgi_factory->CreateSwapChain(device, &desc, &m_swap_chain); if (FAILED(hr)) { return false; } return true; } bool SwapChain::release() { return true; } SwapChain::~SwapChain() { } I am trying to make a swapchain for my graphics engine, and I have the same params as in the header file. Can someone please explain why I am getting this error? Severity Code Description Project Path File Line Suppression State Error (active) E0147 declaration is incompatible with "bool SwapChain::init( hwnd, width, height)" (declared at line 6 of "C:\Users\sudo\source\repos\DX 3D\DX 3D\SwapChain.h") DX 3D C:\Users\sudo\source\repos\DX 3D\DX 3D C:\Users\sudo\source\repos\DX 3D\DX 3D\SwapChain.cpp 8 I am new to C++, by the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/63329422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to return activity based on timedate mysql 5.7 this is my fiddle https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=5422fb347abaf2bde082eb522f5be4fb table data2 +--------------------------------------+-----------------+----------------+----------+ | user_id | event_timestamp | event_name | level_id | +--------------------------------------+-----------------+----------------+----------+ | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01 | level_complete | 1 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02 | level_complete | 2 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02 | level_complete | 3 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02 | level_complete | 4 | +--------------------------------------+-----------------+----------------+----------+ table data3 +--------------------------------------+-----------------+------------+----------+ | user_id | event_timestamp | event_name | level_id | +--------------------------------------+-----------------+------------+----------+ | 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31 | level_end | 1 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01 | level_end | 2 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01 | level_end | 3 | | 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01 | level_end | 4 | +--------------------------------------+-----------------+------------+----------+ so i have 2 tables, if user_id has completed the level, then that data come to data2 table, but if failed the level, then the data come to data3 table. so i want to order by the event_timestamp so the expected results was like this +--------------------------------------+-----------------+------------------+----------+ | user_id | event_timestamp | event_name | level_id | +--------------------------------------+-----------------+------------------+----------+ | 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31 | level_end | 1 | | | 2020-01-01 | level_completed | 1 | | | 2020-01-01 | level_end | 2 | | | 2020-01-01 | level_end | 3 | | | 2020-01-01 | level_end | 4 | | | 2020-01-02 | level_compeleted | 2 | | | 2020-01-02 | level_completed | 3 | | | 2020-01-02 | level_completed | 4 | +--------------------------------------+-----------------+------------------+----------+ i've tried with this query select * from data2 inner join data3 on data2.user_id = data3.user_id order by data2.event_timestamp, data3.event_timestamp; but the output was not like i expected A: Something like this: select * from data2 union select * from data3 order by event_timestamp, level_id; Using UNION and order by event_timestamp, level_id; https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=03b02e0d079011aa4f9e3af7974a98f1
{ "language": "en", "url": "https://stackoverflow.com/questions/63948800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way in Powershell to find ADF slices that completed in last 1 hour for example? Given certain dataset, I want to find out how many of its slices actually became Ready in last 1 hour (or say 2 hours, it's just an example). This gives me idea of cluster health. Because out of dozens of datasets, if no Ready slice was produced in last couple of hours, it's surely alarming for me. I know Powershell has a cmdlet to get slice status which returns actual start and end time of slices -- but the problem is it finds that only on the basis of slice information. I don't care if the slice date is 1 year back -- I want the status on the basis of actual start and end time for that slice -- and I want to do it programmatically. Worst case is -- one will need to get status for all possible slices and then get actual start and end time, but this is very inefficient -- there is also limit on how many API calls one can in an hour. A: I think the cmdlet your looking for here is Get-AzureRmDataFactoryActivityWindow this accepts a run window and will return the result of a time slice either Ready, Waiting, Failed etc. Example of use: Get-AzureRmDataFactoryActivityWindow ` -DataFactoryName $ADFName.DataFactoryName ` -ResourceGroupName $ResourceGroup ` | ? {$_.WindowStart -ge $Now} ` | SELECT ActivityName, ActivityType, WindowState, RunStart, InputDatasets, OutputDatasets ` | Sort-Object ActivityName Use this with the required params to return a list of the information you want. I might then stick it into a SQL table for wider monitoring etc. But you could use an array in PowerShell to get the count value and produce the alert. Next wrap it up in something that polls on the hour maybe. Here's a link to all ADF PowerShell cmdlets available in the Azure module: https://learn.microsoft.com/en-gb/powershell/module/azurerm.datafactories/?view=azurermps-4.0.0 Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/44339545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What pull parser implementation to use and when? I need to use a xml pull parser. I can find stax-api.jar which seems to be already part of com.sun.xml.* and it seems that there is already something stax related implemented. com.sun.xml unfortunately has no sources in JDK 6, so I can't tell. Also there are xmlpull, stax.codehaus.org and apache axiom, that kinda implements stax-api. stax.codehaus.org seems to be a stax reference implementation. Xmlpull seems to be done by the same people as the reference implementation and Apache Axiom seems to be a StAX based parser that was created for Apache Axis2. Could you please clarify what are the main differences, what API to use and when would you use one of these implementations and why ? Edit: Before you decide to close this question, notice that xmlpull.org and stax.codehaus.org releases are pretty old (5 years) and one really can't say if the stax parser implementation is part of sun.com.xml.*. I'd just need someone with pull parser experience to tell me, what to use and why. For instance, Apache Abdera project (I'm parsing atom feeds too) is using Axiom implementation that seems to be implementing its Axiom-api and also geronimo-stax-api_1.0_spec A: Aside from pointing out that JDK/JRE bundles Sun's SJSXP which works ok at this point, I would recommend AGAINST using Stax ref impl (stax.codehaus.org) -- do NOT use it for anything, ever. It has lots of remaining bugs (although many were fixed, initial versions were horrible), isn't particularly fast, doesn't implement even all mandatory features. Stay clear of it. I am partial to Woodstox, which is by far the most complete implementation for XML features (on par with Xerces, about the only other Java XML parser that can say this), more performant than Sjsxp, and all around solid parser and generator -- this is why most modern Java XML web service frameworks and containers bundle Woodstox. Or, if you want super-high performance, check out Aalto. It is successor to Woodstox, with less features (no DTD handling) but 2x faster for many common cases. And if you ever need non-blocking/async parsing (for NIO based input for example), Aalto is the only known Java XML parser to offer that feature. As to Axiom: it is NOT a parser, but tree model built on top of Stax parser like Woodstox, so they didn't reinvent the wheel. XmlPull predates Stax API by couple of years; basically Stax standardization came about people using XmlPull, liking what they saw, and Sun+BEA wanting to standardize the approach. There was some friction in the process, so in the end XmlPull was not discontinue when Stax was finalized, but one can think of Stax as successor -- XmlPull is still used for mobile devices; I think Android platform includes it. (disclaimers: I am involved in both Aalto and Woodstox projects; as well as provided more than a dozen bug fixes to both SJSXP and Stax RI) A: As of Java 1.6, there is a StaX implementation inside the plain bundled JRE. You can use that. If you don't like the performance, drop in woodstox. Axiom is something else entirely, much more complex. Xmlpull seems to be going by the wayside in favor of one Stax implementation or another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7691663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: org.joda.DateTime returning wrong month DateTimeFormatter d_t = DateTimeFormat.forPattern("DD-MMM-YYYY HH:mm"); String date = "02-Mar-2003 00:01"; DateTime dateTime = DateTime.parse(date, d_t); When I am running the code its returning 02-Jan-2003 12:01 A: Your date format string is wrong. Use dd instead of DD for the days. According to the documentation, DD means "day of year", while you need dd, which means "day of month". Change the first line to: DateTimeFormatter d_t = DateTimeFormat.forPattern("dd-MMM-YYYY HH:mm");
{ "language": "en", "url": "https://stackoverflow.com/questions/13025045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to clone div content and append only one at the time? I have form that should allow user to click on the Add Row and create another identical row. This will required new row to give an option to the user to delete that row if created accidentally. Here is my code that doesn't works correct. After I click on add row second time code will insert another 3 rows. Somethings odd is going on with the way I insert and clone new rows. $("#add_row").on('click', addRow); function addRow() { $(".data-bug-item").clone().insertAfter(".data-bug-item"); }; <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script language="javascript" type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script language="javascript" type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div id="dataBug" class="bug-section"> <div class="row"> <div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12"> <button type="button" class="btn" name="add_row" id="add_row"> <span class="glyphicon glyphicon-plus-sign"></span> Add Row </button> </div> </div> <div class="form-group required data-bug-item"> <label class="control-label" for="type"><span class="label label-default">Column & Description:</span></label> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-2 col-lg-2"> <select class="form-control" name="frm_column" id="frm_column" required> <option value="">--Choose--</option> <option value="1">Location</option> <option value="2">Name</option> <option value="3">Year</option> <option value="4">City</option> </select> </div> <div class="col-xs-9 col-sm-9 col-md-10 col-lg-10"> <input class="form-control" type="text" name="frm_descr" id="frm_descr" placeholder="Enter Description" required> </div> </div> </div> </div> I would like to see only one row at the time and button on the end of the Description input field for Delete. A: The simplest way to do that, it's to clone a minor part of html. You're cloning everything including the cloned part. After data-bug-item create a div with same name just to identify and clone JUST the form and not all informations inside the div. Example: $("#add_row").on('click', addRow); function addRow() { $("#form-data-bug-item").clone().insertAfter(".data-bug-item"); }; <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script language="javascript" type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script language="javascript" type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <div id="dataBug" class="bug-section"> <div class="row"> <div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12"> <button type="button" class="btn" name="add_row" id="add_row"> <span class="glyphicon glyphicon-plus-sign"></span> Add Row </button> </div> </div> <div class="form-group required data-bug-item"> <div id="form-data-bug-item"> <label class="control-label" for="type"><span class="label label-default">Column & Description:</span></label> <div class="row"> <div class="col-xs-3 col-sm-3 col-md-2 col-lg-2"> <select class="form-control" name="frm_column" id="frm_column" required> <option value="">--Choose--</option> <option value="1">Location</option> <option value="2">Name</option> <option value="3">Year</option> <option value="4">City</option> </select> </div> <div class="col-xs-9 col-sm-9 col-md-10 col-lg-10"> <input class="form-control" type="text" name="frm_descr" id="frm_descr" placeholder="Enter Description" required> </div> </div> </div> </div> </div> Now you just need to clone form-data-bug-item PS: I'm not considering another things on your code, just the solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/53288347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Double pointer in the function I am trying to insert strings in the binary search tree. So what I am to trying is, parsing strings from a file(contains instruction set) and then inserting in the function insertOpcodeFromFile(). So this function will execute (*node) = Node_insert(&node,instruction). the node will be the root of binary tree which is located in main function. So in simple way to explain, I want to manipulate(insert) the root pointer in the main function by using double pointer in the other function contain insert function. I have a simple understanding about the pointer, but in this situation, I need to use more than double pointer I think. please explain me about the double pointer clearly using this example. Here is my code(I commenting out insert_node) #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef BINARYTREE_H_ #define BINARYTREE_H_ typedef struct node *NodePtr; typedef struct node { char *word; int count; NodePtr left; NodePtr right; } Node; NodePtr Node_alloc(); NodePtr Node_insert(NodePtr node_ptr, char *word); void clearArray(char a[]); void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node); void Node_display(NodePtr); char *char_copy(char *word); #endif int main(int argc, const char * argv[]) { FILE * opFile; FILE * progFile; struct node *root = NULL; if ( argc != 4) { // # of flag check fprintf(stderr, " # of arguments must be 4.\n" ); exit(1); } opFile = fopen ( argv[1], "r"); if(opFile == NULL) { fprintf(stderr,"There is no name of the opcode file\n"); exit(1); } progFile = fopen ( argv[2], "r"); if(progFile == NULL) { fprintf(stderr,"There is no name of the program file \n"); exit(1); } insertOpcodeFromFile(opFile, &root); //Node_display(root); }/* main is over */ void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node) { int fsize = 0; int lengthOfInst = 0; int c; int i; char buffer[100]; fsize = getFileSize(opcodeFile); enum flag {ins,opc,form}; int flag = ins; char instruction[6]; unsigned int opcode = 0; unsigned char format; while (c != EOF) { c = fgetc(opcodeFile); buffer[i++] = c; if (c == 32){ switch (flag) { case ins: flag = opc; memcpy(instruction,buffer,i); instruction[i] = '\0'; clearArray(buffer); i = 0; // printf("인스트럭션 : %s\n",instruction ); break; case opc: flag = form; opcode = atoi(buffer); clearArray(buffer); i = 0; // printf("옵코드 : %d\n",opcode ); break; default: break; }/* end of switch */ }/* end of if(space) */ if((c == 10) || (c == EOF)) { if (flag == form) { format = buffer[0]; clearArray(buffer); i = 0; // printf("포멧: %c\n", format); } flag = ins; //node = Node_insert(node,instruction); } } //Node_display(node); } int getFileSize(FILE *opcodeFile) { int fsize = 0; fseek(opcodeFile,0, SEEK_SET); fseek(opcodeFile,0, SEEK_END); fsize = (int)ftell(opcodeFile); fseek(opcodeFile,0, SEEK_SET); return fsize; } int countUntilSpace(FILE *opcodeFile, int currentPosition) { char readword[1]; char *space = " "; char *nextLine = "/n"; int i = 0; //printf("현재: %d\n",currentPosition ); while(1) { fread(readword, sizeof(char),1,opcodeFile); i++; if(strcmp(readword,space) == 0 || strcmp(readword,nextLine) == 0) { //printf("break\n"); break; } } fseek(opcodeFile,currentPosition ,SEEK_SET); //printf("끝난 현재 :%d\n",ftell(opcodeFile) ); //printf("%I : %d\n",i ); return i - 1; } void clearArray(char a[]) { memset(&a[0], 0, 100); } NodePtr Node_alloc() { return (NodePtr) malloc(sizeof(NodePtr)); } NodePtr Node_insert(NodePtr node_ptr, char *word) { int cond; if (node_ptr == NULL) { node_ptr = Node_alloc(); node_ptr->word = char_copy(word); node_ptr->count = 1; node_ptr->left = node_ptr->right = NULL; } else if ((cond = strcmp(word, node_ptr->word)) == 0) { node_ptr->count++; } else if (cond < 0) { node_ptr->left = Node_insert(node_ptr->left, word); } else { node_ptr->right = Node_insert(node_ptr->right, word); } return node_ptr; } void Node_display(NodePtr node_ptr) { if (node_ptr != NULL) { Node_display(node_ptr->left); printf("%04d: %s\n", node_ptr->count, node_ptr->word); Node_display(node_ptr->right); } } char *char_copy(char *word) { char *char_ptr; char_ptr = (char *) malloc(strlen(word) + 1); if (char_ptr != NULL) { char_ptr = strdup(word); } return char_ptr; } A: In this case, in main(), Node *root; Why do you need to use a "double" pointer ( Node ** ) in functions that alter root is because root value as to be set in these functions. For instance, say you want to allocate a Node and set it into root. If you do the following void alloc_root(Node *root) { root = malloc(sizeof (Node)); // root is a function parameter and has nothing to do // with the 'main' root } ... // then in main alloc_root( root ); // here main's root is not set Using a pointer to pointer (that you call "double pointer") void alloc_root(Node **root) { *root = malloc(sizeof (Node)); // note the * } ... // then in main allow_root( &root ); // here main's root is set The confusion comes probably from the Node *root in main, root being a pointer to a Node. How would you set an integer int i; in a function f? You would use f(&i) to call the function f(int *p) { *p = 31415; } to set i to the value 31415. Consider root to be a variable that contains an address to a Node, and to set its value in a function you have to pass &root. root being a Node *, that makes another *, like func(Node **p).
{ "language": "en", "url": "https://stackoverflow.com/questions/43080416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JAR program not allowed to open/save under MacOS Catalina ("the open file operation failed to connect to the open and save panel service") I am having the following problem: I am using Catalina (10.15.7) on a MacBook and recently I downloaded a JAR executable file (called JKnobMan) but apparently it doesn't have access to the open and save operations, even though the program runs normally otherwise, and it even lets me export. But naturally, what I want is to be able to save my progress and open it later on. The message I get when I click 'open' is: "The open file operation failed to connect to the open and save panel service". I don't get this message when I 'save' but the saved file contains none of the information it should have (I checked this by opening the saved file on the web version of the KnobMan program). I tried going to the Security & Privacy settings to give this program all necessary access but for some reason the JAR file is not selectable when I browse the items. I expect this to be an easy fix, but so far I have been unable to find a solution. Some people experience a similar problem with email services and they're usually easily solved, so this must be straightforward as well? Any help appreciated. EDIT: Note that I'm not asking for help with THIS particular program. I assume that I would have the same issue with any other JAR executable trying to open/save in a Catalina environment. So, knowledge of said program is probably not necessary to know the solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/65098188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Object reference not set to an instance of an object I don't know why I am getting this error when I deploy my web on server. Is it because the problem with my connection string? Please help me. Thank you!!! Web.config <add name="Database1" connectionString="Data Source='170.21.191.85';Initial Catalog='Database1';User ID='sa';Password='123'"/> Login.aspx.vb Dim connection As String = System.Configuration.ConfigurationManager.ConnectionStrings("Database1").ConnectionString() Dim mycon As New SqlConnection(connection) Stack Trace [NullReferenceException: Object reference not set to an instance of an object.] WebApplication1.Login.ImageButton2_Click(Object sender, ImageClickEventArgs e) in C:\Users\L30810\Desktop\fyp final.14\WebApplication1\Login.aspx.vb:16 System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +86 System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +115 System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746 ImageButton2_Click Protected Sub ImageButton2_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton2.Click Dim connection As String = System.Configuration.ConfigurationManager.ConnectionStrings("Database1").ConnectionString() Dim mycon As New SqlConnection(connection) mycon.Open() Dim queryString As String = "SELECT Role,StaffName FROM [role] WHERE LoginID ='" + TextBox1.Text + "' and Password='" + TextBox2.Text + "'" Dim cmd As SqlCommand = New SqlCommand(queryString, mycon) Dim reader As SqlDataReader = cmd.ExecuteReader() Dim user1 As String = "" While reader.Read() Dim role As String = "" role = reader.GetString(0) user1 = reader.GetString(1) Session("role") = role End While If (Session("role") = "SA") Then Response.Expires = 0 Response.ExpiresAbsolute = Now() Response.CacheControl = "no-cache" Session("User") = user1 Response.Redirect("MainPageSA.aspx") ElseIf (Session("role") = "MGR") Then Session("User") = user1 Response.Expires = 0 Response.ExpiresAbsolute = Now() Response.CacheControl = "no-cache" Response.Redirect("MainPageMGR.aspx") ElseIf (Session("role") = "Assessor") Then Session("User") = user1 Response.Expires = 0 Response.ExpiresAbsolute = Now() Response.CacheControl = "no-cache" Response.Redirect("MainPageAssessor.aspx") ElseIf (Session("role") = "MC") Then Session("User") = user1 Response.Expires = 0 Response.ExpiresAbsolute = Now() Response.CacheControl = "no-cache" Response.Redirect("MainPageMC.aspx") Else MsgBox("Invalid Username/Password", MsgBoxStyle.OkOnly, "Clinical Peformance Appraisal") End If reader.Close() mycon.Close() End Sub A: You don't need to quote the values in the connection string. <add name="Database1" connectionString="Data Source=170.21.191.85;Initial Catalog=Database1;User ID=sa;Password=final"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/5115272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: null values returning from gson.fromJson I have some values in my object are returning by value null when converting from json to object and some others doesn't,i can't figure out why is that happening here's my code to convert OriginalMovie originalMovie = gson.fromJson(jsonString, OriginalMovie.class); here's my json {"page":1, "results":[{"adult":false, "backdrop_path":"/o4I5sHdjzs29hBWzHtS2MKD3JsM.jpg", "genre_ids":[878,28,53,12], "id":87101,"original_language":"en", "original_title":"Terminator Genisys", "overview":"The year is 2029. John Connor, leader of the resistance continues the war against the machines.", "release_date":"2015-07-01", "poster_path":"/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg", "popularity":54.970301, "title":"Terminator Genisys","video":false, "vote_average":6.4, "vote_count":197}], "total_pages":11666,"total_results":233312} and here's my base class (contains results) package MovieReviewHelper; import java.util.ArrayList; import java.util.List; public class OriginalMovie { private long page; private List<Result> results = new ArrayList<Result>(); private long totalPages; private long totalResults; public long getPage() { return page; } public void setPage(long page) { this.page = page; } public List<Result> getResults() { return results; } public void setResults(List<Result> results) { this.results = results; } public long getTotalPages() { return totalPages; } public void setTotalPages(long totalPages) { this.totalPages = totalPages; } public long getTotalResults() { return totalResults; } public void setTotalResults(long totalResults) { this.totalResults = totalResults; } } and here's my other class package MovieReviewHelper; import java.util.ArrayList; import java.util.List; public class Result { private boolean adult; private String backdropPath; private List<Long> genreIds = new ArrayList<Long>(); private long id; private String originalLanguage; private String originalTitle; private String overview; private String releaseDate; private String posterPath; private double popularity; private String title; private boolean video; private double voteAverage; private long voteCount; public boolean isAdult() { return adult; } public void setAdult(boolean adult) { this.adult = adult; } public String getBackdropPath() { return backdropPath; } public void setBackdropPath(String backdropPath) { this.backdropPath = backdropPath; } public List<Long> getGenreIds() { return genreIds; } public void setGenreIds(List<Long> genreIds) { this.genreIds = genreIds; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getOriginalLanguage() { return originalLanguage; } public void setOriginalLanguage(String originalLanguage) { this.originalLanguage = originalLanguage; } public String getOriginalTitle() { return originalTitle; } public void setOriginalTitle(String originalTitle) { this.originalTitle = originalTitle; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public String getReleaseDate() { return releaseDate; } public void setReleaseDate(String releaseDate) { this.releaseDate = releaseDate; } public String getPosterPath() { return posterPath; } public void setPosterPath(String posterPath) { this.posterPath = posterPath; } public double getPopularity() { return popularity; } public void setPopularity(double popularity) { this.popularity = popularity; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isVideo() { return video; } public void setVideo(boolean video) { this.video = video; } public double getVoteAverage() { return voteAverage; } public void setVoteAverage(double voteAverage) { this.voteAverage = voteAverage; } public long getVoteCount() { return voteCount; } public void setVoteCount(long voteCount) { this.voteCount = voteCount; } } A: Your Json and Class variables should have the same name. backdrop_path in Json and backdropPath in class would not work A: Incase this helps for someone like me who spent half a day in trying to figure out a similar issue with gson.fromJson() returning object with null values, but when using @JsonProperty with an underscore in name and using Lombok in the model class. My model class had a property like below and am using Lombok @Data for class @JsonProperty(value="dsv_id") private String dsvId; So in my Json file I was using "dsv_id"="123456" Which was causing null value. The way I resolved it was changing the Json to have below ie.without the underscore. That fixed the problem for me. "dsvId = "123456"
{ "language": "en", "url": "https://stackoverflow.com/questions/31341295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ Pass stdcall function name as parameter I am unable to pass stdcall function name "TestFunction" as parameter into ExecuteLocalThread and to use in beginthreadex unsigned __stdcall TestFunction(void* timerPointer) { unsigned result =0; printf("thread is running\n"); return result; } void ExecuteLocalThread(unsigned int (_stdcall *_StartAddress)(void *)) { HANDLE heartBeatThread; unsigned int hbThreadID; heartBeatThread = (HANDLE)_beginthreadex(NULL, 0 , unsigned int (_stdcall *_StartAddress)(void *)/*&TestFunction*/, (void*)this, CREATE_SUSPENDED, &hbThreadID); ResumeThread( heartBeatThread ); } A: Try: heartBeatThread = (HANDLE)_beginthreadex(NULL, 0 , _StartAddress/*&TestFunction*/, (void*)this, CREATE_SUSPENDED, &hbThreadID); A: I'd strongly suggest making a typedef for the function pointer, and using this everywhere else: typedef unsigned int _stdcall (*Pfn)(void*); // typedefs to "Pfn" void ExecuteLocalThread(Pfn _StartAddress) { HANDLE heartBeatThread; unsigned int hbThreadID; heartBeatThread = (HANDLE)_beginthreadex(NULL, 0, _StartAddress, (void*)this, CREATE_SUSPENDED, &hbThreadID); ResumeThread( heartBeatThread ); } It's easier to type, easier to read and harder to mess up ;) Even casting gets easier with it: To cast somePtr to your function pointer type: (Pfn)somePtr
{ "language": "en", "url": "https://stackoverflow.com/questions/14256837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Elements in list fading in at unexpected times I am trying to load in separate elements in a list at different times. The bird top left should be first, followed by the background and then the other elements. https://imgur.com/a/Z4vKcEv As you can see in this gif, the elements are fading in at times different than i expected. Anyone know why? EDIT: If GIF does not load, the last element in the list loads first, and then the other elements load in order. Here is my code: HTML: <ul class="anim"> <li class="logo"> <img src="imgs/bird.jpg"> </li> <li class="fullscreen-bg"> <img class="fullscreen-bg__img" src="imgs/rockymountains.jpg"> </li> <li class="green1"> <h1>ESTUDO</h1> </li> <li class="green2"> <h1>ESTUDO E TRABALHO</h1> </li> <li class="green3"> <h1>IMIGRAÇÃO</h1> </li> </div> <li class="red"> <h1>SEU SONHO, NOSSA MISSÃO</h1> </li> </ul> CSS /* TEXT ANIMATIONS */ li { opacity: 0; animation: fadeIn 3.5s 1; animation-fill-mode: forwards; } .anim li:nth-child(1) { animation-delay: 1s } .anim li:nth-child(2) { animation-delay: 1.5s } .anim li:nth-child(3) { animation-delay: 2s } .anim li:nth-child(4) { animation-delay: 2.8s } .anim li:nth-child(5) { animation-delay: 3.4s } /*...*/ @keyframes fadeIn { 0% { opacity: 0.0; } 100% { opacity: 1.0; } } /* END TEXT ANIMATIONS */ From what i can tell all the children in the list are set properly. Thanks in advance for your help. A: You have 6 "li" elements in your source but you have only set animation-delay for 1-5, that is why the 6th "li" do not have delay and will display first. Add in 1 more delay for that element will make it OK: li { opacity: 0; animation: fadeIn 3.5s 1s; animation-fill-mode: forwards; } .anim li:nth-child(1) { animation-delay: 1s } .anim li:nth-child(2) { animation-delay: 1.5s } .anim li:nth-child(3) { animation-delay: 2s } .anim li:nth-child(4) { animation-delay: 2.5s } .anim li:nth-child(5) { animation-delay: 3s } .anim li:nth-child(6) { animation-delay: 3.5s } /*...*/ @keyframes fadeIn { 0% { opacity: 0.0; } 100% { opacity: 1.0; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/51510712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to inject an HttpClient CustomDelegatingHandler in dependency injection I have a custom delegating handler for logging purposes: public class LoggingDelegatingHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { //my logging return await base.SendAsync(request, cancellationToken); } } I've been tring to inject it in my dependency injection like so: services.AddHttpClient(nameof(MyAuthorityClient), c => { c.BaseAddress = new Uri(myOptions.BaseUri); }) .AddTransientHttpErrorPolicy(x => x.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt))) .ConfigurePrimaryHttpMessageHandler<MyClientHttpHandler>() .AddHttpMessageHandler<LoggingDelegatingHandler>(); It seems to compile. But when the execution hits this code: ar response = await client.GetAsync("/my/api/path"); the debugger never arrives to the SendAsync method in my LoggingDelegatingHandler. At first, I thought it's because I am calling GetAsync and my overridden method is SendAsync but then I have read that it should still hit SendAsync. What am I doing wrong? A: Try the below code: * *Define your custom delegating handler by creating a new class that derives from DelegatingHandler and overrides its SendAsync method public class AuthHeaderHandler : DelegatingHandler { private readonly string _authToken; public AuthHeaderHandler(string authToken) { _authToken = authToken; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authToken); return await base.SendAsync(request, cancellationToken); } } *Next, register the HttpClient and its associated delegating handler in the service collection. You can do this in the ConfigureServices method of your startup class. public void ConfigureServices(IServiceCollection services) { // Register the AuthHeaderHandler with the service collection services.AddTransient<AuthHeaderHandler>(sp => new AuthHeaderHandler(Configuration["AuthToken"])); // Register the HttpClient with the AuthHeaderHandler services.AddHttpClient("MyHttpClient").AddHttpMessageHandler<AuthHeaderHandler>(); // Add other services and dependencies as needed... } *Inject the HttpClient into your class or service using constructor injection. public class MyController : Controller { private readonly HttpClient _httpClient; public MyController(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("MyHttpClient"); } // Use the _httpClient instance to send HTTP requests... }
{ "language": "en", "url": "https://stackoverflow.com/questions/75553512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need more about magento basic I'm new to magento. Need basic knowledge about magento programming, and magento customization. Struggle to print content inside frontend. I followed below site to print content but error shows inside layout,where the content displayed. Can help me what is what in magento A: You can easy learn i have searched it * *It's a great and simple tutorial which help you step by step(After covering this tutorial you will be able to handle admin panel of the magento) http://www.templatemonster.com/help/ecommerce/magento/magento-tutorials/ http://leveluptuts.com/tutorials/magento-community-tutorials
{ "language": "en", "url": "https://stackoverflow.com/questions/30588163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: At what number of columns should you make another table? I had a table that nearly reached 20 columns. I find each one necessary since it's a "project" table, and the project has columns that indicate stuff such as when it was created, when it was updated, its id, who started it, who finished it, some metadata such as keywords, the content of the project itself, a brief description and some other stuff. I was happy with my table, but then I browsed some questions through stackoverflow and saw stuff like "your table should never have more than 10 columns" and suggestions that if it was the case, you should split your table into smaller ones. Following StackOverflow's advice, I split my table into two tables, but I'm finding it more complicated to manipulate. Now, when each project is created, I have to create two new records, each one for each table. I have to handle errors on the creation of either record, which means that if the creation of the record on the second table fails, I have to do yet another query to rollback the creation of the first record. Data retrieval and record deletion has also been made more complex, since now I have to do that on two tables. I'm using the Sails.js framework, and trying to use associations, but I find that it's pretty much the same, I still have to repeat tasks for each table. Is it really worth it to split your table into smaller ones if it gets that big? Or should I just keep my 20 column table? My project is new, not even online, so I don't know performance. I've never understood associations/joins or databases in general, as in, I've never understood why people do it, so, what are the benefits? A: Keep your 20 column table, to be honest 20 columns is not a lot considering 5 columns are taken, as you tell, by who when (created, edited) and the ID. There are other considerations when designing a database table, the number of columns should not be a priority. You can think about splitting it into multiple tables when you have some performance issues but for now keep your table. Go to 40 columns and still you should not care. The person that said never more then 10 was either talking about some performance issues that can be addressed, or it was a specific case where it made a difference or has some strange "standards". But you should really understand database design, as you will see how to design your tables better, but for now make tables with as many fields you want as long as you respect some normalization rules A: I think you never want to change qour schema after your database was in use som for some time. Think about features/functions you propably could wanting to implement in feature, and decide basing on that, if you want to have 40 columns. I prefer to have everything as compact as possible, so i got a lot of foreign-keys and a lot of small tables for the reason to not write or have saved anything twice.
{ "language": "en", "url": "https://stackoverflow.com/questions/29380711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to install fonts without copy to font(windows) folder I want to make a windows application where people can buy the fonts License of the yearly or monthly base so need to font installs without copy to font(windows) folder. how to do this? A: Windows stores list of all fonts in registry: "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts". By default, fonts are referenced with file name only in these registry records and windows automatically searches them in fonts directory, but probably you can add fonts from other folders also by their full path.
{ "language": "en", "url": "https://stackoverflow.com/questions/61971097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Web Server for Progressive web apps I am a beginner to developing a Progressive Web Apps, as i have used Chrome Web Server initially to host my progressive web application.But i don't know how to host my PWA app on other web server. Your help will be appreciated! A: * *Get a GitHub account, install GitHub software, and commit some code to your repo *Get a free Heroku account, and install Heroku CLI on your computer. *Point your Heroku account, in its configuration, to your Git repo's master branch *If your app consists of static files, follow the following instructions (Heroku only hosts non-static sites): Add a file called composer.json to the root directory by running: touch composer.json Add a file called index.php to the root directory by running: touch index.php Rename the homepage (e.g. index.html) to home.html In index.php, add the following line: <?php include_once("home.html"); ?> In composer.json, add the following line: {} From a command line, CD into your project's root directory. Run the following command: git push heroku master *You should now have a staging server on Heroku, with https enabled. Whenever you commit code to your master branch and sync it with GitHub.com, there will automatically be a deployment behind the scenes from your GitHub repository to your Heroku hosting account. Boom! You have all the ingredients you need to stage a successful PWA application. Production hosting is up to you, maybe try DigitalOcean to start with.
{ "language": "en", "url": "https://stackoverflow.com/questions/53792673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading Class from Path I want to create 'modules' which extend a 'Module' interface, these would be separate jars that get loaded on runtime - essentially adding extra features. I want to have these loaded as the 'Module' object (from the interface). I've tried the below code, and while my code prints out the Found module, it doesn't do anything after that. try { Collection<URL> urlList = new ArrayList<>(); Path pluginsDir = Paths.get(Common.getPlugin().getDataFolder().getPath(), "modules"); try (DirectoryStream<Path> jars = Files.newDirectoryStream(pluginsDir, "*.jar")) { for (Path jar : jars) { System.out.println("Found module (" + jar.toFile().getName() + ")."); urlList.add(jar.toUri().toURL()); } } URL[] urls = urlList.toArray(new URL[0]); ClassLoader pluginClassLoader = new URLClassLoader(urls, this.getClass().getClassLoader()); ServiceLoader<Module> loader = ServiceLoader.load(Module.class, pluginClassLoader); for (Module module : loader) { System.out.println("module.getName() = " + module.getName()); } } catch (IOException ex) { ex.printStackTrace(); } I'd expect it to print out the modules name (as an interface method) but it doesn't loop. For example, a module would do; public class ExampleModule implements Module { @Override public String getName() { return "Example"; } @Override public void load() { Bukkit.getLogger().info("Hello!"); } } Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/58353670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modal is not showing and can't close So I am trying to add the search function and the scrollable table in the bootstrap modal I have. At the moment, I have made 1 modal to work with the functions and it is showing good results. But then the other modals of the same page does not seem to load when I click the button for the modal. I did not added any extra codes for these or assigned any new classes or ids. As shown in the first image, the modal wont show and I am unable to go back the main page. Whilst the second image shows the modal with working functionality. This is the code for the Medical Plan Modal <div class="modal fade" id="medicPlanModal" tabindex="-1" role="dialog" aria-labelledby="medicPlanModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content modal-container"> <div class="modal-header"> <h5 class="modal-title" id="medicPlanModalLabel">Add medical plan</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action="/postMedicalPlan" method="POST"> <div class="modal-body"> <div class="form-group"> <label for="medicalPlanName" class="col-form-label">Medical Plan:</label> <input type="text" class="form-control" name="medicalPlanName"></input> </div> <div class="form-group"> <label class="col-form-label">Medical Card:</label> <p>Front</p> <input type="file" name="medicalCardFront"> </div> <div class="form-group"> <p>Back</p> <input type="file" name="medicalCardBack"> </div> <div> <label for="userid" class="col-form-label">Available for:</label> <div class="modal-search-group"> <i class="fa2 fa-search" aria-hidden="true"></i> <input type="search" class="form-control rounded " placeholder="Search" aria-label="Search" aria-describedby="search-addon" id="search_mp_add" /> </div> <div class="modal-table-fix"> <table class="modal-table"> <thread class="thread-inverse"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Contact</th> <th>Action</th> </tr> </thead> <tbody id="table_body_mpadd"> <% for(var i=0; i < data.employee.length; i++) { %> <tr> <td> <%= data.employee[i].name %> </td> <td> <%= data.employee[i].email %> </td> <td> <%= data.employee[i].contact %> </td> <td><input type="checkbox" class="checkbox" name="userid" value=<%=data.employee[i]._id %>> | ADD </td> </tr> <% } %> </tbody> </thread> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> </div> And this is the code for Clinic List <div class="modal fade" id="clinicModal" tabindex="-1" role="dialog" aria-labelledby="clinicModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="clinicModalLabel">Add clinic</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action="/postClinic" method="POST"> <div class="modal-body"> <div> <label for="clinicName" class="col-form-label">Clinic name:</label> <input type="text" class="form-control" name="clinicName"></input> </div> <div> <label for="latitude" class="col-form-label">Latitude:</label> <input type="text" class="form-control" name="latitude"></input> </div> <div> <label for="longitude" class="col-form-label">Longitude:</label> <input type="text" class="form-control" name="longitude"></input> </div> <div> <label for="userid" class="col-form-label">Available for:</label> <table> <thread class = "thread-inverse"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Contact</th> <th>Action</th> </tr> </thead> <tbody> <% for(var i=0; i < data.employee.length; i++) { %> <tr> <td><%= data.employee[i].name %></td> <td><%= data.employee[i].email %></td> <td><%= data.employee[i].contact %></td> <td><input type="checkbox" class="checkbox" name="userid" value=<%= data.employee[i]._id %>> | ADD </td> </tr> <% } %> </tbody> </thread> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> js code function setSearch(inputEle, rowEle){ $(inputEle).keyup(function(){ search_table(rowEle, $(this).val()); }); } function search_table(rowEle, value){ $(rowEle).each(function(){ var found = 'false'; $(this).each(function(){ if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) { found = 'true'; } }); if(found == 'true') { $(this).show(); } else { $(this).hide(); } }); } setSearch('#search_home', '#table_body_home tr'); setSearch('#search_p', '#table_body_p tr'); setSearch('#search_pi', '#table_body_pi tr'); setSearch('#search_atnd', '#table_body_atnd tr'); setSearch('#search_benefit', '#table_body_benefit tr'); setSearch('#search_cal_leave', '#table_body_cal_leave tr'); setSearch('#search_cal_lr', '#table_body_cal_lr tr'); setSearch('#search_cal_act', '#table_body_cal_act tr'); setSearch('#search_contract', '#table_body_contract tr'); setSearch('#search_parties', '#table_body_parties tr'); setSearch('#search_rewards', '#table_body_rewards tr'); setSearch('#search_rewards_add', '#table_body_re_add tr'); setSearch('#search_medplan', '#table_body_medplan tr'); setSearch('#search_medrec', '#table_body_medrec tr'); setSearch('#search_clist', '#table_body_clist tr'); setSearch('#search_insurance', '#table_body_ins tr'); setSearch('#search_mp_add', '#table_body_mpadd tr'); setSearch('#search_clist_add', '#table_body_clistadd tr'); css .modal-container { width: 120%; } .modal-table-fix { overflow-y: auto; overflow-x: hidden; height: 160px; } .modal-table-fix thead th { position: sticky; top: 0; background: rgb(255, 255, 255); padding: 0 0 10px 1px; } /* Borders (if you need them) */ .tableFixHead, .tableFixHead td { box-shadow: inset 1px -1px rgb(255, 255, 255); } .tableFixHead th { box-shadow: inset 1px 1px rgb(255, 255, 255), 0 1px rgb(255, 255, 255); } .modal-table tbody td { padding: 5px; } .modal-search-group { width: 40%; display: -ms-flexbox; display: flex; margin: 0px 0 10px 0; } .fa2 { display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; color: black; padding: 10px; text-align: center; } A: As https://stackoverflow.com/users/13926890/mohit-jain mentioned you need to do this inside your js file, whenever you are invoking your modal either for closing or for opening it. function search_table(rowEle, value){ $(rowEle).each(function(){ var found = 'false'; $(this).each(function(){ if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) { found = 'true'; } }); if(found == 'true') { $('#yourIdHere').modal({show:true}); //in case it doesn't work, use this // $('#yourIdHere').modal('show'); } else { $('#yourIdHere').modal({show:false}); //in case it doesn't work, use this //$('#yourIdHere').modal('hide'); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/66098529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: viewmodel .prototype .function vs self .function in a viewmodel? Both code blocks below work, in context and seem completely functionally equivalent. I understand js prototypes reasonably well, so I'm not asking about them per se (unless that is the only difference). Rather, comparing two simple ways to put a method on a view model as shown below, are there any implications / differences for Knockout, e.g. binding time? define(["knockout", "text!./home.html"], function(ko, homeTemplate) { // <-- An AMD Module function HomeViewModel(route) { var self = this; self.message = ko.observable('Snacks!'); self.eatSomething = function () { self.message('Yum, a viewmodel snack.'); }; } return { viewModel: HomeViewModel, template: homeTemplate }; }); versus adding method via prototype: define(["knockout", "text!./home.html"], function(ko, homeTemplate) { function HomeViewModel(route) { this.message = ko.observable('Snacks!'); }; HomeViewModel.prototype.eatSomething = function () { this.message('Yum, the same viewmodel snack, only different?'); }; return { viewModel: HomeViewModel, template: homeTemplate }; }); (The code is a simple mod of Yeoman's scaffolding output via a Knockout generator. It created the boiler plate code for a knockout component, a fairly recent (KO 3.2) and very welcome feature. A nice KO component explainer is here.) A: In the first example, since the function uses self (which is set to a reference to the new instance) rather than this, no matter how the function is called/bound, it would always correctly set its own message observable. In the second example, when binding normally to the function like data-bind="click: eatSomething", you would get the same result. Knockout calls the function with the value of this equal to the current data. If you had a scenario where you needed to call the function from a different context (maybe your view model has a child object that you are using with or a template against). then you might use a binding like data-bind="click: $parent.eatSomething". KO would still call the function with this equal to the current data (which would not be $parent), so you would have an issue. One advantage of putting the function on the prototype though, is that if you created many instances of HomeViewModel they would all share the same eatSomething function through their prototype, rather than each instance getting its own copy of the eatSomething function. That may not be a concern in your scenario, as you may only have one HomeViewModel. You can ensure that the context is correct by calling it like: data-bind="click: $parent.eatSomething.bind($parent). Using this call, would create a new wrapper function that calls the original with the appropriate context (value of this). Alternatively, you could bind it in the view model as well to keep the binding cleaner. Either way, you do lose some of the value of putting it on the prototype, as you are creating wrapper functions for each instance anyways. The "guts" of the function would only exist once on the prototype though at least. I tend to use prototypes in my code, but there is no doubt that using the self technique (or something like the revealing module pattern) can reduce your concern with the value of this.
{ "language": "en", "url": "https://stackoverflow.com/questions/26198099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Need help making string input return a histogram that counts frequency of letter pairs I need to write a function(s) that takes strings as inputs and outputs a histogram of the frequency of letter pairs, in descending order. I've managed to write a function that returns single char count, but I can't figure out how to do pairs. Here's what I have thus far: var string = "etc"; var histogram = {}; for (var i = 0, len = string.length; i < len; i++) { var char = string[i]; if ((string[i] !== " ") && (string[i] !== " ")) { histogram[char] = (histogram[char] || 0) + 1; } }; console.log(histogram); The function works, and I was able to get it to leave all empty spaces out of the histogram. I'm stuck as to where to go from here, though. How to get it to evaluate pairs, and how to leave out any single char (those not followed by another char)... Any help much appreciated. A: Another approach, breaking the problem down into tiny pieces: const inPairs = (xs) => [...xs].reduce((a, x, i) => i == 0 ? a : [...a, xs[i - 1] + x], []) const pairFreq = str => str // "this is a good thing" .split (/\s+/) //=> ["this","is","a","good","thing"] .filter (s => s.length > 1) //=> ["this","is","good","thing"] .flatMap (inPairs) //=> ["th","hi","is","is","go","oo","od","th","hi","in","ng"] .reduce ( (a, s) => ({...a, [s]: (a[s] || 0) + 1}), {}) //=> {"th":2,"hi":2,"is":2,"go":1,"oo":1,"od":1,"in":1,"ng":1} console .log ( pairFreq('this is a good thing') ) Obviously you could inline inPairs if you chose. I like this style of transformation, simply stringing together steps that move me toward my end goal. A: You need to make use of string[i+1] to get the next letter in the pair. And to avoid accessing outside the array when you use string[i+1], the limit of the loop should be string.length-1. var string = "this is a good thing"; var histogram = {}; for (var i = 0, len = string.length - 1; i < len; i++) { if ((string[i] !== " ") && (string[i + 1] !== " ")) { let pair = string.substr(i, 2); histogram[pair] = (histogram[pair] || 0) + 1; } }; console.log(histogram);
{ "language": "en", "url": "https://stackoverflow.com/questions/56843656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine the current orientation I would like to determine the current orientation of the device in a WP7 app. I do not want to handle the OrientationChange event, because I need the current orientation when the page is opened. I've been trying to do it with this piece of code I found in a forum: ((PhoneApplicationFrame)Application.Current.RootVisual).Orientation However, this always returns with PortraitUp, even if I turn the device sideways. And by the way, I am trying to do this with the emulator, so it might be an emulator-bug. Thanks A: Just tested it on the emulator and on my device. In the emulator it's like Mark is metioning it's always returning PotraitUp. However if i test it on my device than the correct orientation is directly returned. So probably as Mark is suggesting it's a emulator bug. A: This worked for me.. and it worked perfectly.. hope this helps others.. PageOrientation orient = Orientation; CheckOrientation(orient); The above code gets the orientation of the current page. Call it in method of your class. Then, you can perform the following private void CheckOrientation(PageOrientation orient) { if (orient == PageOrientation.LandscapeLeft || orient == PageOrientation.LandscapeRight) { //Do your thing } else if (orient == PageOrientation.PortraitUp || orient == PageOrientation.PortraitDown) { //Do your thing } } A: What I found out about this: ((PhoneApplicationFrame)Application.Current.RootVisual).Orientation does not have the correct orientation in PageLoaded. It does not give back the correct orientation in the first LayoutUpdated event either. However there is a second LayoutUpdated event, in which it gives the correct one. And between the two LayoutUpdated events, if the last page was in another orientation, then there will be an OrientationChanged event as well. So there was no other solution for me then waiting for the OrientationChanged event to happen (because the only page the user can come to this page from supports only Portrait mode). A: Your application must support Landscape orientation to receive it. If you support only Portrait, than you never get nor OrientationChanged event and Landscape orientation in provided property. A: The solution is: public YourPhonePage() { InitializeComponent(); Microsoft.Phone.Controls.PageOrientation currentOrientation = (App.Current.RootVisual as PhoneApplicationFrame).Orientation; if (currentOrientation == PageOrientation.PortraitUp) { // Do something... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/8577760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: F# - Return a value from for .. do I have a (random) set of numbers and I want to decide for any given number, whether the number is a composite one (meaning it can be created by two other numbers in the same given set). Mathematical definition of my function: Current code: let task1 (M : seq<'T>, r : 'T) : bool = if not(Seq.exists((=) r) M) then failwith "nope!" else for s in M do for t in M do if s + t = r then true // error false Issue: I cannot return a boolean result from my iteration, when the element r has been 'found' as sum of the two elements s and t. How could I solve the given problem as efficiently as possible? If somebody finds an algorithm with a total run-time smaller than O(n²), then it is also fine by me. [all called methods must also be faster than O(n²)] A: You can't do what you're trying to do because F# is a language that uses expressions rather than statements. F# expressions always evaluate to a value (although that value might be unit: ()). The code you originally posted doesn't compile because something of type unit is expected, that's because your if/then expression has no else branch. Consider the following: let a = if x > 5 then 10 This code will produce a compiler error, that's obvious because we haven't specified what the integer value of a might be if x is not greater than 5. Of course, this code will compile: let a = if x > 5 then 10 else 5 If you provide and if without an else, the F# compiler will assume the type is unit so this is also valid code: let a = if x > 5 then () This is because both cases still just return unit, there is no type mismatch. Because F# uses expressions, everything has to be bindable to a value. Anyway, you can solve this by using nested Seq.exists statements, this way you can check every combination of values. let inline task1 items r = items |> Seq.exists (fun s -> items |> Seq.exists(fun t -> s + t = r)) I've changed some of your naming conventions (it's idiomatic for F# function parameters to be camelCased) and have made your function inline so it will work on any type that supports addition. A: Generally, you don't want to use loops to implement complicated iterations / recursive functions in F#. That's what tail recursive functions are good for. To get the computational complexity below O(n²), how about this: consider the set of candidate summands, which is the complete set of numbers at first. Now look at the sum of the largest and smallest number in this set. If this sum is larger than the target number, the largest number won't sum to the target number with anything. The same goes the other way around. Keep dropping the smallest or largest number from the set of candidates until either the set is empty or a match has been found. The code could look like this: let rec f M x = if Set.isEmpty M then false else let biggest, smallest = Set.maxElement M, Set.minElement M let sum = biggest + smallest if sum > x then f (Set.remove biggest M) x elif sum < x then f (Set.remove smallest M) x elif sum = x then true else failwith "Encountered failure to compare numbers / NaN" When I look at the mathematical definition, it doesn't seem to be a requirement that the target number is in the set. But if this matters, just check beforehand: let fChecked M x = if Set.contains x M then f M x else invalidArg "x" "Target number is not contained in set." Tom make this generic over the comparable type, the function could be marked inline. Set operations are O(log n), we go over the whole thing once, multiplying O(n), making the total complexity O(n log n) (where n is the number of elements in the set). Effective speed version If it's about actual speed rather than "just" the computational complexity, arrays are probably faster than immutable sets. Here's a version that uses array indices: /// Version where M is types as an unsorted array we're allowed to sort let f M x = Array.sortInPlace M let rec iter iLow iHigh = if iLow > iHigh then false else let sum = M.[iLow] + M.[iHigh] if sum > x then iter iLow (iHigh - 1) elif sum < x then iter (iLow + 1) iHigh elif sum = x then true else failwith "Encountered failure to compare numbers / NaN" iter 0 (M.Length - 1) Note that we could pre-sort the array if the same set is used repeatedly, bringing down the complexity for each call on the same set down to O(n).
{ "language": "en", "url": "https://stackoverflow.com/questions/36816256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Generating first n prime numbers using dynamic programming How can I generate first n prime numbers using dynamic programming ? (Code is not required just the concept would be enough) A: We can use Memoization technique for generating prime numbers using dynamic programing. You can write a function which accepts the number to be checked(say x) for primality and another parameter which accepts divisor(say the variable is i). Inside the function check for the conditions like i==1 then return 1 and x%i==0 then return 0 and again call the function recursivly with decrementing i and the result shoiud be stored in to an array. A: If you will google it, you will find the solution very easily: BTW solution is Use method described here: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
{ "language": "en", "url": "https://stackoverflow.com/questions/29025520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Run Once Code: Beyond Boolean? I'm struggling for a pattern here. I have quite a few tasks that need to be run, but only need to be run once if they haven't been run before. Everything right now is handled by if/then, booleans and a hashtable. There are also nested children of the same effect (if/then, boolean) so their parent if/then, boolean isn't set to true until the very end. In .NET, is there some kind of code pattern or class for this that makes it simplier/clearer/less code, or am I over-thinking it and this is exactly the way needs to be done? P.S. feel free to add better tags to this post, I wouldn't know what to add to make it more descriptive if there is a term out there A: I don't know how your tasks are coded, but it seems that they could be encapsulated in commands, which would then be put in a queue, or some other data structure. Once they are dequeued, their logic is checked. If they need to run, they are executed, and they're not put back in the queue. If their logic says that they shouldn't run, they're just put back in the queue to be able to run later. Your interface would be something like: public interface ITaskSink { void AddTask(ICommandTask task); } public interface ICommandTask { bool ShouldRun(); void Run(ITaskSink sink); } Tasks could also be able to add other tasks to the data structure (so Run takes an ITaskSink as a parameter), covering your subtask creation requirement. A task could even add itself back to the sink, obviating the need for the ShouldRun method and simplifying your task processor class. A: If you're using .NET 4.0, the Lazy<T> generic might be the solution to what you're describing, because it evaluates its value at most once. I'm not sure I exactly understand your use case, but there's no reason you couldn't nest Lazys together to accomplish the nested children issue. A: I'm not exactly sure what you're talking about, but a helpful pattern for complex chained logic is the rules engine. They're really simple to code, and can be driven by simple truth tables, which are either compiled into your code or stored as data. A: Create a private static variable, create a read only property to check for null on the private variable, if the variable is null instantiate/initialize and just return the private variable value. In your implementation code reference the property, never the private variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/3420708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass Post (variable) info to a second page I have an HTML order form that collects info and then on submission passes that to a PHP form which sends an email. Then I have the PHP form forwarding to a PHP confirmation page. * *I am using the POST method on my HTML form. *I am forwarding to the PHP confirmation page with header() after it sends the email. Everything is working fine, but I need to know how to pass the variables along to the confirmation page. I can use them on the email page, but they are dropped on the page forwarding. I'm sure it's easy, but I have a lot to learn yet. :-) Do I have to create a file to store the variables, or can I pass them along? I know I could display the confirmation page with the PHP page that sends the email (I did have it setup that way) but we have had users bookmark that page which will resend the order every time they visit that bookmark. So I'm separating the pages so if they bookmark the confirmation page it will at least not resend an order. Make sense? Thanks for your help! A: You can keep the parameter sent in POST in session variables. This way on your second page, you can still access them. For example on your first page : <?php session_start(); // ... // $_SESSION['value1'] = $_POST['value1']; $_SESSION['value2'] = $_POST['value2']; header('Location: youremailpage.php'); die(); // ... // ?> And on your second page : <?php session_start(); // ... // $value1 = $_SESSION['value1']; $value2 = $_SESSION['value2']; // ... // ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/3754707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does "alternate tone or mood" exactly means in tag definition in HTML 5? In the docs(MDN), it is written:"Use the element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages". What does "alternate tone or mood" means in the above definition? Can someone explain it in simple terms. It would be quite helpful if someone can explain this by providing an example. A: Perhaps a good way to answer your question is from the same reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em New developers are often confused at seeing multiple elements that produce similar results. <em> and <i> are a common example, since they both italicize text. What's the difference? Which should you use? By default, the visual result is the same. However, the semantic meaning is different. The <em> element represents stress emphasis of its contents, while the <i> element represents text that is set off from the normal prose, such a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use <cite>.) This means the right one to use depends on the situation. Neither is for purely decorational purposes, that's what CSS styling is for. To "emphasize" something is to express "alternate tone or mood". If you want to "emphasize" a certain word or phrase in a paragraph, you can use italics. In editors like MS-Word, you can highlight the text, and select "Italicize". Older versions of HTML provided the <i> element. HTML 5 introduced the "semantic" equivalent, <em>. Distinguishing it from other semantic elements, like <cite>.
{ "language": "en", "url": "https://stackoverflow.com/questions/62921999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to structure a Python package so others can add modules easily I have a component-oriented Python (3.3) project. I have a base Component class. I want others to be able to add modules that contain subclasses of Component just by copying their .py file(s) into some folder, without having to edit anything. Running the main program should then simply import all the .py files found in that folder. All accesses from my main program to these subclasses are via Component.__subclasses__(), not by explicit name. I am not especially worried about name clashes between code in different user-written modules, but of course I would like to avoid it if possible without screwing up the simple drop-file-into-folder inclusion. How do I structure a package to achieve this? A: I would structure the package like this: myPackage + -- __init__.py + -- Component.py + -- user_defined_packages + -- __init__.py # 1 + -- example.py Ideas: * *let the users drop into a different folder so that they do not mix up your code and theirs *The init file in user_defined_packages can load all the subpackages once user_defined_packages is imported. It must print all errors. __init__.py # 1 import os import traceback import sys def import_submodules(): def import_submodule(name): module_name = __name__ + '.' + name try: __import__(module_name) except: traceback.print_exc() # no error should pass silently else: module = sys.modules[module_name] globals()[name] = module # easier access directory = os.path.dirname(__file__) for path_name in os.listdir(directory): path = os.path.join(directory, path_name) if path_name.startswith('_'): # __pycache__, __init__.py and others continue if os.path.isdir(path): import_submodule(path_name) if os.path.isfile(path): name, extension = os.path.splitext(path_name) if extension in ('.py', '.pyw'): import_submodule(name) import_submodules()
{ "language": "en", "url": "https://stackoverflow.com/questions/21436315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Phone 8 URI associations and the mail client I have an application that has a registered URI association (my-prefix://) as per http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987(v=vs.105).aspx however I have noticed a difference between how the emulator works and how a device works. Within the emulator I can send myself a HTML email containing a link with the above URI prefix (e.g. my-prefix://my-data). The link appears blue and clicking it opens my app as expected. On a Lumia 920 (accessing the same mail on the same mailbox), the link appears black (as per other text) and clicking it highlights the entire link but doesn't launch the app. It does nothing. Interestingly, accessing the same mail on a WP7 device (Lumia 900) does show it as a blue link, but WP7 doesn't support the URI associations so it obviously doesn't actually work. Reading the documentation that I've found, there is nothing specific that says that this should or should not work from within an email. The documentation states that "A URI association allows your app to automatically launch when another app launches a special URI", and various articles state that Bing Vision doesn't support them directly (although opening a web page which redirects to the URI apparently works). My main question is: am I doing something wrong, or is this the expected behaviour? (Unfortunately the links with the custom URI prefix aren't generated by me so can't be altered to be http with a redirect). Craig. A: Apparently, the "Safe HTML policy" on Exchange can lead to some URIs with "non-standard" schemes being just treated as plain text. If this is the case and you can't control the policy on the server, the only option is to wrap in a HTTP redirect. :(
{ "language": "en", "url": "https://stackoverflow.com/questions/19022676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Better way to handle asynchronous log writing public static class LogWriter { private static ReaderWriterLockSlim writeLock = new ReaderWriterLockSlim(); public static void WriteExceptionLog(string content) { #if DEBUG MessageBox.Show(content); #endif WriteLog(content, Constant.EXCEPTION_LOG_PATH); } public static void WriteLog(string content, string path) { try { writeLock.EnterWriteLock(); string directory = Path.GetDirectoryName(path); if (!Directory.Exists(Path.GetDirectoryName(directory))) Directory.CreateDirectory(directory); using (StreamWriter writeFile = new StreamWriter(path, true)) { content = DateTime.Now + " : " + content; writeFile.WriteLine(content); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { writeLock.ExitWriteLock(); } } } I have a class that writes logs. Because I am writing to a log asynchronously, I need to put a lock and release it when write is done but this seems to be somewhat of a clunky solution and maybe even bad for performance. What is a better way to handle this? A: For performance reason and also to avoid a very different behavior between log-ON and log-OFF, I suggest to run one buffered log file per thread. * *One per thread to avoid locking: no contention *Buffered to avoid disk latency The counterparts are: * *a merging tools based on time (milliseconds) is needed to see application activity as a whole (vs thread activity) *buffering may hide last log records in case of brutal termination To go one step more to real-time, you have to log in memory, and to develop a dedicated interface to extract log on request but this kind of log is generally reserved to hard real-time embedded application. Other solution for safe logging with low CPU consumption (low level C programming): * *place a log record buffer into shared memory *the observed process act as log record producer *create a log manager process, with higher priority, which acts as log record consumer *manage the communication between consumer and producer behind a flip/flop mechanism: a pointer assignment under critical section. If the observed process crash, no log record will be lost since shared memory segment is attached to log manager process. A: Opening, writing to, and then closing the file on each log request is both redundant and inefficient. On your log class, use a buffer, and write that buffer's contents to the file, either every X requests, shutdown, or every Y minutes.
{ "language": "en", "url": "https://stackoverflow.com/questions/13024433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parsing information from a jQuery POST request? I have been trying for 2 weeks to get and parse information from an API of this site: http://www.imei.info/api/imei/docs/ I'm new to web development (RT C++ developer), I can't seem to get is to work. my code here: <!DOCTYPE html> <html> <head> <script src="Scripts/jquery-1.4.1.js" type="text/javascript"> </script> <script type="text/javascript"> $(document).ready(function () { $("input").keyup(function () { txt = $("input").val(); $.post("http://www.imei.info/api/checkimei/", { login: "XXX", password: "XXX", imei: "XXX" }, function (data) { $("span").html(data); $('#message').html(data); }); }); }); </script> </head> <body> <p>Start typing a name in the input field below:</p> First name: <input type="text" /> <div id="message"></div> </body> </html> A: It's returning a JSON response. You can do var responseObj = JSON.parse(data) and access the fields like responseObj.imei or responseObj.brand
{ "language": "en", "url": "https://stackoverflow.com/questions/15988787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: why validate content-type header in REST request The OWASP website suggest to validate the content-type header. But it does not specify the rational for the same. What is the reason that I should validate the content-type header, even though I am not reading or using it? When POSTing or PUTting new data, the client will specify the Content-Type (e.g. application/xml or application/json) of the incoming data. The server should never assume the Content-Type; it should always check that the Content-Type header and the content are the same type. A lack of Content-Type header or an unexpected Content-Type header should result in the server rejecting the content with a 406 Not Acceptable response. A: One example that comes to mind is in a cross-site ajax request, it is easy to send a text/html request which will not generate a pre-flight request, but it is not possible with applictaion/json. So if you have a service with a POST action that expects json and changes server state, it may be possible to exploit CSRF if text/html is accepted for the content type, but there is some basic protection if application/json is verified, because the browser will not send the request from a different domain if the response to the pre-flight does not explicitly allow a CORS post. So some properties of cross-domain ajax requests depend on the content type. I think this may be the main reason. Also from a more theoretical standpoint, the format of the data is needed to parse it. I cannot think of an actual exploit, but at least in theory, trying to parse data in a wrong format may lead to the wrong results, things parsed different from what they were supposed to be. It's best to just validate that the client is actually sending what it claims, and what it should be.
{ "language": "en", "url": "https://stackoverflow.com/questions/40763181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Include argument in NAnt executable call if property is not null or empty For a build script, part of my process is to deploy files using an in-house executable. We call this with a number of parameters. On an application I'm working on, it turns out we need to add a parameter. This isn't something that retroactively applies to anything else I've previously worked on, so the idea is that I would only include the new argument if the corresponding property is not null or empty. Relevant NAnt Call: <property name="deploy.NewArg" value="" /> <echo message="deploy.NewArg = ${deploy.NewArg}" /> <exec program="C:\Deploy\MyAwesomeDeployProgram.exe"> <arg value="AppTitle=${deploy.AppTitle}" /> <arg value="Environment=${deploy.Environment}" /> <!-- Here's the problem argument... --> <arg value="MyNewProperty=${deploy.NewArg}" if="${deploy.NewArg}" /> </exec> The reason what I have is not working, is because of the if clause on the new <arg> tag - the deploy.NewArg string doesn't convert to a boolean statement. Question: In what way can I perform an "Is Null or Empty" check on an <arg if> parameter? As noted above, I want the MyNewProperty=... argument added if deploy.NewArg is anything but nothing or an empty string. I checked a number of other StackOverflow questions, as well as the official NAnt arg tag documentation, but could not find how to do this. A: It turns out, I needed to get back to the basics, and check out some of my fundamentals and functions. The way to do an 'is empty' check on a property is as below: <exec program="C:\Deploy\MyAwesomeDeployProgram.exe"> <!-- Other args... --> <arg value="MyNewProperty=${deploy.NewArg}" if=${string::get-length(deploy.NewArg) > 0}" /> </exec> For someone who hasn't yet done the research, if only works with a boolean. That being said, booleans can be generated in one of two ways: either an explicit true or false, or by using an expression. Expressions are always contained in ${} brackets. The use of string::get-length() should be obvious. Bring it all together, and you only include an argument if it's specified.
{ "language": "en", "url": "https://stackoverflow.com/questions/47354516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Render props with typescript I am trying to create a render props wrapper component. It is working, but I am getting type errors. Here is my link to a code sandbox as well. link to sandbox * *the first error I am getting is children is an expression that is not callable. *the second error is "hello" has implicitly any type. Looking for a react/typescript guru for help type Props = { children: JSX.Element; }; const ControlledWrapper: FC<Props> = ({ children }) => { const state: { hello: string } = { hello: 'hello' }; return children(state); }; export default function App() { return ( <ControlledWrapper> {({ hello }) => <div>{hello}</div>} </ControlledWrapper> ); } A: Change the type of children to a function that returns a React element: type Props = { children: (ctx: { hello: string }) => ReactElement; }; Now when you use the component you get the right types: {({ hello }) => <div>{hello}</div>} // 'hello' is a string Try this out here.
{ "language": "en", "url": "https://stackoverflow.com/questions/72307968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: extension 'GL_ARB_shading_language_420pack' is not supported, how to load this extension in QT? I'm using QT on a mac pro to run a demo of opengl. But I got a message like this: :: OpenGL initialized ( 4.1 INTEL-14.7.8 ) QOpenGLShader::compile(Fragment): WARNING: 0:1: extension 'GL_ARB_shading_language_420pack' is not supported ERROR: 0:6: '{' : syntax error: syntax error Does anyone know how to make this extension "GL_ARB_shading_language_420pack" supported in Qt? A: I'm using QT on a mac pro MacOS does not support any OpenGL version higher than 4.1. It doesn't support 4.20 or most post-4.1 OpenGL extensions. And since OpenGL support is already deprecated in MacOS, no such support will be forthcoming. If you want to use OpenGL on MacOS, then you're going to have to limit everything to 4.1 functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/63380964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Average in dataframes with subsets of rows - Python I have a dataframe as the following: Member Category Total 1001 1 5 1001 2 4 1001 3 9 1003 1 7 1003 2 5 1003 3 2 1005 1 2 1005 3 5 I need to get: Member Category Total Average 1001 1 5 0.27 1001 2 4 0.22 1001 3 9 0.5 1003 1 7 0.5 1003 2 5 0.35 1003 3 2 0.15 1005 1 2 0.28 1005 3 5 0.72 That is, the average of totals for each member. For instance, the member 1001 has a total of 18, in which the category 1 represents 27% of the total. Therefore the average would be 0.27. What I tried was: average = [] for member in df[df["Member"].unique(): total_member = df[df["Member"] == member]["Total"].sum() for category in df["Category"].unique(): total_category = df[(df["Member"]==member) & (df["Category"]==category)]["Total"] average.append(total_category/total_member) df["Average"] = average However, not only does it not work, but since I have a very large amount of data, it is too slow. A: Use transform for sum for divide by column Total: df['Average'] = df['Total'] / df.groupby('Member')['Total'].transform('sum') print (df) Member Category Total Average 0 1001 1 5 0.277778 1 1001 2 4 0.222222 2 1001 3 9 0.500000 3 1003 1 7 0.500000 4 1003 2 5 0.357143 5 1003 3 2 0.142857 6 1005 1 2 0.285714 7 1005 3 5 0.714286 Detail: print (df.groupby('Member')['Total'].transform('sum')) 0 18 1 18 2 18 3 14 4 14 5 14 6 7 7 7 Name: Total, dtype: int64 Alternative solution: df['Average'] = df['Total'] / df['Member'].map(df.groupby('Member')['Total'].sum()) Timings: np.random.seed(123) N = 100000 L = ['AV','DF','SD','RF','F','WW','FG','SX'] dates = pd.date_range('2015-01-01', '2015-02-20') df = pd.DataFrame(np.random.randint(100, size=(N, 3)), columns=['Member','Category','Total']) df = df.sort_values(['Member','Category']).reset_index(drop=True) #Wen solution In [395]: %timeit df.groupby('Member').Total.apply(lambda x : x/sum(x)) 10 loops, best of 3: 31.2 ms per loop In [396]: %timeit df['Total'] / df.groupby('Member')['Total'].transform('sum') 100 loops, best of 3: 5.11 ms per loop #alternative a bit slowier solution In [397]: %timeit df['Total'] / df['Member'].map(df.groupby('Member')['Total'].sum()) 100 loops, best of 3: 9.92 ms per loop A: df['ave']=df.groupby('Member').Total.apply(lambda x : x/sum(x)) df Out[318]: Member Category Total ave 0 1001 1 5 0.277778 1 1001 2 4 0.222222 2 1001 3 9 0.500000 3 1003 1 7 0.500000 4 1003 2 5 0.357143 5 1003 3 2 0.142857 6 1005 1 2 0.285714 7 1005 3 5 0.714286
{ "language": "en", "url": "https://stackoverflow.com/questions/47039231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: display different under IE6 and other browers i know IE6 is dead,but in china, there are lots of people still using it. so expect someone can do me a favor about this problem. this is the page.the even line's background color is not the same length, under IE6, which is shorter the display under IE6. (http://run.xxmn.com/ie6.jpg). the bgcolor displays different from other browers. the display under IE7,FF,CHROME (http://run.xxmn.com/ie7.jpg). it displays ok. how to make it under IE6 displays the same result as other browers? ps:the problem is solved. thanks all the guys. A: The problem in IE6 is probably due to negative margins on the views-field-title class (though I don't have IE6 installed to check). You don't actually need negative margins to achieve the effect you want. So suggest removing them like this: * *Remove margin-left: -4px; from #left_cplist .cplist-bg .view-content .views-field-title *Remove margin-left: 5px; form #left_cplist .cplist-bg .views-row
{ "language": "en", "url": "https://stackoverflow.com/questions/4487274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex: Passing object to save back to server freezes application I have a NavigatorContent which is displayed when the user selects an item in a DataGrid. This NavigatorContent contains a form and an accordion displaying the related objects. When the user presses the Save button in the NavigatorContent the form and the children should be saved to the database by calling the server through BlazeDS: saveObjectToDB() { //Map the form values to the object object.field1 = object_field1.text; object.field2 = object_field2.selectedDate as Date; object.relatedobject3 = comboBox.selectedItem as RelatedObject3; //etc..... //Loop through accordion to save the child objects for(var i:int= 0; i < accordion.numChildren; i++ ) { if(accordion.getChild(i) is RelatedObject1Form) { var formRelated1:RelatedObject1Form = accordion.getChild(i) as RelatedObject1Form; //Map the form values to the related object object.relatedobject1.field1 = formRelated1.relatedobject1_field1.selectedDate; //etc... } if(accordion.getChild(i) is RelatedObject2Grid) { var gridRelated2:RelatedObject2Grid = accordion.getChild(i) as RelatedObject2Grid; //Get dataProvider for the datagrid of the relatedObject object.relatedobject2 = gridRelated2.object.relatedobject2; } } // Call the remoting object's saveObject method var saveObjectOperation:Operation = new Operation(); saveObjectOperation.name = "saveObject"; saveObjectOperation.arguments=[object]; ro.operations = [saveObjectOperation]; saveObjectOperation.send(); if(isNewObject) //dispatchEvent new object else //dispatchEvent object updated } My problem is as the question states that my application freezes for a few seconds when the user presses the save button that calls this method. I guess that is because Flex is single threaded, but still i dont quite get why this method would be so computational expensive? It doesnt seem to matter if i comment out the loop that loops over the accordion children. I tried setting the objects related objects to null before calling the remote save method, and this seemed to speed up the save method, but it provided me with some troubles later. My conclusion is that the remote call is whats freezing up the application, and if i set the related objects to null this seems to fix the issue. But is this really necessary? The related objects aren't really that big, so i don't quite get why the remote call should freeze the application for a few seconds. This is how i create the accordion children when the NavaigatorContent is intialized: var relatedObjectForm:RelatedObject1Form= new RelatedObject1Form(); accordion.addChild(relatedObjectForm); relatedObjectForm.object= object; relatedObjectForm.ro = this.ro; The object that i pass to the accordion children is public and [Bindable] in the NavigatorContent and in the accordion children and is initially passed from the main DataGrid. May this be a problem relating to this issue? Any help/comments is much appreciated. This issue is starting to affect my beauty sleep ;) A: My guess would be that you're spending a lot of time in the serializer. Put a trace target in the app and watch the console when it runs to see what's being sent. The most likely problems are from DisplayObjects - if they've been added to the application they will have a reference to the application itself, and will cause some serializers to start serializing the entire app. The bindable object might have some odd events attached that eventually attach to DisplayObjects - try copying the relevant values in it into your object instead of just taking a reference to the existing object.
{ "language": "en", "url": "https://stackoverflow.com/questions/8984707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to weave AspectJ java project into Spring boot project I have java project named Test which have all aspects in it. I wan to use these aspects in another spring boot project. I am working on a poc to weave aspects in Test project into a spring boot application. What is the efficient way to do so and how it can be done, can some one who implemented please suggest. Code for Java project Test with aspects @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Secured { public boolean isLocked() default false; } @Aspect public class SecuredMethodAspect { @Pointcut("@annotation(secured)") public void callAt(Secured secured) {} @Around("callAt(secured)") public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable { if (secured.isLocked()) { System.out.println(pjp.getSignature().toLongString() + " is locked"); return pjp.proceed(); } else { return pjp.proceed(); } } } <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>aspect</groupId> <artifactId>test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>AspectJ-POC</name> <url>http://maven.apache.org</url> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <java.version>11</java.version> </properties> <!-- nickwongdev aspectj maven plugin, this is for weaving of aspects --> <build> <plugins> <plugin> <groupId>com.nickwongdev</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.12.6</version> <configuration> <source>11</source> <target>11</target> <complianceLevel>11</complianceLevel> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <!-- aspectj runtime dependency --> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.6</version> </dependency> </dependencies> </project> A: Some quick first impressions I got when browsing your projects before cloning them: * *You should not use Lombok + native AspectJ together in a compile-time weaving scenario, see my answer here. *Possible workarounds would be multi-phase compilation, i.e. first Java + Lombok and then post-compile-time weaving with AspectJ, see my answer here. Alternatively, use delombok in order to first generate source code with Lombok annotations expanded into equivalent source code and then compile the generated sources with AspectJ. *On a second look, your sample aspect module does not seem to use any Lombok, so you do not need that dependency. But probably your real project does, hence my remarks above. *Of course, you can use compile-time weaving in order to weave your aspects, as you suggested. You need to correctly configure AspectJ Maven Plugin in this case, though, which you did not. You need to tell it in the Spring Boot module where to find the aspect library and which dependencies to weave, in addition to the main application. Did you ever read the plugin documentation, e.g. chapters Weaving classes in jars, Using aspect libraries and Multi-module use of AspectJ? I also answered tons of related questions here already. *But actually, the preferred approach for weaving aspects into Spring applications is to use load-time weaving (LTW), as described in the Spring manual. That should be easier to configure and you would not need any AspectJ Maven Plugin stuff and probably would not have any Lombok issues during compilation either. Judging from your sample projects and the absence of any aspectLibraries and weaveDependencies sections in your AspectJ Maven configuration, you simply did not bother to read any documentation, which leaves me to wonder what you did during the one month you tried to get this working. I would appreaciate a comment, explaining why you want to use CTW instead of LTW. The only reason I can think of is that in addition to your native aspect, you also want to use Spring AOP aspects withing your Spring application. But if you activate native AspectJ LTW, you cannot use Spring AOP at the same time anymore. If that is not an issue, I recommend LTW, as it is documented and tested well in Spring. CTW is no problem either, but more difficult to understand and manage in your POMs. Update: OK, I did not want to wait any longer for your reason to use CTW and simply decided to show you a LTW solution instead. What I did was: * *Remove AspectJ Maven Plugin and AspectJ Tools from your Spring project *Add src/main/resources/org/aspectj/aop.xml, configuring it to use your aspect and target your base package + subpackages *Fix pointcut to also use your base package + subpackages, because in your base package there are no classes. This is a typical beginner's mistake. You need to use execution(* com.ak..*(..)) with .., not just com.ak.*. Non-essential cosmetics I applied are: * *Call context.getBean(TestController.class).mainRequest() from the Spring Boot application's main method in order to automatically produce some aspect output, in order to avoid having to use curl or a web browser in order to call a local URL. *Use the Spring application as an auto-closeable via try-with-resources in order to make the application close after creating the desired log output. *Change the aspect to also log the joinpoint in order to see in the log, which methods it actually intercepts. Otherwise all log lines look the same, which is not quite helpful. *Use try-finally in order to make sure that the log message after proceeding to the original method is also logged in case of an exception. The diff looks like this (I hope you can read diffs): diff --git a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java --- a/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java (revision Staged) +++ b/aspect-test-project/src/main/java/com/ak/aspect/MethodLogAspect.java (date 1626233247623) @@ -7,14 +7,14 @@ @Aspect public class MethodLogAspect { - @Around("@annotation( MethodLog) && (execution(* com.ak.*(..)))") + @Around("@annotation(MethodLog) && execution(* com.ak..*(..))") public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable { - System.out.println("***Aspect invoked before calling method***"); - - final Object obj = joinPoint.proceed(); - - System.out.println("***Aspect invoked after calling method***"); - - return obj; + System.out.println("[BEFORE] " + joinPoint); + try { + return joinPoint.proceed(); + } + finally { + System.out.println("[AFTER] " + joinPoint); + } } } diff --git a/src/main/java/com/ak/ParentprojectSpringbootApplication.java b/src/main/java/com/ak/ParentprojectSpringbootApplication.java --- a/src/main/java/com/ak/ParentprojectSpringbootApplication.java (revision Staged) +++ b/src/main/java/com/ak/ParentprojectSpringbootApplication.java (date 1626233555873) @@ -1,14 +1,17 @@ package com.ak; +import com.ak.controller.TestController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication(scanBasePackages = { "com.ak.*" }) -//@SpringBootApplication public class ParentprojectSpringbootApplication { public static void main(String[] args) { - SpringApplication.run(ParentprojectSpringbootApplication.class, args); + try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) { + context.getBean(TestController.class).mainRequest(); + } } } diff --git a/parentproject-springboot/pom.xml b/parentproject-springboot/pom.xml --- a/parentproject-springboot/pom.xml (revision Staged) +++ b/parentproject-springboot/pom.xml (date 1626232421474) @@ -71,13 +71,6 @@ <version>1.9.6</version> </dependency> - <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjtools --> - <dependency> - <groupId>org.aspectj</groupId> - <artifactId>aspectjtools</artifactId> - <version>1.9.6</version> - </dependency> - <dependency> <groupId>com.ak.aspect</groupId> <artifactId>aspect-test-project</artifactId> @@ -100,24 +93,6 @@ </configuration> </plugin> - <plugin> - <groupId>com.nickwongdev</groupId> - <artifactId>aspectj-maven-plugin</artifactId> - <version>1.12.6</version> - <configuration> - <source>11</source> - <target>11</target> - <complianceLevel>11</complianceLevel> - </configuration> - <executions> - <execution> - <goals> - <goal>compile</goal> - <goal>test-compile</goal> - </goals> - </execution> - </executions> - </plugin> </plugins> </build> For your convenience, here are the complete changed files: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.ak</groupId> <artifactId>parentproject-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>parentproject-springboot</name> <description>Test project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.ak.dependency</groupId> <artifactId>dependencyprojet</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- aspectj runtime dependency --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>com.ak.aspect</groupId> <artifactId>aspect-test-project</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project> <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver options="-verbose -showWeaveInfo"> <!-- only weave classes in our application-specific packages --> <include within="com.ak..*"/> </weaver> <aspects> <aspect name="com.ak.aspect.MethodLogAspect"/> </aspects> </aspectj> package com.ak.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class MethodLogAspect { @Around("@annotation(MethodLog) && execution(* com.ak..*(..))") public Object wrap(final ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("[BEFORE] " + joinPoint); try { return joinPoint.proceed(); } finally { System.out.println("[AFTER] " + joinPoint); } } } package com.ak; import com.ak.controller.TestController; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication(scanBasePackages = { "com.ak.*" }) public class ParentprojectSpringbootApplication { public static void main(String[] args) { try (ConfigurableApplicationContext context = SpringApplication.run(ParentprojectSpringbootApplication.class, args)) { context.getBean(TestController.class).mainRequest(); } } } Now you simply make sure to add the JVM argument -javaagent:/path/to/aspectjweaver-1.9.6.jar to your Java command line in order to activate native AspectJ LTW. For more details about how to configure LTW within Spring if more sophisticated ways, please read the Spring manual, section Using AspectJ with Spring Applications. The console log should look something like this: [AppClassLoader@3764951d] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT [AppClassLoader@3764951d] info register classloader jdk.internal.loader.ClassLoaders$AppClassLoader@3764951d [AppClassLoader@3764951d] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml [AppClassLoader@3764951d] info register aspect com.ak.aspect.MethodLogAspect [AppClassLoader@3764951d] warning javax.* types are not being woven because the weaver option '-Xset:weaveJavaxPackages=true' has not been specified [RestartClassLoader@1f385e10] info AspectJ Weaver Version 1.9.6 built on Tuesday Jul 21, 2020 at 13:30:08 PDT [RestartClassLoader@1f385e10] info register classloader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@1f385e10 [RestartClassLoader@1f385e10] info using configuration /C:/Users/alexa/Documents/java-src/SO_AJ_SpringCTWMultiModule_68040124/parentproject-springboot/target/classes/org/aspectj/aop.xml [RestartClassLoader@1f385e10] info register aspect com.ak.aspect.MethodLogAspect . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.2) (...) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.service.TestService.incomingRequest())' in Type 'com.ak.service.TestService' (TestService.java:20) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.AccountInfo com.ak.dependency.Route.accountInfo())' in Type 'com.ak.dependency.Route' (Route.java:12) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) [RestartClassLoader@1f385e10] weaveinfo Join point 'method-execution(com.ak.dependency.model.BalanceInfo com.ak.dependency.Pipeline.balanceInfo())' in Type 'com.ak.dependency.Pipeline' (Pipeline.java:11) advised by around advice from 'com.ak.aspect.MethodLogAspect' (MethodLogAspect.java) (...) Controller [BEFORE] execution(AccountInfo com.ak.service.TestService.incomingRequest()) [BEFORE] execution(AccountInfo com.ak.dependency.Route.accountInfo()) [BEFORE] execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo()) [AFTER] execution(BalanceInfo com.ak.dependency.Pipeline.balanceInfo()) [AFTER] execution(AccountInfo com.ak.dependency.Route.accountInfo()) [AFTER] execution(AccountInfo com.ak.service.TestService.incomingRequest()) (...)
{ "language": "en", "url": "https://stackoverflow.com/questions/68040124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: group by ratio and seniority list IN SQL I am working on a MYSQL, and I am looking for a solution to show data grouping by ratio. I have a COURSE table which contain courses id and courses ratio. I have another table, ASK, which contain askers id, and another field course id pointing on COURSE table (ids correspond). With one SQL query, I would like to display all asks grouping by ratio and rejecting other demands. Demands are considered by seniority list. By example, I have 3 courses: the first one allow only 2 people and 2 other courses allow only one person. In the ASK table, we have 3 askers (JACK, JOE AND JOHN) pointing on first course, (JOHN AND JOE) 2 on second and third (JACK AND JOHN). JACK is the older, after its JOHN and after its JOE. I would like to see: course id studentName ------------------------- 1 JACK 1 JOHN 2 JOHN 3 JACK A: SELECT c.courseID s.studentName FROM course AS c JOIN asks AS a ON a.courseID = c.courseID JOIN student AS s ON s.studentName = a.studentName JOIN asks AS a2 ON a2.courseID = c.courseID JOIN student AS s2 ON s2.studentName = a2.studentName AND s2.seniority <= s.seniority GROUP BY c.courseID , c.ratio , s.studentName HAVING c.ratio >= COUNT(*) ORDER BY c.courseID , s.seniority
{ "language": "en", "url": "https://stackoverflow.com/questions/6642130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Iteration of a for loop based on a text file Question: How can I make a for loop iterate over a text or a csv file instead of an array? Scenario: fruits = ["apple", "banana", "cherry"] For instance regarding the code above, instead of the fruits array I want it to be the text or csv file A: Try this: filename=["1.txt","2.txt","3.txt"] for file in filename: with open(file,'r/w') as f: #r for reading w for writing #Other code Or if you want to iterate throught all files from a folder then try this: import os filename=os.listdir("/path/to/folder you want the files from") for file in filename: with open(file,'r/w') as f: #r for reading w for writing #Other code
{ "language": "en", "url": "https://stackoverflow.com/questions/68361159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Postgres 13 pg_cron error on RDS that's hard to track down pg_cron jobs all fail with "role of....doesn't provide permission to schedule a job" I'm working on getting pg_partman and pg_cron set up on RDS, but when my pg_cron jobs run, they return this error: ERROR: The protected role of rds_super doesn't provide permission to schedule a job. From the error text, it seems like I'm missing a simple permissions issue on something in the directory or resources holding pg_cron, but I can't find the source of the problem. And, it's possibly something else. A lot of Googling, hunting through sources, and trial-and-error hasn't lead me to any answers, and I'm hoping for help. For background, this is Postgres 13.4 with pg_cron 1.3. These are the latest versions now available on RDS. My goal is to have pg_cron running jobs in various databases in this cluster, but I've reduced the problem example to the cron schema in postgres. RDS defines a role named rds_superuser that doesn't have a login, which you can then grant to other users. We're using a custom role named rds_super, and have for years. When you create extension pg_cron up on RDS, the install is into the postgres database by default, and it creates a new schema named cron. That's all fine. As a "hello world" version of the problem, here's a simple table and task to insert the current time every minute into a text field. DROP TABLE IF EXISTS cron.foo; CREATE TABLE IF NOT EXISTS cron.foo ( bar text ); GRANT INSERT ON TABLE cron.foo TO rds_super; INSERT INTO cron.foo VALUES (now()::text); select * from cron.foo; -- Run every minute SELECT cron.schedule('postgres.populate.foo','*/1 * * * *', $$INSERT INTO cron.foo VALUES (now()::text) $$); The bare statement INSERT INTO cron.foo VALUES (now()::text) works fine, when connected directly as the rds_super user. But when it's executed through the cron.job defined above, the cron.job_run_details output has the right code, the expected user, but a failure result with this error: ERROR: The protected role of rds_super doesn't provide permission to schedule a job. Does this ring a bell for anyone? I've deleted, reinstalled, set permissions explicitly. No improvement. Public This may be off, but I ran into a couple of things where it looked like I needed to provide access to public. I started in PG 9.4 or 9.5, couldn't get my head around securing public...and stripped all of the rights off it everywhere. Putting some back in may be needed here? Permissions checks Here are the permissions checks that I could think of. select grantor, grantee, table_schema, table_name, string_agg (privilege_type, ',' order by privilege_type) as grants from information_schema.role_table_grants where table_catalog = 'postgres' and table_schema = 'cron' and grantee = 'rds_super' group by 1,2,3,4 order by 1,2,3,4; I gave the user all privileges on all of the tables, just to see if that cleared things up. No joy. grantor grantee table_schema table_name grants rds_super rds_super cron foo DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE rds_super rds_super cron job_run_details_plus DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE rds_superuser rds_super cron job DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE rds_superuser rds_super cron job_run_details DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE Nothing is obviously wrong with the schema rights: select pg_catalog.has_schema_privilege('rds_super', 'cron', 'CREATE') AS create, pg_catalog.has_schema_privilege('rds_super', 'cron', 'USAGE') AS usage; create usage t t Likewise, nothing pops out when I check function execution rights: select proname, proargnames from pg_proc where has_function_privilege('rds_super',oid,'execute') and pronamespace::regnamespace::text = 'cron' order by 1,2 proname proargnames job_cache_invalidate schedule {job_name,schedule,command} schedule {schedule,command} unschedule {job_id} unschedule {job_name} Answer I do not know if this is the answer, but it seems to have fixed my problem. Spoiler: Log in as the user the pg_cron scheduler background worker runs as. I burned everything down and restarted, and then found that my jobs simply would not run. No error, no results. I checked the status of the background workers like this: select application_name, usename, backend_type, query, state, wait_event_type, age(now(),backend_start) as backend_start_age, age(now(),query_start) as query_start_age, age(now(),state_change) state_change_age from pg_stat_activity where backend_type != 'client backend'; I noticed that the background worker had been running for over a day (it's loaded as a shared library), and seemed to be stuck. I rebooted the server, and redid everything logged in as dbadmin, instead of my custom user. That's the user name that the pg_cron scheduler process is running as, in this case. I don't remember if dbadmin is part of the package with RDS Postgres, or if it's something I added years back. There's nothing in the RDS pg_cron instructions about this, so maybe it's just me. I needed to set up its search_path and permissions a bit to get everything working the way I needed, but that's normal. https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/PostgreSQL_pg_cron.html A: At least in my case, the answer is to run the jobs as the same user as the pg_cron background thread. I've posted more details to the end of the original question.
{ "language": "en", "url": "https://stackoverflow.com/questions/69822551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enabling TLS-1.2 on embedded Jetty Currently I am using this code which is enabling TLS 1.2: ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); httpsConnector.setPort(8443); httpsConnector.setIdleTimeout(50000) Now I am using TLS 1.1 and want to change it to TLS 1.2. A: Java 8 is TLS/1.2 by default. * *https://blogs.oracle.com/java-platform-group/entry/java_8_will_use_tls You can diagnose TLS in the JVM using the techniques at: * *https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https If you want to force TLS/1.2, see the prior answer at: How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections Know that the ciphers and protocols you expose in Jetty's SslContextFactory will also have an influence on your TLS support level. (For example: you can exclude the ciphers that TLS/1.0 knows about leaving no ciphers to negotiate against) A: Yeah, I resolved this question just now. We can customize it by org.eclipse.jetty.util.ssl.SslContextFactory just like this: * *exclude TLSv1、TLSv1.1 protocol etc. sslContextFactory.addExcludeProtocols("TLSv1", "TLSv1.1"); By the way, my jetty version is 9.4.45, default protocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3") have already excluded by Jetty. // org.eclipse.jetty.util.ssl.SslContextFactory#DEFAULT_EXCLUDED_PROTOCOLS private static final String[] DEFAULT_EXCLUDED_PROTOCOLS = {"SSL", "SSLv2", "SSLv2Hello", "SSLv3"}; *include only TLSv1.2 protocol (some protocols etc.) sslContextFactory.setIncludeProtocols("TLSv1.2"); The final protocols selected you can see in the method org.eclipse.jetty.util.ssl.SslContextFactory#selectProtocols , you can debug yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/43287071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Liferay Service Builder - Database Persistence i understand that persistence layer is where you store your data, and that not all data is persisted in the same manner -- some use databases, some use XML, some use a remote service. What then is (as a verb) Database Persistence? I'm studying Liferay Service Builder and came across a definition that "it automates creation of interfaces and classes for database persistence" In other words, What is database persistence in the context above in simple plain English! A: Lifera service builder generates classes that can be used to do CRUD operations for database entity only. So its referred as database persistence.
{ "language": "en", "url": "https://stackoverflow.com/questions/23179360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: primefaces datatable selectionMode multiple not working with mojarra Recently I switched to mojarra from myfaces and noticed that primefaces datatable checkbox multiple row selection is not working. I have tried the exact sample program available at http://www.primefaces.org/showcase/ui/datatableRowSelectionRadioCheckbox.jsf With myfaces both single and multiple selection are working ,but with mojarra multiple selection is not working(selectedCars.length is 0 in setSelectedCars method) I have tried with mojarra 2.0.3 and mojarra 2.1.0 with primefaces 2.2.1 A: Adding 'f:view contentType="text/html"' solved the problem. Read this in http://www.primefaces.org/faq.html A: <p:column sortBy="#{tup.docTypeAndDirection}" > <f:facet name="header"> <h:outputText value="Document Type"/> </f:facet> <h:outputText value="#{tup.docTypeAndDirection}"/> </p:column> <p:column sortBy="#{tup.partnerEDIAddress}" > <f:facet name="header"> <h:outputText value="Partner Trading Address"/> </f:facet> <h:outputText value="#{tup.partnerEDIQual}:#{tup.partEDIAddr}"></h:outputText> </p:column> </p:dataTable>
{ "language": "en", "url": "https://stackoverflow.com/questions/5569502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS 11 - Location update not received after adding delegate I have been having trouble with location services in iOS 11 for both "Allow while Use" and "Always Allow". Works without issue in iOS < 11. Followed this thread in trying to fix but still doesn't work. What am I missing? Thank you in advance. * *I have UITabViewController in my app and a UINavigationController inside each tab. *I have a singleton LocationManager class. I'm setting my UINavigationController's RootViewController as delegate the ViewController's viewWillAppear to receive location updates and removing in viewWillDisappear. *Now, When I launch the app, before the tab bar is created, I can see the location update is being called in the LocationManager Class. *But when I add my UIViewController as delegate and give startUpdatingLocation I'm not receiving the location update in my UIVIewController. *Then I press Home button and exit the app. Again immediately launch the app and I get the location update in my delegate method. I have added all three location authorization description in my Info.plist file. Info.Plist: <key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>Blah Blah Blah</string> <key>NSLocationAlwaysUsageDescription</key> <string>Blah Blah Blah</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Blah Blah Blah</string> LocationController.m: #import "LocationController.h" //static int LOCATION_ACCESS_DENIED = 1; //static int LOCATION_NETWORK_ISSUE = 2; //static int LOCATION_UNKNOWN_ISSUE = 3; enum { LOCATION_ACCESS_DENIED = 1, LOCATION_NETWORK_ISSUE = 2, LOCATION_UNKNOWN_ISSUE = 3 }; static LocationController* sharedCLDelegate = nil; @implementation LocationController int distanceThreshold = 10.0; // in meters @synthesize locationManager, currentLocation, locationObservers; - (id)init { self = [super init]; if (self != nil) { self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.distanceFilter = distanceThreshold; self.locationManager.pausesLocationUpdatesAutomatically = NO; [self.locationManager startMonitoringSignificantLocationChanges]; self.locationManager.delegate = (id)self; if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [self.locationManager requestWhenInUseAuthorization]; //I tried both commenting this line and uncommenting this line. Didn't make any difference } if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [self.locationManager requestAlwaysAuthorization]; } [self.locationManager startUpdatingLocation]; [self.locationManager startUpdatingHeading]; locationObservers = [[NSMutableArray alloc] init]; } return self; } #pragma mark - #pragma mark CLLocationManagerDelegate Methods - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@"locationManager didUpdateLocations = %@",locations); CLLocation *newLocation = [locations lastObject]; if (newLocation.horizontalAccuracy < 0) { return; } currentLocation = newLocation; for(id<LocationControllerDelegate> observer in self.locationObservers) { if (observer) { // CLLocation *newLocation = [locations lastObject]; // if (newLocation.horizontalAccuracy < 0) { // return; // } // currentLocation = newLocation; NSTimeInterval interval = [currentLocation.timestamp timeIntervalSinceNow]; //check against absolute value of the interval if (fabs(interval)<30) { [observer locationUpdate:currentLocation]; } } } } - (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error { NSLog(@"locationManager didFailWithError: %@", error); for(id<LocationControllerDelegate> observer in self.locationObservers) { if (observer) { [observer failedToGetLocation:error]; } } switch (error.code) { case kCLErrorDenied: { break; } case kCLErrorNetwork: { break; } default: break; } } #pragma mark - Singleton implementation in ARC + (LocationController *)sharedLocationInstance { static LocationController *sharedLocationControllerInstance = nil; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ sharedLocationControllerInstance = [[self alloc] init]; }); return sharedLocationControllerInstance; } -(void) locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { NSLog(@"didChangeAuthorizationStatus = %i",status); if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) { [self.locationManager stopUpdatingLocation]; [self.locationManager startUpdatingLocation]; } } - (void) addLocationManagerDelegate:(id<LocationControllerDelegate>)delegate { if (![self.locationObservers containsObject:delegate]) { [self.locationObservers addObject:delegate]; } [self.locationManager startUpdatingLocation]; } - (void) removeLocationManagerDelegate:(id<LocationControllerDelegate>)delegate { if ([self.locationObservers containsObject:delegate]) { [self.locationObservers removeObject:delegate]; } } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedCLDelegate == nil) { sharedCLDelegate = [super allocWithZone:zone]; return sharedCLDelegate; // assignment and return on first allocation } } return nil; // on subsequent allocation attempts return nil } - (id)copyWithZone:(NSZone *)zone { return self; } #pragma mark UIAlertViewDelegate Methods - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { switch (alertView.tag) { case LOCATION_ACCESS_DENIED: { if (buttonIndex == 1) { //[[UIApplication sharedApplication] openURL: [NSURL URLWithString: UIApplicationOpenSettingsURLString]]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]]; } } break; case LOCATION_NETWORK_ISSUE: break; case LOCATION_UNKNOWN_ISSUE: break; default: break; } [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES]; } @end LocationController.h #import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> #import <Foundation/Foundation.h> // protocol for sending location updates to another view controller @protocol LocationControllerDelegate @required - (void)locationUpdate:(CLLocation*)location; - (void)failedToGetLocation:(NSError*)error; @end @interface LocationController : NSObject<CLLocationManagerDelegate,UIAlertViewDelegate> @property (nonatomic, strong) CLLocationManager* locationManager; @property (nonatomic, strong) CLLocation* currentLocation; @property (strong, nonatomic) NSMutableArray *locationObservers; + (LocationController*)sharedLocationInstance; // Singleton method - (void) addLocationManagerDelegate:(id<LocationControllerDelegate>) delegate; - (void) removeLocationManagerDelegate:(id<LocationControllerDelegate>) delegate; @end ViewController.m - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSLog(@"VC viewWillAppear"); [locationControllerInstance addLocationManagerDelegate:self]; } AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [LocationController sharedLocationInstance]; } A: I had one of the new devices reported this problem, as you know the the Location Manager usually calls this: -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation The bizarre thing is that the UserLocation object contains two coordinate objects: 1) userLocation.location.coordinate: This used to work fine, but for some reason it's returning NULL on IOS11 on some devices (it's unknown yet why or how this is behaving since IOS11). 2) userLocation.coordinate: This is another (same) object as you can see from the properties, it has the location data and continues to work fine with IOS11, this does not seem to be broken (yet). So, with the example above, "I guess" that your: * *(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations Might be having the same problem (i.e. the array might be returning a NULL somewhere in the location object, but not the coordinate object, the solution I did on my code which gets one location at a time, is now fixed by by replacing userLocation.location.coordinate with userLocation.coordinate, and the problem gone away. I also paste my function below to assist you further, hopefully it would help you to resolve yours too, notice that I have two conditions for testing one for sourcing the location object and the other for sourcing the coordinate object, one works fine now, and the other seems to be broken in IOS11: -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { Log (4, @"MapView->DidUpdateUL - IN"); if (_OrderStartTrackingMode == enuUserMapTrackingMode_User) { if (userLocation) { if (userLocation.location) { if ( (userLocation.location.coordinate.latitude) && (userLocation.location.coordinate.longitude)) { [_mapLocations setCenterCoordinate:userLocation.location.coordinate animated:YES]; } else { if ( (userLocation.coordinate.latitude) && (userLocation.coordinate.longitude)) { [self ShowRoutePointsOnMap:userLocation.coordinate]; } } } } } else if (_OrderStartTrackingMode == enuUserMapTrackingMode_Route) { if (userLocation) { if ( (userLocation.coordinate.latitude) && (userLocation.coordinate.longitude)) { [self ShowRoutePointsOnMap:userLocation.coordinate]; } } } Log (4, @"MapView->DidUpdateUL - OUT"); } Needless to say, have you checked your settings for the Map object, you should have at least "User Location" enabled: P.S. The Log function on the code above is a wrapper to the NSLog function, as I use mine to write to files as well. Good luck Uma, let me know how it goes. Regards, Heider
{ "language": "en", "url": "https://stackoverflow.com/questions/46616496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meteor: Count data from collection anyone please i need you help. before this I have asking question but I cannit find this solution. I have create code to count variable in collection. I can get the result when count one by one but not by group. Thats my code, I want to count this but the code not given any resut to me. I want the result like this: PTR 1 KOM 4 This my code: <template name="laporankategori"> <table class="table"> <thead> <tr> <th>Jenis Peralatan</th> <th>Kuantiti</th> </tr> </thead> <tbody> {{#each profil}} <tr> <td>{{PTR}}</td> <td>{{KOM}}</td> </tr> {{/each}} </tbody> </table> </template> //js Template.laporankategori.helpers({ profil: function() { return Profil.find({kategori: { $in: ['PTR', 'KOM'] } }).count(); } }); A: Whenever you're iterating with {{#each ...}} your helper should return either a cursor or an array. Your helper is returning a scalar: the count. In your {{#each }} block you refer to {{PTR}} and {{KOM}} but those won't exist. I suspect that you weren't actually looking for the count in this case and your helper should just be: Template.laporankategori.helpers({ profil: function() { return Profil.find({kategori: { $in: ['PTR', 'KOM'] } }); } }); Also you don't often need to count things in a helper since in a template you can refer to {{profil.count}} and get the count of the cursor directly. A: <template name="laporankategori"> <table class="table"> <thead> <tr> <th>Jenis Peralatan</th> <th>Kuantiti</th> </tr> </thead> <tbody> {{#each profil}} <tr> <td>{{count}}</td> </tr> {{/each}} </tbody> </table> </template> //js Template.laporankategori.helpers({ profil: function() { var PTR = { count: Profil.find({kategori: { $in: ['PTR'] } }).count() }; var KOM = { count : Profil.find({kategori: { $in: ['KOM'] } }).count() }; var resultArr = [PTR, KOM]; return resultArr; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/37087209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: new ATMEGA1281 and avrdude I'm experiencing sometimes problems when programming my new ATMEGA1281. It is suposed to be the same as my old one, the only difference I guess is the serial number: ATMEGA1281 16AU 1104 vs ATMEGA1281 16AU 1304 I'm used to program the ATMEGA1281 with avrdude command, but with the new chip, I have sometimes this error: avrdude: verifying ... avrdude: verification error, first mismatch at byte 0x0000 0x0c != 0xff avrdude: verification error; content mismatch Do you know why I'm having this problem? Thanks in advance! A: What programmer do you use? The brand new microcontroler might have lower clock than your previous one and it might be to slow for your programmer. Try decreasing your programmer bitclock (-B option of avrdude). It should be 4 times slower than the clock. Then you can change microcontroller fuses and use the programmer with the old bitclock.
{ "language": "en", "url": "https://stackoverflow.com/questions/16733662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: insert data into html table from flat file I have lots of user records similar to the following inside my main index.html page: <tr> <td>Angelica Ramos</td> <td>Chief Executive Officer (CEO)</td> <td>London</td> <td>47</td> <td>2009/10/09</td> <td>$1,200,000</td> <td>504</td> </tr> This is of course in a table. Now, what i want to do is make this dynamic. I cant modify the original index.html page each time a user record is updated. so my question is, how do i make html read from a file and insert the records in the file in the table in the original index.html file? my index.html file has a code that allows you to type a user name in a search box and the record for that particular user will pop up. the preferred solution will work with this already existing code so that, after html reads from the record from the external file, an admin can still search for the user name and have the user name pop up as though it was still embedded in the original index.html file. I tried to do this on my own, but was not successful: <script> $.ajax( {url:"myuserRecords.html", dataType:"text"}).done( function(data){ $('#table-responsive').html(data); }); </script> The record did not show up when searched for through the search box. A: The following works with a CSV file. You may need to do this before proceding. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>StackOverflow</title> </head> <body> <input type="text" id="searchvalue"><button onclick="search()">Search</button> <table id="userslist"></table> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> var data = [],keys,values=[],delimeter=";"; function getData(onsuccess) { $.ajax({ url:"/Users/Default/Downloads/test.csv", type:"GET", datatype:"csv", success:onsuccess }); } function parseData() { keys = data.splice(0,1)[0].split(delimeter); values = []; for(var i=0,n=data.length;i<n;i++) { values.push(data[i].split(delimeter)); } } function getTableRow(data,isheading) { var rowtype = isheading ? 'th' : 'td'; var rowhtml = '<tr>'; for(var key in data) { rowhtml+='<'+rowtype+'>'+data[key]+'</'+rowtype+'>'; } return (rowhtml+'</tr>'); } function populateData() { var htmldata = ""; htmldata = getTableRow(keys,true); for(var index in values) { htmldata+=getTableRow(values[index]); } document.getElementById("userslist").innerHTML = htmldata; } function search() { var data = [], keys = [], values = [];; function addRecord() { for(var i=0,n=data.length;i<n;i++) { var value = data[i].split(delimeter); if(value[0].toLowerCase().includes(searchvalue.toLowerCase())) { values.push(value); } } if(values.length) { for(var index in values) { table.insertAdjacentHTML("beforeend",getTableRow(values[index])); } } else { alert("No records found.") } } var searchvalue = document.getElementById("searchvalue").value; var table = document.getElementById("userslist"); getData(function(response){ data = response.split(/\n/); addRecord(); }); } getData(function(response){ data = response.split(/\n/); parseData(); populateData();}); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/48363701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error: is a 'field' but is used like a 'type' c# I have a global variable averagel that I am trying to manipulate in a method. The compiler doesn't have a problem with me setting the value averagel = averagel / (xrestriction * yrestriction); but for some reason it doesn't like it when I try to use it to set another variable: inside = (inside + averagel * (xrestriction * yrestriction)) - 2 * (averagel)(suml); Only on the line where I try to use averagel's value to set another int does it return the error 'sqlDataReader.ReaderDemo.averagel' is a 'field' but is used like a 'type'. I also tried setting an int in the method to the value of averagel and then trying to use that value to set my inside variable but that returned with an error of "The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?)" and all I did the line before was declare int test=averagel; Any ideas what could be going on here? A: You probably need an asterisk: inside = (inside + averagel * (xrestriction * yrestriction)) - 2 * averagel * suml; You can't multiply two values in C# like you can in mathematics. E.g. (averagel)(suml) makes sense in a math equation but you have to write averagel * suml in C#. A: You've got your parentheses wrong and accidentally included a typecast in the expression. The bit at the end (averagel) (suml) Tries to cast suml to type averagel, and so the compiler's right to complain. I suspect you're missing an operator between those two terms.
{ "language": "en", "url": "https://stackoverflow.com/questions/11192153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SWT Help button in TrayDialog I have a class that extends TrayDialog and that has a help button. I have set the folowing: setDialogHelpAvailable(true); setHelpAvailable(true); And I can't find how I'm supposed to implement the Help button in the lower left corner. I've tried @Override protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); if(buttonId == IDialogConstants.HELP_ID) { System.out.println("Help requested"); } } But it doesn't work. I've seen Can't put content behind SWT Wizard Help Button but I have no performHelp() method because I'm not in a wizard. What am I missing here? thanks A: When the help button is pressed TrayDialog looks for a control with a SWT.Help listener. It starts at the currently focused control and moves up through the control's parents until it finds a control with the listener (or runs out of controls). You can set up a help listener that is connected to a 'help context' in the Eclipse help system using PlatformUI.getWorkbench().getHelpSystem().setHelp(control, "context-id"); or you can write your own help listener. A: I had the same problem and solved it by just adding a HelpListener to one of my controls: Composite area.addHelpListener(new HelpListener() { @Override public void helpRequested(HelpEvent e) { System.out.println("This is the help info"); } }); and adding the following to my Constructor: setDialogHelpAvailable(true);
{ "language": "en", "url": "https://stackoverflow.com/questions/24041022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Allowing user to save contents of html list to text file I'm working on an application (ASP.NET, Webforms) that generates a list of outputs based on a user input. I want to allow the user to save the contents of said list as text file, or possibly as other filetypes such as .csv. What is the best way to approach this? Can it be done client-side with Javascript? A: I think you will need to use ActiveX or Java Applets or Silverlight to do something like that. JavaScript does not have access to local file system. Another way to go with this is create a file on server (physically or on the fly) and make it available for download to the user. That will get him the save file dialog. To do this on the fly, create a blank page (without any markup. not even ), set Response.ContentType = 'text/plain' and use Response.Write() to write your content in Page_Load. A: You can generate a plain text or csv file purely in client-side JavaScript by constructing and opening a data URI. Example using jQuery: window.open( 'data:text/csv;charset=utf-8,' + escape( $('#yourlist li') // <- selector for source data here .map(function(){ // format row here return $(this).text(); }) .get() .join('\r\n') ) ); Unfortunately, this technique will not work in IE due to lack of data URI support until IE8 and security restrictions once IE added support for data URIs. You'd have to use an alternative technique for IE, either hitting the server again or using ActiveX / Silverlight / Flash / Java Applet to avoid a round trip for data that is presumably already on the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/4331634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert InfluxQL to FLUX query in Grafana In Grafana I have a dashboard that uses InfluxDB 1.x as data source, I'm migrating it to use InfluxDB 2.0 data source and Flux querys. In the Grafana dashboard there is a Variable called "Server" which has the following query defined: SHOW TAG VALUES ON telegraf WITH KEY = "host" I'm really struggling creating a similar Variable with Flux query.. Any idea how to accomplish this? Thanks A: Try this: import "influxdata/influxdb/schema" schema.measurementTagValues( bucket: "my_bucket", tag: "host", measurement: "my_measurement" ) A: this work for me: from(bucket: "telegraf") |> range(start: -15m) |> group(columns: ["host"], mode:"by") |> keyValues(keyColumns: ["host"]) Note: if you want more time back (e.g. -30d) the performance will be slow, you can solve it by load this query only once (available in grafana variables) or better add some filters and selectors for example: from(bucket: "telegraf") |> range(start: -30d) |> filter(fn: (r) => r._field == "you field") |> filter(fn: (r) => /* more filter*/) |> group(columns: ["host"], mode:"by") |> first() |> keyValues(keyColumns: ["host"]) A: I'm using the following flux-code to extract all host tag-values for the bucket "telegraf" - just as your posted InfluxQL: import "influxdata/influxdb/schema" schema.tagValues(bucket: "telegraf", tag: "host") InfluxDB has a bit about this in their documentation: https://docs.influxdata.com/influxdb/v2.0/query-data/flux/explore-schema/#list-tag-values
{ "language": "en", "url": "https://stackoverflow.com/questions/63480988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Managing a windows cluster from C# I am trying to start/stop a windows based cluster in C#, below is the code I am working with so far...when I get to TakeOffLine function below I get a "Not Found" exception from, System.Management.ManagementStatus.NotFound. Not sure what is exactly not being found? If there is a (alternate) better way of doing this please let me know. Thanks! using System.Management; class App { public static void Main() { string clusterName = "clusterHex"; // cluster alias string custerGroupResource = "clusterHex.internal.com"; // Cluster group name ConnectionOptions options = new ConnectionOptions(); options.Authentication = System.Management.AuthenticationLevel.PacketPrivacy; // Connect with the mscluster WMI namespace on the cluster named "MyCluster" ManagementScope s = new ManagementScope("\\\\" + clusterName + "\\root\\mscluster", options); ManagementPath p = new ManagementPath("Mscluster_Clustergroup.Name='" + custerGroupResource + "'"); using (ManagementObject clrg = new ManagementObject(s, p, null)) { // Take clustergroup off line and read its status property when done TakeOffLine(clrg); clrg.Get(); Console.WriteLine(clrg["Status"]); System.Threading.Thread.Sleep(3000); // Sleep for a while // Bring back online and get status. BringOnLine(clrg); clrg.Get(); Console.WriteLine(clrg["Status"]); } } static void TakeOffLine(ManagementObject resourceGroup) { ManagementBaseObject outParams = resourceGroup.InvokeMethod("Takeoffline", null, null); } static void BringOnLine(ManagementObject resourceGroup) { ManagementBaseObject outParams = resourceGroup.InvokeMethod("Takeoffline", null, null); } } A: Looks like you're missing case in your method call. You have to use TakeOffline according to msdn static void TakeOffLine(ManagementObject resourceGroup) { ManagementBaseObject outParams = resourceGroup.InvokeMethod("TakeOffline", null, null); }
{ "language": "en", "url": "https://stackoverflow.com/questions/4867397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Inserting icc color profile into image using Pillow ImageCMS I am trying to insert an ICC color profile into an image. Using code from this post as an example my code looks like this: from PIL import Image, ImageCms # Read image img = Image.open(IMG_PATH) # Read profile profile = ImageCms.getOpenProfile(PROFILE_PATH) # Save image with profile img.save(OUT_IMG_PATH, icc_profile=profile) I get the following error Traceback (most recent call last): File "/home/----/Documents/code_projects/hfss-misc/icc_profiles/insert_icc_profile_into_image.py", line 17, in <module> img.save(OUT_IMG_PATH, icc_profile=srgb_profile) File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/Image.py", line 2102, in save save_handler(self, fp, filename) File "/home/----/.virtualenvs/color-correction/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 706, in _save markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER]) TypeError: 'PIL._imagingcms.CmsProfile' object is not subscriptable I thought that there might be a problem with my ICC profile so I tried to use one generated by Pillow. from PIL import Image, ImageCms # Read image img = Image.open(IMG_PATH) # Creating sRGB profile profile = ImageCms.createProfile("sRGB") # Save image with profile img.save(OUT_IMG_PATH, icc_profile=profile) I still get the same error, however. Does anyone know what the cause for this error is? My system environment is as follows: * *Ubuntu 18.04 *Python 3.6 *Pillow==7.0.0 A: The answer from github at (https://github.com/python-pillow/Pillow/issues/4464) was to use profile.to_bytes(): img.save(OUT_IMG_PATH, icc_profile=profile.tobytes())
{ "language": "en", "url": "https://stackoverflow.com/questions/60567455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP voting system check votes I’m working on a PHP voting system and I want to check logged in user voted on posts and display voted if the user have voted. I would like to do it in one single query without using multiple quires. Posts table +---------+--------+--------+ | post_id | title | c_id | +---------+--------+--------+ | 1 | post 1 | 2 | | 2 | post 2 | 3 | | 3 | post 3 | 2 | | 4 | post 4 | 1 | +---------+--------+--------+ MySQL Loop SELECT * FROM posts LEFT JOIN categories ON categories.cat_id = posts.c_id WHERE posts.c_id = categories.cat_id AND posts. active = 1 ORDER BY posts.post_id DESC LIMIT 0, 10 Votes table +---------+--------+---------+ | vote_id | p_id | u_id | +---------+--------+---------+ | 1 | 1 | 1 | | 2 | 2 | 1 | | 3 | 2 | 2 | | 4 | 4 | 1 | +---------+--------+---------+ Logged in user = $uid So if I run query inside the above MySQL loop it work fine SELECT * FROM votes WHERE u_id = $uid AND p_id= $post_id Is there a way to combine these two queries? A: SELECT * FROM posts P LEFT JOIN categories C ON C.cat_id = P.c_id LEFT JOIN (SELECT p_id FROM votes WHERE u_id = $uid) V ON V.p_id=P.post_id WHERE P. active = 1 ORDER BY P.post_id DESC LIMIT 0, 10 ; A: LEFT JOIN votes table (also no need fo left join categories if you don't want null-joins). If user has voted there will be values in joined columns - nulls will be joined otherwise. SELECT * FROM posts AS p INNER JOIN categories AS c ON c.cat_id = p.c_id LEFT JOIN votes AS v ON p.post_id = v.p_id AND v.u_id = $uid WHERE p.active = 1 ORDER BY p.post_id DESC LIMIT 0, 10 Not voted post will have nulls in vote columns, but since you want only know if user has voted you may limit output data (get only what you need) specifying concrete fields and make voted column that returns 1/0 values only: SELECT p.*, c.title, ..., IF(v.vote_id; 1; 0) AS voted A: You could use a join targeting the common Fields in both the Votes Table and the Posts Table like so: <?php $sql = "SELECT * FROM votes AS V LEFT JOIN posts AS P ON V.p_id=P.post_id WHERE (V.u_id={$uid} AND V.p_id={$post_id}) GROUP BY V.u_id"; A: You can't select votes as an array in a column but you can actually extract votes and group them. So basically what we'll do is join the two tables partially and maybe sum all the votes SELECT p.*, c.*, sum(v.Score) FROM posts p LEFT JOIN categories c ON c.cat_id = p.c_id LEFT JOIN votes v ON p.post_id = v.p_id WHERE p.active = 1 AND v.u_id = $uid GROUP BY p.post_id ORDER BY p.post_id DESC LIMIT 0, 10 You can see that I'm summing all the scores in the votes in case there're duplications
{ "language": "en", "url": "https://stackoverflow.com/questions/38025983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: trouble when running tansorflow project I was trying to run main.py of this project on my m1 macbook and got this output: Collecting Dataset... Time elapsed getting Dataset: 25.09 s Using CullPDB Filtered dataset Hyper Parameters Learning Rate: 0.0009 Drop out: 0.38 Batch dim: 64 Number of epochs: 35 Loss: categorical_crossentropy Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ... ... 2021-04-28 11:24:42.005679: I tensorflow/core/profiler/lib/profiler_session.cc:136] Profiler session initializing. 2021-04-28 11:24:42.005933: I tensorflow/core/profiler/lib/profiler_session.cc:155] Profiler session started. 2021-04-28 11:24:42.005978: I tensorflow/core/profiler/lib/profiler_session.cc:172] Profiler session tear down. 2021-04-28 11:24:48.497673: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2) 2021-04-28 11:24:48.502759: W tensorflow/core/platform/profile_utils/cpu_utils.cc:126] Failed to get CPU frequency: 0 Hz 2021-04-28 11:24:48.516051: F tensorflow/core/grappler/costs/op_level_cost_estimator.cc:710] Check failed: 0 < gflops (0 vs. 0)type: "CPU" model: "0" num_cores: 8 environment { key: "cpu_instruction_set" value: "ARM NEON" } environment { key: "eigen" value: "3.3.90" } l1_cache_size: 16384 l2_cache_size: 524288 l3_cache_size: 524288 memory_size: 268435456 and got error code 134 (interrupted by signal 6: SIGABRT) I am running in miniconda virtual env with necessary dependencies installed. Is there any solutions? Any help would be appreciated. A: The problem is I did not use proper version of TensorFlow. I finally got an answer by following this page, which tells me to install apple version Tensorflow and use conda environment, it solves the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/67293426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Optimize MySQL query with subqueries, IF and Joins I've a complex SQL Statemant which needs per call (its for a calender view) 0.35sec. With 50 users and a 2 weeks of calender items, it takes 245sec which is much too long. I tried to optimize the query but at the moment I've no more idea. I've an index on all related columns. SELECT DISTINCT tax.ta_id, tax.a_id, ax.status, ax.kunden_id, IF(ax.todo_from != '0000-00-00', DATE_FORMAT(ax.todo_from, '%d.%m'), 'k. day_date') todo_from, IF(ax.todo_until != '0000-00-00', DATE_FORMAT(ax.todo_until, '%d.%m'), 'k. day_date') todo_until, IF((SELECT taj.city FROM suborders taj WHERE taj.a_id = tax.a_id AND taj.order_type = 'BRING' ORDER BY pos_id ASC LIMIT 1) != '', CONCAT(IF((SELECT short_name FROM locations WHERE company_id = '100' AND h_id = tax.h_id) != '', (SELECT short_name FROM locations WHERE company_id = '100' AND h_id = tax.h_id),tax.city),'>', CONCAT((SELECT IF((SELECT short_name FROM locations WHERE company_id = '100' AND h_id = taj.h_id) != '', (SELECT short_name FROM locations WHERE company_id = '100' AND h_id = taj.h_id), taj.city) FROM suborders taj WHERE taj.a_id = tax.a_id AND taj.order_type = 'BRING' AND taj.pos_id >= tax.pos_id ORDER BY pos_id ASC LIMIT 1))), IF((SELECT short_name FROM locations WHERE company_id = '100' AND h_id = tax.h_id) != '', (SELECT short_name FROM locations WHERE company_id = '100' AND h_id = tax.h_id),tax.city)) as city, tax.user_id, tax.day_date, tax.pos_gesamt_id, '4' as class_type FROM suborders tax INNER JOIN orders ax ON (ax.a_id = tax.a_id) WHERE tax.order_type = 'TAKE' AND tax.user_id = '140' AND (tax.day_date = '2013-04-16' AND '2013-04-16' = (SELECT taj.day_date FROM suborders taj WHERE taj.a_id = tax.a_id AND taj.user_id = '140' AND taj.day_date = '2013-04-16' AND taj.user_id = '140' AND taj.order_type = 'BRING' ORDER BY pos_gesamt_id ASC)) AND tax.company_id = '100' GROUP BY tax.ta_id Maybe you give me some recommendation. A: First attempt at a rewrite (untested, as I have no idea of your table layouts):- SELECT DISTINCT tax.ta_id, tax.a_id, ax.status, ax.kunden_id, IF(ax.todo_from != '0000-00-00', DATE_FORMAT(ax.todo_from, '%d.%m'), 'k. day_date') todo_from, IF(ax.todo_until != '0000-00-00', DATE_FORMAT(ax.todo_until, '%d.%m'), 'k. day_date') todo_until, IF((SELECT taj.city FROM suborders taj WHERE taj.a_id = tax.a_id AND taj.order_type = 'BRING' ORDER BY pos_id ASC LIMIT 1) != '', CONCAT( IF(Sub2.short_name != '', Sub2.short_name,tax.city), '>', CONCAT(( SELECT IF( Sub3.short_name != '', Sub3.short_name, taj.city) FROM suborders taj LEFT OUTER JOIN (SELECT h_id, short_name FROM locations WHERE company_id = '100') Sub3 ON Sub3.h_id = taj.h_id WHERE taj.a_id = tax.a_id AND taj.order_type = 'BRING' AND taj.pos_id >= tax.pos_id ORDER BY pos_id ASC LIMIT 1))), IF(Sub2.short_name != '', Sub2.short_name, tax.city)) as city, tax.user_id, tax.day_date, tax.pos_gesamt_id, '4' as class_type FROM suborders tax INNER JOIN orders ax ON (ax.a_id = tax.a_id) INNER JOIN ( SELECT DISTINCT a_id FROM suborders taj WHERE taj.user_id = '140' AND taj.day_date = '2013-04-16' AND taj.user_id = '140' AND taj.order_type = 'BRING' ) Sub4 ON Sub4.a_id = tax.a_id LEFT OUTER JOIN (SELECT h_id, short_name FROM locations WHERE company_id = '100') Sub2 ON Sub2.h_id = tax.h_id WHERE tax.order_type = 'TAKE' AND tax.user_id = '140' AND tax.day_date = '2013-04-16' AND tax.company_id = '100' GROUP BY tax.ta_id At this stage I am not sure I can go any further with this, as it is REALLY confusing me how things fit together. The problem is you have a lot of correlated subqueries and these are slow (ie, a sub query that relies on a field from outside the query - hence MySQL has to perform that subquery for every single line). I have removed a couple of these that I can work out and replaced them with joins to subqueries (with these MySQL can perform the subquery once and then join the results to the main query) But it is very confusing when you have correlated subqueries within queries, and you have reused alias names between different tables and subqueries. The query can be greatly improved in performance if I can work out what it is meant to be doing! Further you also have used GROUP BY on the main query without any aggregate columns. This is sometimes done instead of a DISTINCT, but you have a DISTINCT as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/16064857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What does "Clear Graphics Context" means? In Xcode 4.3, when you choose some UIView object placed in .xib, you can find out there is an option saying "Clear Graphics Context". What does it means? A: When it is checked, iOS will draw the entire area covered by the object in transparent black before it actually draws the object.It is rarely needed. Beginning IOS 5 Development: Exploring the IOS SDK, page 81, paragraph3. A: It will apply an OpenGL "clear context" before starting the DrawRect function of the UIView: glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT);
{ "language": "en", "url": "https://stackoverflow.com/questions/10361903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: ISNULL() in LINQ to XML SELECT * FROM CUSTOMERS WHERE RTRIM(ISNULL([SHORTNAME],'')) LIKE '%john%' I want to write this using Linq, var persons = from person in xmlDoc.Descendants("Table") where person.Element("SHORTNAME").Value.Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = person.Element("PHONE") != null ? person.Element("PHONE").Value : "", zip = person.Element("ZIPCODE") != null ? person.Element("ZIPCODE").Value : "", }; This works fine when [SHORTNAME] is not null, if [SHORTNAME] is a null value this breakes the code and pops up a "Null Reference Exception" Please help me... A: Assuming you're trying to avoid picking up anything where there isn't a short name... var persons = from person in xmlDoc.Descendants("Table") let shortNameElement = person.Element("SHORTNAME") where shortNameElement != null && shortNameElement.Value.Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = person.Element("PHONE") != null ? person.Element("PHONE").Value : "", zip = person.Element("ZIPCODE") != null ? person.Element("ZIPCODE").Value : "", }; Alternatively, you can use the null coalescing operator to make all of these a bit simpler: var emptyElement = new XElement("ignored", ""); var persons = from person in xmlDoc.Descendants("Table") where (person.Element("SHORTNAME") ?? emptyElement).Value.Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = (person.Element("PHONE") ?? emptyElement).Value zip = (person.Element("ZIPCODE") ?? emptyElement).Value }; Or alternatively, you could write an extension method: public static string ValueOrEmpty(this XElement element) { return element == null ? "" : element.Value; } and then use it like this: var persons = from person in xmlDoc.Descendants("Table") where person.Element("SHORTNAME").ValueOrEmpty().Contains("123") select new { shortName = person.Element("SHORTNAME").Value, longName = person.Element("LONGNAME").Value, address = person.Element("ADDRESS").Value, Phone = person.Element("PHONE").ValueOrEmpty(), zip = person.Element("ZIPCODE").ValueOrEmpty() }; A: Use the null coalescing operator: Phone = person.Element("PHONE") ?? String.Empty;
{ "language": "en", "url": "https://stackoverflow.com/questions/1519501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java/C: OpenJDK native tanh() implementation wrong? I was digging through some of the Java Math functions native C source code. Especially tanh(), as I was curious to see how they implemented that one. However, what I found surprised me: double tanh(double x) { ... if (ix < 0x40360000) { /* |x|<22 */ if (ix<0x3c800000) /* |x|<2**-55 */ return x*(one+x); /* tanh(small) = small */ ... } As the comment indicates, the taylor series of tanh(x) around 0, starts with: tanh(x) = x - x^3/3 + ... Then why does it look like they implemented it as: tanh(x) = x * (1 + x) = x + x^2 Which is clearly not the correct expansion, and even a worse approximation than just using tanh(x) = x (which would be faster), as indicated by this plot: (The bold line is the one indicated on top. The other gray one is the log(abs(x(1+x) - tanh(x))). The sigmoid is of course the tanh(x) itself.) So, is this a bug in the implementation, or is this a hack to fix some problem (like numerical issues, which I can't really think of)? Note that I expect the outcome of both approaches to be exactly the same as there are not enough mantisse bits to actually perform the addition 1 + x, for x < 2^(-55). EDIT: I will include a link to the version of the code at the time of writing, for future reference, as this might get fixed. A: Under the conditions in which that code is executed, and supposing that IEEE-754 double-precision floating point representations and arithmetic are in use, 1.0 + x will always evaluate to 1.0, so x * (1.0 + x) will always evaluate to x. The only externally (to the function) observable effect of performing the computation as is done instead of just returning x would be to set the IEEE "inexact" status flag. Although I know no way to query the FP status flags from Java, other native code could conceivably query them. More likely than not, however, the practical reason for the implementation is given by by these remarks in the Javadocs for java.StrictMath: To help ensure portability of Java programs, the definitions of some of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic. The Java math library is defined with respect to fdlibm version 5.3. Where fdlibm provides more than one definition for a function (such as acos), use the "IEEE 754 core function" version (residing in a file whose name begins with the letter e). The methods which require fdlibm semantics are sin, cos, tan, asin, acos, atan, exp, log, log10, cbrt, atan2, pow, sinh, cosh, tanh, hypot, expm1, and log1p. (Emphasis added.) You will note in the C source code an #include "fdlibm.h" that seems to tie it to the Javadoc comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/41818255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Test that a record is a duplicate of another record in RSpec In my Rails app tested with RSpec, I'm testing a function that calls .dup() on some records and saves the duplicates. How can I test that the newly created records are duplicates of the expected original records? I doubt there's an assertion for this specific case. And I can always make sure that the duplicate and original records have the same values for their attributes but are different records. I'm wondering if there's a more elegant, accepted pattern for this kind of test. A: You can use the have_attributes assertion. match_attributes = first_user.attributes.except(:id, :created_at, :updated_at) expect(second_user).to have_attributes(match_attributes) A: You could go about it like so: it 'creates a duplicate' do record = Record.find(1) new_record = record.dup new_record.save expect(Record.where(id: [record.id,new_record.id], **new_record.attributes.except(:id, :created_at, :updated_at) ).count ).to eq 2 end This should quantify the duplication and persistence of both records in one shot.
{ "language": "en", "url": "https://stackoverflow.com/questions/56190618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: comment out lines in /fstab with bash script I need a bash script command to look in /etc/fstab and find the line that contains a mount name "/mymount" and just puts a "#" at the beginning of the line to comment it out. from this: /dev/lv_mymount /mymount ext4 defaults 1 2 to this (with a #): #/dev/lv_mymount /mymount ext4 defaults 1 2 A: Using sed: sed -i '/[/]mymount/ s/^/#/' /etc/fstab How it works: * *-i Edit the file in-place */[/]mymount/ Select only lines that contain /mymount * *s/^/#/ For those selected lines, place at the beginning of the line, ^, the character #. Using awk: awk '/[/]mymount/{$0="#"$0} 1' /etc/fstab >/etc/fstab.tmp && mv /etc/fstab.tmp /etc/fstab How it works: * */[/]mymount/ {$0="#"$0} For those lines containing /mymount and place a # at the beginning of the line. *1 This is awk's cryptic shorthand for "print each line."
{ "language": "en", "url": "https://stackoverflow.com/questions/29399790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TortoiseSVN Won't Allow Me To Add Any Files I am trying to add files to an SVN repository using TortoiseSVN 1.8.1. I right click on the files and select TortoiseSVN->Add. I then select all the files in the window that pops up and click OK. Upon clicking OK, another dialog box pops up and all the files appear to be successfully added because it says "Added" next to each file and finally it says "Completed!" at the bottom. I click OK, and then right click on the parent directory and click "Commit". I fill out the message box and ensure that all the files I added are checked and they all say "added" under "status". Finally, I click "OK". A box pops up, as it normally does, saying "You haven't entered an issue Number", and I click "Proceed without an issue number". The next box that pops up has a line that says "Adding" with a file that I'm trying to add followed by: Error: Commit failed (details follow): Error: File '%Path to my file%' is Error: out of date Error: File '%File name%' already exists Error: You have to update your working copy first. I successfully update my working copy, which has no changes. I also do a successful cleanup. I have tried deleting the parent directory and deleting the base folder altogether and rechecking out the base folder. I check the repository and there is no file there with the file name of the file being added. All of the above was through the gui. Using command prompt I got the following: svn status: svn: E155037: Previous operation has not finished; run 'cleanup' if it was interrupted svn cleanup 5.0.1: svn: E155009: Failed to run the WC DB work queue associated with '%PathToBaseRepoFolder%', work item 12841 (sync-file-flags 56 %Path to another file I was unable to add from the base repo folder%) svn: E720003: Can't set file '%Full path to the other file I was unable to add%' read-write: The system cannot find the path specified. If I do an update and cleanup from the gui, it says both are successful. We're using http:// I believe the permissions are correct. A: The problem was I updated to version 1.8.1 which has a bug. I downloaded version 1.8.0 and it works fine. A: Happened to me couple of now many times with TortoiseSVN 1.8.2 - 1.8.10. I found this blog post which solved this problem once, until it pops up again. It annoyed me so much that I wrote a quick bat file script that I run from desktop. Prerequisites * *Download and unzip sqlite3 shell tool, e.g. sqlite-shell-win32-x86-3080803.zip *Adjust paths in the commands below to match your environment Fix (manual) Run this if you just want to test if this helps * *In CMD do C:\Downloads\sqlite3.exe "C:\src\.svn\wc.db" *Once in sqlite shell run delete from WORK_QUEUE; *Run tortoise svn clean up Fix (automated) If previous step worked for you, consider automating the process with these steps * *Go to your .svn folder, e.g. C:\src\.svn *Copy sqlite3 shell tool there *Create a fix-svn.bat file in that folder *Insert scripting code, and adjust paths "C:\src\.svn\sqlite3.exe" wc.db "delete from WORK_QUEUE" "C:\Program Files\TortoiseSVN\bin\svn" cleanup "C:\src" *Save bat file and make a shortcut to your desktop *Next time you need to fix it, just run the shortcut on your desktop A: Okay, I don't know if this may be an issue. I've sen this error happen when sparse checkouts are used. You can adjust what files you see during checkouts via the --depth flag and in updates via the --set-depth flag. If you --set-depth=exclude on certain files, you will see this error if you attempt to add a file. Try this from the command line. From the ROOT of your working directory: $ svn cleanup $ svn update --set-depth=infinity $ svn status Make sure all three of these commands work. Then, try the commit. A: Update to the release candidate has solved the problem for me. A: sudo svn cleanup resolve my problem
{ "language": "en", "url": "https://stackoverflow.com/questions/18000363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: ExpressionEngine 1.6.9: displaying a weblog at all pages I'm a EE newbie. I have the code below. the poll weblog displays at search result page, but doesn't display at blog and post details page :/ what am I missing? display at search result page: www.blabla.com/search/noresults/d8ee432f229715a4adfbe1cc0d21049a/ NO display at blog pages: www.blabla.com/blog/ or www.blabla.com/blog/post/lorem_ipsum_is_simply_dummy_text/ Appreciate helps!!!! Thanks a lot! {exp:weblog:entries weblog="lg_polls"} {exp:lg_polls:poll entry_id="29" precision="1" return="/blog/"} <p>{poll_question}</p> {if can_vote} {poll_form} {if has_voted}<p>You have already voted in this poll, however you can vote again.</p>{/if} <ul class='lg-polls-answers'> {poll_answers} <li class='a-{answer_count}'> <label for='lg-polls-answer-{answer_id}'>{answer_input} <span class='answer'>{answer}</span></label> </li> {/poll_answers} </ul> <div class="alignCenter"><input type="image" src="{site_url}/images/btn_submitpoll.png" alt="Vote" /></div> {/poll_form} {if:else} {if has_voted}<p>Thanks for voting in this poll.</p>{/if} {if restricted}<p>Sorry, You are restricted from voting in this poll.</p>{/if} {if expired}<p>This poll ended on {expiration_date}.</p>{/if} {if yet_to_begin}<p>This poll is yet to begin. Voting opens on {entry_date}.</p>{/if} {/if} {if show_results} <div class='lg-poll-results' id='lg-poll-results-29'> <ul class='lg-polls-answers'> {results_answers} <li class='a-{answer_count}'> <span class='answer'>{answer}</span> <span class='answer-total-votes'>{answer_total_votes} votes &nbsp;&nbsp; <b>{answer_percentage}%</b></span> </li> {/results_answers} </ul> <div class='poll-total-votes'>Total Votes: {poll_total_votes}</div> </div> {if:else} {if show_results_after_poll && has_voted}The results of the poll will be made available on {expiration_date}{/if} {if never_show_results && has_voted}The results of this poll will be made public at a later date.{/if} {/if} {/exp:lg_polls:poll} {/exp:weblog:entries} A: I'm not 100% sure, since I haven't used LG Polls before, but try adding in dynamic="off" to your exp:weblog:entries opening tag. That will prevent EE from trying to find entries within the weblog you're calling based on the URL. See the link below: http://expressionengine.com/legacy_docs/modules/weblog/parameters.html#par_dynamic
{ "language": "en", "url": "https://stackoverflow.com/questions/3529934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If just the index.php loads as its generic unparsed self, what exactly is [not] happening? I visited a client's site today, and I'm getting the actual content of their index.php file itself rather than their website. The function of the index.php file says: This file loads and executes the parser. * Assuming this is not happening, what would be some common reasons for that? A: If the apache and php are configured correctly, so that .php files go through the php interpreter, the thing I would check is whether the php files are using short open tags "<?" instead of standard "<?php" open tags. By default newer php versions are configured to not accept short tags as this feature is deprecated now. If this is the case, look for "short_open_tag" line in php.ini and set it to "on" or, preferrably and if time allows, change the tags in the code. Although the second option is better in the long run, it can be time consumming and error-prone if done manually. I have done such a thing in the past with a site-wide find/replace operation and the general way is this. * *Find all "<?=" and replace with "~|~|~|~|" or some other unusual string that is extremely unlikely to turn up in real code. *Find all "<?php" and replace with "$#$#$#" *Find all "<?" in the site and replace with "$#$#$#" *Find all "$#$#$#" and replace with "<?php " The trailing space is advised *Find all "~|~|~|~|" and replace with "<?php echo " The trailing space is neccessary
{ "language": "en", "url": "https://stackoverflow.com/questions/7555624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the same value at multiple indexes I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output. Example index 0 = 2, index 1 = 3, index 2 = 2 Output : array 2 is found at index 0 only I break it on the loop to stop but if I did not do that, it will loop the Output Here's what I want for Output: array 2 is found at index 0,2 Code: import java.awt.*; import javax.swing.*; import java.io.*; public class Buff { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter how many index :"); int v = Integer.parseInt( in .readLine()); int x; int[] c = new int[v]; int vv; for (x = 0; x < v; x++) { System.out.print("Enter your value :"); c[x] = Integer.parseInt( in .readLine()); } System.out.print("Enter your search number :"); int xx = Integer.parseInt( in .readLine()); for (x = 0; x < v; x++) { if (c[x] == xx) { System.out.print("array " + xx + " found at index :" + x); break; } else { System.out.print("array not found"); } } } } A: The solution to to make a list of the indexes that match and populate it in your for loop. then after the for loop is done, print out the results List<Integer> foundIndexes = new ArrayList<>(); for (x = 0; x < v; x++) { if (c[x] == xx) { foundIndexes.add(x); } } //now we looped through whole array if(foundIndexes.isEmpty()){ System.out.print("array not found"); }else{ System.out.print("array " + xx + " found at index : "); for(Integer i : foundIndex){ System.out.print(i + ","); } } This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out. A: You can also use StringBuilder if all you care is to output the indexes. StringBuilder sb = new StringBuilder("array" + xx +" is found at index: "); for (x = 0; x < v; x++) { if (c[x] == xx) { sb.append(x).append(","); } } if (sb.charAt(sb.length() - 1) == ',') { sb.deleteCharAt(sb.length() - 1); System.out.println(sb); } else { System.out.println("array not found"); } A: If I understand correctly the problem is the following: You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement. Personally, what I'd do one of these two things: Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this: boolean found = false; for( x=0; x<v; x++) { if(c[x] == xx) { System.out.println("array " + xx + " found at index :"+x); found = true; } } if (found = false) { System.out.println("array not found"); } println does the same as print, only it introduces a \n at the end, so the response looks like this: array 2 found at index :0 array 2 found at index :2 Instead of: array 2 found at index :0 array 2 found at index :2 Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question. Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.
{ "language": "en", "url": "https://stackoverflow.com/questions/27572128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firebase Authentication error occured I am working on firebase authentication in vuejs using firebaseui method.But i am getting this error Could not find the FirebaseUI widget element on the page. Here is my code var config = { apiKey: "some api key", authDomain: "sample-1234.firebaseapp.com", databaseURL: "https://sample-1234.firebaseio.com", projectId: "sample-1234", storageBucket: "sample-1234.appspot.com", messagingSenderId: "123456789", clientId: "2565985323215244u7hf3lc6k.apps.googleusercontent.com" }; var app = firebase.initializeApp(config); var auth = app.auth(); var uiConfig = { signInSuccessUrl: 'http://localhost:8080/', signInOptions: [{ firebase.auth.GoogleAuthProvider.PROVIDER_ID, }], tosUrl: '<your-tos-url>' }; var ui = new firebaseui.auth.AuthUI(auth); console.log(ui); ui.start('#firebaseui-auth-container', uiConfig);
{ "language": "en", "url": "https://stackoverflow.com/questions/51034604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: system.loadlibrary with libname as parameter I want to do a class that receives a libname as a parameter in constructor. Depending on that parameter different objects instanciated of this class have to load different dynamic libraries with a call to system.loadlibrary(libname). For example, object 1 loads library1 and object 2 load library 2 but the problem is both are loading the same library. Not sure is second call to loadlibrary is ignored or the second is overloading the first. Is there a way to do this? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/25662282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy columns from one excel file to another excel file sheet using python I have two excel sheets, I am trying to copy contents from one excel sheet to another using pandas. First_excel sheet - Name Class City Date Misc Misc2 Blank Col AA xxx 12 -- AA xx 32 -- BB yyyyy 54 -- BB zz 23 -- CC yy 54 -- CC ww 32 -- Second_excel sheet - Name Class Date City Tom Q,W 01-11-20 AA Jerry W 05-03-19 AA Don E,R 06-05-20 BB Rob T,Y 02-01-20 BB Mike W 05-03-18 CC Ann O,p 04-09-20 CC Final Expected Sheet - Name Class City Date Misc Misc2 Blank Col Tom Q,W AA 01-11-20 xxx 12 -- Jerry W AA 05-03-19 xx 32 -- Don E,R BB 06-05-20 yyyyy 54 -- Rob T,Y BB 02-01-20 zz 23 -- Mike W CC 05-03-18 yy 54 -- Ann O,p CC 04-09-20 ww 32 -- df1 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet1") df2 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet2") result = pd.concat([df1,df2]) This is the resultant dataframe I got Name Class City Date Misc Misc2 Blank Col 0 NaN NaN AA NaT xxx 12.0 -- 1 NaN NaN AA NaT xx 32.0 -- 2 NaN NaN BB NaT yyyyy 54.0 -- 3 NaN NaN BB NaT zz 23.0 -- 4 NaN NaN CC NaT yy 54.0 -- 5 NaN NaN CC NaT ww 32.0 -- 0 Tom Q,W AA 2020-11-01 NaN NaN NaN 1 Jerry W AA 2019-03-05 NaN NaN NaN 2 Don E,R BB 2020-05-06 NaN NaN NaN 3 Rob T,Y BB 2020-01-02 NaN NaN NaN 4 Mike W CC 2018-03-05 NaN NaN NaN 5 Ann O,p CC 2020-09-04 NaN NaN NaN My ideas was to replace NaN with actual values from df2 or second_excel in their positions. Please help me to get my expected output. A: You can use fillna to merge the two columns with same name then append the last column. First load the files: df1 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet1") df2 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet2") Fill empty columns in df1 with df2: fill = df1.fillna(df2[['Name', 'Class', 'Date']]) Then join the last column: result = teste.join(df2[['City']]) Edit Since you edited your post, just use fill = df1.fillna(df2) and it will do The output: Name Class City Date Misc Misc2 Blank Col 0 Tom Q,W AA 2020-11-01 00:00:00 xxx 12 -- 1 Jerry W AA 2019-03-05 00:00:00 xx 32 -- 2 Don E,R BB 2020-05-06 00:00:00 yyyyy 54 -- 3 Rob T,Y BB 2020-01-02 00:00:00 zz 23 -- 4 Mike W CC 2018-03-05 00:00:00 yy 54 -- 5 Ann O,p CC 2020-09-04 00:00:00 ww 32 --
{ "language": "en", "url": "https://stackoverflow.com/questions/65150103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use a file from a remote repository into my Terraform file? I have this module to provision an EC2 instance using Terraform module "EC2" { source = "../Modules/ec2" ami = "ami-xxxxxxxxxxxxx" instance_type = "t2.micro" userdata_1 = file("C:/Users/My_User/Documents/terraform/Modules/ec2/userdata_1.sh") } To test locally, I use File Function to call my userdata_1.sh from the directory where the EC2 resources are. I want now, push my terraform to GitHub, create a pipeline in Jenkins to use the terraform as CI/CD template and so on. It will fail once I test the pipeline in anywhere I would like to run the jenkins because it won't find my local directory. I tried to short the path to be something like file("/terraform/Modules/ec2/userdata_1.sh") but I got an error testing locally: Invalid value for "path" parameter: no file exists at terraform\Modules\ec2\userdata_1.sh; this function works only with files that are distributed as part of the configuration source code, so if this file will be created by a resource in this configuration you must instead obtain this result from an attribute of that resource. When I clone the repo I got the .sh script in the directory of the module. Is there a way I can specify on that file path to use a path from a remote repository or use a default directory from a linux filesystem? A: As outlined in the terraform documentation: Filesystem and Workspace Info: path.module is the filesystem path of the module where the expression is placed. path.root is the filesystem path of the root module of the configuration. path.cwd is the filesystem path of the current working directory. In normal use of Terraform this is the same as path.root, but some advanced uses of Terraform run it from a directory other than the root module directory, causing these paths to be different. Or in your case, as you need to give a relative path try something like this: module "EC2" { source = "../Modules/ec2" ami = "ami-xxxxxxxxxxxxx" instance_type = "t2.micro" userdata_1 = file("${path.module}/Modules/ec2/userdata_1.sh") }
{ "language": "en", "url": "https://stackoverflow.com/questions/66092211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ip camera using ffmpeg drawing on screen I'm using ffmpeg 1.2 to take video from ip camera.I make it draw on the screen, so I wonder if there is some event mechanism to to know if it is time to call av_read_frame? If I read frame not so frequent as the camera gives frames i get segmentation fault = on some malloc functions inside ffmpeg routines(video_get_buffer) I also get segmentation fault just when drawing on screen. In Render function call every 0 miliseconds void BasicGLPane::DrawNextFrame() { int f=1; while(av_read_frame(pFormatCtx, &packet)>=0) { // Is this a packet from the video stream? if(packet.stream_index==videoStream) { // Decode video frame avcodec_decode_video2(pCodecCtx, pFrame, &FrameFinished, &packet); // Did we get a video frame? if(FrameFinished) { f++; this->fram->Clear(); // if (pFrame->pict_type == AV_PICTURE_TYPE_I) wxMessageBox("I cadr"); if (pFrame->pict_type != AV_PICTURE_TYPE_I) printMVMatrix(f, pFrame, pCodecCtx); pFrameRGB->linesize[0]= pCodecCtx->width*3; // in case of rgb4 one plane sws_scale(swsContext, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize); //glGenTextures(1, &VideoTexture); if ((*current_Vtex)==VideoTexture) current_Vtex = &VideoTexture2;else current_Vtex = &VideoTexture; glBindTexture(GL_TEXTURE_2D, (*current_Vtex)); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, pCodecCtx->width, pCodecCtx->height, GL_RGB, GL_UNSIGNED_BYTE, pFrameRGB->data[0]); //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pCodecCtx->width, pCodecCtx->height, 0, GL_RGB, GL_UNSIGNED_BYTE, pFrameRGB->data[0]); //glDeleteTextures(1, &VideoTexture); GLenum err; while ((err = glGetError()) != GL_NO_ERROR) { cerr << "OpenGL error: " << err << endl; } // av_free(buffer); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); if (f>1) break; } //av_free(pFrameRGB); } The picture I get on the screen is strange (green quads and red lines are motion vectors of those quads) http://i.stack.imgur.com/9HJ9t.png A: If you hang on the video device, you should read frames as soon as camera has them; you should either query the camera hardware for supported FPS, or get this information from the codec. If no information is available, you have to guess. It is suspicious that you get a crash when you don't read the frame in time; the worst which should happen in this case would be a lost frame. Depending on the camera colorspace you may also need to convert it before showing it on a screen. I don't see you doing that.
{ "language": "en", "url": "https://stackoverflow.com/questions/22189938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: packing a php self contained executable with my application I am building a mac application using Xojo framework, the app i am building have to run php as a command line, i could use the php that ships with mac osx however i need a php with mcrypt extension, and the one built into the osx does not have the mcrypt and i don't want to force my customers to update their php, so the optimal solution that i could think of, is to pack a php self contained executable with my application is this possible? and how to go for it? A: Yes, sounds possible. In the Xojo IDE you could insert a Copy Files build step after the OS X build that copies your php executable into the resources folder of your built app. Then in your App.Open you could copy that executable to wherever you want to from that SpecialFolder, or just reference it as is in your command lines depending on whether there are any restrictions imposed on how your are distributing the app (i.e. App Store). Check out http://docs.xojo.com/index.php/SpecialFolder for some guidance on where to copy any files you need to bundle or how to reference them.
{ "language": "en", "url": "https://stackoverflow.com/questions/24719408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does std::count return a signed integer? I was really surprised to see that std::count returned a iterator_traits<InputIterator>::difference_type, which in turns refers to a long int on my platform. Why is that? A negative count elements within a container doesn’t make any sense. A: It's actually a std::ptrdiff_t, which has to be a signed integer. It has to be signed because it can be used as the difference between two iterators, and that can of course be negative.
{ "language": "en", "url": "https://stackoverflow.com/questions/14811606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do you reference 3rd party react components in a Rails app? I'm building an app using the react-rails gem. This means all assets flow through the rails asset pipeline. In order to access 3rd party javascript libraries, I've been taking advantage of rails-assets.org which bundles javascript packages from bower into your rails environment. Most packages can just be called directly in your javascript code. So if you add package, take marked the markdown library, you include it like: gem 'rails-assets-marked', source: 'https://rails-assets.org' And then can easily call it from any js file in your rails app like: console.log(marked('I am using __markdown__.')); However, how do you use packages which are not functions but instead are react components? In a node app, you'd use require() like below. Here's an example with react-clipboard: var Clipboard = require("react-clipboard"); var App = React.createClass({ render: function() { return ( <div> <Clipboard value='some value' onCopy={some function} /> </div> ); }, But, what do you do to accomplish this in a Rails app? Even though the package is included in the rails asset pipeline, the react component Clipboard isn't available in JSX. How does one make it available? A: There is no way to accomplish this directly using rails only. To be able to use require("react-clipboard"), one solution (the less intrusive) would be to use a combination of rails, react-rails and browserify as explained here: http://collectiveidea.com/blog/archives/2016/04/13/rails-react-npm-without-the-pain/ and here https://gist.github.com/oelmekki/c78cfc8ed1bba0da8cee I did not re paste the whole code example as it is rather long and prone to changes in the future
{ "language": "en", "url": "https://stackoverflow.com/questions/39156365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }