text
stringlengths
15
59.8k
meta
dict
Q: Memory Problem when creating large Access reports We are having a problem. We have a complex Access 2003 application. When our main user is trying to create a particularly long report he getting a message “2004 - There isn't enough memory to perform this operation. Close unneeded programs and try the operation again”. The problem is the rest of us are able to run the same report fine. Our user is able to run the same report ok with fewer amounts of data. We looked at the obvious things such as the amount of memory on his machine and the disk space available. That seems to be ok compared to those of are able to run ok. The failure occurs when he tries to write the report to a word file. He is able to create the report when he writes directly to a printer, but since the report is so long what we do is to write the output to a pdf file. The report runs 4500 pages. These are oversize pages meaning that the data would be truncated if you use a normal size printer and page. I have search the internet but none of the suggestions seem to work for us. Any suggestions you have will be appreciated. Bob Avallone A: Do you have graphics on the report? Even a small one on the page header? If so don't use the format event to fill the graphic. Or change the grapic to a BMP.
{ "language": "en", "url": "https://stackoverflow.com/questions/4199360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: service / subscription manager engine Is there a good opensource service/subscription manager engine that contains things like service dependencies (i.e. if I choose service A, I also need Service B and Service C), subscription types, start and termination etc... I'm building a site that sells various services and subscriptions and would prefer not to have to write that code as I'm pretty sure it's been done many times over (e.g. in e-commerce sw), but I'd prefer a small library / egine instead of having to integrate with an e-shop. A: If your "Service" is just Java classes/package/modules then you can use Spring or any other DI container that supports lifecycle hookups. If by "Service" you mean something big/bloated/enterprise you can also look into OSGI. But for a small/library engine I suggest you look at plexus and picocontainer.
{ "language": "en", "url": "https://stackoverflow.com/questions/1439641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I grab the AR1 estimate and its SE from the gls function in R? I am attempting to get the lag one autocorrelation estimates from the gls function (package {nlme}) with its SE. This is being done on a non-stationary univariate time series. Here is the output: Generalized least squares fit by REML Model: y ~ year Data: tempdata AIC BIC logLik 51.28921 54.37957 -21.64461 Correlation Structure: AR(1) Formula: ~1 Parameter estimate(s): Phi 0.9699799 Coefficients: Value Std.Error t-value p-value (Intercept) -1.1952639 3.318268 -0.3602072 0.7234 year -0.2055264 0.183759 -1.1184567 0.2799 Correlation: (Intr) year -0.36 Standardized residuals: Min Q1 Med Q3 Max -0.12504485 -0.06476076 0.13948378 0.51581993 0.66030397 Residual standard error: 3.473776 Degrees of freedom: 18 total; 16 residual The phi coefficient seemed promising since it was under the correlation structure in the output Correlation Structure: AR(1) Formula: ~1 Parameter estimate(s): Phi 0.9699799 but it regularly goes over one, which is not possible for correlation. Then there is the Correlation: (Intr) Yearctr -0.36 but I was advised that this was likely not a correct estimate for the data (there were multiple test sites so this is just one of the unexpected estimates). Is there a function that outputs an AR1 estimate and its SE (other than arima)? sample of autocorrelated data: set.seed(29) y = diffinv(rnorm(500)) x = 1:length(y) gls(y~x, correlation=corAR1(form=~1)) Note: I am comparing the function arima() to gls() (or another method) to compare AR1 estimates and SE's. I am doing this under adviser request.
{ "language": "en", "url": "https://stackoverflow.com/questions/39781945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Editing repeating table INfoPath Form in form library? I created repeating table and I added two fields in it.while publishing its not giving me option to edit those properties in my document library...when we generally publish we get the option to edit those properties in document library but its disable while creating repeating table any suggestions how to do that? A: Check the box to enable editing in SP during your form publish.
{ "language": "en", "url": "https://stackoverflow.com/questions/2580692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot link to libclang in OSX High Sierra I have installed llvm and clang through brew. When I compile a program with the header file "clang-c/Index.h", I get Undefined symbols for architecture x86_64: "_clang_createIndex", referenced from: _main in t-c9baef.o .... Here is the command I used for compiling my program: CXX=/usr/local/opt/llvm/bin/clang++ CPPFLAGS=-I/usr/local/opt/llvm/include make prog I am using OSX High Sierra. A: I have managed to fix the issue. The command I used for building is: CXX=/usr/local/opt/llvm/bin/clang++ \ LDFLAGS+='-L/usr/local/opt/llvm/lib \ -L/usr/local/Cellar/llvm/5.0.1/lib -lclang' \ CPPFLAGS=-I/usr/local/opt/llvm/include \ make myprog I had to link against the libclang.dylib and add -lclang
{ "language": "en", "url": "https://stackoverflow.com/questions/48538296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: checkbox onchange not working What am I missing. None of these checkboxes, when checked or unchecked, produces any messages, even if I just past this into a clean html file. It also doesn't work even in an html file where everything else is working fine in terms of the javascript. Here is the form declaration: <form> <input type="checkbox" name="all" id="all" onChange="alert('hi')"> <input type="checkbox" name="all" id="all" onClick="alert('hi')"> <input type="checkbox" name="all" id="all" onClick="javascript: alert('hi')"> <input type="checkbox" name="all" id="all" onclick="alert('hi')"> </form> None of these work. I also tried radiobuttons, which also don't work. What gives? A: Check if you have JavaScript disabled in your browser, running this example on jsFiddle does output the alert messages: To enable JavaScript in Chrome * *Click the Chrome menu in the top right hand corner of your browser. *Select Settings *Click Show advanced settings *Under the "Privacy" section, click the Content settings button. *In the "Javascript" section, select "Allow all sites to run JavaScript (recommended)" To enable JavaScript in Firefox Click the Tools drop-down menu and select Options. Check the boxes next to Block pop-up windows, Load images automatically, and Enable JavaScript. Refresh your browser by right-clicking anywhere on the page and selecting Reload, or by using the Reload button in the toolbar. As the poster mentioned above, if you have any other scripts running somewhere they might be throwing up errors and has nothing to do with JavaScript being disabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/28333442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Material properties databases (BRDF) I am working on a new Ray Tracing project which has to provide highly realistic simulation. I have a problem with calculating reflection on target. I wanted to use the BRDF (bidirectional reflectance distribution function) model which gives information about diffuse and specular reflection to calculate how much energy was reflected from the target What I wanted to ask: * *I was wondering if there are any databases with measurements of BRDF for different materials (including incoming light direction and outgoing direction) and for different wavelengths of the light source (the most interesting for me is the laser source 800-1600nm)? *The second thing, do you know any good databases with material properties like: ambient, diffuse, specular, shininess and roughness of surface values. What I've already found: http://www.merl.com/brdf/ https://globe3d.sourceforge.io/g3d_html/gl-materials__ads.htm http://www.cs.columbia.edu/CAVE/software/curet/ https://github.com/POV-Ray/povray/tree/master/distribution/include But if I understand correctly all of them used a lamp as a light source and I don't see any references to the wavelengths of the light source. Moreover, there aren't any good values of material properties. I am quite new in this so if you have any advice or I wrote something wrong, I will be grateful for any correction and information connecting with this topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/58918939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bitrate by default for Audio Recording with MediaRecorder With java class MediaRecorder, you can record audio with encoder AMR NB (4.75 to 12.2 kbps sampled @ 8kHz) I developed an app for a mobile with Android 2.2 and the bit rate used was 12.2 kbps by default, but I installed the same apk in a mobile with Android 2.3.3 and I think that bit rate changed to 4.75 kbps by default. Is it normal? The mobile used is Nexus One. The codec lines for this issue are: mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mrecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); I tried to force MediaRecorder to use a specific bitrate with setAudioEncodingBitRate(int bitRate) but it didn´t work. I don´t understand why bitrate has decreased. A: setAudioEncodingBitRate(int bitRate) is not decreased, it is working since API 8 (2.2), and some encoding formats and frequencies, like AAC 44,1KHz, only since API 10 (2.3.3) :(
{ "language": "en", "url": "https://stackoverflow.com/questions/5821526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to define records count to a table that updated only when the table is updated * *I want to defint a view (or something else) that will save a static variable of the table count. I want this variable to be update only when the table is updated, this way each time I call the view it will not calculate the count, just return the value. in the past someone told me that "select count_bit(Id) from table1" will do the job. is it right? * *I want to use the variable in mvc site using entity-framework . How do I do it? A: Create a separate table to store the count value. Create insert, update and delete triggers for table1, which calculates the new count and updates the count value. But do you really need to do this? Are you having performance problems with select count(*) from table1? You know, triggers will slow down all update, delete and inserts a bit. A: Just use a Select Count to the table ,even if you select just a column and count that for your rows or select the the whole table to count the complete table data...put your count expression after your update is done .
{ "language": "en", "url": "https://stackoverflow.com/questions/25010023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why isn't xsl:for-each select="" working with this xml file? I am trying to display an xml file with an xsl stylesheet. I just canNOT seem to get it to work. The feed I'm using is this: http://screamingdeals.tdn.travelscream.com/atom.xml Here is an abbreviated copy of the xml for it: <feed xmlns="http://www.w3.org/2005/Atom" xmlns:ts="http://www.travelscream.com"> <title type="text">Travelscream Deal Alerts</title> <updated>2012-08-08T11:09:44-06:00</updated> <id>http://screamingdeals.tdn.travelscream.com/</id> <link rel="alternate" type="text/html" hreflang="en" href="http://screamingdeals.tdn.travelscream.com"/> <link rel="self" type="application/atom+xml" href="http://screamingdeals.tdn.travelscream.com/atom.xml"/> <generator uri="http://screamingdeals.tdn.travelscream.com" version="1.0">screamingdeals.tdn.travelscream.com</generator> <entry> <title>New York City: Best Western President Hotel - $152</title> <link rel="alternate" type="text/html" href="http://screamingdeals.tdn.travelscream.com/a477908344.htm"/> <id>http://screamingdeals.tdn.travelscream.com/a477908344.htm</id> <updated>2012-08-08T11:09:44-06:00</updated> <published>2012-08-08T00:00:00-06:00</published> <author> <name>screamingdeals.tdn.travelscream.com</name> <uri>http://screamingdeals.tdn.travelscream.com</uri> </author> <content type="html" xml:base="screamingdeals.tdn.travelscream.com" xml:lang="en"> &lt;table&gt; &lt;tr&gt; &lt;td valign="middle"&gt; &lt;img width="80" width="60" src="http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg"&gt; &lt;/td&gt; &lt;td valign="top"&gt; $152/night &amp; up - Best Western President Hotel (New York City, NY) - 46% Off Travel Dates: Through Dec 31, 2012 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </content> <ts:data> <ts:primarykey>477908344</ts:primarykey> <ts:location_data> <ts:location id="50" selected="0" airport_codes="EWR,JFK,LGA" type="dest">New York</ts:location> <ts:location id="55" selected="1" airport_codes="EWR,JFK,LGA" type="dest">New York City</ts:location> <ts:location id="199" selected="0" airport_codes="" type="dest">United States</ts:location> <ts:location id="288" selected="0" airport_codes="" type="dest">North America</ts:location> <ts:location id="524" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Manhattan</ts:location> <ts:location id="525" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Bronx</ts:location> <ts:location id="526" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Brooklyn</ts:location> <ts:location id="527" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Queens</ts:location> <ts:location id="528" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Staten Island</ts:location> <ts:location id="613" selected="0" airport_codes="" type="dest">SoHo</ts:location> </ts:location_data> <ts:pkg_attributes> <ts:attribute id="3" type="TYPE">Honeymoon</ts:attribute> <ts:attribute id="40" type="MAIN">Hotel</ts:attribute> <ts:attribute id="62" type="DTYP">City</ts:attribute> </ts:pkg_attributes> <ts:deal_expires>2012-09-07T14:54:05-06:00</ts:deal_expires> <ts:deal_supplier>DealBase.com</ts:deal_supplier> <ts:feed_image>http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg</ts:feed_image> <ts:fullscreen_image/> <ts:price1>15200</ts:price1> <ts:alpha>0</ts:alpha> <ts:coord> <ts:lat>40.7606</ts:lat> <ts:long>-73.9864</ts:long> <ts:latlong>40.7606,-73.9864</ts:latlong> </ts:coord> <ts:desc>$152/night &amp; up - Best Western President Hotel (New York City, NY) - 46% Off Travel Dates: Through Dec 31, 2012</ts:desc> <ts:tacomm/> <ts:direct>true</ts:direct> <ts:top>false</ts:top> <ts:traveldates> <ts:from>01/01/2050</ts:from> <ts:to>01/01/2050</ts:to> </ts:traveldates> </ts:data> </entry> </feed> the php page that loads up the stylesheet and tells it to transform the xml is coded thusly: $xp = new XsltProcessor(); // create a DOM document and load the XSL stylesheet $xsl = new DomDocument; $xsl->load('deals_stylesheet.xsl'); // import the XSL styelsheet into the XSLT process $xp->importStylesheet($xsl); // create a DOM document and load the XML datat $xml_doc = new DomDocument; $xml_doc->load('http://screamingdeals.tdn.travelscream.com/atom.xml'); // transform the XML into HTML using the XSL file if ($html = $xp->transformToXML($xml_doc)) { echo $html; } else { trigger_error('XSL transformation failed.', E_USER_ERROR); } // if So far...so good. I'm not getting an error. Here is the xsl file contents: <?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Facebook Deals Page</title> <style type="text/css"> <![CDATA[ <!-- --> ]]> </style> </head> <body> <table border="1"> <tr> <td><b>Title</b></td> <td><b>ID</b></td> </tr> <xsl:for-each select="feed/entry"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="id"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> And here is a display of it not working: http://www.margaretpickarddesign.com/clients/travelscream/facebook_deals/facebook_rss.php Looking at the xml structure, the node "feed" is followed by node "entry" which has child nodes "title" and "id". So why isn't it working? What am I missing? A: Adding comment as an actual answer... The ts prefixed namespace isn't the problem because you're not accessing any elements in that namespace. The problem is the default namespace (the xmlns with no prefix). What you need to do is add xmlns:a="http://www.w3.org/2005/Atom" to xsl:stylesheet and use that prefix in your selects. (select="a:feed/a:entry", select="a:title", and select="a:id") Also note that you can use any prefix, not just "a". The only thing that has to be the same is the namespace itself (http://www.w3.org/2005/Atom).
{ "language": "en", "url": "https://stackoverflow.com/questions/11870687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: typeof operator on Folder returns error In a google apps script function, I have a Folder parameter. So, this statement Logger.log(typeof folder); logs 'undefined' when the parameter is not supplied, which is right. But when a folder is supplied, I get this error: Invalid JavaScript value of type $Proxy686. (line 15) Not able to diagnose why. Need some help. Thanks. Sanjay Update: Here is the code reproducing the issue: function typeOfTest() { var folders = DocsList.getAllFolders(); for (var i = 0; i < folders.length; i++) Logger.log(typeof folders[i]); }; A: In fact. I have the same behavior. I don't know either it is a bug or a feature. A possible workaround is to use the Folder's toString() function. Something like function typeOfTest() { var folders = DocsList.getAllFolders(); for (var i = 0; i < folders.length; i++) Logger.log(folders[i].toString()); };
{ "language": "en", "url": "https://stackoverflow.com/questions/11609275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there any way to add a custom library to jre there are some codes that I use very often in my programs and its kind of annoying to add it to my program every time I'm wondering if there is any way to solve this problem like adding
{ "language": "en", "url": "https://stackoverflow.com/questions/72109917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AttributeError: 'NoneType' object has no attribute 'da' I am calling another program(script2.py) from the script1.py. The script1.py contains a button when i press it, it will start to execute the script2.py. I want to use a variable of script1 in script2. I have tried 2 way to fetch it but giving the error or the empty list. Please help me with this and let me know if any other information is needed. Thank you. script1.py class window2: #i have tried to use d but even the value changes in the __init__function it is giving me a empty list in script2 print function d=[] def __init__(data): self.data=data window2.d=data data_copy() def data_copy(): #so created this function to fetch da but giving the following error da=window2.d script2.py from script1 import data_copy from script1 import window2 def view(): print(window2.d) #giving empty list print(data_copy().da) #giving error Error for data_copy: Traceback (most recent call last): File "C:\Users\Desktop\Status\script2.py", line 59, in <module> view() File "C:\Users\Desktop\Status\script2.py", line 13, in view print(data_copy().da) AttributeError: 'NoneType' object has no attribute 'da' A: A common reason you have NoneType where you don't expect it is the assignment of an in-place operation on a mutable object. For example: mylist = mylist.sort() The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1), Python will give you this error. A: You can try to create a function in the second script which takes your data as an argument and call it in the first script. from script2 import view class Window2: def __init__(self, data): # init should take self, it is an instance of class self.data = data window_2 = Window2('some data') # creating instance view(window_2.data) # call function from script2 # script2 def view(data): print(data) # > 'some data'
{ "language": "en", "url": "https://stackoverflow.com/questions/63788965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python urllib2 does not respect timeout The following two lines of code hangs forever: import urllib2 urllib2.urlopen('https://www.5giay.vn/', timeout=5) This is with python2.7, and I have no http_proxy or any other env variables set. Any other website works fine. I can also wget the site without any issue. What could be the issue? A: If you run import urllib2 url = 'https://www.5giay.vn/' urllib2.urlopen(url, timeout=1.0) wait for a few seconds, and then use C-c to interrupt the program, you'll see File "/usr/lib/python2.7/ssl.py", line 260, in read return self._sslobj.read(len) KeyboardInterrupt This shows that the program is hanging on self._sslobj.read(len). SSL timeouts raise socket.timeout. You can control the delay before socket.timeout is raised by calling socket.setdefaulttimeout(1.0). For example, import urllib2 import socket socket.setdefaulttimeout(1.0) url = 'https://www.5giay.vn/' try: urllib2.urlopen(url, timeout=1.0) except IOError as err: print('timeout') % time script.py timeout real 0m3.629s user 0m0.020s sys 0m0.024s Note that the requests module succeeds here although urllib2 did not: import requests r = requests.get('https://www.5giay.vn/') How to enforce a timeout on the entire function call: socket.setdefaulttimeout only affects how long Python waits before an exception is raised if the server has not issued a response. Neither it nor urlopen(..., timeout=...) enforce a time limit on the entire function call. To do that, you could use eventlets, as shown here. If you don't want to install eventlets, you could use multiprocessing from the standard library; though this solution will not scale as well as an asynchronous solution such as the one eventlets provides. import urllib2 import socket import multiprocessing as mp def timeout(t, cmd, *args, **kwds): pool = mp.Pool(processes=1) result = pool.apply_async(cmd, args=args, kwds=kwds) try: retval = result.get(timeout=t) except mp.TimeoutError as err: pool.terminate() pool.join() raise else: return retval def open(url): response = urllib2.urlopen(url) print(response) url = 'https://www.5giay.vn/' try: timeout(5, open, url) except mp.TimeoutError as err: print('timeout') Running this will either succeed or timeout in about 5 seconds of wall clock time.
{ "language": "en", "url": "https://stackoverflow.com/questions/27327787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: I'm trying to automatically reload a div after some seconds but it doesn't work in Chrome Here is the Main code. Please check it. what is making this conflict. <script type="text/javascript"> $(document).ready(function () { setInterval(function() { $.get("ajax_files/manage_friend_requests.php", function (result) { $('#all_friends_requests').html(result); // This is the div i am reloading again and again after some seconds. }); }, 9000); }); </script> A: You should be safer with something like this: $(document).ready(function(){ setInterval(function(){ $.ajax({ type: "GET", url: "ajax_files/manage_friend_requests.php" }).done(function(result) { var $friends_requests = $('#all_friends_requests'); if ($friends_requests.length > 0) { console.log('Received: '+result); $friends_requests.html(result); console.log('UPDATED friends requests'); } else { console.log('CANNOT access friends requests container'); } }); }, 9000); }); Depending on what the console will display, you will probably put the issue in evidence.
{ "language": "en", "url": "https://stackoverflow.com/questions/18185947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to submit dropzone js form and django form with one submit button I am using dropzone js to make a form where users can upload information along side images. Dropzone js requires that dropzone has a form with a class of dropzone for the drag and drop image uploads to work, this now leaves me with two forms. The first is the normal input form and the second is the dropzone js form. My question is how can I submit both the dropzone js form and the normal input form with one submit button. Please note I am using html forms, not django crispy forms. <form method="POST" enctype="multipart/form-data" id="inputform" name="form1"> {% csrf_token %} <button type="submit" id="add">Save</button> </form> <div class="col-sm-12 col-lg-6" id="inner"> <form method="POST" enctype="multipart/form-data" id="inputform" name="form1"> {% csrf_token %} <h4>Title</h4> <input type="text" name="product_title" id="product_title" placeholder="Give your product a name"> <h4>Price</h4> <input type="text" name="product_price" id="product_price" placeholder="0.00"> <h4>Description</h4> <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product"> </form> </div> <div class="col-sm-12 col-lg-6" id="inner2"> <h3>Images</h3> <form method="POST" action="#" class="dropzone col-sm-8 col-lg-8" id="dropzone" name="form2"> {% csrf_token %} </form> </div> def add(request): if request.method == "POST": title = request.POST.get("product_title") price = request.POST.get("product_price") description = request.POST.get("product_description") print(title,price,description) return render(request,"main/add.html") A: You don't need separate form for dropzone. Use first form and give it class name dropzone. <form method="POST" enctype="multipart/form-data" id="inputform" name="form1" class="dropzone"> {% csrf_token %} <h4>Title</h4> <input type="text" name="product_title" id="product_title" placeholder="Give your product a name"> <h4>Price</h4> <input type="text" name="product_price" id="product_price" placeholder="0.00"> <h4>Description</h4> <input type="text" name="product_description" id="product_description" placeholder="Write a description about your product"> <button type="submit" id="add">Save</button> </form> PS. In order to submit files you need to have <input type="file" name="file" /> in your form.
{ "language": "en", "url": "https://stackoverflow.com/questions/54652835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automate a user assignment to a specific app role within an application I'm automating an app setup and having registered an applicatioin with az ad app create --app-roles with the manifest: [{ "allowedMemberTypes": [ "User", "Application" ], "description": "Read items", "displayName": "Reader", "isEnabled": "true", "value": "items/r" }] I'm trying to figure a way to assign above mentioned Reader to a principal without PowerShell's New-AzureADUserAppRoleAssignment and coming up empty. I'd take ARM template, .NET SDK or az CLI way of doing it, but none seem to support it. Not interested in the portal/ui as I'm trying to script this, any ideas? A: Just use az cli rest to assign a custom app role to a principal via Azure AD Graph Rest API : az rest --method post --uri "https://graph.windows.net/<your tenant ID>/servicePrincipals/<your principle object Id>/appRoleAssignments?api-version=1.6" --body "{\"id\":\"<your custom role app ID>\",\"principalId\":\"<your principle object Id>\",\"resourceId\":\"<your app object id>\"}" --headers "Authorization=Bearer <access token>" You can get access token via az account get access token : az account get-access-token --resource "https://graph.windows.net" Test request on Azure cli : Result, as you can see the role has been assigned to principle successfully :
{ "language": "en", "url": "https://stackoverflow.com/questions/58868505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating a Sum with case sensitive Picture of the table { "_id" : ObjectId("62f6e11df737d6c2b49b9b9f"), "_ID" : 345, "name" : "Ron", "age" : 25, "city" : "Holon", "Number_Days_booked" : 2 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba0"), "_ID" : 459, "name" : "Ifat", "age" : 25, "city" : "Holon", "Number_Days_booked" : 4 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba1"), "_ID" : 789, "name" : "Oren", "age" : 26, "city" : "ramla", "Number_Days_booked" : 3 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba2"), "_ID" : 324, "name" : "Gali", "age" : 28, "city" : "Ramla", "Number_Days_booked" : 5 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba3"), "_ID" : 123, "name" : "Adi", "age" : 34, "city" : "Tel_aviv", "Number_Days_booked" : 3 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba4"), "_ID" : 456, "name" : "Dan", "age" : 36, "city" : "tel_aviv", "Number_Days_booked" : 4 } { "_id" : ObjectId("62f6e11df737d6c2b49b9ba5"), "_ID" : 678, "name" : "Ronht", "age" : 39, "city" : "Holon", "Number_Days_booked" : 6 } I am trying to calculate the Sum of Number_days_booked only for Tel Aviv, but I have case sensitivity issue. I have tried so far -> db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } }) But that produces the sum of all cities and I want to represent only Tel Aviv, how can I do so? A: db.Customers.aggregate({ $group: { "_id": { $toLower: "$city" }, "count": { $sum: "$Number_Days_booked" } } }, {$match:{_id:"tel_aviv"}}) matching at the end did the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/73341866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can't make an onClick with Zepto Hello I have a simple HTML page like this: <html> <head> </head> <body> <h1>Test page</h1> <script type="text/javascript" src="script.js"></script> <script type="text/javascript"> app.init([ "param", "123456789" ]); app.execute(); app.edit(); </script> </body> </html> The content of script.js is the following: // Zepto include ... // My code var app = app || (function(){ var _args = {}; return { init : function(Args) { _args = Args; }, execute : function() { ... }, edit: function() { $('body').on('click', function(e){ alert('aa'); }); }, }; }()); My problem is with this instruction $('body').on('click', function(e){. I do not understand why. It do not work. Anyone to help me ?
{ "language": "en", "url": "https://stackoverflow.com/questions/32567356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract a meta tag from XML/HTML using Linq? I am trying to parse a bit of data from an HTML file, but my Linq statement is not working. Here is the XML/HTML. Below, how can I extract the string "41.8;12.23" from the geo.position meta tag? Thx!! Here is my Linq String longLat = (String) from el in xdoc.Descendants() where (string)el.Name.LocalName == "meta" & el.FirstAttribute.Name == "geo.position" select (String) el.LastAttribute.Value; Here is my Xdocument <span> <!--CTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="application/xhtml+xml; charset=utf-8" http-equiv="Content-Type" /> <meta content="text/css" http-equiv="Content-Style-Type" /> <meta name="geo.position" content="41.8;12.23" /> <meta name="geo.placename" content="RomeFiumicino, Italy" /> <title>RomeFiumicino, Italy</title> </head> <body /> </html> </span> Edit: My query as given returns nothing. The "inner" query seems to return a list of all the meta elements instead of just the one element I want. Edit: The following Linq query works against the same XDocument to retreive a table with class name = "data" var dataTable = from el in xdoc.Descendants() where (string)el.Attribute("class") == "data" select el; A: A span around your html tag? You could do this with XLinq, but it would only support well-formed XML. You might want to look at the HTML Agility Pack instead. Edit - This works for me: string xml = "..."; var geoPosition = XElement.Parse(xml).Descendants(). Where(e => e.Name.LocalName == "meta" && e.Attribute("name") != null && e.Attribute("name").Value == "geo.position"). Select(e => e.Attribute("content").Value). SingleOrDefault(); A: I'd bet that the problem you're having comes from not referencing the namespace correctly with an XmlNamespaceManager. Here are two ways to do it: string xml = @"<span> <!--CTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt --> <html xmlns=""http://www.w3.org/1999/xhtml""> <head> <meta content=""application/xhtml+xml; charset=utf-8"" http-equiv=""Content-Type"" /> <meta content=""text/css"" http-equiv=""Content-Style-Type"" /> <meta name=""geo.position"" content=""41.8;12.23"" /> <meta name=""geo.placename"" content=""RomeFiumicino, Italy"" /> <title>RomeFiumicino, Italy</title> </head> <body /> </html> </span>"; string ns = "http://www.w3.org/1999/xhtml"; XmlNamespaceManager nsm; // pre-Linq: XmlDocument d = new XmlDocument(); d.LoadXml(xml); nsm = new XmlNamespaceManager(d.NameTable); nsm.AddNamespace("h", ns); Console.WriteLine(d.SelectSingleNode( "/span/h:html/h:head/h:meta[@name='geo.position']/@content", nsm).Value); // Linq - note that you have to create an XmlReader so that you can // use its NameTable in creating the XmlNamespaceManager: XmlReader xr = XmlReader.Create(new StringReader(xml)); XDocument xd = XDocument.Load(xr); nsm = new XmlNamespaceManager(xr.NameTable); nsm.AddNamespace("h", ns); Console.WriteLine( xd.XPathSelectElement("/span/h:html/h:head/h:meta[@name='geo.position']", nsm) .Attribute("content").Value); A: I agree with Thorarin - use the HTML Agility pack, it's much more robust. However, I suspect the problem you are having using LinqToXML is because of the namespace. See MSDN here for how to handle them in your queries. " If you have XML that is in a default namespace, you still must declare an XNamespace variable, and combine it with the local name to make a qualified name to be used in the query. One of the most common problems when querying XML trees is that if the XML tree has a default namespace, the developer sometimes writes the query as though the XML were not in a namespace."
{ "language": "en", "url": "https://stackoverflow.com/questions/1313529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Property Names of MultiDimensional array I am new to JS. Programmatically I need to find propery names of multidimensional array. Expected Output - ["name", "position", "salary", etc.] When I am using map I am getting values of "name" data.map(item => item.name). var data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" }] A: Using Object#keys: const getPropertyNames = (arr = []) => arr.length > 0 ? Object.keys(arr[0]) : []; const data = [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "320800", "start_date": "2011\/04\/25", "office": "Edinburgh", "rating": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "170750", "start_date": "2011\/07\/25", "office": "Tokyo", "rating": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "86000", "start_date": "2009\/01\/12", "office": "San Francisco", "rating": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "433060", "start_date": "2012\/03\/29", "office": "Edinburgh", "rating": "6224" } ]; console.log( getPropertyNames(data) );
{ "language": "en", "url": "https://stackoverflow.com/questions/71008093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error occurred while trying to connect to db in aws I deployed war file to aws which is spring project. and I installed oracle rds on aws. When I try to connect to oracle rds on aws from my local computer with root-context.xml. It worked. It can connect to oracle rds on aws from my local computer with my spring project. But when I try to run spring war file on aws. http://ip address:8080 it gives me an error message. Would you please help me with this? I have been struggling with this for three days...any help would be appreciated. java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection here is the root-context.xml <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property> <property name="url" value="jdbc:log4jdbc:oracle:thin:@database ip address on aws:1521:orcl" /> <property name="username" value="id" /> <property name="password" value="password" /> </bean> aws security inbound setting: http tcp 80 0.0.0.0/0 custom tcp rule 8080 0.0.0.0/0 custom tcp rule 8080 ::/0 [database setting][1] [security group][2] [1]: https://i.stack.imgur.com/869s0.png [2]: https://i.stack.imgur.com/hqaeU.png A: After trying and trying - created another RDS DB, copying existing one, created another VPC to try it out there are few things that need to be considered (obviously, they are all documented, but it's not an easy task to find all the information, since - at least in my case - it wasn't documented in one place: * *If you want your DB instance in the VPC to be publicly accessible, you must enable the VPC attributes DNS hostnames and DNS resolution (existing VPC can be changed too). *Check the VPC security group and enable the DB access port (in case of the standard MS SQL deployment - 1433) - since starting the 2013, VPC security groups have replaced the RDS security group. *Check thoroughly the RDS DB information for Security Groups, port and other info that can be misidentified. *Somehow not obvious (at least for me at first), but when using SQL Management Studio to access the RDS DB - do not use the ":1433" or other port identifier at the end of DB instance name. *If nothing of the above works, ask the question here and keep googling... :) Most of the info found here: http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSVPC.html
{ "language": "en", "url": "https://stackoverflow.com/questions/58045540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: updating the screen during computer controlled UI changes I've checked the other questions asked here and didn't succeed in implementing the solutions. My application uses controls, not drawing on the canvas. Basically this sums up my issue: - public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn1 = (ToggleButton) findViewById(R.id.btn1); btn2 = (ToggleButton) findViewById(R.id.btn2); btn3 = (ToggleButton) findViewById(R.id.btn2); btn4 = (ToggleButton) findViewById(R.id.btn4); btn5 = (ToggleButton) findViewById(R.id.btn5); btn6 = (ToggleButton) findViewById(R.id.btn6); btn7 = (ToggleButton) findViewById(R.id.btn7); //blah blah blah btn1.requestFocus(); wait(100); btn2.requestFocus(); wait(100); btn3.requestFocus(); wait(100); btn3.setChecked(true); wait(100); btn4.requestFocus(); wait(100); btn4.setChecked(true); wait(100); btn5.requestFocus(); wait(100); btn6.requestFocus(); wait(100); btn6.setChecked(true); wait(100); btn7.requestFocus(); wait(100); //etc } The point being the computer animates the moving to a the buttons and checking them so the user can see what it is doing. So, my issue is, what goes in my wait() method that will pause for 100ms and also update the screen, and the focus? Any help really appreciated, cheers Jonathan. Solution applies, thanks Andrew :) int timerCounterInterval = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1); final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2); // more btns timerCounterInterval = 0; //reset, for each pass of automation setFocus(btn1); setFocus(btn2); setChecked(btn2); // tidy up timerCounterInterval++; new Handler().postDelayed(new Runnable() { public void run() { btn2.clearFocus(); //whatever button that had the focus last } }, 100*(timerCounterInterval)); // etc - note any code from here will execute *before* the above timer } public void setFocus(final ToggleButton btn) { timerCounterInterval++; new Handler().postDelayed(new Runnable() { public void run() { btn.setFocusableInTouchMode(true); //eww, messy i know btn.requestFocus(); btn.setFocusableInTouchMode(false); } }, 100*timerCounterInterval); } public void setChecked(final ToggleButton btn) { timerCounterInterval++; new Handler().postDelayed(new Runnable() { public void run() { btn.setChecked(true); } }, 100*timerCounterInterval); } Hope this helps other people! A: I highly suggest you look into the Handle object and in particular the postDelayed method. That way you can keep everything on the UI thread while not causing the thread to actually be tied up in an animate method. This also keeps the Activity from giving that dreaded this-application-is-not-responding message. In fact, simply wrapping your calls to the control's setters in a runnable and passing them to postDelayed should be enough to update the GUI controls. [Update] As an example per your comments you might try something like this. I haven't actually tested this but I think the idea is still there... public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ToggleButton btn1 = (ToggleButton) findViewById(R.id.btn1); final ToggleButton btn2 = (ToggleButton) findViewById(R.id.btn2); // more btns Handler handler = new Handler(); /* tell the handler run these bits after 1 sec, 2 sec, 3 sec, ect... */ handler.postDelayed(new Runnable() { void run () { btn1.requestFocus(); } }, 1000); handler.postDelayed(new Runnable() { void run () { btn2.requestFocus(); } }, 2000); handler.postDelayed(new Runnable() { void run () { btn2.setChecked(true); } }, 3000); }
{ "language": "en", "url": "https://stackoverflow.com/questions/4351154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a notify email with file attatchment , whenever we place new file in shared location? I will explain my requirement here. We have shared location in Network(like http://emea.com/ABC/Files), Every month some other team folks will place some excel sheet in that location. we manully check that location and pick up that file. Requirement is :- whenever A new file will place in that location we need to get email automatically with the latest file attached. How can i achieve this in java , or do we have any open source tools for this , Please share your thoughts on this :)
{ "language": "en", "url": "https://stackoverflow.com/questions/44963443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Play Framework 2.2 log output to console in tests How do I configure the logger in Play Framework 2.2 in order that I see log output in the console during play integration tests? The configuration for Play Framework 2.1 does not work anymore. BR Rene A: Update To understand more about how logback is configured you should pass -Dlogback.debug=true property to the jvm/play. This might save you hours of debbugging. Add a file in test/logback-test.xml (needs to be on classpath so it might depend on how the play application is configured to find tests resources) with a content like <configuration> <conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${application.home:-.}/logs/application.log</file> <encoder> <pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern> </encoder> </appender> <logger name="play" level="INFO" /> <logger name="application" level="INFO" /> <root level="ERROR"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root> </configuration> A: I have not done this yet, but you have to configure a logback configuration file. See the play documentation for additional information: http://www.playframework.com/documentation/2.2.x/SettingsLogger Once you defined a specific logback configuration file, this needs to be placed in the test package, see this issue for details:https://github.com/playframework/playframework/issues/1669#issuecomment-24452132 See message from @benmccann: you can configure the logger in test mode by placing a logback-test.xml in test/resources (took me hours to figure out!).
{ "language": "en", "url": "https://stackoverflow.com/questions/18999294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to write multiple ArrayList in a text file In below code , i'm trying to create a txt file and there i want to add some list of values. So here my approach is create a new file if file is not present and add the respective elements into it. Please see below , i'm unable to get my expected output, So can you help me with some idea so it will be very helpful public class MyTest { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub SftpConn sftp = new SftpConn(); //sftp.sftpGetConnect(); List<String> list = new ArrayList<>(); list.add("AAAA"); list.add("BBBB"); list.add("CCCC"); sftp.writeIntoText(list); List<String> list1 = new ArrayList<>(); list1.add("AAAA1111"); list1.add("BBBB2222"); list1.add("CCCC2222"); sftp.writeIntoText(list1); } } public class SftpConn { public void writeIntoText(List<String> result) throws Exception { connect(); List<String> resultdata= result; System.out.println("Result Updated"); channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); fileOutStream = channelSftp.put("/home/dasrsoum/RM.txt"); PrintWriter writer = new PrintWriter(fileOutStream,true); writer.println("------------------"); for (String value : resultdata) { writer.println(value+ System.lineSeparator()); System.out.println(value); } writer.close(); } Actual output AAAA1111 BBBB2222 CCCC2222 Excepted OutPut AAAA BBBB CCCC AAAA1111 BBBB2222 CCCC2222 A: You first file is overwritten by the second call to the function
{ "language": "en", "url": "https://stackoverflow.com/questions/63048653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is there a list of all possible fields for sorting in WooCommerce? I see that it is possible to add your custom field for sorting products in WooCommerce (e.g. this question) Copying from the example: add_filter( 'woocommerce_get_catalog_ordering_args', 'enable_catalog_ordering_by_modified_date' ); function enable_catalog_ordering_by_modified_date( $args ) { if ( isset( $_GET['orderby'] ) ) { if ( 'modified_date' == $_GET['orderby'] ) { return array( 'orderby' => 'modified', //This is the custom field to be sorted by, and what I am asking for 'order' => 'DESC', ); } } return $args; } Is there a list of all fields that I can use for sorting? P.S. Thanks for the comment, but what I need is not sorting normal posts in WordPress, but the products in WooCommerce. A: These are the default list of orderby options available( id, title, relevance, rand, date, price, popularity, rating). The case of the switch case may be what you are looking for. switch ( $orderby ) { case 'id': $args['orderby'] = 'ID'; break; case 'menu_order': $args['orderby'] = 'menu_order title'; break; case 'title': $args['orderby'] = 'title'; $args['order'] = ( 'DESC' === $order ) ? 'DESC' : 'ASC'; break; case 'relevance': $args['orderby'] = 'relevance'; $args['order'] = 'DESC'; break; case 'rand': $args['orderby'] = 'rand'; // @codingStandardsIgnoreLine break; case 'date': $args['orderby'] = 'date ID'; $args['order'] = ( 'ASC' === $order ) ? 'ASC' : 'DESC'; break; case 'price': $callback = 'DESC' === $order ? 'order_by_price_desc_post_clauses' : 'order_by_price_asc_post_clauses'; add_filter( 'posts_clauses', array( $this, $callback ) ); break; case 'popularity': add_filter( 'posts_clauses', array( $this, 'order_by_popularity_post_clauses' ) ); break; case 'rating': add_filter( 'posts_clauses', array( $this, 'order_by_rating_post_clauses' ) ); break; } The above code is from woocommerce/includes/class-wc-query.php line 586... A: You need to know what is inside of an product object. You can sort your products by any of this product data. Here is a list I found where you can access all the data inside of a product object. (source: https://wpdavies.dev/how-to-get-all-product-info-in-woocommerce/) <?php /** * * General Product Data * */ $product->get_id(); // Returns the unique ID for this object. $product->get_description(); // Get product description. $product->get_formatted_name(); // Get product name with SKU or ID. Used within admin. $product->get_featured(); // If the product is featured. $product->get_name(); // Get product name. $product->get_title(); // Get the product's title. For products this is the product name. $product->get_type(); // Get internal type. Should return string and *should be overridden* by child classes. $product->get_virtual(); // Get virtual. $product->get_total_sales(); // Get number total of sales. $product->get_short_description(); // Get product short description. $product->get_sku(); // Get SKU (Stock-keeping unit) - product unique ID. $product->get_slug(); // Get product slug. $product->get_status(); // Get product status. $product->get_permalink(); // Product permalink. $product->get_catalog_visibility(); // Get catalog visibility. /** * * Pricing Data * */ $product->get_price(); // Returns the product's active price. $product->get_date_on_sale_from(); // Get date on sale from. $product->get_date_on_sale_to(); // Get date on sale to. $product->get_display_price(); // Returns the price including or excluding tax, based on the 'woocommerce_tax_display_shop' setting. $product->get_price_excluding_tax(); // Returns the price (excluding tax) - ignores tax_class filters since the price may *include* tax and thus needs subtracting. $product->get_price_html(); // Returns the price in html format. $product->get_price_html_from_text(); // Functions for getting parts of a price, in html, used by $product->get_price_html. $product->get_price_html_from_to(); // Functions for getting parts of a price, in html, used by $product->get_price_html. $product->get_price_including_tax(); // Returns the price (including tax). Uses customer tax rates. Can work for a specific $qty for more accurate taxes. $product->get_price_suffix(); // Get the suffix to display after prices > 0. $product->get_sale_price(); // Returns the product's sale price. $product->get_regular_price(); // Returns the product's regular price. $product->get_tax_class(); // Returns the tax class. $product->get_tax_status(); // Returns the tax status. /** * * Image Related Data * */ $product->get_image(); // Returns the main product image. $product->get_image_id(); // Get main image ID. $product->get_gallery_attachment_ids(); // Returns the gallery attachment ids. $product->get_gallery_image_ids(); // Returns the gallery attachment ids. /** * * Stock or Inventory Data * */ $product->get_backorders(); // Get backorders. $product->get_availability(); // Returns the availability of the product. $product->get_max_purchase_quantity(); // Get max quantity which can be purchased at once. $product->get_min_purchase_quantity(); // Get min quantity which can be purchased at once. $product->get_stock_managed_by_id(); // If the stock level comes from another product ID, this should be modified. $product->get_stock_quantity(); // Returns number of items available for sale. $product->get_stock_status(); // Return the stock status. $product->get_total_stock(); // Get total stock - This is the stock of parent and children combined. $product->get_sold_individually(); // Return if should be sold individually. $product->get_low_stock_amount(); // Get low stock amount. /** * * Shipping Data * */ $product->get_height(); // Returns the product height. $product->get_length(); // Returns the product length. $product->get_weight(); // Returns the product's weight. $product->get_width(); // Returns the product width. $product->get_dimensions(); // Returns formatted dimensions. $product->get_manage_stock(); // Return if product manage stock. $product->get_shipping_class(); // Returns the product shipping class SLUG. $product->get_shipping_class_id(); // Get shipping class ID. /** * * Product Variations / Parent Data * */ $product->get_child(); // Returns the child product. $product->get_children(); // Returns the children IDs if applicable. Overridden by child classes. $product->get_formatted_variation_attributes(); // Get formatted variation data with WC < 2.4 back compat and proper formatting of text-based attribute names. $product->get_matching_variation(); // Match a variation to a given set of attributes using a WP_Query. $product->get_parent(); // Get the parent of the post. $product->get_parent_id(); // Get parent ID. $product->get_variation_default_attributes(); // If set, get the default attributes for a variable product. $product->get_variation_description(); // Get product variation description. $product->get_variation_id(); // Get variation ID. /** * * Product Downloads * */ $product->get_download_expiry(); // Get download expiry. $product->get_download_limit(); // Get download limit. $product->get_downloadable(); // Get downloadable. $product->get_downloads(); // Get downloads. $product->get_file(); // Get a file by $download_id. $product->get_file_download_path(); // Get file download path identified by $download_id. $product->get_files(); // Same as $product->get_downloads in CRUD. /** * * Attributes, Tags, Categories & Associated Data Objects * */ $product->get_attribute(); // Returns a single product attribute as a string. $product->get_attributes(); // Returns product attributes. $product->get_categories(); // Returns the product categories. $product->get_category_ids(); // Get category ids. $product->get_default_attributes(); // Get default attributes. $product->get_cross_sell_ids(); // Get cross sell IDs. $product->get_cross_sells(); // Returns the cross sell product ids. $product->get_related(); // Get and return related products. $product->get_tag_ids(); // Get tag ids. $product->get_tags(); // Returns the product tags. $product->get_upsell_ids(); // Get upsell IDs. $product->get_upsells(); // Returns the upsell product ids. $product->get_meta(); // Get Meta Data by Key. $product->get_meta_data(); // Get All Meta Data. /** * * Ratings and Reviews * */ $product->get_rating_count(); // Get the total amount (COUNT) of ratings, or just the count for one rating e.g. number of 5 star ratings. $product->get_rating_counts(); // Get rating count. $product->get_rating_html(); // Returns the product rating in html format. $product->get_review_count(); // Get review count. $product->get_reviews_allowed(); // Return if reviews is allowed. $product->get_average_rating(); // Get average rating. /** * * Other Product Data * */ $product->get_changes(); // Return data changes only. $product->get_data(); // Returns all data for this object. $product->get_data_keys(); // Returns array of expected data keys for this object. $product->get_data_store(); // Get the data store. $product->get_date_created(); // Get product created date. $product->get_date_modified(); // Get product modified date. $product->get_extra_data_keys(); // Returns all "extra" data keys for an object (for sub objects like product types). $product->get_menu_order(); // Get menu order. $product->get_meta_cache_key(); // Helper method to compute meta cache key. Different from WP Meta cache key in that meta data cached using this key also contains meta_id column. $product->get_object_read(); // Get object read property. $product->get_post_data(); // Get the product's post data. $product->get_post_password(); // Get post password. $product->get_purchase_note(); // Get purchase note. With this you can see under "other product data", that there is a date_modified you can order your products by. It is not directly a list of all fields you can sort by. But it indirectly shows you which fields are available inside a product and what the fields are called. With the name, you are able to access them. Custom meta: Unfortunatelly there is no data saved for "published_date". But you could create a custom field for your product post type and save the date inside product. Via the meta key you can than access the data of the product and sort your products by your custom meta data. A: If the point of the question is whether there is a list that returns all the fields that can be used for sorting, the short answer is no. The woocommerce_get_catalog_ordering_args filter allows you to add your own ordering args, but there is no list that would store these fields. This filter is used to overwrite args, not to store it as an array. Within the get_catalog_ordering_args() function, some orderby defaults are statically specified: id, menu_order, title, relevance, rand, date, price, popularity, rating. But there is no way to tell what values have been added using a filter by WordPress plugins. Possible solution: There is a woocommerce_catalog_orderby filter that stores sorting options as an array. This is used to display sorting options in the view. So you can assume that WordPress plugins will add options to this as well. /** * Add orderby option by plugin */ add_filter( 'woocommerce_catalog_orderby', function ( $options ) { $options['order_by_plugin'] = __( 'Order by plugin setting', 'text-domain' ); return $options; } ); /** * Get orderby options */ $catalog_orderby_options = apply_filters( 'woocommerce_catalog_orderby', array( 'menu_order' => __( 'Default sorting (custom ordering + name)', 'woocommerce' ), 'popularity' => __( 'Popularity (sales)', 'woocommerce' ), 'rating' => __( 'Average rating', 'woocommerce' ), 'date' => __( 'Sort by most recent', 'woocommerce' ), 'price' => __( 'Sort by price (asc)', 'woocommerce' ), 'price-desc' => __( 'Sort by price (desc)', 'woocommerce' ), ) ); You can use $catalog_orderby_options in which the sorting options are stored, if you only need the orderby fields, use the array_keys() function. Note: you must specify the default value in apply_filters(), because WooCommerce added these statically, not using add_filter(). So you have to add it statically too.
{ "language": "en", "url": "https://stackoverflow.com/questions/72520190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert database table entry to an enum? In my web application I have many tables which have fixed data, when I use them in my project then I use enums for that purpose. I want to convert these tables to enums automatically. After little looking up I did this by using T4, TextTemplates: see my code here. But I wanted to do this by using Entity Framework, according to the official documentation enums are supported in .NET Framework 4.5 and above, but I am using .NET 3.5. How can I achieve this, potentially by using custom text templates? A: So I finally solved it. Made a T4 template and replaced that with the default generated tt file. My code is here, please star it if you found it helpful and add comments in case of help or suggestions.
{ "language": "en", "url": "https://stackoverflow.com/questions/27731646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Making an image control invert its colors depending on theme I'm trying to work out how to have an Image control in my Windows Phone application invert its colors based on the global background setting (either "Dark" or "Light") chosen by the user in Settings->Themes->Background. A: There is no built-in way to invert image colors within the framework. Instead, because of the overhead of doing this on the phone, you should create both versions of the image at design/build time and then choose which version to display from your code by detecting Theme Visibility and Opacity. A: I must add that what i did in the end was a continuation of what Matt wrote. * *create two different images that have different versions of the image (dark and light) and place them in the exact same position *set their visibility based on the theme resource the code looks like this: <Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgDark" Stretch="Fill" Visibility="{StaticResource PhoneLightThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageDarkTheme.png" /> <Image Height="30" HorizontalAlignment="Center" Margin="0,0,0,220" Name="imgLoading" Stretch="Fill" Visibility="{StaticResource PhoneDarkThemeVisibility}" VerticalAlignment="Center" Width="30" Source="/MyApplication;component/imageLightTheme.png" /> A: This Question is 1.5 years old now. But here is the easiest way to do what you want. The example given there is very simple like <Button> <Image Stretch="None" Source="{Binding Converter={StaticResource ThemedImageConverter}, ConverterParameter={StaticResource PhoneBackgroundColor} }" DataContext="/WP7SampleProject4;component/Images/{0}/appbar.feature.camera.rest.png" /> </Button>
{ "language": "en", "url": "https://stackoverflow.com/questions/4656880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Calling drawnow causes heap corruption I'm still new to Matlab and Simulink and I'm seeing a strange problem. I have a series of Simulink blocks (processA, processB, etc) which are Matlab functions connected serially. They all have the same format. function outConfig = run_processA_Fcn(inConfig) coder.extrinsic('hilite_system'); hilite_system('myModel/processA'); drawnow; coder.extrinsic('run_processA_mex'); run_processA_mex(inConfig); hilite_system('myModel/processA', 'none'); drawnow; outConfig = inConfig; The function run_processA_mex() is a .mexw64 MEX function which take in pointers to the heap (via inConfig). Inside these MEX functions I am calling my Visual Studio compiled C code (within a DLL). Each Simulink block could take some time to process, so I wanted it to highlight the current block. The problem is when I call drawnow, the data from my pointers change to some invalid values. The pointers themselves point to the same address, just the values they point to are wrong. If I just comment out the drawnow, my data is okay. I'm not clear on the best way around this. I don't know why calling drawnow would corrupt my heap. Any help would be great. A: Okay, this was silly of me. The pointers I was passing were pointing to the heap but they were pointers to pointers. The final data was sitting on the stack, so I was losing that data because of the additional function calls I introduced. I've properly allocated the data onto the heap now and it seems to be working now.
{ "language": "en", "url": "https://stackoverflow.com/questions/48655761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python (+Django) : use @property in success_url KO . while using it with get_success_url is OK (class based view) I found a workaround for my issue but I need to know why the first above case doesn't work. I need to pass a parameter (reman_pk) to my view but when I try : class RepairCreateView(LoginRequiredMixin, CreateView): @property def reman_pk(self): return int(self.kwargs['reman_pk']) [...] success_url = reverse_lazy( 'reman:update-reman', kwargs={'pk': reman_pk}) [...] ... I got an error django.urls.exceptions.NoReverseMatch: Reverse for 'update-reman' with keyword arguments '{'pk': <property object at 0x10c20bbd0>}' not found. 1 pattern(s) tried: ['reman/update/(?P[0-9]+)/$'] But when in the same class based view I use : def get_success_url(self, **kwargs): if kwargs != None: return reverse_lazy('reman:update-reman', kwargs={'pk': self.reman_pk}) ... it's OK : an int is well passed in my URL. I tried to pass int(reman_pk) in the first method ... not better. I've already use @property in the past and always got a value (int/str) and not property object. EDIT (FULL views.py) success_url = reverse_lazy...is commented. I must use def get_success_url( ... instead. Otherwise I get the above mentioned error. class RepairCreateView(LoginRequiredMixin, CreateView): @property def reman_pk(self): return int(self.kwargs['reman_pk']) # success_url = reverse_lazy( # 'reman:repairs-list', kwargs={'pk': reman_pk}) success_message = "Nouvelle réparation créée" form_class = RepairCreateForm template_name = 'reman/repair_create_form.html' def get_context_data(self, *args, **kwargs): context = super(RepairCreateView, self).get_context_data( *args, **kwargs) context['title'] = 'Nouveau Repair' context['pk'] = self.reman_pk return context def get_initial(self): reman = Reman.objects.get(pk=self.reman_pk) return {'reman': reman} def get_success_url(self, **kwargs): return reverse_lazy('reman:repairs-list', kwargs={'pk': self.reman_pk}) A: This is not related to django, this is related to python in general. When you want to access a class property within the class you always have to call self before! class Tree: fruits = 5 @property def leafes(self): return self.fruits * 5 def show_tree(self): print(self.fruits) print(self.leafes) print(leafes) # THIS LINE WOULD ERROR Edit after comment of OP I don't know how to phrase this properly. Anyhow this keeps being a problem related to python and not to django. The reason is how classes work. You probably know the def __init__(self): function. That is called when the class gets instanciated. After that function got called your class can use all the self attributes (class attributes). But class attributes like my fruits = 5 get assigned even before that def __init__(self) method is called. So all your assignments directly inside the body of the class do not have self yet. class Tree: fruits = 5 def __init__(self): self.twigs = 10 self.weight = self.twigs + self.fruits # THIS WORKS class Tree: fruits = 5 weight = self.twigs + fruits # THIS DOES NOT WORK def __init__(self): self.twigs = 10 Last example does not work because at the moment you want to assign weight = self.twigs + fruits your class's __init__ function was not called yet. So you can not use self at that place.
{ "language": "en", "url": "https://stackoverflow.com/questions/75384392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto layout delayed on label I have a calculator app (just like the apple in-built calculator app) and I used auto-layout. Everything is working fine in portrait mode but when I rotate the screen to landscape the UIButtons resize according to the screen size but the UILabel that show result resizes after a delay, i.e. when I rotate the screen to landscape mode the UITextField also rotate but the size of UITextField is same as the portrait size for 2 seconds and then it resizes correctly. Is it something related to hugging priority or compression priority? The content hugging priority Horizontal - 251 Vertical - 251 Content compression resistance priority Horizontal - 750 Vertical - 750 Hope you understand the question Thanks in advance. see the second screenshot the display (i.e. the zero is not towards the margin but at the middle but after 2 seconds it sizes correctly.)
{ "language": "en", "url": "https://stackoverflow.com/questions/33008578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading SQLite data using AsyncTask , What am I doing wrong? I'm new to android and java, and I'm trying to implement an Asynchronous Loader. But no data is being loaded. Am I missing something conceptually here? My Activity: public class TestActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { ListView bookList; MyCursorAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_library); // dloader = new DBLoader(this); //dloader.loadInBackground(); /* blah blah*/ getSupportLoaderManager().initLoader(1,null,this); /* blah blah*/ View header = (View) getLayoutInflater().inflate(R.layout.row_layout_title, null); TextView totals = header.findViewById(R.id.mainText); totals.setText("Total Books: " + Integer.toString(totalBooks)); bookList.addHeaderView(header); bookList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { /* blah blah*/ } } }); /* blah blah*/ } /* blah blah*/ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { /*CursorLoader loader = new CursorLoader(this, null, null, null, null, null){ @Override public Cursor loadInBackground(){ DBHandler db = new DBHandler(getContext()); return db.getCursor(); } };*/ DBLoader loader = new DBLoader(this); return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { myAdapter = new MyCursorAdapter(this,data,0); bookList.setAdapter(myAdapter); // myAdapter.swapCursor(data); //myAdapter.notifyDataSetChanged(); } @Override public void onLoaderReset(Loader<Cursor> loader) { myAdapter.swapCursor(null); } } DBLoader: public class DBLoader extends AsyncTaskLoader<Cursor> { private Cursor mCursor; Context context; public DBLoader(Context context) { super(context); this.context = context; } @Override public Cursor loadInBackground() { DBHandler db = new DBHandler(context); Cursor cursor = db.getCursor(); return cursor; } @Override public void deliverResult(Cursor cursor){ if(isReset()){ releaseResources(cursor); return; } Cursor oldCursor = mCursor; mCursor = cursor; if(isStarted()){ super.deliverResult(cursor); } if(oldCursor!=null && oldCursor!=cursor){ releaseResources(oldCursor); } } private void releaseResources(Cursor cursor) { cursor.close(); } } I don't know if I'm missing any important calls here, and most resources on the internet are about content providers(which I don't need). What I simply need is to asynchronously load data from my local SQLite database. EDIT: My Adapter: public class MyCursorAdapter extends CursorAdapter { private LayoutInflater cursorInflater; public MyCursorAdapter(Context context, Cursor c, int flags) { super(context, c, flags); cursorInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return cursorInflater.inflate(R.layout.row_layout, parent, false); } @Override public void bindView(View v, Context context, Cursor cursor) { Log.d("Cursor :", cursor.getString(1)); TextView title = (TextView) v.findViewById(R.id.listTitle); title.setText(cursor.getString(1)); TextView author = (TextView) v.findViewById(R.id.listAuthor); author.setText(cursor.getString(2)); TextView copies = (TextView) v.findViewById(R.id.listCopies); copies.setText(cursor.getString(5)); } } A: Declare your DBLoader loader as global variable at the onCreateLoader loader = new DBLoader(this); return loader; put this at the onCreate method instead of onLoadFinished myAdapter = new MyCursorAdapter(this,null,0); bookList.setAdapter(myAdapter); put this at onLoadFinishied this.loader=(DBLoader)loader; adapter.changeCursor(cursor); A: After some searching, I saw a few examples on the internet where they use a getSupportLoaderManager().initLoader(1,null,this).forceLoad();. That seems to work. also calling loader.forceLoad() in the onCreateLoader() works too. On further checking, I saw this : https://issuetracker.google.com/issues/36925900 It seems we have to implement forceLoad in onStartLoading() as thus: protected void onStartLoading() { if (mCursor != null) { deliverResult(mCursor); } if (takeContentChanged() || mCursor == null) { forceLoad(); } } doing this will cease the need for a .forceLoad() in our Activity
{ "language": "en", "url": "https://stackoverflow.com/questions/45233875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bookmarklet, js injection and popup issue I'm currently writing a bookmarklet that loads and executes a remote js file by appending a new <script> tag in the current window, like so : javascript:(function() { if(typeof __bml_main != "undefined") return __bml_main.init(); var s= document.createElement('script'); s.type= 'text/javascript'; s.src= 'http://127.0.0.1:8000/media/bookmarklet.js'; void(document.body.appendChild(s)); })(); My bookmarklet needs to perform some dom manipulations in order to extract data from the page being viewed, and then to open a new popup to list them. The thing is : if I want to bypass pop-up blockers, I can't open my new window from the injected script. I need to open it right from the beginning in the bookmarklet code, and to access it later when needed. I've tried to do somehting like this : javascript:var my_popup = window.open('http://127.0.0.1:8000/resources/manage/new/', 'newResourcePopup',config='height=200,width=400,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no'); (function() { // script injection (...) })(); but if I then try to access my_popup from my remotely loaded script, most browsers will throw a security warning and won't let me access the Window object. This is understandable since the script is not from the same domain than the displayed page, but I'm kind of stuck... A solution would be to use a div overlay, but I'd really prefer to open a window in this case. Any hints ? A: You could load the markup for the window as a string in your bookmarklet.js file, then (later) use window.open without a URL (or with "about:blank", I forget which is more cross-browser-compatible), and use my_popup.document.write to write the markup to the new window. You may find that you can't open the window later, even without cross-domain issues, unless you're doing so in direct response to a user action — which is probably a good thing. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/2994187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: In Python 2, what are the performance trade-offs for viewvalues()/viewitems() over itervalues()/iteritems()? Obviously, using values, items, and keys is bad practice in Python 2.X in virtually every instance, because you'll allocate an extra list you don't actually need. Thus, for some time, the recommended best practice was to use iteritems/itervalues, and to use the built-in __iter__ if you wanted to enumerate the dict's keys. With the backport of Python 3's keys, values, and items to Python 2.7 as viewkeys, viewvalues, and viewitems, I'm wondering what the actual performance tradeoffs are of the view* family of functions, vs. their iter* counterparts. Is the only reason to continue using the iter* functions that you are targeting Python 2.6 and earlier, or can the older iter* methods be faster than the newer view* methods in certain contexts? A: Here's an answer addressing iterkeys vs. viewkeys here: https://stackoverflow.com/a/10190228/344143 Summary (with a little backstory): view* methods are a live view into the data (that will update as it updates), whereas iter* and just-plain * are more like snapshots. The linked answerer suggests that while the view*-flavored methods may have a minor performance edge as well, there may be compatibility issues with the backport, and recommends continuing to use iter*/* under Python 2. My take: if you want a live view and you're under Python 2, use view*; if you just want to whip through the set of keys/values/items once, use iter*; if you want to hang on to a snapshot of k/v/i for a bit (or iterate in some non-linear fashion), use *. Let the performance slide until you pick it up in an inner loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/21783763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: can we use js variable name as class name in html I want to concatinate class name with variable count which keep getting updated after each button click, for which I am getting error as "citysName is null". can anyone suggest button.addEventListener('click', resp => { count = count +1; var card = document.createElement('card'); card.innerHTML = ` <img src="..." class="card-img-top" alt="..."> <div class="card-body"> **<h5 class="card_title" + count></h5> <h6 class="temp" + count></h6> <p class="card-text" + count></p>** <a href="#" class="btn-primary"></a> </div> `; card.className = 'card'; var content = document.getElementById('id1'); content.appendChild(card); **var citysName = document.querySelector('.card_title'+count); var description = document.querySelector('.card-text'+count); var temp = document.querySelector('.temp'+count);** fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc') .then(post => post.json()) .then(data => { var cityName = data['name']; var temper = data['main']['temp']; var descrip = data['weather'][0]['description']; let ctemp = Math.round(temper-273); citysName.innerHTML = cityName; temp.innerHTML = ctemp + "°C"; description.innerHTML = descrip; }) }) A: First of all thats not how you add variables using template literals you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals Second why do you query it again when you've just made the element you can use card as reference and if you need something within it, its much easier to access it using the variable you already have other than looking for it in your document Maybe something like this but its hard to tell withouth more code etc button.addEventListener('click', resp => { count = count +1; var card = document.createElement('card'); card.innerHTML = ` <img src="..." class="card-img-top" alt="..."> <div class="card-body"> **<h5 class="card_title${count}"></h5> <h6 class="temp${count}"></h6> <p class="card-text${count}"></p>** <a href="#" class="btn-primary"></a> </div> `; card.className = 'card'; var content = document.getElementById('id1'); content.appendChild(card); var citysName = card.querySelector('.card_title'+count); var description = card.querySelector('.card-text'+count); var temp = card.querySelector('.temp'+count); fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc') .then(post => post.json()) .then(data => { var cityName = data['name']; var temper = data['main']['temp']; var descrip = data['weather'][0]['description']; let ctemp = Math.round(temper-273); citysName.innerHTML = cityName; temp.innerHTML = ctemp + "°C"; description.innerHTML = descrip; }) })
{ "language": "en", "url": "https://stackoverflow.com/questions/70728977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Excel DNA with ILNumerics I have used ILNumerics via Excel DNA in Excel successfully for some time. Now I wrote a new function which uses the linsolve function from ILNumerics (which needs the mkl_custom.dll) and I cannot build this into an XLL. My custom function works in debug which is why I assume sth in the packaging goes wrong. Here is my dna file: <DnaLibrary Name="Nik's Lib" RuntimeVersion="v4.0"> <ExternalLibrary Path="MyLib2010.dll" Pack="true"/> <Reference Path="ILNumerics.dll" Pack="true"/> <Reference Path="mkl_custom.dll" Pack="true"/> </DnaLibrary> When packaging this I get the error message that path for mkl_custom.dll path not found This might be due to the folder structure of the dll: Any pointers on how to resolve this would be appreciated. A: The Excel-DNA packing does not currently support native or mixed assemblies. So you won't be able to use the mechanism to pack the mkl library. You might be able to store it in your C# assembly as a resource, and extract it yourself at runtime (in an AutoOpen or something, before any of the functions using it are run). If you extract it to a temp file, then call LoadLibrary yourself to load it into the process, it should work when ILNumerics needs it.
{ "language": "en", "url": "https://stackoverflow.com/questions/30863959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I write float value in python that can be read natively in Java? How can I write float value to file in python so that it can be later read in Java with ObjectInputStream#readFloat? I need high read performance, so I'd like to avoid parsing the float from String. A: Use the struct module (documentation), specifying the data as a float.
{ "language": "en", "url": "https://stackoverflow.com/questions/8630341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Earth Engine How to Create a CNN Model for a Multi-class Image Classification I am trying to build a satellite image classifier CNN using Google Earth Engine. I have been stuck on this problem for almost a week now and any help would be greatly appreciated. I have been following this tutorial: https://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/UNET_regression_demo.ipynb#scrollTo=CTS7_ZzPDhhg I am using 6 input bands (3RGB, 3IR) and 1 band for labels. By using neighbourhoodToArray() function, I construct a 256 x 256 rectangle so I can use it in a CNN classifier. KERNEL_SIZE = 256 featureStack = ee.Image.cat([ l8_image.select(BANDS), aafc_image.select(LABEL) ]).float() list = ee.List.repeat(1, KERNEL_SIZE) lists = ee.List.repeat(list, KERNEL_SIZE) kernel = ee.Kernel.fixed(KERNEL_SIZE, KERNEL_SIZE, lists) arrays = featureStack.neighborhoodToArray(kernel) n = 200 # Number of shards in the polygon. N = 2000 # Total sample size in the polygon. # Export all the training data (in many pieces), with one task # per geometry. training = ee.FeatureCollection([]) for i in range(n): sample = arrays.sample( region = BOUNDED_AREA, scale = 30, numPixels = N / n, # Size of the shard. seed = i, # random sample location seed tileScale = 8 ) training = training.merge(sample) And then I export this to Drive and then get it back in a TFRecord format. But, when I get the data in a TFRecord format, the input is of shape (256, 256, 7) so I divide it into training and labels such that training is of shape (256, 256, 6) and labels is of shape (256, 256, 1). But the thing here is that, I want my output node in the model to be a one-hot encoded vector that uses categorical cross entropy loss. But since my labels are in the shape of (256, 256, 1), I can't have it because the labels should have a form of (N_CLASSES,). To be more clear, my model should be in the form of: model2 = tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(256, 256, 6)), tf.keras.layers.Conv2D(256, (3,3), padding='same', activation=tf.nn.relu), #4d tf.keras.layers.Conv2D(128, (3, 3), padding='same', activation=tf.nn.relu), # 4D tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu), # 4D tf.keras.layers.Flatten(), # 1D tf.keras.layers.Dense(256, activation=tf.nn.relu), # 1D tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(N_CLASSES, activation=tf.nn.softmax) # (72,) ]) # Compile the model with the specified loss function. model2.compile(optimizer=tf.keras.optimizers.Adam(), loss='categorical_crossentropy', metrics=['accuracy']) history2 = model2.fit(x=training, epochs=5) I have tried def to_tuple(inputs): """Function to convert a dictionary of tensors to a tuple of (inputs, outputs). Turn the tensors returned by parse_tfrecord into a stack in HWC shape. Args: inputs: A dictionary of tensors, keyed by feature name. Returns: A tuple of (inputs, outputs). """ inputsList = [inputs.get(key) for key in FEATURE_NAMES] stacked = tf.stack(inputsList, axis=0) # for Conv2D, input should be (BATCH, HEIGHT, WIDTH, CHANNEL) # Convert from CHW to HWC - meaning channel-height-width to height-width-channel stacked = tf.transpose(stacked, [1, 2, 0]) labels = stacked[:, :, len(BANDS):] # first one is inputs (first 6 bands), second is only the last band - label reshaped_labels = tf.reshape(tf.cast(labels, tf.int32), [KERNEL_SIZE * KERNEL_SIZE]) return stacked[:,:,:len(BANDS)], tf.one_hot(indices=reshaped_labels, depth=N_CLASSES) # depth makes the 2nd dimension 72 By doing so my labels is of shape (256*256, 72), but still not exactly what I want. If there is a CNN classification tutorial I can follow (not UNET or regression), that information is also greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/71368962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: springframework.integration.kafka ConsumerContext Iterator is in failed state When trying to consume a topic on my java application I get the following exception: org.springframework.integration.kafka.support.ConsumerConfiguration.executeTasks(ConsumerConfiguration.java:135) ... 32 more Caused by: java.lang.IllegalStateException: Iterator is in failed state at kafka.utils.IteratorTemplate.hasNext(IteratorTemplate.scala:54) at kafka.utils.IteratorTemplate.next(IteratorTemplate.scala:38) at kafka.consumer.ConsumerIterator.next(ConsumerIterator.scala:46) at org.springframework.integration.kafka.support.ConsumerConfiguration$1.call(ConsumerConfiguration.java:104) at org.springframework.integration.kafka.support.ConsumerConfiguration$1.call(ConsumerConfiguration.java:98) at java.util.concurrent.FutureTask.run(FutureTask.java:266) ... 3 more This exception happens after a while when processing a lot of messages. And always happens on the same topic. The configuration of the kafka consumer is: <int-kafka:zookeeper-connect id="zookeeperConnect" zk-connect="${kafkaZookeeperUrl}" zk-connection-timeout="${kafkaZkConnectionTimeout}" zk-session-timeout="${kafkaZkSessionTimeout}" zk-sync-time="${kafkaZkSyncTime}" /> <!-- --> <!-- Spring Integration --> <!-- --> <bean id="consumerProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="auto.commit.enable">${kafkaConsumerAutoCommitEnable}</prop> <prop key="auto.commit.interval.ms">${kafkaConsumerAutoCommitInterval}</prop> <prop key="fetch.min.bytes">${kafkaConsumerFetchMinBytes}</prop> <prop key="fetch.wait.max.ms">${kafkaConsumerFetchWaitMax}</prop> <prop key="auto.offset.reset">${kafkaConsumerOffsetReset}</prop> </props> </property> </bean> <!-- --> <!-- Channels --> <!-- --> <int:channel id="kafka1"> <int:interceptors> <int:wire-tap channel="kafkaWiretap" /> </int:interceptors> </int:channel> <!-- --> <!-- Consumer Contexts --> <!-- --> <int-kafka:consumer-context id="consumerContext1" consumer-timeout="${kafkaDataInTimeout}" zookeeper-connect="zookeeperConnect" consumer-properties="consumerProperties"> <int-kafka:consumer-configurations> <int-kafka:consumer-configuration group-id="dataWriterSource" value-decoder="valueDecoder" key-decoder="valueDecoder" max-messages="${kafkaDataInMaxMessages}"> <int-kafka:topic id="DATA_IN" streams="${kafkaDataInStreams}" /> </int-kafka:consumer-configuration> </int-kafka:consumer-configurations> </int-kafka:consumer-context> <!-- --> <!-- Inbound Channel Adapters --> <!-- --> <int-kafka:inbound-channel-adapter id="kafkaInboundChannelAdapter1" kafka-consumer-context-ref="consumerContext1" auto-startup="${kafkaConsumerChannelAutoStartup}" channel="kafka1"> <int:poller fixed-delay="10" time-unit="MILLISECONDS" max-messages-per-poll="1000" /> </int-kafka:inbound-channel-adapter> The topic has 600 partitions and it receives a lot of messages. The configuration of the context consumer is: #################################### # KAFKA Consumers Configuration. #################################### # General consumer properties kafkaConsumerAutoCommitEnable=true kafkaConsumerAutoCommitInterval=500 kafkaConsumerFetchMinBytes=1 kafkaConsumerFetchWaitMax=100 kafkaConsumerOffsetReset=largest # Consumers # Data In kafkaDataInTimeout=500 kafkaDataInMaxMessages=5000 kafkaDataInStreams=4 Now as far as I can check, there is some kind of a problem, either with how I have configured the poller for the consumer or there is a bug in the following piece of code on the ConsumerContext.java: private Map<String, Map<Integer, List<Object>>> executeTasks( final List<Callable<List<MessageAndMetadata<K, V>>>> tasks) { final Map<String, Map<Integer, List<Object>>> messages = new ConcurrentHashMap<String, Map<Integer, List<Object>>>(); messages.putAll(getLeftOverMessageMap()); try { for (final Future<List<MessageAndMetadata<K, V>>> result : this.executorService.invokeAll(tasks)) { if (!result.get().isEmpty()) { final String topic = result.get().get(0).topic(); if (!messages.containsKey(topic)) { messages.put(topic, getPayload(result.get())); } else { final Map<Integer, List<Object>> existingPayloadMap = messages.get(topic); getPayload(result.get(), existingPayloadMap); } } } public ConsumerMetadata<K, V> getConsumerMetadata() { return consumerMetadata; } public Map<String, Map<Integer, List<Object>>> receive() { count = messageLeftOverTracker.getCurrentCount(); final Object lock = new Object(); final List<Callable<List<MessageAndMetadata<K, V>>>> tasks = new LinkedList<Callable<List<MessageAndMetadata<K, V>>>>(); for (final List<KafkaStream<K, V>> streams : createConsumerMessageStreams()) { for (final KafkaStream<K, V> stream : streams) { tasks.add(new Callable<List<MessageAndMetadata<K, V>>>() { @Override public List<MessageAndMetadata<K, V>> call() throws Exception { final List<MessageAndMetadata<K, V>> rawMessages = new ArrayList<MessageAndMetadata<K, V>>(); try { while (count < maxMessages) { final MessageAndMetadata<K, V> messageAndMetadata = stream.iterator().next(); synchronized (lock) { if (count < maxMessages) { rawMessages.add(messageAndMetadata); count++; } else { messageLeftOverTracker.addMessageAndMetadata(messageAndMetadata); } } } } catch (ConsumerTimeoutException cte) { LOGGER.debug("Consumer timed out"); } return rawMessages; } }); } } return executeTasks(tasks); } The line 104 is final MessageAndMetadata messageAndMetadata = stream.iterator().next(); not synch and may get into conflict with the line 135: if (!result.get().isEmpty()) { Any help from the spring integration kafka people will be really great. The question is: What is going on and how can we solve the issue. Thanks in advance, Francisco
{ "language": "en", "url": "https://stackoverflow.com/questions/32139124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Node.js module: export async function In the given example it is demonstrated, how to export a variable, or a function from a custom module. How could one export an asynchronous function in a similar manner and then call it from app.js something like: // app.js var things = require("./someThings"); await things.getSomeThingsAsync(); EDIT: The example (answer on Stackoverflow) pointed to by the above link contains the following code: // someThings.js (function() { var someThings = ...; ... module.exports.getSomeThings = function() { return someThings(); } }()); // main.js var things = require("someThings"); ... doSomething(things.getSomeThings()); Say inside of the module's incapsulated function a asynchronous function exists, which you would like to expose to whoever imports the module. For example: (function() { ... const doSomethingAsync = (time) => { return new Promise(resolve => { setTimeout(() => resolve(42), time) }) } //const doSomething = async () => { async function doSomething () { let answer1 = await doSomethingAsync(3000) let answer2 = await doSomethingAsync(1000) return answer1 + answer2 } ... /*module.exports.doSomething = function() { return doSomething(); }*/ module.exports.doSomething = async function() { return doSomething(); } }()); How would you expose the doSomething function in similar fashion as the in the original answer it is done for someThings - how can the referred to answer be changed in such a way, that when exporting functions, it lets you use the await keyword? It will then be used as: // app.js var things = require("./someThings"); console.log(await things.doSomething()); I have tried multiple approaches, but I always get: SyntaxError: await is only valid in async function A: You can try this : //yourModule.js let yourModule={}; yourModule.you=async()=>{ //something await... } modules.export = yourModule; //app.js let yourModule = require('<pathToModule>'); async function test() { await yourModule.you(); //your `await` here } A: You are misunderstanding the error. It says SyntaxError: await is only valid in async function not "for async function" There is no problem with your export. It is simply not possible to use await outside of a function marked async. Therefore the bug is in app.js. It should be: var things = require("./someThings"); async function app () { console.log(await things.doSomething()); } app().then(() => console.log('done calling app()')); A: This is probably a duplicate of this question. You can simply assign the function (or a function expression) to a property (or just the entirety) of `module.exports’. For example: async function AsyncStuff () { ... } module.exports.myAsyncThing = myAsyncStuff; A: Try this var things = require("./someThings"); let result = getResult(); async function getResult() { return await things.getSomeThingsAsync(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/56592352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Move last item in flexbox to new line when items take up different width .main{ display:flex; border: 1px solid black; } .item, .item2, .item3, .item4{ padding: 10px; } .item { flex-grow: 1; flex-wrap: wrap; } .item2{ flex-grow: 7; background-color: pink; } .item3 { flex-grow: 2; background-color: yellow; } <div class="main"> <div class="item">1</div> <div class="item2">2</div> <div class="item3">3</div> <div class="item4">4</div> </div> In the above scenario, how can I move item 4 into a new line? All the examples I've seen, it's possible when the items are of the same width. A: You need to activate the wrap on the parent element (the flex container) then make the element full width: .main{ display:flex; border: 1px solid black; flex-wrap:wrap; } .item, .item2, .item3, .item4{ padding: 10px; } .item { flex-grow: 1; } .item2{ flex-grow: 7; background-color: pink; } .item3 { flex-grow: 2; background-color: yellow; } .item4 { flex-basis:100%; } <div class="main"> <div class="item">1</div> <div class="item2">2</div> <div class="item3">3</div> <div class="item4">4</div> </div> A: Use .item-groups to organize your .items by row. Example: * { box-sizing: border-box; margin: 0; padding: 0; } .main { display: flex; border: 1px solid black; flex-wrap: wrap; } .item-group { flex-basis: 100%; display: flex; } .item1, .item2, .item3, .item4 { padding: 10px; } .item1 { flex-grow: 1; } .item2{ flex-grow: 7; background-color: pink; } .item3 { flex-grow: 2; background-color: yellow; } .item4 { background-color: violet; } <div class="main"> <div class="item-group"> <div class="item1">1</div> <div class="item2">2</div> <div class="item3">3</div> </div> <div class="item-group"> <div class="item4">4</div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/51489582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Server "An invalid floating point operation occurred" This is not really a problem because I solved it. But, I wanted to share something that ate my brain today. So, run this query and check it out: The query: select 2 as ID1,0 as ID2 into #TEMP insert into #TEMP (ID1,ID2) values (2,1),(2,2),(2,0) select case when min(case when ID1=2 and ID2=0 then 0 else 1 end)=0 then 0 else sum(log(ID2)) end from #TEMP The fix: select case when min(case when ID1=2 and ID2=0 then 0 else 1 end)=0 then 0 else sum(log(case when ID1=2 and ID2<>0 then ID2 else 1 end)) end from #TEMP My query was larger and more difficult to debug, but what do you say about the plan that MSSQL is making and the fact that it gets it wrong with this query? How can it be modified to work except my little fix that I showed before? I am guessing that computing scalars before the query would make things slow if the scalars are not easy to compute and we compute for all values. A: SQL Server does not perform short circuit evaluation (i.e. should not be relied upon). It's a fairly well known problem. Ref: * *Don’t depend on expression short circuiting in T-SQL (not even with CASE) *Short Circuit *Short-Circuit Evaluation *Is the SQL WHERE clause short-circuit evaluated? A: EDIT: I misunderstood the question with my original answer. I supposed you could add a where clause, as shown below. Side note: this query might benefit from an index on (ID1, ID2). select sum(log(convert(float, ID2))) from #TEMP where -- exclude all records with ID1 = 2 if there are any records with ID1 = 2 and ID2 = 0 not exists ( select 1 from #TEMP NoZeros where NoZeros.ID1 = #TEMP.ID1 and NoZeros.ID2 = 0 ) Update: Just in case performance is a concern, I got fairly comparable performance from this query after adding the following indexes: create index ix_TEMP_ID1_ID2 on #TEMP (ID1, ID2) create index ix_TEMP_ID2 on #TEMP (ID2) include (ID1) Original Answer How about modifying your sum function as shown below? sum(case ID2 when 0 then null else log(convert(float, ID2)) end)
{ "language": "en", "url": "https://stackoverflow.com/questions/8760581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python iterate over regex condition to replace column's values Suppose I have a non-standardized dataframe with keywords like this: data = pd.DataFrame({'tool_description':['bond assy fixture', 'pierce die', 'cad geometrical non-template', '707 bond assy fixture', 'john pierce die', '123 cad geometrical non-template', 'jjashd bond assy fixture', '10481 pierce die', '81235 cad geometrical non-template']}) Dataframe: tool_description bond assy fixture pierce die cad geometrical non-template 707 bond assy fixture john pierce die 123 cad geometrical non-template jjashd bond assy fixture 10481 pierce die 81235 cad geometrical non-template As you can see, the keywords, in this case, are bond assy fixture, pierce, and cad geometrical non-template. I want to replace those values based on their keywords to have a standardized data. So I worked on a workaround like this: # Pull the data matching my regex condition X = data.loc[data.tool_description.str.contains((r"\b(bond assy fixture)\b"), case=False, regex=True), :] # Replace values by a standardized name X['tool_description] = 'bond assy fixture' # Pull index from X dataset index_list = X.tool_description.index.tolist() # Create empty column in the original dataset data['standardized_column'] = "" # Loop to fill new column with a standardized description for index in index_list: data.loc[index, 'standardized_column'] = 'bond assy fixture' Output: tool_description standardized_column bond assy fixture bond assy fixture pierce die nan cad geometrical non-template nan 707 bond assy fixture bond assy fixture john pierce die nan 123 cad geometrical non-template nan jjashd bond assy fixture bond assy fixture 10481 pierce die nan 81235 cad geometrical non-template nan This works fine, however for one condition, and I need to make a loop of all these for hundreds of regex conditions. When I try to loop over the line where I use this line of code conditions = ['a', 'b', 'c'] for i in conditions: X = data.loc[data.tool_description.str.contains((r"\b(i)\b"), case=False, regex=True), :] I have a problem placing the regex condition as an iterator. When the loop extracts the str from the list of conditions it will pull it with the quotation mark. Now that I have put you in context, I have the following questions: * *Is there a simpler and elegant way to replace those values? *If not, how can I create a loop to iterate over that regex? Thank you for your time and answers. I know I could have asked how to remove the quotation mark for iteration purposes using regex, but, I wanted to know also if there's another way to solve the general problem which is the replacement of values. A: You could write a function to attempt to find the matching substring, and return 'nan' if not found def replace(s): keywords = ['bond assy fixture', 'pierce', 'cad geometrical non-template'] try: return next(i for i in keywords if i in s) except StopIteration: return 'nan' Then you can use apply to make this substitution >>> data['standardized_column'] = data.tool_description.apply(replace) >>> data tool_description standardized_column 0 bond assy fixture bond assy fixture 1 pierce die pierce 2 cad geometrical non-template cad geometrical non-template 3 707 bond assy fixture bond assy fixture 4 john pierce die pierce 5 123 cad geometrical non-template cad geometrical non-template 6 jjashd bond assy fixture bond assy fixture 7 10481 pierce die pierce 8 81235 cad geometrical non-template cad geometrical non-template Instead of if i in s you could use a regex in the replace function as well if you need something more complex than a simple substring check. A: You are close to the solution, just minor touch-ups needed, as follows: data['standardized_column'] = np.nan # init column to NaN for word in keywords: data.loc[data.tool_description.str.contains((rf"\b{word}\b"), case=False, regex=True), 'standardized_column'] = word Here, we use word boundary \b to enclose the keyword in the regex so that partial word match is avoided. Eg. 'pierce' won't match with 'mpierce'. Python test of StringA in StringB would produce false match since pierce in mpierce is True but not what we want to match. Result: print(data) tool_description standardized_column 0 bond assy fixture bond assy fixture 1 pierce die pierce 2 cad geometrical non-template cad geometrical non-template 3 707 bond assy fixture bond assy fixture 4 john pierce die pierce 5 123 cad geometrical non-template cad geometrical non-template 6 jjashd bond assy fixture bond assy fixture 7 10481 pierce die pierce 8 81235 cad geometrical non-template cad geometrical non-template
{ "language": "en", "url": "https://stackoverflow.com/questions/67726431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Code not executing on Ubuntu Server The following script is running on my localhost without any problems. It creates a json file that I request using AJAX to build a table in my front end. However, when I put it on my Ubuntu VM, which runs apache 2 and php 5.5 (json module is installed) it doesn't create the json file, the result being that my table is empty. <?php $arr = scandir('.\lehre\test'); foreach($arr as $k=>$v){ if($arr[$k] == "." || $arr[$k] == ".."){ unset($arr[$k]); } $fp = fopen('files.json', 'w'); fwrite($fp, json_encode($arr)); fclose($fp); } ?> PS: Other PHP Elements, like the include statement work. EDIT: I don't get any error msg. I use the forward slash notation within any other path declaration A: By the sounds of it your development environment is a Windows machine I'm guessing, which makes use of back slashes (\) when referencing directory paths. However on UNIX systems (Ubuntu in your case) the system uses forward slashes (/). Good news however, even though the Windows system uses backslashes, running PHP scripts in Windows will recognise both back slashes and forward slashes as the same, so you can use the one without having to change it every time you run the script in a different OS. TL;DR: Use / instead of \. It'll work on both Windows and Ubuntu.
{ "language": "en", "url": "https://stackoverflow.com/questions/46663522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: when i select radio button then all radio button is selected. i want only one radio button should be selected I am trying to do this. I have three radio buttons, it is working fine when i use all radio button in a single div but it is not working when i divide all radio button in particular div. i click on it then it is selected but next time when i click on it then still radio button is selected. It should be unselected when i click on it. Please help. Your help will be appreciated. Thanks a lot. Here's my code so far. <html> <head> </head> <body> <div class="filter_subdivisions"> <div class="popular_city radio mgnb6 clearfix"> <span class="fltl" style="width:70%;padding-top: 6px;">Delhi Airport</span> <span class="fltr"> <label class="label_radio" for="radio-01"><input name="sample-radio" id="radio-01" value="1" type="radio" checked />&nbsp;</label> </span> </div> <div class="popular_city radio mgnb6 clearfix"> <span class="fltl" style="width:70%;padding-top: 6px;">Delhi Airport</span> <span class="fltr"> <label class="label_radio" for="radio-02"><input name="sample-radio" id="radio-02" value="1" type="radio" />&nbsp;</label> </span> </div> </div> </body> </html> and <script> var d = document; var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false; var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); }; onload = function() { var body = gebtn(d,'body')[0]; body.className = body.className && body.className != '' ? body.className + ' has-js' : 'has-js'; if (!d.getElementById || !d.createTextNode) return; var ls = gebtn(d,'label'); for (var i = 0; i < ls.length; i++) { var l = ls[i]; if (l.className.indexOf('label_') == -1) continue; var inp = gebtn(l,'input')[0]; if (l.className == 'label_radio') { l.className = (safari && inp.checked == true || inp.checked) ? 'label_radio r_on' : 'label_radio r_off'; l.onclick = turn_radio; }; }; }; var turn_radio = function() { var inp = gebtn(this,'input')[0]; if (this.className == 'label_radio r_off' || inp.checked) { var ls = gebtn(this.parentNode,'label'); for (var i = 0; i < ls.length; i++) { var l = ls[i]; if (l.className.indexOf('label_radio') == -1) continue; l.className = 'label_radio r_off'; }; this.className = 'label_radio r_on'; if (safari) inp.click(); } else { this.className = 'label_radio r_off'; if (safari) inp.click(); }; }; </script> A: You have to have type="radio" buttons within the same container to make them behave like radio buttons, like as per w3schools example <form> <input type="radio" name="sex" value="male">Male<br> <input type="radio" name="sex" value="female">Female </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/25928787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I fix an error with the seed file in Prisma and typescript? I'm building a backend using Prisma, Postgres 14.5, Node 18, and Typescript. Every time try to seed the DB I get the following: └ ➜ yarn prisma db seed Environment variables loaded from .env Running seed command `ts-node prisma/seed.ts` ... An error occurred while running the seed command: Error: Command failed with ENOENT: ts-node prisma/seed.ts spawn ts-node ENOENT ENOENT errors mean "No such file or directory" I have this in my package.json: "prisma": { "seed": "ts-node prisma/seed.ts" }, My seed file is located at prisma/seed.ts and contains: import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); async function main() { const person = await prisma.name.upsert({ where: { id: 0 }, update: {}, create: { firstName: 'Sakiko', }, }); } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); }); A: Turns out I was missing ts-node as we don't have our build fully set up yet. So I fixed it with yarn add ts-node. Additionally, I had to simplify our tsconfig.json to remove the compilerOptions.rootDir as the prisma code is outside the src directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/74935766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Build One Project from GIT Repo (Jenkins/GIT) I am trying to check out just one maven project from a GIT repo (Total of 49 modules) in Jenkins and do a build. The only reason is that they all need to be built a little bit differently in order to be deployed on to Tomcat. I probably might have been able to do it in SVN because I have dealt with it for a decade. But I am a spring chicken when it comes to GIT, I just don't have much idea how to get this to work. The current GIT folder structure is like: Maven Parent Project Child Project A Child Porject B Child Porject C Child Porject D . . . . . and so on... Now lets say I want to create a job that just builds ChildProjectD, how do I go about it? Is it even possible? I did install the plugin GIT Parameter, thinking it would get me somewhere. But just don't know what to put in the fields. Any help with this would be helpful. Thanks in advance. A: These following guidelines may help you with initializing a Jenkins freestyle job for building a subproject rather than building all projects included in a git repo. * *Install git-plugin for Jenkins *Create a freestyle job and add your git hub repository's link on SCM repository field * *New Item --> *Name the item and OK --> *Select Git in SCM --> *Add repository URL --> *Add invoke top-level maven targets as Build steps --> *In Goals install -pl ChildProjectD *(optional) Add post-build and other configurations It will build the Child project as you want instead of full project. You can refer Jenkins GitHub Java Application Project Build Configuration Maven to get more help. Check also mvn install -pl --help for more info. Feel free to ask questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/60204481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't rename an ActiveRecord table a second time. "[table]_pkey" does not exist Some time ago, I ran the following rails migration to change the name of a table: class RenameMaterialDonationsToMaterialDonationRequests < ActiveRecord::Migration def change rename_table :material_donations, :material_donation_requests end end Now I need to rename the table again. Here's my migration: class RenameMaterialDonationRequestsToHelpRequests < ActiveRecord::Migration def change rename_table :material_donation_requests, :help_requests end end However, when I run the migration, I'm getting the following error: PG::Error: ERROR: relation "material_donation_requests_pkey" does not exist : ALTER INDEX "material_donation_requests_pkey" RENAME TO "help_requests_pkey"/Users/[me]/.rvm/gems/ruby-2.1.4/gems/activerecord-4.2.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `exec' I'm using Postgresql. In pgAdmin3, I can see that the pkey still retains the table name from before the first migration: CONSTRAINT material_donations_pkey PRIMARY KEY (id) How can I fix this to rename the table? A: The answer below might work, but I decided to go with this: execute "ALTER INDEX material_donations_pkey RENAME TO material_donation_requests_pkey;" I chose this because it is the command that the migration was trying to run automatically as part of the original migration. That command wasn't automatically part of the pre-4.0 rails when I renamed this table the first time so I ran it now. I felt more comfortable doing exactly what rails is doing presently. A: Here is a hacky solution, add another migration file and do this before change table name second time: execute "ALTER TABLE material_donation_requests DROP CONSTRAINT material_donations_pkey;" execute "ALTER TABLE material_donation_requests ADD PRIMARY KEY (id);" And you probably need to do something similar after your next name changing. A: Adding my solution for similar problem. Below is the error while running migrations 01 PG::UndefinedTable: ERROR: relation "fundraise_stories_pkey" does not exist 01 : ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey" Connected to database via pgadmin and selected constraints for the table fundraise_stories. It was showing constraint name as "fundrise_stories_pkey". So it was some old mistake because constraint name doesnt match with table name. Solution: * *Find existing index name under constraints section for the table. In my case it was 'fundrise_stories_pkey' *Rename the index before renaming table *Finally, Rename the table. Below is modified migration to rename index before renaming table. def self.up execute "ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;" rename_table :fundraise_stories, :fundraisers end Log D, [2020-02-02T17:16:27.428294 #7363] DEBUG -- : (0.2ms) BEGIN == 20200127102616 RenameFundraiseStoryTableToFundraisers: migrating =========== -- execute("ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;") D, [2020-02-02T17:16:27.434366 #7363] DEBUG -- : (5.5ms) ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey; -> 0.0061s -- rename_table(:fundraise_stories, :fundraisers) D, [2020-02-02T17:16:27.435722 #7363] DEBUG -- : (0.7ms) ALTER TABLE "fundraise_stories" RENAME TO "fundraisers" D, [2020-02-02T17:16:27.438769 #7363] DEBUG -- : (0.3ms) ALTER TABLE "public"."fundraise_stories_id_seq" RENAME TO "fundraisers_id_seq" D, [2020-02-02T17:16:27.439334 #7363] DEBUG -- : (0.2ms) ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey" D, [2020-02-02T17:16:27.445452 #7363] DEBUG -- : (0.8ms) ALTER INDEX "index_fundraise_stories_on_bank_account_id" RENAME TO "index_fundraisers_on_bank_account_id" D, [2020-02-02T17:16:27.446153 #7363] DEBUG -- : (0.3ms) ALTER INDEX "index_fundraise_stories_on_creator_id_and_creator_type" RENAME TO "index_fundraisers_on_creator_id_and_creator_type" -> 0.0131s == 20200127102616 RenameFundraiseStoryTableToFundraisers: migrated (0.0193s) ==
{ "language": "en", "url": "https://stackoverflow.com/questions/34241900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Redirect back to same page (with variables) on form submit in Laravel 5 On my page events.index, I first display a list of events for the logged on user. On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user. I'm not sure what would be the best approach: * *Set a session variable to keep the user_id value? Not sure how to do that with a form. *Submit the form with a get method (and get an ugly ?user_id=1 URL) *Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController@store')) Not sure what would be a clean way to do this: My route for events/index: Route::get('events', [ 'as' => 'event.index', 'uses' => 'EventsController@index' ]); Events Controller public function index() { // How to get the $user_id value from form? if (empty($user_id)) { $user_id = \Auth::user()->id; } $events = Event::where('events.user_id','=','$user_id'); $users = User::all(); return view('events.index')->with(['events' => $events])->with(['users' => $users]); } View for index {!! Form::open(['route' => 'events.index', 'method' => 'get']) !!} <select id="user_id" name="user_id"> @foreach($users as $user) <option value="{{$user->id}}">{{$user->name}}</option> @endforeach </select> {!! Form::submit('Show events for this user') !!} {!! Form::close() !!} @foreach($events as $event) ... @endforeach A: You can get the user_id from a Request object, you just need to inject it in the index method: public function index(Request $request) { $user_id = $request->get('user_id') ?: Auth::id(); $events = Event::where('events.user_id','=','$user_id')->get(); $users = User::all(); return view('events.index')->with(['events' => $events])->with(['users' => $users]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/36438071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS certificate pinning with Swift and NSURLSession Howto add certificate pinning to a NSURLSession in Swift? The OWASP website contains only an example for Objective-C and NSURLConnection. A: Save the certificate (as .cer file) of your website in the main bundle. Then use this URLSessionDelegate method: func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let serverTrust = challenge.protectionSpace.serverTrust, SecTrustEvaluate(serverTrust, nil) == errSecSuccess, let serverCert = SecTrustGetCertificateAtIndex(serverTrust, 0) else { reject(with: completionHandler) return } let serverCertData = SecCertificateCopyData(serverCert) as Data guard let localCertPath = Bundle.main.path(forResource: "shop.rewe.de", ofType: "cer"), let localCertData = NSData(contentsOfFile: localCertPath) as Data?, localCertData == serverCertData else { reject(with: completionHandler) return } accept(with: serverTrust, completionHandler) } ... func reject(with completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) { completionHandler(.cancelAuthenticationChallenge, nil) } func accept(with serverTrust: SecTrust, _ completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) { completionHandler(.useCredential, URLCredential(trust: serverTrust)) } A: Just a heads up, SecTrustEvaluate is deprecated and should be replaced with SecTrustEvaluateWithError. So this: var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if errSecSuccess == status { // Proceed with evaluation switch result { case .unspecified, .proceed: return true default: return false } } The reason i wrote the // Proceed with evaluation section is because you should validate the secresult as well as this could imply that the certificate is actually invalid. You have the option to override this and add any raised issues as exceptions, preferably after prompting the user for a decision. Should be this: if SecTrustEvaluateWithError(server, nil) { // Certificate is valid, proceed. } The second param will capture any error, but if you are not interested in the specifics, you can just pass nil. A: Swift 3+ Update: Just define a delegate class for NSURLSessionDelegate and implement the didReceiveChallenge function (this code is adapted from the objective-c OWASP example): class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil) if(isServerTrusted) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let cert1 = NSData(bytes: data, length: size) let file_der = Bundle.main.path(forResource: "certificateFile", ofType: "der") if let file = file_der { if let cert2 = NSData(contentsOfFile: file) { if cert1.isEqual(to: cert2 as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } } (you can find a Gist for Swift 2 here - from the initial answer) Then create the .der file for your website using openssl openssl s_client -connect my-https-website.com:443 -showcerts < /dev/null | openssl x509 -outform DER > my-https-website.der and add it to the xcode project. Double check that it's present in the Build phases tab, inside the Copy Bundle Resources list. Otherwise drag and drop it inside this list. Finally use it in your code to make URL requests: if let url = NSURL(string: "https://my-https-website.com") { let session = URLSession( configuration: URLSessionConfiguration.ephemeral, delegate: NSURLSessionPinningDelegate(), delegateQueue: nil) let task = session.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in if error != nil { print("error: \(error!.localizedDescription): \(error!)") } else if data != nil { if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) { print("Received data:\n\(str)") } else { print("Unable to convert data to text") } } }) task.resume() } else { print("Unable to create NSURL") } A: Thanks to the example found in this site: https://www.bugsee.com/blog/ssl-certificate-pinning-in-mobile-applications/ I built a version that pins the public key and not the entire certificate (more convenient if you renew your certificate periodically). Update: Removed the forced unwrapping and replaced SecTrustEvaluate. import Foundation import CommonCrypto class SessionDelegate : NSObject, URLSessionDelegate { private static let rsa2048Asn1Header:[UInt8] = [ 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00 ]; private static let google_com_pubkey = ["4xVxzbEegwDBoyoGoJlKcwGM7hyquoFg4l+9um5oPOI="]; private static let google_com_full = ["KjLxfxajzmBH0fTH1/oujb6R5fqBiLxl0zrl2xyFT2E="]; func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let serverTrust = challenge.protectionSpace.serverTrust else { completionHandler(.cancelAuthenticationChallenge, nil); return; } // Set SSL policies for domain name check let policies = NSMutableArray(); policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString))); SecTrustSetPolicies(serverTrust, policies); var isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil); if(isServerTrusted && challenge.protectionSpace.host == "www.google.com") { let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0); //Compare public key if #available(iOS 10.0, *) { let policy = SecPolicyCreateBasicX509(); let cfCertificates = [certificate] as CFArray; var trust: SecTrust? SecTrustCreateWithCertificates(cfCertificates, policy, &trust); guard trust != nil, let pubKey = SecTrustCopyPublicKey(trust!) else { completionHandler(.cancelAuthenticationChallenge, nil); return; } var error:Unmanaged<CFError>? if let pubKeyData = SecKeyCopyExternalRepresentation(pubKey, &error) { var keyWithHeader = Data(bytes: SessionDelegate.rsa2048Asn1Header); keyWithHeader.append(pubKeyData as Data); let sha256Key = sha256(keyWithHeader); if(!SessionDelegate.google_com_pubkey.contains(sha256Key)) { isServerTrusted = false; } } else { isServerTrusted = false; } } else { //Compare full certificate let remoteCertificateData = SecCertificateCopyData(certificate!) as Data; let sha256Data = sha256(remoteCertificateData); if(!SessionDelegate.google_com_full.contains(sha256Data)) { isServerTrusted = false; } } } if(isServerTrusted) { let credential = URLCredential(trust: serverTrust); completionHandler(.useCredential, credential); } else { completionHandler(.cancelAuthenticationChallenge, nil); } } func sha256(_ data : Data) -> String { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA256($0, CC_LONG(data.count), &hash) } return Data(bytes: hash).base64EncodedString(); } } A: Here's an updated version for Swift 3 import Foundation import Security class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { // Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if(errSecSuccess == status) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let cert1 = NSData(bytes: data, length: size) let file_der = Bundle.main.path(forResource: "name-of-cert-file", ofType: "cer") if let file = file_der { if let cert2 = NSData(contentsOfFile: file) { if cert1.isEqual(to: cert2 as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } } A: The openssl command in @lifeisfoo's answer will give an error in OS X for certain SSL certificates that use newer ciphers like ECDSA. If you're getting the following error when you run the openssl command in @lifeisfoo's answer: write:errno=54 unable to load certificate 1769:error:0906D06C:PEM routines:PEM_read_bio:no start line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL09 8-59.60.1/src/crypto/pem/pem_lib.c:648:Expecting: TRUSTED CERTIFICATE You're website's SSL certificate probably is using an algorithm that isn't supported in OS X's default openssl version (v0.9.X, which does NOT support ECDSA, among others). Here's the fix: To get the proper .der file, you'll have to first brew install openssl, and then replace the openssl command from @lifeisfoo's answer with: /usr/local/Cellar/openssl/1.0.2h_1/bin/openssl [rest of the above command] Homebrew install command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" hope that helps. A: You can try this. import Foundation import Security class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate { let certFileName = "name-of-cert-file" let certFileType = "cer" func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) { if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if(errSecSuccess == status) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let certificateOne = NSData(bytes: data, length: size) let filePath = Bundle.main.path(forResource: self.certFileName, ofType: self.certFileType) if let file = filePath { if let certificateTwo = NSData(contentsOfFile: file) { if certificateOne.isEqual(to: certificateTwo as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } } Source: https://www.steveclarkapps.com/using-certificate-pinning-xcode/
{ "language": "en", "url": "https://stackoverflow.com/questions/34223291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: ViewPager with classes instead of layouts? Basically what I'm trying to do is I want to have a ViewPager. But it should swipe between classes instead of layouts so that every page of the ViewPager has its own class where it also has its own stuff. If you take instagram for instance. It has a BottomNavigationView where every item has its own acticity which handles its own methods and functions. What I want to achieve is a BottomNavigationView like instagram which starts a new activity but with a slide animation to the left/right like with a ViewPager.
{ "language": "en", "url": "https://stackoverflow.com/questions/48667281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add duplicate key elements in JavaScript Object? I want to make the following newArray using by following testArray. newArray↓ let newArray = [ {section:"business",name:["Bob","John"]}, {section:"H&R",name:["Jen","Bobby"]}, ] testArray↓ let test = [ {section:"business",name:"Bob"}, {section:"business",name:"John"}, {section:"H&R",name:"Jen"}, {section:"H&R",name:"Bobby"}, ] First of all, I tried to find some key elements using by filter method like below. let newArray = test.filter((x:any,i,self)=> self.indexOf(x.section)===i ) but this code output is []. So, how do I make code to get my expected output? Does anyone help me? A: Use Array.reduce(): let test=[{section:"business",name:"Bob"},{section:"business",name:"John"},{section:"H&R",name:"Jen"},{section:"H&R",name:"Bobby"}]; let newArray = test.reduce((acc,cur) => { if(acc.some(el => el.section === cur.section)){ acc.forEach((el,idx) => { if(el.section === cur.section){ acc[idx].name.push(cur.name) } }) }else{ cur.name = [cur.name] acc.push(cur) } return acc },[]) console.log(newArray) A: you can try this const test = [{ section: "business", name: "Bob" }, { section: "business", name: "John" }, { section: "H&R", name: "Jen" }, { section: "H&R", name: "Bobby" }, ]; // gather sections const sections = {}; test.forEach(t => { sections[t.section] = sections[t.section] || []; sections[t.section].push(t.name); }); // convert sessions to array const newArray = Object.keys(sections).map(k => { return { section: k, name: sections[k] }; }); console.log(newArray);
{ "language": "en", "url": "https://stackoverflow.com/questions/65878412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to resume multiple download using PersistableTransfer manager in amazon s3 in android I am downloading a list of objects using following function: TransferManager transferManager = new TransferManager(s3client); try { GetObjectRequest getRequest = new GetObjectRequest(bucketName, entity.getName()); download = transferManager.download(getRequest, f, new S3ProgressListener() { @Override public void onPersistableTransfer(PersistableTransfer arg0) { // TODO Auto-generated method stub saveTransferState(arg0, Environment.getExternalStorageDirectory()+"/"+entity.getName()); } @Override public void progressChanged( com.amazonaws.event.ProgressEvent arg0) { long transferred = arg0.getBytesTransferred(); Log.d("AWS3", "" + transferred); } }); Now when my internet connection stops while downloads were in progress i pause this download and resume it when internet connection again available using following code: TransferManager transferManager = new TransferManager(S3Getter.s3client); String bucket = "Short_Films"; String key = entity.getName(); String[] parts = key.split("/"); String fileName = parts[parts.length - 1]; final String full_path = Environment.getExternalStorageDirectory()+"/"+entity.getName(); File file = new File(full_path); FileInputStream fis = null; if(file.exists()) { try { fis = new FileInputStream(file); PersistableDownload persistableUpload = PersistableTransfer.deserializeFrom(fis); S3Getter.download = transferManager.resumeDownload(persistableUpload); } catch (Exception e1) { e1.printStackTrace(); } } Now the problem is this code works fine to resume single object. But when there are multiple objects to resume it resume only last resumed object. I am stuck at this point. Please some body help me.....
{ "language": "en", "url": "https://stackoverflow.com/questions/27438136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: How to replace missing values column wise by median I have a dataframe as follows df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.45, 2.33, np.nan], 'C': [4, 5, 6], 'D': [4.55, 7.36, np.nan]}) I want to replace the missing values i.e. np.nan in generic way. For this I have created a function as follows def treat_mis_value_nu(df): df_nu = df.select_dtypes(include=['number']) lst_null_col = df_nu.columns[df_nu.isnull().any()].tolist() if len(lst_null_col)>0: for i in lst_null_col: if df_nu[i].isnull().sum()/len(df_nu[i])>0.10: df_final_nu = df_nu.drop([i],axis=1) else: df_final_nu = df_nu[i].fillna(df_nu[i].median(),inplace=True) return df_final_nu When I apply this function as follows df_final = treat_mis_value_nu(df) I am getting a dataframe as follows A B C 0 1 1.0 4 1 2 2.0 5 2 3 NaN 6 So it has actually removed column D correctly, but failed to remove column B. I know in past there have been discussion on this topic (here). Still I might be missing something? A: Use: df = pd.DataFrame({'A': [1, 2, 3,5,7], 'B': [1.45, 2.33, np.nan, np.nan, np.nan], 'C': [4, 5, 6,8,7], 'D': [4.55, 7.36, np.nan,9,10], 'E':list('abcde')}) print (df) A B C D E 0 1 1.45 4 4.55 a 1 2 2.33 5 7.36 b 2 3 NaN 6 NaN c 3 5 NaN 8 9.00 d 4 7 NaN 7 10.00 e def treat_mis_value_nu(df): #get only numeric columns to dataframe df_nu = df.select_dtypes(include=['number']) #get only columns with NaNs df_nu = df_nu.loc[:, df_nu.isnull().any()] #get columns for remove with mean instead sum/len, it is same cols_to_drop = df_nu.columns[df_nu.isnull().mean() <= 0.30] #replace missing values of original columns and remove above thresh return df.fillna(df_nu.median()).drop(cols_to_drop, axis=1) print (treat_mis_value_nu(df)) A C D E 0 1 4 4.55 a 1 2 5 7.36 b 2 3 6 8.18 c 3 5 8 9.00 d 4 7 7 10.00 e A: I would recommend looking at the sklearn Imputer transformer. I don't think it it can drop columns but it can definetly fill them in a 'generic way' - for example, filling in missing values with the median of the relevant column. You could use it as such: from sklearn.preprocessing import Imputer imputer = Imputer(strategy='median') num_df = df.values names = df.columns.values df_final = pd.DataFrame(imputer.transform(num_df), columns=names) If you have additional transformations you would like to make you could consider making a transformation Pipeline or could even make your own transformers to do bespoke tasks.
{ "language": "en", "url": "https://stackoverflow.com/questions/54879621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overlap in labels of point data in rasterVis I have a raster r, one polygon shapefile regions and a point shapefile cities. I need to plot all three into one map layout. In addition to this I need to label point file with names of cities (cities$city$Town.Name) and their temperature and precipitation value (assigned as cities$labels). So I have used the following code with packages 'raster' and 'rasterVis'. p1<-levelplot(regions.r,par.settings=mytheme,scales=list(draw=FALSE),xlab="",ylab="",margin=F)+ layer(sp.polygons(regions))+ layer(sp.points(cities,pch=20,cex=1.5,col="black")) p1+ layer(sp.text(coordinates(cities), txt = cities$city$Town.Name, pos = 3,col="black",font=list(face="bold"),cex=0.8))+ layer(sp.text(coordinates(cities),txt = cities$label, pos = 1,cex=0.6,col="black"))#Add shapefile labels This works fine when area has scattered cities distribution (see figure below). However, if the cities are concentrated in one part I experience overlap of labels (see figure below). Is there a way to avoid the label overlap?
{ "language": "en", "url": "https://stackoverflow.com/questions/45791663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I create an in-memory class and then include it in Perl? So I am toying with some black magic in Perl (eventually we all do :-) and I am a little confused as to exactly how I am supposed to be doing all of this. Here is what I'm starting with: use strict; use warnings; use feature ':5.10'; my $classname = 'Frew'; my $foo = bless({ foo => 'bar' }, $classname); no strict; *{"$classname\::INC"} = sub { use strict; my $data = qq[ package $classname warn 'test'; sub foo { print "test?"; } ]; open my $fh, '<', \$data; return $fh; }; use strict; unshift @INC, $foo; require $foo; use Data::Dumper; warn Dumper(\@INC); $classname->foo; I get the following errors (depending on whether my require line is commented out): With require: Recursive call to Perl_load_module in PerlIO_find_layer at crazy.pl line 16. BEGIN failed--compilation aborted. without: $VAR1 = [ bless( { 'foo' => 'bar' }, 'Frew' ), 'C:/usr/site/lib', 'C:/usr/lib', '.' ]; Can't locate object method "foo" via package "Frew" at crazy.pl line 24. Any wizards who know some of this black magic already: please answer! I'd love to learn more of this arcana :-) Also note: I know that I can do this kind of stuff with Moose and other lighter helper modules, I am mostly trying to learn, so recommendations to use such-and-such a module will not get my votes :-) Update: Ok, I guess I wasn't quite clear originally with my question. I basically want to generate a Perl class with a string (that I will manipulate and do interpolation into) based on an external data structure. I imagine that going from what I have here (once it works) to that shouldn't be too hard. A: I do this: use MooseX::Declare; my $class = class { has 'foo' => (is => 'ro', isa => 'Str', required => 1); method bar() { say "Hello, world; foo is ", $self->foo; } }; Then you can use $class like any other metaclass: my $instance = $class->name->new( foo => 'foo bar' ); $instance->foo; # foo-bar $instance->bar; # Hello, world; foo is foo-bar etc. If you want to dynamically generate classes at runtime, you need to create the proper metaclass, instantiate it, and then use the metaclass instance to generate instances. Basic OO. Class::MOP handles all the details for you: my $class = Class::MOP::Class->create_anon_class; $class->add_method( foo => sub { say "Hello from foo" } ); my $instance = $class->new_object; ... If you want to do it yourself so that you can waste your time debugging something, perhaps try: sub generate_class_name { state $i = 0; return '__ANON__::'. $i++; } my $classname = generate_class_name(); eval qq{ package $classname; sub new { my \$class = shift; bless {} => \$class } ... }; my $instance = $classname->new; A: Here is a version which works: #!/usr/bin/perl use strict; use warnings; my $class = 'Frew'; { no strict 'refs'; *{ "${class}::INC" } = sub { my ($self, $req) = @_; return unless $req eq $class; my $data = qq{ package $class; sub foo { print "test!\n" }; 1; }; open my $fh, '<', \$data; return $fh; }; } my $foo = bless { }, $class; unshift @INC, $foo; require $class; $class->foo; The @INC hook gets the name of the file (or string passed to require) as the second argument, and it gets called every time there is a require or use. So you have to check to make sure we're trying to load $classname and ignore all other cases, in which case perl continues down along @INC. Alternatively, you can put the hook at the end of @INC. This was the cause of your recursion errors. ETA: IMHO, a much better way to achieve this would be to simply build the symbol table dynamically, rather than generating code as a string. For example: no strict 'refs'; *{ "${class}::foo" } = sub { print "test!\n" }; *{ "${class}::new" } = sub { return bless { }, $class }; my $foo = $class->new; $foo->foo; No use or require is necessary, nor messing with evil @INC hooks. A: For a simple example of how to do this, read the source of Class::Struct. However, if I needed the ability to dynamically build classes for some production code, I'd look at MooseX::Declare, as suggested by jrockway. A: A Perl class is little more than a data structure (usually a hashref) that has been blessed into a package in which one or more class methods are defined. It is certainly possible to define multiple package namespaces in one file; I don't see why this wouldn't be possible in an eval construct that is compiled at run-time (see perlfunc for the two different eval forms). #!/usr/bin/perl use 5.010; use strict; use warnings; use Data::Dumper; eval q[ package Foo; sub new { my ( $class, %args ) = @_; my $self = bless { %args }, $class; return $self; } 1; ]; die $@ if $@; my $foo = Foo->new(bar => 1, baz => 2) or die; say Dumper $foo;
{ "language": "en", "url": "https://stackoverflow.com/questions/1128117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is the name of this q/kdb+ feature? Does any flavor of LISP implement it? How? The q programming language has a feature (which this tutorial calls "function projection") where a function of two or more parameters can be called with fewer parameters than it requires, but the result is an intermediate object, and the function will not be executed until all remaining parameters are passed; one way to see it is that functions behave like multi-dimensional arrays, so that (f[x])[y] is equivalent to f[x;y]. For example ... q)add:{x+y} q)add[42;] {x+y}[42;] q)add[42;][3] 45 q)g:add[42;] q)g[3] 45 Since q does not have lexical scoping, this features become very useful in obtaining lexical scoping behavior by passing the necessary variables to an inner function as a partial list of parameters; e.g. a print parameter decorator can be constructed using this feature: q)printParameterDecorator:{[f] {[f;x] -1 "Input: ",string x; f x}f}; q)f: printParameterDecorator (2+); q)f 3 Input: 3 5 My questions: * *Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature? *Does any variety of LISP implement this feature? Which ones? *Could you provide some example LISP code please? A: Is the term "function projection" a standard term? Or does this feature carry a different name in the functional programming literature? No, you usually call it partial application. Does any variety of LISP implement this feature? Which ones? Practically all Lisp allow you to partially apply a function, but usually you need to write a closure explicitly. For example in Common Lisp: (defun add (x y) (+ x y)) The utility function curry from alexandria can be used to create a closure: USER> (alexandria:curry #'add 42) #<CLOSURE (LAMBDA (&REST ALEXANDRIA.1.0.0::MORE) :IN CURRY) {1019FE178B}> USER> (funcall * 3) ;; asterisk (*) is the previous value, the closure 45 The resulting closure is equivalent to the following one: (lambda (y) (add 42 y)) Some functional languages like OCaml only allow functions to have a single parameter, but syntactically you can define functions of multiple parameters: (fun x y -> x + y) The above is equivalent to: (function x -> (function y -> x + y)) See also What is the difference between currying and partial application? Nb. in fact the q documentation refers to it as partial application: Notationally, projection is a partial application in which some arguments are supplied and the others are omitted A: I think another way doing this : q)f:2+ q)g:{"result: ",string x} q)'[g;f]3 "result: 5" It is composite function, passing 3 to f, then the result from f will be passed to g. I'm not sure if it is LISP, but it could achieve the same result.
{ "language": "en", "url": "https://stackoverflow.com/questions/64423568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graphics and Graphics 2D in java I am having a problem changing the color of the diamond I had created when I am using methods in java. I don't know how to inherit or to correct it by using methods. I just want it to become object oriented I don't know how to properly do it. Please help me. package Trial; import javax.swing.*; import java.awt.*; public class ColorRed extends JApplet { public GradientPaint gradientPaint; public void paint(Graphics g){ super.paint(g); Graphics2D g2 = (Graphics2D)g; GradientPaint black = new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK); blackDiamond(g2,black); GradientPaint yellowOrange = new GradientPaint(50,20,Color.YELLOW,50,50,Color.RED); redDiamond(g2,yellowOrange); } public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){ int a [] = {100,50,100,150,100}; int b [] = {10,60,110,60,10}; setGradientPaint(gradientPaint); g2.setPaint(getGradientPaint()); fillPolygon(a,b,5,g2); } public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){ int a2 [] = {100,60,100,140,100}; int b2 [] = {20,60,100,60,20}; setGradientPaint(gradientPaint); g2.setPaint(getGradientPaint()); fillPolygon(a2,b2,5,g2); } public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){ getGraphics().fillPolygon(a,b,c); } public GradientPaint getGradientPaint() { return gradientPaint; } public void setGradientPaint(GradientPaint gradientPaint) { this.gradientPaint = gradientPaint; } } This is the code that I try to create object-oriented but it doesn't inherit the color of gradient paint. enter image description here That is the result of my code This the code that not yet create multiple methods import javax.swing.*; import java.awt.*; public class ColorRed extends JApplet { public GradientPaint gradientPaint; public void paint(Graphics g){ super.paint(g); Graphics2D g2 = (Graphics2D)g; int a [] = {100,50,100,150,100}; int b [] = {10,60,110,60,10}; g.fillPolygon(a,b,5); GradientPaint red = new GradientPaint(50,10,Color.RED,10,70,Color.ORANGE); g2.setPaint(red); int a2 [] = {100,60,100,140,100}; int b2 [] = {20,60,100,60,20}; g.fillPolygon(a2,b2,5); } } This is the result that I want: enter image description here I just want to correct it to organize so that I wont declare all the local variables in paint method I just want to seperate it in different methods the problem is that the Color doesn't change. Please help me thanks a lot. :) A: Maybe organize it like this, so that the color is easily changed: package Trial; import javax.swing.*; import java.awt.*; public class ColorRed extends JApplet { private GradientPaint black; private GradientPaint yellowOrange; public void init() { setBlack(new GradientPaint(50,20,Color.BLACK,50,50,Color.BLACK)); setYellowOrange(GradientPaint(50,20,Color.YELLOW,50,50,Color.RED)); } public setBlack(GradientPaint black) { this.black = black; } public setYellowOrange(GradientPaint yellowOrange) { this.yellowOrange = yellowOrange; } public void paint(Graphics g){ super.paint(g); Graphics2D g2 = (Graphics2D)g; blackDiamond(g2,black); redDiamond(g2,yellowOrange); } public void blackDiamond(Graphics2D g2,GradientPaint gradientPaint){ int a [] = {100,50,100,150,100}; int b [] = {10,60,110,60,10}; g2.setPaint(gradientPaint); fillPolygon(a,b,5,g2); } public void redDiamond(Graphics2D g2,GradientPaint gradientPaint){ int a2 [] = {100,60,100,140,100}; int b2 [] = {20,60,100,60,20}; g2.setPaint(gradientPaint); fillPolygon(a2,b2,5,g2); } public void fillPolygon(int a [], int b [] ,int c,Graphics2D g2){ g2.fillPolygon(a,b,c); } } Unfortunately I didn't locate an online swing runner to test it. A: I modified Adder's answer (which worked as advertised) so it would work without using JApplet (which is also tagged as deprecated). I added some comments where different. import java.awt.Color; import java.awt.Dimension; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class ColorRed extends JPanel { private GradientPaint black; private GradientPaint yellowOrange; JFrame frame = new JFrame(); public static void main(String[] args) { SwingUtilities.invokeLater(() -> new ColorRed().init()); } public void init() { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the panel size setPreferredSize(new Dimension(500, 500)); // add panel to frame. frame.add(this); // adjust frame and subcomponents frame.pack(); // center on screen frame.setLocationRelativeTo(null); frame.setVisible(true); setBlack(new GradientPaint(50, 20, Color.BLACK, 50, 50, Color.BLACK)); setYellowOrange(new GradientPaint(50, 20, Color.YELLOW, 50, 50, Color.RED)); } public void setBlack(GradientPaint black) { this.black = black; } public void setYellowOrange(GradientPaint yellowOrange) { this.yellowOrange = yellowOrange; } // use paintComponent(g) and not paint(g) public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; blackDiamond(g2, black); redDiamond(g2, yellowOrange); } public void blackDiamond(Graphics2D g2, GradientPaint gradientPaint) { int a[] = { 100, 50, 100, 150, 100 }; int b[] = { 10, 60, 110, 60, 10 }; g2.setPaint(gradientPaint); fillPolygon(a, b, 5, g2); } public void redDiamond(Graphics2D g2, GradientPaint gradientPaint) { int a2[] = { 100, 60, 100, 140, 100 }; int b2[] = { 20, 60, 100, 60, 20 }; g2.setPaint(gradientPaint); fillPolygon(a2, b2, 5, g2); } public void fillPolygon(int a[], int b[], int c, Graphics2D g2) { g2.fillPolygon(a, b, c); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/58609766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery remove everything after and including certain character I have a location - Pearl River, NY (10965) that I want displayed as Pearl River, NY (so it must delete (10965) -- including the space before ( -- I'm not looking to make a big deal of this and do anything server side. jQuery would work fine. I know this is probably simple as hell, I just don't use JS much. Thanks! A: location_string = location_string.replace(/ \([^)]*\)/, ''); On a side note, please stop thinking that jQuery is necessary for anything at all, especially not a string manipulation task like this. It really isn't, and jQuery is overhyped. A: I'm not sure how you're given "Peal River NY..." (variable? innerHTML?), but you need to use a regular expression to match the (numbers), and the replace method to substitute the match for nothing "". "Peal River, NY (10965)".replace(/ \([0-9]+\)/, ""); This doesn't use jQuery! See the String.replace method. As mentioned by @James in the comments, this snippet will leave "Peal River, NY ()" as "Peal River, NY ()", rather than removing the brackets. If this is a case you need to consider, change the + to *: "Peal River, NY (10965)".replace(/ \([0-9]*\)/, ""); A: Use a regex: var s = "Pearl River, NY (10965)"; alert(s.replace(/ \([\d]*\)/,'')); See it at this JSFiddle Of course, here I am assuming you'll be wanting to replace only numbers in the brackets. For letter and underscore, use \w in place of \d You might also want to make it a requirement that the item occurs at the end. In which case, the following will suffice: alert(s.replace(/ \([\d]*\)$/,'')); You'll note that none of the above references jQuery. This is something that can be achieved with pure JavaScript.
{ "language": "en", "url": "https://stackoverflow.com/questions/6873720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to style a dashboard with CSS in dash and python? I don’t know much about CSS and I need help aligning these 4 smaller graphs under this larger graph. This is the closest I’ve come to being aligned. I need the 4 smaller graphs to be aligned under the larger graph, but covering the whole page, how to do that? my code: fig_pick = px.pie(map_pick, values='Total', names='Map', title='Mapas com mais Picks no Valorant Champions 2022') fig_pick.update_layout(margin=dict(l=40, r=25, t=45, b=20), height=300, width=340 , template='darkly') fig_ban = px.pie(map_ban, values='Total', names='Map', title='Mapas com mais Bans no Valorant Champions 2022') fig_ban.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, width=340 , template='darkly') fig_atk = px.bar(map_side, x='Map', y='Atk Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de ataque pelo Valorant Champions em %:', labels={ 'Atk Wins': 'Vitórias no lado de Ataque em %', 'Map': 'Mapa' }, text='Atk Wins') fig_atk.update_traces(textposition='inside',texttemplate='%{text:.3s}') fig_atk.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, width=360 , template='darkly') fig_def = px.bar(map_side, x='Map', y='Def Wins', color='Map', title='Taxa de Vitórias nos mapas no lado de defesa pelo Valorant Champions em %:', labels={ 'Def Wins': 'Vitórias no lado de Defesa em %', 'Map': 'Mapa' }, text='Def Wins') fig_def.update_traces(textposition='inside',texttemplate='%{text:.3s}') fig_def.update_layout(margin=dict(l=40, r=55, t=45, b=20), height=300, width=360 , template='darkly') app.layout = html.Div(children=[ dbc.Row([ dbc.Col([ dbc.Card([ html.H5('Opcões'), dcc.Dropdown(opcoes, value = 'ACS' , id='check_opcao', style={'width': '100%'}), ],style={'height': '94vh', 'margin': '20px', 'padding': '20px', 'width': '300px'}) ], sm=2), dbc.Col([ dbc.Row([dcc.Graph( id='grafico_gc_players', style={ 'width': '1100px'})], style={ 'margin': '20px', 'margin-right': '70px'}), dbc.Row([ dbc.Col([dcc.Graph(id='map_pick', figure=fig_pick)], sm=3), dbc.Col([dcc.Graph(id='map_ban', figure=fig_ban)], sm=3), dbc.Col([dcc.Graph(id='map_side_atk', figure=fig_atk )], sm=3), dbc.Col([dcc.Graph(id='map_side_def', figure=fig_def )], sm=3) ]) ],sm=10) ])
{ "language": "en", "url": "https://stackoverflow.com/questions/74061322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to convert webp image to jpeg or png by using intervention image laravel I am developing an app in Laravel Framework (PHP). I want to upload image which have webp format and then convert it to jpeg or png image format. After converting the image i also want to upload it to s3 bucket. A: Firstly we can use Intervention Image library. We must have php 7 and gd library installed. I am writing the commands to install gd library and webp library below (for ubuntu) : sudo apt-get update sudo apt-get install webp sudo apt-get install php7.0-gd (check php version and then install accordingly) now check file extension and if extension is webp, select your output file extension $extension = $this->file->extension(); if($this->file->getMimeType() == 'image/webp'){ $extension = 'png'; } // Generate a random filename $fileName = time() . '_' . strtolower(uniqid()) . '.' . $extension; Now encode the image to desired format if($this->file->getMimeType() == 'image/webp'){ $image = $image->encode($extension); } $image = $image->stream(); Now upload the image to s3 bucket Storage::disk('s3')->put($folderName . '/' . $fileName, $imageNormal->__toString());
{ "language": "en", "url": "https://stackoverflow.com/questions/54899430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Intellij SBT project: How to change the content roots? This is the current content root configuration in my project: However, I want the "scala" directory to be the actual test content root, and not the directory named "test". If I modify it, I get the warning that "Module is imported from Sbt. Any changes in its configuration will may be lost after re-importing." (and, indeed, they are). Unfortunately, I couldn't find where in my Build.scala file (or any other file) this configuration is declared. What I can do to once and for all convince IntelliJ that "scala" is the correct test content root? This is my Build.scala file (this is a Play 2.5.4 project if it matters): import play.routes.compiler.StaticRoutesGenerator import play.sbt.PlayScala import play.sbt.routes.RoutesKeys._ import sbt.Keys._ import sbt._ object Build extends Build { val main = Project("Mp3Streamer", file(".")).enablePlugins(PlayScala).settings( scalaVersion := "2.11.8", version := "1.0-SNAPSHOT", addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full), libraryDependencies ++= Seq( // a bunch of dependencies ), resolvers += Resolver.mavenLocal, javaOptions ++= Seq("-Xmx4000M", "-Xms2024M", "-XX:MaxPermSize=2000M"), routesGenerator := StaticRoutesGenerator ) } A: By adding scalaSource in Test := baseDirectory.value / "test" "/scala", to my Build.scala file, I've been able to make the "scala" folder a test source, but the parent "test" folder was still also a test source: As far as I could tell, this is a setting inherited from Play, since if I removed the .enablePlugins(PlayScala) code, the "test" folder stops being a test source. Following the instructions in https://www.playframework.com/documentation/2.5.x/Anatomy#Default-SBT-layout, I disabled the play layout, and then manually added the source and resource directories, which I copied from https://github.com/playframework/playframework/blob/master/framework/src/sbt-plugin/src/main/scala/play/sbt/PlayLayoutPlugin.scala#L9, only modifying the test source, and adding my own resource folders. My modified Build.scala file is now: val main = Project("Mp3Streamer", file(".")) .enablePlugins(PlayScala) .disablePlugins(PlayLayoutPlugin) .settings( target := baseDirectory.value / "target", sourceDirectory in Compile := baseDirectory.value / "app", // My change sourceDirectory in Test := baseDirectory.value / "test" / "scala", resourceDirectory in Compile := baseDirectory.value / "conf", scalaSource in Compile := baseDirectory.value / "app", // My change scalaSource in Test := baseDirectory.value / "test" / "scala", // I've added this resource resourceDirectory in Test := baseDirectory.value / "test" / "resources", javaSource in Compile := baseDirectory.value / "app", sourceDirectories in(Compile, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Compile).value), sourceDirectories in(Test, TwirlKeys.compileTemplates) := Seq((sourceDirectory in Test).value), // sbt-web sourceDirectory in Assets := (sourceDirectory in Compile).value / "assets", sourceDirectory in TestAssets := (sourceDirectory in Test).value / "assets", resourceDirectory in Assets := baseDirectory.value / "public", // Native packager sourceDirectory in Universal := baseDirectory.value / "dist", // Everything else is the same as the original Build.scala file Honestly, this feels so hacky that I'll probably end up modifying my directory structure to match Play's default... But it's the principle that counts!
{ "language": "en", "url": "https://stackoverflow.com/questions/46001058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why did I lose data when I change the orientation of camera doing crop image? I'm doing an app that takes an image from camera and crop it after, but some how i'm losing the objects of my activity and when it comes back i get NullPointerExeception, on OnCreate method of it. But when i choose an image from gallery it works fine, because it does not close the activity. public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Camera")) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra("return-data", true); startActivityForResult(intent, Constants.PICK_FROM_CAMERA); } else if (items[item].equals("Galeria")) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/*"); // ******** code for crop image intent.putExtra("crop", "true"); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 100); intent.putExtra("outputY", 100); intent.putExtra("max-height", 800); intent.putExtra("max-width", 800); intent.putExtra("return-data", true); intent.putExtra("scaleType", "centerCrop"); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); try { startActivityForResult(Intent.createChooser(intent, "Complete action using"), Constants.PICK_FROM_GALLERY); } catch (ActivityNotFoundException e) { } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bitmap tempImage; OutputStream fOut = null; File root = new File(Environment.getExternalStorageDirectory() + File.separator); try { File sdImageMainDirectory = new File(root, "foto.jpg"); fOut = new FileOutputStream(sdImageMainDirectory); } catch (Exception e) { e.printStackTrace(); } if (requestCode == Constants.PICK_FROM_CAMERA) { root = new File(Environment.getExternalStorageDirectory() + File.separator + "foto.jpg"); Bitmap photo = (Bitmap) data.getExtras().get("data"); saveBitmap(photo, Environment.getExternalStorageDirectory() + File.separator + "foto.jpg"); try{ cropCapturedImage(Uri.fromFile(root)); }catch(ActivityNotFoundException aNFE){ //display an error message if user device doesn't support String errorMessage = "Desculpe, seu dispositivo não suporta Crop!"; Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); toast.show(); } } if (requestCode == Constants.PICK_FROM_GALLERY && data != null) { Bundle extras2 = data.getExtras(); if (extras2 != null) { Bitmap photo = extras2.getParcelable("data"); this.photo.setImageBitmap(photo); this.photo.buildDrawingCache(); tempImage = this.photo.getDrawingCache(); try { tempImage.compress(Bitmap.CompressFormat.JPEG, 100, fOut); fOut.flush(); fOut.close(); BasicUserPerson.getInstance().setPhotoPath( Environment.getExternalStorageDirectory() + File.separator + "foto.jpg"); } catch (Exception e) { e.printStackTrace(); } } } //user is returning from cropping the image else if(requestCode == Constants.PIC_CROP && data != null){ //get the returned data Bundle extras = data.getExtras(); if (extras != null){ Bitmap thePic = (Bitmap) data.getExtras().get("data"); saveBitmap(thePic, Environment.getExternalStorageDirectory() + File.separator + "foto.jpg"); photo.setImageBitmap(thePic); BasicUserPerson.getInstance().setPhotoPath( Environment.getExternalStorageDirectory() + File.separator + "foto.jpg"); } } } public void saveBitmap(Bitmap photo, String path) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes); File f = new File(path); try { f.createNewFile(); FileOutputStream fo = new FileOutputStream(f); fo.write(bytes.toByteArray()); fo.close(); } catch (IOException e) { e.printStackTrace(); } } public void cropCapturedImage(Uri picUri){ Intent cropIntent = new Intent("com.android.camera.action.CROP"); cropIntent.setDataAndType(picUri, "image/*"); cropIntent.putExtra("crop", "true"); cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1); cropIntent.putExtra("outputX", 256); cropIntent.putExtra("outputY", 256); cropIntent.putExtra("return-data", true); cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); startActivityForResult(cropIntent, Constants.PIC_CROP); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dados_pessoais); fullName = (EditText) findViewById(R.id.edtFullName); cpf = (EditText) findViewById(R.id.edtCpf); email = (EditText) findViewById(R.id.edtDadEmail); ddd = (EditText) findViewById(R.id.edtDadDDD); telefone = (EditText) findViewById(R.id.edtDadTele); ddd2 = (EditText) findViewById(R.id.edtDadDDD2); celular = (EditText) findViewById(R.id.edtDadTel); btSalvar = (ImageView) findViewById(R.id.imgSalvar); head = (ImageView) findViewById(R.id.imgDadosHead); sexo = (Spinner) findViewById(R.id.spnSex); birthday = (EditText) findViewById(R.id.edtBrithday); civil = (Spinner) findViewById(R.id.spnCivil); loadingCity = (ImageView) findViewById(R.id.imgLoadingCity); escolaridade = (Spinner) findViewById(R.id.spnEscolaridade); cep = (EditText) findViewById(R.id.edtCep); state = (Spinner) findViewById(R.id.spnState); city = (Spinner) findViewById(R.id.spnCity); endereco = (EditText) findViewById(R.id.edtEndereco); bairro = (EditText) findViewById(R.id.edtBairro); num = (EditText) findViewById(R.id.edtNum); comp = (EditText) findViewById(R.id.edtComp); photo = (ImageView) findViewById(R.id.imgPhoto); btSalvar.setOnClickListener(this); photo.setOnClickListener(this); //Line of error if (!User.getInstance().getFullName().equals("null") && !User.getInstance().getFullName().equals("")){ fullName.setText(User.getInstance().getFullName()); } if (!BasicUserPerson.getInstance().getPersonRegistration().equals("null") && !BasicUserPerson.getInstance().getPersonRegistration().equals("")){ cpf.setText(BasicUserPerson.getInstance().getPersonRegistration()); } if (!User.getInstance().getEmail().equals("null") && !User.getInstance().getEmail().equals("null")){ email.setText(User.getInstance().getEmail()); } email.setKeyListener(null); if (!BasicUserPerson.getInstance().getMobilePhone().equals("null") && !BasicUserPerson.getInstance().getMobilePhone().equals("")){ String tel = BasicUserPerson.getInstance().getMobilePhone().replace("(", "").replace(")", "").replace(" ", ""); ddd.setText(tel.subSequence(0, 2)); celular.setText(tel.substring(2)); } if (!BasicUserPerson.getInstance().getPhone().equals("null") && !BasicUserPerson.getInstance().getPhone().equals("")){ String tel = BasicUserPerson.getInstance().getPhone().replace("(", "").replace(")", "").replace(" ", ""); ddd2.setText(tel.subSequence(0, 2)); telefone.setText(tel.substring(2)); } if (!BasicUserPerson.getInstance().getBirthday().equals("null") && !BasicUserPerson.getInstance().getBirthday().equals("")){ birthday.setText(BasicUserPerson.getInstance().getBirthday()); } if (!BasicUser.getInstance().locationObj.getZipCode().equals("null") && !BasicUser.getInstance().locationObj.getZipCode().equals("")){ cep.setText(BasicUser.getInstance().locationObj.getZipCode()); } if (!BasicUser.getInstance().locationObj.getAddress().equals("null") && !BasicUser.getInstance().locationObj.getAddress().equals("")){ endereco.setText(BasicUser.getInstance().locationObj.getAddress()); } if (!BasicUser.getInstance().locationObj.getNeighborhood().equals("null") && !BasicUser.getInstance().locationObj.getNeighborhood().equals("")){ bairro.setText(BasicUser.getInstance().locationObj.getNeighborhood()); } } And it outputs: 12-15 21:22:55.002: E/AndroidRuntime(2263): FATAL EXCEPTION: main 12-15 21:22:55.002: E/AndroidRuntime(2263): Process: br.com.inradar, PID: 2263 12-15 21:22:55.002: E/AndroidRuntime(2263): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.inradar/br.com.inradar.activities.DadosPessoais}: java.lang.NullPointerException 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread.access$800(ActivityThread.java:139) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.os.Handler.dispatchMessage(Handler.java:102) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.os.Looper.loop(Looper.java:136) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread.main(ActivityThread.java:5103) 12-15 21:22:55.002: E/AndroidRuntime(2263): at java.lang.reflect.Method.invokeNative(Native Method) 12-15 21:22:55.002: E/AndroidRuntime(2263): at java.lang.reflect.Method.invoke(Method.java:515) 12-15 21:22:55.002: E/AndroidRuntime(2263): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 12-15 21:22:55.002: E/AndroidRuntime(2263): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606) 12-15 21:22:55.002: E/AndroidRuntime(2263): at dalvik.system.NativeStart.main(Native Method) 12-15 21:22:55.002: E/AndroidRuntime(2263): Caused by: java.lang.NullPointerException 12-15 21:22:55.002: E/AndroidRuntime(2263): at br.com.inradar.activities.DadosPessoais.onCreate(DadosPessoais.java:176) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.Activity.performCreate(Activity.java:5275) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 12-15 21:22:55.002: E/AndroidRuntime(2263): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166) 12-15 21:22:55.002: E/AndroidRuntime(2263): ... 11 more A: Are you using in this way protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if(resultCode == RESULT_OK) { // stub here } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/27484553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: geofacet package in R adding labels to bar graphs in geofacets I recently discovered the geofacet package in R. Amazing. I have 5 years worth of data for each state. I have horizontal bars in each facet. I am trying to figure out how to add a simple label that shows the value of each bar in each graph such that it sits off to the right of the bar or right side of the facet. I have tried geom_text and a number of code lines but nothing seems to add the labels for each bar in each facet. Below is my code to make the geofacet of the US. Not sure where to add the label code either. Any help is greatly appreciated. This is my last step to complete this awesome map. ggplot(Alabamatest, aes(YEAR, SALES, fill = YEAR)) + geom_bar(alpha=1, width = .75, aes(color =TYPE, fill=TYPE), stat = "identity", position = position_stack(reverse = TRUE) ) + scale_color_manual(values = c("firebrick1", "cornflowerblue"))+ scale_fill_manual(values = c("firebrick1", "cornflowerblue"))+ ylim(0,9 )+ coord_flip() + theme_bw()+ facet_geo(~ state, grid= "us_state_grid4", label ="SALES")+ scale_y_continuous(expand = c(0, 0)) + labs(title = "2019 State Average Sales", caption = "Data Source: Year End Data", x = NULL, y = "Percentage of Voters") + theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(), strip.text.x = element_text(size = 6)) I am adding some test data to run with the code. I am not sure how to add a simple data frame so I have typed it out here. I am brand new to Stackoverflow. Apologies if this is not the correct way to present data state name YEAR SALES TYPE AL ALABAMA 2019 2 POS AL ALABAMA 2018 1.5 POS AL ALABAMA 2017 1.4 NEG AL ALABAMA 2016 1.7 NEG AZ ARIZONA 2019 3 POS AZ ARIZONA 2018 3 POS AZ ARIZONA 2017 2 POS AZ ARIZONA 2016 3.4 POS AZ ARIZONA 2015 5 POS The two states create bar graphs. I want to be able to add the sales label to the right side of the bar graph for each year.
{ "language": "en", "url": "https://stackoverflow.com/questions/60435659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How much does minifying reduce file size? In a React app, is it possible to find out how much Webpack's minification reduces the project's size excluding all the dependencies and packages not written by the project's developer? My build/static/ directory is currently bigger than my src directory and I believe it is because code from the dependencies is also minified with the files of interest. Where could I find something to approximately compare my src directory size to? A: I built the project with npm run build to find out how large the output is with minimization enabled. Then I edited node_modules/react-scripts/config/webpack.config.js and changed line 189 (the line with the minimize property) from: ... optimization: { minimize: isEnvProduction, minimizer: [ ... to: ... optimization: { minimize: false, minimizer: [ ... to disable minimization. Then built the project again to find out its size without minimization. You can compare the built file sizes manually to find out their difference, but you will also get a nice output to the terminal when building the second time: File sizes after gzip: 613.36 KB (+504.48 KB) build\static\js\2.0ddf8239.chunk.js 60.24 KB (+20.01 KB) build\static\js\main.8e9dd59c.chunk.js 4.73 KB (+457 B) build\static\css\main.aaaa4d7d.chunk.css 1.66 KB (+933 B) build\static\js\runtime~main.7f8cc4df.js Notice the differences stated in parantheses.
{ "language": "en", "url": "https://stackoverflow.com/questions/59599422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory issue when create a diagonal numpy array I have created a diagonal numpy array: a = numpy.float32(numpy.random.rand(10)) a = numpy.diagonal(a) However, I face MemoryError since my matrix is extremely large. Is there anyway to save the memory? A: The best way to handle this case is to create a sparse matrix using scipy.sparse.diags as follows: a = numpy.float32(numpy.random.rand(10)) a = sparse.diags(a) If the shape of your diagonal numpy array is n*n, utilizing sparse.diags would result in a matrix n times smaller. Almost all matrix operations are supported for sparse matrices.
{ "language": "en", "url": "https://stackoverflow.com/questions/74200379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: When is the appropriate moment in rotation to change the Layout parameters of a UICollectionView Hopefully a simple question for a relatively new UIKit control I have a UICollectionView that has a viewLayout with a single row of cells that are the exact height of the UICollectionView bounds in Portrait mode Therefore, when the iPad is flipped to Landscape mode, that row becomes taller than the screen itself, at which point the layout (almost) silently fails and complains that the row is taller than the bounds. What is the ideal way to manipulate the characteristics of the viewLayout, particularly as it relates to responding to rotation in a ViewController? A: I'm working on a similar problem. Currently, my UICollectionViewController has two instance variables of UICollectionViewFlowLayout, each with the appropriate insets for portait or landscape. On rotation, I do this: -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ if (UIDeviceOrientationIsPortrait(toInterfaceOrientation)) { [_itemCollection setCollectionViewLayout:_portraitLayout]; [_itemCollection reloadData]; } else { [_itemCollection setCollectionViewLayout:_landscapeLayout]; [_itemCollection reloadData]; } } The only problem that I'm having is that it randomly crashes with exc_bad_access on setCollectionViewLayout randomly. Something like the above might work for you. I'm not sure if this is the right way to do things. I have only recently started using UICollectionViews.
{ "language": "en", "url": "https://stackoverflow.com/questions/12606570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Python PyAutoGUI (automatic mouse macro) I want to display the (x.y) coordinates of the mouse found using "pyautogui.position()" on the window. What command should I use in this case? A: If you want to print out the x,y mouse positions, you can use .position() like so: print(pyautogui.position()) It will output something like (346, 653) (the numbers will be different, and this is just an example) where the first value is the x coordinate of the cursor, and the second value being the y coordinate.
{ "language": "en", "url": "https://stackoverflow.com/questions/68431430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: React Router v4 - How to dynamically use layouts To start, I'm both new to React and React-Router. I know the basics of each. Here is my scenario... I want to have a separate login page with NO layouts at route (/login). When the user logs in, I want to route them to /home. This home page and every other page (beside login) will reuse a layout that contains a navbar and a sidebar. How do I hide the reusable layout when the user visits the /login route? Do I use a conditional or is there a specific React-Router 'WAY'? I couldn't find examples in the documentation that fit my scenario. Thanks a bunches! A: If you are asking how could I render navbar and sidebar to all components except login, then you can check the browser url. There are many ways of doing this, but one of which is like following: <Route path="*" render={props => <Layout {...props} />} /> This will appear for all your routes now. Then inside Layout, you can check the route, and only render something if the route does not equal to login. render(){ if(this.props.location === "login"){return null} ... } While typing this, you can do it directly in React Router, maybe excluding certain route.
{ "language": "en", "url": "https://stackoverflow.com/questions/51529481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Maps API-Key in gmaps4rails Why don't I have to supply my own gmaps-api-key in gmaps4rails? A: Actually, you don't need the API key because, Google Maps Javascript API V3 is used there. Only Google maps Javascript V2 requires an api-key, and it's deprecated now.
{ "language": "en", "url": "https://stackoverflow.com/questions/5042829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java regex for word with dot I need to a regex to validate a string like "foo.com". A word which contains a dot. I have tried several but could not get it work. The patterns I have tried: * *(\\w+\\.) *(\\w+.) *(\\w.) *(\\W+\\.) Can some one please help me one this. Thanks, A: Use regex with character class ([\\w.]+) If you just want to contain single . then use (\\w+\\.\\w+) In case you want multiple . which is not adjacent then use (\\w+(?:\\.\\w+)+) A: To validate a string that contains exactly one dot and at least two letters around use match for \w+\.\w+ which in Java is denoted as \\w+\\.\\w+ A: This regex works: [\w\[.\]\\]+ Tested for following combinations: foo.com foo.co.in foo... ..foo A: I understand your question like, you need a regex to match a word which has a single dot in-between the word (not first or last). Then below regex will satisfy your need. ^\\w+\\.\\w+$
{ "language": "en", "url": "https://stackoverflow.com/questions/39158902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Restricting one view on Flask-Admin? I have a single file for a Flask application, views.py. Inside views.py, I have the setup for Flask-Admin and the corresponding sqlalchemy database here: db = SQLAlchemy(flaskapp) def build_db(): import random import datetime db.drop_all() db.create_all() # Create sample Users testuser = [] testgroup = [] testlevel = [] user_list = [] for i in range(len(testuser)): user = User() user.testuser = testuser[i] user.testlevel = testlevel[i] user.testgroup = testgroup[i] user_list.append(user) db.session.add(user) for user in user_list: entry = random.choice(sample_text) # select text at random post = Post() post.user = user post.title = entry['title'] post.text = entry['content'] tmp = int(1000*random.random()) # random number between 0 and 1000: post.date = datetime.datetime.now() - datetime.timedelta(days=tmp) post.tags = random.sample(tag_list, 2) # select a couple of tags at random db.session.add(post) db.session.commit() return # Create models class User(db.Model): id = db.Column(db.Integer, primary_key=True) testuser = db.Column(db.String(100)) testgroup = db.Column(db.String(100)) testlevel = db.Column(db.String(100)) # Required for administrative interface. For python 3 please use __str__ instead. def __repr__(self): return self.testuser class UserInfo(db.Model): id = db.Column(db.Integer, primary_key=True) key = db.Column(db.String(64), nullable=False) value = db.Column(db.String(64)) user_id = db.Column(db.Integer(), db.ForeignKey(User.id)) user = db.relationship(User, backref='info') def __repr__(self): return '%s - %s' % (self.key, self.value) ### Attempt at doing something... class MyView(ModelView): @expose('/admin/userview', methods=('GET', 'POST')) def adminview(): return "yes" ##ADMIN admin = Admin(flaskapp, name="Test Aptly") admin.add_view(MyView(User, db.session)) The Question. How do I block access to the "/admin/userview" page depending on what level the user is (defined with the database "testlevel")? Users have 3 qualities, An example for two users would be: testuser testgroup testlevel joe it admin john dev basic How would I restrict the admin page to only let people with testlevel="admin"? Do I use Flask-Security? Flask-Principal? If so, how? I've been tinkering with both for a little bit and I haven't gotten anything working so far. Here's an example "/admin/userview" looks like: example Flask-Admin First of all, you can use various class-level properties to configure what should be displayed and how. For example, column_list can be used to show some of the column or include extra columns from related models. For example: class UserView(ModelView): # Show only name and email columns in list view column_list = ('name', 'email') # Enable search functionality - it will search for terms in # name and email fields column_searchable_list = ('name', 'email') # Add filters for name and email columns column_filters = ('name', 'email') Alternatively, you can override some of the ModelView methods and implement your custom logic. For example, if you need to contribute additional field to the generated form, you can do something like this: class UserView(ModelView): def scaffold_form(self): form_class = super(UserView, self).scaffold_form() form_class.extra = wtf.TextField('Extra') return form_class Check flask.ext.admin.contrib.sqlamodel documentation for list of configuration properties and methods. Thanks! A: I'll assume that you subclassed BaseView to create your admin view and that you are using Flask-login. Then override the is_accessible method in your view class, to check the current user's quality: from flask.ext.admin.base import BaseView from flask.ext.login import current_user class MyView(BaseView): def is_accessible(self): return current_user.testlevel == 'admin' Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/24742144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The method in the type is not applicable for the arguments (even though they are?!) I'm trying to call a method using parameters that definitely match my args, yet I get this error... The method getAdministratablePaging(Long, ContentFilter, int, int, Integer, Integer) in the type ContentService is not applicable for the arguments (Long, ContentFilter, int, int, Integer, Integer) The code is... ResultPage knowledgeCenters = _kcs.getAdministratablePaging(ContentConstants.KNOWLEDGE_ROOT, filter, 0, Constants.COUNT_ALL, ContentConstants.COLUMN_SIZE, Constants.SORT_ORDER_ASCENDING); I'm working in Eclipse and have tried Clean and rebooting the IDE. Suggestions much appreciated! A: Just putting my comment as an answer in case it can help somebody seeing this question in the future. When you see a message like this, then the only possibility is that there are multiple types of one of the parameter objects. In this case, @nscoppin had two different definitions for ContentFilter. Either import the correct one, or use the fully qualified name in the method call, ie someMethod(com.packageA.subPackage.ContentFilter);
{ "language": "en", "url": "https://stackoverflow.com/questions/28349321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: what is the dpdk0's effect in ovs-dpdk? today i get other guy's confiuration about ovs-dpdk,the config file is below: dpdk-devbind –s dpdk-devbind --force --bind=ixgbe 0000:81:00.0 dpdk-devbind --force --bind=ixgbe 0000:81:00.1 dpdk-devbind --force --bind=igb_uio 0000:81:00.0 dpdk-devbind --force --bind=igb_uio 0000:81:00.1 ovs-vsctl del-port br-eth6 eth6 ovs-vsctl del-port br-eth9 eth9 ovs-vsctl -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1 ovs-vsctl -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1 ovs-vsctl -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1 the config file describe about take eth6 and eth9 ethernet interface to ovs bridge br-eth6 and br-eth9 but i wonder to know why set interface dpdk0's type to dpdk ? Does the port dpdk0 is a specific port or something else? I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. A: Based on the comments discussion, the problem turned out to be the configuration file sequence. Recommend approach of removing the Kernel Ports, then binding with dpdk compatible driver works ovs-vsctl del-port br-eth6 eth6 ovs-vsctl del-port br-eth9 eth9 dpdk-devbind –s dpdk-devbind --force --bind=ixgbe 0000:81:00.0 dpdk-devbind --force --bind=ixgbe 0000:81:00.1 dpdk-devbind --force --bind=igb_uio 0000:81:00.0 dpdk-devbind --force --bind=igb_uio 0000:81:00.1 ovs-vsctl -- set Interface dpdk0 type=dpdk options:dpdk-devargs= 0000:06:00.0,n_rxq=1 ovs-vsctl -- set Interface eth6 type=dpdk options:dpdk-devargs= 0000:81:00.0,n_rxq=1 ovs-vsctl -- set Interface eth7 type=dpdk options:dpdk-devargs= 0000:81:00.1,n_rxq=1
{ "language": "en", "url": "https://stackoverflow.com/questions/64909264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GreG nested templates We need to nest templates in the main template. The nested template should be able to display fields that the customer can fill. For example, there are two attachments to this message. The file 1.jpg: In this picture you can see how it displays a button with the plus sign. It has a red arrow. When I press the button it shows a nested template. In this template I can fill the event type and a path field, and nothing else. In our case we need to display fields that the user can fill, and the option of add more templates nested within the nested template. In the picture 2.jpg you can see the result that we need. This image 2 shows a red arrow that point to a green button. If you press the green button it displays another nested template. In this template you can fill in more fields. In addition you have another green button to nest another template. Summarizing we need to create complex templates, that is, templates included in a main template. A: If you mean RXT nesting by nested templates, WSO2 Governance Registry does not support nested RXTs as of now.
{ "language": "en", "url": "https://stackoverflow.com/questions/10813762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP preg_match: exclude whitespaces I'm working on some code block that validates a config file containing PHP variable. I want to detect variables left empty using preg_match. If the file contains the following lines: $db_host = "blablah"; $db_host ='blablah'; $db_host=''; $db_host=" "; $db_host=""; I'd like to match only lines 3-4-5, lines 1 and 2 being valid (no empty value). The following preg_match works well but matches all lines, not handling the whitespaces or empty values; how could I match only empty/whitespaced values? preg_match( '#\$db_host(\ +)?\=(\ +)?(\'|\")(.*?)(\'|\");#i', $string ); Note: I'd rather not included the files to validate to check their validity. There might be a lot of them and I can't assume I'll always have control on their content. I'd rather not include unknown, third party code into my own. A: How should your regex check something like this?: $a = ''; $b = $a; $c = preg_replace('/.*/', $a); You should use PHP to check the variables and not a regex: include 'config.php'; foreach(array( 'db_host', 'db_pass', ... ) as $varname) { $value = trim($$varname); if(empty($value)) { die($varname . ' must not be empty'); } } Also you should use trim() to avoid variables containing just whitespace content. (thanks @SamuelCook) A: Why use preg_match when you can use trim() & empty() to check if it's empty or not. Take the following examples: <?php $str[0] = ' '; $str[1] = "\t"; $str[2] = "\r\n"; foreach($str as $k=>$val){ $val = trim($val); if(empty($val)){ echo $k.' is empty<br>'; } } They will all return empty. A: You can use this pattern: $pattern = '~\$db_host\s*=\s*(["\'])\s*\1\s*;~'; \s* means "any white character zero or more times". White characters are spaces, tabs, carriage returns and newlines, but if you want, you can replace \s by \h that matches only horizontal white characters (i.e. tabs and spaces). I put the type of quote in a capturing group with (["\']) and then I use a backreference to this group with \1 (1 because it is the first capturing group of the pattern).
{ "language": "en", "url": "https://stackoverflow.com/questions/20526644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP 7.1 on hosted server not recognizing session.save_path I am pulling my hair out over this issue. It seems simple enough, but the following simple script is not working for me. I want to keep my session files in the directory as indicated. I have the 'musanizer_session_tmp' folder in the same root with this php script: if (!isset($_REQUEST['testit'])) { ini_set ('session.auto_start' , '1' ); ini_set('session.save_path', '../musanizer_session_tmp'); $_SESSION['tester'] = 'Testing Session Save Path! '; echo '<script language="Javascript">'; echo 'window.location.href="sesstest.php?testit=YES"'; echo '</script>'; } else { echo "===>>> ". $_SESSION['tester'].date('H:i:s'); } Isn't that fairly straightforward and correct?
{ "language": "en", "url": "https://stackoverflow.com/questions/51000840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is "undefined" in Javascript an error or just a notice? Is the undefined message in the pop up or console log (e.g. when calling a variable that doesn't exist) an ERROR message or just a NOTICE message? In PHP there is a difference, so, looking for your explanation on this subject. A: Neither, it is a value (or a stringification of a value in the case of an alert) Whether or not you can ignore the fact that a variable/property/whatever is undefined depends on the needs of the program you are writing. If a message displays "undefined" when it should display "sweet cuppin' cakes", then that would be a logic error; conversely, if a message displays undefined when it is merely intended to reflect an internal state that can legitimately be undefined, it would not be an error. A: It sounds to me like an incomplete error message; like when a developer prints "This should never appear!11" Undefined is nothing more than a value, so seeing it on its own does not assign any meaning or importance to the message. A: 'undefined' means exactly what it says - you have referenced a variable name that is not defined. Some languages, like Python, are stricter about this kind of thing, and will throw an error if you try to do this. Javascript assumes you know what you are doing, and so doesn't complain. A: undefined is a special data type. For example, a common case is a missing parameter in a function call: var foobar = function(val) { alert(typeof val); // alerts 'undefined' alert(foobar.length); // throws an error } foobar(); The author of this example function should have checked for the type of val before trying to access the length property. A: Undefined is, what its name says, a sign for something beeing not defined, like var a=new Array(10); It is an array: Array.isArray(a)is true, a.length is 10; but all it contains are undefined values: e.g. a[5] is undefined. So it is no error. ERROR message or just a NOTICE message? Neither nor.
{ "language": "en", "url": "https://stackoverflow.com/questions/25815760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do i remove or merge duplicated values in my JSON List? My Json looks like this, [ { "MatchNumber": 1, "RoundNumber": 1, "HomeTeam": "Crystal Palace", "AwayTeam": "Liverpool", "Group": null, "HomeTeamScore": 0, "AwayTeamScore": 2 }, { "MatchNumber": 16, "RoundNumber": 2, "HomeTeam": "Fulham", "AwayTeam": "Liverpool", "Group": null, "HomeTeamScore": 2, "AwayTeamScore": 2 }, { "MatchNumber": 11, "RoundNumber": 2, "HomeTeam": "Arsenal", "AwayTeam": "Leicester", "Group": null, "HomeTeamScore": 4, "AwayTeamScore": 2 }, { "MatchNumber": 191, "RoundNumber": 20, "HomeTeam": "Arsenal", "AwayTeam": "Leeds", "Group": null, "HomeTeamScore": null, "AwayTeamScore": null } ] for this Json example, using this list will produce 2 Arsenal in the HomeTeam and 2 Liverpool AwayTeam in the dropdown list. here's my controller code so far, i tried set but it only reordered the list, didn't remove duplicated teams. @Controller public class CCController { private static final String MAIN_PAGE = "main"; private static final String JSON_URL = "https://randomfootball.com/json/epl-2022"; @GetMapping("/") public String main(Model model, @ModelAttribute Team team){ List<Team> teams = (List<Team>) parsingService.parse(JSON_URL); Set<Team> targetSet = new HashSet<>(teams); model.addAttribute("teamList", targetSet); return MAIN_PAGE; } } here is my Team model, added as per request. thanks for any guidance public class Team{ public Team() { } Set<String> HomeTeam; public Set<String> getHomeTeam() { return HomeTeam; } public void setHomeTeam(Set<String> homeTeam) { HomeTeam = homeTeam; } public static Set<String> keySet() { return null; } } I finally got a list that doesn't duplicate. I did it by getting the object from the array of Json. Build that into JsonArray, then use set. That requires a dependency, jakarta.json.
{ "language": "en", "url": "https://stackoverflow.com/questions/73458240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do I have to do a dispatch again or why is my code not running? I am trying to make it so when I do an ajax request my preload shows up when a request finishes(success or not) it goes away. I am using Axios and they have interceptors for request and response. I am trying to do request right now. import axios from "axios"; import {setPreLoader} from './PreLoaderActions.js'; export const axiosInstant = axios.create({ baseURL: 'http://localhost:54690/api', timeout: 2000, }); export const config = axiosInstant.interceptors.request.use( config => { // Do something before request is sent console.log('afaf'); setPreLoader(true); return config; }, function (error) { // Do something with request error // this.setPreLoader(false); return Promise.reject(error); }); import {actions} from './Actions.js'; export function setPreLoader(show) { return function (dispatch) { dispatch({ type: actions.SHOW_PRE_LOADER, payload: { showPreLoader: show } }); }; } when my setPreloader(true) gets hit nothing happens. Nothing is dispatched. Not sure if I need to do something else as I only ever done this in a react component so redux/reactjs might be doing something for me behind the scenes. A: The setPreLoader function doesn't do anything itself beside returning another anonymous function. Therefore, just calling setPreLoader(true) does nothing because the anonymous function is not called. You have to call the result of setPreLoader(true) with appropriate function: setPreLoader(true)(someFunction)
{ "language": "en", "url": "https://stackoverflow.com/questions/39047803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Write the content of an object into a file in C++ I'm using OpenCV, and I am computing the histogram of some images, which is contained inside a class named CvHist. I have a CvHist object, but I want to store it to use it later on in another file. How can I do that? Thank you A: Actually, in OpenCV there is a specific way to do that. You can write an object in an XML file as follow: CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_WRITE); cvWrite(storage, "histogram", global_histogram); and read is as such: CvHistogram* global_histogram; CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_READ); global_histogram = (CvHistogram *)cvReadByName(storage, 0, "histogram" ,0); A: The Boost Serialization library is pretty nice. It may do what you want. http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html A: 1) Decide on a file format, plan it at the byte level (If an existing format is suitable, prefer it). 2) Write out the data in the file format you decided on. A: You can add a method to the class called Serialise, something along the lines of the following: CvHist::Serialise( std::string fName, bool read ) { if ( read ) { std::ifstream fStream( fName ); // Read in values from file, eg: fStream >> this->param1; fStream >> this->param2; // ...etc } else { std::ofstream fStream( fName, ios::trunc ); // (ios::trunc clears file) // Read out values into file, eg: fStream << this->param1; fStream << this->param2; // ...etc } } Note, the order is important - the order that you read the various parameters from the file must match the order you write parameters to the file. Also remember to #include <fstream> Now, to create a CvHist object populated with data from a file data.txt you can simply write this: CvHist object; object.Serialise( "data.txt", true ); If you've populated an object and want to store it in a file, this time, say, bob.dat, write this: // (object has been populated with data previously) object.Serialise( "bob.dat", false );
{ "language": "en", "url": "https://stackoverflow.com/questions/9561135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opendiff and online file I'd like to make a diff between to file, one is local and the other is online using for example opendiff http://www.tex.ac.uk/ctan/web/lua2dox/Doxyfile Doxyfile But it throw the following error : 2014-02-12 15:23:43.579 opendiff[72650:1007] /Users/Dev/Joker/http:/www.tex.ac.uk/ctan/web/lua2dox/Doxyfile does not exist So how can I use a online file the same way as a local one ? A: Since this is a programming Q&A site, we may as well write a program to do this for us :-) You can create a script called (for example) odw for OpenDiffWeb which will detect whether you're trying to access web-based files and first download them to a temporary location. Examine the following script, it's pretty rudimentary but it shows the approach that can be taken. #!/bin/bash # Ensure two parameters. if [[ $# -ne 2 ]] ; then echo Usage: $0 '<file/url-1> <file/url-2>' exit 1 fi # Download first file if web-based. fspec1=$1 if [[ $fspec1 =~ http:// ]] ; then wget --output-document=/tmp/odw.$$.1 $fspec1 fspec1=/tmp/odw.$$.1 fi # Download second file if web-based. fspec2=$2 if [[ $fspec2 =~ http:// ]] ; then wget --output-document=/tmp/odw.$$.2 $fspec2 fspec2=/tmp/odw.$$.2 fi # Show difference of two files. diff $fspec1 $fspec2 # Delete them if they were web-based. if [[ $fspec1 =~ /tmp/odw. ]] ; then rm -f $fspec1 fi if [[ $fspec2 =~ /tmp/odw. ]] ; then rm -f $fspec2 fi In this case, we detect a web-based file as one starting with http://. If it is, we simply use wget to bring it down to a temporary location. Both files are checked this way. Once both files are on the local disk (either because they were brought down or because thet were already there), you can run the diff - I've used the standard diff but you can substitute your own. Then, the temporary files are cleaned up. As a test, I downloaded the page http://www.example.com and made a very minor change to it then compared the page to my modified local copy: pax> odw http://www.example.com example.txt --2014-09-25 16:40:02-- http://www.example.com/ Resolving www.example.com (www.example.com)... 93.184.216.119, 2606:2800:220:6d:26bf:1447:1097:aa7 Connecting to www.example.com (www.example.com)|93.184.216.119|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 1270 (1.2K) [text/html] Saving to: `/tmp/odw.6569.1' 100%[=================================>] 1,270 --.-K/s in 0s 2014-09-25 16:40:02 (165 MB/s) - `/tmp/odw.6569.1' saved [1270/1270] 4c4 < <title>Example Domain</title> --- > <title>Example Domain (slightly modified)</title> Now there's all sorts of added stuff that could go into that script, the ability to pass flags to the diff and wget programs, the ability to handle other URL types, deletion of temporary files on signals and so on. But it should hopefully be enough to get you started.
{ "language": "en", "url": "https://stackoverflow.com/questions/21730948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hand-create images in javascript and draw with respect to the alpha channel? I'm currently trying to create a page with dynamically generated images, which are not shapes, drawn into a canvas to create an animation. The first thing I tried was the following: //create plenty of those: var imageArray = ctx.createImageData(0,0,16,8); //fill them with RGBA values... //then draw them ctx.putImageData(imageArray,x,y); The problem is that the images are overlapping and that putImageData simply... puts the data in the context, with no respect to the alpha channel as specified in the w3c: pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc. So I thought, well how can I use Images and not ImageDatas? I tried to find a way to actually put the ImageData object back into an image but it appears it can only be put in a canvas context. So, as a last resort, I tried to use the toDataURL() method of a 16x8 canvas(the size of my images) and to stick the result as src of my ~600 images. The result was beautiful, but was eating up 100% of my CPU...(which it did not with putImageData, ~5% cpu) My guess is that for some unknown reason the image is re-loaded from the image/png data URI each time it is drawn... but that would be plain weird... no? It also seems to take a lot more RAM than my previous technique. So, as a result, I have no idea how to achieve my goal. How can I dynamically create alpha-channelled images in javascript and then draw them at an appreciable speed on a canvas? Is the only real alternative using a Java applet? Thanks for your time. A: Not knowing, what you really want to accomplish: Did you have a look at the drawImage-method of the rendering-context? Basically, it does the composition (as specified by the globalCompositeOperation-property) for you -- and it allows you to pass in a canvas element as the source. So could probably do something along the lines of: var offScreenContext = document.getCSSCanvasContext( "2d", "synthImage", width, height); var pixelBuffer = offScreenContext.createImageData( tileWidth, tileHeight ); // do your image synthesis and put the updated buffer back into the context: offScreenContext.putImageData( pixelBuffer, 0, 0, tileOriginX, tileOriginY, tileWidth, tileHeight ); // assuming 'ctx' is the context of the canvas that actually gets drawn on screen ctx.drawImage( offScreenContext.canvas, // => the synthesized image tileOriginX, tileOriginY, tileWidth, tileHeight, // => frame of offScreenContext that get's drawn originX, originY, tileWidth, tileHeight // => frame of ctx to draw in ); Assuming that you have an animation you want to loop over, this has the added benefit of only having to generate the frames once into some kind of sprite-map so that in subsequent iterations you'll only ever need to call ctx.drawImage() -- at the expense of an increased memory footprint of course... A: Why don't you use SVG? If you have to use canvas, maybe you could implement drawing an image on a canvas yourself? var red = oldred*(1-alpha)+imagered*alpha ...and so on... A: getCSSCanvasContext seems to be WebKit only, but you could also create an offscreen canvas like this: var canvas = document.createElement('canvas') canvas.setAttribute('width',300);//use whatever you like for width and height canvas.setAttribute('height',200); Which you can then draw to and draw onto another canvas with the drawImage method.
{ "language": "en", "url": "https://stackoverflow.com/questions/4117992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: implement array.prototype.reduce() on string I have some confusion regarding how reduce operation takes place on a string .First a new Str instance is created and sends desired string as a parameter. Then using split method it splits into an array of string.A reduceIt method takes the array and execute a reduce operation which returns the array element which has height length. It works fine with a two element array.But if there is more than two elements it returns NAN. Why it returns NAN for array having more than two elements?? function Str(text){ this.text=text.split('\n'); } Str.prototype.reduceIt = function() { return this.text.reduce(function(first,last,index,arr) { return Math.max(first.length,last.length); }); }; var t=new Str('i am a boy\n she loves cats\n a goat ate my flower garden '); console.log(t.reduceIt()); A: The first time the callback is called first is a string (the first element in the array), and your function makes sense when first and last are both strings, so it works when the callback is only called once (the array has at most 2 elements). The second time it is called it is the result of the previous call, a number. When you call first.length on a number you get undefined and when you call Math.max on that you get NaN. If you want to find the length of the longest string in your array, you could use: Math.max.apply(Math, this.text.map(function (str) { return str.length; })); A: Some good answers already. :-) The simple way to fix your problem is to supply an initial value of 0, then compare the returned value with the length of the new string, so: Str.prototype.reduceIt = function() { return this.text.reduce(function(first,last,index,arr) { // Compare current value (first) with length of string return Math.max(first,last.length); }, 0); // supply 0 as the initial value }; It might make things clearer to rename first to maxSoFar and last to currentString. A: Why it returns NAN for array having more than two elements?? Because number.length is undefined, let's name your function foo and follow how it's invoked * *foo(0, "i am a boy") gives NaN *foo(NaN, " she loves cats") gives NaN *foo(NaN, " a goat ate my flower garden ") gives NaN Giving a final result of NaN. This happens because number.length is undefined and Math.max(undefined, x) is NaN It looks like you wanted to write a function which only takes the length of the second arg function foo(a, b) { return Math.max(a, b.length); } In this case, you'll get * *foo(0, "i am a boy") gives 10 *foo(10, " she loves cats") gives 15 *foo(15, " a goat ate my flower garden ") gives 29 Giving a final result of 29.
{ "language": "en", "url": "https://stackoverflow.com/questions/25881774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add partition in presto? In hive I can do it by: ALTER TABLE xxx ADD PARTITION (datehour='yy') LOCATION 'zz'; How can I do it in presto? A: Currently, Presto Hive connector does not provide means for creating new partitions at arbitrary locations. If your partition location is under table location, you can use Presto Hive connector procedures: * *system.create_empty_partition -- creates a new empty partition with specified values for partition keys *system.sync_partition_metadata -- synchronizes partition list in Metastore with the partitions on the storage If you want to create/declare partitions somewhere else than under table's location, please file an issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/56319510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when retrieving office 2007 files from sql server 2005 blob I have a simple document storage database that allows people to upload various types of documents and then do a full-text search on them. It works just fine for all documents except office 2007 documents. My retrevial code uses content type "application/octet-stream", the server has the MIMETypes registered as does my computer. I can open the file just fine on my system, but uploading it and then redownloading it gives an error: "This error can be caused by some of the following conditions: * *Your hard drive or floppy drive has a corrupt section (damaged track or sector). *A temporary operating system or network failure has occurred. *Your network is unavailable, slow, or is corrupting data packets (failure of a router, network card, or noise on the network transmission line). If the network is experiencing problems, it is usually a temporary condition and if you wait a short period of time and try again, you can usually save the file. If the problem persists, consult your network administrator" A: It would be tough for others to have debugged this, but when I created a byteStream, I used length, instead of length - 1. For some reason in almost all documents this is no problem, but office 2007 threw a fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/2774868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using an external tool for C# builds in Visual Studio When using Visual Stdio 2008, you can make a C++ project build with an internal tool rather than having the IDE invoke MSVC directly. This improves the consistency of builds across platforms if a cross-platform build system is used. However, I cannot figure out how to do the same as a C# project. It would be possible to simply register it as a native project with C# sources, however, you lose some of the advantages gained through having a C# project. More importantly, it will mean that allowing a project to build both directly and with an external tool (which is sadly necessary) will require two separate projects, rather than merely creating an alternate build configuration to invoke the external tool. Does anyone know if it's possible to prevent Visual Studio from invoking csc by itself and instead call an external tool? EDIT: Apparently there has some misunderstanding. The goal here is not to compile anything outside of Visual Studio. Instead, it's to allow Visual Studio to serve as the IDE but not the build system. There is already a (Scons-based) build system capable of compiling the C# and C++ sources, and Visual Studio has been configured to invoke Scons for compilation of C++ projects. I'm trying to configure it so that when you hit the 'Build' button, it will invoke Scons for the C# projects as well as the C++ ones. A: Edit: Your question is still answered using MSBuild(if you are simply looking to compile outside the IDE). The IDE(Visual Studios) is simply a "fancy" way of constructing the build files that are built by MSBuild. Visual Studios isn't building the files, it simply is invoking MSBuild which ships with the .NET Framework 2.0 and up which compiles your code based on the project file that you create. If Scons can read and process an MSBuild file then I'm sure you can invoke it to build your project. But considering the fact that C# is a Microsoft language, I think you will be hard-pressed to find a value-add in not using MSBuild since I'd assume both the language and build tool are very tuned to work together. - End Edit You can use MSBuild to compile your C# project. If you open your .csproj file in a text editor you will see that it is a MSBuild file. If you want to write some C# outside of the IDE you can construct a build file using the .csproj file as a starting point and invoke MSBuild to compile your apps. The IDE is just a way of abstracting the editing of the MSBuild file away for you. If you are really industrious you can create a set of custom tasks to do things in your custom build process like move files around and versioning. MSBuild Community Tasks are a great example of using custom code to do task for you during MSBuild. A: Given all the other answers, what MSBuild does when either VS or MSBuild perform a build can be found in the Targets files that ship with .Net. These can be be found in the FrameWork directory on your system. In my case: C:\Windows\Microsoft.NET\Framework64\v3.5 Contains Microsoft.Common.targets among others. This file contains the following snippit: <!-- ============================================================ Build The main build entry point. ============================================================ --> <PropertyGroup> <BuildDependsOn> BeforeBuild; CoreBuild; AfterBuild </BuildDependsOn> </PropertyGroup> <Target Name="Build" Condition=" '$(_InvalidConfigurationWarning)' != 'true' " DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/> This means that redifining this Target you can make MSBuild an VS do anything you want. The top of the mentioned file contains an important messagge: Microsoft.Common.targets WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have created a backup copy. Incorrect changes to this file will make it impossible to load or build your projects from the command-line or the IDE. This file defines the steps in the standard build process for .NET projects. It contains all the steps that are common among the different .NET languages, such as Visual Basic, C#, and Visual J#. My suggestion would be to read all you can about MSBuild and it's build file syntax and try redifining the Build target in your project(s). My impression is that after reading up on MSBuild you'll probably find an easier way to meet your requierements. You can find an example of redifining a Target like this in one of the answers of this so question . Edit: How to redefine a target? Redefining is essentially defining the same target 'after' it has been defined. So for instance in your .*proj file(s) define a Build Task after the <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> line that imports all targets needed to in this case build a C# project. An example could be <Target Name="Build" Condition=" '$(_InvalidConfigurationWarning)' != 'true' " DependsOnTargets="BeforeBuild" Outputs="$(TargetPath)"> <Exec Command="nmake" /> </Target> A: I found a question in the same direction here, where it is suggested to edit the registry. I am pretty sure there is no other way to change the compiler used by Visual Studio because there is no trace of csc.exe in any solution, config, csproj file or whatsoever, nor in the Visual Studio 9.0 folder / subfolders within the Program Files dir. Registry locations can be found in: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\74ACAA9F1F0087E4882A06A5E18D7D32 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\9055DA7481CC1024CB23A6109FD8FC9B but those keys may differ dependng on your installation. Conclusion: changing the compiler used by VS seems next to impossible. Addition: The following MSDN article deals with the same question for an custom C++ compiler, and Ed Dore's answer seems to confirm my theory that there's no way to choose an custom compiler for use within VS. A: Under 'Tools' > 'External Tools' you should be able to define an outside tool to do activities for you. The Command should be the path to the executible for your external tool. Hope this helps some. A: You don't have to maintain different project files to build using an external tool. MSBuild is designed to build using the same project files that Visual Studio uses. Here's an article that describes it. Customize Your Builds in Visual Studio Using the Standalone MSBuild Tool It's for VS2005, but should apply to VS2008 as well. A: You can build your solution from the command line like this: C:\WINDOWS\Microsoft.NET\Framework\v3.5>msbuild.exe "C:\path\Your Solution.sln" A: Edit your project file and update the CscToolPath keys to point to the directory containing your tool and add CscToolExe keys that holds the name of the directory: <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|.NET 3.5' "> . . . <CscToolPath>path\to\custom\tool\directory</CscToolPath> <CscToolExe>exe name</CscToolExe> . . . </PropertyGroup> I have not tested this, and the CscToolExe key may cause problems, in which case I would simply rename the external tool executable to "csc.exe". A: Looking through the answers, it seems clear to me that integrating scons into Visual Studio in a way that is compatible with the debugger and so on is not going to happen... An option you might to consider, and I understand you don't want to change build systems, but bear with me, is to use a meta-build system, ie 'cmake'. http://www.cmake.org/ Cmake doeesn't actually build the project. What it does is to create build files for you, that you can use to build the project, and on Windows, the build files it creates for you are: Visual Studio project files. You can simply load those directly into your IDE, and compile, and use normally! CMake is I feel very easy to use, and provides a high level of transparence and maintainability. The exact same CMakeLists.txt files on linux will causes linux makefiles to be generated. On mingw, they can generate mingw makefiles. There are numerous generators available within cmake. The list is here: http://www.cmake.org/cmake/help/cmake-2-8-docs.html#section_Generators http://springrts.com is a huge opensource rts game that used to use scons as its cross-platform build system and now uses cmake. I understand that you don't really want to have to change build systems, so it is a medium to long term solution. Cmake is in any case one more option, to add to those of using a custom build tool, or using msbuild, or running the scons build from the commandline by hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/1764744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: RDLC image not show by set report parameter I am working with RDLC Report in 2010 I want to bind image from external source ReportParameter rpara = new ReportParameter("rpt1", "D:\\Projects\\Image\\logo.jpg"); ReportViewer1.LocalReport.EnableExternalImages = true; ReportViewer1.LocalReport.SetParameters(new ReportParameter[] { rpara }); I also set all the property of rdlc design like add parameter rpt1 in report data window add new image in body part then set image property to external and select report parameter everything okay but still I am not able to get image on my report viewer A: Try to use this way string imagepath = "File:///" + "C:\\image.jpg"; this.reportViewer1.LocalReport.EnableExternalImages = true; ReportParameter[] param = new ReportParameter[1]; param[0] = new ReportParameter("Path", imagepath); this.reportViewer1.LocalReport.SetParameters(param); this.reportViewer1.RefreshReport();
{ "language": "en", "url": "https://stackoverflow.com/questions/15293564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How get the biggest number? I am trying to get the biggest number from a field in my database using this code: var bb=(from c in Office_TBLs select c.CodeNumber).Max(); When i run the query I receive the result "999" which is wrong because the biggest number in the databse is 1601. Does the datatype being Nvarchar in the field of database matter? How could I fix my code to get the correct max number. A: Since you are using LINQ to SQL you should use Convert.ToInt32 for converting to string to number, so your query would be: var bb =(from c in Office_TBLs select Convert.ToInt32(c.CodeNumber)).Max(); See: Standard Query Operator Translation C# casts are supported only in projection. Casts that are used elsewhere are not translated and are ignored. Aside from SQL function names, SQL really only performs the equivalent of the common language runtime (CLR) Convert. That is, SQL can change the value of one type to another. There is no equivalent of CLR cast because there is no concept of reinterpreting the same bits as those of another type. That is why a C# cast works only locally. It is not remoted. A: "999" > "1601" as string comparison - so to get result you want you need to convert string values to numbers. The easiest approach would be to use .Select(s => int.Parse(s)).Max()) (or .Max(s => int.Parse(s))) instead of .Max() which ends up using regular string comparison. Note that depending on where data is coming from there could be much better ways to get integer results (including changing field type in database). Using .Select on query most likely force query to return all rows from DB and only than compute Max in memory. A: Try this var bb=(from c in Office_TBLs select (e => e.CodeNumber).Max()) A: If you use NVarChar then you are asking to have the values sorted alphabetically. "999" comes after "1601" just like "ZZZ" comes after "HUGS". If the column is supposed to only contain numeric values then the best fix is to change the datatype to a more appropriate choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/16351648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Registry is setting 1 char My code is setting 1 char of the registry name and value. bool setRegValue(std::wstring valueName, std::wstring valueToSet) { HKEY key=NULL; if (get_HKEY_LOCAL_MACHINE(&key) && (key!=NULL)) { if (RegSetValueEx((HKEY)key, (LPCSTR)valueName.c_str(), 0, REG_SZ, (const BYTE*)valueToSet.c_str(), (valueToSet.size() +1)*sizeof(wchar_t)) != ERROR_SUCCESS) { RegCloseKey((HKEY)key); log.error("Failed to SET the registry value. Name : "+ std::string(valueName.begin(), valueName.end())+" Value : "+ std::string(valueToSet.begin(), valueToSet.end())); RegCloseKey(key); return false; } log.info("Successfully SET the registry value. Name : " + std::string(valueName.begin(), valueName.end()) + " Value : " + std::string(valueToSet.begin(), valueToSet.end())); RegCloseKey(key); return true; } return false; } And, this is the calling method. bool setServiceAsClient() { if (setRegValue(L"ServiceType", L"Client")) return true; return false; } Its setting the registry name as S And, value as C A: When a wide-char string is seen as a 1-char string, that's a symptom that you're providing a wide-char string where a multi-byte string is expected. Indeed we see the error here: (LPCSTR)valueName.c_str() (where valueName is a std::wstring). LPCSTR is const char *, whereas wstring::c_str() returns const wchar_t *. So L"ServiceType" is seen as "S\0e\0r\0v\0i\0c\0e\0T\0y\0p\0e\0", which becomes simply "S" There are 2 solutions possible: * *Use std::string instead of std::wstring (and remove the L from strings like L"ServiceType"). This solution is not recommended, since the Win32 API internally is Unicode. *Change project settings from Multi-byte to Unicode Character Set and remove the casting to LPCSTR (if you do need to cast, use LPTSTR instead, which always matches project character set settings). See Working with Strings - Win32 API for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/59775997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to detect merged cells in vba (Word 2010) I would like to detect and skip merged cells in vba on word 2010. I'm making a macro which need to write in the first column but I've some merged cells and I don't want to write in. All examples I found was for Excel. I tried to detect the number of columns per rows but that didn't works. I got "Error 5991 table has vertically merged cells". So how can I just skip the row when I get merged cells ? Sub test() Dim Ro As Integer, Col As Integer 'init Count = 1 Col = 1 For Ro = 4 To ActiveDocument.Tables(4).Rows.Count 'format If Count < 10 Then flag = "0" Else flag = "" End If 'detect merge If ActiveDocument.Tables(4).Rows(Ro).Cells.Count = 9 Then ActiveDocument.Tables(4).Cell(Ro, Col).Range.Text = "R" & flag & CStr(Count) Count = Count + 1 Else Ro = Ro + 1 End If Next Ro End Sub A: i found a solution ! i used this to bypass the error: On Error GoTo ErrorHandler ErrorHandler: If Err.Number = 5991 Or Err.Number = 5941 Then Err.Clear Resume byebye End If For Ro = 4 To ActiveDocument.Tables(4).Rows.Count [My ugly code] #in my case i can use a cell to determinate if it's a my row is merged or not If Len(ActiveDocument.Tables(4).Cell(line, 5).Range.Text) > 0 Then [My Ugly Code] byebye: Next Ro Hope my solution can help you...
{ "language": "en", "url": "https://stackoverflow.com/questions/28559703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to save model in keras python? Model description: cnn1=Sequential() cnn1.add(Conv2D(128,(2,300), activation = 'relu',input_shape = (maxLenofSent,300,1))) cnn1.add(MaxPooling2D(1,3)) cnn1.add(Flatten()) cnn1.add(Dense(100, activation = 'relu')) cnn2=Sequential() cnn2.add(Conv2D(128,(2,300), activation = 'relu',input_shape = (maxLenofSent,300,1))) cnn2.add(MaxPooling2D(1,3)) cnn2.add(Flatten()) cnn2.add(Dense(100, activation = 'relu')) classifier2=Sequential() classifier2.add(Merge([cnn1,cnn2], mode='concat')) classifier2.add(Dense(70,activation='sigmoid')) classifier2.add(Dropout(0.2)) classifier2.add(Dense(2,activation='tanh')) sgd = SGD(lr = 0.01, momentum = 0.9, decay=1e-2, nesterov = False) classifier2.compile(loss = 'categorical_crossentropy', optimizer = sgd, metrics = ['accuracy']) How to save full model so that it can be used later for testing. Output of two cnn goes to ann and classify. A: Here how to save the model: model_json = model.to_json() with open("<path.json>", "w") as json_file: json_file.write(model_json) model.save_weights("<path.hdf5>", overwrite=True) If you want to save the model and weights at every epoch, try searching for callbacks. A: before saving the model, you need to train it using classifier2.fit() https://keras.io/models/sequential/#fit to save the model use classifier2.save('filename.hdf5')
{ "language": "en", "url": "https://stackoverflow.com/questions/47377832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: express static files on cPanel server with phussion passanger I am trying to deploy a node app with Cpanel using the setup node js app tool. The application has been deployed successfully but the static files of my application are broken I am getting a 404 error for my public folder. My hosting server uses Phusion Passanger to manage HTTP requests. Are there any settings I need to provide to add the path to my static files? In localhost it was enough to use: server.use(express.static(path.join(__dirname, 'public'))); But when testing it in production there seems to be some overlap of the passenger configuration with respect to my express server configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/75476729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Absolute & Relative URL Types I wrote a login code in PHP: <form NAME="form1" METHOD="POST" ACTION="operation/validateLogin.php"> Username <br/><input name="username" type=text autocomplete="off"><br/><br/> Password <br/><input name="password" type=text autocomplete="off"><br/><br/> <button class="btn btn-primary submit" type="submit">Sign In</button> </form> When I submit the form the credentials are sent to a validation file. If an error occurs the file sends the error message back to the login page: header("Location: http://localhost/demoapp/login.php/?em=28"); I handle the 'GET' parameter and print the error message: if (isset($_GET['em'])){ if($_GET['em'] == 28){$errorMessage = "Your username or password was incorrect.";} } Now the user needs to try to login again by resubmitting the form, but the action of the form is: operation/validateLogin.php and the URL is now: http://localhost/demoapp/login.php/?em=28 Therefore, when the form is submitted the url becomes: http://localhost/demoapp/login.php/operation/validateLogin.php When it should be... http://localhost/demoapp/operation/validateLogin.php How do you prevent this from happening to the URL? A: The ACTION attribute of an HTML form can be set with a relative URL: /operation/validateLogin.php or /validateLogin.php It's actually recommended to work with relative URLs for HTML elements: Absolute vs relative URLs However, when working with PHP an absolute URL is your best option: http://localhost/demoAPP/operation/validateLogin.php The use of absolute URLs will relieve your code of accidental URL concatenation. I had trouble recently figuring out which type of URL to use for certain situations, but this is what I've realized... PHP (local/server language) = Absolute Local/Server Address require "C:/dev/www/DEMO/operation/login/validateLogin.php"; include "C:/dev/www/DEMO/operation/login/validateLogin.php"; header("Location: http://localhost/demoapp/login.php/?em=28"); (redirect to a web address) This may seem really simple but remembering this will save you a lot of troubleshooting time. If you are using .PHP files, alter the URL in any way, and are not using absolute URLs you will most certainly receive errors. Additional: You'll notice that you can use a web address for HTML attributes and not run into any problems. However, with PHP requires and includes you can only use local addresses. There is a reason for this limitation and it's all because of one important PHP setting... https://help.dreamhost.com/hc/en-us/articles/214205688-allow-url-include
{ "language": "en", "url": "https://stackoverflow.com/questions/43484592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to separate 2 values returned by a function into 2 different variables C++ The function that return the values is this float calcVelocity(float xacceleration, float yacceleration,sf::Clock clock, float originalDistance){ sf::Time time = clock.getElapsedTime(); //get current time and store in variable called time float xvelocity = xacceleration*time.asSeconds(); float yvelocity = yacceleration*time.asSeconds(); while (!(originalDistance + calcDisplacement(yacceleration, clock, originalDistance) <= 0)) { time = clock.getElapsedTime(); //get current time and store in variable called time xvelocity = xacceleration*time.asSeconds();//Calculates velocity from acceleration and time yvelocity = yacceleration*time.asSeconds(); cout << xvelocity<<endl;//print velocity cout << yvelocity << endl; system("cls");//clear console } return xvelocity; return yvelocity; } I then want them to print as finalXvelocity = blah and finalYvelocity = blah after the while loop is finised. In the main code when I call the function and output the result, it prints both values together. E.g finalXvelocity = blahblah. I was thinking I could separate the values returned into the main code and then print them using those but I don't know how to do that. Thanks A: Use a struct: struct velocity { float x_component; /*ToDo - do you really need a float*/ float y_component; }; This will be the most extensible option. You can extend to provide a constructor and other niceties such as computing the speed. Perhaps a class is more natural, where the data members are private by default. A: If you have more than one return value, since C++11 you can return them as a std::tuple. No need to explicit declare a data struct. e.g. tuple<float,float> calcVelocity(/*parameters*/) { // your code return make_tuple(xvelocity,yvelocity); } Outside the function you can access the values by: tuple mytuple = calcVelocity(/*parameters*/); float xvelocity = get<0>(my_tuple); float yvelocity = get<1>(my_tuple); For pre-C++11 std::pair is also an option for just 2 values. But in this case the struct solution is more explicit.
{ "language": "en", "url": "https://stackoverflow.com/questions/35699149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: type 'int' is not a subtype of type 'String' i am trying to fetch the data from api, i am getting the value when i print it in console, but when i am tried to access it using shared perference on other screen, i am not getting the values, and it print this error type 'int' is not a subtype of type 'String' here is my api code getstatus=(req,res)=>{ jwt.verify(req.body.token, 'secret' , function(err, decoded) { if(err) { err["expiredAt"] = err["expiredAt"].toLocaleString(); //here the error points res.status(300).json(err) } else { let leaves=0,sick_leaves=0,annual_leaves=0,maternity_leaves=0; User.find({"username":req.body.username,"leave":"ON"},function(err,data){ User.find({"username":req.body.username,"leave":"ON","type":"Sick"},function(err,value){ User.find({"username":req.body.username,"leave":"ON","type":"annual"},function(err,value1){ User.find({"username":req.body.username,"leave":"ON","type":"maternity"},function(err,value2){ console.log(value2.length) if(data.length>0){ leaves = data.length } if(value2.length>0){ maternity_leaves= value2.length } if(value.length>0){ sick_leaves= value.length} if(value1.length>0){ annual_leaves= value1.length } console.log(leaves,sick_leaves,annual_leaves,maternity_leaves) res.json({"leaves":leaves,"sick":sick_leaves,"annual":annual_leaves,"maternity":maternity_leaves}).status(200) }) }) }) }) }}) } and here i am fetching the api on frontend data={ "token":token, "username":name, "leave":"ON", "type":"maternity" }; dio .post(localHostUrlleaveCount, data: json.encode(data)) .then((onResponse) async { print(onResponse.data); String sickCount=(onResponse.data['sick'].toString()); print("sickCount"); //i get value here print(sickCount); String annualCount=(onResponse.data['annual'].toString()); String maternityCount=(onResponse.data['maternity']); String totalleaveCount=(onResponse.data['leaves']); print("annualcount"); print(annualCount); // but it prints this "type 'int' is not a subtype of type 'String'" error before this line myPrefs.setString('totalleave', totalleaveCount); myPrefs.setString('sickcount', sickCount); myPrefs.setString('annualcount', annualCount); myPrefs.setString('maternitycount', maternityCount); }).catchError((onerror){ print(onerror.toString()); // showAlertDialog(context); }); and on dashboard screen i getting the shared perference value like this String sickcount=""; _userDetails() async { SharedPreferences myPrefs = await SharedPreferences.getInstance(); setState(() { sickcount=myPrefs.getString('sickcount'); print(int.parse(sickcount)); //error on this way "Unhandled Exception: FormatException: Invalid number (at character 1)" print(sickcount); //i tried in this way print(sickcount.toString()); //i tried in this way but same error on all the ways }); } i am getting values perfectly from other api's, i don't know what i am doing wrong with this api, please help me to fix it. one more thing i am doing is when i am logged in in app i am calling the dashboard screen on click on login button, but i want this above api output in leave screen, so when i create this api on leave screen and call it in initState function it send me this error on backend TypeError: Cannot read property 'toLocaleString' of undefined and Http status error [500] error on frontend Api output is {leaves: 3, sick: 2, annual: 0, maternity: 1}
{ "language": "en", "url": "https://stackoverflow.com/questions/68617905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 vs Rails 2 "wild controller" routing I'm trying to get my Rails 3 project to automatically resolve namespaced controllers, similar to the Rails 2 behaviour. For example (Rails 2): $ rails pathtest && cd pathtest $ script/generate controller First $ script/generate controller first/second $ script/generate controller first/second/third $ script/server Requests to: */first routes to first controller */first/second routes to second controller */first/second/third routes to third controller But, Rails 3 yields different routing using the 'wild controllers' path. $ rails new pathtest && cd pathtest $ rails generate controller First $ rails generate controller first/second $ rails generate controller first/second/third ## config/routes.rb Pathtest::Application.routes.draw do match ':controller(/:action(/:id(.:format)))' end $ rails server Requests to: */first routes to first controller */first/second routes to first#second */first/second/third routes to first#second :id => 'third' I'm starting to think that kind of automatic resolution of namespaced controllers isn't the way anymore? Has anyone found a way to automatically resolve namespaced controllers like this? Thanks! A: Try this: Pathtest::Application.routes.draw do resources :first do resources :second do resources :third end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/4901376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass ui-sref url to ng-click function <td class="text-left"> <a class="curosr" ui-sref="private.Registered_details ({uid: x.userID,vid:x.vehicleID,page_value:'page1'})" ng- click="linkClick(x.name,0,Registered_details/uid/vid/page_value)">{{x.name}} </a> </td> In the above code segment, I have a with ui-sref="private.Registered_details ({uid: x.userID,vid:x.vehicleID,page_value:'page1'})"..How to pass this a s url to linkClick funtion in ng-click A: Have ng-click like this. Pass all the details necessary to navigate to your chosen state. <td class="text-left"> <a class="curosr" ng-click="navigateToDetails(x)">{{x.name}} </a> </td> And in controller, first inject $state as dependency, and then, use $state.go to navigate to the state. $scope.navigateToDetails = function(x) { // some amazing code to decide whether or not to navigate $state.go("private.Registered_details", { uid: x.userID, vid: x.vehicleID, page_value:'page1' }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/43365147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make UITableView look like the one in Contacts? I'm trying to make UITableViewController look like following. (it has picture and several rows for someone's identify.) I wonder how to make like following programmatically. How to adjust UITableViewCell's origin.x and width? How to add a picture at left top? Please help me.. I will thank you. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; cell.frame = CGRectMake(50, 0, 250, 44) <--- ?????? I think this is wrong way. return cell; } A: My best bet is that either there are two static UITableViews inside a UIScrollView or that it's some custom subclass UIView set as tableHeaderView and styled to look as on the picture. If I were to implement it I'd go with the second choice. A: Make a subclass of UITableView. Give your subclass properties referring to the photo well and the three special row cells. Override layoutSubviews to call [super layoutSubviews] and then set the frames of the photo well and the three special row cells. The photo well should not be a cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/13200420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }