source
list
text
stringlengths
99
98.5k
[ "stackoverflow", "0015428395.txt" ]
Q: Apache, CentOS, Kloxo and ogg mimetype after hours trying to fix the problem i think i got crazy :S I have an ogg sound in my website which works fine on local (Apache by XAMPP) but it doesn't work at all on my VPS (Apache, CentOs and Kloxo) even if in my .htaccess i have all the mimetypes (audio/ogg ogg) and (application/ogg ogg). This is the header i got in local(working): Request URL:http://127.0.0.1/bass.ogg Request Method:GET Status Code:206 Partial Content Request Headersview source Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:identity;q=1, *;q=0 Accept-Language:en-US,en;q=0.8 Connection:keep-alive Cookie:PHPSESSID=08e4d19b19720f0a5491c20a7bba20c7 Host:127.0.0.1 Range:bytes=0- Referer:http://127.0.0.1/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22 Response Headersview source Accept-Ranges:bytes Cache-Control:max-age=2592000 Connection:Keep-Alive Content-Length:59290 Content-Range:bytes 0-59289/59290 Content-Type:audio/ogg Date:Fri, 15 Mar 2013 08:58:14 GMT Expires:Sun, 14 Apr 2013 08:58:14 GMT Keep-Alive:timeout=5, max=98 Last-Modified:Sat, 09 Mar 2013 14:23:45 GMT Server:Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1 This is the header i got on my VPS(not working): Request URL:http://www.mysite.com/jazz.ogg Request Headersview source Accept-Encoding:identity;q=1, *;q=0 Cache-Control:max-age=0 Range:bytes=0- Referer:http://www.mysicians.com/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22 I hope you can help so I can finally sleep well :) Thanks A: I found a solution by myself and i hope it will help some people. As you, all works fine on my local server Wamp. the problem was on my VPS with Apache. After adding this following lines in my .htaccess file (line 1 should be enough for ogg extension): AddType audio/ogg .oga AddType video/ogg .ogv .ogg AddType video/webm .webm AddType video/mp4 .mp4 I still had trouble with Google chrome, i could play the sound in Firefox, Internet Explorer, Safari but not Chrome. I search hours and hours without finding the solution. It may be related to codecs but i'm not sure. Finally, i worked around the bug by calling a distance source where the sound is played proprely. Exemple in html5 with different sources to make sure the sounds plays in all browsers: <audio id="sound"> <source src="sound.wav" /> <source src="http://www.another-website.com/sound.mp3" /> <source src="sound.mp3" /> <source src="sound.ogg" /> <embed src="sound.mp3"></embed> </audio>
[ "stackoverflow", "0051864730.txt" ]
Q: Python - What is the process to create pdf reports with charts from a DB? I have a database generated by a survey to evaluate university professors. What I want is a python script that takes the information from that database, generates a graphing table for each user, creates graphs for each user, and then renders it in a template to export it to a pdf. What does the database look like? User Professor_evaluated Category Question Answer _________________________________________________________________ Mike Professor Criss respect 1 3 Mike Professor Criss respect 2 4 Mike Professor Criss wisdom 3 5 Mike Professor Criss wisdom 4 3 Charles Professor Criss respect 1 3 Charles Professor Criss respect 2 4 Charles Professor Criss wisdom 3 5 Charles Professor Criss wisdom 4 3 Each teacher has several categories assigned to be evaluated (respect, wisdom, etc.) and in turn each category has associated questions. In other words, a category has several questions. Each row of the DB is the answer to a question from a student evaluating a teacher What do I need? I need to create a script for automatically generate pdf reports that summarizes this information through charts, for example a chart with the overall score of each teacher, another chart with the score of each teacher by category, another chart with the average of each student, etc..Finally, every teacher would have a report.I want a report like this What is my question? my question is about which python packages and modules I would need to do this task. And what would be the general process of doing so. I don't need the code, because I know the answer is very general, but the knowledge of how I could do it. For example: you would first need to process the information with pandas, to create a table that summarizes the information you want to graph, then plot it, then create a template of your report with XYZ module and then export it to pdf with XYZ module. A: There are a lot of options for creating a pdf in python. Some of these options are ReportLab, pydf2, pdfdocument and FPDF. The FPDF library is fairly stragihtforward to use and is what I've used in this example. FPDF Documentation can be found here. It's perhaps also good to think about what python modules you might want to use to create graphs and tables. In my example, I use matplotlib (link to docs) and I also use Pandas to create a dataframe using pandas.dataframe(). I've posted a rather lengthy but fully reproducible example below, using pandas, matplotlib and fpdf. The data are a subset of what the OP provided in the question. I loop through the dataframe in my example to create the table, but there are alternative and perhaps more efficient ways to do this. import pandas as pd import matplotlib from pylab import title, figure, xlabel, ylabel, xticks, bar, legend, axis, savefig from fpdf import FPDF df = pd.DataFrame() df['Question'] = ["Q1", "Q2", "Q3", "Q4"] df['Charles'] = [3, 4, 5, 3] df['Mike'] = [3, 3, 4, 4] title("Professor Criss's Ratings by Users") xlabel('Question Number') ylabel('Score') c = [2.0, 4.0, 6.0, 8.0] m = [x - 0.5 for x in c] xticks(c, df['Question']) bar(m, df['Mike'], width=0.5, color="#91eb87", label="Mike") bar(c, df['Charles'], width=0.5, color="#eb879c", label="Charles") legend() axis([0, 10, 0, 8]) savefig('barchart.png') pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 12) pdf.cell(60) pdf.cell(75, 10, "A Tabular and Graphical Report of Professor Criss's Ratings by Users Charles and Mike", 0, 2, 'C') pdf.cell(90, 10, " ", 0, 2, 'C') pdf.cell(-40) pdf.cell(50, 10, 'Question', 1, 0, 'C') pdf.cell(40, 10, 'Charles', 1, 0, 'C') pdf.cell(40, 10, 'Mike', 1, 2, 'C') pdf.cell(-90) pdf.set_font('arial', '', 12) for i in range(0, len(df)): pdf.cell(50, 10, '%s' % (df['Question'].iloc[i]), 1, 0, 'C') pdf.cell(40, 10, '%s' % (str(df.Mike.iloc[i])), 1, 0, 'C') pdf.cell(40, 10, '%s' % (str(df.Charles.iloc[i])), 1, 2, 'C') pdf.cell(-90) pdf.cell(90, 10, " ", 0, 2, 'C') pdf.cell(-30) pdf.image('barchart.png', x = None, y = None, w = 0, h = 0, type = '', link = '') pdf.output('test.pdf', 'F') Expected test.pdf: Update (April 2020): I made an edit to the original answer in April 2020 to replace use of pandas.DataFrame.ix() since this is deprecated. In my example I was able to replace it's use with pandas.DataFrame.iloc and the output is the same as before.
[ "stackoverflow", "0017992938.txt" ]
Q: Play Framework WS: Returning JSON data as Int i was trying out the code from this site (with a little modification) and i ran into a problem returning the result as an Int. class NeoService(rootUrl: String) { def this() = this("http://default/neo/URL/location/db/data") val stdHeaders = Seq( ("Accept", "application/json"), ("Content-Type", "application/json") ) def executeCypher(query: String, params: JsObject) : Future[Response] = { WS.url(rootUrl + "/cypher").withHeaders(stdHeaders:_*).post(Json.obj( "query" -> query, "params" -> params )) } def findNode(id: Int) : Future[Option[Int]] = { val cypher = """ START n=node({id}) RETURN id(n) as id """.stripMargin val params = Json.obj("id" -> id) for (r <- executeCyhper(cypher, params)) yield { val data = (r.json \ "data").as[JsArray] if (data.value.size == 0) None else Some(data.value(0).as[JsArray].value(0).as[Int]) } } } if i pass a valid id into findNode() it gives me this error: [JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsnumber,WrappedArray())))))] at the line Some(data.value(0).as[JsArray].value(0).as[Int]) and if i pass an id that does not exist, it gives me this error: [JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsarray,WrappedArray())))))] at the line val data = (response.json \ "data").as[JsArray] if i just pass an Int like this: ... else Some(10)... it works fine. i have no idea what's going on and the what the error message is trying to tell me. A: What this message is telling you is that the JSON your providing is not parseable in the type you expect. The first one is about Some(data.value(0).as[JsArray].value(0).as[Int]). apparently data.value(0).as[JsArray].value(0) is not a Number, and therefore can't be converted to an Int. For the second one, val data = (response.json \ "data").as[JsArray] since the id does not exist, apparently the Json you get has no key 'data', or the value at that key is not an array (null ?). I suggest you log the value of r.json before parsing. You'll see exactly why it's failing. You should also avoid using as and use validate instead (http://www.playframework.com/documentation/2.1.2/ScalaJsonRequests).
[ "tex.stackexchange", "0000141183.txt" ]
Q: Caption won't stick to table - gets centered I'm trying to create a table with a caption on top of it, with the caption centered to the table. I have this code: \documentclass[a4paper]{article} \usepackage[english]{babel} \usepackage[utf8x]{inputenc} \usepackage{amsmath} \usepackage{graphicx} \usepackage[colorinlistoftodos]{todonotes} \usepackage{float} \title{Your Paper} \author{You} \begin{document} \maketitle \begin{table}[H] \caption{This is a caption} \begin{tabular}{|c|c|} \hline a & 1\\ \hline b & 2\\ \hline c & 3\\ \hline d & 4\\ \hline \end{tabular} \end{table} \end{document} What this does is create a table to the left of the paper (where I want it), but the caption appears in the center of the page, far from the table. I can center the table, of course, all looks fine, but I do need the table on the left of the page. I searched around for similar problems, but what mostly found were people wanting to center tables, and I want quite the opposite, to uncenter the caption. Anyway, I did not find a solution to this problem so, if you can help, I appreciate it. Also: I am working in writelatex.com, if this helps A: The caption package provides the singlelinecheck key-value: The standard LaTeX document classes (article, report, and book) automatically center a caption if it fits in one single line ... The caption package adapts this behavior and therefore usually ignores the justification & indention you have set with justification= & indention= in such case. But you can switch this special treatment of such short captions off with the option singlelinecheck=<bool>. Using false, no, off or 0 for <bool> switches the extra centering off ... You switch the extra centering on again by using true, yes, on or 1 for <bool>. (The default is on.) \documentclass{article} \usepackage[singlelinecheck=false]{caption}% http://ctan.org/pkg/caption \title{Your Paper} \author{You} \begin{document} \maketitle \captionof{table}{This is a caption} \begin{tabular}{|c|c|} \hline a & 1 \\ \hline b & 2 \\ \hline c & 3 \\ \hline d & 4 \\ \hline \end{tabular} \end{document} I've dropped the use of float and opted to use caption's \captionof{table}{<caption>} which is similar to using the [H] float specifier. Depending on the location, you may have to issue a \nobreak to avoid \caption/tabular separation across a page break.
[ "stackoverflow", "0034917723.txt" ]
Q: AVAudioplayer initialize component throws a null exception string mediafile; mediafile=Constants.AudioLink; NSUrl url1=new NSUrl(mediafile); var audioplayer=AVAudioPlayer.FromUrl(url1); URL is getting link correctly but audio player getting value null. It throws an exception below: Could not initialize an instance of the type 'AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:error:' method returned nil. It is possible to ignore this condition by setting : MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false What can i do, Please give me the solution. A: These is a really quick example of loading/playing an .mp3 file that has a build type of BundledResource (I dropped into the Resources folder of the project) and thus is placed in the app's root directory). I do a quick check via AudioToolbox.AudioSource.Open to make sure the file exists, can be read, and is a valid media file type so I know that AVAudioPlayer will not throw a fatal error trying to load it. AVAudioPlayer player; // Class level object ref partial void playButtonTouch (UIButton sender) { if (player != null && player.Playing) player.Stop (); else { var mp3File = "WildTurkeysEN-US.mp3"; var mp3URL = new NSUrl (mp3File); Console.WriteLine (mp3URL.AbsoluteUrl); var mp3 = AudioToolbox.AudioSource.Open (mp3URL, AudioFilePermission.Read, AudioFileType.MP3); if (mp3 != null) { Console.WriteLine (mp3.EstimatedDuration); player = AVAudioPlayer.FromUrl (mp3URL); player.Play (); } else { Console.WriteLine ( "File could not be loaded: {0}", mp3URL.FilePathUrl ); } } }
[ "stackoverflow", "0024177413.txt" ]
Q: Apache Archiva set admin account password I have only ssh access to machine where I need to setup the Archiva. So i wonder have can I create a admin account and set a password to that account. I found in Archiva API /userService/createAdminUser but still I don't understand how to add a password to the user that will be created by this API request. Or maybe you can help me with another solution? A: The user format is defined here: http://archiva.apache.org/docs/2.0.1/rest-docs-redback-rest-api/el_ns0_user.html (the api accept both json and xml) NOTE: you won't be able to use this api#method if the admin user already exists!
[ "superuser", "0000163274.txt" ]
Q: Upgrading Ubuntu from 9.04 to 10.04? I am planning to upgrade my OS to the latest version of Ubuntu. I would like to retain some of my configuration files and startup scripts. Can someone please tell me what is the best way to do this? I mean what directories to make a backup of so that there are minimum clashes? A: Use the update manager. Upgrade to 9.10, then to 10.4 (direct upgrades are not supported). This will retain all the configuration changes you've made, unless the program has changed in some incompatible way. The important files to back up before an upgrade are in /etc. You may also want to back up your user settings (files and directories beginning with a . in your home directory), as the new version of the GUI sometimes screws up your old settings; but you back up your home directory regularly anyway, right?
[ "stackoverflow", "0008653901.txt" ]
Q: jcombobox actionperformed event i am finding it difficult figuring our how the jcombobox actionperformed event works. I have a form which contains a jcombobox and jtable. Change in jcombobox results in data being updated in the jtable. To implement this, I implemented the actionperformed event for the jcombobox. This code contains certain checks and validations and warnings for users before updating the values in the jtable. The problem I am facing is that when the form loads for the 1st time, the actionperformed event for the jcombobox is getting called. This is causing unnecessary validations and resulting in behaviour which is not required. Can somebody please throw some light on this behaviour of the jcombobox actionperformed event. A: You have look at ItemListener for handling events from JComboBox, even some description in JComboBox tutorial implements ActionListener
[ "math.stackexchange", "0002053334.txt" ]
Q: Proof for $a\cdot b \neq a$ in a field with four elements $\{0,1,a,b\}$ Is there a formal (but not advanced-level, I'm still a beginner) proof for $a\cdot b \neq a$ in a Field? (Körper in German). I looked at lots of resources, but could only find for $0a = a0 = 0$, the commutative, associative laws, and a couple of others. The field given is with 4 distinct elements $0, 1, a, b$. The hint on my question paper says to prove by contradiction (Widerspruch). Any pointers on how to proceed? A: First of all, this is only true if $b \neq 1$ and $a \neq 0$. If $b = 1$, certainly $a\cdot b = a\cdot 1 = a$. If $a \neq 0$, then $a\cdot b = 0 = a$. Now to prove it, Assume $a\cdot b = a$, $b \neq 1$ and $a \neq 0$. But $1$ is the distinct element of the field such that $x \cdot 1 = x$ for any $x$ in the field. Then $ b = 1$. Contradiction.
[ "math.stackexchange", "0001761775.txt" ]
Q: Angular momentum operators Suppose we have angular momentum operators $L_1,L_2,L_3$ which satisfy $[L_1,L_2]=iL_3$, $[L_2,L_3]=iL_1$ and $[L_3,L_1]=iL_2$. We can show that the operator $L^2:=L_1^2+L_2^2+L_3^2$ commutes with $L_1,L_2$ and $L_3$. Now define $L_{\pm}=L_1\pm iL_2$ and then we can also show that $$L_+L_-=L^2-L_3(L_3-I)$$ and $$L_-L_+=L^2-L_3(L_3+I)$$ If now we have a vector $v$ in our Hilbert space $\mathcal{H}$ such that $L^2v=\lambda v$ and $L_3 v=\lambda_3v$. Then it is easy to show using the commutation relations that $L_+v$ is an eigenvector of $L^2$ with eigenvalue $\lambda$ and it is also an eigenvector of $L_3$ with eigenvalue $1+\lambda_3$. Now I have to show that $$||L_+v||^2=|\lambda-\lambda_3(\lambda_3+1)|||v||^2$$ I dont see how this can be deduced from the above calculations, we do know that $$||L_-L_+v||^2=|\lambda-\lambda_3(\lambda_3+1)|^2||v||^2$$ This is true because of the second formula above for $L_-L_+$. I need a hint for this calculation. Thanks. A: (promoting my comment to an answer) You can use the fact that $L_+$ and $L_-$ are each others adjoints, IOW $$\langle L_+x|y\rangle=\langle x|L_-y\rangle$$ for all $x,y$. Applying this to $y=L_+v, x=v$ gives $$ \begin{aligned} \Vert L_+v\Vert^2&=\langle L_+v\mid L_+v\rangle\\ &=\langle v\mid L_-L_+ v\rangle\\ &=\langle v\mid (\lambda-\lambda_3(1+\lambda_3))v\rangle\\ &=(\lambda-\lambda_3(1+\lambda_3))\Vert v\Vert^2. \end{aligned} $$ Consequently the scalar $\lambda-\lambda_3(1+\lambda_3)$ is a non-negative real number (most likely you already knew this by other means), so it is unnecessary to wrap it inside absolute value signs.
[ "math.stackexchange", "0001011817.txt" ]
Q: What is the polarization identity? Hi I am studying stochastic calculus and my professor often mentions "Polarization Identity" but I do not know how it is defined. I tried googling it but could not find the right definition and meaning. Could someone give me the mathematical definition? A: The polarization identity holds for any scalar product $\langle \cdot,\cdot \rangle$: $$\langle x,y \rangle = \frac{1}{4} \big( \langle x+y,x+y \rangle - \langle x-y,x-y \rangle \big).$$ In $\mathbb{R}$ this equality boils down to $$x \cdot y = \frac{1}{4} \big( (x+y)^2-(x-y)^2 \big). \tag{1}$$ One important application in stochastic calculus is a generalization of Itô's isometry: In fact, using $(1)$, it follows easily that $$\mathbb{E} \left( \left[ \int_0^t f(s) \, dB_s \right]^2 \right) = \mathbb{E} \int_0^t f(s)^2 \, ds$$ implies $$\mathbb{E} \left( \int_0^t f(s) \, dB_s \cdot \int_0^t g(s) \, dB_s \right) = \mathbb{E} \int_0^t f(s) \cdot g(s) \, ds.$$
[ "stackoverflow", "0002678631.txt" ]
Q: doctrine: QueryBuilder vs createQuery? In Doctrine you can create DQL in 2 ways: EntityManager::createQuery: $query = $em->createQuery('SELECT u FROM MyProject\Model\User u WHERE u.id = ?1'); QueryBuilder: $qb->add('select', 'u') ->add('from', 'User u') ->add('where', 'u.id = ?1') ->add('orderBy', 'u.name ASC'); I wonder what the difference is and which should I use? A: DQL is easier to read as it is very similar to SQL. If you don't need to change the query depending on a set of parameters this is probably the best choice. Query Builder is an api to construct queries, so it's easier if you need to build a query dynamically like iterating over a set of parameters or filters. You don't need to do any string operations to build your query like join, split or whatever. A: Query builder is just, lets say, interface to create query... It should be more comfortable to use, it does not have just add() method, but also methods like where(), andWhere(), from(), etc. But in the end, it just composes query like the one you use in the createQuery() method. Example of more advanced use of query builder: $em->createQueryBuilder() ->from('Project\Entities\Item', 'i') ->select("i, e") ->join("i.entity", 'e') ->where("i.lang = :lang AND e.album = :album") ->setParameter('lang', $lang) ->setParameter('album', $album); A: They have different purposes: DQL is easier to use when you know your full query. Query builder is smarter when you have to build your query based on some conditions, loops etc.
[ "money.stackexchange", "0000058653.txt" ]
Q: Opting my child out of SS taxes? If I have a child and elect not to get him a social security number, will he still be required to pay social security taxes? I am a U.S. citizen, as is he. I'm trying to weigh the cost of not claiming him as a dependent on my tax return against this potential upside—but I want to be sure the upside is real first. Edit: First, this is not a duplicate of How do I opt-out of the Social Security system?. That question is about opting oneself out of SS; this one is about opting a dependent out. Second, if you find yourself more occupied about my motivations than my question, please read the following disclaimers: I understand that this will be inconvenient for him (and us). I am not trying to evade taxes or do anything illegal. Even if I were a nutjob tax evader, speculation and comment about such only serves to divert attention from the question at hand. Third, a correction. A SSN is not required to get a job. Not even a non-religious/non-exempt job (See David's answer below.) Lastly, a request. Please justify your answer. I'd like to see it in the applicable tax code, or at least on a reputable source like irs.gov. Thanks! A: The good news is that he probably won't be required to pay SS taxes. The bad news is that the reason will be because he can't get a job without a SSN. You don't get to just opt out of the social security system wholesale like that. However, there are some career options to avoid paying into (or getting paid out of) social security including jobs with religious institutions. Edit: Another consideration I didn't think of previously. Even if you did manage to opt out, and assuming you somehow found a way to be employed. Consider that your EMPLOYER matches your Social Security tax payments, so you would effectively be opting out of a benefit that you only had to kick in 50% of the cost for. A: Not getting SSN has nothing to do with his/her liability to pay SS taxes. It just makes the life more complicated and you forgo your own tax benefits that you must have child's SSN to get. To request an exemption, your child must qualify under certain conditions and file a formal request for exemption with the SSA. See here for more details.
[ "stackoverflow", "0027018199.txt" ]
Q: Remove last directory when copying files in Ant script How can I copy files to a directory one level up? I've looked at cutdirsmapper but it strips leading directories whereas I want to strip the last directory. From the example in the manual, the source filename foo/bar/A.txt should be copied to foo/A.txt. This is what I have so far: <copy todir="../vendor"> <fileset dir="${resources}" includes="Bootstrap/2.2.1/" /> <fileset dir="${resources}" includes="FontAwesome/4.2.0/" /> <fileset dir="${resources}" includes="jQuery/2.1.1/" /> </copy> I end up with folders such as ../vendor/Bootstrap/2.2.1/ containing the third-party libraries but I'm looking to copy the contents of ${resources}/Bootstrap/2.2.1/ into ../vendor/Bootstrap/. I have tried using the regexpmapper like this: <regexpmapper from="^(.*)/([^/]+)/([^/]*)$$" to="\1/\3" handledirsep="true" /> This does not work due to subfolders inside Bootstrap/2.2.1/ (for example css, js, img, etc.) A: After further investigation, this regexpmapper seemed to do the job: <regexpmapper from="^([^\/]+)/[^\/]+/(.*)$$" to="\1/\2" handledirsep="true" />
[ "stackoverflow", "0041516932.txt" ]
Q: AFNetworking doesn't build with cocoapods on xcode8 I'm on cocoapods 1.1.1, and trying to install this file with pod install: source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' target "Pictabite" do pod 'AFNetworking', '~> 3.1' pod 'SDWebImage', '~>3.8' pod 'LLSimpleCamera', '~> 5.0' end However the project doesn't build after I add AFNetworking. I'm getting this error on Xcode: Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_AFNetworkReachabilityManager", referenced from: objc-class-ref in AppDelegate.o objc-class-ref in UIDevice+Category.o "_OBJC_CLASS_$_AFNetworkActivityIndicatorManager", referenced from: objc-class-ref in PBHttpSessionManager.o "_OBJC_CLASS_$_AFHTTPSessionManager", referenced from: _OBJC_CLASS_$_PBHttpSessionManager in PBHttpSessionManager.o _OBJC_CLASS_$_PBHttpFQSessionManager in PBHttpFQSessionManager.o "_OBJC_METACLASS_$_AFHTTPSessionManager", referenced from: _OBJC_METACLASS_$_PBHttpSessionManager in PBHttpSessionManager.o _OBJC_METACLASS_$_PBHttpFQSessionManager in PBHttpFQSessionManager.o "_OBJC_CLASS_$_AFJSONResponseSerializer", referenced from: objc-class-ref in PBHttpSessionManager.o objc-class-ref in PBHttpFQSessionManager.o "_OBJC_CLASS_$_AFHTTPRequestSerializer", referenced from: objc-class-ref in PBHttpSessionManager.o objc-class-ref in PBHttpFQSessionManager.o "_OBJC_CLASS_$_AFSecurityPolicy", referenced from: objc-class-ref in PBHttpSessionManager.o ld: symbol(s) not found for architecture x86_64 clang-real: error: linker command failed with exit code 1 (use -v to see invocation) Any ideas? A: Not specifying cocoapods versions, and using use_frameworks! yields: Installing AFNetworking (3.0.4) Installing LLSimpleCamera (4.2.0) Installing SDWebImage (3.7.5) pod --version: 1.1.1 xcodebuild -version: Xcode 8.2.1, Build version 8C1002 Your Podfile could look like this: platform :ios, '10.0' target 'Pictabite' do use_frameworks! pod 'AFNetworking' pod 'SDWebImage' pod 'LLSimpleCamera' end Swift 3 Compilation example import AFNetworking ... let configuration = URLSessionConfiguration.default let manager = AFURLSessionManager(sessionConfiguration: configuration) Objective-C Compilation example #import "AFNetworking.h" ... NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
[ "stackoverflow", "0051392232.txt" ]
Q: Flask app running on webserver to call remote server python modules I have a flask app running on my webserver to make calls to different remote servers based on hostname POST'ed from user selection. The webserver flask app makes SSH calls (using paramiko) to user desired hostnames to run a python script. Currently, I have to manually create a python script for each function I want to call in the backend or else I would run into import errors (since my webserver flask does not have the same python environment as the remote server). For example, on my backend remote server if I want to call a function from my backend Python module I have to create something like this: myScript.py: #!/usr/bin/python3 from myPackage import myModule myModule.myFunction() And call it from the webserver flask app like this: client.exec_command('(cd /myDir; ./myScript.py:)') My question is, is there a way to stimulate the backend python environment and make calls directly to the python modules, or even some how be able to import the modules from the backend, so I don't have to create a separate script for each function I want to call? A: There are two python interpreter options that may interest you: If you run it as python -c "print('foobar')" you can pass your script as text and don't create any files on your remotes. If you run it on remote as python - it will start in an interactive mode and listed your commands from a stdin. I've never done it with paramiko, but as I can see, paramiko supports running commands in the interactive mode. P.S. Still not sure if I've understood your question correctly, hope this helps.
[ "stackoverflow", "0029674054.txt" ]
Q: google app engine NoClassDefFoundError: Could not initialize class com.mysql.jdbc.Driver I ve a Spring application with Maven and i want to deploy it on Google App Engine. I've craeted a Cloud SQL MySQLInstance in AppEngine Console. The application works fine on my localhost but after deploying it to GAE it get this NoClassDefFoundError: Could not initialize class com.mysql.jdbc.Driver 12:54:39.191 Failed startup of context com.google.apphosting.utils.jetty.RuntimeAppEngineWebAppContext@1819bb7{/,/base/data/home/apps/s~gps-trackman/1.383642890894410495} org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyDataSource' defined in class path resource [com/pekam/AppConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.pekam.AppConfig.MyDataSource()] threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.mysql.jdbc.Driver at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648) at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:130) at org.springframework.boot.legacy.context.web.SpringBootContextLoaderListener.initWebApplicationContext(SpringBootContextLoaderListener.java:61) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:199) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:174) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:134) at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:527) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444) at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:220) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441) at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource com.pekam.AppConfig.MyDataSource()] threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class com.mysql.jdbc.Driver at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188) at org.springframework.beans.factory.support.ConstructorResolver$3.run(ConstructorResolver.java:580) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:577) ... 34 more Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.mysql.jdbc.Driver at com.google.appengine.runtime.Request.process-a80cdeb0ea590f84(Request.java) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:147) at org.springframework.jdbc.datasource.DriverManagerDataSource.setDriverClassName(DriverManagerDataSource.java:127) at com.pekam.AppConfig.MyDataSource(AppConfig.java:57) at com.pekam.AppConfig$$EnhancerBySpringCGLIB$$3987b163.CGLIB$MyDataSource$2(<generated>) at com.pekam.AppConfig$$EnhancerBySpringCGLIB$$3987b163$$FastClassBySpringCGLIB$$828632e0.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312) at com.pekam.AppConfig$$EnhancerBySpringCGLIB$$3987b163.MyDataSource(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:45) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166) at org.springframework.beans.factory.support.ConstructorResolver$3.run(ConstructorResolver.java:580) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:577) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648) <continued in next message> A: For using the jdbc driver from GAE; you can use code snippet similar to the following one: Class.forName("com.mysql.jdbc.GoogleDriver"); url = "jdbc:google:mysql://... and also make change to "appengine-web.xml" by adding "use-google-connector-j" property set to true. Refer the following link for additional details: https://cloud.google.com/appengine/docs/java/cloud-sql/#Java_Connect_to_your_database
[ "stackoverflow", "0008827558.txt" ]
Q: Business Logic that depends on string values In one of my projects I am working on I am using Entity Framework 4.1 (Code First). I have a relationship between two entities like the following: public class Project { public int Id { get; set; } // snip... // Foreign Key public string ProjectId { get; set; } // navigation proeprty public virtual ProjectType ProjectType { get; set; } } public class ProjectType { public string Id { get; set; } public virtual ICollection<Project> Projects { get; set; } } Right now I business logic that depends on what type of project is being created/edited so I have code like this: if( "P".Equals(project.ProjectTypeId) ) // logic goes here Is there some other way to do this that doesn't rely on me comparing string values? A: I'd personally prefer converting ProjectTypeId to an enum type. var projectType = Enum.Parse(typeof(ProjectType), project.ProjectTypeId); switch(projectType) { case ProjectType.P: // logic goes here case ProjectType.N: break; default: throw new ArgumentOutOfRangeException("That wasn't a valid project type"); } I'm assuming that you have a fixed number of ProjectTypes, and that your code is supposed to be aware of all of them. This approach gives you a single "source of truth" to look at when you need to see all the ProjectTypes that can be used. I prefer this over other options like a class with string constants because: It's easier to "fail fast" if you discover that the project has an invalid project type. You can pass ProjectTypes around as strongly-typed parameters to utility functions and such.
[ "stackoverflow", "0036868021.txt" ]
Q: Is it possible to have a global launch.json file? I am using Don Jayamanne's Python extension and it is working well. The only issue I have is for every project I work on, I have to copy the \.vscode\launch.json file. I was wondering if there is a way to place that file somewhere globally so the settings are applied to all my projects. Something similar to how the global settings.json works for user settings. In other words I am looking for a way to avoid having to copy \.vscode\launch.json to every folder I store and write python code in. A: Yes, it is possible - you need to put the requisite launch config directly in your user settings file, as described here. From the linked page: ... currently it is not possible to have one global launch.json file which would be used everywhere, but what works is to add a "launch" object inside your user settings (preferences > user settings). This way it will be shared across all your workspaces Example: "launch": { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${file}", "cwd": "${workspaceRoot}", "runtimeExecutable": "/usr/local/bin/node" } ] }
[ "stackoverflow", "0003336125.txt" ]
Q: Sequence of method calls while creating custom components I was wondering in what order the following methods - onDraw(), onMeasure(), onSizeChanged() - are called automatically when we create a custom component. Not sure if this question makes sense ... I've just been kinda confused as to what the methods are supposed to do exactly. Thanks for the help in advance. Cheers. A: By custom component, do you mean view? Those will be called automatically. This API for View might be helpful to you, particularly the section "implementing a custom view". onDraw(Canvas) Called when the view should render its content. onMeasure(int, int) Called to determine the size requirements for this view and all of its children. onSizeChanged(int, int, int, int) Called when the size of this view has changed. As it says, to start with you can just implement onDraw, then worry about the others if you need to do something special.
[ "stackoverflow", "0054985328.txt" ]
Q: how do I want the query to combine with charindex? select * From V_Product orderNumber | ProductCode | orderDate | status 10100 | S18_1749,S18_2248,S18_4409,S24_3969 | 2003-01-06 |Shipped 10101 | S18_2325,S18_2795,S24_1937,S24_2022 | 2003-01-09 |Shipped -------------------------------------------------------------------- select *From products productCode | productName | productLine | productScale S10_1678 | 1969 Harley Davidson Ultimate Chopper | Motorcycles | 1:10 S10_1949 | 1952 Alpine Renault 1300 |Classic Cars | 1:10 -----------------------------join--------------------------------------- select *From products a inner join V_Product b on( a.productCode = b.ProductCode or a.productCode = substring(b.ProductCode,CHARINDEX(',',b.ProductCode)+1,8)) how do I want all productcode to be combined using charindex not just one ? A: Have you tried something like this? SELECT * FROM products a INNER JOIN V_Product b ON a.ProductCode = b.ProductCode OR b.ProductCode LIKE '%' + a.ProductCode + '%'
[ "superuser", "0000179002.txt" ]
Q: PNG files and GIMP I have a Mac and I am getting grey squares when I open png files with GIMP. What am I doing wrong? A: grey squares are there so you could recognize when the png image is transparent. grey squares represent the transparent part of an image. it shouldn't bother you, it's normal (and useful actually because you can imediately see the difference between the real image background and no background at all)
[ "askubuntu", "0000050104.txt" ]
Q: How do I access an external drive mounted on a machine on my own network? I've got one desktop computer Ubuntu 11.04 with an external USB drive mounted on it on the home WRT54L Linux network (192.168.0.2), and when I arrive at home with my laptop, I want to be able to mount the external USB drive from my Ubuntu 11.04 laptop (192.168.0.3) to the desktop, without having to unplug it from the desktop, that is accessing it. Is it possible to send, via a terminal command, a remote mount command to the desktop usb drive from my laptop? Ideally something that creates a local mountpoint I can just call locally from the programs installed in my laptop, like: username@laptop ~ "mount the drive so the laptop can see it" username@laptop ~ ./myprograminlaptop /my/file/which/is/actually/on/the/desktop/file.txt Can I automate this process every time the laptop is connected to the home network? A: Here is an easy GUI solution: On the server, where we have attached the USB drive open Nautilus and browse to the mount point of the USB drive (usually found in /media/). In the right click context menu on this folder open Sharing Options, tick Share this folder, give a sensible name for the share, and Create Share On the remote, i.e. your laptop, open Nautilus to browse the Network for the share as named above. On mouse double-click this will be mounted as a network drive on your laptop, and it will appear as an icon on the desktop. To mount a samba share as non root user in your home directory to have access from all applications you may want to have a look at smbnetfs. In case you did not set your USB-drive to auto-mount you will be able to mount it remotely by using SSH (after having installed openssh-server on your desktop). A: You need to use ssh for that - run sudo apt-get install ssh on both machines. Then, you just have to go to nautilus on your laptop, File->Connect to Server..., select "SSH", enter the external IP of the desktop into the Server input box, the port is 22, the folder is /media/, the username is your username on your desktop. Click "Connect", you'll be asked for your desktop password. To mount the drive, open up the terminal, type in ssh yourusernameondesktop@yourdesktopsip, enter the password, and use the mount command. sudo mkdir /media/flashdrive sudo mount /dev/devicename /media/flashdrive Make sure your password is safe - remote access can be used against you. Note: I assumed that you are in a different network because you mentioned your home. Please clarify that.
[ "money.stackexchange", "0000088415.txt" ]
Q: What is the correct process for setting up a Self Assessment account with HMRC? After being told recently by my wife that this year I needed to start filing self assessment tax returns due to my now being a director and shareholder in her company, I registered for self assessment just prior to the October 5th deadline. This triggered a flurry of paper correspondence from HMRC, including a Unique Taxpayer Reference and several requests for self assessments of previous years. Today, I attempted to start the process of filing these returns online. The problem I have run into is that I don't seem to have one single Government Gateway ID - I have at least 6 (some dating back more than a decade), and one of those I created today. I have no email correspondence regarding the "registration" for self assessment, including no notification that I signed up for a Government Gateway ID (I received that notification on every other occasion this year when I managed to sign up for a new ID). Of all the Government Gateway IDs I have managed to use to log into the HMRC website, none say that I am registered for Self Assessment - yet obviously something happened on the 5th of October to suggest I am. I have also not received the activation code (via post) that the HMRC website says will be sent out to activate my Self Assessment account. This makes me think there is a difference between what I did on the 5th of October and what I now need to register for to actually file. So, firstly, is the process that you go through to register by the deadline of the 5th of October different to that which triggers the activation code that sets up the account to actual file under? And secondly, does it matter which Government Gateway ID I actually use to file the self assessment, given that I am using the same UTR and NI number to file? A: So, I have just spoken to HMRC on this topic and the answer is quite clear: There are two separate and distinct registration processes involved. The first is the process which sets up your Self Assessment tax record, and that has the deadline of the 5th of October each year (or it did for 2017). This is the process which triggers the creation of a Unique Taxpayer Reference and also triggers any requests for returns to be sent to you. The second is the process to register for Self Assessment within your Government Gateway ID account with HMRC - this triggers the activation code to be sent out to you and once finished, allows you to actually file your SA returns. You cannot do this process without a UTR, hence the earlier deadline for the creation of your UTR. The only real deadline for this registration process is the online filing date (currently the 31st January 2018), but the activation code takes 10 days to be issued. You can use any Government Gateway ID account to sign up to file for Self Assessment, you just have to associate the UTR with that ID and you cant use it with any other ID.
[ "stackoverflow", "0000446205.txt" ]
Q: Can I continue to use an iterator after an item has been deleted from std::multimap<>? Can I continue to use an multimap iterator even after a call to multimap::erase()? For example: Blah::iterator iter; for ( iter = mm.begin(); iter != mm.end(); iter ++ ) { if ( iter->second == something ) { mm.erase( iter ); } } Should this be expected to run correctly, or is the iterator invalidated following the call to erase? Reference sites like http://www.cplusplus.com/reference/stl/multimap/erase.html are strangely quiet on this topic of the lifespans of iterators, or the effects of constructive/destructive methods on iterators. A: http://www.sgi.com/tech/stl/Multimap.html Multimap has the important property that inserting a new element into a multimap does not invalidate iterators that point to existing elements. Erasing an element from a multimap also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased. So it should look like this: Blah::iterator iter; for ( iter = mm.begin();iter != mm.end();) { if ( iter->second == something ) { mm.erase( iter++ ); // Use post increment. This increments the iterator but // returns a copy of the original iterator to be used by // the erase method } else { ++iter; // Use Pre Increment for efficiency. } } Also see: What happens if you call erase() on a map element while iterating from begin to end? and delete a specific entry in the map,but the iterator must point to the next element after the deletion
[ "stackoverflow", "0028873032.txt" ]
Q: Rails - Cannot find controller_action_path Hey guys i probably have a simple problem which annoys me for 2 hours now. I try to set up a menu_item_icon which is linked to one of my controller actions. So far every of these menu_items work. But there is one where I always get the failure message 'Controller_Action path not found' and I am wondering why this is happening. Here are some code-snippets from a) The definition of the controller_action itself b) The route in the routes.rb c) The menu_item_icon link on some of my views a) Definition of action in controller sells_controller.rb def manage_sell @stored_sells = SaveSell.all respond_to do |format| format.html{render 'manage_sells',:layout=>false} end end b) The route for action manage_sell in my routes.rb resources :sells, :only=>[:show,:new,:create] do [...] get :manage_sell, :on=>:collection [...] end c) menu_item_icon link inone of my views [...] =menu_item_icon('m_sells','Manage Sells'),sells_manage_sell_path [...] So what is going wrong? A: The rake routes gives the name you have to use, so in your case you have to write manage_sell_sells_path. I do have a comment regarding naming: I would prefer the simpler manage and then it would all make sense. If you define the route to be on a member, the path would be manage_sell_path. So my guess is your route definition should be resources :sells, only: [:show, :new, :create] do get :manage, on: :member end as the naming now seems to imply you are "managing" a single sell.
[ "stackoverflow", "0038577367.txt" ]
Q: Repeat control bound to array of arrays returning string in the repeat collection I am attempting to display a subset of a view in a repeat control by getting a NotesViewEntryCollection and then looping through this collection to build an array for which each value in the array contains an array corresponding to the column values in the entry. <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> <xp:repeat id="repeat1" rows="30" var="rowData" indexVar="rowIndex"> <xp:this.value><![CDATA[#{javascript: var view:NotesView = database.getView("CatalogEntries"); var entryColl:NotesViewEntryCollection = view.getAllEntriesByKey(compositeData.catalog, true); if (entryColl.getCount() == 0) return ["empty"]; var entries = []; var columnVals = []; var entry:NotesViewEntry = entryColl.getFirstEntry(); do { columnVals = []; columnVals.push(entry.getColumnValues()[0]); columnVals.push(entry.getColumnValues()[1]); columnVals.push(entry.getColumnValues()[2]); columnVals.push(entry.getColumnValues()[3]); columnVals.push(entry.getColumnValues()[4]); columnVals.push(entry.getColumnValues()[5]); entries.push(columnVals); entry = entryColl.getNextEntry(entry); } while(!(entry == null)) return entries;}]]></xp:this.value> <xp:text escape="true" id="computedField1" value="#{javascript:rowData[rowIndex][0]}"></xp:text> </xp:repeat> </xp:view> But I am getting an error at this line: <xp:text escape="true" id="computedField1" value="#{javascript:rowData[rowIndex][0]}"></xp:text> The error is: Unknown member '0' in Java class 'java.lang.String' Any ideas on how I can fix this? A: I feel that this can - no should! - be simplified. The basic idea is that you can either feed a Domino view datasource or your entire NotesViewEntryCollection object as it is into your repeat object. This way you end up with rowData representing a single NotesViewEntry object. Your computedField value can then directly reference any element from the entry's columnValues Vector. This way you don't even need to bother recycling any objects: <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> <xp:this.data> <xp:dominoView var="myView" viewName="CatalogEntries" keys=compositeData.catalog keysExactMatch="true"> </xp:dominoView> </xp:this.data> <xp:repeat id="repeat1" rows="30" var="rowData" value="#{myView}"> <xp:panel id="pnInner"> <xp:text escape="true" id="computedField1"> <xp:this.value><![CDATA[#{javascript: if(rowData){ return rowData.getColumnValues()[0].toString(); }else{ return "empty"; }}]]> </xp:this.value> </xp:text> </xp:panel> </xp:repeat> </xp:view> Filtering of your view data is done at the datasource level.
[ "stackoverflow", "0010892506.txt" ]
Q: From Rails devise auth to backbone & api? i want to rebuild an app which is a typical rails 3.2 mvc app into a API + Frontend (Backbone) only. As I have no experience in building APIs in rails including authenticatin: What's the best way to authenticate with devise using backbone? Using auth_tokens? How should I make he API? Just printing out JSON or use a gem like Grape? thanks in advance! A: I can explain you the way i do this : First, i install a standard rails application with devise. After that, i create my own session controller : class SessionsController < ApplicationController def authenticate # this method logs you in and returns you a single_access_token token for authentication. @user = User.find_for_authentication(:email => params[:user][:email]) if @user && @user.valid_password?(params[:user][:password]) render :json => {:user => {:email => @user.email, :id => @user.id, :firsname => @user.firstname, :lastname => @user.lastname, :team_id => @user.team_id, :singleAccessToken => @user.generate_access_token}} else render :json => {:errors => ["Nom d'utilisateur ou mot de passe invalide"]}, :status => 401 end end end As you can see, i send a request to this url with the json looking like : { user => { email => "[email protected]", password => "monpass" } } And my controller return me the json with user data if every thing is fine, or an error. On json with user, i return an access_token used on next requests to check that the user is allowed to request. I made this filters in my application controller : class ApplicationController < ActionController::Base protect_from_forgery protected def user_access_token request.headers["HTTP_X_USER_ACCESS_TOKEN"] || request.headers["HTTP_USER_ACCESS_TOKEN"] end def current_user if token = user_access_token @user ||= User.find_by_access_token(token) end end def require_user unless current_user render :json => {:error => "Invalid Access Token"}, :status => 401 end end def require_owner unless current_user && current_user == object.user render :json => {:error => "Unauthorized"} end end end As you can see, on each next request, i will add the access_token in html header on key : HTTP_USER_ACCESS_TOKEN So, i can check if the user is allowed to make the request. To make an API, you can use the Rails API gem as see here : http://railscasts.com/episodes/348-the-rails-api-gem Good luck.
[ "stackoverflow", "0027186257.txt" ]
Q: How can I get only a part of a json file instead of the entire thing with php? I'm connecting to the trakt.tv api, I want to create a little app for myself that displays movies posters with ratings etc. This is what I'm currently using to retrieve their .json file containing all the info I need. $json = file_get_contents('http://api.trakt.tv/movies/trending.json/2998fbac88fd207cc762b1cfad8e34e6'); $movies = json_decode($json, true); $movies = array_slice($movies, 0, 20); foreach($movies as $movie) { echo $movie['images']['fanart']; } Because the .json file is huge it is loading pretty slow. I only need a couple of attributes from the file, like title,rating and the poster link. Besides that I only need the first 20 or so. How can I make sure to load only a part of the .json file to load it faster? Besides that I'm not experienced with php in combination with .json so if my code is garbage and you have suggestions I would love to hear them. A: Unless the API provides a limit parameter or similar, I don't think you can limit the query at your side. On a quick look it doesn't seem to provide this. It also doesn't look like it really returns that much data (under 100KB), so I guess it is just slow. Given the slow API I'd cache the data you receive and only update it once per hour or so. You could save it to a file on your server using file_put_contents and record the time it was saved too. When you need to use the data, if the saved data is over an hour old, refresh it. This quick sketch of an idea works: function get_trending_movies() { if(! file_exists('trending-cache.php')) { return cache_trending_movies(); } include('trending-cache.php'); if(time() - $movies['retreived-timestamp'] > 60 * 60) { // 60*60 = 1 hour return cache_trending_movies(); } else { unset($movies['retreived-timestamp']); return $movies; } } function cache_trending_movies() { $json = file_get_contents('http://api.trakt.tv/movies/trending.json/2998fbac88fd207cc762b1cfad8e34e6'); $movies = json_decode($json, true); $movies = array_slice($movies, 0, 20); $movies_with_date = $movies; $movies_with_date['retreived-timestamp'] = time(); file_put_contents('trending-cache.php', '<?php $movies = ' . var_export($movies_with_date, true) . ';'); return $movies; } print_r(get_trending_movies());
[ "stackoverflow", "0031706822.txt" ]
Q: building gcc 5.2.0 from source: configure: error: C compiler cannot create executables I am trying to build gcc 5.2.0 from source in my local $HOME directory and I get the following errors: gcc-gcc_5_2_0_release> ./configure --prefix=$HOME/usr/local checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking target system type... x86_64-unknown-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking whether ln works... yes checking whether ln -s works... yes checking for a sed that does not truncate output... /usr/bin/sed checking for gawk... gawk checking for libatomic support... yes checking for libcilkrts support... yes checking for libitm support... yes checking for libsanitizer support... yes checking for libvtv support... yes checking for gcc... gcc checking for C compiler default output file name... configure: error: in `/home/s31941/tmp/gcc-gcc_5_2_0_release': configure: error: C compiler cannot create executables See `config.log' for more details. here is a copy of the config.log This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by configure, which was generated by GNU Autoconf 2.64. Invocation command line was $ ./configure --prefix=/home/username/usr/local ## --------- ## ## Platform. ## ## --------- ## hostname = fmsserv uname -m = x86_64 uname -r = 3.0.101-0.46-default uname -s = Linux uname -v = #1 SMP Wed Dec 17 11:04:10 UTC 2014 (8356111) /usr/bin/uname -p = unknown /bin/uname -X = unknown /bin/arch = x86_64 /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown /usr/bin/hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /home/username/usr/local/bin PATH: /home/username/tools/git/bin PATH: /home/username/tools/java/jre1.8.0_40/bin PATH: /home/username/tools/eclipse PATH: . PATH: /usr/NX/bin PATH: /usr/lib64/mpi/gcc/openmpi/bin PATH: /home/username/bin PATH: /usr/local/bin PATH: /usr/bin PATH: /bin PATH: /usr/bin/X11 PATH: /usr/X11R6/bin PATH: /usr/games PATH: /opt/kde3/bin PATH: /usr/lib/mit/bin PATH: /usr/lib/mit/sbin PATH: /opt/gnome/bin PATH: /usr/lib/qt3/bin PATH: /home/fms/bin PATH: /usr/gnat/bin PATH: . ## ----------- ## ## Core tests. ## ## ----------- ## configure:2292: checking build system type configure:2306: result: x86_64-unknown-linux-gnu configure:2353: checking host system type configure:2366: result: x86_64-unknown-linux-gnu configure:2386: checking target system type configure:2399: result: x86_64-unknown-linux-gnu configure:2453: checking for a BSD-compatible install configure:2521: result: /usr/bin/install -c configure:2532: checking whether ln works configure:2554: result: yes configure:2558: checking whether ln -s works configure:2562: result: yes configure:2569: checking for a sed that does not truncate output configure:2633: result: /usr/bin/sed configure:2642: checking for gawk configure:2658: found /usr/bin/gawk configure:2669: result: gawk configure:3183: checking for libatomic support configure:3193: result: yes configure:3202: checking for libcilkrts support configure:3212: result: yes configure:3240: checking for libitm support configure:3250: result: yes configure:3259: checking for libsanitizer support configure:3269: result: yes configure:3278: checking for libvtv support configure:3288: result: yes configure:4074: checking for gcc configure:4090: found /usr/bin/gcc configure:4101: result: gcc configure:4330: checking for C compiler version configure:4339: gcc --version >&5 gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973] Copyright (C) 2008 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. configure:4350: $? = 0 configure:4339: gcc -v >&5 Using built-in specs. Target: x86_64-suse-linux Configured with: ../configure --prefix=/usr --infodir=/usr/share/info --mandir=/usr/share/man --libdir=/usr/lib64 --libexecdir=/usr/lib64 --enable-languages=c,c++,objc,fortran,obj-c++,java,ada --enable-checking=release --with-gxx-include-dir=/usr/include/c++/4.3 --enable-ssp --disable-libssp --with-bugurl=http://bugs.opensuse.org/ --with-pkgversion='SUSE Linux' --disable-libgcj --disable-libmudflap --with-slibdir=/lib64 --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-allocator=new --disable-libstdcxx-pch --enable-version-specific-runtime-libs --program-suffix=-4.3 --enable-linux-futex --without-system-libunwind --with-cpu=generic --build=x86_64-suse-linux Thread model: posix gcc version 4.3.4 [gcc-4_3-branch revision 152973] (SUSE Linux) configure:4350: $? = 0 configure:4339: gcc -V >&5 gcc: '-V' option must have argument configure:4350: $? = 1 configure:4339: gcc -qversion >&5 gcc: unrecognized option '-qversion' gcc: no input files configure:4350: $? = 1 configure:4370: checking for C compiler default output file name configure:4392: gcc conftest.c >&5 gcc: error trying to exec 'cc1': execvp: No such file or directory configure:4396: $? = 1 configure:4433: result: configure: failed program was: | /* confdefs.h */ | #define PACKAGE_NAME "" | #define PACKAGE_TARNAME "" | #define PACKAGE_VERSION "" | #define PACKAGE_STRING "" | #define PACKAGE_BUGREPORT "" | #define PACKAGE_URL "" | /* end confdefs.h. */ | | int | main () | { | | ; | return 0; | } configure:4439: error: in `/home/username/tmp/gcc-gcc_5_2_0_release': configure:4443: error: C compiler cannot create executables See `config.log' for more details. ## ---------------- ## ## Cache variables. ## ## ---------------- ## ac_cv_build=x86_64-unknown-linux-gnu ac_cv_env_AR_FOR_TARGET_set= ac_cv_env_AR_FOR_TARGET_value= ac_cv_env_AR_set= ac_cv_env_AR_value= ac_cv_env_AS_FOR_TARGET_set= ac_cv_env_AS_FOR_TARGET_value= ac_cv_env_AS_set= ac_cv_env_AS_value= ac_cv_env_CCC_set= ac_cv_env_CCC_value= ac_cv_env_CC_FOR_TARGET_set= ac_cv_env_CC_FOR_TARGET_value= ac_cv_env_CC_set= ac_cv_env_CC_value= ac_cv_env_CFLAGS_set= ac_cv_env_CFLAGS_value= ac_cv_env_CPPFLAGS_set= ac_cv_env_CPPFLAGS_value= ac_cv_env_CXXFLAGS_set= ac_cv_env_CXXFLAGS_value= ac_cv_env_CXX_FOR_TARGET_set= ac_cv_env_CXX_FOR_TARGET_value= ac_cv_env_CXX_set= ac_cv_env_CXX_value= ac_cv_env_DLLTOOL_FOR_TARGET_set= ac_cv_env_DLLTOOL_FOR_TARGET_value= ac_cv_env_DLLTOOL_set= ac_cv_env_DLLTOOL_value= ac_cv_env_GCC_FOR_TARGET_set= ac_cv_env_GCC_FOR_TARGET_value= ac_cv_env_GCJ_FOR_TARGET_set= ac_cv_env_GCJ_FOR_TARGET_value= ac_cv_env_GFORTRAN_FOR_TARGET_set= ac_cv_env_GFORTRAN_FOR_TARGET_value= ac_cv_env_GOC_FOR_TARGET_set= ac_cv_env_GOC_FOR_TARGET_value= ac_cv_env_LDFLAGS_set= ac_cv_env_LDFLAGS_value= ac_cv_env_LD_FOR_TARGET_set= ac_cv_env_LD_FOR_TARGET_value= ac_cv_env_LD_set= ac_cv_env_LD_value= ac_cv_env_LIBS_set= ac_cv_env_LIBS_value= ac_cv_env_LIPO_FOR_TARGET_set= ac_cv_env_LIPO_FOR_TARGET_value= ac_cv_env_LIPO_set= ac_cv_env_LIPO_value= ac_cv_env_NM_FOR_TARGET_set= ac_cv_env_NM_FOR_TARGET_value= ac_cv_env_NM_set= ac_cv_env_NM_value= ac_cv_env_OBJCOPY_FOR_TARGET_set= ac_cv_env_OBJCOPY_FOR_TARGET_value= ac_cv_env_OBJCOPY_set= ac_cv_env_OBJCOPY_value= ac_cv_env_OBJDUMP_FOR_TARGET_set= ac_cv_env_OBJDUMP_FOR_TARGET_value= ac_cv_env_OBJDUMP_set= ac_cv_env_OBJDUMP_value= ac_cv_env_RANLIB_FOR_TARGET_set= ac_cv_env_RANLIB_FOR_TARGET_value= ac_cv_env_RANLIB_set= ac_cv_env_RANLIB_value= ac_cv_env_READELF_FOR_TARGET_set= ac_cv_env_READELF_FOR_TARGET_value= ac_cv_env_READELF_set= ac_cv_env_READELF_value= ac_cv_env_STRIP_FOR_TARGET_set= ac_cv_env_STRIP_FOR_TARGET_value= ac_cv_env_STRIP_set= ac_cv_env_STRIP_value= ac_cv_env_WINDMC_FOR_TARGET_set= ac_cv_env_WINDMC_FOR_TARGET_value= ac_cv_env_WINDMC_set= ac_cv_env_WINDMC_value= ac_cv_env_WINDRES_FOR_TARGET_set= ac_cv_env_WINDRES_FOR_TARGET_value= ac_cv_env_WINDRES_set= ac_cv_env_WINDRES_value= ac_cv_env_build_alias_set= ac_cv_env_build_alias_value= ac_cv_env_build_configargs_set= ac_cv_env_build_configargs_value= ac_cv_env_host_alias_set= ac_cv_env_host_alias_value= ac_cv_env_host_configargs_set= ac_cv_env_host_configargs_value= ac_cv_env_target_alias_set= ac_cv_env_target_alias_value= ac_cv_env_target_configargs_set= ac_cv_env_target_configargs_value= ac_cv_host=x86_64-unknown-linux-gnu ac_cv_path_SED=/usr/bin/sed ac_cv_path_install='/usr/bin/install -c' ac_cv_prog_AWK=gawk ac_cv_prog_ac_ct_CC=gcc ac_cv_target=x86_64-unknown-linux-gnu acx_cv_prog_LN=ln ## ----------------- ## ## Output variables. ## ## ----------------- ## AR='' AR_FOR_BUILD='$(AR)' AR_FOR_TARGET='' AS='' AS_FOR_BUILD='$(AS)' AS_FOR_TARGET='' AWK='gawk' BISON='' BUILD_CONFIG='' CC='gcc' CC_FOR_BUILD='$(CC)' CC_FOR_TARGET='' CFLAGS='' CFLAGS_FOR_BUILD='' CFLAGS_FOR_TARGET='' COMPILER_AS_FOR_TARGET='' COMPILER_LD_FOR_TARGET='' COMPILER_NM_FOR_TARGET='' CONFIGURE_GDB_TK='' CPPFLAGS='' CXX='' CXXFLAGS='' CXXFLAGS_FOR_BUILD='' CXXFLAGS_FOR_TARGET='' CXX_FOR_BUILD='$(CXX)' CXX_FOR_TARGET='' DEBUG_PREFIX_CFLAGS_FOR_TARGET='' DEFS='' DLLTOOL='' DLLTOOL_FOR_BUILD='$(DLLTOOL)' DLLTOOL_FOR_TARGET='' ECHO_C='' ECHO_N='-n' ECHO_T='' EXEEXT='' EXPECT='' EXTRA_CONFIGARGS_LIBJAVA='--disable-static' FLAGS_FOR_TARGET='' FLEX='' GCC_FOR_TARGET='' GCC_SHLIB_SUBDIR='' GCJ_FOR_BUILD='$(GCJ)' GCJ_FOR_TARGET='' GDB_TK='' GFORTRAN_FOR_BUILD='$(GFORTRAN)' GFORTRAN_FOR_TARGET='' GNATBIND='' GNATMAKE='' GOC_FOR_BUILD='$(GOC)' GOC_FOR_TARGET='' INSTALL_DATA='${INSTALL} -m 644' INSTALL_GDB_TK='' INSTALL_PROGRAM='${INSTALL}' INSTALL_SCRIPT='${INSTALL}' LD='' LDFLAGS='' LDFLAGS_FOR_BUILD='' LDFLAGS_FOR_TARGET='' LD_FOR_BUILD='$(LD)' LD_FOR_TARGET='' LEX='' LIBOBJS='' LIBS='' LIPO='' LIPO_FOR_TARGET='' LN='ln' LN_S='ln -s' LTLIBOBJS='' M4='' MAINT='' MAINTAINER_MODE_FALSE='' MAINTAINER_MODE_TRUE='' MAKEINFO='' NM='' NM_FOR_BUILD='$(NM)' NM_FOR_TARGET='' OBJCOPY='' OBJCOPY_FOR_TARGET='' OBJDUMP='' OBJDUMP_FOR_TARGET='' OBJEXT='' PACKAGE_BUGREPORT='' PACKAGE_NAME='' PACKAGE_STRING='' PACKAGE_TARNAME='' PACKAGE_URL='' PACKAGE_VERSION='' PATH_SEPARATOR=':' RANLIB='' RANLIB_FOR_BUILD='$(RANLIB)' RANLIB_FOR_TARGET='' RAW_CXX_FOR_TARGET='' READELF='' READELF_FOR_TARGET='' RPATH_ENVVAR='' RUNTEST='' SED='/usr/bin/sed' SHELL='/bin/sh' STRIP='' STRIP_FOR_TARGET='' SYSROOT_CFLAGS_FOR_TARGET='' TOPLEVEL_CONFIGURE_ARGUMENTS='./configure --prefix=/home/username/usr/local' WINDMC='' WINDMC_FOR_BUILD='$(WINDMC)' WINDMC_FOR_TARGET='' WINDRES='' WINDRES_FOR_BUILD='$(WINDRES)' WINDRES_FOR_TARGET='' YACC='' ac_ct_CC='gcc' ac_ct_CXX='' bindir='${exec_prefix}/bin' build='x86_64-unknown-linux-gnu' build_alias='' build_configargs='' build_configdirs='build-libiberty build-libcpp build-texinfo build-flex build-bison build-m4 build-fixincludes' build_cpu='x86_64' build_libsubdir='build-x86_64-unknown-linux-gnu' build_noncanonical='x86_64-unknown-linux-gnu' build_os='linux-gnu' build_subdir='build-x86_64-unknown-linux-gnu' build_tooldir='' build_vendor='unknown' compare_exclusions='' configdirs='intl libiberty opcodes bfd readline tcl tk itcl libgui zlib libbacktrace libcpp libdecnumber gmp mpfr mpc isl libelf libiconv texinfo flex bison binutils gas ld fixincludes gcc cgen sid sim gdb gprof etc expect dejagnu m4 utils guile fastjar gnattools libcc1 gotools' datadir='${datarootdir}' datarootdir='${prefix}/share' do_compare='' docdir='${datarootdir}/doc/${PACKAGE}' dvidir='${docdir}' exec_prefix='NONE' extra_host_libiberty_configure_flags='' extra_isl_gmp_configure_flags='' extra_liboffloadmic_configure_flags='' extra_linker_plugin_configure_flags='' extra_linker_plugin_flags='' extra_mpc_gmp_configure_flags='' extra_mpc_mpfr_configure_flags='' extra_mpfr_configure_flags='' gmpinc='' gmplibs='' host='x86_64-unknown-linux-gnu' host_alias='' host_configargs='' host_cpu='x86_64' host_noncanonical='x86_64-unknown-linux-gnu' host_os='linux-gnu' host_shared='' host_subdir='host-x86_64-unknown-linux-gnu' host_vendor='unknown' htmldir='${docdir}' includedir='${prefix}/include' infodir='${datarootdir}/info' islinc='' isllibs='' libdir='${exec_prefix}/lib' libexecdir='${exec_prefix}/libexec' localedir='${datarootdir}/locale' localstatedir='${prefix}/var' mandir='${datarootdir}/man' oldincludedir='/usr/include' pdfdir='${docdir}' poststage1_ldflags='' poststage1_libs='' prefix='/home/username/usr/local' program_transform_name='s,y,y,' psdir='${docdir}' sbindir='${exec_prefix}/sbin' sharedstatedir='${prefix}/com' stage1_cflags='' stage1_checking='' stage1_languages='' stage1_ldflags='' stage1_libs='' stage2_werror_flag='' sysconfdir='${prefix}/etc' target='x86_64-unknown-linux-gnu' target_alias='' target_configargs='' target_configdirs='target-libgcc target-libbacktrace target-libgloss target-newlib target-libgomp target-libcilkrts target-liboffloadmic target-libatomic target-libitm target-libstdc++-v3 target-libsanitizer target-libvtv target-libmpx target-libssp target-libquadmath target-libgfortran target-boehm-gc target-libffi target-zlib target-libjava target-libobjc target-libada target-libgo target-rda' target_cpu='x86_64' target_noncanonical='x86_64-unknown-linux-gnu' target_os='linux-gnu' target_subdir='x86_64-unknown-linux-gnu' target_vendor='unknown' tooldir='' ## ------------------- ## ## File substitutions. ## ## ------------------- ## alphaieee_frag='' host_makefile_frag='/dev/null' ospace_frag='' serialization_dependencies='' target_makefile_frag='' ## ----------- ## ## confdefs.h. ## ## ----------- ## /* confdefs.h */ #define PACKAGE_NAME "" #define PACKAGE_TARNAME "" #define PACKAGE_VERSION "" #define PACKAGE_STRING "" #define PACKAGE_BUGREPORT "" #define PACKAGE_URL "" configure: exit 77 Any help determining whats wrong would be greatly appreciated. gcc-gcc_5_2_0_release> which ld /usr/bin/ld gcc-gcc_5_2_0_release> which gcc /usr/bin/gcc gcc-gcc_5_2_0_release> ld --version GNU ld (GNU Binutils; SUSE Linux Enterprise 11) 2.23.1 Copyright 2012 Free Software Foundation, Inc. This program is free software; you may redistribute it under the terms of the GNU General Public License version 3 or (at your option) a later version. This program has absolutely no warranty. gcc-gcc_5_2_0_release> gcc --version gcc (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973] Copyright (C) 2008 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. A: First, it is documented that GCC should not be built inside its source tree: First, we highly recommend that GCC be built into a separate directory from the sources which does not reside within the source tree. Then you need to be sure that the prefix tree exists. I believe that your choice $HOME/usr/local/ is a poor one (it is confusing). I suggest using $HOME/soft/ instead. If you have a Debian or similar distribution, be sure to aptitude install build-dep gcc g++ before configuring (You might need some deb-src line in your /etc/apt/sources.list file). This will download all the software required to build GCC. Don't forget to aptitude install gcc g++ build-essential in all cases (to have a working gcc & g++ system compilers). On SUSE, try to find the equivalent packages and commands: gcc-c++ package, build service. So I suggest to start again. Use mkdir -p -$HOME/tmp/softbuilds mkdir -p $HOME/soft/ cd $HOME/tmp/ ## the following URL is not the best one, choose carefully the server wget http://open-source-box.org/gcc/gcc-5.2.0/gcc-5.2.0.tar.bz2 cd softbuilds tar xvf ../gcc-5.2.0.tar.bz2 mkdir _GCC-5.2_Build cd _GCC-5.2_Build ../gcc-5.2.0/configure --help ## you could add some other configure options here: ../gcc-5.2.0/configure --prefix=$HOME/soft --program-suffix=-mine \ --enable-plugins --enable-languages=c,c++,jit,lto,go \ --enable-check=release --enable-host-shared If the configuration step succeeded, you compile the thing with make -j 3 Then (perhaps a few hours later) install it with: make #to be sure all went ok make install Then add $HOME/soft/bin/ to your PATH (e.g. by editing .bashrc ...) and use gcc-mine as your compiler (e.g. make CC=gcc-mine) If you want to always use your GCC, and if $HOME/bin/ is early in your $PATH, you might make symlinks from $HOME/soft/bin/gcc-mine to $HOME/bin/gcc (and likewise for g++-mine ...). BTW, you could later install the MELT meta-plugin for your GCC. I have released MELT 1.2.0 for GCC 4.9 & 5.x a few days ago (end of july 2015).
[ "math.stackexchange", "0000576592.txt" ]
Q: Show that $\frac{xy}{z} + \frac{xz}{y} + \frac{yz}{x} \geq x+y+z $ by considering homogeneity Well, I'm preparing for an undergrad competition that is held in April and because of that I've been trying to solve the inequalities I find on the internet. I found this problem: $$\displaystyle \frac{xy}{z} + \frac{xz}{y} + \frac{yz}{x} \geq x+y+z \text{ for all } x,y,z \in \mathbb{R^+}$$ It's easy to show that this inequality holds by applying the AM-GM inequality three times like the following: $$ \frac{xy}{z} + \frac{xz}{y} \geq 2 \sqrt{\frac{xy}{z} \cdot\frac{xz}{y}} = 2x$$ $$ \frac{xy}{z} + \frac{yz}{x} \geq 2 \sqrt{\frac{xy}{z} \cdot\frac{yz}{x}} = 2y$$ $$ \frac{zy}{x} + \frac{xz}{y} \geq 2 \sqrt{\frac{zy}{x} \cdot\frac{xz}{y}} = 2z$$ Then summing these inequalities and canceling a factor of $2$ at the end will give us the desired inequality. But if you look at the problem from another point of view, if we substitute $x'=\lambda x$, $y'=\lambda y$ and $z' = \lambda z$ the inequality stays the same. So, I was wondering if there could be another way of solving this inequality and the inequalities that are homogenous like this one in a more systematic way that could be applied to a broader range of problems. I decided to add a constraint $x^2+y^2+z^2=1$ to the problem because the inequality in the problem could be thought of as a function in the three variables $x,y,z$ in $\mathbb{R}^3$. So, it's sufficient to study this function on the unit sphere because homogeneity allows us to define it for other points of $\mathbb{R}^3$, but I have no idea how this could lead me anywhere. A: Here's one way to take advantage of the homogeneity. By symmetry and homogeneity, one can assume without loss of generality that $z=\min(x,y,z)$ and that $z=1$. This reduces the problem to the following. Proposition: If $x\ge1$ and $y\ge1$, then $\displaystyle \frac{x}{y}+\frac{y}{x}+xy \ge 1+x+y$. Proof: Assume that $x\ge1$ and $y\ge1$. Then $$x y=((x-1)+1)((y-1)+1)=$$ $$(x-1)+(y-1)+1+(x-1)(y-1)\ge x+y-1\textrm,$$ because $(x-1)(y-1)$ is non-negative. The sum of a positive real number and its reciprocal is always at least 2, so $$\frac{x}{y}+\frac{y}{x} \ge 2\textrm.$$ Combining these two inequalities gives the desired result.
[ "stackoverflow", "0008278833.txt" ]
Q: Java SE find the adjacent PCs or Devices on the network I have seen applications that can detect adjacent networks and desktops and devices attached to them. They can also know the computer/device name that is attached within 30 seconds. Shall I try runtime.execute ping and net view command to do it, for I find them fast. How can I capture the output as a result from these commands? I tried sockets but they are time consuming.. only advantage, that I can also know that they have application installed (in which I created socket, enabling this communication). Regards A: Time-Outs in the initialization of Socket are useful, but you cannot have each connection connected within less than 300 Milli-seconds. On the server side also there is a timeout implementation. There is one sided communication in both. Multi-threading will help.
[ "askubuntu", "0000420396.txt" ]
Q: ntop: INTERFACES is not defined, please run 'dpkg-reconfigure ntop' and ntop is broken or not fully installed I am go into a dead loop of install and configure ntop. It tells me ntop: INTERFACES is not defined, please run 'dpkg-reconfigure ntop' on startup, but this command leads to ntop is broken or not fully installed. Is there any way to manually reconfigure ntop? A: Try this: sudo apt-get purge ntop; sudo apt-get install ntop Then the follow screen popps: **Package configuration ┌─────────────────────────┤ Configuring ntop ├─────────────────────────┐ │ Please enter a comma-separated list of interfaces that ntop should │ │ listen on. │ │ │ │ Interfaces for ntop to listen on: │ │ │ │ none________________________________________________________________ │ │ │ │ │ │ │ └─────────────────────────────────────────────────────────────────── You can get the interface name if you click on the Network Manager in your top panel and select Connection Information. Near the top, you'll see something like "Interface: Ethernet (eth0)". If that's the connection you want to monitor, you'll enter "eth0". (Answer copied and pasted from answered Nov 1 at 19:41Jo-Erlend Schinstad) I hope I was able to help you. Cheers.
[ "softwareengineering.meta.stackexchange", "0000007202.txt" ]
Q: Question closed because of "asking for advice on what to do" My question got closed as off-topic with the reason that it's "asking for advice on what to do": https://softwareengineering.stackexchange.com/questions/274551/what-are-the-possible-repercussions-of-developing-an-application-for-a-customer?noredirect=1#comment562488_274551 I am trying to understand why, and if there is anything more I can do to salvage the question. The link of the close comment links to this meta post on The Workplace: https://workplace.meta.stackexchange.com/questions/2693/custom-off-topic-close-reasons-change/2695#2695 I am not even sure why a Workplace meta post counts as a reason to close on Programmers, but I followed the advice there anyway: Another alternative is to edit your post to ask about why and how you should make the decision, rather than just what decision to make. For instance, instead of asking "Should I take the job in the big multi-national company or the up-and-coming startup?" you could ask a question that will help you make that decision, like "How can I figure out the financial health of a startup I am applying to by asking questions in an interview?" So I edited the question to not ask for what I should do, but for information that helps me make the decision myself. The question got closed anyway. Also I am not sure that the reason for closure in the meta post even applies to me: Our goal here at The Workplace is to help out people in the future who are facing the same problem. When people ask us for personalized advice, a lot of the specific details will not apply to other people who come across the question since their details may be slightly different and they can't determine whether or not the answer is appropriate for their situation. The problem in the question is pretty generic and I tried to keep it general enough so that it will be helpful to people with a similar problem (customers asking for something that violates someone else's TOS). Someone mentioned that it is a matter of legal advice, but that's only a part of the problem really. Also, there are many other questions with a similar direction that weren't closed for that reason, for example: Is it possible to rewrite every line of an open source project in a slightly different way, and use it in a closed source project? What to do if you find a vulnerability in a competitor's site? Both of those questions handle legal topics as well, but are deemed on-topic. Can someone explain to me why my question is off-topic? Is there a chance to edit it so it could be reopened? If yes, in what way should I change the question? EDIT: To make my point, this question is both about a legal topic and asking what to do (and in relation to a client asking for something risky as well on top!), and still is on-topic: Should I accept to write unsecure code if my employer requests me to do so? I really have a hard time to see where the line is between on- and off-topic questions here to be honest. A: The question of: What are the possible repercussions of developing an application for a customer that will violate the TOS of another company? is one that is purely a legal one. The possible repercussions are whatever the lawyers at the company dream up. As this is a legal question, it is not one that we, as programmers, can answer and is thus off topic under the category of 'legal assistance' as described in the help center.
[ "stackoverflow", "0002497930.txt" ]
Q: How do I prevent the concurrent execution of a javascript function? I am making a ticker similar to the "From the AP" one at The Huffington Post, using jQuery. The ticker rotates through a ul, either by user command (clicking an arrow) or by an auto-scroll. Each list-item is display:none by default. It is revealed by the addition of a "showHeadline" class which is display:list-item. HTML for the UL Looks like this: <ul class="news" id="news"> <li class="tickerTitle showHeadline">Test Entry</li> <li class="tickerTitle">Test Entry2</li> <li class="tickerTitle">Test Entry3</li> </ul> When the user clicks the right arrow, or the auto-scroll setTimeout goes off, it runs a tickForward() function: function tickForward(){ var $active = $('#news li.showHeadline'); var $next = $active.next(); if($next.length==0) $next = $('#news li:first'); $active.stop(true, true); $active.fadeOut('slow', function() {$active.removeClass('showHeadline');}); setTimeout(function(){$next.fadeIn('slow', function(){$next.addClass('showHeadline');})}, 1000); if(isPaused == true){ } else{ startScroll() } }; This is heavily inspired by Jon Raasch's A Simple jQuery Slideshow. Basically, find what's visible, what should be visible next, make the visible thing fade and remove the class that marks it as visible, then fade in the next thing and add the class that makes it visible. Now, everything is hunky-dory if the auto-scroll is running, kicking off tickForward() once every three seconds. But if the user clicks the arrow button repeatedly, it creates two negative conditions: Rather than advance quickly through the list for just the number of clicks made, it continues scrolling at a faster-than-normal rate indefinitely. It can produce a situation where two (or more) list items are given the .showHeadline class, so there's overlap on the list. I can see these happening (especially #2) because the tickForward() function can run concurrently with itself, producing different sets of $active and $next. So I think my question is: What would be the best way to prevent concurrent execution of the tickForward() method? Some things I have tried or considered: Setting a Flag: When tickForward() runs, it sets an isRunning flag to true, and sets it back to false right before it ends. The logic for the event handler is set to only call tickForward() if isRunning is false. I tried a simple implementation of this, and isRunning never appeared to be changed. The jQuery queue(): I think it would be useful to queue up the tickForward() commands, so if you clicked it five times quickly, it would still run as commanded but wouldn't run concurrently. However, in my cursory reading on the subject, it appears that a queue has to be attached to the object its queue applies to, and since my tickForward() method affects multiple lis, I don't know where I'd attach it. A: You can't have concurrent executions of a function in javascript. You just have several calls waiting to execute in order on the pile of execution. So setting a flag when the function runs cannot work. When the event handler runs, it cannot run concurrently with a tickHandler() execution (javascript is threadless). Now you have to define precisely what you want, because it doesn't appear in your question. What you happen when the user clicks, say, 3 times in rapid succession on the arrow? And how do the clicks interfere with the auto-scroll? I'd say the easiest way would be to process a click only when the ticker is idle, so 3 clicks in a row will only tick once. And you make clicks replace auto-scroll and reset its timer. So I use a flag ticksInQueue that is raised when a tick is queue by a click and only lowered when the fadeIn has completed: var ticksInQueue = 0, timerId = setInterval(tickForward, 5000), isPaused = false; function tickForward() { var $active = $('#news li.showHeadline'); var $next = $active.next(); if($next.length==0) $next = $('#news li:first'); $active.stop(true, true); $active.fadeOut('slow', function() { $active.removeClass('showHeadline'); }); setTimeout(function(){ $next.fadeIn('slow', function(){ $next.addClass('showHeadline'); if(ticksInQueue) ticksInQueue--; // only change })}, 1000); if(isPaused == true){ } else { startScroll() } } $('#arrow').click(function () { if(ticksInQueue) return; ticksInQueue++; clearInterval(timerId); timerId = setInterval(tickForward, 5000); tickForward(); }); You can try a demo here : http://jsfiddle.net/mhaCF/
[ "stackoverflow", "0018552977.txt" ]
Q: Using Capistrano and error occurs during execution of cap deploy I'm using Capistrano to help deploy a Rails project and when I run the command cap deploy I get the following error produced below. Anyone have an idea what's going wrong? Here is the error that is being generated when it's trying to execute the command. * executing "cd -- /var/www/crowdcode/releases/20130831210643 && RAILS_ENV=production RAILS_GROUPS=assets bundle exec rake assets:precompile" servers: ["54.215.187.53"] [54.215.187.53] executing command *** [err :: 54.215.187.53] Faraday: you may want to install system_timer for reliable timeouts *** [err :: 54.215.187.53] *** [err :: 54.215.187.53] rake aborted! *** [err :: 54.215.187.53] /var/www/crowdcode/releases/20130831210643/config/initializers/redis.rb:1: syntax error, unexpected ':', expecting ')' *** [err :: 54.215.187.53] $redis = Redis.new(host: 'localhost', port: 6379, driver: :hiredis) *** [err :: 54.215.187.53] ^ *** [err :: 54.215.187.53] /var/www/crowdcode/releases/20130831210643/config/initializers/redis.rb:1: syntax error, unexpected ',', expecting $end *** [err :: 54.215.187.53] $redis = Redis.new(host: 'localhost', port: 6379, driver: :hiredis) *** [err :: 54.215.187.53] ^ *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:245:in `load' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:245:in `load' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:236:in `load_dependency' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:245:in `load' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/engine.rb:588 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/engine.rb:587:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/engine.rb:587 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/initializable.rb:30:in `instance_exec' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/initializable.rb:30:in `run' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/initializable.rb:55:in `run_initializers' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/initializable.rb:54:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/initializable.rb:54:in `run_initializers' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/application.rb:136:in `initialize!' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/railtie/configurable.rb:30:in `send' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/railtie/configurable.rb:30:in `method_missing' *** [err :: 54.215.187.53] /var/www/crowdcode/releases/20130831210643/config/environment.rb:5 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `require' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `require' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:236:in `load_dependency' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/activesupport-3.2.11/lib/active_support/dependencies.rb:251:in `require' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/application.rb:103:in `require_environment!' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/railties-3.2.11/lib/rails/application.rb:297:in `initialize_tasks' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `call' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:184:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:177:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:170:in `invoke' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/actionpack-3.2.11/lib/sprockets/assets.rake:93 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `call' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:184:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:177:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:205:in `invoke_prerequisites' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:203:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:203:in `invoke_prerequisites' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:183:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:177:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:170:in `invoke' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/actionpack-3.2.11/lib/sprockets/assets.rake:60 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `call' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:184:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:177:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:170:in `invoke' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/actionpack-3.2.11/lib/sprockets/assets.rake:23:in `invoke_or_reboot_rake_task' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/actionpack-3.2.11/lib/sprockets/assets.rake:29 *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `call' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:246:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:241:in `execute' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:184:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:177:in `invoke_with_call_chain' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/task.rb:170:in `invoke' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:143:in `invoke_task' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:101:in `top_level' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:101:in `each' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:101:in `top_level' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:110:in `run_with_threads' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:95:in `top_level' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:73:in `run' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:160:in `standard_exception_handling' *** [err :: 54.215.187.53] /var/www/crowdcode/shared/bundle/ruby/1.8/gems/rake-10.0.4/lib/rake/application.rb:70:in `run' *** [err :: 54.215.187.53] Tasks: TOP => environment *** [err :: 54.215.187.53] (See full trace by running task with --trace) command finished in 2472ms *** [deploy:update_code] rolling back * executing "rm -rf /var/www/crowdcode/releases/20130831210643; true" servers: ["54.215.187.53"] [54.215.187.53] executing command command finished in 21ms failed: "sh -c 'cd -- /var/www/crowdcode/releases/20130831210643 && RAILS_ENV=production RAILS_GROUPS=assets bundle exec rake assets:precompile'" Edit: Here's what's in redis.rb $redis = Redis.new(host: 'localhost', port: 6379, driver: :hiredis) class << $redis def get_json_list(key) str = "[" << $redis.lrange(key, 0, -1).join(',') << "]" JSON.parse(str) end end Edit 2: The issue was that it was somehow running the wrong version of Ruby and from the error we can see that it says 1.8. So I had to make sure my system defaulted to 1.9.3 and voila! No more syntax error and it was able to run fine. A: This is a shot in the dark. I would also verify that the environment that you are deploying this app to is using the same version of ruby and rails. I was getting all kinds of syntax errors when I deployed my last app and went about crazy until I realized I hadn't adjusted my rvm.
[ "stackoverflow", "0003613494.txt" ]
Q: In Ruby on Rails, if we generated a model "Animal", and now want to have "Dog", how should we do it? say, if we generated a model rails generate model animal name:string birthday:date and now we want to create other model to inherit from it (such as Dog and Cat), should we use rails generate model again or just add the files ourselves? How do we specify Dog should inherit from Animal if we use rails generate model? I think if we use rails generate model instead of adding the model files ourselves, there will be unit test files and fixture files created for us as well. A migration file is also added, except if it is using MongoDB, then there will be no migration file. A: If the Dog, Cat and other subclasses you are planning are not going to diverge away from Animal model, you can STI (Single Table Inheritance) pattern here. To do that, add a String column to Animal. And then you can have: class Dog < Animal end class Cat < Animal end >> scooby = Dog.create(:name => 'Scooby', :date => scoobys_birthdate) => #<Dog id: 42, date: "YYYY-MM-DD", type: "Dog"> To generate model Dog $ script/generate model Dog --skip-migration And then change (usually app/models/dog.rb): class Dog < ActiveRecord::Base to class Dog < Animal A: As far as I know you can't specify a superclass when generating a model. However, generators are only a stepping stone to creating your classes. You can generate the model class as normal and simply change the superclass in the generated model file. There are no other places that the inheritance relationship has to be specified for the generated files to work (the fixtures and unit tests for example don't specify super- or subclasses). So: script/generate model Dog Then change: class Dog < ActiveRecord::Base to: class Dog < Animal If you want to generate a model that will inherit from Animal using single table inheritance then you may want to specify --skip-migrations on the script/generate call (though you may want a migration to add e.g. dog-specific columns to the animals table and you will need to add a type column of type string to the animals table).
[ "stackoverflow", "0050458538.txt" ]
Q: How to Junit test a try catch block in my code I have a class with couple of methods and each with a try catch block to look for any exceptions. The code as follows: public ResponseEntity get() { try { ..... } catch (Exception e) { output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return output; } and I came up with a test case using Mokito to test the above scenario but confused how to enter into catch block of the above @Test public void testgetAllUsers_withoutexecp() { when(sMock.getAll()).thenReturn(someList); Assert.assertTrue(result.getStatusCode() == HttpStatus.OK ); } @Test(expected=NullPointerException.class) public void testgetAllUsers_execp() { when(sMock.getAll()).thenReturn(null); Assert.assertFalse(result.getStatusCode() == HttpStatus.OK ); } I tried to raise a NullPointerException but still the catch block is left out in codecoverage (by which I assume it is not been tested). please help me to write a Junit test case for this to enter exception. I am very new to all these topics. A: You can raise exception using thenThrow clause of Mockito: when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred")); and then assert like this: Assert.assertTrue(result.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR);
[ "math.stackexchange", "0000307701.txt" ]
Q: Proof in Group Theory Show that if $G$ is a finite group with identity $e$ and with an even number of elements, then there is an $a \neq e$ in $G$, such that $a \cdot a = e$. I read the solutions here http://noether.uoregon.edu/~tingey/fall02/444/hw2.pdf Why do they say $D = \{a, a^\prime\}$? Isn't $D$ not a group? There is no identity and if they include the identity they get 3 elements, which means $|D| = 3 = $ odd. A: Consider the relation on $G$ given by $g\equiv h\iff g\in\{\ h\ , h^{-1}\ \}$. It is easy to see that this is symmetric, reflexive, and transitive, and so an equivalence relation with equivalence classes $\{\ h\ ,\ h^{-1}\ \}$. The equivalence class of the identity $e$ of $G$ is $\{\ e\ \}$ containing only one element, and all equivalence classes have at most two elements. Since the order of $G$ is even, at least one equivalence class besides $\{\ e\ \}$ must have only one element, and that element is its own inverse.
[ "security.stackexchange", "0000195811.txt" ]
Q: What (besides not complying, and reporting) should I do with blackmail emails? I received the following email which claims, among other social engineering, to have installed a keylogger on a former system administrator's Linux box: I‌ kno‌w [old password deleted] o‌n‌e o‌f yo‌ur pa‌ssphra‌s‌es. Lets g‌et dir‌ectly to‌ th‌e purpo‌s‌e. No‌-on‌e ha‌s pai‌d m‌e to ch‌eck abo‌ut yo‌u. Yo‌u may not know m‌e and yo‌u a‌re proba‌bly thi‌nking why you're g‌etti‌ng thi‌s mai‌l? W‌ell, i a‌ctua‌lly pla‌ced a‌ softwa‌r‌e o‌n th‌e 18+ vi‌ds (porno‌gra‌phi‌c mat‌eri‌a‌l) w‌ebsit‌e a‌nd guess wha‌t, yo‌u vi‌si‌t‌ed this si‌te to‌ ‌exp‌eri‌‌enc‌e fun (yo‌u kno‌w wha‌t i m‌ean). Wh‌en yo‌u w‌ere wa‌tchi‌ng vi‌d‌eo‌ clips, your w‌eb bro‌ws‌er i‌niti‌a‌t‌ed functi‌o‌ni‌ng as a‌ R‌emo‌te co‌ntrol D‌eskto‌p that has a k‌eylo‌gg‌er which pro‌vi‌d‌ed m‌e wi‌th a‌cc‌ess to‌ your di‌spla‌y scr‌een and a‌lso‌ w‌ebca‌m. Just aft‌er tha‌t, my softwa‌r‌e pro‌gra‌m co‌llect‌ed all your co‌ntacts from yo‌ur M‌ess‌enger, so‌ci‌a‌l n‌etwo‌rks, a‌nd ‌ema‌i‌lacco‌unt. a‌ft‌er that i‌ mad‌e a‌ vid‌eo‌. 1st part di‌splays th‌e vi‌deo yo‌u w‌er‌e vi‌‌ewi‌ng (yo‌u ha‌v‌e a‌ ni‌c‌e ta‌st‌e haha‌), a‌nd s‌econd pa‌rt di‌splays th‌e r‌eco‌rdi‌ng of yo‌ur w‌eb ca‌m, & i‌t i‌s yo‌u. Yo‌u wi‌ll hav‌e no‌t o‌ne but two‌ cho‌ic‌es. Lets ch‌eck o‌ut ‌each o‌f th‌es‌e so‌luti‌o‌ns i‌n d‌eta‌i‌ls: Fi‌rst choi‌c‌e i‌s to n‌egl‌ect thi‌s ‌ema‌i‌l m‌essa‌g‌e. Th‌en, i a‌m go‌i‌ng to‌ s‌end yo‌ur v‌ery own r‌eco‌rd‌ed ma‌t‌eri‌a‌l to‌ ‌ea‌ch of yo‌ur your p‌erso‌nal conta‌cts a‌nd thus just think co‌nc‌erni‌ng th‌e sha‌me yo‌u f‌eel. Furth‌ermo‌re i‌f yo‌u ar‌e in a‌ roma‌nc‌e, how it i‌s going to a‌ff‌ect? La‌tter a‌lt‌erna‌tive is to pay m‌e $7000. L‌ets thi‌nk o‌f i‌t as a do‌na‌ti‌on. Subs‌equ‌ently, i mo‌st c‌erta‌i‌nly wi‌ll a‌sa‌p ‌era‌s‌e yo‌ur vid‌eo‌ fo‌o‌ta‌ge. Yo‌u co‌uld k‌e‌ep go‌i‌ng dai‌ly li‌f‌e li‌k‌e thi‌s n‌ev‌er ha‌ppen‌ed a‌nd you a‌r‌e n‌ever goi‌ng to‌ h‌ea‌r ba‌ck a‌gai‌n fro‌m m‌e. Yo‌u'll ma‌ke th‌e pa‌ym‌ent thro‌ugh Bi‌tcoi‌n (i‌f yo‌u don't kno‌w this, search 'how to‌ buy bit‌co‌i‌n' i‌n Go‌ogle s‌earch ‌engine). B‌T‌C‌ a‌ddr‌ess: 1EWaFmaMG33BB6pujkcJUFsp5PxLbQVnhw [Ca‌Se-SeNSi‌TiVe co‌py & paste i‌t] if you a‌re curi‌ous a‌bo‌ut go‌i‌ng to‌ th‌e la‌w, oka‌y, thi‌s messa‌ge ca‌nno‌t b‌e tra‌ced ba‌ck to‌ m‌e. I‌ ha‌ve co‌v‌er‌ed my mo‌ves. i‌ a‌m a‌lso no‌t trying to cha‌rg‌e a f‌e‌e so much, i pr‌ef‌er to b‌e r‌eward‌ed. i‌ ha‌v‌e a‌ sp‌eci‌fi‌c pix‌el in this ‌ema‌il m‌essa‌g‌e, a‌nd right no‌w i kno‌w tha‌t yo‌u ha‌v‌e r‌ea‌d thro‌ugh thi‌s m‌essa‌g‌e. You ha‌v‌e o‌n‌e da‌y i‌n ord‌er to make th‌e pa‌ym‌ent. i‌f i‌ do no‌t r‌ec‌ei‌v‌e th‌e B‌itC‌o‌i‌ns, i‌ wi‌ll c‌erta‌i‌nly s‌end yo‌ur vid‌eo‌ to a‌ll o‌f yo‌ur co‌nta‌cts i‌ncludi‌ng m‌emb‌ers o‌f yo‌ur fa‌mi‌ly, co‌llea‌gues, a‌nd so o‌n. Ha‌vi‌ng sa‌id tha‌t, i‌f i do g‌et pa‌id, i‌ wi‌ll ‌era‌s‌e th‌e r‌ecordi‌ng ri‌ght awa‌y. i‌f yo‌u wa‌nt ‌evi‌d‌enc‌e, reply with Y‌es th‌en i‌ wi‌ll send your vi‌d‌eo‌ r‌ecordi‌ng to‌ yo‌ur 7 conta‌cts. i‌t i‌s a‌ no‌n:negoti‌abl‌e off‌er, thus do no‌t wa‌st‌e my persona‌l ti‌me & yo‌urs by r‌esponding to‌ thi‌s ‌ema‌il. I know the standard response to ordinary spam, and the ordinary response to phishing. I reported this as phishing because it seemed a closest fit, and furthermore far more severe than "BETH ADD REAL INCHES TO YOUR PEN1S!". How can I, or should I, respond to blackmail spam? Is any LE followup appropriate? A: The only important takeaway to this particular scam is: change the password. This scam has been around since approximately July 2018 and so far there are have been no videos published (that are linked to this type of extortion) but a lot of money has changed hands. One source claimed that "So far, 30 victims have paid more than $50,000 in total". One thing that we do know, that the password that is sent is indeed real. The scammers probably did not get this by penetrating your machine, but by copying it from a database of leaked credentials that are found in shady forums. TL;DR: Change your password. Don't reuse passwords. You can also check haveibeenpwned.com to see where and when your credentials were leaked. A: Law enforcement in various jurisdictions are catching up with these types of emails. I know some that encourage people to report these types of emails. They are straight-up blackmail and that often falls under different laws than phishing. Please check what your local law enforcement has in place in your area. Secondly, because this is new, people are not equipped to know how to respond to this, so reporting to your local IT department can be important so they can block them and chase up with other employees who may have received the same email in your company. I got a panicked email from a security admin a few months ago with the same type of email, and he was asking the same question you did. While I worked with the local LE, I asked the security admin if there were copies of the email in other people's inboxes. It turned out that 15 people received the email, only one reported it, and they were all freaking out. Some were trying to figure out how to pay the blackmailer (the amount, in this case, was much lower). So, check with your local LE, and do make sure your IT department knows about it so they can help the poor souls who are freaking out. Once this becomes more mainstream, our responses can become more standard.
[ "stackoverflow", "0044675827.txt" ]
Q: How to zoom into a GraphStream View? In GraphStream visualizations Graphs can be dense. The enableAutoLayout method gives a global visualization of the Graph and so zooming is needed. How to zoom into a GraphStream View? Graph go=...; Viewer viewer = new Viewer(go, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD); viewer.enableAutoLayout(); View view = viewer.addDefaultView(false); swingNode.setContent((JComponent) view); A: I tried to find a way to zoom to the mouse cursor using the mouse wheel and stumbled across this thread, hoping to find an answer. I figured out how to zoom to the mouse eventually with GraphStream: The zoom-factor for each mouse wheel rotation in my case is 1.25 (or 0.8 when zooming out). The code calculates the new center of the graph based on the original center of the graph, the clicked point in the graph, the zoom and eventually the ratio of Px to Gu which can be retrieved from the camera. final Viewer viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_ANOTHER_THREAD); viewer.enableAutoLayout(); final View view = viewer.addDefaultView(false); view.getCamera().setViewPercent(1); ((Component) view).addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { e.consume(); int i = e.getWheelRotation(); double factor = Math.pow(1.25, i); Camera cam = view.getCamera(); double zoom = cam.getViewPercent() * factor; Point2 pxCenter = cam.transformGuToPx(cam.getViewCenter().x, cam.getViewCenter().y, 0); Point3 guClicked = cam.transformPxToGu(e.getX(), e.getY()); double newRatioPx2Gu = cam.getMetrics().ratioPx2Gu/factor; double x = guClicked.x + (pxCenter.x - e.getX())/newRatioPx2Gu; double y = guClicked.y - (pxCenter.y - e.getY())/newRatioPx2Gu; cam.setViewCenter(x, y, 0); cam.setViewPercent(zoom); } });
[ "stackoverflow", "0047784802.txt" ]
Q: Output stdio and stderr from pytest.main() Is there a way to get the output from a test that you run via pytest, using the call to main? string = "-x mytests.py" pytest.main(string) print(????????) If this was a process I could get the output using communicate() but I can't find the equivalent for pytest when running it as function from Python3, instead than run it as standalone from terminal. EDIT: I did try to use sys.stdout but it didn't work either...I am fundamentally stuck since I can't get the pytest output in any way; beside in my output IDE window. Any suggestion or workaround would be really appreciated. A: Found the answer thanks to a different question, which was mentioning how to redirect the whole stdout stream. I did not find a way to print only pytest messages; but I can redirect stdio from the output on screen, in a string variable in this way: import sys from io import StringIO def myfunctionThatDoesSomething(): # Save the original stream output, the console basically original_output = sys.stdout # Assign StringIO so the output is not sent anymore to the console sys.stdout = StringIO() # Run your Pytest test pytest.main(script_name) output = sys.stdout.getvalue() # close the stream and reset stdout to the original value (console) sys.stdout.close() sys.stdout = original_output # Do whatever you want with the output print(output.upper()) Hope this helps anyone looking for a way to retrieve data from their pytest output, in the meantime that a better solution to get just the pytest output in a variable is found.
[ "stackoverflow", "0006827331.txt" ]
Q: Get opening tag with jquery I have an issue where I need to format html that's stored in a client cache in the following format: html[0] = '<tr>' html[1] = '<td>text</td>' html[2] = '<td>text</td>' On normal occasions I work directly with the dom and don't need to go near this cache but sometimes I need to update it like so... html[1] = '<td><a href="">text</a></td>' Because of the 'unusual' storage of the opening 'tr' am I able somehow to construct a new 'tr', manipulate it, then render only the opening tag? $(html[0] + '</tr>'); I'm aware this could be done with regexp but curious to know if there's a jquery technique I can use. A: HTML is not XML. In HTML this is perfectly legal: <table> <tr> <td>Text</td> <td>Text</td> <tr> <td>Text</td> <td>Text</td> </table> That means that you don't have to close the opening <tr> bracket with </tr>. You can use the W3C Markup Validation Service to check your HTML for validness. You can wrap the text with an anchor like this: <!doctype html> <html> <head> <title>Wrap td text</title> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(function () { var html = []; html[0] = '<tr>'; html[1] = '<td>text</td>'; html[2] = '<td>text</td>'; $(html.join("")) .children("td") .each(function () { $(this).html($('<a href="">' + $(this).text() + '</a>')); }) .end() .appendTo("table"); }); </script> </head> <body> <table> </table> </body> </html>
[ "stackoverflow", "0006843870.txt" ]
Q: Disable auto scanning for JDO classes datanucleus exploded war When I deploy an exploded war file datanucleus fails with following error Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "JDOTutorial.war.WEB-INF.classes.com.blogspot.jkook.daytrader.jdo.QJDOOrderData" was not found in the CLASSPATH This does not occur when war is deployed. Seems DN is scanning for classes which use JDO annotations when loading the JCA. With exploded deployment it is scanning all the classes inside the exploded folder and fails to load since the location of the class and the class in the class path does't match. (class name is com.blogspot.jkook.daytrader.jdo.QJDOOrderData , but DN is looking for JDOTutorial.war.WEB-INF.classes.com.blogspot.jkook.daytrader.jdo.QJDOOrderData) I am using settings below but DN is still scanning the exploded folder datanucleus.autoStartMechanism = Classes , datanucleus.autoStartClassNames = com.blogspot.jkook.daytrader.jdo.JDOOrderData Question : How to hint DN to stop scanning the exploded folders ? A: finally solved jboss has feature to add external deployment folder default = deployment -- placed the datanucleus-jca-3.0.0-m6 myPath = extdeployments -- placed the JDOTutorial.war (exploded folder) Now DN doest scan for classes inside exploder folder :)
[ "stackoverflow", "0060547933.txt" ]
Q: C# Filter List of Active Directory Users & return Active/Enabled Users I have a list of Users being returned from AD and I need to filter them to just return the Active users. This is my code, but it's not returning any users. After extensive googling, I'm at a loss as to what's missing; public static List<Models.ToolUser> ActiveUsers() { int unlimitedAccess; //string userAccountControl; string listEntry; string fName; string lName; string unlimitedAccessGroup; //This is getting the List of Users that I need to filter List<Models.ToolUser> activeUserList = UIDal.GetFullWindowsUserList(); try { string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))"; string[] propertiesToLoad = new string[1] { "name" }; using (DirectoryEntry de = GetDirectoryEntryWithGc()) using (DirectorySearcher searcher = new DirectorySearcher(de, filter, propertiesToLoad)) using (SearchResultCollection results = searcher.FindAll()) { foreach (SearchResult result in results) { unlimitedAccess = 0; fName = result.Properties["givenName"][0].ToString(); lName = result.Properties["sn"][0].ToString(); listEntry = fName + " " + lName; var name = result.Properties["sAMAccountName"][0].ToString(); var u = new ToolUser { ToolUserId = 0, DomainAccount = result.Properties["sAMAccountName"][0].ToString(), FirstName = fName, LastName = lName, LoginId = "pc-" + result.Properties["sAMAccountName"][0].ToString(), UnlimitedAccess = unlimitedAccess > 0, }; activeUserList.Add(u); } } } catch { } return activeUserList; } A: Empty catch blocks are the devil. You should at least log the exception before continuing. In this case, your empty catch block is hiding what's really going on. You're getting an "Index was out of range" exception here: fName = result.Properties["givenName"][0].ToString(); Because result.Properties["givenName"] is an empty collection (there is no element at index 0). That's happening because of this: string[] propertiesToLoad = new string[1] { "name" }; You are telling the search to only return the name attribute for the objects found, but then you go on to use givenName, sn and sAMAccountName. You need to tell it to return those attributes if you intend to use them: string[] propertiesToLoad = new string[3] { "givenName", "sn", "sAMAccountName" }; That said, givenName and sn are not required attributes. If those attributes are empty on any of the accounts found, then they will not appear in the Properties collection at all and you will run into the same exception again. So you should test that those attributes are actually there before trying to use them. For example, this will check and set the variables to an empty string if the attribute doesn't exist: fName = result.Properties.Contains("givenName") ? result.Properties["givenName"][0].ToString() : ""; lName = result.Properties.Contains("sn") ? result.Properties["sn"][0].ToString() : "";
[ "politics.stackexchange", "0000002258.txt" ]
Q: Is House Resolution 368 Permenant? US House Resolution 368 amended Clause 4 of standing rule XXII of House Procedures and was passed on September 30th, just before the government shutdown took effect. It prevented members other than the Majority Leader from bringing motions passed by the Senate before the House. Is this a permanent rule change, or will this change expire now that the shutdown has ended? A: The rule change is permanent (I think) but narrow in scope. It only pertains to the budget bill. Source: ...takes from the Speaker's table the joint resolution (H.J. Res. 59) making continuing appropriations for fiscal year 2014 and ...relating to House Joint Resolution 59 may be offered only by the Majority Leader or his designee.
[ "stackoverflow", "0054318701.txt" ]
Q: How to train a Phrases model from a huge corpus of articles (wikipedia)? I'd like to create a big gensim dictionary for french language to try getting better results in topic detection, similarities between texts and other things like that. So I've planned to use a wikipedia dump and process it the following way: Extract each article from frwiki-YYYYMMDD-pages-articles.xml.bz2 (Done) Tokenize each article (basically converting the text to lowercases, removing stop words and non-word characters) (Done) Train a Phrases model on the articles to detect collocation. Stem the resulting tokens in each article. Feed the dictionary with the new corpus (one stemmed-collocated-tokenized article per line) Because of the very large size of the corpus, I don't store anything in memory and access the corpus via smart_open but it appears gensim Phrases model is consuming too much RAM to complete the third step. Here is my sample code: corpus = smart_open(corpusFile, "r") phrases = gensim.models.Phrases() with smart_open(phrasesFile, "wb") as phrases_file: chunks_size = 10000 texts, i = [], 0 for text in corpus: texts.append(text.split()) i += 1 if i % chunks_size == 0: phrases.add_vocab(texts) texts = [] phrases.save(phrases_file) corpus.close() Is there a way to complete the operation without freezing my computer or will I have to train the Phrases model only on a subset of my corpus? A: I'm answering myself because I realized I forgot to deal with some memory related parameters in the Phrases class. So, first I've divided max_vocab_size by 2 so it should consume less memory, and also I've decided to save the Phrases object every 100 000 articles and then reload it from the saved file as these kind of tricks have shown they can be helpful with some other classes in the gensim lib... Here is the new code, a little slower maybe but it has completed the task successfully: corpus = smart_open(corpusFile, "r") max_vocab_size=20000000 phrases = Phrases(max_vocab_size=max_vocab_size) chunks_size = 10000 save_every = 100000 texts, i = [], 0 for text in corpus: texts.append(text.split()) i += 1 if i % chunks_size == 0: phrases.add_vocab(texts) texts = [] if i % save_every == 0: phrases.save(phrasesFile) phrases = Phrases.load(phrasesFile) corpus.close() phrases.save(phrasesFile) Ending up with 412 816 phrasegrams in my case after putting all this in a Phraser object.
[ "stackoverflow", "0039074387.txt" ]
Q: JavaScript / Save context of varaible inside async function I have the following code in JavaScript: for (var i = 0; i< uuids.length; i++){ var attr = uuids[i] var uuid = attr["uuid"]; console.log("uuid is: " + uuid) multiClient.hget(var1, var2, function(err, res1){ console.log("uuid INSIDE hget is: " + uuid) } } hget is an async method. Here are the prints of this function: "uuid is: 1" "uuid is: 2" "uuid INSIDE hget is: 2" "uuid INSIDE hget is: 2" I wish to save the context of the uuid inside the hget function, so I will get: "uuid is: 1" "uuid is: 2" "uuid INSIDE hget is: 1" (where all the context before the loop has saved for this uuid) "uuid INSIDE hget is: 2" (where all the context before the loop has saved for this uuid) How can I do that? A: The following code multiClient.hget(var1, var2, function(err, res1){ console.log("uuid INSIDE hget is: " + uuid) } uuid value will be the value when async operation is completed. You can solve this using anonymous function executing and copy the value of uuid to some other variable say uuid_temp and use that value as shown below. (function() { var uuid_temp = uuid; multiClient.hget(var1, var2, function(err, res1){ console.log("uuid INSIDE hget is: " + uuid_temp); //note uuid_temp here } }());
[ "stackoverflow", "0020930998.txt" ]
Q: php conditional statement not giving supposed result My code below is supposed to display the last statement if the date expiry date is less than current date but it is instead showing second statement acting as though the expiry date is greater than the current date. I tested with a code that expired since01-12-2013 but it is still showing that the client have active discount. Please help point out where I might have made mistake. <?php if ($totalRows_coupon == 0) { ?> <table width="96%" border="0"> <tr> <td bgcolor="#FF0000" class="hint style2"> <div align="center" class="style3">You have entered an invalid discount code. Leave blank if you don't have any.</div></td> </tr> </table> <?php } else { if ($row_coupon['type']=='percentage' && date("d-m-Y") < strtotime("$edate") && $row_coupon['status']=='active') {?> <table width="96%" border="0"> <tr> <td bgcolor="#FFCCCC" class="hint"> <div align="center">You have a <span class="style1"><?php echo $row_coupon['value']; ?>%</span> discount valid for <?php if ($row_coupon['freq'] == 888) { echo "<font color=black>unlimited</font>";}else { echo $row_coupon['freq'];}?> uses. You have <?php if ($row_coupon['freq'] == 888) { echo "<font color=black>unlimited</font>";}else { echo $row_coupon['rem'];}?> uses left to expire on <?php echo $row_coupon['eDate']; ?> </div></td> <input name="coupon" type="hidden" id="coupon" value="<?php echo $row_coupon['value']; ?>"/> </tr> </table> <?php }elseif (date("d-m-Y") > strtotime("$edate") OR $row_coupon['status']!='active') { ?> <table width="96%" border="0"> <tr> <td bgcolor="#FF0000" class="hint style2"> <div align="center" class="style3">This discount code have expired since <?php echo $row_coupon['eDate']; ?>. Please enter an active code or leave blank.</div></td> </tr> </table> <?php } } ?> A: You're comparing apples and oranges: date("d-m-Y") < strtotime("$edate") date() returns a STRING representing the date in the specified format, e.g. 04-01-2014. strtotime() returns an INTEGER - a unix timestamp which is the number of seconds since Jan 1, 1970. In other words, your code boils down to if('04-01-2014' < 523423423) // picking out some random timstamp value Since you're comparing strings to ints, the string will be converted to an int, resulting in 4, and you end up with if (4 < 523423423) which is true.
[ "stackoverflow", "0000904970.txt" ]
Q: mod-rewrite URL Change I had an issue playing with Gallery when I changed a setting. However, I noticed there is a pattern to the error: The URLs look as such: main.php/d/number/name.jpg "number" is dynamic (ie "9496-2") "name" is dynamic (ie "all+clad+7pc+b") Everything else is static. Unfortunately, when I made the setting change, the "number" portion then changed from "9496-2" to "9495-2". How can I subtract the value "1" from variable "number"? Jeff A: This should do it. RewriteEngine On RewriteBase / RewriteRule ^photos/ebay/main.php/d/([0-9]*)6-([0-9]*)/(.*).jpg /photos/ebay/main.php/d/$1\5-$2/$3.jpg [QSA,L] I know you said you already got it but here is a solution without an additional script. (And I actually tested this one to ensure that \5 works).
[ "rpg.stackexchange", "0000122628.txt" ]
Q: Can you give health potions to Polymorphed companions? If a fellow adventurer gets turned into a beast using the Polymorph spell can you administer first aid using a Health Potion? A: If they retain the ability to ingest things and didn't drop to 0hp, you can. @JeremyECrawford confirmed that you can administer potions to willing (or incapacitated, i.e. unable to consent or refuse) characters. Assuming you simply wish to raise their health in their polymorphed shape you should be golden. As long as you have an action to spend on feeding the potion to your buddy and they have the ability to drink it (RAW potions explicity require being consumed to function). If you want to administer a potion right when they hit 0hp in their polymorphed state, it wouldn't. The transformation lasts for the Duration, or until the target drops to 0 hit points or dies. Dropping to zero instantly reverts the polymorphed creature back to what it was. As such, if you get to ready your action you could use it to feed your fellow adventurer the instant a dangerous enemy tries to strike them, much like the way Catapult is used in this question.
[ "stackoverflow", "0020521820.txt" ]
Q: Delete files getting names from array without knowing extension I have an array which contains a number of file names without extensions (below, the numbers are the name of the files): [1] => 214 [2] => 12 [3] => 2763 [4] => 356 [5] => 87 I would like to delete these files from the server without knowing their extensions (which could be .jpg .JPG .GIF .jpeg, etc). I tried using GLOB but I don't understand how to teach PHP to use wildcards and in the same time get the name of the files from the array. A: Assuming $names is your array: $path = "../pictures/"; foreach ($names as $name) { foreach (glob($path . $name . '*') as $filename) { unlink(realpath($filename)); } }
[ "stackoverflow", "0033786145.txt" ]
Q: PHP Imagick setFont not working in web but works in console Here's the Code: /* Create Imagick objects */ $image = new \Imagick(); $draw = new \ImagickDraw(); $color = new \ImagickPixel('#000000'); $background = new \ImagickPixel('none'); // Transparent /* Font properties */ $draw->setFont("annabelle"); $draw->setFontSize(80); $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); /* Get font metrics */ $metrics = $image->queryFontMetrics($draw, $text); /* Create text */ $draw->annotation(0, $metrics['ascender'], $text); /* Create image */ $image->newImage($metrics['textWidth'], $metrics['textHeight'], background); $image->setImageFormat('png'); $image->drawImage($draw); /* Save image */ file_put_contents('imagick_test.png', $image); ?> And ImageMagick configuration file: <?xml version="1.0" encoding="UTF-8"?> <typemap> <include file="type-dejavu.xml" /> <include file="type-ghostscript.xml" /> <include file="type-windows.xml" /> <type name="annabelle" family="annabelle" glyphs="/home/nginx/testing/annabelle.ttf" /> </typemap> If I call this in console mode by: php -f test.php, it's OK. But when I accessing by web interface: http://test-srv/testing/test.php, It raise an exception: Fatal error: Uncaught exception 'ImagickException' with message 'The path does not exist: /home/nginx/testing/annabelle' in /home/nginx/testing/test.php:15 Stack trace: #0 /home/nginx/testing/test.php(15): ImagickDraw->setfont('annabelle') #1 {main} thrown in /home/nginx/testing/test.php on line 15 I tried use setFontFamily() instead of setFont() like this: ... /* Font properties */ $draw->setFontFamily("annabelle"); $draw->setFontSize(80); ... Or using the font file instead using font name in setFont() like this: ... /* Font properties */ $draw->setFont("annabelle.ttf"); $draw->setFontSize(80); ... The image created like this: The right one should like this if I run the code in cosole: A: Well, I get the answer. I've upgraded php from 5.5 to 5.6, than I found Imagick module disabled so I re-emerge Imagick with PHP_TARGET="php5-6" (I'm running gentoo). But I forget restart php-fpm service. After I restart the service, it runs right.
[ "stackoverflow", "0023322730.txt" ]
Q: How to fix input paddig in HTML5 I have a problem with padding in HTML5. I'm using this code: input[type="password"] { border: 1px solid #CECECE; border-radius: 0 0 3px 3px; padding: 7px; font-size: 1em; outline: none; width: 100%; margin: 0px;} I use inputs in div, which has padding 10px. And when I'm testing code the width of input is not right, look at this pic: How to solve this problem? I want to have padding 10px in any window size. A: Add this CSS : input { -moz-box-sizing:border-box; -webkit-box-sizing: border-box; box-sizing:border-box; } This property will include padding and border to the width/height of inputs so they won't overflow anymore.
[ "apple.stackexchange", "0000187646.txt" ]
Q: Problem with build-in VPN client for Cisco IPSec protocol I recently bought a new MacBook Pro Retina and unfortunately the built-in VPN client (Cisco IPsec configuration) doesn't work. Whats interesting third party VPN Tracker 8 works. I'm running Mac OS X is Yosemite 10.10.3. Logs after getting connected status using Apple build-in client: May 17 21:31:44 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: transmit success. (Information message). May 17 21:31:44 MacBook-Pro-Marcin.local racoon[706]: IKEv1 Information-Notice: transmit success. (R-U-THERE? ACK). May 17 21:31:44 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: receive success. (Information message). May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: transmit success. (Information message). May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IKEv1 Information-Notice: transmit success. (R-U-THERE? ACK). May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: receive success. (Information message). May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IPSec Phase 2 started (Initiated by me). May 17 21:32:14 --- last message repeated 1 time --- May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: >>>>> phase change status = Phase 2 started May 17 21:32:14 --- last message repeated 1 time --- May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: transmit success. (Initiator, Quick-Mode message 1). May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: Fatal NO-PROPOSAL-CHOSEN notify messsage, Phase 1 should be deleted. May 17 21:32:14 --- last message repeated 1 time --- May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: Message: ''. May 17 21:32:14 --- last message repeated 1 time --- May 17 21:32:14 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: receive success. (Information message). May 17 21:32:17 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: transmit success. (Phase 2 Retransmit). May 17 21:32:42 --- last message repeated 7 times --- May 17 21:32:42 MacBook-Pro-Marcin.local racoon[706]: IKE Packet: transmit success. (Information message). May 17 21:32:42 MacBook-Pro-Marcin.local racoon[706]: IKEv1 Information-Notice: transmit success. (R-U-THERE? ACK). Both VPN Tracker 8 and Apple build-in VPN client have connected status . However using the second one safari can't open the page because the server where the page is located isn't responding. My ifconfig logs to satisfy your request: /* -ipconfig with VPN Tracker 8. VPN work great. * * * */ lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 options=3<RXCSUM,TXCSUM> inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 nd6 options=1<PERFORMNUD> gif0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 8192 inet 192.168.43.64 --> 172.30.4.0 netmask 0xffffffff stf0: flags=0<> mtu 1280 en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether d0:a6:37:ee:7d:79 inet6 fe80::d2a6:37ff:feee:7d79%en0 prefixlen 64 scopeid 0x4 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 nd6 options=1<PERFORMNUD> media: autoselect status: active en1: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 options=60<TSO4,TSO6> ether 4a:00:00:44:18:c0 media: autoselect <full-duplex> status: inactive en2: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 options=60<TSO4,TSO6> ether 4a:00:00:44:18:c1 media: autoselect <full-duplex> status: inactive p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304 ether 02:a6:37:ee:7d:79 media: autoselect status: inactive awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1452 ether e2:d2:f5:14:4f:8e inet6 fe80::e0d2:f5ff:fe14:4f8e%awdl0 prefixlen 64 scopeid 0x8 nd6 options=1<PERFORMNUD> media: autoselect status: active bridge0: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 1500 options=63<RXCSUM,TXCSUM,TSO4,TSO6> ether d2:a6:37:ee:ae:00 Configuration: id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0 maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200 root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0 ipfilter disabled flags 0x2 member: en1 flags=3<LEARNING,DISCOVER> ifmaxaddr 0 port 5 priority 0 path cost 0 member: en2 flags=3<LEARNING,DISCOVER> ifmaxaddr 0 port 6 priority 0 path cost 0 nd6 options=1<PERFORMNUD> media: <unknown type> status: inactive /* -ipconfig with Apple built-in VPN client. VPN does not work. * * * */ lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384 options=3<RXCSUM,TXCSUM> inet6 ::1 prefixlen 128 inet 127.0.0.1 netmask 0xff000000 inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1 nd6 options=1<PERFORMNUD> gif0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280 stf0: flags=0<> mtu 1280 en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether d0:a6:37:ee:7d:79 inet6 fe80::d2a6:37ff:feee:7d79%en0 prefixlen 64 scopeid 0x4 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 nd6 options=1<PERFORMNUD> media: autoselect status: active en1: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 options=60<TSO4,TSO6> ether 4a:00:00:44:18:c0 media: autoselect <full-duplex> status: inactive en2: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 options=60<TSO4,TSO6> ether 4a:00:00:44:18:c1 media: autoselect <full-duplex> status: inactive p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304 ether 02:a6:37:ee:7d:79 media: autoselect status: inactive awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1452 ether e2:d2:f5:14:4f:8e inet6 fe80::e0d2:f5ff:fe14:4f8e%awdl0 prefixlen 64 scopeid 0x8 nd6 options=1<PERFORMNUD> media: autoselect status: active bridge0: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 1500 options=63<RXCSUM,TXCSUM,TSO4,TSO6> ether d2:a6:37:ee:ae:00 Configuration: id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0 maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200 root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0 ipfilter disabled flags 0x2 member: en1 flags=3<LEARNING,DISCOVER> ifmaxaddr 0 port 5 priority 0 path cost 0 member: en2 flags=3<LEARNING,DISCOVER> ifmaxaddr 0 port 6 priority 0 path cost 0 nd6 options=1<PERFORMNUD> media: <unknown type> status: inactive utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1280 inet 192.168.43.120 --> 192.168.43.120 netmask 0xffffffff A: I found solution. It's working now. I changed my DNS settings to use Google Public DNS in VPN(IPSec) preferences.
[ "stackoverflow", "0037513192.txt" ]
Q: How can I "refresh" iron-swipeable-container after a change of data in firebase My code with swipable-container and dom-repeat of firebase-data <iron-swipeable-container id="teamchat"> <paper-card class="swipe item blue"> <template is="dom-repeat" items="[[tcmmessages]]" as="tcmmessage"> <div class="card-content"> <b>[[tcmmessage.teamname]]</b><br> [[tcmmessage.beitrag]]<br> <span class="chatmetadata">von [[tcmmessage.username]] &bull; [[tcmmessage.update]] &bull; [[tcmmessage.uptime]] </span> </div> </template> </paper-card> </iron-swipeable-container> I have defined a listener listeners: { 'teamchat.iron-swipe': '_onTeamChatSwipe' }, and remove the firebase-data with '_onTeamChatSwipe'. That work fine! But when there is new firebase-data, how can I bring the iron-swipeable-container back again without refreshing the entire page? I don't find a solution. A: It looks like you've created just one paper-card that contains multiple messages. When the card is swiped away, your code has no template to refill the container. Did you actually mean to create a card for each message? That would require moving paper-card inside the template repeater like this: <iron-swipeable-container id="teamchat"> <template is="dom-repeat" items="[[tcmmessages]]" as="tcmmessage"> <paper-card class="swipe item blue"> <div class="card-content"> <b>[[tcmmessage.teamname]]</b><br> [[tcmmessage.beitrag]]<br> <span class="chatmetadata">von [[tcmmessage.username]] &bull; [[tcmmessage.update]] &bull; [[tcmmessage.uptime]] </span> </div> </paper-card> </template> </iron-swipeable-container> When tcmmessages refills (via Firebase), the iron-swipeable-container automatically repopulates with a paper-card per message. Here's a demo of similar code that shows that behavior: <head> <base href="https://polygit.org/polymer+1.4.0/components/"> <script src="webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="polymer/polymer.html"> <link rel="import" href="paper-card/paper-card.html"> <link rel="import" href="iron-swipeable-container/iron-swipeable-container.html"> <link rel="import" href="iron-flex-layout/iron-flex-layout-classes.html"> </head> <body> <x-foo></x-foo> <dom-module id="x-foo"> <style include="iron-flex"> paper-card { margin-bottom: 16px; } </style> <template> <iron-swipeable-container class="container"> <template is="dom-repeat" items="[[items]]"> <paper-card heading="{{item}}" class="layout vertical"> <div class="card-content"> Swipe me left or right </div> </paper-card> </template> </iron-swipeable-container> </template> <script> HTMLImports.whenReady(function() { Polymer({ is: 'x-foo', properties : { items: { type: Array, value: function() { return [1,2,3]; } } }, _clearListAfterDelay: function(delay) { this.async(function() { this.set('items', []); }, delay); }, _refillListAfterDelay: function(delay) { this.async(function() { this.push('items', 4); this.push('items', 5); }, delay); }, ready: function() { this._clearListAfterDelay(1000); this._refillListAfterDelay(2000); } }); }); </script> </dom-module> </body> codepen
[ "unix.stackexchange", "0000487880.txt" ]
Q: TMUX + Rails = stty: 'standard input': unable to perform all requested operations I have a fairly large Rails project that always returns the following after every command in the Rails console: stty: 'standard input': unable to perform all requested operations This only happens within TMUX. Without using TMUX I don't see this output. I'm also not seeing this behavior with smaller Rails projects within TMUX. I'm on Mac OS Mojave with iTerm 2 (nightly build) and am using vanilla TMUX (i.e. no special configs). Any ideas? In response to Joseph Tingiris question: In TMUX I get: › stty -a speed 9600 baud; rows 47; columns 178; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; start = ^Q; stop = ^S; susp = ^Z; dsusp = ^Y; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; status = ^T; min = 1; time = 0; -parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff ixany imaxbel iutf8 opost -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe -echok -echonl -noflsh -tostop -echoprt echoctl echoke -flusho -extproc › echo $TERM screen-256color Outside of TMUX I get: › stty -a speed 38400 baud; rows 48; columns 178; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; start = ^Q; stop = ^S; susp = ^Z; dsusp = ^Y; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; status = ^T; min = 1; time = 0; -parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff ixany imaxbel iutf8 opost -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe echok -echonl -noflsh -tostop -echoprt echoctl echoke -flusho -extproc › echo $TERM xterm-256color A: Had the same issue using pry in tmux within iTerm2. This GitHub issue helped me discover that the version of stty provided by gnubin coreutils was overriding the OSX standard /bin/stty. I modified my PATH to resolve /bin/stty first, and the errors went away.
[ "stackoverflow", "0048925728.txt" ]
Q: How to call a function after 5 seconds? I want to call a function executeAfter5secs() in my home.ts when home.html is opened. How do I do this ? Currently I have added a button on home.html and on click of it, the function is being called, but I want to be free from the click and want to call it automatically once the page is loaded, but after 5 seconds. How do I code in home.ts side, I am bit confused like what do I code inside: ngOnInit() { } so that once page is loader time starts and after 5 seconds my function is called. A: Add this code in your .ts file ionViewDidLoad(){ setTimeout(() => { alert('Hello...') }, 5000); } A: you need to use 'AfterViewInit' after component's view fully initialized. in .ts file export class LoginPage implements AfterViewInit { ngAfterViewInit(){ setTimeout( ()=>{ console.log('works') }, 5000) } }
[ "stackoverflow", "0015149795.txt" ]
Q: Jquery Mobile popup triggering by itself I have a popup set up on the index.html as follows: <!-- Choice Popup --> <div class="ui-popup-screen ui-overlay-a ui-screen-hidden" id="popupDialog-screen"></div> <div data-role="popup" class="ui-popup-container ui-overlay-a" data-transition="pop" id="choicePopup"> <div data-role="popup" id="choicePopup" data-overlay-theme="b" data-theme="c" data-dismissible="false" class="ui-corner-all ui-popup ui-body-c ui-overlay-shadow" aria-disabled="false" data-disabled="false" data-shadow="true" data-corners="true" data-transition="slidedown" data-position-to="window" data-arrow="true" data-arrow-sides="t,b,l,r"> <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content ui-body-d" role="main"> <h1 class="ui-title" role="heading" aria-level="1">Your decision has been made:</h1> <h2 align="center" id="choice-p"></h2> <a href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" class="ui-btn ui-btn-up-c ui-shadow ui-btn-corner-all ui-btn-inline"> <span class="ui-btn-inner"> <span class="ui-btn-text">Thanks</span> </span> </a> <a href="#" onclick="eatsome('Food'); return false;" data-role="button" data-inline="true" data-transition="flow" data-theme="b" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" class="ui-btn ui-btn-up-b ui-shadow ui-btn-corner-all ui-btn-inline"> <span class="ui-btn-inner"> <span class="ui-btn-text">Again!</span> </span> </a> </div> </div> The problem is, I don't know why its booting on loading, some attribute is triggering it, can anyone find the issue? Thank you A: There are several issues with your markup and code: First of all your markup for the popup looks already jQM-enhanced like being copied from the browser's developer view. Therefore make it normal first. It might look like <div data-role="popup" id="choicePopup" data-overlay-theme="b" data-theme="c" data-dismissible="false" class="ui-corner-all"> <div data-role="header" data-theme="a" class="ui-corner-top"> <h1></h1> </div> <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content"> <h3 class="ui-title">Your decision has been made:</h3> <a id="btnThanks" href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c">Thanks</a> <a id="btnAgain" href="#" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-theme="b">Again!</a> </div> </div> Second a popup markup should reside inside the same page as the link that opens it. <div data-role="page" id="main"> ... <div data-role="popup" id="choicePopup"> ... </div> </div> Third use proper jQM events to place your code that manipulates the content. Forth Stop using onclick and other on* event attributes with jQM. Once again use proper jQM or jQuery events. So instead of <a href="#" onclick="eatsome('Food'); return false;" ... >Again!</a> use <a id="#btnAgain" href="#" ... >Again!</a> $("#btnAgain").click(function(){ eatsome('Food'); return false; }); Fifth After injecting html you need to call trigger('create') on a parent element to let jQM enhance and style the markup that you injected. var content = '<form>; ... content += '</form>; $("div.settings-content").html(content).trigger("create"); And here is working jsFiddle based on your markup. As you can see the popup doesn't pop up on its own. There are two buttons that show how to open the popup declaratively and programmatically. And content for settings page is injected and styled properly.
[ "stackoverflow", "0033176683.txt" ]
Q: How to preserve nested array value when modify a value of an cloned array? I have a default nested array called default_array, very simple : default_array = [ ["a", "b", "c"] ]; And I create a obj called obj where the value of his array attribute is the copy of default_array : obj = { "array" : default_array.slice(0) }; But when I modify a element of the obj.array like this : obj.array[0][0] = "z"; This modify also the default_array. I want this modification doesn't affect default_array. I want to preserve default_array. Any idea ? A: function copy(array) { var result = []; for (var i = 0, len = array.length; i < len; i++) { result.push(array[i].slice()); } return result; } var default_array = [ ["a", "b", "c"] ]; var obj = { "array": copy(default_array) }; obj.array[0][0] = 'z'; console.log(obj.array); console.log(default_array);
[ "stackoverflow", "0002232647.txt" ]
Q: Populating DropDownList based on another DropDownList (Cascading Drop Down) I am having trouble getting the functionality we want in our Create View in our ASP.NET MVC application. We have got two DropDownLists in our Create View. One is a selection of categories and the second should be populated with items based on the id value of the first category selected. (They have a FK relationship). Have you guys encountered any similar situation and can you give me some advice or a hint on how I can tackle this problem best? Should I create some specified ActionResult method for this? Or should I go with a static method in the Repository / Controller? All help is more than appreciated! A: You're looking for a Cascading Drop Down. A: Just to clarify what NicklLarsen said If you want them to update on the page without having to reload after every selection of the first drop down list, you will want to use cascading drop downs Cascading drop downs is short for making an AJAX call to another action method with the selected value of the first drop down list. The action method would take that value, use it to look up the corresponding information based on that value, and return a JSON/XML format of the list of items. Using javascript, you would then update the second drop down list with items.
[ "stackoverflow", "0031561946.txt" ]
Q: AlphaData alternative in Matlab In Matlab I'm plotting a matrix (let's call it M) using imagesc over an image using imshow. I would like M to have a degree of transparency so I can actually see the image below. This is what I'm doing: imshow(img); hold on; h = imagesc(M); set(h,'AlphaData',0.4); % set transparency to 40% However, the last line generates an error when running it on Linux. I've been trying to solve it but nothing seems to work. I wonder if there is an alternative to the "AlphaData" property to make it transparent. Thanks! EDIT: I'm using Matlab R2014a and Java 1.7 on a Linux CentOS 6.6 A: As Luis Mendo suggested, I just needed to change the renderer. You can: >get(gcf,'renderer'); % to see which render engine is Matlab using >set(gcf,'renderer'); % to get a list with all the possible renderers in your machine So, at least in Linux, to change the renderer it's necessary to start Matlab from terminal by calling it as: matlab -softwareopengl Once this is done, setting transparency in an specific plot, as shown in the description of the question, is possible.
[ "chemistry.meta.stackexchange", "0000000507.txt" ]
Q: Is Halocarbons a subtag of halides? I personally have the taste, that halocarbons (6) is very specific and may be viewed as a subtopic of the more general halides (6). Incredibly, there is no cross tagging. I would merge the former tag into the latter. A: Seeing no objections, I have merged halocarbons into halides and made halocarbons a synonym of halides.
[ "stackoverflow", "0029997704.txt" ]
Q: SQL find records from table 1 that are not in table 2 OR in table 2 with condition I see many examples on how to find records that are not in another table, but I'm having a lot of trouble finding records that are either not in table 2, or are in table two, but the freq column value is less than 10%. I'm first joining a list of variants with ensembl gene names for BRCA1, BRCA2 and any genes that start with BRC, where a variant falls between the start and stop position. From those results, I would like to check kaviar allele frequencies (k) and return results that either do not have an entry in the kaviar table, or results that are in the kaviar table with an alle_freq of < .10. The results from the first join need to be matched with kaviar by chr, pos, ref and alt. I've tried: SELECT DISTINCT * FROM puzz p, ensembl ens, kaviar k WHERE (ens.gene_name IN ('BRCA1', 'BRCA2') OR ens.gene_name LIKE 'RAS%') AND p.chr = ens.chromosome AND p.pos >= ens.start AND p.pos <= ens.stop AND NOT EXISTS (SELECT k.chromosome, k.pos, k.ref, k.alt, k.alle_freq, k.alle_cnt FROM public_hg19.kaviar k WHERE p.chr = k.chromosome AND p.pos = k.pos AND p.ref = k.ref AND p.alt = k.alt ) AND p.pos = k.pos AND p.ref = k.ref AND p.alt = k.alt AND k.alle_freq < .10 And I've also tried: WITH puzz AS ( SELECT * FROM puzz p WHERE p.gt IS NOT NULL ) SELECT DISTINCT t1.*, kav.* FROM (SELECT puzz.*, ens.* FROM puzz, public_hg19.ensembl_genes AS ens WHERE (ens.gene_name IN IN ('BRCA1', 'BRCA2') OR ens.gene_name LIKE 'RAS%') AND puzz.chr = ens.chromosome AND puzz.pos BETWEEN ens.start AND ens.stop AND ens.chromosome NOT LIKE "H%") t1 LEFT JOIN public_hg19.kaviar as kav ON kav.chromosome = t1.chr AND kav.pos = t1.pos AND kav.ref = t1.ref AND kav.alt = t1.alt AND (kav.alle_freq < .10 OR kav.alle_freq IS NULL) SOLUTION: Thanks to @John Bollinger for providing the framework for the solution. Because Impala does not index, the quickest solution involved creating a temporary table that narrows down the number of rows passed to string operations, as shown in the ens temp table. WITH ens AS ( SELECT DISTINCT chromosome as chr, start, stop, gene_name FROM public_hg19.ensembl_genes WHERE (gene_name IN ( 'BRCA1', 'BRCA2') OR gene_name LIKE 'RAS%') AND chromosome NOT LIKE "H%" ) SELECT p.*, k.chromosome, k.pos, k.id, k.ref, k.alt, k.qual, (k.alle_freq * 100) as kav_freqPct, k.alle_cnt as kav_count FROM (SELECT DISTINCT p.sample_id, p.chr, p.pos, p.id, p.ref, p.alt, p.qual, p.filter, ens.gene_name FROM ens, p7_ptb.itmi_102_puzzle p WHERE p.chr = ens.chr AND p.gt IS NOT NULL AND p.pos >= ens.start AND p.pos <= ens.stop ) AS p LEFT JOIN public_hg19.kaviar k ON p.chr = k.chromosome AND p.pos = k.pos AND p.ref = k.ref AND p.alt = k.alt WHERE COALESCE(k.alle_freq, 0.0) < .10 The following line, as pointed out by @Gordon Linoff could also be WHERE (k.alle_freq IS NULL OR k.alle_freq < 0.10) Both final clauses return the same results, but on impala, the coalesce function is somehow faster. A: The two queries you present don't seem to match up. Table names differ, and some of the filter conditions simply don't correlate. In particular, from whence came the condition AND ens.chromosome NOT LIKE "H%" (with its incorrect quotes)? I do think your outer join approach is promising, but I don't understand why you need a CTE or an inline view. Also, "any gene that starts with 'BRC'" includes 'BRCA1' and 'BRCA2', so you don't need to test those separately. Removing redundant conditions may improve performance a little. Furthermore, if happens to be the case that the structure of your data will preclude duplicate rows anyway, then explicitly selecting DISTINCT rows cannot help you, but might harm you. (Nevertheless, I follow your lead by including it in my suggested query.) If there are many results then SELECT DISTINCT is expensive; especially so if you are selecting a lot of columns. This seems like it accurately expresses the query you describe: SELECT DISTINCT p.sample_id, p.chr, p.pos, p.ref, p.alt, p.gt, p.qual, p.filter FROM p7_ptb.itmi_102_puzzle p join public_hg19.ensembl_genes ens ON p.chr = ens.chromosome left join public_hg19.kaviar k ON p.chr = k.chromosome AND p.pos = k.pos AND p.ref = k.ref AND p.alt = k.alt WHERE ens.gene_name LIKE 'BRC%' AND ens.chromosome NOT LIKE 'H%' AND p.pos BETWEEN ens.start AND ens.stop AND COALESCE(k.alle_freq, 0.0) < .10 If it's not fast enough for you then you'll want to examine your query plan to determine what the bottleneck is rather than trying to guess.
[ "stackoverflow", "0015205626.txt" ]
Q: Handling WPF TabItems Visibility property I have been reading about Visibility.Collapsed for TabItems. When the Visibility is set to Collapsed, the TabItem header is hidden but the contents are still visible. I have also tried the following approch mentioned in here, but no luck. Is there any way to get the contents inside the TabItems to hide and also select the tab that is visible. A: You don't need any of that. Conceptually, a TabControl is just a graphical representation of an ObservableCollection<ViewModel>, where each viewmodel is represented by a tab item, and there's only 1 SelectedItem at a given time: <Window x:Class="WpfApplication4.Window12" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window12" Height="300" Width="300"> <Window.Resources> <BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/> </Window.Resources> <TabControl ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"> <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/> <Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource BoolToVisibilityConverter}}"/> <Setter Property="Header" Value="{Binding Title}"/> </Style> </TabControl.ItemContainerStyle> </TabControl> </Window> Code Behind: using System.Windows; using BaseFramework.MVVM; using System.Collections.ObjectModel; namespace WpfApplication4 { public partial class Window12 : Window { public Window12() { InitializeComponent(); DataContext = new TabbedViewModel() { Items = { new TabViewModel() {Title = "Tab #1", IsEnabled = true, IsVisible = true}, new TabViewModel() {Title = "Tab #2", IsEnabled = false, IsVisible = true}, new TabViewModel() {Title = "Tab #3", IsEnabled = true, IsVisible = false}, } }; } } ViewModel: public class TabbedViewModel: ViewModelBase { private ObservableCollection<TabViewModel> _items; public ObservableCollection<TabViewModel> Items { get { return _items ?? (_items = new ObservableCollection<TabViewModel>()); } } private ViewModelBase _selectedItem; public ViewModelBase SelectedItem { get { return _selectedItem; } set { _selectedItem = value; NotifyPropertyChange(() => SelectedItem); } } } public class TabViewModel: ViewModelBase { private string _title; public string Title { get { return _title; } set { _title = value; NotifyPropertyChange(() => Title); } } private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; NotifyPropertyChange(() => IsEnabled); } } private bool _isVisible; public bool IsVisible { get { return _isVisible; } set { _isVisible = value; NotifyPropertyChange(() => IsVisible); } } } } Then, its just a matter of inheriting TabViewModel for each one of your tabs (creating the appropiate logic inside of each), and a proper DataTemplate for each one of these derived classes in the app.xaml or something. Whenever you want to remove a tab item from the view, instead of manipulating the view you manipulate the ViewModel. this is the WPF approach for everything. It simplifies everything by removing the need to manipulate complex objects (UI elements) in code. Whenever you set TabbedViewModel.SelectedItem.IsVisible = false;, make sure you also do: TabbedViewModel.SelectedItem = TabbedViewModel.Items.First(x => x.IsVisible && x.IsEnabled); This will prevent you from ever falling into the case of having an invisible tab item as the selected item.
[ "aviation.stackexchange", "0000066337.txt" ]
Q: Why does the Antonov AN-225 not have any winglets? Winglets provide a lift boost that would be useful to a plane of this size. But the An-255 does not have any winglets. Why is it so? A: Winglets are less effective at producing added lift than an equal-length wingspan extension. They are used on airliners when simply enlarging the wing would put the plane into a larger size class, or outside the 80 m "box". A longer wingspan, which the An-225 has (10% over the limit), is better at producing lift. The An-225 is a special purpose cargo aircraft for delivering very large loads such as the Buran space shuttle. It doesn't have to care for commercial airport traffic patterns meant for high-throughput operations - servicing thousands of planes separated into fixed size groups. In its original role the An-225 would operate from airstrips purpose-built for it, and seeing little other traffic. Today, on the rare (or not so rare, but its most public deliveries are to remote destinations) occasion when it has a commercial airport in its itinerary, they can deal with the extra requirements of a somewhat larger plane. Think of it like a wide load truck: they can go outside the 102"+3" limit at the expense of pre-planning the route. It's always a special delivery with these planes.
[ "pt.stackoverflow", "0000064531.txt" ]
Q: Verificar no URL se tem uma variavel passada GET LUA Quero verificar através do URL se tenho alguma variável passada para via GET. Por exemplo neste url: www.exemplo.htm?teste=teste if url then -- se na barra de endereço tem um get return true else return false end Tenho uma variável passada, como posso verificar isso em linguagem LUA? A: Uma maneira de fazer isto é usar a função string.gmatch: function checkURL(url, parametro) for chave, valor in string.gmatch(url, "(%w+)=(%w+)") do if valor == parametro then return true end end return false end Utilize a função checkURL assim: if checkURL("www.exemplo.htm?chave1=valor1&chave2=valor2", "valor1") then print ("valor1 está presente na URL") else print ("valor1 NÃO foi encontrado na URL") end Ver demonstração Uma outra alternativa é usar a função string.find: url = "www.exemplo.htm?chave1=valor1&chave2=valor2" if string.find(url, "valor1") then print ("valor1 está presente na URL") else print ("valor1 NÃO foi encontrado na URL") end Ver demonstração
[ "cooking.stackexchange", "0000088036.txt" ]
Q: Baby parsnips vs. parsley root I cooked parsnips for the first time this week (glad I did - delicious). When the produce clerk pointed them out, I asked if he had baby parsnips instead (as the recipe called for them). He pointed out parsley root, which looked very similar. I did a search while in the store (and got in many shoppers' way), but could not find whether they were the same thing definitively. A follow up question would be, if they aren't in fact the same thing, had I chosen to make this dish (roast veggies and chicken), how would the taste have differed for the parsley roots? A: Parsley root is not the same as parsnip. It tastes more like parsley, which is not really a surprise. Parsley roots don't get as sweet and delicious when you roast them as parsnips do, in my opinion - I get plenty of both from my Community Supported Agriculture box and buy a lot of parsnips as well. If you can't find parsnips you could use parsley root as a substitute rather than going without. On the matter of "baby" parsnips -- I just cut the large ones into more pieces. The centre of the largest ones are woody sometimes, but unless it's 4" or more across (which I have seen) you have nothing to worry about. A: No, they are not the same. Parsnips are Pastinaca sativa, parsley roots are roots of Petroselinum crispum. They are interchangeable only to a degree: Parsnips are a lot milder, with a sweet note and a lot more tender. Parsley is sometimes slightly sharp, can be more fibrous, especially the core, and takes longer to cook.
[ "math.stackexchange", "0003628861.txt" ]
Q: Question envolving linear algebra, Hyperplane and $GL(n,F)$ I need to prove that $H \cap GL(n,F) \neq {\emptyset}$, where $H$ is a hyperplane of $F^{n \times n}$. My professor gave me some tips. a)Suppose that $H \cap GL(n,F) = \emptyset$, then prove that $\forall N \notin H$, there are $M\in H$ and $\lambda \in F$ s.t $I = M + \lambda N$. b)Prove that every nilpotent matriz in $H$. Ok, item a): Let $N \notin H$, since $H$ is a hyperplane, we have $F^{n \times n} = H \oplus <N>$, every matrix $A \in F^{n \times n }$ can be written by $A = M + \lambda N$ where $M \in H$ and $\lambda N \in <N>$. In particular $A = I$. b) For this item, suppose that there is a nilpotent matrix $A \notin H$. Hence, by a) $I = M+ \lambda A$, for some $M \in H$ and $\lambda \in F $. Since $M \in H$ and $H \cap Gl(n,F) = \emptyset$, we have $0=\det(M) = \det(I- \lambda A)$, that is $\lambda $ is eigenvalue of $A$. But $A$ is nilpotent, then $\lambda = 0$. So we have a contradiction. Therefore, if $A$ is nilpotent, then $A \in H$. Ok, I've proved this itens, but how can I conclude that $H \cap Gl(n,F) \neq \emptyset$?? A: I don't know exactly what your professor had in mind, so let me propose a possible solution. First of all, notice that the statement is false for $n = 1$ (since then $H =\{0\}$). Let thus $n \geq 2$. Consider the matrices $$A_1 := \begin{pmatrix}0 & 1 \\ 1 & 0\end{pmatrix} \text{ and } A_2 := \begin{pmatrix}0 & 1 & 1 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix}.$$ You can easily check that these two matrices are invertible, since their respective determinants are $-1$ and $1$. Now, define a matrix $A$ as follows. If $n$ is even, let $A$ be the block diagonal matrix $$A = \mathrm{diag}(\underbrace{A_1,...,A_1}_{n/2 \text{ times}}),$$ and if $n$ is odd, then $n \geq 3$ and define $$A := \mathrm{diag}(A_2,\underbrace{A_1,...,A_1}_{(n-3)/2 \text{ times}}).$$ In any case, $A$ is invertible, since it is block diagonal and its blocks are invertible. To conclude, as you showed, $H$ contains every nilpotent matrix. Thus, observe that $H$ contains the $n^2-n$ matrices $E_{ij}$ for $i \neq j$ whose $(i,j)$-th entry is $1$ and the other entries are $0$ (all of the matrices $E_{ij}$ are nilpotent). Of course, the matrix $A$ can be written as a linear combination of the $E_{ij}$'s (since the diagonal entries of $A$ are $0$). Hence, since $H$ is a linear subspace, $A \in H$.
[ "unix.stackexchange", "0000413712.txt" ]
Q: Finding how many hex values a string containing hex and random string I have the file ~/dummy_hex.txt containing hex and random string: \x12\xA1\xF1\xE3somegibberigh I want to count how many hex values (groups of \x^hex_digit^^hex_digit^) the string above has. In the example above I want the commands to run to return the number 4. In other words I want to type over my terminal: command ^file_having hex^ And return the value 4 So far I tried to do that with: sed 's/[^\x[0-9A-Fa-f][0-9A-Fa-f]]//g' dummy_hex.txt | awk '{ print length }' But somehow seems to return wrong result because of regex misstype. Can you tell me how to use full PCRE compartible regex with sed in order to do that? Alternatively I want to count how many hex values my string contains. Edit 1 An another approach is to count the \x string occurences but that may count any stray \x that may not be followed with a value indicating a hexadimal string. sed 's/[^\x]//g' dummy_hex.txt | awk '{ print length }' Further more I tried to do that with -r option that enables PCRE: sed -r 's/^\\x[0-9A-Fa-f][0-9A-Fa-f]]/g' dummy_hex.txt | awk '{ print length }' But I get the error: sed: -e expression #1, char 31: unterminated `s' command A: With a grep that supports Extended Regular Expressions and the -o option: grep -Eo '\\x[[:xdigit:]]{2}' input | wc -l To fit the requirement of command filename: function counthex() { grep -Eo '\\x[[:xdigit:]]{2}' "$1" | wc -l } As: counthex input
[ "stackoverflow", "0015974112.txt" ]
Q: How to find C functions without a prototype? Company policy dictates that every function in C source code has a prototype. I inherited a project with its own make system (so I cannot test it on gcc or Visual Studio) and found that one of the files has some static functions declared without prototypes. Is there a way (not necessarily with a compiler) to list all functions without prototypes in all .c files? A: gcc has an option to warn you about this: gcc -Wmissing-prototypes You can turn this warning into an error to stop compilation and force people to fix it: gcc -Werror=missing-prototypes If you just want to list it you can compile with the gcc option -Wmissing-prototypes and grep for no previous prototype for in the log. Update based on edit: Since you now mention that you can't use gcc, you'll have to find a similar option for your current compiler. Most compilers have such an option. Start with the man page or the built in help output. A: ctags can do that! --c-kinds=p generates the list of all function prototypes --c-kinds=f generates the list of all function definitions Now you just need to compare those. diff -u <(ctags -R -x --sort=yes --c-kinds=f | cut -d' ' -f1) <(ctags -R -x --sort=yes --c-kinds=p | cut -d' ' -f1) | sed -n 's/^-//p'
[ "stackoverflow", "0018094930.txt" ]
Q: How to make a custom select box with filter using jQuery Mobile? I am having a problem with jQuery Mobile. I want to make a custom select box with search option on the top like in the ul of jQuery mobile. I have made a custom select box using jQuery mobile but cannot add the search bar on it. I want exactly the thing like this: http://jsfiddle.net/sEMyT/2/ <!DOCTYPE html> <html> <head> <link class="jsbin" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" rel="stylesheet" type="text/css" /> <script class="jsbin" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <script class="jsbin" src="https://github.com/downloads/aliok/jquery-mobile/jquery.mobile_selectmenu_filter_01.js"></script> <title>JS Bin</title> </head> <body> <div data-role="page"> <div data-role="content"> <h2>Select menu options filtering</h2> <p>The mobile browsers are limited and sometimes it is annoying to scroll a long list. For this kind of selects, you can use <code>data-filter</code> attribute alongside with <code>data-force-dialog</code> and <code>data-native</code> attributes to have a select menu with search bar filtering its options.</p> <a href="#" onclick="$('#select-choice-12').selectmenu('refresh', true); return false;">Refresh the selectmenu (forcerebuild) with clearing the filter value</a> <div data-role="fieldcontain"> <label for="select-choice-12" class="select">Your state:</label> <select name="select-choice-12" id="select-choice-12" data-native-menu="false" data-force-dialog="true" data-native-menu="false" data-filter="true"> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </select> </div> You can see the source code at <a href="https://github.com/aliok/jquery-mobile/commits/selectmenu-forceDialog/">https://github.com/aliok/jquery-mobile/commits/selectmenu-forceDialog/</a> <br/> <br/> Developed by <a href="http://twitter.com/aliok_tr">Ali Ok - @aliok_tr</a> </div> </div> </body> </html> But the problem with that it is customized with a very old version of jQuery Mobile and I am using the latest version. A: You could just follow the example on the JQM demo pages Filter inside Custom Select
[ "joomla.stackexchange", "0000005410.txt" ]
Q: Create custom language switcher module I would like to customize the language switcher module, that is I would have some different effect, like having name and flags together. How could I perform it? EDIT: Joomla version 3.3.6 template used: SJ plus v1 A: You can easily create an override of that module from Template Manager, as explained here: http://docs.joomla.org/J3.x:How_to_use_the_Template_Manager#Creating_Overrides Just go into the "override" tab and click con "mod_language" on the modules list. You'll get lang switcher overrideable file added to your template's HTML folder (inside a mod_language subfolder). Just browse to that file and edit it directly from your template manager: http://docs.joomla.org/J3.x:How_to_use_the_Template_Manager#Customisation_View Once there, it's up to your HTML/CSS skills how much you can modify the module ;).
[ "stackoverflow", "0008372223.txt" ]
Q: Get zip code based on lat & long? Is there a service or API I can ping, and pass in the lat/long as parameters, where it returns the zip code that lat/long pair is within? This is US-only, so I don't have to worry about international codes, etc. I feel like Google Maps' reverse-geocoding is too heavy for me. I'd prefer something lighter, if possible. This will be done in javascript. A: It is called Reverse Geocoding (Address Lookup). To get address for lat: 40.714224, lng: -73.961452 query http://maps.googleapis.com/maps/api/geocode/json with parameters latlng=40.714224,-73.961452&sensor=true (example) and it returns JSON object or use http://maps.googleapis.com/maps/api/geocode/xml to return XML response (example). It's from Google and it's free. A: For the Google API, you need to use it within a Google map, according to their site: Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited. A: Please have a look on http://geonames.org. There is a webservice findNearbyPostalCodes (international). Example: findNearbyPostalCodesJSON?lat=47&lng=9&username=demo Shortened output: { "postalCodes": [{ "adminCode3": "1631", "distance": "2.2072", "postalCode": "8775", "countryCode": "CH", "lng": 8.998679778165283, "placeName": "Luchsingen", "lat": 46.980169648620375 }] } Limit of the demo account is 2000 queries per hour.
[ "stackoverflow", "0062134807.txt" ]
Q: Plot based on group I have dataset with total of 500 rows: 250 pop, 250 heavy-metal. How can i produce this plot in R? My actual dataset is not seperated like the example i give though. Should i just seperate it? What i have done so far ggplot(data = playlist, aes(x = genre, y = danceability)) + geom_jitter(aes(col = genre)) A: The problem you're having is that you've mapped x = genre. Thus, genre gets converted to a factor and then plotted at either 1 or 2. Instead, what you want to do is have the data plotted at a random point on the x-axis. A simple way to do this is to randomly sample 1:nrow(playlist) like this: ggplot(data = playlist, aes(x = sample(1:nrow(playlist),nrow(playlist)), color = genre, y = danceability)) + geom_point(aes(col = genre)) + labs(x = "data") Note that you no longer need geom_jitter. Data: playlist <- structure(list(danceability = c(0.683, 0.768, 0.693, 0.765, 0.506, 0.809, 0.628, 0.556, 0.72, 0.706, 0.414, 0.448, 0.687, 0.747, 0.532, 0.483, 0.491, 0.224, 0.666, 0.416, 0.44, 0.362, 0.28, 0.42, 0.115, 0.35, 0.519, 0.538, 0.507, 0.261), genre = c("pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "pop", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal", "heavy-metal")), row.names = c(NA, -30L), class = "data.frame") Note: This data was derived by optical character recognition from your screen shot, please excuse any errors.
[ "stackoverflow", "0042257926.txt" ]
Q: How can a change data based off of user's location? I created a tableview with 2 cells, with each cell showing both your senators (based off of your location). I used CLGeocoder to successfully grab the user's zipcode, and I then put that value (which is of type string) into a variable that declared outside of the function. Ideally, I want to go to a different function in the class, and use that string variable (which should hold the user's zip code) to create specific data. However, it doesn't work! Here is the code that extracts the zip code and puts it in var zipCode:(note that the print function in the if condition successfully prints the zip code in the terminal when I run the program). let locationManager = CLLocationManager() var zipcode: String = "" func getTableInfo() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers locationManager.requestWhenInUseAuthorization() locationManager.startMonitoringSignificantLocationChanges() CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in if error != nil { print("Reverse geocoder failed with error" + error!.localizedDescription) } if placemarks!.count > 0 { let pm = placemarks![0] self.zipcode = pm.postalCode! print(self.zipcode) } else { print("Problem with the data received from geocoder") } }) } I call this function in viewDidLoad() and then in the viewDidLoad() function, using an if-statement, I try to use the zip code to change an array of strings. names[] is declared as a empty array of strings right above the viewDidLoad() function. if zipcode == "94108" { names[1] = "WORKS!" print(names) } For some reason, it doesn't print the names! (Note that the zip code is indeed 94108 because 94108 is what prints in the console when I ask to print 'zipcode') A: Create a completion handler for your getTableInfo method, like this: typealias ZipcodeCompletionBlock = (String?) -> Void func getTableInfo(completionBlock: @escaping ZipcodeCompletionBlock) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers locationManager.requestWhenInUseAuthorization() locationManager.startMonitoringSignificantLocationChanges() CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in if error != nil { print("Reverse geocoder failed with error" + error!.localizedDescription) completionBlock(nil) } else if placemarks!.count > 0 { let pm = placemarks![0] self.zipcode = pm.postalCode! completionBlock(self.zipcode) } else { print("Problem with the data received from geocoder") completionBlock(nil) } }) } Now you can call this function like this inside viewDidLoad: self.getTableInfo { zipcode in if zipcode == "94108" { self.names[1] = "WORKS!" print(self.names) } }
[ "stackoverflow", "0021506659.txt" ]
Q: Using two different style for checkbox, both on the same page I defined my "default" checkbox style on globals.css, I file that I include on every page input[type=checkbox] { display:none; } input[type=checkbox]+label { width:auto; display:inline-block; cursor:pointer; position:relative; line-height:20px; padding-left:22px; } input[type=checkbox]+label:before { content:""; display:inline-block; width:16px; height:16px; position:absolute; left:0; background-color:#F5F5F5; border-width:1px; border-style:solid; border-radius:3px; } input[type=checkbox]:checked+label { outline:0; } input[type=checkbox]:checked+label:before { content:'\2713'; font-size:16px; line-height:16px; text-align:center; } Then on a page I need this type of checkbox as "default" and another checkbox (on-off switch) only in one place. The problem is that the switch take also the CSS style of the normal checkbox of globals.css. Is the only way to solve this problem apply !important to each?? (or most of) the lines of the on-off switch? Or is there a way to reset CSS to normal checkbox for this container and the apply new styles? On-off CSS .checkbox_onoff { float:left; width:60%; position: relative; width: 60px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; } .checkbox_onoff-checkbox { display: none; } .checkbox_onoff-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #666666; border-radius: 0px; } .checkbox_onoff-inner { width: 200%; margin-left: -100%; -moz-transition: margin 0.3s ease-in 0s; -webkit-transition: margin 0.3s ease-in 0s; -o-transition: margin 0.3s ease-in 0s; transition: margin 0.3s ease-in 0s; } .checkbox_onoff-inner:before, .checkbox_onoff-inner:after { float: left; width: 50%; height: 20px; padding: 0; line-height: 20px; font-size: 10px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .checkbox_onoff-inner:before { content: "ON"; padding-left: 10px; background-color: #6194FD; color: #FFFFFF; } .checkbox_onoff-inner:after { content: "OFF"; padding-right: 10px; background-color: #F8F8F8; color: #666666; text-align: right; } .checkbox_onoff-switch { height:20px; width:20px; margin: 0px; background: #FFFFFF; border: 2px solid #666666; border-radius: 0px; position: absolute; top: 0; bottom: 0; right: 36px; -moz-transition: all 0.3s ease-in 0s; -webkit-transition: all 0.3s ease-in 0s; -o-transition: all 0.3s ease-in 0s; transition: all 0.3s ease-in 0s; background-image: -moz-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%); background-image: -webkit-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%); background-image: -o-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%); background-image: linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%); } .checkbox_onoff-checkbox:checked + .checkbox_onoff-label .checkbox_onoff-inner { margin-left: 0; } .checkbox_onoff-checkbox:checked + .checkbox_onoff-label .checkbox_onoff-switch { right: 0px; } A: You can use !important or you can do what is done in this post What are the implications of using "!important" in CSS? I also found this other post very helpful: http://css-tricks.com/when-using-important-is-the-right-choice/ Make sure your global css declaration is before your second css declaration.
[ "stackoverflow", "0044713997.txt" ]
Q: EF: Update the same DB table row in multiple threads I have an education task and don't understand what's wrong in my code. I'm trying to update DB table and isolate this logic in the transaction. Finally, I get a deadlock. Can someone explain to me what's I doing wrong, please? Here my thread creation logic: for (int i = 0; i < 10; i++) { var thread = new Thread(() => UpdateOrder(orderId)); threadList.Add(thread); thread.Start(); } foreach (var t in threadList) { t.Join(); } //Display sum by order items amount and amount property from order entity WriteAmount(orderId); And UpdateOrder method public static void UpdateOrder(int orderId) { using (var db = new OrderContext() { using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew ,new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead })) { var o1 = new OrderItem { Title = "title", Amount = 50, Count = 1, OrderId = orderId }; db.OrderItems.Add(o1); var order = db.Orders.Find(orderId); //Include(o => o.Items).Single(o => o.Id == orderId); order.Amount += 50; //order.Items.Sum(oi => oi.Amount); db.SaveChanges(); transactionScope.Complete(); } } } I've created own context for each thread. Why my DB detect a deadlock? This is the exception message: "Transaction (Process ID 51) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction." Thanks in advance! A: You have the problem on the database side. Why did you use the IsolationLevel.RepeatableRead transaction type? Suppose this is the cause. You can read about different isolation level here: https://docs.microsoft.com/en-us/sql/t-sql/statements/set-transaction-isolation-level-transact-sql. I'll advise you to: 1. Change isolation level to default READ COMMITTED 2. Remove order.Amount += 50;. Instead, create a trigger on the database side to handle INSERT/UPDATE/DELETE events on OrderItems table and modify the Orders table.
[ "math.stackexchange", "0000811234.txt" ]
Q: patterns in the decimal expansions of adjacent square and cube roots For fun I made a table in Excel which evaluated the square and cube roots of whole numbers in ascending order. Then of the result, I extracted the first, second and third decimal place digits, then color-coded them (using resistor color code). Interestingly, I found several 'mirrored' (or ascending-descending) patterns which I can only explain via the attached screenshots (try it for the cube roots - similar patterns) ... Can someone figure out what's going on here? Am I asking a wrong question from the get-go? Is it simply emergent from the way Excel evaluates the decimal values? Thank you! A: Long story short: The fact that $\sqrt{x}$ is almost linear when $x$ does not change much results in the repetitive pattern: $\sqrt{a},\sqrt{a+1},\sqrt{a+2},\dots,\sqrt{a+n}$ behaves like an arithmetic sequence for $n\ll a$. The second degree correction to the linear approximation around $a$ is symmetric around $a$, which gives the mirrored (symmetric) pattern. Let's take for example the longest pattern, that one around $\sqrt{400}$. Making the first degree assumption for $\sqrt{x}$ around $x=400$ yields $$ \sqrt{x} \approx 20 + \frac{x-400}{2\sqrt{400}} = 20 + \frac{x-400}{40}. $$ If we plug $x=382$ into that approximation, we get $$ \sqrt{382} \approx 19.55, $$ which is quite close to the real value. In other words, the linear approximation is rather accurate for the values in this pattern. Let's see what values the linear approximation gives: $$ \begin{align*} 400 &&& 20.0 \\ 401 &&& 20.025 \\ 402 &&& 20.05 \\ 403 &&& 20.075 \\ 404 &&& 20.1 \\ 405 &&& 20.125 \\ 406 &&& 20.15 \\ 407 &&& 20.175 \\ 408 &&& 20.2 \\ 409 &&& 20.225 \\ 410 &&& 20.25 \\ \end{align*} $$ Tada! There's the pattern: the second decimal is $0,2,5,7,0,2,5,7,\dots$ ad infinitum. Because the actual values are a bit smaller than what the linear approximation gives, you see the pattern $9,2,4,7,9,2,\dots$ until the error between the real value and the approximation grows large enough. But that only explains the repetition. Why the mirrored pattern? Let's make a 2nd degree approximation around $x=a$! $$ \sqrt{x} \approx \sqrt{a} + \frac{x-a}{2\sqrt{a}} - \frac{(x-a)^2}{8\sqrt{a}^3} $$ Now the correction term $- \frac{(x-a)^2}{8\sqrt{a}^3}$ is symmetric around $x=a$. So when the linear approximation stops giving the right decimals, the correction term changes the values the same amount in the same direction for $x=a+b$ and $x=a-b$. This causes the symmetry when the repetitive pattern near $x=a$ fails.
[ "worldbuilding.stackexchange", "0000145682.txt" ]
Q: Multiple fireplaces in an apartment building? I was working on a short story set in winter--a good time to contrast the cold, deprived life of the main character, reflecting his mental state, and the warmth and joy of other characters. There is an apartment situation (perhaps only a few dozen max people, more likely about 20-30,) I imagine in a small city (or on the outskirts of a larger one) and I imagine all characters having fireplaces of their own. My ideal setting is in the 20's-40's~50's, without going to the radiator or boiler route, is there any way each apartment could have its own fireplace, even if not bigger than a few feet? I mean, theoretically, there could be complex series of pipes in the building, but that is more dangerous than anything and quite stupid. If there is nothing historically, I suppose I can go with a gas heater... A: Here's a stock photo of Edinburgh. As you can see, there are a lot of fireplaces. (From www.dreamstime.com's royalty-free section). I used this photo as it is royalty free, but most tenements are in straight rows, not as messy as this A large part of the housing stock in Edinburgh is what we call tenements. A fairly typical tenement consists of a stair, with 3 flats off each stair, and 4 floors, so about 12 flats total. Each flat has 2 to 4 rooms of 8-15m2, and each of these rooms has a fireplace. There are also smaller box rooms or cupboards which do not have fireplaces, many have been converted to bathrooms. Every flat has at least one 1m2 cupboard which would have been used as a coal store. They vary from quite grand in some areas of town, to quite small and cramped in others. So this "typical" tenement has 36 fireplaces, slightly more than one per person living there in modern times, though in the time frame you mention, there would likely have been more people in each one. They aren't exactly what you're looking for, but they sound pretty close. They are also very characteristic of Scottish cities, and I have not seen anything quite like them in the US where I assume your story is based. The Brownstones in Boston look similar, but lack the forest of chimneys and also presumably the fireplaces. These tenements were mostly built between about 1700 and 1850. By 1920-1940, they were often a bit dilapidated, and potentially the cheaper end of the market (many are now very expensive). It would be quite believable to find tenements still using coal in that period, with gas fired heating taking off after the war. A: My solution would be to go with a conversion of what the Americans refer to as a "colonial" due to when they were built in the US. Use a building much older than the setting that was converted from a large single dwelling to apartment living but due to its age they kept the fireplaces rather convert to the latest and greatest of the date of conversion. Such buildings are quite common in most of the western world; big old grand homes, from an era where fireplaces were put into almost every room, that were later sold when the families that built them fell on hard times and sub divided into flats/apartments by developers. In my local area many such buildings are actually elder care facilities. A: You can definitely have a fireplace for each room. That is how they did it. A college dormitory is like an apartment house. Older dorms often had a fireplace for each room. Here is a dorm at Yale. Judging by the laptop this is recent. https://fyeahcooldormrooms.com/post/128888769089/yale-university In this photo of Burton Hall at Carleton, you can see the chimneys - there are many. Each of those chimneys has 6 stacks in it, and each stack is shared by several floors of rooms. Of course at Carleton they bricked up the fireplaces long ago because of the propensity of Carls to conduct flammability tests of items they found. But the principle is what I am after. You can have your characters reside in a dorm, or a converted dorm. Or apartments built in that period. Take a look at old photos or new photos of old apartments and you will see that they, like Burton Hall, have many, many chimneys.
[ "stackoverflow", "0054228060.txt" ]
Q: Im expecting a function to return a string but seems to return undefined. it's not passing Mocha test I have a js file where I implement a fetch call to an API, the returned value is indeed a string (or it should be). I'm trying to run a test that check it is true, but it does not pass the test. Can you tell me where I am making the mistake? this is my users.js file code: const fetch = require("node-fetch"); exports.retrieveFirstUserName = () => { let title = ""; fetch("https://jsonplaceholder.typicode.com/todos/1") .then(response => response.json()) .then(json => { title = json.title; console.log(typeof title); }); }; And this is the test: var assert = require("chai").assert; var users = require("./users"); describe("fetching function tests using ASSERT interface from CHAI module: ", function () { describe("Check retrieveFirstUserName Function: ", function () { it("Check the returned value using: assert.equal(value,'value'): ", function () { result = users.retrieveFirstUserName(); assert.typeOf(result, "string"); }) }) }) A: First of all, your function should return its promise: const fetch = require("node-fetch"); exports.retrieveFirstUserName = () => { let title = ""; return fetch("https://jsonplaceholder.typicode.com/todos/1") .then(response => response.json()) .then(json => { title = json.title; console.log(typeof title); return title; }); }; Then, to test it, you have to wait on the promise and then check. describe("fetching function tests using ASSERT interface from CHAI module: ", function () { describe("Check retrieveFirstUserName Function: ", function () { it("Check the returned value using: assert.equal(value,'value'): ", function () { users.retrieveFirstUserName().then(result => { assert.typeOf(result, "string"); }); }) }) })
[ "japanese.stackexchange", "0000018900.txt" ]
Q: Meaning of 「以上」 when someone finishes his/her speech and says 「以上」 What is the meaning of 「以{い}上{じょう}」 when someone finishes his/her speech and says 「以上」? For example - the lawyer at the court after his speech says 「以上」and stops speaking then. A: The meaning is "that's all", in the sense of "(all that there is, I've said) before". The second definition of 以上 here shows that "above" is equated with "before", and the fourth definition corresponds to the usage you're referring to.
[ "stackoverflow", "0026387645.txt" ]
Q: How to use system environment variable as part of @PropertySource value? I want to launch my program with java ... -Denv=prod ... and have @PropertySource("classpath:/settings/$idontknowwhat$/database.properties")` read properties file: /settings/prod/database.properties I have tried using #{systemProperties['env']} but it is not resolved with exception: Could not open ServletContext resource ['classpath:/settings/#{systemProperties['env']}/database.properties] A: Found it, I can simply use @PropertySource("classpath:/settings/${env}/database.properties")
[ "android.stackexchange", "0000203624.txt" ]
Q: Is it possible to successfully adjust predictive text for offensive words? I am using a oneplus 5t, and Gboard. I use signal to text. I have cleared the personal dictionary within gboard, and I have also enabled "do not make offensive suggestions" in the keyboard options. I don't believe signal has an associated settings option. Still.. for some reason when I type 'sucking', I get 2/3 followup suggestions that are predictably offensive. I would just rather not see words like this, and I can guarantee I've never used this particular combination of words before, so I don't understand why this is happening. Either the "offensive predictive text" function is broken, or these words are not considered to be part of that dictionary (I find this hard to believe). Or something else entirely... A: It seems that you can dis-associate the word from the phrase by deleting it as a suggestion. As per Get word suggestions & fix mistakes: Get word suggestions & fix mistakes On your Android phone or tablet, install Gboard. Open any app that you can type with, like Gmail or Keep. Tap where you can enter text. Type a word. At the top of the keyboard, you’ll see suggestions: If you see the word you want, tap it. If you don’t like a suggested word, touch and hold it, and then drag the word to Trash. I tried it out and I don't get the test word I moved to trash as a suggestion for the one that I dis-associated it from, but I still get it as a suggestion after other words.
[ "stackoverflow", "0006528209.txt" ]
Q: Run repeating timer when applicationDidEnterBackground My goal is to run a repeating timer every five seconds if and only if the application is running in the background. I've tried a couple of ideas, but they don't seem to work. Idea 1: Doesn't run even once. - (void)applicationDidEnterBackground:(UIApplication *)application { [NSTimer scheduledTimerWithTimeInterval:(5.0/5.0) target:self selector:@selector(check_expiry) userInfo:nil repeats:YES]; } Idea 2: Runs every five seconds, but I can't seem to stop the loop. - (void)applicationDidEnterBackground:(UIApplication *)application { counter = YES; while (counter) { sleep(5); [self check_expiry]; } // Counter is set to NO in willEnterForeground and didBecomeActive, but this loop continues to run due the sleep(); } How can I get this loop to run properly? Thanks! A: When an application "enters the background" in iOS, that's not like normal operating systems, where it continues to run. The application enters a suspended state. It doesn't keep running; only application state is preserved, and even that's not guaranteed - if the device is running low on memory, iOS will happily terminate your application to give the memory to the active application. If you attempt to block in applicationDidEnterBackground:, like you are doing with sleep(), iOS will simply terminate your application for not returning from that method promptly. Your application is woken up periodically if it's configured for background processing GPS events, VOIP, etc., but abusing those just to get your app to run will stop you from getting App Store approval. This is all covered in The iOS Application Programming Guide.
[ "superuser", "0000173821.txt" ]
Q: vpn through vpn The target VPN server I want to connect to allows connections only from one IP address. When I am at my office (the network public IP is trusted on the VPN server) everything is OK, but I figured that when I am at home I could do the following: Connect to office VPN (using built in windows VPN client) When I do it I have 2 active network interfaces: home network office network (VPN) Connect to target VPN (using custom VPN client) If the VPN server sees my office IP, it should let me in. Unfortunately, I get rejected. The strange thing is, I made it work this way: I connect to VPN at my office I start a bridged virtual machine I connect to target VPN in the virtual machine and it works. Probably, all virtual machine traffic is routed through the office VPN connection. My question is, how can I make it work without the virtual machine? system: Windows XP VPN client: Check Point VPN-1 Connection settings: IKE over TCP, Force UDP encapsulation A: Since you're using Windows XP, we'll work with Windows commands. From the Command Prompt on your workstation, type route print - you should get something like this: IPv4 Route Table =========================================================================== Interface List 0x1 ........................... MS TCP Loopback interface 0x10003 ...08 00 27 c3 52 ca ...... AMD PCNET Family PCI Ethernet Adapter =========================================================================== =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.89 20 127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1 192.168.1.0 255.255.255.0 192.168.1.89 192.168.1.89 20 192.168.1.89 255.255.255.255 127.0.0.1 127.0.0.1 20 192.168.1.255 255.255.255.255 192.168.1.89 192.168.1.89 20 224.0.0.0 240.0.0.0 192.168.1.89 192.168.1.89 20 255.255.255.255 255.255.255.255 192.168.1.89 192.168.1.89 1 Default Gateway: 192.168.1.1 =========================================================================== Persistent Routes: None You can get additional documentation on the route command here: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/route.mspx?mfr=true What you can do is set a route for your connection to the VPN service. Let's say you are on the 192.168.1.0 network, and you have a gateway on your office network at 10.10.10.5 configured to access the VPN service on the 72.21.211.1/24 network. You would use "route add" like this: route ADD 72.21.211.1 MASK 255.255.255.0 10.10.10.5 Your routing table should now reflect that change, and all traffic to the 72.21.211.0 range will now be sent over to the office gateway. The route add change will only persist across reboots if you add it with the -p flag: route -p ADD 72.21.211.1 MASK 255.255.255.0 10.10.10.5
[ "stackoverflow", "0061416519.txt" ]
Q: Parsing a generated method declaration in TypeScript With TypeScript, in Visual Studio Code, I start out with the following line in my React app's render method: <button className="btn btn-outline-primary" onClick={this.load}>Load</button> I use Visual Studio Code's built-in helper to generate the method load for me, and it generates: load(): ((event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void) | undefined { throw new Error("Method not implemented."); } I can't find documentation for this declaration style and can't quite parse it mentally. What is the | undefined { throw ... } doing? What does the => void mean? I assumed it meant the method returns void, but if I don't return something in the method body, I get an error. Is this declaration style known as a specific declaration style I could research further? A: First lets remove the TS load() { throw new Error("Method not implemented."); } That's just the normal JS part. Now sprinkling back in the types: load(): (event) => void { throw new Error("Method not implemented."); } this.load is a function with event argument that returns void. Let's extract that out: type LoadFunction = (event) => void load(): LoadFunction | undefined { throw new Error("Method not implemented."); } this.load is either LoadFunction OR it's undefined
[ "sharepoint.stackexchange", "0000045692.txt" ]
Q: What is a good way to determine via server object model if a field supports multiple values? When looking at an SPField object, how can I tell if it supports multiple values? I.e. a Choice field that is displayed using Checkboxes, a Managed Metadata field that allows multiple values, Person or Group that allows multiple selections, and quite possibly something I'm not thinking of? The best I've come up with is compiling a list of multi valued types (e.g. TaxonomyFieldTypeMulti, LookupMulti, UserMulti..) and comparing against FieldTypeAsString. I'm wondering if there's a better approach. A: Lookup fields (which user extends) supports AllowMultipleValues. Then you can do: var multi = field is SPFieldMultiChoice || (field is SPFieldLookup && (field as SPFieldLookup).AllowMultipleValues); Same for Taxonomy
[ "stackoverflow", "0038433371.txt" ]
Q: SQL - sorting data according to the first priority when using LIKE in Clause After googling I could not find my answer to sort data according to the priority when using like in clause I am using the following query to sort and view data: SELECT i.name,i.add_time,round(i.price),s.store_address FROM store_items i,stores s WHERE i.store_id = s.store_id AND (lower(i.name) LIKE '%samsung glaxy%' OR lower(i.name) LIKE '%samsung%' OR lower(i.name) LIKE '%glaxy%') ORDER BY i.price ASC LIMIT 0,25 How I can sort resulting rows firstly for Samsung Galaxy first like operator as first priority, and then rows for Samsung and Galaxy as second priority? Please Note: First priority means that result rows should be shown firstly and second priority means that other resulted rows should be shown after I have to fit it in my PHP function. @10086'answer I am not able to fit it in PHP CODE My PHP code is: $sort = $_COOKIE['sort']; $price_sort = $_COOKIE['price_sort']; $currency_value = $_COOKIE['currency_value']; if (!isset($_GET['number'])) { $limit = 0; }else{ $limit = filter_var($_GET['number'], FILTER_SANITIZE_NUMBER_INT); } $keyword_exp = explode(" ", $keyword); //separating keywords $like = ""; //for use like clause for every keyword $case = ""; // for priority selection case in query order $case_inc = 2; foreach ($keyword_exp as $value) { $like .= "AND lower(i.name) like '%$value%'"; $case .= "WHEN lower(i.name) like '%$value%' THEN $case_inc"; $case_inc += 1; } //query performing to show result $sql_query = "SELECT i.name 'title',i.add_time 'time',round(i.price) 'price',round(i.new_price) 'new_price',s.store_address 'address' FROM store_items i,stores s WHERE i.store_id = s.store_id $like ORDER BY CASE WHEN lower(i.name) LIKE '%$keyword%' THEN 1 $case END ASC LIMIT 0,25"; $query = mysql_query($sql_query) or die(mysql_error()); while ($row = mysql_fetch_array($query)) : extract($row); endwhile; My SQL query in PHP code gives me following error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lower(i.name) like '%refurbished%' THEN 3 END ASC LIMIT 0,25' at line 1 A: Your queries are not going to be as fast as they could because: You use the lower function when LIKE is already case insensitive. select 'a' LIKE 'A' will return true Using a column as the argument of a function in your WHERE forces the server to bypass its index and process the row: eg: lower(i.name). This should be avoided in general If you have MySQL 5.6+, and if store_items.name is of type CHAR, VARCHAR or TEXT, then add a FULLTEXT index to your name column to optimize it for text searches. ALTER TABLE store_items ADD FULLTEXT fulltext_name (name); Then modify your query to use the MATCH...AGAINST syntax: SELECT i.name,i.add_time,round(i.price),s.store_address FROM store_items i JOIN stores s ON i.store_id = s.store_id WHERE MATCH(i.name) AGAINST('samsung galaxy') This search will return all rows that have at least one of the two words samsung and galaxy. Rows that have both words will be higher in the result set. From the docs: MATCH() takes a comma-separated list that names the columns to be searched. AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform ... Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns
[ "ux.stackexchange", "0000042229.txt" ]
Q: Contact form in a web app for registered users When someone is not registered (or someone needs not to be, if it is not web app) on a site, then the contact form usually has 3 fields: name sender e-mail message body When the user gets registered, is it a better user experience to follow a different scheme than the one shown above? I am talking specifically about the case where a user wants to contact the administrators and not other users of the web/app. A: If the user has registered and logged in then you will already know who they are. But they may want to quote a different email address from the one they registered with. So you could keep much the same look and feel for registered users by using the same three pieces of data but presenting them slightly differently: name (either on the form itself, or in a disabled text field) sender email address (filled in in a text field, ready to be changed if necessary) message body You should also have a method of signalling "I'm someone else" which would log out the logged-in user and revert to the unregistered form. A refinement would be to have a further option (probably hidden until needed) to signal that the registered email address should be changed to the email address actually used in the form. download bmml source – Wireframes created with Balsamiq Mockups
[ "stackoverflow", "0024551959.txt" ]
Q: Retrieving and using a json associative array I use jquery and ajax to retrieve a dynamically made array made in php, like so: $json = array(); while ($row = $stmt->fetch_assoc()) { $json['item_'.$row['id']] = $row['name']; } header('Content-type: application/json; charset=utf-8'); echo json_encode($json); exit; If I test the php file in browser, it outputs: {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"} So far so good. But how do I use that array in jquery? I have this jquery ajax: $.getJSON( "json.php", function(data) { console.log(data); }); And testing that page in browser, it put this in console: Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"} And that's ok right? Or should item_x also be in quotes? Now, how do I USE that array in jquery? If I try console.log(data[0]) it puts undefined A: As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly. A solution would be to send an array of objects instead: while ($row = $stmt->fetch_assoc()) { $json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']]; } the in js: data[0].key; data[0].value; EDIT obviously key is a misleading name in this example, better to call it something else: $json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']]; //js data[0].id;
[ "stackoverflow", "0019771511.txt" ]
Q: Custom UITextField not showing I am trying to create a custom UITextField that shows a date picker instead of a keyboard. I already change the textfields in my storyboard to use DateTextField custom class, however, still the keyboard is being shown instead of the date picker. Note that the textfields are inside a UITableviewCell. Also, i am not sure if this is the correct way of creating the toolbar: self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)]; @interface DateTextField : UITextField @property (strong, nonatomic) UIDatePicker *datePicker; @property (strong, nonatomic) UIToolbar *datePickerToolbar; @end @implementation DateTextField - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.datePicker = [[UIDatePicker alloc] init]; self.datePicker.datePickerMode = UIDatePickerModeDate; self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)]; [self.datePickerToolbar setBarStyle:UIBarStyleBlackTranslucent]; UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(setDatePickerValue:)]; [self.datePickerToolbar setItems:[[NSArray alloc] initWithObjects:extraSpace, doneButton, nil]]; self.inputView = self.datePicker; self.inputAccessoryView = self.datePickerToolbar; } return self; } @end A: If you add the textfields in storyboard/xib the init method will not be called. Try with awakeFromNib. Move all the code in the init method to awakeFromNib - (void)awakeFromNib { [super awakeFromNib]; self.datePicker = [[UIDatePicker alloc] init]; self.datePicker.datePickerMode = UIDatePickerModeDate; self.datePickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.superview.bounds.size.width, 44)]; [self.datePickerToolbar setBarStyle:UIBarStyleBlackTranslucent]; UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(setDatePickerValue:)]; [self.datePickerToolbar setItems:[[NSArray alloc] initWithObjects:extraSpace, doneButton, nil]]; self.inputView = self.datePicker; self.inputAccessoryView = self.datePickerToolbar; }
[ "stackoverflow", "0059678358.txt" ]
Q: Jovo Alexa: jovo deploy says Trigger settings for the lambda is invalid I am creating an Alexa skill using JOVO framework. I have completed the following steps on Amazon Alexa console: Created a new skill in AWS Alexa console Created a function in Lambda console Under endpoints of the skill added the Lambda arn. Added an Alexa Skill Kit trigger in the above lambda function and added the Skill ID Saved endpoints successfully. Local setup: $ jovo new WeatherService $ cd WeatherService $ code . $ ask init selected ask defualt. Logged in through IAM console in browser $ jovo build --platform alexaSkill Up to this everything works fine. So I went on to deploy the skill by the following command: $ jovo deploy When the Lambda was trying to deploy, I get the following message: The trigger setting for the Lambda arn:aws:lambda:us-east-1:880731272882:function:MyWeatherTeller is invalid Out of curiosity, I ran the same command $jovo deploy and this time it is a different error message: askApiUpdateSkill:Resource not found What I am doing wrong? Below are screenshots of the console setup: Function setup: Skill endpoint setup: A: In a newly created Jovo project, the $ jovo deploy command creates a new Alexa Skill project. This new project has a different Skill ID than the Skill project you've created by hand. This is why your trigger (which only accepts 1 Skill ID if verification is enabled) is complaining. If you don't want to create a new Skill project with the deploy command, you can also add the current Skill ID to your project.js (learn more here) file: alexaSkill: { nlu: 'alexa', skillId: 'yourSkillId', }, Then run the two commands again: $ jovo build $ jovo deploy
[ "stackoverflow", "0029152299.txt" ]
Q: How can I step directly into a function without stepping into intermediate functions for parameters? In Visual Studio 2013 (or any version really) and I am debugging a C++ project, I want to be able to bypass stepping into intermediate functions that are called due to parameters being passed into the function of interest. How can I bypass stepping into these intermediate functions (not of interest directly) and just go straight to my function of interest? For example, let's say I have a function that passes in a list of objects and another parameter that is a string. If I set a breakpoint and click the Step Into button or F8 then it is actually first steps into the functions necessary to get the list of objects ready as well as the string object. I don't care about these intermediate functions for the setup and I just want to go directly to my function of interest. Is there a setting to be able to do this? A: Right Click -> Step Into Specific -> pick the function you want to step into.
[ "stackoverflow", "0006456576.txt" ]
Q: xml paeser for iphone app i have a xml file on a server that look for example like this one: <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> </breakfast_menu> i need xml parser that will parse it and enter each one of them to a class that for examle will called food(and have 4 parameters : name,price,.....). and finally to create an array of the classes that he create.there is built xml parser that do it? A: Here are some sources on the topic: Navigating XML from Objective-C How do I parse an NSString containing XML in Objective-C? Objective C: Parsing an XML file Parsing XML in Cocoa Parsing XML in objective-c
[ "stackoverflow", "0010974985.txt" ]
Q: i want to run the following php script continously in specified intervals of time and can be set by a user using a form. how to do this? //i need to run this script repetadly and the time interval can be set by a user // checking the internet connection if (!$sock = fsockopen("www.google.com", 80, $errno, $errstr,20)) { ?> <script type="text/javascript"> alert("Connection problem"); </script> <?php } // retriving data from database and checking the site is down else { for($i=0;$i<count($res);$i++) { $fp=fsockopen($res[$i]['url'],80,$errno,$errstr,30); if($fp==false) { ?> <script type="text/javascript"> alert("Website is down"); </script> <?php // writing data to database and sending mail mail($email[0]['email_id'],"website is down",$res[$i]['url']." is down"); $inputs=array('website_id'=>$res[$i['website_id'], 'date'=>date("Y-m-d H:i:s"),'reason'=>"website down"); $obj3->addLog($inputs); } } } sleep(300); } A: Look at the cron service. Someone has already explained it here. If you want it to stay in the form of a web page, automatically reloading itself, then look at the JavaScript function setTimeout. A: Your problem with cron is this "and the time interval can be set by a user". You can use cron such way, that you run script every 30 seconds or every N seconds. That is your smallest granularity for running script. Now, if user sets that script must be run every 30 minutes, first thing you do at script is check that, if script needs to proceed - if last run was before that 30 minutes that user set. Script pseudo goes like this: 1) load last run from DB, compare it with interval - do we need to proceed, if not exit 2) do what script needs to do 3) save to the DB last run time Of course this all is only necessary, if user needs to be able to dynamically change run interval and dont want to touch cron.
[ "stackoverflow", "0057633364.txt" ]
Q: Querying with restriction values from an OWL ontology I'm starting to learn how inferencing works against an owl ontology, and having a bit of a problem determining if what I'm trying to do is actually possible. The ontology that I'm using is the wine ontology located here; it references this food ontology. I've been playing around with the inferencing engines in both Protege and Jena. What I'm trying to do is determine the wines that could be associated with a MealCourse instance. I've added an instance of the LightMeatFowlCourse to my copy of the ontology: <owl:NamedIndividual rdf:about="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#test"> <rdf:type rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#LightMeatFowlCourse"/> <food:hasFood rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#Chicken" /> </owl:NamedIndividual> Now I can see the types, both asserted and inferred, of this instance, so I believe that inferencing is working - here's the output of the types for this instance in Jena: http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#LightMeatFowlCourse http://www.w3.org/2002/07/owl#NamedIndividual http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#MealCourse http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#ConsumableThing http://www.w3.org/2000/01/rdf-schema#Resource So now I'm trying to use the hasDrink property to determine what kinds of wine could go with this course. There are several restrictions defined in the ontology for instances that can be associated with this property: hasBody, hasColor, etc. - here's the definition: <owl:Class rdf:about="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#LightMeatFowlCourse"> <owl:equivalentClass> <owl:Class> <owl:intersectionOf rdf:parseType="Collection"> <rdf:Description rdf:about="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#MealCourse"/> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasFood"/> <owl:allValuesFrom rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#LightMeatFowl"/> </owl:Restriction> </owl:intersectionOf> </owl:Class> </owl:equivalentClass> <rdfs:subClassOf rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#MealCourse"/> <rdfs:subClassOf> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasDrink"/> <owl:allValuesFrom> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasBody"/> <owl:hasValue rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#Medium"/> </owl:Restriction> </owl:allValuesFrom> </owl:Restriction> </rdfs:subClassOf> <rdfs:subClassOf> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasDrink"/> <owl:allValuesFrom> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasColor"/> <owl:hasValue rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#White"/> </owl:Restriction> </owl:allValuesFrom> </owl:Restriction> </rdfs:subClassOf> <rdfs:subClassOf> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasDrink"/> <owl:allValuesFrom> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasFlavor"/> <owl:hasValue rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#Moderate"/> </owl:Restriction> </owl:allValuesFrom> </owl:Restriction> </rdfs:subClassOf> <rdfs:subClassOf> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasDrink"/> <owl:allValuesFrom> <owl:Restriction> <owl:onProperty rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/wine#hasSugar"/> <owl:hasValue rdf:resource="http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#Dry"/> </owl:Restriction> </owl:allValuesFrom> </owl:Restriction> </rdfs:subClassOf> </owl:Class> Can I A) get these restrictions, so I can determine what kinds of wine would be a match for my MealCourse instance, and B) perform that query to get the list of instances that are a match? I've been reading through the w3c documents on querying OWL relationships and I'm pretty sure this can be done, but I'm having a real problem coming up with the SPARQL - I feel like I'm missing something pretty obvious, but I'm not sure what exactly I should be looking at. A: The comment from AKSW gave the answer: SELECT ?p ?val WHERE { <http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#LightMeatFowlCourse> rdfs:subClassOf ?restriction . ?restriction owl:onProperty <http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#hasDrink>. ?restriction owl:allValuesFrom [owl:onProperty ?p; owl:hasValue ?val]. }
[ "stackoverflow", "0003906891.txt" ]
Q: what is the max limit of data into list in c#? How many values I can add to List? For example: List<string> Item = runtime data The data is not fixed in size. It may be 10 000 or more than 1 000 000. I have Googled but have not found an exact answer. A: The maximum number of elements that can be stored in the current implementation of List<T> is, theoretically, Int32.MaxValue - just over 2 billion. In the current Microsoft implementation of the CLR there's a 2GB maximum object size limit. (It's possible that other implementations, for example Mono, don't have this restriction.) Your particular list contains strings, which are reference types. The size of a reference will be 4 or 8 bytes, depending on whether you're running on a 32-bit or 64-bit system. This means that the practical limit to the number of strings you could store will be roughly 536 million on 32-bit or 268 million on 64-bit. In practice, you'll most likely run out of allocable memory before you reach those limits, especially if you're running on a 32-bit system. A: 2147483647 because all functions off List are using int. Source from mscorlib: private T[] _items; private int _size; public T this[int index] { get { //... } } A: list.Count() property is int32, so it must be the maxium limit of int32 but how your list performs over this limit is a nice observation. if you do some list manupulation operations, it would be linier in theory. i would say if your are having very large number of items thnink about the Parallel Collections in .net 4.0 this would make your list operations more responsive.
[ "serverfault", "0000185244.txt" ]
Q: nginx: location, try_files, rewrite: Find pattern match in subfolder, else move on? I'd like for Nginx to do the following: If the uri matches the pattern: http://mysite.com/$string/ and $string is not 'KB', and not 'images', look for $string.html in a specific subfolder. If $string.html exists in the subfolder, return it. If it does not exist, move on to the next matching location. $string = {any letters, numbers, or dash} For example, if the user requests: http://mysite.com/test/ It should look for a file called: /webroot/www/myfolder/test.html I've tried variations of: location ~ /[a-zA-Z0-9\-]+/ { try_files /myfolder/$uri.html @Nowhere; } But: It doesn't seem to find the file even when it does exist, and If it fails (which is always right now), it wants to jump to the @nowhere location, rather than moving on and trying to find another location that matches. I'd like for it to consider the current location "not a match" if the file doesn't exist. A: I think you can try this: location ~* ^/(KB|images)/$ { #rule for KB or images goes here } location ~* ^/([a-zA-Z0-9\-]+)/$ { root /webroot/www/myfolder/; try_files $1.html @Nowhere; } location @Nowhere { #rule for @Nowhere goes here } For more, refer to: http://wiki.nginx.org/HttpCoreModule#location
[ "stackoverflow", "0001513492.txt" ]
Q: Enabling Disabled tools in the visual studio toolbar I am developing my minor and major project in VS2008. Suddenly tools have started to go missing from my toolbar. I have visited several forums but am not able to solve the problem. Basically I have silverlight 2.0 installed with SDK, and tools and all. Now when I need to access the media element control from silverlight it does not display. Further more on listing all controls I can see those controls but they are disabled. Please Help Me out. Regards Shrey Mishra A: It's weird but I was able to solve the problem by simply removing USB Mouse .:) When i checked this out with some others developing on their laptops it came to me that it happens with very few of us in VS 2008 but still can drive on mad.