text
stringlengths
64
89.7k
meta
dict
Q: PBKDF2WithHmacSHA256 on Android API 24 and lower I'm trying to use Luke Joshua Park SecureCompatibleEncryptionExamples on android. My problem is that PBKDF2WithHmacSHA256 is not available for android below API 26. Any way to get around this? A: Android doesn't support PBKDF2withHmacSHA256 before API 26, but it does support PBKDF2withHmacSHA1 in older versions. Unless there is a specific reason you want to use SHA256 as the PBKDF2 hash, there is no harm in changing this. The algorithms in my repository can be changed relatively easily by adjusting the PBKDF2_NAME parameter. SHA1 is still safe to use with PBKDF2, so you could simply adjust: private final static String PBKDF2_NAME = "PBKDF2WithHmacSHA256"; To: private final static String PBKDF2_NAME = "PBKDF2WithHmacSHA1"; In your Android code and in your PHP change: define("PBKDF2_NAME", "sha256"); To: define("PBKDF2_NAME", "sha1"); Also of note, if you're using this as transport security, you shouldn't be. You should be using TLS.
{ "pile_set_name": "StackExchange" }
Q: Is it true that cyclic subgroups are always normal? There is a proposition that I'm supposed to "prove", but it doesn't sound true to me. It says that if $H$ is a cyclic subgroup of a group $G$ (notation $H<G$), then every $K <H$ is normal in $G$. If that were the case, since $H<H$, we'd have a corollary: If $H$ is cyclic, then $H$ is normal in $G$. But is that even true? A: No, it's not true that if $H$ is a cyclic subgroup of $G$ then it is a normal subgroup of $G$. For a simple counterexample, let $G=S_3$ and let $H$ be the subgroup generated by the transposition $(12)$. Perhaps the problem should instead read "every $K\leq H$ is normal in $H$".
{ "pile_set_name": "StackExchange" }
Q: What's wrong with this? Cannot find symbol. symbol - constructor public MyLine(double x, double y) { MyLine p1 = new MyLine(); p1.x = x; p1.y = y; } That's my code and the error I get is ./MyLine.java:12: cannot find symbol symbol : constructor MyLine() location: class MyLine MyLine p1 = new MyLine(); A: Don't instantiate it inside the constructor. Just assign: this.x = x; this.y = y; The error tells you that you don't have a no-argument constructor, but even if you had, the behaviour won't be as you expect A: The error message tells you that you don't have a no-arguments constructor in your MyLine class. You could create one to let that code compile. However it looks like you're trying to instantiate a MyLine object inside the MyLine constructor. You almost certainly don't want to do this. Instead you want to take the values passed as arguments and initialize the fields of the current object with them: public MyLine(double x, double y) { this.x = x; this.y = y; } A: This line: MyLine p1 = new MyLine(); should be removed. That's creating a new instance, you actually want to work with the instance you're creating (since you're in the constructor.) You're getting the error because you're calling a constructor from this line that doesn't exist, but you don't want to be doing that anyway. You can use the this keyword to reference the current instance (which you need to do if the fields have the same name as the parameters, which in this case it looks like they do.) So taking that into account, you'd end up with the following: public MyLine(double x, double y) { this.x = x; this.y = y; }
{ "pile_set_name": "StackExchange" }
Q: Javascript - Infinite scroll loop Short story : I want to parse a website that has infinite scroll on it, I don't want to implement infinite scroll. So I want to create a script that automatically scroll the page from the browser console wait for the data to appears then repeat until the end. Long story : I'm trying to scroll down an infinite scroll using javascript console into my browser. When we scroll to the bottom, an Ajax call is made and fill a <div> element so we have to wait for this to occurs then resume our process. My main problem here is that all of this is done too quickly, it doesn't wait the ajax to be completed before resuming the process. To have a concrete example, when I go to AngelList jobs page (need to be logged in) and when I put this in my browser console : function sleep(µs) { var end = performance.now() + µs/1000; while (end > performance.now()) ; // do nothing } var loading = true; $(window).load(function () { loading = false; }).ajaxStart(function () { loading = true; }).ajaxComplete(function () { loading = false; }); function waitAfterScroll() { if(loading === true) { console.log("Wait the Ajax to finish loading"); setTimeout(waitAfterScroll, 1000); return; } console.log("Ajax DONE"); } var X= 0; while(X < 100){ sleep(1000000); X = X + 10; console.log(X); window.scrollTo(0,document.body.scrollHeight); waitAfterScroll(); } I've got this result : 10 Wait the Ajax to finish loading 20 Wait the Ajax to finish loading 30 Wait the Ajax to finish loading 40 Wait the Ajax to finish loading 50 Wait the Ajax to finish loading 60 Wait the Ajax to finish loading 70 Wait the Ajax to finish loading 80 Wait the Ajax to finish loading 90 Wait the Ajax to finish loading 100 Wait the Ajax to finish loading Wait the Ajax to finish loading Ajax DONE What I would like is : 10 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 20 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 30 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 40 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 50 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 60 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 70 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 80 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 90 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE 100 Wait the Ajax to finish loading // one or multiple times..... Ajax DONE I hope this is clear. In other words, I would like to be able to scroll down, stop the execution of the javascript or at least wait for the ajax to finish loading, then repeat. A: I am pretty sure that I misunderstood what you wanted, but anyway. Why not using Promises?: var promise = new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { if (req.status == 200) { resolve(req.response); } }; }); promise.then(function(result) { window.scrollTo(0,document.body.scrollHeight); }) Or, you could make a synchronous ajax request to stop javascript execution. jQuery.ajax({ url: "someurl.html", async: false, success: function(html){ window.scrollTo(0,document.body.scrollHeight); } }); But, for performance reasons, I would not recommend that. Instead you could: // Start off with a promise that always resolves var sequence = Promise.resolve(); arrayOfWebsiteContentUrls.forEach(function(url) { sequence = sequence.then(function() { return fetchTheContent(url); }).then(function(content) { addContent(content); window.scrollTo(0,document.body.scrollHeight); }); }); I took that last bit from this excelent article on Promises. Please, let me know if there is something that you don't get.
{ "pile_set_name": "StackExchange" }
Q: Python pickle - how does it break? Everyone knows pickle is not a secure way to store user data. It even says so on the box. I'm looking for examples of strings or data structures that break pickle parsing in the current supported versions of cPython >= 2.4. Are there things that can be pickled but not unpickled? Are there problems with particular unicode characters? Really big data structures? Obviously the old ASCII protocol has some issues, but what about the most current binary form? I'm particularly curious about ways in which the pickle loads operation can fail, especially when given a string produced by pickle itself. Are there any circumstances in which pickle will continue parsing past the .? What sort of edge cases are there? Edit: Here are some examples of the sort of thing I'm looking for: In Python 2.4, you can pickle an array without error, but you can't unpickle it. http://bugs.python.org/issue1281383 You can't reliably pickle objects that inherit from dict and call __setitem__ before instance variables are set with __setstate__. This can be a gotcha when pickling Cookie objects. See http://bugs.python.org/issue964868 and http://bugs.python.org/issue826897 Python 2.4 (and 2.5?) will return a pickle value for infinity (or values close to it like 1e100000), but may (depending on platform) fail when loading. See http://bugs.python.org/issue880990 and http://bugs.python.org/issue445484 This last item is interesting because it reveals a case where the STOP marker does not actually stop parsing - when the marker exists as part of a literal, or more generally, when not preceded by a newline. A: This is a greatly simplified example of what pickle didn't like about my data structure. import cPickle as pickle class Member(object): def __init__(self, key): self.key = key self.pool = None def __hash__(self): return self.key class Pool(object): def __init__(self): self.members = set() def add_member(self, member): self.members.add(member) member.pool = self member = Member(1) pool = Pool() pool.add_member(member) with open("test.pkl", "w") as f: pickle.dump(member, f, pickle.HIGHEST_PROTOCOL) with open("test.pkl", "r") as f: x = pickle.load(f) Pickle is known to be a little funny with circular structures, but if you toss custom hash functions and sets/dicts into the mix then things get quite hairy. In this particular example it partially unpickles the member and then encounters the pool. So it then partially unpickles the pool and encounters the members set. So it creates the set and tries to add the partially unpickled member to the set. At which point it dies in the custom hash function, because the member is only partially unpickled. I dread to think what might happen if you had an "if hasattr..." in the hash function. $ python --version Python 2.6.5 $ python test.py Traceback (most recent call last): File "test.py", line 25, in <module> x = pickle.load(f) File "test.py", line 8, in __hash__ return self.key AttributeError: ("'Member' object has no attribute 'key'", <type 'set'>, ([<__main__.Member object at 0xb76cdaac>],))
{ "pile_set_name": "StackExchange" }
Q: Hive date conversion I intended to extend certain records in a table by adding 366 days to its date keys: to_date(date_add(from_unixtime(unix_timestamp('20150101' ,'yyyyMMdd'), 'yyyy-MM-dd'), 366)) as new_date 2016-01-01 But how to convert this value back to format of original key i.e. 20160101 ? A: Since your requested date is 2016-01-01 it seems you want to add 365 days and not 366. select from_unixtime(unix_timestamp(date_add(from_unixtime(unix_timestamp( '20150101','yyyyMMdd')),365),'yyyy-MM-dd'),'yyyyMMdd'); Demo hive> select from_unixtime(unix_timestamp(date_add(from_unixtime(unix_timestamp( > '20150101','yyyyMMdd')),365),'yyyy-MM-dd'),'yyyyMMdd'); OK 20160101
{ "pile_set_name": "StackExchange" }
Q: Add columns based on join I have huge tables (3 millions records) that must have a joined column. This value will not change. How can I add a column based on a join? There will be some other queries. If I use join, it will be a slower process. Ex: Main Table: add_cod | name 1 | alfa 2 | beta 1 | zeta Addon Table: cod | col_ext 1 | jam 2 | bam The result should be the main table, but with col_ext column: add_cod | name | col_ext 1 | alfa | jam 2 | beta | bam 1 | zeta | jam A: This is a simple JOIN. SELECT a.*, b.col_ext FROM main a INNER JOIN addon b ON a.add_cod = b.cod You don't have to worry about performance if you have properly implemented index on your tables. SQLFiddle Demo
{ "pile_set_name": "StackExchange" }
Q: How to remove stop words using nltk or python So I have a dataset that I would like to remove stop words from using stopwords.words('english') I'm struggling how to use this within my code to just simply take out these words. I have a list of the words from this dataset already, the part i'm struggling with is comparing to this list and removing the stop words. Any help is appreciated. A: from nltk.corpus import stopwords # ... filtered_words = [word for word in word_list if word not in stopwords.words('english')] A: You could also do a set diff, for example: list(set(nltk.regexp_tokenize(sentence, pattern, gaps=True)) - set(nltk.corpus.stopwords.words('english'))) A: I suppose you have a list of words (word_list) from which you want to remove stopwords. You could do something like this: filtered_word_list = word_list[:] #make a copy of the word_list for word in word_list: # iterate over word_list if word in stopwords.words('english'): filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword
{ "pile_set_name": "StackExchange" }
Q: MVC 3 Razor - Unobtrusive Validation Not Working Can anyone see why my validation is not working? Currently it just posts and fails on the insert because the data insert doesn't allow nulls instead of catching it client-side and displaying the required field messages. View http://pastebin.com/4grwD02i Controller http://pastebin.com/jdbYk8tR Layout http://pastebin.com/AbQ9xYLG AppSettings <appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> ~~UPDATE~~ Model http://pastebin.com/FJkPgKsX I'm just using a Linq to SQL DBML file for my DAL so, no I haven't done any decorating of properties. Can I do this and still use DBML? A: The default model binder relies on data annotations in order to perform validation. So if your model properties don't have any attributes to indicate how validation is performed it will always be considered as valid (except for example in cases where you are trying to bind invalid formats to a DateTime or int fields when the default model binder will automatically mark the model state as invalid).
{ "pile_set_name": "StackExchange" }
Q: Why GIT status is confusing when deleted a file and created a folder with same name? I did this in a git repo. My git version is 2.9.0. touch a git add --all git commit -m "file created" rm a mkdir a cd a touch b git status Now the status shows this, in the changes not staged for commit. deleted: a But it doesn't show anything for the fact that a new folder (named "a") is created and there is a new file (named "b") in it. Not even as untracked changes... I mean what about new file b, there is nothing in untracked file section or anything So the confusion is, if I remove a file and create a new folder/directory with the same name, git only shows that file is deleted, but not the addition of the directory. However when I did git add and commit, I got my changes committed. But why does status behave in such a way? Why is git confused when a file is deleted and a folder is created with the same name? A: It's a minor bug in git status. As Arpit noted, you have to get git status to give you information about all untracked files, rather than letting it attempt to summarize directories ("folders"). When it does the summary instead, it gets confused by the fact that there is an entry in the index for a file with the shortened version of the name: $ mkdir rmtest; cd rmtest; git init Initialized empty Git repository in /home/torek/tmp/rmtest/.git/ $ echo for testing rm file replace with dir > README $ git add README $ git commit -m initial [master (root-commit) c650ec0] initial 1 file changed, 1 insertion(+) create mode 100644 README $ echo create a as file > a $ git add a $ git commit -m 'add file a' [master e33cff2] add file a 1 file changed, 1 insertion(+) create mode 100644 a $ rm a $ mkdir a $ touch a/b We are now in your state: there is an untracked file named a/b, while tracked file a has gone missing. The tracked file a is still in the index so it will be in the next commit made. The untracked file a/b is not in the index, so it will not be in the next commit made—it cannot be; the tracked file a is in the way. Due to the minor bug, git status reports this as: $ git status On branch master Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: a no changes added to commit (use "git add" and/or "git commit -a") However, git status -uall makes git status list the contents of directory a individually, rather than trying to summarize them as "there are one or more untracked files within a directory named a", so that we see: $ git status -uall On branch master Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: a Untracked files: (use "git add <file>..." to include in what will be committed) a/b no changes added to commit (use "git add" and/or "git commit -a") This happens because the summarized version uses the path a, which—as noted above—remains in the index. If we force a new commit, we can see that the new commit contains the file a: $ git commit --allow-empty -m recommit [master d7cbb81] recommit $ git ls-tree -r HEAD 100644 blob ada8d39a4e96a31a4c7f2301dbfc807fcfdac71c README 100644 blob 739675cd3231d46a10d4b8f477cc1b35857758c1 a $ git log --all --decorate --oneline --graph * d7cbb81 (HEAD -> master) recommit * e33cff2 add file a * c650ec0 initial Normally, Git would print "a/" in the "untracked files" section, but because a is tracked (and as we just saw, still gets committed!), it can't report it there (because it's missing a special case that would take it temporarily out of the in-core cache to allow it to be reported). Interestingly, the same issue shows up differently if you git reset HEAD a: $ git reset HEAD a Unstaged changes after reset: T a Note that here, Git is reporting the issue as a file-type change (the file type has gone from "regular file" to "directory", and Git does not store directories, so this is also a bug). If we replace directory a containing file a/b with plain symlink a, the status reports become correct, since Git is able to store symlinks and is not attempting to summarize anything: $ rm -r a; ln -s foo a $ git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) typechange: a no changes added to commit (use "git add" and/or "git commit -a")
{ "pile_set_name": "StackExchange" }
Q: Node file modes on Windows? In Node, file modes (e.g. for fs.open) are defined in the terms of the POSIX world (a three-digit octal value). However, that does not map to how Windows does things. Windows does not have such tight coupling between user permissions and the filesystem. Windows' OpenFile function does not even have any related parameters. But from what I gathered so far, they are not entirely ignored either. Is there any explanation on how to use Node file modes on Windows? A: Take a look at the source. It seems like the only thing they are doing is setting FILE_ATTRIBUTE_READONLY based on whether the file is writeable or not. if (flags & _O_CREAT) { if (!((req->mode & ~current_umask) & _S_IWRITE)) { attributes |= FILE_ATTRIBUTE_READONLY; } } The notes on fs.chmod are interesting as well. /* Todo: st_mode should probably always be 0666 for everyone. We might also * want to report 0777 if the file is a .exe or a directory. * * Currently it's based on whether the 'readonly' attribute is set, which * makes little sense because the semantics are so different: the 'read-only' * flag is just a way for a user to protect against accidental deleteion, and * serves no security purpose. Windows uses ACLs for that. * * Also people now use uv_fs_chmod() to take away the writable bit for good * reasons. Windows however just makes the file read-only, which makes it * impossible to delete the file afterwards, since read-only files can't be * deleted. * * IOW it's all just a clusterfuck and we should think of something that * makes slighty more sense. * * And uv_fs_chmod should probably just fail on windows or be a total no-op. * There's nothing sensible it can do anyway. */
{ "pile_set_name": "StackExchange" }
Q: Triangle - Triangle Intersection Test I'd like to know if there is out there some tutorial or guide to understand and implement a Triangle-Triangle intersection test in a 3D Environment. (i don't need to know precise where the intersection happened, but only that an intersection has occurred) I was going to implement it following a theoric pdf, but i'm pretty stuck at the Compute plane equation of triangle 2. Reject as trivial if all points of triangle 1 are on same side. Compute plane equation of triangle 1. Reject as trivial if all points of triangle 2 are on same side. Compute intersection line and project onto largest axis. Compute the intervals for each triangle. Intersect the intervals. point 5 of this guide. I don't really know what's asking (all 5,6 and 7). XD As i don't have high knowledge in mathematics (well, i know as far the couple of exams at the university has given me (i'm a raw programmer XD)), please try to be as simple as possible with me. :D (I tried to search on google, but most of the links point to some 4-5 pages full of formulas I don't really care to know and I don't understand.) Thanks for the help A: You said: I'd like to know if there is out there some tutorial or guide to understand and implement a Triangle-Triangle intersection test in a 3D Environment. And then you said: most of the links point to some 4-5 pages full of formulas I don't really care to know I note that those two statements totally contradict each other. So which is it? Do you want to understand how triangle-triangle intersection works, or do you just want an implementation that works but you don't understand it? It's not like all those web pages are full of unnecessary math. All the math is necessary to understanding how the intersection algorithm works. Start at the beginning and learn how all of it works. Steps 5, 6 and 7 are straightforward to understand once you know what the words mean. The intersection line is the line made by the intersection of the two planes. Each triangle lies in a plane. There are three cases: the planes are parallel and do not intersect. The triangles obviously do not intersect. the planes are the same plane. The triangles might meet or might not. the planes are two different planes that meet at a line. If the triangles intersect, they obviously must intersect on that line. Suppose we're in the third case. Compute the segment of the intersection line which is contained in the first triangle. Compute the segment of the intersection line which is in the second triangle. The question is now "do these segments overlap?" You can work that out by projecting the segments onto a convenient axis, and seeing whether the line segments on that axis overlap. Basically, it works like this: imagine you are shining a light on the line segments, such that their shadows fall onto an axis. If the shadows on the axis intersect then the line segments must intersect. If there is a gap between the shadows on the axis, then clearly there must be a gap between the line segments, and therefore the triangles do not intersect. If you want to understand how this works then there's no getting around the fact that you are going to need to understand all this stuff -- all the algebra that works out how planes intersect and how projects onto an axis work. It's all necessary. And all that stuff is basic building blocks out of which more complex transformations, projections, and so on, will be built, so understand the basics thoroughly if you want to go farther.
{ "pile_set_name": "StackExchange" }
Q: Column vs Field: have I been using these terms incorrectly? I feel kind of embarrassed here, I've always used the terms "column" and "field" completely interchangeably, which recently caused some confusion in a technical discussion. I was told, though, that this wasn't correct, that it should be (translating each term into spreadsheet terminology, ignoring data types and all the other stuff that make databases useful): Database Column: like a spreadsheet column Database Record: like a spreadsheet row Database Field: like a spreadsheet "cell" (a specific column of a specific row) Is this right? I could have sworn that column and field are used more interchangeably than that. I certainly have been. So we don't add fields to a table, we add columns to a table, and fields are only relevant when talking about data within a record? Other thoughts on column vs field? Edit: to clarify, the current context is MS SQL Server. My background before SQL server was MS Access, which might influence my use of these terms. A: Relational database theory does not include the use of the word Field. Dr. E.F. Codd, who wrote the series of papers that provide the theoretical basis for RDBMS's never used the term. You can read his seminal 1970 paper A Relational Model of Data for Large Shared Data Banks if you want to check. Terms like Domain, Table, Attribute, Key and Tuple are used. One reason for this, is that his papers were largely concerned with relational algebra, and the way a particular implementation would define a table in a database wasn't considered by Codd to be important. Vendors would flesh that out later. People also have to understand that historically, RDBMS's evolved from existing hierarchical and network databases that predate them, AND the inner workings of an RDMBS still have to be concerned with data organization and storage. In common use, and you can easily verify this by simply doing a bit of googling, Fields and columns are the same thing. PC Databases like DBase, Access and Filemaker typically use "field" instead of "column". "Attribute" is another term that can be used interchangeably. For example, here's a link to the MS Access manual on adding a "field" to a table. It's clear to see that in MS Access a "field" is equivalent to a "column". The same holds for Dbase and Filemaker Pro. Sometimes people will refer to a specific value in a specific row as being a "field" or more properly a "field value" but that does not make the use of "field" when referring to a column or column-equivalent-concept incorrect. This does tend to cause a level of confusion because people have used "field" to mean different things for many years. In relational theory -- a single atomic value is referred to as a "Datum". If someone stated that a "field" is one value in a relational database and not the same as a column, that is their opinion, since "field" is not part of relational database vernacular. They are neither right nor wrong, however, throughout the database world, field is more often used to mean column. With that said, projects and teams often have to work out an understanding of how they want to use particular terminology within the project to avoid confusion. You aren't wrong, but you also might decide to simply go along with the convention being used, or avoid using the word field altogether in favor of "column". With relational databases, "Table" and "Column" are the building blocks that exist in DDL and it's best to just use those terms and avoid "field" which isn't used, nor clearly defined. A: The older SQL:92 refers to fields as components of datetime items: "Fields in datetime items", specifies the fields that can make up a date time value; a datetime value is made up of a subset of those fields The fields here are year, month, and so on... and the term field doesn't seem to have any other meaning in the rest of the document. The newer SQL:2003 standard has this: Columns, fields, and attributes The terms column, field, and attribute refer to structural components of tables, row types, and structured types, respectively, in analogous fashion. As the structure of a table consists of one or more columns, so does the structure of a row type consist of one or more fields and that of a structured type one or more attributes. Every structural element, whether a column, a field, or an attribute, is primarily a name paired with a declared type. and later: A field F is described by a field descriptor. A field descriptor includes: — The name of the field. — The data type descriptor of the declared type of F. — The ordinal position of F within the row type that simply contains it. This contrast with the column, which is defined as: A column C is described by a column descriptor. A column descriptor includes: — The name of the column. — Whether the name of the column is an implementation-dependent name. — If the column is based on a domain, then the name of that domain; otherwise, the data type descriptor of the declared type of C. — The value of , if any, of C. — The nullability characteristic of C. — The ordinal position of C within the table that contains it. ... (and more) Then later again, when introducing tables: A table is a collection of rows having one or more columns. A row is a value of a row type. Every row of the same table has the same row type. The value of the i-th field of every row in a table is the value of the i-th column of that row in the table. The row is the smallest unit of data that can be inserted into a table and deleted from a table. (emphasis mine). This seems to support what you wrote in the question: a specific column of a specific row. A: And how many angels can dance around the head of a pin? The person who corrected you could themselves be corrected. Table = Relation Row = Tuple Column = Attribute Domain = Data Type See the Wikipedia entry on relational databases here. I worked for an airline and the word "flight" could be used in three different ways depending on whether you were talking to pilots/flight-attendants, engineers or marketing. pilots/attendants: a "flight" was out and back from base (i.e. two take-offs and two landings), engineers: one take-off and one landing, could be test, repair, training (i.e. one airport back to the same airport) or a "leg", i.e. one airport to another - what "civilians" would normally call a flight, as in "I'm catching my flight home tomorrow"), marketing: a six month (typically on-season or off-season) series of "flights" from/to a given airport in the context of a contract. The spreadsheet analogy is more than good enough for 99.99% of cases, even in reasonably technical speech (unless one is a professor of relational algebra). Does the person who corrected you use the word "whom" correctly? 99.99% of people don't and it really doesn't matter.
{ "pile_set_name": "StackExchange" }
Q: Ubuntu 14.04 Server - WiFi WPA2 Personal I just installed Ubuntu 14.04 Server and cannot get wifi configured correctly to work with WPA2 personal and could use some help. There was a simple wizard during install where I selected my SSID from a list and entered my passphrase and that worked great. Now that the install is done I am having trouble configuring wifi. My Access Point is setup to WPA2 Personal TKIP or AES. Any advice would be greatly appreciated. I have been messing around with WPA supplicant ant my /etc/network/interfaces file with no luck. Thanks A: I suggest you set up /etc/network/interfaces something like: auto lo iface lo inet loopback auto wlan0 iface wlan0 inet static address 192.168.1.150 netmask 255.255.255.0 gateway 192.168.1.1 wpa-ssid <your_router> wpa-psk <your_wpa_key> dns-nameservers 8.8.8.8 192.168.1.1 Be sure to select a static address outside the range used by the DHCP server in the router, switch or other access point. Of course, substitute your details here. Get the system to read and use the changes: sudo ifdown wlan0 && sudo ifup -v wlan0 Did you connect? ping -c3 192.168.1.1 ping -c3 www.google.com A: I managed to connect to my WPA2 access point by putting the following in /etc/network/interfaces. Slightly modified from the accepted answer, and using DHCP. auto wlan0 iface wlan0 inet dhcp wpa-ssid <your_router> wpa-psk <your_wpa_key> Then a simple sudo ifup -v wlan0 and it connected. All good. A: Using either DHCP or a static config (doesn't matter which)--AND assuming your wifi worked during install--make your /etc/network/interfaces look something like below (for wlan0 should match the name of your wifi card listed under ifconfig -a e.g. your detected wifi card could be nicknamed eth1 by the OS for all I know.): auto lo iface lo inet loopback auto wlan0 iface wlan0 inet dhcp wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf To configure wpa_supplicant use the command (Referenced in the config above) wpa_passphrase "YOUR_SSID" SSID_PASSWORD | sudo tee /etc/wpa_supplicant/wpa_supplicant.conf Next, create a new executable script named iwconfig (you can name this script anything really, "iwconfig-default-ssid", perhaps?--I just made it short for the example): sudo touch /etc/network/if-up.d/iwconfig && sudo chmod 700 /etc/network/if-up.d/iwconfig && sudo ln -s /etc/network/if-up.d/iwconfig /etc/network/if-pre-up.d/iwconfig Now edit /etc/network/if-up.d/iwconfig and add the SSID you want Ubuntu Server to connect to on startup: #!/bin/sh iwconfig wlan0 essid "YOUR_DEFAULT_SSID" mode managed Now bring ifdown (if you haven't already), then ifup, and you should be golden now and when you reboot (as long as you're near your SSID.) If you're out in public with your laptop with this config, you'll have to use: iwlist wlan0 scan, then sudo iwconfig essid "PUBLIC_ESSID" mode managed to connect with anything (and/or make a unique script for each place(s) you visit--just don't put any of these scripts under the 'if-up.rc.d' folder. /etc/network/interfaces can also handle location alias, so check the man/forums for help on this.) Or you can try your luck with the CLI frontend for wicd when roaming about town: sudo apt-get install wicd-curses
{ "pile_set_name": "StackExchange" }
Q: Parse Python's serialized object in Perl I need to make my Perl code read some Python's serialized object for later processing. I came with parser based on Parse::MGC, but it's slow. May be I did it wrong or may be someone knows better way to convert Python's serialized object in some sort of Perl structure? Here is my Parse code: package Room::HandParser; use base qw( Parser::MGC ); my @poker_cards_string = ( '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh', 'Qh', 'Kh', 'Ah', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Td', 'Jd', 'Qd', 'Kd', 'Ax', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc', 'Qc', 'Kc', 'Ac', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Ts', 'Js', 'Qs', 'Ks', 'As' ); sub parse_declaration { my $self = shift; [ $self->any_of( sub { $self->token_int }, sub { $self->token_string }, ), $self->expect(":"), $self->parse, ] } sub parse_hash { my $self = shift; my %ret; $self->list_of(",", sub { my $res = $self->parse_declaration; $ret{$res->[0]} = $res->[2]; }); return \%ret; } sub parse_cards { my $self = shift; my $card = $self->token_int; return $poker_cards_string[$card & 0x3F]; } sub parse { my $self = shift; $self->any_of( sub { $self->scope_of( "[", sub { $self->list_of(",", \&parse) }, "]" ) }, sub { $self->scope_of( "(", sub { $self->list_of(",", \&parse) }, ")" ) }, sub { $self->scope_of( "{", sub { $self->parse_hash }, "}" ) }, sub { $self->scope_of( "PokerCards([", sub { $self->list_of(",", \&parse_cards) }, "])" ) }, sub { $self->token_float }, sub { $self->token_int }, sub { $self->token_string }, sub { $self->token_kw( qw(None True False) ) }, ); } 1; Here is example of serialized Python object I need to parse: [('game', 0, 195, 0, 0.0, 'holdem', '100-200-no-limit', [50312, 50313, 50314, 50315, 50316, 50317, 2], 0, {2: 1000000, 50312: 200000, 50313: 200000, 50314: 200000, 50315: 200000, 50316: 200000, 50317: 200000}), ('position', 1), ('blind', 50313, 10000, 0), ('position', 2), ('blind', 50314, 20000, 0), ('position', -1), ('round', 'pre-flop', PokerCards([]), {2: PokerCards([226, 208]), 50312: PokerCards([223, 206]), 50313: PokerCards([221, 233]), 50314: PokerCards([222, 211]), 50315: PokerCards([235, 216]), 50316: PokerCards([209, 236]), 50317: PokerCards([237, 243])}), ('position', 3), ('call', 50315, 20000), ('position', 4), ('call', 50316, 20000), ('position', 5), ('call', 50317, 20000), ('position', 6), ('call', 2, 20000), ('position', 0), ('fold', 50312), ('position', 1), ('call', 50313, 10000), ('position', 2), ('check', 50314), ('position', -1), ('round', 'flop', PokerCards([7, 21, 46]), {2: PokerCards([226, 208]), 50313: PokerCards([221, 233]), 50314: PokerCards([222, 211]), 50315: PokerCards([235, 216]), 50316: PokerCards([209, 236]), 50317: PokerCards([237, 243])}), ('position', 1), ('check', 50313), ('position', 2), ('check', 50314), ('position', 3), ('check', 50315), ('position', 4), ('check', 50316), ('position', 5), ('check', 50317), ('position', 6), ('check', 2), ('position', -1), ('round', 'turn', PokerCards([7, 21, 46, 38]), None), ('position', 1), ('check', 50313), ('position', 2), ('check', 50314), ('position', 3), ('check', 50315), ('position', 4), ('check', 50316), ('position', 5), ('check', 50317), ('position', 6), ('check', 2), ('position', -1), ('round', 'river', PokerCards([7, 21, 46, 38, 20]), None), ('position', 1), ('check', 50313), ('position', 2), ('check', 50314), ('position', 3), ('check', 50315), ('position', 4), ('check', 50316), ('position', 5), ('check', 50317), ('position', 6), ('check', 2), ('position', -1), ('showdown', None, {2: PokerCards([226, 208]), 50313: PokerCards([29, 41]), 50314: PokerCards([222, 211]), 50315: PokerCards([43, 24]), 50316: PokerCards([209, 236]), 50317: PokerCards([45, 51])}), ('end', [50317], [{'serial2delta': {2: -20000, 50313: -20000, 50314: -20000, 50315: -20000, 50316: -20000, 50317: 100000}, 'player_list': [50312, 50313, 50314, 50315, 50316, 50317, 2], 'serial2rake': {50317: 0}, 'serial2share': {50317: 120000}, 'pot': 120000, 'serial2best': {2: {'hi': [101154816, ['FlHouse', 46, 20, 7, 34, 21]]}, 50313: {'hi': [50841600, ['Trips', 46, 20, 7, 38, 21]]}, 50314: {'hi': [50841600, ['Trips', 46, 20, 7, 38, 21]]}, 50315: {'hi': [50842368, ['Trips', 46, 20, 7, 38, 24]]}, 50316: {'hi': [50841600, ['Trips', 46, 20, 7, 38, 21]]}, 50317: {'hi': [101171200, ['FlHouse', 46, 20, 7, 51, 38]]}}, 'type': 'game_state', 'side_pots': {'building': 0, 'pots': [[120000, 120000]], 'last_round': 3, 'contributions': {0: {0: {2: 20000, 50313: 20000, 50314: 20000, 50315: 20000, 50316: 20000, 50317: 20000}}, 1: {}, 2: {}, 'total': {2: 20000, 50313: 20000, 50314: 20000, 50315: 20000, 50316: 20000, 50317: 20000}, 3: {}}}}, {'serials': [50313, 50314, 50315, 50316, 50317, 2], 'pot': 120000, 'hi': [50317], 'chips_left': 0, 'type': 'resolve', 'serial2share': {50317: 120000}}])] For such structure it takes several seconds and 100% CPU to parse this object which is not acceptable in my case. EDIT: here I am NOT looking for workaround like writing python script for eval'ing this strucutre and output it JSON, or rewrite original Python app with added functions to store data as JSON. I am looking into parsing this data with Perl with reasonable performance, since this format is pretty close to JSON and it should be possible to parse it in similar time. A: How about you use a different format? JSON for example is fairly easy to parse, and there are implementations in Perl that should work out-of-the box. Python has JSON serialization and deserialization built into it, so you won't have to reinvent any wheels there either. A: If anyone interested: I end up with few regexps which transform this string into JSON (since they are so close-looking) and then parsing it with JSON::XS. https://github.com/hippich/Bitcoin-Poker-Room/commit/2f0e089908d3fa71dc16021ac6a24807c46529ad#diff-1 __parse_hands() subroutine.
{ "pile_set_name": "StackExchange" }
Q: Unable to produce variable output of type string in multi-lines in PHP I don't know the correct wording for this issue I am having. I have a object returned from the database like below: $pProvisioningFileData->m_fileContent = # Placeholders identified by '${}' will be replaced during the provisioning # process, only supported placeholders will be processed. Dcm.SerialNumber = ${unit.serial_number} Dcm.MacAddress = ${unit.mac_address} Dcm.MinSeverity = "Warning" Cert.TransferHttpsCipherSuite = "CS1" Cert.TransferHttpsTlsVersion = "TLSv1" Cert.MinSeverity = "Warning"; The curly brackets are placeholders, the problem I am facing is that when I try output all the content using either echo or print_r, all the content prints in one line however I want to display the content in the same sequence as above. I tried using var_dump but it also gives some extra info like length and type of variable which I don't want. So is there a simple way of doing this without using an array? A: If you are outputting to browser then wrapping your var_dump in html <pre> tags is quick solution. If you outputting to console then I advise you to install some advanced debuging software. Xdebug comes to mind.
{ "pile_set_name": "StackExchange" }
Q: Well ordering of $\mathbb{N}$ with weak induction In my Algebra course the well-ordering property of $\mathbb{N}$ has been proven just by standard ("weak") induction, but I can't understand the proof given by the lecturer. The proof proceeds as follows: let $S\subset \mathbb{N}$ a set with no minimum, we show that $S=\emptyset$. The claim is that if $S$ has no minimum and $ t \in \mathbb{N}$, then $S \cap t=\emptyset$; from this fact the conclusion would easily follow, since this proves that no $n \in \mathbb{N}$ can belong to $S$. Now we suppose by contradiction that $S \cap t \ne \emptyset$; since $S \cap t \subset t$, $S \cap t$ is finite, since $S \cap t \subset \mathbb{N}$, $S \cap t$ is totally ordered. Hence there is $m=\min S \cap t$. We claim that this $m$ is in fact the minimum of the whole $S$, which is a contradiction. We have to prove that $m \le x$ for every $x \in S$. If $x \in S \cap t$, this is obvious. If $x \notin S \cap t$, then $x \notin t$, hence either $x=t$ or $t \in x$ (by trichotomy property). Here begins the part I can't understand: the lecturer writes: " In this case [which one?] we have $m \in t$, so that $m \subsetneq t$, but also $ t \subsetneq x \implies m \subsetneq x \implies m <x$". Can someone explain this last passage? A: It seems to refer to the case where $t\in x$. But both cases can be treated the same way: in either case you have $t\subseteq x$ so since $m\in t$ you have $m\in x$, so $m<x$ by definition.
{ "pile_set_name": "StackExchange" }
Q: Texto sin traducción en el perfil Al ver el perfil de un usuario cualquiera que no tiene respuestas a ninguna pregunta se ve el texto sin traducir "answered" y debería cambiarse a "respondido": En todo caso debería quedar: Este usuario no ha respondido ninguna pregunta. También ocurre lo mismo cuando se observa las preguntas del usuario: Aunque en este caso creo que se debería cambiar a algo que tenga más sentido ya que: Este usuario no tiene preguntas ninguna pregunta. Es incorrecto, de acuerdo a los enlaces a los que apunta cada uno lo ideal sería: Este usuario no ha preguntado ninguna pregunta. Y este último suena como al Chavo del 8. Creo que podría quedar así: Este usuario no ha preguntado aún. ¿Qué opinan? Actualización El perfil que he visitado para la parte de las preguntas es el de Andres Vilca A: ¡Ya está solucionado!
{ "pile_set_name": "StackExchange" }
Q: Populate HTML listbox using javascript function on page load I have a HTML Listbox and I need to add values to it on the page load. I have tried to call a JS function on page load event on both <body> tag and <select> tag but it does not execute the the function. <body onload='popListbox(<%=session.getAttribute("objNames")%>)'> <select id="lstObjects" onload='popListbox(<%=session.getAttribute("objNames")%>)'> If I try onclick it executes fine but not in onload event. Can someone help me with this.? UPDATE: my JS function function popListbox(objList){ var select = document.getElementById("lstObjects"); var objects = objList; var objects_array = []; for(var i in objects) { if(objects.hasOwnProperty(i) && !isNaN(+i)) { objects_array[+i] = objects[i]; } } for(var i = 0; i < objects_array.length; i++) { var opt = objects_array[i]; var el = document.createElement("option"); el.textContent = opt; el.value = opt; select.appendChild(el); } } A: try document.ready $( document ).ready(function() { //your code here });
{ "pile_set_name": "StackExchange" }
Q: Creating loops to read an ascii (.txt) file by piping it into a program and then outputting it into another file I am trying to essentially pipe a .txt ascii file into a program. My program needs to be able read the lines upon lines of ascii code and then output what it reads into a file. At which point i will compare the file I just filled with ascii to another file which has the correct output of the file already using the diff command. I am really new to C (it's my third week, with once a week lab instruction time with my prof), and I feel I'm quite close to figuring this out, but i feel the nesting of my loops is off. The three files I'm dealing with: encoded_picture.txt decoded_picture.txt ascii_cat.txt eg (encoded_picture.txt) Using less 29: 1. 1 4. 36: 1. 1 4. 3 2. 1: 1. 5 1. 1: 1. 8: -1? 30: 2. 39: 1. 1 3. 3 4. 7 1. 6: 2. 1: -1? 12: 1. 58: 6. 2 2. 9 1. 6: 2. 1: -1? 12: 2. 57: 1. 1 3. 1 3. 11 1. 8: -1? 12: 3 1. 55: 2. 2 1. 1 2. 12 1. 8: -1? 12: 1. 3 1. 53: 1. 1 1. 1 4. 13 1. 8: -1? 12: 1. 5 51: 8. 15 8: -1? 13: 1. 1 2. 2 1. 49: 7. 5 2. 9 8: -1? 14: 2 2. 2 1. 48: 6. 6 3. 2 1. 5 8: -1? 14: 1. 2 2. 3 1. 45: 6. 8 3. 1 2. 4 8: -1? 15: 1. 1 3. 3 1. 44: 5. 7 2. 1 6. 2 1. 8: -1? 16: 1 4. 4 1. 41: 5. 5 6. 1 5. 2 1. 8: -1? 16: 6. 5 1. 38: 6. 3 8. 1 5. 2 1. 8: -1? 17: 6. 5 2. 35: 6. 3 9. 1 5. 2 1. 8: -1? 17: 7. 6 2. 32: 6. 5 8. 1 5. 2 1. 8: -1? 18: 7. 7 1. 30: 6. 5 7. 1: 1. 1 3. 1 1. 2 1. 8: -1? eg. (decoded_picture.txt) ::::::::::::::::::::::::::::::.. .....:::::::::::::::::::::::::::::::::::::.. ..... ...::.. ..::..::::::::: :::::::::::::::::::::::::::::::...::::::::::::::::::::::::::::::::::::::::.. .... ..... ..:::::::...:: :::::::::::::..:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::....... ... ..:::::::...:: :::::::::::::...::::::::::::::::::::::::::::::::::::::::::::::::::::::::::.. .... .... ..::::::::: ::::::::::::: ..::::::::::::::::::::::::::::::::::::::::::::::::::::::::... .. ... ..::::::::: :::::::::::::.. ..::::::::::::::::::::::::::::::::::::::::::::::::::::::.. .. ..... ..::::::::: :::::::::::::.. ::::::::::::::::::::::::::::::::::::::::::::::::::::......... ::::::::: ::::::::::::::.. ... ..::::::::::::::::::::::::::::::::::::::::::::::::::........ ... ::::::::: ::::::::::::::: ... ..:::::::::::::::::::::::::::::::::::::::::::::::::....... .... .. ::::::::: :::::::::::::::.. ... ..::::::::::::::::::::::::::::::::::::::::::::::....... .... ... ::::::::: ::::::::::::::::.. .... ..:::::::::::::::::::::::::::::::::::::::::::::...... ... ....... ..::::::::: ::::::::::::::::: ..... ..::::::::::::::::::::::::::::::::::::::::::...... ....... ...... ..::::::::: :::::::::::::::::....... ..:::::::::::::::::::::::::::::::::::::::....... ......... ...... ..::::::::: ::::::::::::::::::....... ...::::::::::::::::::::::::::::::::::::....... .......... ...... ..::::::::: ::::::::::::::::::........ ...:::::::::::::::::::::::::::::::::....... ......... ...... ..::::::::: :::::::::::::::::::........ ..:::::::::::::::::::::::::::::::....... ........::.. .... .. ..::::::::: :::::::::::::::::::.......... ..::::::::::::oooo:::::::ooo:::ooo:::...... .........::: .. .. ..::::::::: ::::::::::::::::::::......... ...::::::oooooOO&&OOooooOOooOOOOOOOOoo::..... ..........::.. .. ..::::::::: ::::::::::::::::::::..::::..::..... ...::::ooOO&&OOO&&&&OOOO&&&&&&&OOOOOooo::.. ...........::.. ..::..::..:::::: :::::::::::::::::::::::::::..::.... ....::oooOO&&&&&&&&&&&&&&&&OOOOooo::oo:: ....:::........ ..:::::..::::: :::::::::::::::::::::::::::::::... ::::oooOO&&&&OO&&&&&&&&&&&&OOOOOoo::... ...:::::::..... ..:::::::..::: :::::::::::::::::::::::::::::::::....::oooOOOO&&&&OO&&&&&&OO&&&&&OO&&OOOOooo::::.. ........::::.... ..::::::::..:: ::::::::::::::::::::::::::oooo::::::ooooOOOO&&&&OOOOO&&&&&OO&&&&OOO&&&OOOoooooo:::.. .... .......:::... ::..::::::..::.. :::::::::::::::::::::::ooo:::::::::oooOOOOOO&&&&OOOOO&&&&&OO&&&&OOOO&&OOOOOoooo:::..:::.. ....::... .. ..:::...:::::..:: :::::::::::::::::::::ooo::::::::ooooOOoooOOOO&&&&&OOOOO&&&&&&&OO&&OOooOOOOOOOOOooo::ooo..... ... ..::.....:::.... :::::::::::::::::::::ooo::::::oo::ooOOOOOOOO&&OO&&OOOOoooOO&&&&OO&&OOO&&OOooOOOOOOOOOooooo:::::........... .....::....... :::::::::::::::::::::oo::..::...::ooOOOOO&&&OO&&OO&&OO&&OOOOOOO&&&&OOOOOOOoooOOOOOOOOOOOoo::ooo::::... ..... ..::........... :::::::::::::::::::::::....::oooOO&&&&&&&&OO&&OOOOOOoooOOOOOooOOOOOOooooOOOOOOOOOOoooooo::..... .. ..::......:::.... ::::::::::::::::::::::...:::ooOOOO&&&&&&OOOOOOOOOOoooOOOOOooooOOoooooooOOOOOOOOOOoooooo:::.... .. ....::..:::::::: ::::::::::::::::::::::....::OOO&&&&&&&&OOOOOOOOOoooo&&OOOoooooooooooooooOOooooOOOOoooooo::.... .... ...::....:::::::: :::::::::::::::::::::... ..::oo&&&&&&&OOOOOooOOOoooooooOOOOooooooo:::oooooooooooOOOOooOOoooo:::::.. ..::::...:::::::: ::::::::::::::::::::::....::ooOO&&&&OOOOOOOooOOooooooooooOOoo::oo:::oo:::ooooooooooooOOoooOOoooooooo.. ..::::::..::::::: ::::::::::::::::::::::....::OOO&&&OOOOOOooOOoooo::ooooo::ooOOoooo:::::::::oooo::ooooooOOOOOOooooooo.. ..:::::...::::::: ::::::::::::::::::::::.. ...ooOOOOOOOoooooo::::oooo::..ooOOoooo::..:::::::::::oooooooOOOOOOOoooo::.. :::::::..::::::: :::::::::::::::::::::::...::OOOOooooooooo:::..::ooo:::..::OOooo:::..:::::...:::::oooooooooOOooooooo::.. ..:::::::::::::.. :::::::::::::::::::::::::ooOOOoooooo:::ooo::...::oo::::..ooOOooo::....:::....::::::::ooooooooooooo:::.. ..::::::::.....::: ::::::::::::::::::::::::oooooooooo:::::....:::::...ooooo.....::::....::::..:::oooooooooooooo::.. ..::::::::::::oo::: ::::::::::::::::::::::::oooo:::ooooo::::.....:::::..::ooooOO::........ ...::...:::ooooooooooooo::.. ..::::::::ooo::oo:::: :::::::::::::::::::::::oooo:::::::::::.. :::::..::OO:::OO::........ .....:::::oooooooooooo:: ..::::::::oo::::::oo ::::::::::::::::::::::oooo::::::::::::.. ....::...OOoo:::OOoo..::.... .....:::::::::oooooooo::.. :::::::::oo::::::oo :::::::::::::::::::ooooooo:::..::::::..::..........::OOoo:::OOO::..... ......:::::::::::oooooo::.. :::..:::...::::::...:: :::::::::::oo::::::::oooooo::....::..::oo:: ..........ooOOooooOOO:: ... .....:::::::..::::ooooooo::.. ..::..:::...::::::.. .. ::::::::::oooo::::::oooOOOOoo....:::..::oo.. :::......::OOOoooOO&&OO:: ....:::::.....::oooooooo::.. ...:::...:::::..... ::::::::ooooo:::::::ooOOOOoo::....:::..ooo.. ::&&oo.....::OOOooOO&&&OO:: ........ ...:::ooooooo::.. ....::...::..::::::.. ::::::ooooooo::::::ooOOOOOoo::....::...:::.. ::&&oo.....::OO&&OO&&&&OO.. .. ..oo:: ... ..::::oooooo::......::...:::ooo::::.. ::::::ooooo:::::::OOOOOOOoo::::..::: ... ..oo&&:::....::OO&&&&&OOoo.. ... ..::: .... ..::::ooooo:::::...ooo::ooo:::..... :::::ooooo:::::::ooOOOOOOOoo:::::::..... ::&&OO..::.. ..::OO&&&&OOoo::.. .... ..::...........:::ooooooo::oo:::ooo:::........ ::::ooooo:::::::ooOOOOOOOOOoo:::..:::.. ....::oo.......OO&&&&&OOoo::.. ..::.. .............::::oooooooooo::........... :::oooooooooo::oooOOOOOOOOOoo::........ ......::...::oo&&&&&&OOO::.. ....::: ... ...........:::ooooooooo::...... ..... :::oooOOooooo::::ooOOOOOOOOOOoo::......:::...:::...::...ooOO&&&&&&OOOoo::.. ....::::.. ... ...........:::::ooooooo:::...... ...... ::oooooo::::...::OOOOOOOOOOOoo::......:::::........ooOO&&&&OOOOOoo::.. .....::..... ..........::::::oooooo:::..... ....... ESC At this point in the command line i would compile and then: ./a.out < encoded_picture.txt > decoded_picture.txt And then to compare to see if it work: diff decoded_picture.txt ascii_cat.txt At this point i know that if diff displays an output, I've done it wrong. Any help would be appreciated (actual program part3_file.c). int length; int i; // loop until the end of input sentinel is seen while (1) { // get the first element in the line scanf("%d%c", &length, &character); if(length == -1) { break; } else { // is it the sentinel? if so, then break out of the loop // reconstruct a line, as per part 2 while ( length != -1 ) { for( i = 0; i<= length; i++) { printf("%c", character); } scanf("%d%c", &length, &character); } printf("\n"); } } return 0; A: If I understand your question and you want to read encoded_picture.txt from stdin and then based on each encoded pair 'lc' (that's l as in length and c as in character) output l number of characters c to stdout until length is -1 where a '\n' is output, then you are on the right track. However your loop logic is a bit strange. You can use your scanf format string "%d%c". However, you always, always want to check the return of scanf to validate the expected number of conversions took place. For example, to read each pair until end of file is encountered you can do something like the following: while (scanf ("%d%c", &l, &c) == 2) { Your next task, to repeatedly output the specified number of characters, you can simply do: for (int i = 0; i < l; i++) printf ("%c", c); (if l == -1 the loop will not execute anyway, also note: the loop is i < l for l characters, where i <= l would result in l+1 chars) Your final task is to control the output of the newline in the event l == -1, if (l == -1) putchar ('\n'); Putting it together, you could do something like: #include <stdio.h> int main (void) { int l; char c; while (scanf ("%d%c", &l, &c) == 2) { for (int i = 0; i < l; i++) printf ("%c", c); if (l == -1) putchar ('\n'); } return 0; } Example Use/Output Based on the encoded_picture.txt text you provided, that would result in something like the following (that looks like the start of Ratchet's ears): $ ./bin/decodpic <dat/encpic.txt :::::::::::::::::::::::::::::. ....::::::::::::::::::::::::::::::::::::. .... ..:. .:.:::::::: ::::::::::::::::::::::::::::::..:::::::::::::::::::::::::::::::::::::::. ... .... .::::::..: ::::::::::::.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::...... .. .::::::..: ::::::::::::..:::::::::::::::::::::::::::::::::::::::::::::::::::::::::. ... ... .:::::::: :::::::::::: .:::::::::::::::::::::::::::::::::::::::::::::::::::::::.. . .. .:::::::: ::::::::::::. .:::::::::::::::::::::::::::::::::::::::::::::::::::::. . .... .:::::::: ::::::::::::. :::::::::::::::::::::::::::::::::::::::::::::::::::........ :::::::: :::::::::::::. .. .:::::::::::::::::::::::::::::::::::::::::::::::::....... .. :::::::: :::::::::::::: .. .::::::::::::::::::::::::::::::::::::::::::::::::...... ... . :::::::: ::::::::::::::. .. .:::::::::::::::::::::::::::::::::::::::::::::...... ... .. :::::::: :::::::::::::::. ... .::::::::::::::::::::::::::::::::::::::::::::..... .. ...... .:::::::: :::::::::::::::: .... .:::::::::::::::::::::::::::::::::::::::::..... ...... ..... .:::::::: ::::::::::::::::...... .::::::::::::::::::::::::::::::::::::::...... ........ ..... .:::::::: :::::::::::::::::...... ..:::::::::::::::::::::::::::::::::::...... ......... ..... .:::::::: :::::::::::::::::....... ..::::::::::::::::::::::::::::::::...... ........ ..... .:::::::: ::::::::::::::::::....... .::::::::::::::::::::::::::::::...... .......:. ... . .:::::::: Look things over and let me know if I misunderstood or if you have questions. Writing Output WITHOUT a final POSIX line-end While this is improper, the decoded_picture.txt does not contain a POSIX line-end. If you run the first version of my code, and then use diff -uNb decoded_picture.txt the_output.txt you find the only difference is my code properly includes a POSIX line-end (e.g. '\n') after the final line written. You can dupe the code into not writing a POSIX line-end by setting a toggle to only write the newline if characters were previously written in that line. That effectively prevent a final newline. You can do that as follows: #include <stdio.h> int main (void) { int l, flag = 1; char c; while (scanf ("%d%c", &l, &c) == 2) { for (int i = 0; i < l; i++) printf ("%c", c); if (l == -1) { if (flag) { putchar ('\n'); flag = 0; } } else flag = 1; } return 0; } Result Then testing the code and output, you find the following: $ gcc -Wall -Wextra -pedantic -std=gnu11 -Ofast -o bin/decodpic2 decodpic2.c $ ./bin/decodpic2 <dat/encoded_picture.txt > dat/decode2.txt $ diff -uNb dat/decoded_picture.txt dat/decode2.txt (no output, the files match :) While there is educational use in forcing a final write without a POSIX line-end -- do not do this is real life :)
{ "pile_set_name": "StackExchange" }
Q: Print html with images (every image on separate page) I have an HTML with images: <img id="1" .../> <img id="2" .../> <img id="3" .../> <img id="4" .../> While printing, I want every image to be on a separate page (according to the print size). Now I get the images cut off in the middle. Is there any way to fix it? A: You can try the following.. <html> <head> <style type="text/css"> @media print { p.pageBreak {page-break-after: always;} } </style> </head> <body> <p class="pageBreak"> <img id="1" src="http://placehold.it/250x250"> </p> <p class="pageBreak"> <img id="2" src="http://placehold.it/250x250"> </p> <p class="pageBreak"> <img id="3" src="http://placehold.it/250x250"> </p> <p class=""> <img id="4" src="http://placehold.it/250x250"> </p> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Unable to block room using Google calendar Api This is my java code using this code I am trying to create event with room (room is added using resource Google Calendar API) event created success fully with room A. However when I check in Google Calendar and try see available room in that A room is available. I would expect it should not display or it should show with strike can any one please tell me the solution for this where am doing I am mistake is there permission issue please suggest me. public class CalendarQuickstart { private static final String APPLICATION_NAME = "API Quickstart"; private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/calendar-java-quickstart"); private static FileDataStoreFactory DATA_STORE_FACTORY; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static HttpTransport HTTP_TRANSPORT; private static final List < String > SCOPES = Arrays.asList(CalendarScopes.CALENDAR); static { try { HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } public static Credential authorize() throws IOException { // Load client secrets. /*InputStream in = CalendarQuickstart.class.getResourceAsStream("/client_secret.json"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build(); Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath()); return credential;*/ Credential credential = GoogleCredential.fromStream(CalendarQuickstart.class.getResourceAsStream("/client_secret.json")) .createScoped(SCOPES); return credential; } public static com.google.api.services.calendar.Calendar getCalendarService() throws IOException { Credential credential = authorize(); return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME).build(); } public static void createEvent() throws IOException { Event event = new Event().setSummary("Google I/O 2015") .setDescription("A chance to hear more about Google's developer products."); DateTime startDateTime = new DateTime("2017-02-27T22:00:00+05:30"); EventDateTime start = new EventDateTime().setDateTime(startDateTime).setTimeZone("Asia/Kolkata"); event.setStart(start); DateTime endDateTime = new DateTime("2017-02-27T23:00:00+05:30"); EventDateTime end = new EventDateTime().setDateTime(endDateTime).setTimeZone("Asia/Kolkata"); event.setEnd(end); EventAttendee[] attendees = new EventAttendee[] { new EventAttendee().setEmail("[email protected]"), new EventAttendee().setEmail("[email protected]"), new EventAttendee(). setEmail("company.com_35353134363037362d333130@resource.calendar.google.com").setResponseStatus("accepted") }; event.setAttendees(Arrays.asList(attendees)); EventReminder[] reminderOverrides = new EventReminder[] { new EventReminder().setMethod("email").setMinutes(24 * 60), new EventReminder().setMethod("popup").setMinutes(10), }; Event.Reminders reminders = new Event.Reminders().setUseDefault(false) .setOverrides(Arrays.asList(reminderOverrides)); event.setReminders(reminders); String calendarId = "primary"; event = getCalendarService().events().insert(calendarId, event).execute(); System.out.printf("Event created: %s\n", event.getId()); } public static void updateEvent() throws IOException { Event event = getCalendarService().events().get("primary", "3k90eohao76bk3vlgs8k5is6h0").execute(); event.setSummary("Appointment at Somewhere"); // Update the event Event updatedEvent = getCalendarService().events().update("primary", event.getId(), event).execute(); System.out.println(updatedEvent.getUpdated()); } public static void main(String[] args) throws IOException { com.google.api.services.calendar.Calendar service = getCalendarService(); DateTime now = new DateTime(System.currentTimeMillis()); Events events = service.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime") .setSingleEvents(true).execute(); List < Event > items = events.getItems(); if (items.size() == 0) { System.out.println("No upcoming events found."); } else { System.out.println("\nUpcoming events"); for (Event event: items) { DateTime start = event.getStart().getDateTime(); if (start == null) { start = event.getStart().getDate(); } System.out.printf("%s (%s)\n", event.getSummary(), start); } } createEvent(); } A: Hi All after long search from google i found solution . Steps to create event google event. Step1: Set following scopes to authorise api. https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar Step2: While authorizing asks for permission to manage and view calendar , uses has to allow it . and which will generated authorization code. Step3: Create access_token by generated authorization code Step 4: Pass generated access_token to craete google event. Java code to create google event public static com.google.api.services.calendar.Calendar getCalendarService() { GoogleCredential credential = new GoogleCredential().setAccessToken(access_token); return new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build(); } these steps Work for me block room while creating Event using Google calendar api. i have tried with another way using service account in that case we are able to create event but not able to block room .
{ "pile_set_name": "StackExchange" }
Q: Is it possible to retrieve the HTTP Status Response Code in an MVC View? Is it possible to retrieve the HTTP Status Response Code in an ASP.net MVC View? For instance, I can get the server name with @Environment.MachineName. Is there a similar, easy way to get the http status response code for the current page? If not, what about using Javascript? If not, is there any way to do it without issuing a new request? I want to grab this information off of every page view, and I'd rather not double the hits just to do it. Thanks A: Response.StatusCode is on the WebPageRenderingBase So you can write this on any view: @{ Response.StatusCode } http://msdn.microsoft.com/en-us/library/system.web.webpages.webpagerenderingbase(v=vs.111).aspx A: Use Context.Response.StatusCode
{ "pile_set_name": "StackExchange" }
Q: Publish contenttype after activating feature (Office 365) I've created a Contenttype and some fields in a visual studio project. They are deployed when activating the "Content types"-feature. But here's the problem: I want them to be deployed to the Content Type HUB (in Office 365). Deploying itself isn't a problem but I also want the content-types to be published, so I can use them in my other sitecollections. I guess I'll need to do this with the client object model with a feature receiver? Is there anyone who has an example how to do this? (Or if there's a better way to do this, please say so...) A: I don't think client side object model is a good idea. I think you need to publish them using code written in a feature receiver. Please see the link below... http://blogs.msdn.com/b/chaks/archive/2011/09/04/content-type-hub-publishing-and-subscribing-to-content-types-programmatically-c-code.aspx
{ "pile_set_name": "StackExchange" }
Q: What is the impact on health of travelling internationally for 50-70% of the time? I was offered a job as worldwide head of business development for X. I was offered twice my current salary, plus a bonus. It's a very attractive offer, but I will have to travel 50-70% internationally (US, EMEA and APAC). I will not have a "machine behind me", as the company has very few people with a background in X, but will have to work together with each country's general manager and their teams to develop the business. I am not afraid of travelling a lot, but I am wondering about the impact on health. So the question is: what is the impact on physical and mental health of travelling internationally 50-70% of the time? A: I spent a few years in my career doing a lot of business travel. It was hard hard work. After a few weeks I definitely got "road burn." It made me irritable and, honestly, my relationships with family and co-workers suffered. Here are some things I learned about staying healthy and happy. Recognize that it's hard to stay healthy / happy when traveling all the time, and cut yourself some breaks. Pace yourself. Don't try to do too much useful work after an overnight flight. Don't work extra hours just because you're away from home. Develop some personal strategies for coping with jet lag. Use hotels with fitness rooms. Or, just walk up and down the stairs ten times. Try to avoid a Friday night overnight flight as the start to your weekend too often. Be careful with restaurant food and drink. Most of it is designed for feasting or celebration, not for daily sustenance. If you travel to one place frequently, it's smart to tell the waitress / waiter where you eat you're on the road a lot and ask for help choosing the healthiest food. Inflight wi-fi is a curse. Pretend it doesn't exist so flight time can be downtime. Sanitation: wash your hands a lot to avoid infection. A small bottle of hand-sanitizer is helpful. I also found that paying for access to an airline's first class lounge ("Admirals Club", "Gold Member Club," whatever) was worth a lot in saving health and sanity. The desk clerks there have time to help with various issues, and some of the seating is suitable for sleeping if you need to. Get your employer to pay for it if you can, but if not, pay for it yourself. A: That depends on the type of travel, the work you are doing, how many timezones you are serving, your relationship status, your personality, your talents, the frequency (not percentage) and your aptitude for this. So i expect the impact to be dramatically different between you have no permanent health conditions, are married for 30 years with grown up kids and while you have 50%-70% travel, the travel happens planned every week (e.g. from US westcoast to Canada or east China) or for a few months at a piece, and it's a stable industry, and you know the foods in the region. You are freshly engaged, your fiance is pregant and you can not plan/emergency departures with 12h notice and an unknown number of days, hav a lot of allergies and the job is physical and you don't have access to healthy food. So the reality is probably somewhere between these scenarios, and without further details it's difficult to tell, but be prepared that in any case you will loose some friendships or personal relationships. A: There are a lot of good answers and comments already. I won't quote studies since the others did that already. Instead I will bring up my own experience. I spent several years working 4-5 days a week in various European cities. I understand you will be spending less time travelling, but your distances will be bigger: Most people do experience negative consequences of travelling so much. Among my colleagues we all agreed that the beginning is easy, but after 3-4 months of regular travels at the latest you are just tired. I was so tired I was just able to sleep on the weekends. Stress is actually an incredible important aspect. When you travel, there are plenty of things you can't control. Flights get cancel and you normally learn about it in the very last moment. You miss your connections. There are problems with your booking. Your hotel doesn't want to issue you an invoice for whatever reason. Especially if you don't have a machine behind you to help you with the organization, you will be spending a lot of time and energy for that. Long-term stress mixed with lack of sleep isn't really conductive to a good health. The fact you will lose many of your personal connections will contribute to stress. Your support networks will decompose. Other answers mentioned the lack of healthy food, which is also a big issue. Hygiene levels in hotels are frequently low, even in good four star - five star hotels. What does that mean? Personally one shower without bath slippers cost me months of painful dermatological problems. Don't even think about accepting the position if no good international insurance is offered. You can have problems with check-ups and doctor appointments. Even if you have a good international insurance, it can be complex to organize doctor appointments if your travels aren't planned much in advance unless the healthcare system in your country is excellent. I don't know anybody who travels so much for reasons different than money. If the money is great, accept the position and try to cope for a year or two. Maybe you will be one of the few who love it. If not, leave it.
{ "pile_set_name": "StackExchange" }
Q: using proxy in Angular CLI to redirect http post requests, not redirecting I want my requests sent from localhost to be passed to the remote server, I have no control of, by the use of proxy. So that http://localhost:8000/api/Lists/GetCarList would be resolved as https://other-site.ru/api/Lists/GetCarList But with my solution, the request is still sent as http://localhost:8000/api/Lists/GetCarList i am running my app with ng serve --proxy-config proxy.conf.json --port 8000 my proxy.conf.json file { "/coreapi/*": { "target": "https://other-site.ru", "secure": false, "pathRewrite": { "^/": "" }, "changeOrigin": true } } my request var headers = new Headers(); headers.append('Authorization', 'Bearer ' + this.oauthService.getAccessToken()); headers.append('Content-Type', 'application/json;charset=UTF-8'); let options = new RequestOptions({headers: headers}); return this.http.post('/coreapi/UserService/GetUserServersList', {}, options) .toPromise().then((response: Response)=>{ var resp = response; }, err =>{ console.log("err"); }) So, the question is how to fix this, so that relative requests to /coreapi/** be picked up at https://other-site.ru/coreapi/**? A: try this : "pathRewrite": {"^/coreapi" : "https://other-site.ru/coreapi"}
{ "pile_set_name": "StackExchange" }
Q: Bash commands not executed when through cron job - PHP I have a cron job running a PHP script every five minutes; the PHP script executes two bash commands at the end of the script. I know the script is running due to a log file it appends to. When I run the PHP script manually via the Ubuntu Gnome Terminal both bash commands execute flawlessly; however when the PHP script is triggered via cron, the two bash commands are not ran. Any ideas? $command = 'notify-send "' . count($infoleakPosts) . ' New Posts."'; `$command`; $command = 'firefox http://example.com'; `$command`; */1 * * * * php /home/andrew/grab.php USERNAME PASSWORD # JOB_ID_1 A: Generally your cron scripts are going to be run under a different user account, and probably have a different environment path set up. Try setting your command lines to use the full path to the command, ie. /path/to/notify-send "x New Posts". You can use which notify-send from your regular terminal to get the path to put into your script. You can also grab the output from your command to help debugging. Use of the backtick operator will return the output, so you can assign it to a variable and/or dump it. $output = `$command`; error_log($output);
{ "pile_set_name": "StackExchange" }
Q: How can I get data out of NSURLRequest config object I have an Angular web build inside an iOS app and want to POST requests up to the native layer with some JSON that I can use to build some native functionality. I am using the old UIWebView (because Angular) so am using an NSURLProtocol to intercept the request. This works and I can break at the point that the request comes in. The problem is that I can not see the JSON in the data property at this point because it is not the response. The request is still in the config object but I have no idea how to grab this. My angular code for creating the post is currently like this: var newdata = $.param({ json: JSON.stringify({ name: "Lee" }) }); $http.post(url, newdata) and in my NSURLProtocol class I am successfully intercepting this POST in this method but the HTTPBody property is nil: override class func canInitWithRequest(request:NSURLRequest) -> Bool { if (request.URL!.absoluteString as NSString).containsString("request_media_gallery") { if(request.HTTPBody != nil){ let data:NSData = request.HTTPBody! print(data) } return true } return request.URL?.host == "file" } If I debug this in chrome I get a 405 because of CORS but I can see that my request object does not have any data but does have a config object. Here's the console log from Chrome: A: By the time a URL request gets down to the protocol layer, IIRC, the URL Loading System sanitizes it in a lot of ways. In particular, if a request has an HTTPBody object associated with it, it basically does this: req.HTTPBodyStream = [NSInputStream inputStreamWithData:req.HTTPBody]; req.HTTPBody = nil; As a result, to get the data, you need to read from the HTTPBodyStream, regardless of whether the request was originally created with an NSData object or a body stream.
{ "pile_set_name": "StackExchange" }
Q: Unexpected text being rendered by Ember I have models // models/group export default DS.Model.extend({ parent: DS.belongsTo('parent'), items: DS.hasMany('item', {async: true}), quantity: Ember.computed.sum('[email protected]'), }); // models/item export default DS.Model.extend({ ... quantity: DS.attr('number') }); And in my template (with controller.model set to parent) I try to render {{#each group}} {{quantity}} {{/each}} and expect a list of numbers, but instead what's rendered is a list of text like <spa@model:item::ember1036:165> I'm guessing that the async promise is only resolved after rendering, but then why does it not update? A: I don't believe sum will pull properties from each item in a collection. I believe it has to be a collection of numbers. quantities: function(){ return this.get('items').getEach('quantity'); }.property('[email protected]'), quantity: Ember.computed.sum('quantities'),
{ "pile_set_name": "StackExchange" }
Q: iterate over a Json file and insert into db in Python {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}, {"groupId":"org.springframework","artifactId":"spring-beans","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-beans/5.1.2.RELEASE/5d513701a79c92f0549574f5170a05c4af7c893d/spring-beans-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-core","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.1.2.RELEASE/b9b00d4075c92761cfd4e527e0bdce1931b4f3dc/spring-core-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}, {"groupId":"org.springframework","artifactId":"spring-expression","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-expression/5.1.2.RELEASE/3c16b062785e4c101db6b754fcb34a77c1e912c/spring-expression-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-core","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.1.2.RELEASE/b9b00d4075c92761cfd4e527e0bdce1931b4f3dc/spring-core-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}, {"groupId":"org.springframework","artifactId":"spring-core","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.1.2.RELEASE/b9b00d4075c92761cfd4e527e0bdce1931b4f3dc/spring-core-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}, {"groupId":"org.springframework","artifactId":"spring-web","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/5.1.2.RELEASE/3ff2a93b072da42c3930225e3dceeabb0678eb0b/spring-web-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-beans","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-beans/5.1.2.RELEASE/5d513701a79c92f0549574f5170a05c4af7c893d/spring-beans-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-core","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.1.2.RELEASE/b9b00d4075c92761cfd4e527e0bdce1931b4f3dc/spring-core-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}, {"groupId":"org.springframework","artifactId":"spring-core","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.1.2.RELEASE/b9b00d4075c92761cfd4e527e0bdce1931b4f3dc/spring-core-5.1.2.RELEASE.jar","dependencies":[ {"groupId":"org.springframework","artifactId":"spring-jcl","version":"5.1.2.RELEASE","file":"/home/howie/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jcl/5.1.2.RELEASE/f0d7165b6cfb90356da4f25b14a6437fdef1ec8a/spring-jcl-5.1.2.RELEASE.jar","dependencies":[]}]}]}]}] output, error = process.communicate() data = json.loads(output.decode('UTF-8')) page = open("JSON/Java.json", "r") parsed = json.loads(page.read()) for v in parsed['groupId'].values(): if isinstance(v, dict): db_entry = {} db_entry['artifactId'] = v['artifactId'] db_entry['version'] = v['version'] db_entry['repo_id'] = repo_id dep_coll.insert_one(db_entry) else: raise ValueError("object is not dictionary") hi i am trying to import a json file on iterate over it so that certain values are inserted into a db. In this case i need artifactid, version insertred. The json file has a list so i would have multiple inserts. I think i am on the right track , any help would be greatly appreciated. At the moment this is the error i am getting for v in parsed['groupId'].values(): TypeError: list indices must be integers or slices, not str A: 'parsed' is a list and not a dict. It contains dicts. Each dict contains a field named 'groupId'. So your code should look like. Upload "JSON/Java.json" to a public location if the code below does not work for you. for entry in parsed: # entry is a dict - do something with it
{ "pile_set_name": "StackExchange" }
Q: how right use function in include file? Good day. We have 3 files: 1) index.php <?php require_once("functions.php"); $t= new getgunctions; $t->getgainTpl(); $t->controllerTpl(1); ?> 2) functions.php <?php class getgunctions{ ..... public function controllerTpl(){ $this->form(); } private function form(){ include "form.tpl"; } public function right(){ echo 'test'; } ..... } ?> 3) form.tpl <div><?php $this->right(); ?></div> but i get error: Using $this when not in object context... Tell me please how right use function right(); in form.tpl? A: check files on server. it was worked if you not error in function.php
{ "pile_set_name": "StackExchange" }
Q: max number of connected sockets vs. values of SO_SNDBUF and SO_RCVBUF I have more than 3 million file descriptors on a Linux machine, so I look how socket buffers size against RAM size would constrain the maximum number of simultaneous tcp connections that the machine can handle. If you had similar experience, please, advise. Thank you. A: It's not about RAM size, but rather about virtual memory size. Clearly you cannot have buffers exceeding the total virtual memory available on the computer. That said, if you are finding that things start to break when you have three million sockets open, you may be better off focusing your efforts on reducing the number of sockets if you can, rather than reducing the buffer sizes--three million sockets is an awful lot, and may suggest some other issues with your architecture.
{ "pile_set_name": "StackExchange" }
Q: In NetBeans, Mojarra 2.2 outputStyleSheet doesn't have media attribute I'm using NetBeans 8.0.2 and Mojarra 2.2 where according to the docs there's a media attribute and this is not the case, I get the following message: The attribute media is not defined in the component outputStyleSheet So the problem I know is with NetBeans 8.0.2. When I launch the application, It runs properly so does anyone know why NetBeans shows this error ? A: It's documentary bug in the tag library declaration file of the Mojarra implementation. The Mojarra guys forgot to declare the media attribute of outputStylesheet tag in the html_basic.taglib.xml file. Netbeans is relying its tag/attribute validation on it and therefore gives false warnings. The tag library declaration entry of the attribute is not necessary for the technical functioning of the attribute (not in components, tagfiles, nor composites) and that's why it just works fine. The same documentary bug problem is known with below tag attributes: <ui:fragment rendered> - fixed in Mojarra 2.1 <f:selectItem itemEscaped> - fixed in Mojarra 2.2 If you report the <h:outputStylesheet media> documentary bug, it'll likely be fixed in Mojarra 2.3.
{ "pile_set_name": "StackExchange" }
Q: Network manager issue: The system network services are not compatible with this version I have seen relevant solutions in askubuntu and other sites but none worked for me so far. I reinstalled network manager, modem manager, tried to upgrade them and manually install everything, also tried nm-applet solution. But nothing seems to be working. The network manager icon is not there and normal reboot has no networking option. I have also gone to recovery and enabled networking via Ethernet and then resumed normal boot. But again after reboot there is not networking option. No WiFi, no Ethernet. Can someone please help me out? Reinstalling will definitely solve this but all my settings and work will be gone and it is painful to set up again. So folks here please suggest me what to do. A: Get onto a working machine (or plug into internet using an Ethernet cable) and download these three packages ... they are the working versions prior to recent broken release : wget http://mirrors.kernel.org/ubuntu/pool/main/libn/libnl3/libnl-3-200_3.2.21-1_amd64.deb wget http://mirrors.kernel.org/ubuntu/pool/main/libn/libnl3/libnl-route-3-200_3.2.21-1_amd64.deb wget http://mirrors.kernel.org/ubuntu/pool/main/libn/libnl3/libnl-genl-3-200_3.2.21-1_amd64.deb once downloaded copy onto a memory stick or similar then transfer onto your broken ubuntu box ... then install : sudo dpkg -i libnl-3-200_3.2.21-1_amd64.deb sudo dpkg -i libnl-genl-3-200_3.2.21-1_amd64.deb sudo dpkg -i libnl-route-3-200_3.2.21-1_amd64.deb reboot and your Wifi will be back working ... enjoy
{ "pile_set_name": "StackExchange" }
Q: Elastic behaviour of objects If I strike my car with a wrench with enough force to make a dent in it, then it's obvious that I won't be able to produce any acceleration in the car. But I am applying an external deforming force. Then according to Newton's third law the car body will also produce an equal and opposite force. If both forces are equal then how is a dent being made in the first case? Is there something I am missing? I have been pondering on it for quite some time. EDIT: Is there any limit on the restoring force that a body can apply? A: If the car door was dented, then at least for a short time there was some acceleration in the door that caused it to change velocities and dent inwards. In the normal configuration where a car door is not dented, there is a limit to the normal force it can apply. When you pass this limit the forces become unbalanced and the door deforms until a new equilibrium condition is met. You can get to equilibrium in two ways. Either the new dented configuration of the car door is able to support a greater normal force and resist further denting, or energy is dissipated during the denting process until the impact force is low enough that it reaches equilibrium with the dented car door. In some physics problems you create an ideal surface that can respond with whatever normal forces you want without deforming. This is often a good approximation because most solids change shape very little when you apply a force. But in reality, solids do change shape when you apply a load to them. Many behave like springs when forces are small.
{ "pile_set_name": "StackExchange" }
Q: questions about a fiber bundle I am reading the book From holomorphic functions to complex manifolds by Klaus Fritzsche and Hans Grauert. I have a question about a fiber bundle. On page 186, the last line. How to show that $$ \Gamma(U, \mathcal{O}^*_{X}) \cong \mathcal{O}^*(U):=\{f\in \mathcal{O}(U) : f(x) \neq 0 \text{ for every } x\in U\}? $$ Thank you very much. A: To get this off the Unanswered list, I'll restate Aaron's explanation as an answer: The notation is $\mathbb C^*=\mathbb C\setminus \{0\}$ and $\mathcal{O}_X^* = X\times \mathbb C^*$, a trivial fibre bundle. By definition of a section, an element of $\Gamma(U,\mathcal{O}_X^*)$ is a holomorphic map $s:U\to \mathcal{O}_X^*$ such that $\pi\circ s = \mathrm{id}_U$. The fibres being $\mathbb C^*$, what we have is a nonvanishing holomorphic function.
{ "pile_set_name": "StackExchange" }
Q: Replace the even characters to upper case and the remaining characters to lower case Is there an SQL query to replace the even characters to upper case and the remaining characters to lower case in a string? For example if the string is 'sagar' the result should be like sAgAr What would be the appropriate solution for this? A: I can't resist answering. This seems like such a natural for a recursive CTE: with t as ( select 'abcdef' as str ), cte as ( select cast(lower(str) as varchar(max)) as str, 1 as pos from t union all select stuff(str, pos + 1, 1, (case when pos % 2 = 1 then upper(substring(str, pos + 1, 1)) else lower(substring(str, pos + 1, 1)) end) ) as str, 1 + pos from cte where pos < len(str) ) select top (1) * from cte order by pos desc;
{ "pile_set_name": "StackExchange" }
Q: How to calculate $*dx^i$ on an oriented Riemannian manifold Let $M$ be a $d$ dimensional oriented Riemannian manifold, $(x^i)$ an oriented local chart, then we can define a star operator $*:\Omega^p(M)\to\Omega^{d-p}(M)$ by looking at orthonormal frames. But how can we calculate $*dx^i$? Can it be expressed as a function of $g^{jk}$ and $dx^1\wedge\cdots\wedge\widehat{dx^j}\wedge\cdots\wedge dx^d$? A: Of course it can. The Hodge star operator is characterized by$$\alpha\wedge*\beta=\langle\alpha,\beta\rangle\mathrm{vol},$$where $\alpha$ and $\beta$ are differential forms of the same degree. So, for $*dx^i$ you have $$dx^j\wedge* dx^i=g^{ij}\mathrm{vol},\quad j=1,\ldots,n.$$Letting $\omega_{ij}$ denote the coefficient of $dx^1\wedge\ldots\widehat{dx^j}\ldots\wedge dx^n$, the above equality means that (up to sign! But I'm not gonna go into signs...) $$\omega_{ij}dx^1\wedge\ldots\wedge dx^n=g^{ij}\mathrm{vol}=g^{ij}\sqrt{\det(g_{ij})}dx^1\wedge\ldots\wedge dx^n,$$and you have what you need.
{ "pile_set_name": "StackExchange" }
Q: Enable SSH access for AD admin accounts I have the need to configure SSH access for a AD service account on a fleet of Macs. I can't make the account a local account as the password for the service account cycles often. The end goal is to allow all accounts in a restricted AD security group ssh access to our Macs, but I'd like to start with just a single AD account. Any ideas? Thank you! A: Within System Preferences -> Sharing, the Remote Login option should have a spot for "Only these users". If you've properly joined the machine to the domain (good luck), you should be able to select the group from the "+" sign.
{ "pile_set_name": "StackExchange" }
Q: How to inject a controller into a directive when unit-testing I want to test an AngularJS directive declared like this app.directive('myCustomer', function() { return { template: 'cust.html' controller: 'customerController' }; }); In the test I would like to inject (or override) the controller, so that I can test just the other parts of the directive (e.g. the template). The customerController can of course be tested separately. This way I get a clean separation of tests. I have tried overriding the controller by setting the controller property in the test. I have tried injecting the customController using $provide. I have tried setting ng-controller on the html directive declaration used in the test. I couldn't get any of those to work. The problem seems to be that I cannot get a reference to the directive until I have $compiled it. But after compilation, the controller is already set up. var element = $compile("<my-customer></my-customer>")($rootScope); A: One way is to define a new module (e.g. 'specApp') that declares your app (e.g. 'myApp') as a dependency. Then register a 'customerController' controller with the 'specApp' module. This will effectively "hide" the customerController of 'myApp' and supply this mock-controller to the directive when compiled. E.g.: Your app: var app = angular.module('myApp', []); ... app.controller('customerController', function ($scope,...) { $scope = {...}; ... }); app.directive('myCustomer', function () { return { template: 'cust.html', controller: 'customerController' }; }); Your spec: describe('"myCustomer" directive', function () { $compile; $newScope; angular.module('specApp', ['myApp']) /* Register a "new" customerController, which will "hide" that of 'myApp' */ .controller('customerController', function ($scope,...) { $scope = {...}; ... }); beforeEach(module('specApp')); it('should do cool stuff', function () { var elem = angular.element('<div my-customer></div>'); $compile(elem)($newScope); $newScope.$digest(); expect(... }); }); See, also, this working demo. A: I think there is a simpler way than the accepted answer, which doesn't require creating a new module. You were close when trying $provide, but for mocking controllers, you use something different: $controllerProvider. Use the register() method in your spec to mock out your controller. beforeEach(module('myApp', function($controllerProvider) { $controllerProvider.register('customerContoller', function($scope) { // Controller Mock }); });
{ "pile_set_name": "StackExchange" }
Q: How to show values from 2 fields in a single textbox in an asp.net GridView I have a GridView and a linqdatasource. The GridView is editable and when the user clicks to edit a row I want to concatenate two of the fields in the linqdatasource and place it in a single textbox. I tried something like: <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Field1") %> - <%# Bind("Field2") %>'></asp:TextBox> That didn't work. A: It wouldn't make sense to Bind two values in one textbox, though you can Eval two of them together like this Text='<%# Eval("Field1","{0}") + "-" + Eval("Field2","{0}") %>' The formatting parameter {0} isn't always needed.
{ "pile_set_name": "StackExchange" }
Q: How do you return an Observable of an object where the object has a property built using an http request? [RxJs] I have a type I want to return from a method that is not the same as one the http request gets - I basically want to assign the results of that http request as a property on the object and return an observable of that object. I understand why the below is not going to work but for the purposes of having code.. getAuditsByObjectAndType<T>(object: T): Observable<IAuditInformation<T>> { const auditInfo: IAuditInformation<T> = { audits: [], object: object }; auditInfo.audits = this.get<IAudit>(`audits?id=${object.id}`) return Observable.of(auditInfo) } Is there an operator that will help me do what I want please? Edit: Got a working implementation but probably could be a lot better.. getAuditsByObjectAndType<T>(object: T): Observable<IAuditInformation<T>> { const auditInfo: Observable<IAuditInformation<T>> = Observable.of({ audits: [], object: object }); return this.get<IAudit>(`AuditItems?id=${object.id}`) .combineLatest(auditInfo, (audits, info) => { info.audits = audits; return info }); } A: You could map the response: import 'rxjs/add/operator/map'; getAuditsByObjectAndType<T>(object: T): Observable<IAuditInformation<T>> { return this.get<IAudit>(`audits?id=${object.id}`) .map(audits => ({ audits, object })); } However typescript has no way of knowing that your T contains an id property, to solve that you could do the following: interface TheObjectWithAnId { id: number; } getAuditsByObjectAndType<T extends TheObjectWithAnId>(object: T): Observable<IAuditInformation<T>>
{ "pile_set_name": "StackExchange" }
Q: Why is there a line length limit in Kate? In Kate, KDE's text editor, and other editors too I'm sure, sometimes files will not open correctly because of this line length limit. Why is it there? Is it safe to set this to an extreme number or is there a way to get rid of it somehow? My Kate version: Kate Version 3.10.5 Using KDE Development Platform 4.10.5 A: The way to do it, is by disabling the auto-wrap by changing the line length limit to zero in Settings --> Configure Kate --> Open/Save. A: Why? Because most shinny editors can hang-up your computer on documents that doesn't have line-endings. If you have dynamic line, it can use lots of CPU on certain files with long lines. Color Markup also consumes lots of CPU. Try to use dump a 100Mb MySql Database, and open it on Kate. It should work. Now remove line endings (for example using sed) and if you try again, your computer probably will hang up. On KDE 3.5, i was using KWrite/KEdit to open SQL dumps of several Gigabytes without problems. I could, because they don't had either dynamic line adjust nor color markup.
{ "pile_set_name": "StackExchange" }
Q: Ignoring certain values when calculating AVG sqlite I have the following query which finds all the hotels with overall rating greater than 3 and average cleanliness greater or equal to 5. There are 2 tables - Reviews where there is the [Cleanliness] attribute and Hotel - where there is the [Overall_Rating] attribute and both tables have [Hotel_ID] as an attribute. SELECT Reviews.Hotel_ID FROM [Reviews] INNER JOIN [Hotel] ON Reviews.Hotel_ID = Hotel.Hotel_ID WHERE [Overall_Rating] > 3 GROUP BY Reviews.Hotel_ID HAVING AVG([Cleanliness]) >= 5; The problem is in some of the reviews the Cleanliness value is -1 and if this is the case I need to ignore it when calculating the average. I came up with: SELECT Reviews.Hotel_ID FROM [Reviews] INNER JOIN [Hotel] ON Reviews.Hotel_ID = Hotel.Hotel_ID AND Reviews.Cleanliness > -1 WHERE [Overall_Rating] > 3 GROUP BY Reviews.Hotel_ID HAVING AVG([Cleanliness]) >= 5; Is this correct and if not how can I fix it? A: Filtering with WHERE is done before the aggregation, with HAVING, afterwards. So you should put the Cleanliness > -1 into the WHERE clause. Putting it into the ON clause of the join works exactly the same way, but makes the query a little bit more unclear because this filter does not actually have anything to do with the join itself.
{ "pile_set_name": "StackExchange" }
Q: Is SSL enough for protecting a request and its headers? I ask this because I work on an application where the X-AUTH-TOKEN can be copied from one request to another and impersonate another person. This makes me nervous, but I'm told since we're going to use HTTPS we don't have to worry about anything. So, my question is: Is it good enough trust SSL to protect against stealing headers used for auth/sessions? Thanks, A: The HTTPS standard implements HTTP entirely on top of SSL/TLS. Because of this, practically everything except for the DNS query is encrypted. Since headers are part of the request and response, and only sent after the secure-channel has been created, they are precisely as secure as the implementation of HTTPS on the given server.
{ "pile_set_name": "StackExchange" }
Q: How to combine two class in css here my two class classA and classB i want classB inherit style of classA and use only classB .classA{ width:100px;} .classB{ height:100px;} <div class="classB"></div> A: .classA{ width:100px;} .classB{ height:100px;} <div class="classA classB"></div>
{ "pile_set_name": "StackExchange" }
Q: 2-3 second delay loading page when using JQueryMobile I've found that if I load a web page in iOS, then if that page uses JQueryMobile it takes about 2 to 3 seconds longer to initially load. For example, the following page loads almost instantaneously: <!DOCTYPE> <html> <head> <title>Hello</title> </head> <body> <h1>Hello</h1> </body> </html> However this one takes a few seconds to load: <!DOCTYPE> <html> <head> <title>Hello</title> <link rel="stylesheet" href="jquery.mobile-1.1.1.min.css" /> <script src="jquery-1.7.2.min.js"></script> <script src="jquery.mobile-1.1.1.min.js"></script> </head> <body> <h1>Hello</h1> </body> </html> Is there anything I can do to try to get rid of this delay? Thanks A: If it’s the scripts that are taking too long, you can move them to the bottom of the page: <!DOCTYPE html> <html> <head> <title>Hello</title> <link rel="stylesheet" href="jquery.mobile-1.1.1.min.css" /> </head> <body> <h1>Hello</h1> <script src="jquery-1.7.2.min.js"></script> <script src="jquery.mobile-1.1.1.min.js"></script> </body> </html> Then again, doing so will make it harder to predict exactly what happens and when it will happen. But the DOM should load and render before the blocking script tags load. Now you just need to figure out how to deal with that. A: jQueryMobile is not that famous for its responsiveness. Even after you have tried every optimization. You could try loading the scripts via document.createElement() though. (Ideally, even this should go at the bottom) function createScript(src){ var script = document.createElement('script'); script.src = src; document.getElementsByTagName('head')[0].appendChild(script); } What this effectively does is to start loading and executing the scripts only after the page has rendered. i.e. kind-of asynchronously. If you have many like these. var files = ['1.js', '2.js', '3.js']; files.map(createScript); Also, I would vouch for SenchaTouch(if that's an option you're willing to consider)
{ "pile_set_name": "StackExchange" }
Q: Will developing my leg muscles improve my running? Will doing strength exercises and working out the leg muscles like the thigh and calve on machines improve speed or endurance in running? A: Yes. Training for strength & power - low reps, heavy weight, compound lifts, explosive movements - can help your speed & acceleration. If you train your muscular endurance - high reps, low weight, Crossfit or Crossfit Endurance style metcons - you'll help your endurance running. However, it's worth mentioning a few things: Not all exercises are the same. There is a big difference between machines and free weights and between compound exercises and isolation exercises. See my answer here. You'll see MUCH more of an effect from squats, deadlifts, cleans, snatches, lunges and step-ups than you will from leg curls, leg extensions, and calf raises. Depending on your current level of running & exact goals, weight training might not be a high priority. It should go without saying that the best way to improve your running is to do more running. Any cross training you do is secondary in importance and should be scheduled accordingly. Watch your diet. Weight training benefits from increased mass. Running, at least for any distance over ~400m, doesn't. It is certainly possible to build a ton of strength/power without gaining any extra mass, but you have to watch what you eat. Don't get me wrong - you won't become the hulk overnight or even over a year - but adding 5-10lbs by squatting & eating a lot is easy and could negatively impact your running. Just eat maintenance calories and you'll be fine. A: For someone who is new at the sport, strength training not only helps prevent injuries but will increase muscle mass thereby making running easier which means your endurance and speed improves. However, for the elite-athlete (i.e. marathoners) the endurance gains are far less from strength training but more from just honing their craft - they just run a lot. All their muscles are used to it.
{ "pile_set_name": "StackExchange" }
Q: Javascript: best practical way to declare functions The past few sites I worked on and primarily event driven using jquery and i usually make my functions as so function abc() { //do stuff } abc(); and function foo() { var a = $('.aaa'); var b = $('.bbb'); var c = $('.ccc'); function animal() { //do stuff } animal(); function pet() { //do stuff } pet(); } foo(); I know its not the best practice but, im still learning and it seems to work. I just would like to know the way I should handle this for now on. A: Actually the code in your example (the first one) is not the best thing you can do if you're defining all these functions in the global scope (like properties/methods of the global object window). I prefer using module pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript I recommend you to read the whole book in the upper link. Another thing which is extremely useful - Stoyan Stefanov's JS Patterns book http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752. Another alternative of your example (the second one) is self-executing function: (function () { //attaching events and doing all other stuff }()); Self-executing functions are helping you to do some initialization work when loading the page for first time. You can attach events or/and do another stuff which you should do once. It's preventing you from polluting the global scope and doing init multiple times.
{ "pile_set_name": "StackExchange" }
Q: Angular ng-click error <li role="menuitem"><a href="#" ng-click='getData1()'>Day</a></li> <li role="menuitem"><a href="#" ng-click='getWData2()'>Week</a></li> <li role="menuitem"><a href="#" ng-click='getMData3()'>Month</a></li> I have these three HTML elements defined and on click I would like to call a function in Angular. The problem is I defined three functions in angular that do the same thing but use a different parameter. How can I pass a fixed parameter into this function to pass in the string therefore helping me create one reusable function called getData(): <li role="menuitem"><a href="#" ng-click='getData('Day')'>Day</a></li> <li role="menuitem"><a href="#" ng-click='getData('Week')'>Week</a></li> <li role="menuitem"><a href="#" ng-click='getData('Month')'>Month</a></li> Here is the function: $scope.getDayData = function(day){ $scope.currentInterval = "day"; $http.get("http://localhost:8080/" + day) .then(function(response) { }); A: You should use double quotes for attributes since you are using single quote for passing the parameter: <li role="menuitem"><a href="#" ng-click="getData('Day')">Day</a></li> <li role="menuitem"><a href="#" ng-click="getData('Week')">Week</a></li> <li role="menuitem"><a href="#" ng-click="getData('Month')">Month</a></li> This may not work on some browsers. Rest of it looks good.
{ "pile_set_name": "StackExchange" }
Q: Show offline cache when server is unreachable Is it possible to show an offline cache of my website when the server is down? All the examples I can find regarding offline pages has to do with the client being offline. What I need is to show the user a cached version of my site if the server can't be reached. I've read about the Cache Manifest in HMTL 5 but it's getting removed and it causes to many problems. What can be done without using any other loadbalancing servers and such? A: I recently learned that with Fetch API and service workers its dead simple: First, you register the Service worker: if (!navigator.serviceWorker) return; navigator.serviceWorker.register('/sw.js') Then configure it to cache whats needed: self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/', 'js/main.js', 'css/main.css', 'imgs/icon.png', ]); }) ); }); And use Fetch API to get cached peaces if no response from the call: self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); if need to get cached version only if server is down, try something like: self.addEventListener('fetch', function(event) { event.respondWith( return fetch(event.request).then(function(response) { if (response.status !== 200) { caches.match(event.request).then(function(response) { return response; }).catch(function(error) { console.error('Fetching failed:', error); throw error; }); }) ); }); p.s. using Fetch API seems much nicer way than implementing old and nasty XMLHttpRequest.
{ "pile_set_name": "StackExchange" }
Q: angular-strap tooltip not working in ng-repeat Question: Is there a bug in angular-strap? Or do I misunderstand how Angular works, and this is expected? I've created a plunker to demonstrate the behavior. What I want: I want to show a different tooltip for each item in an ng-repeat. Behavior I'm seeing: Under certain conditions, the tooltip content is not properly inserted into the content template. Thus you only see the template, and not the content template or content itself. Conditions: When the page is first loaded, the tooltips work as expected. When an item is added to the ng-repeat, its tooltip does not populate the template's content section. If the page starts off with zero items in the ng-repeat, the tooltip in the first item added will work as expected. Items added after that will exhibit the problem. Regardless of how many items the ng-repeat starts with, any removal of any item from it will make all items added in the future not have working tooltips. Thoughts: If I boil it down, the "first load" works fine. After that, it doesn't. I'd guess that what happens is that there's a compilation step happening after the first round of adding items into ng-repeat. At that point, the angular-strap tooltip code sees the directive attributes, and sets up those tooltips and the content template. Subsequent changes to the ng-repeat are missed by angular-strap (even though I can see in the console that the call from bs-popover=tooltip(item) does actually run each time the ng-repeat list is updated). But I'm still stumped and wondering if this is behavior I can get around. How do I allow dynamic tooltips in items added to an ng-repeat? A: This seems to work in _popover.html <div class="popover-content">{{content}}</div> That is using {{ }} instead of ng-bind...works very odd. Upon further investigation... Its probably happening somewhere around here: https://github.com/mgcrea/angular-strap/blob/master/src/tooltip/tooltip.js#L83 Though I don't know where/how/what yet. Update So the bug (in Angular-Strap) is with caching your template. Initial retrieval (via http) works fine. But it caches them as an array, and upon retrieval from cache (subsequent additions) it gets an array. Which doesn't have a .data property so your template is empty, and your ng-bind is removed..
{ "pile_set_name": "StackExchange" }
Q: Using the power series of $\sin x^3$, the value of $f^{(15)}(0)$ is equal to $k\cdot11!$. Find the value of $k$. I have the following question: Using the power series of $\sin x^3$, the value of $f^{(15)}(0)$ is equal to $k\cdot11!$. Find the value of $k$. I tried to write the power series using the one from $\sin(x)$: $$\sin(x^{3})=\sum_{n=1}^{+\infty}(-1)^{n}\frac{x^{6n+3}}{(2n+1)!}$$ So, since $f^{(15)}(0)$ is related to $x^{15}$, so I got $n=2$. But I really don't know how can I use it. A: Since $\dfrac{f^{(15)}(0)}{15!}=\dfrac{(-1)^2}{5!}=\dfrac1{5!}$, you have $f^{(15)}(0)=\dfrac{15!}{5!}$. You can get the value of $k$ from this.
{ "pile_set_name": "StackExchange" }
Q: Implementing bidirectional relations between objects of the same class I have to implement a class whose instances have a bidirectional relation to each other. For example I have the class FooBar which should offer the method sameAs(FooBar x) and maintain a Set for each instances containing its equivalent instances. So if I call foo.sameAs(bar), the Set in foo should contain bar and vice versa. Invoking bar.sameAs(foo) doesn't work, of course. For clarifiction: the instances of this class are only semantically equal. equals should still return false. The solutions I've come up with is either to implement a private method internalSameAs(FooBar x) which is invoked from sameAs(FooBar x) or to use a static method sameAs(FooBar x, FooBar y). Solution 1: class FooBar { Set<FooBar> sameAs = new HashSet<FooBar>(); public void sameAs(FooBar x) { this.internalSameAs(x); x.internalSameAs(this); } public void internalSameAs(FooBar x) { sameAs.add(x); } } Solution 2: class FooBar { Set<FooBar> sameAs = new HashSet<FooBar>(); public static void sameAs(FooBar x, FooBar y) { x.sameAs.add(y); y.sameAs.add(x); } } Which one would you prefer and why? Or is there another way I didn't think about? A: are you flexible with the data structures to be used? If so you could use a Multimap (from Guava Collections) that is static amongst all the instances of the class FooBar. In that Multimap you can have the keys as FooBar references (or a unique id if you have one) and the values would be the references (or id.s) of the FooBars that have the sameAs relation.
{ "pile_set_name": "StackExchange" }
Q: Is the 有 in 你有想要买什么吗 some kind of auxiliary verb? I was going to the convenience store and asked my local friend how to ask in Chinese "Do you want anything?" Her answer was: 你有想要买什么吗 I wasn't sure what to make of the 有 before the verb 想要 meaning "to want" and as a native speaker she could not explain it though she did understand my questions about its grammatical function. Is it a kind of auxiliary verb in this sentence? Or is it a case of the special Taiwanese 有 that can be used for some references to the past but which also has other uses? Or is it something entirely different? A: 你有想要买什么吗. It sounds more like Taiwanese usage of 有 to my ear. I found they often put 有 between subject and verb. E.g. 我有去过;我有看过;where I often just say 我去过;我看过. In this case, I'll probably say 你想要买什么? or 你想要买什么(东西)吗?.
{ "pile_set_name": "StackExchange" }
Q: CMake - what does this OPTION command do? I'm getting into CMake and have some trouble with the syntax of it. I was wondering if any of you could tell me what the following command does exactly: OPTION(USE_OPENGL "Use OpenGL" FOUND_OPENGL) As far as I can tell, it will Default OPENGL to ON if it is found. Is that correct? A: This command provides an option to the user to change a specific aspect of your build system. The syntax is explained in the documentation: option(<option_variable> "help string describing option" [initial value]) In your specific case, it will create an option called USE_OPENGL which should have the default value from the FOUND_OPENGL variable. So the default will probably be the same as the result of an automatic check whether opengl is available. However, the syntax is actually wrong in the example you give. It should be: OPTION(USE_OPENGL "Use OpenGL" ${FOUND_OPENGL}) Options are specifically available through the ccmake command or the cmake gui. Here, the given documentation string will be available to the user. After the user has decided on the option, you can use the the variable given as the first argument like any other boolean variable in CMake. E.g.: IF(USE_OPENGL) MESSAGE(STATUS "Will us OpenGL") ENDIF()
{ "pile_set_name": "StackExchange" }
Q: How to set sample rate as 100KHz using AudioTrack in Android? I'm developing an Android app that will play a specific audio. This audio is generated by code. My problem is that I need the sample rate up to 100KHz, but I got the error message as below. Could anyone know how to set sample rate as 100KHz with AudioTrack. Thanks. PS: As I know, only AudioTrack could modify audio data, that's why I use AudioTrack ---------------code start------------------- audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 100000, AudioFormat.ENCODING_PCM_16BIT, (int)minSize, AudioTrack.MODE_STREAM); ---------------log start-------------------- > D/AndroidRuntime( 7952): Shutting down VM E/AndroidRuntime( 7952): > FATAL EXCEPTION: main E/AndroidRuntime( 7952): > java.lang.RuntimeException: Unable to start activity > ComponentInfo{com.examples.audiotracktest/com.examples.audiotracktest.AudioTrackTest}: > java.lang.IllegalArgumentException: 100000Hz is not a supported sample > rate. E/AndroidRuntime( 7952): at > android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1830) > E/AndroidRuntime( 7952): at > android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1851) > E/AndroidRuntime( 7952): at > android.app.ActivityThread.access$1500(ActivityThread.java:132) > E/AndroidRuntime( 7952): at > android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038) > E/AndroidRuntime( 7952): at > android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( > 7952): at android.os.Looper.loop(Looper.java:150) E/AndroidRuntime( > 7952): at android.app.ActivityThread.main(ActivityThread.java:4293) > E/AndroidRuntime( 7952): at > java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( > 7952): at java.lang.reflect.Method.invoke(Method.java:507) > E/AndroidRuntime( 7952): at > com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) > E/AndroidRuntime( 7952): at > com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607) > E/AndroidRuntime( 7952): at dalvik.system.NativeStart.main(Native > Method) E/AndroidRuntime( 7952): Caused by: > java.lang.IllegalArgumentException: 100000Hz is not a supported sample > rate. E/AndroidRuntime( 7952): at > android.media.AudioTrack.audioParamCheck(AudioTrack.java:369) > E/AndroidRuntime( 7952): at > android.media.AudioTrack.<init>(AudioTrack.java:312) E/AndroidRuntime( > 7952): at android.media.AudioTrack.<init>(AudioTrack.java:265) > E/AndroidRuntime( 7952): at > com.examples.audiotracktest.AndroidAudioDevice.<init>(AndroidAudioDevice.java:21) > E/AndroidRuntime( 7952): at > com.examples.audiotracktest.AudioThread.<init>(AudioThread.java:11) > E/AndroidRuntime( 7952): at > com.examples.audiotracktest.AudioTrackTest.onCreate(AudioTrackTest.java:29) > E/AndroidRuntime( 7952): at > android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072) > E/AndroidRuntime( 7952): at > android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1794) > E/AndroidRuntime( 7952): ... 11 more A: 100kHz is a non-standard sampling rate and most Android platforms only support the standard rates (ref. Wikipedia: Sampling Rate). The closest standard rate is 96kHz (professional audio) but most phones don't support this high a rate. CD quality (44.1kHz) is widely supported and you might be lucky and get 48kHz (e.g. Nexus S).
{ "pile_set_name": "StackExchange" }
Q: css centering text within a background image I have a number inside a background image. I can't put the number in the center of the circle. So far, I have center the number but it is in the topmost part of the circle. How do I move it down to the center? HTML code: <div class="number"> <p> 576 </p> </div> CSS code: .number{ float:left; background-position: center; text-align: center; font-size:200%; } .number p{ position:relative; top: 38%; left:57%; z-index:999; background-image: url("http://davidwalsh.name/demo/css-circles.png"); width: 207px; height: 204px; } Here is the jsfiddle A: All you need to do is to set a line-height for your p element like line-height: 204px; which is equivalent to the element height. Demo .number p { /* Other properties here */ line-height: 204px; /* add this */ } Also, I have no idea why you are using top and left properties here with z-index property, I think you can clean up the mess by a great extent.
{ "pile_set_name": "StackExchange" }
Q: How can I do that when the home view navigates to the login view, trigger the useEffect of the login? Basically in login I have a function that verifies if a token exists, and if it exists automatically redirects to thehome view, otherwise it will remain in the login view. Login const Login = props => { const [loading, setLoading] = useState(true); useEffect(() => { getTokenPrevious(); }, [loading]); const getTokenPrevious = () => { AsyncStorage.multiGet(["token"]) .then(value => { let token = value[0][1]; if (token !== null) { props.navigation.navigate("home"); } else { setLoading(false); } }) .catch(error => { setLoading(false); }); }; if (loading) { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Text>Loading...</Text> <Spinner color={STYLES.bgHeader.backgroundColor} /> </View> ); } return ( rest code login.... Sometimes when from the home view I use thebackbutton of the cell phone or when I try to tap on the logout button, this redirects me to thelogin view but this part is shown: return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Text>Loading...</Text> <Spinner color={STYLES.bgHeader.backgroundColor} /> </View> ); the part that should be shown is this: return ( rest code login.... because the token no longer exists because it was deleted. home const Home= props => { clearStorage = () => { AsyncStorage.removeItem("token") .then(() => { props.navigation.navigate("Login"); }) }; return ( <View> <Button onPress={clearStorage()} ><Text>Logout</Text></Button> <View> ) } How can i fix this? A: <Button onPress={clearStorage()} ><Text>Logout</Text></Button> clearStorage() call the method, When If loaded. remove the () from clearStorgae. <Button onPress={clearStorage} ><Text>Logout</Text></Button>
{ "pile_set_name": "StackExchange" }
Q: What are the differences/connections between the Churches of Christ and the Congregational Churches? I have done a fair amount of research but am still very confused about the difference between the two, the Churches of Christ and the Congregational Churches. I know of the United Church and Church of Jesus Christ of Latter-Day Saints, but that is not what I am referring to with the Churches of Christ. Are they the same thing? Are they different? In what way are they different? If anyone has any knowledge regarding this, please share. Thank you very much! A: Congregationalist churches are of the Protestant Reformed tradition, and go way back to the English Civil War when the King tried to gain control over the governance of the Church. Back in the mid 1600’s, Puritans resisted the influence of the Church of England and broke away. By the early 1800’s, the Congregational Church had established itself in America with its own form of governance, with a strong emphasis on the autonomy of the local church, and tolerance of doctrinal variations. In 1957, the Evangelical Reformed Church merged with the Congregational Christian Churches to become the United Church of Christ. The Conservative Congregational Christian Conference was formed in 1948 in opposition to the liberal theology making inroads in other Congregational churches. Then, in 1955, the National Association of Congregational Christian Churches was formed. More information on the history of Congregationalism here: https://www.gotquestions.org/congregationalism.html The Churches of Christ came out of the Restoration Movement: The Restoration Movement began in the early 19th century... Among the most influential leaders of this movement were Alexander Campbell and Barton W. Stone. Although the fundamental views remained, in 1906 this group split. The followers of Campbell and Stone divided into two sects, called the Church of Christ (Non-Instrumental) and the Christian Church (Disciples of Christ). Over time many additional schisms have formed from these core groups as well. Currently there are three major and several minor groups who trace their roots back to the Stone-Campbell Restoration Movement: the Christian Churches/Disciples of Christ, Churches of Christ, Independent Christian Churches, Churches of Christ in Australia, Associated Churches of Christ (New Zealand), United Reformed Church (UK), and others... Although a key principle of the Restoration Movement is concern for Christian unity, the history of the movement is itself riddled with numerous splits, re-splits and schisms. Source: https://www.gotquestions.org/Restoration-movement.html Perhaps the most significant difference between the beliefs of Congregationalists and the Churches of Christ is the view of the latter that baptism by full water immersion (for consenting adults only) is a requirement for salvation. Equally worrying is the view that a person must continue to strive to maintain their salvation by doing works. Insisting that the use of music in worship is unbiblical almost certainly won’t affect anybody’s salvation, but it should be of concern that any religious group would be so dogmatic. Even the Free Church of Scotland has now conceded on that one! The article in the link below came to this conclusion: Many Church of Christ churches are in fact solid, biblically based churches. There are many Church of Christ churches which declare the true Gospel of salvation by faith alone, through grace alone, in Christ alone. At the same time, with an extreme over-emphasis on the absence of musical instruments, with a claim of exclusive access to salvation, and with a doctrine of salvation that is borderline (at best) works-based, there are other Church of Christ churches that should definitely not be attended / participated in. This requires discernment on the part of a believer considering joining a Church of Christ church. The answer to the question depends entirely on which type of Church of Christ church it is. Source: https://www.gotquestions.org/Church-of-Christ.html I hope this information will help you in your research into the differences and connections between the two groups.
{ "pile_set_name": "StackExchange" }
Q: OSX terminal tilde bash complete On my Linux box, when I type $ cd ~/Des[TAB] it completes to ~/Desktop/. But in OSX terminal doing the same thing expands to /Users/username/Desktop/. This appears rather annoying to me as it 'jumps' and also takes more space. Can I somehow get the former behaviour? A: I hadn't ever picked up on this behavior before, but my shell on OS X shows the former behavior (expanding cd ~/Des[TAB] to cd ~/Desktop/). Unfortunately I don't have a good answer as to why. Dumb luck, I guess. That said, here is a similar thread that discusses some ways to turn it off. Additionally, here is another in-depth discussion talking about the Linux-y way to enable/disable the feature. Hope one of 'em works for you.
{ "pile_set_name": "StackExchange" }
Q: Linq: Split list by condition and max size of n I want to transform an array: ["a", "b", "b", "a", "b", "a", "b"] to ["a", "a", "b", "b", "a", "b", "b"] or ["b", "b", "a", "a", "b", "b", "a"] I want to group the array in a way where a special condition matches. In my case when item == 'a' or item == 'b'. And these groups I want to chunck into groups of 2. I'm currently a bit confused how to do it the elegant way. Can anyone help? Maybe the following makes it more clear: I like to group the array into 'a' and 'b'-items first like so: a-group: ["a","a","a"] and b-group: ["b","b","b","b"] then I want to chunk this into groups of 2: a-group: ["a","a"] ["a"] b-group: ["b","b"] ["b","b"] And now I want to merge them together to get the result: ["a","a","b","b","a","b","b"] (always 2 of each group merged together) A: First you need to GroupBy your data. Let assume the object are string but it's irrelevant anyway it's your grouping condition that will change if you have anything other than that. For this to work you will need MoreLinq or simply include the Batch extension which does the "group by 2 and 1 for left overs". Details can be found here note that the Batch(2) can be changed to whatever you need. If you put Batch(5) and you have 7 elements it will make 2 groups, one with 5 elements and one of 2 elements // be my data, 4 x a, 3 x b, 1 x c, 2 x d, As a list for easier linQ var data = new[] { "a", "a", "c", "b", "a", "b", "b", "d", "d", "a" }.ToList(); // group by our condition. Here it's the value so very simple var groupedData = data.GroupBy(o => o).ToList(); // transform all groups into a custom List of List of List so they are grouped by 2 internally // each list level represent Grouping -> Groups of 2 (or 1) -> element var groupedDataBy2 = groupedData.Select(grp => grp.ToList().AsEnumerable().Batch(2).ToList()).ToList(); // find the group with the maximum amount of groups or 2 (and 1) var maxCount = groupedDataBy2.Max(grp => grp.Count()); // will contain our final objects listed var finalObjects = new List<string>(); // loop on the count we figured out and try add each group one by one for (int i = 0; i < maxCount; i++) { // try each group foreach (var group in groupedDataBy2) { // add the correct index to our final list only if the current group has enough to fill if (i < group.Count) { // add the data to our final list finalObjects.AddRange(group[i]); } } } // result here is : a,a,c,b,b,d,d,a,a,b var results = string.Join(",", finalObjects);
{ "pile_set_name": "StackExchange" }
Q: C# Linq merge multiple lists? var results = from thing in AnArrayOfThings let list = Function(thing) ??? select OneLongResultsList; How can I merge all the "list" collections into one long list? I'm new to linq and I can't use lambda expressions. Basically, what I want to do, is this: List<Result> results = new ...; foreach (Thing t in ListOfThings) { List<Result> list = Function( t ); results.MergeOrAdd( list ); } A: Maybe you just need SelectMany? var results = AnArrayOfThings.SelectMany(x => Function(x)); Or in query syntax: var results = from thing in AnArrayOfThings from thingInAList in Function(thing) select thingInAList;
{ "pile_set_name": "StackExchange" }
Q: Python: Get data BeautifulSoup I need help with BeautifulSoup, I'm trying to get the data: <font face="arial" font-size="16px" color="navy">001970000521</font> They are many and I need to get the value inside "font" <div id="accounts" class="elementoOculto"> <table align="center" border="0" cellspacing=0 width="90%"> <tr><th align="left" colspan=2> permisos </th></tr><tr> <td colspan=2> <table width=100% align=center border=0 cellspacing=1> <tr> <th align=center width="20%">cuen</th> <th align=center>Mods</th> </tr> </table> </td> </tr> </table> <table align="center" border="0" cellspacing=1 width="90%"> <tr bgcolor="whitesmoke" height="08"> <td align="left" width="20%"> <font face="arial" font-size="16px" color="navy">001970000521</font> </td> <td>...... <table align="center" border="0" cellspacing=1 width="90%"> <tr bgcolor="whitesmoke" height="08"> <td align="left" width="20%"> <font face="arial" font-size="16px" color="navy">001970000521</font> </td> I hope you can help me, thanks. A: You should use the bs4.Tag.find_all method or something similar. soup.find_all(attrs={"face":"arial","font-size":"16px","color":"navy"}) Example: >>>import bs4 >>>html='''<div id="accounts" class="elementoOculto"> <table align="center" border="0" cellspacing=0 width="90%"> <tr><th align="left" colspan=2> permisos </th></tr><tr> <td colspan=2> <table width=100% align=center border=0 cellspacing=1> <tr> <th align=center width="20%">cuen</th> <th align=center>Mods</th> </tr> </table> </td> </tr> </table> <table align="center" border="0" cellspacing=1 width="90%"> <tr bgcolor="whitesmoke" height="08"> <td align="left" width="20%"> <font face="arial" font-size="16px" color="navy">001970000521</font> </td> <td>...... <table align="center" border="0" cellspacing=1 width="90%"> <tr bgcolor="whitesmoke" height="08"> <td align="left" width="20%"> <font face="arial" font-size="16px" color="navy">001970000521</font> </td> ''' >>>print bs4.BeautifulSoup(html).find_all(attrs={"face":"arial","font-size":"16px","color":"navy"}) [<font color="navy" face="arial" font-size="16px">001970000521</font>, <font color="navy" face="arial" font-size="16px">001970000521</font>]
{ "pile_set_name": "StackExchange" }
Q: custom html inside errorElement of jquery Validate I'm putting my error message inside a div (errorElement) and giving it errorClass:"callout border-callout error, which I require to custom style it. This is how it looks now: <input type="text" id="email" name="email" placeholder="Enter your E-Mail Address"/> <div id="email-id" class="callout border-callout error"><!-- this is my error div --> Here is my error message </div> but I want two more elements inside this errorElement so i can style it properly. Ideally, it should look as follows: <input type="text" id="email" name="email" placeholder="Enter your E-Mail Address"/> <div id="email-id" class="callout border-callout error"><!-- this is my error div --> Here is my error message <b class="border-notch notch"></b> <b class="notch"></b> </div> My current jquery validate code: $(function() { $('#form1').validate({ rules: { email: { required: true, email: true }, fname: { required: true, }, lname: { required: true, } }, messages: { email: { required: 'Please enter your email', email: 'Please enter a valid email' }, fname: { required: 'Please enter your First Name', }, lname: { required: 'Please enter your Last Name', } }, submitHandler: function(form) { $(form).ajaxSubmit({ dataType: 'json', success: function(jsonResponse) { //Example json object returned by server: [false, "You have already subscribed!"] var notyType; if (jsonResponse.response) { notyType = 'success'; } else { notyType = 'error'; } showNoty(jsonResponse.message, notyType); } }); }, errorClass: "error callout border-callout", }); }); UPDATE: <form method="post" id='form1' class="subscription-form"> <div class="subscription-form-email"> <span class="input-row"><input type="text" id="email" name="email" placeholder="Enter your E-Mail Address"/></span> <div id="email-id" class="callout border-callout error" style="display:none"> <b class="border-notch notch"></b> <b class="notch"></b> </div> <span class="input-row"><input type="text" id="fname" name="fname" placeholder="First Name"/></span> <span class="input-row"><input type="text" id="lname" name="lname" placeholder="Last Name"/></span> </div> <input type="submit" value="SUBSCRIBE" class="submit-button" name="submit" id="submitButton" title="Click here to submit your message!" /> </form> A: There are a couple issues with your code that need to be corrected... 1) Fix the HTML. You have mismatched div tags... specifically, you have one more </div> than you have <div>. I don't see any other HTML issues, but your layout looks like an unusual mix of div elements with input elements nested inside span elements. If you want those span elements to behave like rows, then IMHO, they should be div elements instead. 2) The error class, border-callout, is a real problem. Although it may be technically ok to have class names that contain hyphens, it's bad practice. Why? Because JavaScript will interpret that hyphen as a minus sign. Your unedited code in a jsFiddle shows that the error messages will stack up on each other instead of toggling. Simply removing border-callout from errorClass, clears that issue right up. As far as what you're asking... how to insert the error message into a predefined div full of other HTML. First, you're going to have to put the message into some kind of container of its own... label, p, span, etc. It's how the plugin needs it so it can be targeted. Unless you specify it with the errorElement option, the plugin will just use label by default. <div id="email-id" class="callout border-callout error"><!-- this is my error div --> <label>Here is my error message</label><!-- message must be inside a container --> <b class="border-notch notch"></b> <b class="notch"></b> </div> Then place the message label object inside your <div> using the errorPlacement callback function and a bunch of jQuery DOM traversal methods... errorPlacement: function(error, element) { error.insertBefore(element.parent().next('div').children().first()); } Breakdown: error // the error object (includes message and its label container) .insertBefore( // insert the error object before what's defined inside () element // your input element object .parent() // the span which encloses your input element .next('div') // the div which immediately follows your span .children() // everything inside your div .first() // the first element inside your div ) // closes insertBefore() Then since you also need to toggle the <div> container along with the error message, you'll need to use the highlight and unhighlight callback functions and a couple jQuery DOM traversal methods... highlight: function (element) { $(element).parent().next('div').show(); }, unhighlight: function (element) { $(element).parent().next('div').hide(); } Working DEMO: http://jsfiddle.net/naa6w/
{ "pile_set_name": "StackExchange" }
Q: Variables did not replaced I wrote some code to replace variables in docx tamplate file header. List<SectionWrapper> sectionWrappers = this.wordMLPackage.getDocumentModel().getSections(); for (SectionWrapper sw : sectionWrappers) { HeaderFooterPolicy hfp = sw.getHeaderFooterPolicy(); HeaderPart defaultHP = hfp.getDefaultHeader(); if (defaultHP != null) { defaultHP.variableReplace(getVariablesForChange()); if (hfp.getFirstHeader() != null) { hfp.getFirstHeader().variableReplace(getVariablesForChange()); } } } getVariablesForChange() is a Map has contains the variables and values. When I running the unit test the replace is corectly fine but I use this in my web application on Tomee Plume the variables does not replaced. For example the variable is: ${TOCHANGE} it looks like this after change TOCHANGE. Docx4j version is: 3.3.6 Please help me to resolve this issue. A: It won't work if your KEY is split across separate runs in your docx. See https://github.com/plutext/docx4j/blob/master/src/main/java/org/docx4j/model/datastorage/migration/VariablePrepare.java
{ "pile_set_name": "StackExchange" }
Q: DirectX or Hyper-V In google cloud? Okay so basically i want to run some programs thath need Directx , a good alternative would be RemoteFX with Hyper-V but google cloud plataform dosnt support Hyper-V. And RDP dosnt support Directx. I do have any alternative for succesfully running those? Or its impossible? I already try installing Hyper-V and i always get : "a hypervisor is already running or the host server isnt compatible with Hyper-V" I also try using anydesk/teamviewer but i realize thaths pretty useless cause you just connect with them to the RDP session, once you close the sesion, its the same. And if you dont close, you are just getting in the RDP. Same issue. I also try installing all type of drivers also the GRID of nvidia, but nothing worked. Im already desesperated , if someone can help me out. Would be insane. A: With regards to running Hyper-V on GCP, this is referred to as 'nested virtualization' and while it is possible to run a nested hypervisor, Windows Hyper-V is not currently supported. For more details please see here. However one cloud based alternative that is worth checking out is Amazon Workspaces as they have GPU enabled virtual desktop services. More details here. However whether they provide the features required by your specific application is something you will have to test.
{ "pile_set_name": "StackExchange" }
Q: Python List in Java I'm using XMLRPC calls from java to python. So my server in python has these remote method and use apache xmlrpc lib in java to make the calls. So i always prefered to use Dictionary to return from the calls. Cause when i used dictionary, Object data type in java, was directly printing my valueset returned from python. Then i used Map to iterate. Now i 've to return list in one of the methods. I couldn convert Object to List/ArrayList/HashMap. need help... How to convert Python List in Java? Sample Output: {hello=1, list=[Ljava.lang.Object;@1ba9f7} A: It looks like the conversion worked correctly - [Ljava.lang.Object;@1ba9f7 is the default way that a Java array (not List) of Objects is printed out. Not very helpful, but there you go... You could convert it to a Java List using Arrays.asList(mylist). See the JavaDoc. Or try printing out the items in the array using: for (Object obj: myArray) { System.out.println(obj); }
{ "pile_set_name": "StackExchange" }
Q: Jquery File Upload - $_FILES array empty Using Jquery File Upload. It's 'working' and uploading images & displaying the thumbs. However when I Submit the form in the handler if I dump $_FILES there's nothing there. I'm basically using the Basic Plus example with autoUpload set to false. I was hoping that I would be able to use this to have users select multiple images. Then have them uploaded once the form was submitted and handle them basically the same way I would handle them if I had X number of file upload buttons on a page. Uploading them using autoUpload=TRUE also works as well. I tried that and didn't see anything in POST or FILES either. Comments to get either method working would be great. Here's my js below. $('#fileupload').fileupload({ url: url, method: 'POST', dataType: 'json', autoUpload: false, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, maxFileSize: 5000000, // 5 MB // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true }).on('fileuploadadd', function (e, data) { data.context = $('<div/>').appendTo('#files'); $.each(data.files, function (index, file) { var node = $('<p/>') .append($('<span/>').text(file.name)); node.appendTo(data.context); }); }).on('fileuploadprocessalways', function (e, data) { var index = data.index, file = data.files[index], node = $(data.context.children()[index]); if (file.preview) { node .prepend('<br>') .prepend(file.preview); } if (file.error) { node .append('<br>') .append($('<span class="text-danger"/>').text(file.error)); } if (index + 1 === data.files.length) { data.context.find('button') .text('Upload') .prop('disabled', !!data.files.error); } }).on('fileuploadprogressall', function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); }).on('fileuploaddone', function (e, data) { $.each(data.result.files, function (index, file) { if (file.url) { var link = $('<a>') .attr('target', '_blank') .prop('href', file.url); $(data.context.children()[index]) .wrap(link); } else if (file.error) { var error = $('<span class="text-danger"/>').text(file.error); $(data.context.children()[index]) .append('<br>') .append(error); } }); }).on('fileuploadfail', function (e, data) { $.each(data.files, function (index, file) { var error = $('<span class="text-danger"/>').text('File upload failed.'); $(data.context.children()[index]) .append('<br>') .append(error); }); }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); Here's my html <form action="/submit_form" accept-charset="utf-8" class="form-horizontal review-validate-form" id="review-form" autocomplete="off" enctype="multipart/form-data" method="POST"><div style="display:none"> <div class="control-group"> <label class="required control-label" for="first_name">Comments <span class="required">*</span></label> <div class="controls"> <textarea name="comments" cols="40" rows="10" class="span8 required" id="comments" ></textarea> </div> </div> <!-- The fileinput-button span is used to style the file input field as button --> <span class="btn btn-success fileinput-button"> <i class="glyphicon glyphicon-plus"></i> <span>Add files...</span> <!-- The file input field used as target for the file upload widget --> <input id="fileupload" type="file" name="files[]" multiple> </span> <br> <br> <!-- The global progress bar --> <div id="progress" class="progress"> <div class="progress-bar progress-bar-success"></div> </div> <!-- The container for the uploaded files --> <div id="files" class="files"></div> <br> <div class="form-actions" style=""> <input type="submit" value="Submit Review" name="submitReview" class="btn btn-primary btn-large"> </div> </form> A: Got it to work by appending a hidden input for each file uploaded so that I can process them and add them to the database after the form is submitted. I feel like there should be something built in already to handle this but for now this works. Added a filesHidden div to hold the hidden fields. <div id="files" class="files"></div> Then updated the js to which appends a hidden input with filename to pass along to my form handler so I can link up the images with the form submission. }).on('fileuploaddone', function (e, data) { $.each(data.result.files, function (index, file) { if (file.url) { $( "#filesHidden" ).append( '<input type="hidden" name="images[]" value="' + file.name + '">' ); } else if (file.error) { var error = $('<span class="text-danger"/>').text(file.error); $(data.context.children()[index]) .append('<br>') .append(error); } }); } Full Example Below (Requested in comments below). Note my example also adds a title text box to each uploaded image. var url = '/js/fileUpload/server/php/'; uploadButton = $('<button/>') .addClass('btn btn-primary') .prop('disabled', true) .text('Processing...') .on('click', function () { var $this = $(this), data = $this.data(); $this .off('click') .text('Abort') .on('click', function () { $this.remove(); data.abort(); }); data.submit().always(function () { $this.remove(); }); }); $('#fileupload').fileupload({ url: url, method: 'POST', dataType: 'json', autoUpload: true, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, maxFileSize: 5000000, // 5 MB // Enable image resizing, except for Android and Opera, // which actually support image resizing, but fail to // send Blob objects via XHR requests: disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent), previewMaxWidth: 100, previewMaxHeight: 100, previewCrop: true }).on('fileuploadadd', function (e, data) { data.context = $('<div/>').appendTo('#files'); }).on('fileuploadprocessalways', function (e, data) { var index = data.index, file = data.files[index], node = $(data.context.children()[index]); if (file.preview) { var node = $('<p/>') .append('<br /><strong>Description</strong>: <input type="text" name="title[]" value="">'); node.appendTo(data.context); node = $(data.context.children()[index]); node .prepend('<br>') .prepend(file.preview); } if (file.error) { alert(file.error); } if (index + 1 === data.files.length) { data.context.find('button') .text('Upload') .prop('disabled', !!data.files.error); } }).on('fileuploadprogressall', function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); }).on('fileuploaddone', function (e, data) { $.each(data.result.files, function (index, file) { if (file.url) { $( "#filesHidden" ).append( '<input type="hidden" name="images[]" value="' + file.name + '">' ); } else if (file.error) { var error = $('<span class="text-danger"/>').text(file.error); $(data.context.children()[index]) .append('<br>') .append(error); } }); }).on('fileuploadfail', function (e, data) { $.each(data.files, function (index, file) { var error = $('<span class="text-danger"/>').text('File upload failed.'); $(data.context.children()[index]) .append('<br>') .append(error); }); }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); A: You need the set correct datatype dataType: 'json', to multipart form data you cant set $_FILES variable with data type json attribute
{ "pile_set_name": "StackExchange" }
Q: Change image on click in custom listview Android In my custom listview I want to change Image when the image is clicked. But currently when I click on Image, last row image is changed not the one on which I clicked. My customAdapter classis below: package com.zek.androidvoicechanger; import java.util.List; import org.w3c.dom.Text; import android.app.Activity; import android.content.Context; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; public class CustomAdapter extends ArrayAdapter<Items> { Context context; ImageView image ; // int[] Radio = { R.drawable.play, R.drawable.pause }; public CustomAdapter(Context context, int resourceId, List<Items> items) { super(context, resourceId, items); this.context = context; } private class ViewHolder { // ImageView imageView; TextView txtTitle; // ImageView img; } public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder holder = null; Items rowItem = getItem(position); LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.custom_list, null); holder = new ViewHolder(); holder.txtTitle = (TextView) convertView .findViewById(R.id.textView1); // holder.img = (ImageView) convertView.findViewById(R.id.imageView2); image = (ImageView) convertView.findViewById(R.id.imageView2); // holder.rdo = (RadioButton) convertView.findViewById(R.id.radioButton1); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.txtTitle.setText(rowItem.getTitle()); image.setImageResource(rowItem.getImageId()); image.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "image clicked", 1000).show(); if(position==0){ image.setImageResource(R.drawable.pause); } AudioListner.playRecord(position); } }); //holder.rdo.setTag(position); // holder.rdo.setOnCheckedChangeListener(new OnCheckedChangeListener() { // // @Override // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // // // // } // }); // rdo.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // // // if(position==0){ // rdo.indexOfChild(findViewById(isEnabled(position))); // Toast.makeText(context, "image clicked", 1000).show(); // rdo.setBackgroundResource(R.drawable.pause); // AudioListner.playRecord(position); // // } // // // // if (rdo.isClickable()) { // rdo.setBackgroundResource(R.drawable.pause); // Toast.makeText(context, "image clicked", 1000).show(); // // //Radio[1] = 1; // AudioListner.playRecord(position); // // } else { // // rdo.setBackgroundResource(R.drawable.play); // Toast.makeText(context, "image not clicked", 1000).show(); // // } //// // } // }); return convertView; } } Any help will be appreciated. A: Adapter based views like ListView recycles its views to save resources. During scrolls, ListView will recycle views that are no more visible. This post by Lucas is a great place to learn more about its working: http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/ So registering onClick in your getView() method might not be a very good idea. Instead use the setOnItemClickListener() method on your ListView. To accomplish what you're trying to do, you can do this: Edit: Updated my code as per your comment. mYourListView..setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick (AdapterView<?> parent, View view, int position, long id) { Toast.makeText(context, "Item #" + position + " clicked", Toast.LENGTH_SHORT).show(); // here, "position" is the position of your item and "id" is your // item's id in your data set. // mLastClickedPosition is a member field of type long which // stores the position of the most recently clicked item, // initially set to -1 if(mLastClickedPosition != -1){ // do something to pause the item in your list at this position } // next, update mLastClickedPosition mLastClickedPosition = position // find the image in your view and update it if(position==0){ ImageView imageView = view.findViewById(R.id.your_image); imageView.setImageResource(R.drawable.pause); } // play audio AudioListner.playRecord(position); } });
{ "pile_set_name": "StackExchange" }
Q: learning C#, need help understanding this code I am learning C# and I came to this "for" function and something really bothers me about it: int[] arrayNumbers = new int[numberAmmount]; // take "numberAmmount" as 5 so numberAmmount = 5; for (int i = 0; i < numberAmmount; i++) { Console.Write("{0} Number: ", i + 1); numberAmmount[i] = int.Parse(Console.ReadLine()); } Isn't "i++" in for function the same i as in the Console.Write "i + 1" Shouldn't i after the first cycle be 2? and after the second cycle be 4 because of the i + 1 in console.write??? Basically I am trying to get in a number from the user which will be the amount of numberAmmount and by this for function i give every numberAmmount[x] a value and then have my program decide the highest and the lowest number but I don't understand why the i + 1 doesn't add an extra 1 edit: got it thanks A: The syntax i + 1 does not have an assignment operator. That code is printing the value of i plus a constant. So when your loop is looping from 0...n Console.write is printing the counting value of each loop 1...n+1.
{ "pile_set_name": "StackExchange" }
Q: How to rotate a dynamically created ListBoxItem on a Canvas? In my WPF MVVM application I have a ListBox with Canvas as its ItemsPanel. The ListBox's items are dynamically created by the user when he clicks a button - the ListBox.ItemsSource is a list of items of my custom type stored in my MainViewModel which is the DataContext of my MainWindow. I would like the user to be able to rotate items using a set of Thumb controls attached to every ListBoxItem. So far I've had little success attempting to find a workable solution and I'm getting quite desperate. Here's the most important part of my ListBoxItem's Style: <Style TargetType="ListBoxItem"> <Setter Property="Canvas.Left" Value="{Binding X}"/> <Setter Property="Canvas.Top" Value="{Binding Y}"/> <Setter Property="Width" Value="{Binding Width}"/> <Setter Property="Height" Value="{Binding Height}"/> <Setter Property="FocusVisualStyle" Value="{StaticResource EmptyFocusVisualStyle}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem" > <Grid> <Control Name="RotateDecorator" Width="{Binding Width}" Height="{Binding Height}" Template="{StaticResource RotateDecoratorTemplate}" Visibility="Visible"/> <ContentPresenter x:Name="Content" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> And here you can see how it looks like: http://screenshooter.net/100101493/dhokpue The RotateDecorator is essentially merely a set of slightly customized Thumb controls (displayed as the little triangles around the selected item in the picture) which I'd like to rotate my ListBoxItem. But I've completely run out of ideas on how to do this. The only thing I know is that I need to write suitable DragDelta and DragStarted methods to serve as event handlers. Any ideas that could ease my exasperation? EDIT: Here are the DragStarted and DragDelta methods of the RotationThumb. Could they affect the way the moving Thumb is acting? DragStarted: private void RotateThumb_DragStarted(object sender, DragStartedEventArgs e) { var thumb = sender as RotateThumb; var parent = VisualTreeHelper.GetParent(thumb); for (int i = 0; i < 3; i++ ) { parent = VisualTreeHelper.GetParent(parent); } this.designerItem = parent as ListBoxItem; if (this.designerItem != null) { this.designerCanvas = VisualTreeHelper.GetParent(this.designerItem) as Canvas; if (this.designerCanvas != null) { this.centerPoint = this.designerItem.TranslatePoint( new Point(this.designerItem.Width * this.designerItem.RenderTransformOrigin.X, this.designerItem.Height * this.designerItem.RenderTransformOrigin.Y), this.designerCanvas); Point startPoint = Mouse.GetPosition(this.designerCanvas); this.startVector = Point.Subtract(startPoint, this.centerPoint); this.rotateTransform = this.designerItem.RenderTransform as RotateTransform; if (this.rotateTransform == null) { this.designerItem.RenderTransform = new RotateTransform(0); this.initialAngle = 0; } else { this.initialAngle = this.rotateTransform.Angle; } } } } DragDelta: private void RotateThumb_DragDelta(object sender, DragDeltaEventArgs e) { if (this.designerItem != null && this.designerCanvas != null) { Point currentPoint = Mouse.GetPosition(this.designerCanvas); Vector deltaVector = Point.Subtract(currentPoint, this.centerPoint); double angle = Vector.AngleBetween(this.startVector, deltaVector); RotateTransform rotateTransform = this.designerItem.RenderTransform as RotateTransform; rotateTransform.Angle = this.initialAngle + Math.Round(angle, 0); this.designerItem.InvalidateMeasure(); } } EDIT2: Problems Solved A: There are several ways, but here is some pseudo-code that might get you started: // for every drag event Point a = listboxitem center position (or wherever you want the rotation origin) Point b = position before drag Point c = position after drag // calculate and normalize vectors a-b and a-c Vector v1 = ( b - a ).Normalized(); Vector v2 = ( c - a ).Normalized(); // calculate angles for v1 and v2 (in radians) double a1 = Math.Atan2( v1.y, v1.x ); double a2 = Math.Atan2( v2.y, v2.x ); // the amount of rotation is then the difference between a1 and a2 // NOTE: there's a catch here, Atan2 returns angles = -π ≤ θ ≤ π, so // the values might wrap around, which you'll need to take care of too double angleInRadians = a2 - a1; double angleInDegrees = ( angleInRadians / Math.PI ) * 180.0; Then add this angle to the angle of a RotateTransform you put on the ListBoxItem.
{ "pile_set_name": "StackExchange" }
Q: pass multiple parameters to a javascript and update html content bases on both parameters + php loop I have form that uses jquery to fetch mysql data with an external php page. the script is essentially an autocomplete for an input field. trouble is that I have the input field in a loop, field ID is being determine by the counter '$i' in the loop. as such I want to pass the user entered value of the input box to the javascript along with the counter value '$i' so that the javascript can return the result to the correct input box in the loop. I hope that makes sense. the original and working code for a single input box is below: Javascript <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> HTML <div> <input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" /> </div> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> &nbsp; </div> </div> So what I want to do is pass the row number ($i) to the javascript as well so that it returns the value to the correct input box. My basic attempts at this are below [apologies for my lack of javascript skill :-) ] Javascript <script type="text/javascript"> function lookup(rownumber, inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("autocompleteperson.php", {queryString: ""+(inputString+rownumber)+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString'+'rownumber').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> PHP / HTML <table> <? for ( $i = 1; $i <=50; $i++ ) { ?> <tr> <td> <div> <input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(<? echo $i; ?>,this.value);" onblur="fill();" /> </div> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> &nbsp; </div> </div> </td> </tr> <? } ?> </table> The second part of the question would be getting the div suggestionbox to appear in the correct place as well. The same applies where I would like the name of the suggestionbox to append the row number '$i'. Any help would be appreciated. Kind Regards, UPDATED CODE javascript <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("autocompleteperson.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(rownumber, thisValue) { // add the rownumber as a parameter $('#inputString'+rownumber).val(thisValue); // remove the quotation marks setTimeout("$('#suggestions').hide();", 200); } </script> HTML/PHP <table> <? for ( $i = 1; $i <=50; $i++ ) { ?> <tr> <td> Job <? echo $i; ?></td> <td> <SELECT NAME=job<? echo $i; ?> id=job<? echo $i; ?> style="width:150px;border: 1px solid #2608c3;color:red"> <OPTION VALUE=0 ></option> <option> <?=$optionjobs?> </option> </SELECT> </td> <td> Person </td> <td> <div> <input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(<? echo $i; ?>,this.value);" onblur="fill(<? echo $i; ?>,this.value);" /> </div> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="upArrow.png" style="position: relative; top: -12px; left: 20px;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> &nbsp; </div> </div> </td> </tr> <? } ?> </table> A: first of all, in the basic code that works, you're calling fill() without giving any parameters whereas in the javascript, you're waiting for thisValue. Now for your problem, let's take your fill function and do some modifications function fill(rownumber, thisValue) { // add the rownumber as a parameter $('#inputString'+rownumber).val(thisValue); // remove the quotation marks setTimeout("$('#suggestions').hide();", 200); } and in the HTML file [...] <div> <input type="text" size="30" value="" id="inputString<? echo $i; ?>" onkeyup="lookup(<? echo $i; ?>,this.value);" onblur="fill(<? echo $i; ?>,this.value);" /> [...] simply add in the fill() function the needed parameters.
{ "pile_set_name": "StackExchange" }
Q: How can I set default value in select without duplicate in list I have select control in my web page: <select class="form-control" name="user"> <#list sbUsers as sbUser> <option value="${sbUser.login}">${sbUser.login}</option> </#list> </select> But I need set current user like default value. Current user contains in this list and in other variable. I tried this: <select class="form-control" name="user"> <option value="${userName}" selected >${userName}</option> <#list sbUsers as sbUser> <option value="${sbUser.login}">${sbUser.login}</option> </#list> </select> But this realization not working. When I open my web page I have current user like default value but in list values this user contains too. userCurrent(default) -user1 -user2 -user3 -userCurrent -user4 but I need userCurrent(default) -user1 -user2 -user3 -user4 A: <select class="form-control" name="user"> <option value="">All</option> <#list sbUsers as sbUser> <#if sbUser.login == userName> <option value="${sbUser.login}" selected>${sbUser.login}</option> <#else> <option value="${sbUser.login}">${sbUser.login}</option> </#if> </#list> </select>
{ "pile_set_name": "StackExchange" }
Q: Difference between executing php from the commandline and from the Http Side What is the difference between executing php from command line and from HTTP? Do they use the same executable such as (php.exe or php-cgi.exe ( Apache or IIS ))? Do the results differ when they are executing from command line or HTTP? A: No html markup in errors This is a php.ini setting(html_errors), but this defaults to off in the cli version. Logging to stderr Usually errors are logged to the webservers error.log, but in the cli version errors are written to stderr. This is also available as a php.ini setting(error_log) php.ini The php.ini file that is used for the cli version can be a different file. Which can lead to some nasty bugs (curl suddenly not available, etc). Different executables It's possible to install multiple version of php (php5 alongside php4) Use which php to determine which version you're using. Everything is shown as text var_dump() is readable without a <pre> No difference between header('Hello'); and echo('Hello');
{ "pile_set_name": "StackExchange" }
Q: Approximation of smooth surfaces with polygonal meshes I'm just getting started with Blender. It seems to be a nice tool, but like most 3D programs, it has a strange limitation: it seems to only render polygon meshes. A polygon mesh is of course a set of perfectly flat surfaces connected by perfectly straight edges. This is great for moddling man-made objects such as cubes, or for genuinely angular things such as crystals. But how the heck do you draw curved things? Of course, you can approximate any curve with a sufficient number of straight lines. But it's always a pretty crude approximation. You would need billions of polygons to produce a genuinely smooth-looking surface. Even if it were somehow possible to model that, the memory and render time requirements would be crazy. To get around this, most 3D programs have a button somewhere to blur out the surface normals, creating the illusion of actual curves. But it's just that — an illusion. The outline of the object still has raggid, sharp edges. The shadow of the object still has sharp edges. If two objects intersect, you can see all the straight lines where they meet, no matter how smooth the surface looks. And then I sat and watched Spring. And you know what? I don't recall seeing a single straight edge anywhere in the entire thing! So how's it done? Where is the secret button that lets you have curved surfaces? A: This is a very good question. It all comes down to fooling your brain. 1. “Approximating a curve with polygons is pretty crude” Well, human eyes have considerably limited resolution. Screen resolution also contributes - it isn't infinite. You don't need infinite polygons, just enough to fool the human eye. It's easier to do, than most people think. 2. “You would need billions of polygons for a smooth-looking surface” Smooth-looking is the key word. Surface needs far less geometry to look smooth, than a silhouette. Most of your focus is on surfaces, not silhouettes. 3. “I don't recall seeing a straight edge anywhere” Don't recall is the key phrase. You don't focus on details, but on the moving imagery. When you pause the animation, chances are you'll find some jagged edges. Try pausing older movies like Toy story 1, Shrek or Ice age. This is what Pixar understood first - you don't need it perfect. Just non-distracting. Fig. 02 - Surface of a low-poly object looks perfectly smooth, while it's silhouette is jagged
{ "pile_set_name": "StackExchange" }
Q: convert plain string to xml format using Linux command I want to convert "[email protected]" plain string to XML format string like "&#116;&#101;&#115;&#116;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;" https://coderstoolbox.net has exact function but i want to use Linux command to encode plain string. Is there easy way to convert that string to XML format string using Linux command? A: $ echo [email protected] | grep -o . | xargs -l1 -I{} printf "&#%d;" "'{}" &#116;&#101;&#115;&#116;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;
{ "pile_set_name": "StackExchange" }
Q: Using Intent, to enable GPS doens't always work correctly. How do I fix The below code enables me to turn the user's GPS on and off at will but at times this doesn't work correctly, although the icon for GPS scanning will be at the top of the screen in the user's notification bar the GPS icon will not be highlighted. Making verifications like (isProviderEnabled(LocationManager.GPS_PROVIDER);) not detect whether or not GPS is enabled. Code used to enable GPS: Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", true); sendBroadcast(intent); Screenshot: A: refer this link: Its sdk version problem. higher version doesnt support this intent. http://iamvijayakumar.blogspot.in/2013/08/disable-gps-via-programatically-in.html
{ "pile_set_name": "StackExchange" }
Q: What does "(test1, test2, test3="3", test4="4", test5 = "5", test6 = "6")" do? This question is based off some really odd code I recently found in a colleagues work. He claims not to know how it works only he copied it from somewhere else. That's not good enough for me, I want to understand what's going on here. If we have something like: (test1, test2, test3="3", test4="4") The result will be that test1 == "3", test2 == "4", test3 == nil and test4 == "4". I understand why this happens, but if we do something like: (test1, test2, test3="3", test4="4", test5 = "5", test6 = "6") now the result is test1 == "3", test2 == "4", test3 == "5", test4 == "4", test5 == "5", test6 == "6". Why isn't test5 == nil? A: It looks like it's executing like this: (test1, test2, test3) = ("3"), (test4 = "4"), (test5 = "5"), (test6 = "6") # Equivalent: test1 = "3" test2 = test4 = "4" test3 = test5 = "5" ; test6 = "6"
{ "pile_set_name": "StackExchange" }
Q: How to use UICollectionViewController in storyboard while still supporting ios 5.1? It is a best practice to detect if a certain feature's class exists and degrade user's features depending on availability. I created UICollectionView in storyboard and a standard tableview to support ios 5.1 users. I then simply check if the user has this feature and segue to the appropriate scene. However, when I now try to compile my code I get a "dyld: Symbol not found: _UICollectionElementKindSectionHeader" This seems very anti-pattern of apple to not allow ios6.0 features in storyboard with a ios 5.1 deployment target. if ([UICollectionView class]) { [self performSegueWithIdentifier:@"UserShow" sender:self]; } else { [self performSegueWithIdentifier:@"UserShowTable" sender:self]; } The above seems like a pretty reasonable approach to me... A: I know this is not proper to put only link answers but her it is not possible to include the whole files. Please see this. A controller is designed to provide the same functionality as UICollectionController of iOS 6 but still supports to iOS 4/5 What developer is telling PSTCollectionView Open Source, 100% API compatible replacement of UICollectionView for iOS4.3+ You want to use UICollectionView, but still need to support iOS4/5? Then you'll gonna love this project. I've originally written it for PSPDFKit, my iOS PDF framework that supports text selection and annotations, but this project seemed way to useful for others to to keep it for myself :) Plus, I would love the influx of new gridviews to stop. Better just write layout managers and build on a great codebase. The goal is to use PSTCollectionView on iOS 4/5 as a fallback and switch to UICollectionView on iOS6. We even use certain runtime tricks to create UICollectionView at runtime for older versions of iOS. Ideally, you just link the files and everything works on older systems. Practically, it's not that easy, and especially when you're using subclasses of UICollectionView-classes, since they can't be replaced at runtime. A: You can't. As soon as you drop the collections view controller to the storyboard, it will try to reference it automatically, what will result in the compilation error you've got.
{ "pile_set_name": "StackExchange" }
Q: How do I fetch the VLAN tags using libpcap and C? I am trying to parse a pcap file including different type of Network Packets (some are tagged as VLAN and some aren't) using #include . here is my code so far: pcap_t *pcap; const unsigned char *packet; char errbuf[PCAP_ERRBUF_SIZE]; struct pcap_pkthdr header; pcap = pcap_open_offline(argv[0], errbuf); if (pcap == NULL) { fprintf(stderr, "error reading pcap file: %s\n", errbuf); exit(1); } while ((packet = pcap_next(pcap, &header)) != NULL) { struct ip_header *ip; unsigned int IP_header_length; packet += sizeof(struct ether_header); capture_len -= sizeof(struct ether_header); ip = (struct ip_header*) packet; IP_header_length = ip->vhl * 4; /* ip_hl is in 4-byte words */ char *sinfo = strdup(inet_ntoa(ip->src)); char *dinfo = strdup(inet_ntoa(ip->dst)); printf ("%s<-__->%s\n", sinfo ,dinfo); free (sinfo); free (dinfo); } There must be somewhere in the code to check the VLAN and jump over them correctly.How should I distinguish VLAN packets from non-VLANS? A: (If you are testing this on a 'live' environment, it's important to remember that routers can remove 802.1q tags before forwarding to a non-trunking line.) If you have a particular platform & protocol in mind, the fastest way to do this will always be to 'manually' check a frame: htonl( ((uint32_t)(ETH_P_8021Q) << 16U) | ((uint32_t)customer_tci & 0xFFFFU) ) T However, libpcap provides for a portable & clean packet filters in the form of functions for compiling a BPF filters and applying those to a stream of packets (although it is important to note that there are different sets of functions for on-the-wire vs. offline filtering) In this fashion, We can use pcap_offline_filter to apply the compiled BPF filter directive to a PCAP file. I've used the filter expression vlan here, you may want something else like vlan or ip. If you need something more complex, you can consult the documentation) ... pcap_t *pcap; char errbuf[PCAP_ERRBUF_SIZE]; const unsigned char *packet; struct pcap_pkthdr header; struct bpf_program fp; // Our filter expression pcap = pcap_open_offline(argv[0], errbuf); if (pcap == NULL) { fprintf(stderr, "error reading pcap file: %s\n", errbuf); exit(1); } // Compile a basic filter expression, you can exam if (pcap_compile(pcap, &fp, "vlan", 0, net) == -1) { fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); return 2; } while ((packet = pcap_next(pcap, &header) != NULL) && pcap_offline_filter(&fp, header, packet)) { struct ip_header *ip; unsigned int IP_header_length; packet += sizeof(struct ether_header); capture_len -= sizeof(struct ether_header); ip = (struct ip_header*) packet; IP_header_length = ip->vhl * 4; /* ip_hl is in 4-byte words */ char *sinfo = strdup(inet_ntoa(ip->src)); char *dinfo = strdup(inet_ntoa(ip->dst)); printf ("%s<-__->%s\n", sinfo ,dinfo); free (sinfo); free (dinfo); } ...
{ "pile_set_name": "StackExchange" }
Q: In Python how to pipe a string into an executables stdin? On Windows I have a program (prog.exe) that reads from stdin. In python I want to pipe a string as the input to its stdin. How to do that? Something like: subprocess.check_output("echo {0} | myprog.exe".format(mystring)) or (to make the args a list) subprocess.check_output("echo {0} | myprog.exe".format(mystring).split()) doesn't seem to work. It gave me: WindowsError: [Error 2] The system cannot find the file specified I also tried to use the "stdin" keyword arg with StringIO (which is a file-like object) subprocess.check_output(["myprog.exe"], stdin=StringIO(mystring)) Still no luck - check_output doesn't work with StringIO. A: You should use Popen communicate method (docs). proc = subprocess.Popen(["myprog.exe"], stdin=subprocess.PIPE) stdout, stderr = proc.communicate('my input')
{ "pile_set_name": "StackExchange" }
Q: What should I tell other people about giving money to a Beggar? This question asks whether, what, or how to tell other people about giving money to a beggar. Scenario I was seated inside the bus today and I saw a man begging for while selling some incense sticks boxes and he was wearing a mask for an unknown reason. Firstly it occurred to me whether it's worthwhile to donate some amount to him. Them it occurred that drop by drop only the pot will be filled. So I decided to donate some and I was suppose to give the bus ticket money to the conductor. I had some hundred notes and a 20 rupee note. I was thinking whether to give a 100 rupee note to the beggar at first and then I thought of donating the 20 rupee to the beggar and pay the conductor with a 100 rupee so that I could have change. Both the beggar and the conductor arrived near my seat and I was having both notes on my hand. (I was holding the phone from the other hand). I tried to give the 20 ripped to the beggar and the conductor unknowingly reached his hand to the 20 rupee note and asked where I was going to. I was about confused on what to do and then I settled my mind thinking "It's fine. Let the beggar have the 100 and let him do something beneficial with it". After saying where I was going I donated the 100 rupee to the beggar. This incident happened very fast. And at the instance I let go of the typical craving for the small 100 rupee note so that I could fulfill the charity purely. And after that the conductor told me not to give that sort of large amount to them. I smiled and, unshaken in my intention, I continued on the journey. Question My question is this: I'm not sure whether the beggar was virtuous or not; but I know for a fact that only drop by drop a pot can be fulfilled. So the question is, if this sort of a situation were to arise another time, should I instruct the other person (in this case the conductor) on what the intention and the situation was, or just shut up and mind my business? May the Triple Gem bless you. A: The Buddha has mentioned that it is the givers qualities that matters most in giving. He says for example that if he were to receive something from Ven. Sariputta, that would not be as meritorious as if he gave the same thing to Ven. Sariputta. So, if you are a person with Arya qualities, as long as your giving is also Arya, the effects will be much greater than that dictated by the receivers qualities. Arya giving is letting go at a distance.
{ "pile_set_name": "StackExchange" }
Q: CMake can't find X11 I'm trying to compile Minetest 0.4.10 on Ubuntu 12.04.3 LTS with CMake, but I get this error: andrew@rasts-tv:~$ cmake \Minetest-0.4.10 -- *** Will build version 0.4.10 *** -- IRRLICHT_SOURCE_DIR = -- IRRLICHT_INCLUDE_DIR = IRRLICHT_INCLUDE_DIR-NOTFOUND -- IRRLICHT_LIBRARY = IRRLICHT_LIBRARY-NOTFOUND -- Could NOT find IRRLICHT (missing: IRRLICHT_LIBRARY IRRLICHT_INCLUDE_DIR) -- CURL_INCLUDE_DIR = CURL_INCLUDE_DIR-NOTFOUND -- CURL_LIBRARY = CURL_LIBRARY-NOTFOUND -- CURL_DLL = -- GetText disabled CMake Error at /usr/share/cmake-2.8/Modules/FindX11.cmake:411 (MESSAGE): Could not find X11 Call Stack (most recent call first): src/CMakeLists.txt:147 (find_package) -- Configuring incomplete, errors occurred! I installed LXDE (Lightweight X11 Desktop Environment), but it still shows the same error. What should I do? This is the error message I got after installing the x11 header files: andrew@rasts-tv:~$ cmake \Minetest-0.4.10 -- *** Will build version 0.4.10 *** -- IRRLICHT_SOURCE_DIR = -- IRRLICHT_INCLUDE_DIR = IRRLICHT_INCLUDE_DIR-NOTFOUND -- IRRLICHT_LIBRARY = IRRLICHT_LIBRARY-NOTFOUND -- Could NOT find IRRLICHT (missing: IRRLICHT_LIBRARY IRRLICHT_INCLUDE_DIR) -- CURL_INCLUDE_DIR = CURL_INCLUDE_DIR-NOTFOUND -- CURL_LIBRARY = CURL_LIBRARY-NOTFOUND -- CURL_DLL = -- GetText disabled CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:91(MESSAGE): Could NOT find OpenGL (missing: OPENGL_gl_LIBRARY) Call Stack (most recent call first): /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:252(_FPHSA_FAILURE_MESSAGE) /usr/share/cmake-2.8/Modules/FindOpenGL.cmake:153 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) src/CMakeLists.txt:148 (find_package) -- Configuring incomplete, errors occurred! A: LXDE and X11 are not quite the same thing. You probably need the X11 header files. Try installing libx11-dev: sudo apt-get install libx11-dev
{ "pile_set_name": "StackExchange" }
Q: Translation of La Prise de la Bastille (song) What is the translation of the old revolutionary song “La Prise de la Bastille”, particularly the following phrase: R’li r’lan r’lan tan plan Tire lire en plan The lyrics can be found here and a recording from YouTube here. The ”r’li” construction looks like nothing else I have seen in French and I would like to know where it comes from. A: There is no possible translation of "R’li r’lan r’lan tan plan Tire lire en plan"; it's just as what you find in "Little drummer Boy", as reproduced below. However, as is suggested in the comments (jlliagre) a rendering might eventually be decided upon. Pa ra pam pam pam Ra pum pum pum, Ra pum pum pum A longer extract from that song shows that this is not translated. Come they told me Venez ils m'ont dit Pa ra pum pum pum A new born king to see Qu'un nouveau-né roi est à voir Pa ra pum pum pum Our finest gifts we bring Nos plus beaux cadeaux nous apportons Pa ra pum pum pum To lay before the king Pour poser devant le roi Pa ra pam pam pam Ra pum pum pum, Ra pum pum pum Very probably "R’li r’lan r’lan tan plan" has been made up to reproduce the sound of drums; as we find an R-sound in sound of the drums for "Little Drummer Boy" we also find one in the mimicked sound of the drums in this revolutionary song. "Tire lire" in "Tire lire en plan" has nothing to do with "tirelire", that is "piggybank"; again, those words are merely words used for rhyming sounds. I'm aware of no translation of the song, but I could make one up; here it is below. Firmly forging ahead in triumph The burgher at the sound of drums Is marching to the Bastille And everywhere is felt his ardour (The burgher and the merchant Are marching to the Bastille) Citizens of all walks of life Behind the flying colours Are marching forth undaunted Nothing cows them down On all sides can be heard The sounds of thundering brass Aimed at the citadel O! fatal Bastille! Thou will before long Thou will before long Yield to the triumphant arms Of your besiegers Get out of your funereal dungeons Victims of a detested rule See through the darkness Liberty's rays For too long gloomy sadness Filled your hearts with poison Bathe in tears of joy Your liberators brow
{ "pile_set_name": "StackExchange" }
Q: Could anyone please examplify the garden path model in german? I want to bring forth some examples of the garden path model in German and am reading the Wikipedia page but get stuck on the examples, for example, Welche Politikerin hat die Minister getroffen? If I am not wrong, it means "Which politician did the ministers meet?". It seems that in English the sentence is alright with no any ambiguity. Could anyone please explain it a bit to me? Thanks. A garden path sentence, such as “The old man the boat” (meaning “Old people are the crew of the boat”), is a grammatically correct sentence that starts in such a way that a reader’s most likely interpretation will be incorrect; the reader is lured into a parse that turns out to be a dead end or yields a clearly unintended meaning. (Wikipedia: Garden path sentence) In German it is called Holzwegeffekt, see Wikipedia: Holzwegeffekt A: Welche Politikerin hat die Minister getroffen? Which (female) politician has met the ministers? Consider: Welche Politikerin hat der Minister getroffen? Which (female) politician has been met by the (male) minister? The "Holzweg" is assuming the (female) politician is the object, because Welche is usually introducing an accusative object, not the subject. This is cleared up as soon the article is heard, because its case, number and gender doesn't match that "Holzweg".
{ "pile_set_name": "StackExchange" }
Q: Git history - find lost line by keyword I had somewhere in my Git repository a line containing the word "Foo" a couple of hundreds commits before. If there is any way to find its revision number where it was the last time without buying FishEye? A: That may be addressed by the pickaxe (-S) option of gitlog git log -SFoo -- path_containing_change (you can even add a time range: --since=2009.1.1 --until=2010.1.1) -S<string> Look for differences that introduce or remove an instance of <string>. Note that this is different than the string simply appearing in diff output; see the pickaxe entry in gitdiffcore(7) for more details. diffcore-pickaxe This transformation is used to find filepairs that represent changes that touch a specified string. When diffcore-pickaxe is in use, it checks if there are filepairs whose "original" side has the specified string and whose "result" side does not. Such a filepair represents "the string appeared in this changeset". It also checks for the opposite case that loses the specified string. Update 2014: Since then, you can do (from nilbus's answer): git log -p --all -S 'search string' git log -p --all -G 'match regular expression' These log commands list commits that add or remove the given search string/regex, (generally) more recent first. The -p (--patch) option causes the relevant diff to be shown where the pattern was added or removed, so you can see it in context. Having found a relevant commit that adds the text you were looking for (eg. 8beeff00d), find the branches that contain the commit: git branch -a --contains 8beeff00d (I reference that last command in "How to list branches that contain a given commit?")
{ "pile_set_name": "StackExchange" }
Q: Get nETBIOSName from a UserPrincipal object I am using the System.DirectoryServices.AccountManagement part of the .Net library to interface into ActiveDirectory. Having called GetMembers() on a GroupPrincipal object and filter the results, I now have a collection of UserPrincipal objects GroupPrincipal myGroup; // population of this object omitted here foreach (UserPrincipal user in myGroup.GetMembers(false).OfType<UserPrincipal>()) { Console.WriteLine(user.SamAccountName); } The above code sample will print out usernames like "TestUser1". I need to compare these to a list coming from another application in "DOMAIN\TestUser1" format. How do I get the "DOMAIN" part from the UserPrincipal object? I can't just append a known domain name as there are multiple domains involved and I need to differentiate DOMAIN1\TestUser1 and DOMAIN2\TestUser2. A: You have two choices that I can think of. Parse, or take everything that is on, the right of [email protected]; Use the System.DirectoryServices namespace. I don't know about UserPrincipal, neither do I about GroupPrincipal. On the other hand, I know of a working way to achive to what you want. [TestCase("LDAP://fully.qualified.domain.name", "TestUser1")] public void GetNetBiosName(string ldapUrl, string login) string netBiosName = null; string foundLogin = null; using (DirectoryEntry root = new DirectoryEntry(ldapUrl)) Using (DirectorySearcher searcher = new DirectorySearcher(root) { searcher.SearchScope = SearchScope.Subtree; searcher.PropertiesToLoad.Add("sAMAccountName"); searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", login); SearchResult result = null; try { result = searcher.FindOne(); if (result == null) if (string.Equals(login, result.GetDirectoryEntry().Properties("sAMAccountName").Value)) foundLogin = result.GetDirectoryEntry().Properties("sAMAccountName").Value } finally { searcher.Dispose(); root.Dispose(); if (result != null) result = null; } } if (!string.IsNullOrEmpty(foundLogin)) using (DirectoryEntry root = new DirectoryEntry(ldapUrl.Insert(7, "CN=Partitions,CN=Configuration,DC=").Replace(".", ",DC=")) Using DirectorySearcher searcher = new DirectorySearcher(root) searcher.Filter = "nETBIOSName=*"; searcher.PropertiesToLoad.Add("cn"); SearchResultCollection results = null; try { results = searcher.FindAll(); if (results != null && results.Count > 0 && results[0] != null) { ResultPropertyValueCollection values = results[0].Properties("cn"); netBiosName = rpvc[0].ToString(); } finally { searcher.Dispose(); root.Dispose(); if (results != null) { results.Dispose(); results = null; } } } Assert.AreEqual("INTRA\TESTUSER1", string.Concat(netBiosName, "\", foundLogin).ToUpperInvariant()) } Other related information or links available in this SO question. C# Active Directory: Get domain name of user? How to find the NetBIOS name of a domain
{ "pile_set_name": "StackExchange" }
Q: Carousel View in Xamarin Forms NOT Loading different Templates public DataTemplate CreateQuestionAnswerRadioButtonTemplate(string question, List<string> answers){ DataTemplate template = new DataTemplate(() => { StackLayout parentLayout = new StackLayout() { Padding = new Thickness(20, 20, 20, 20), HeightRequest = 500, }; ScrollView surveyScrollView = new ScrollView() { Orientation = ScrollOrientation.Vertical, }; StackLayout questionLayout = new StackLayout() { Padding = new Thickness(5, 5, 5, 5), HeightRequest = 500, }; Label questLabel = new Label(); questLabel.Text = question; questLabel.TextColor = Color.FromHex("#EF4D80"); questLabel.FontAttributes = FontAttributes.Bold; questLabel.FontSize = 18; BindableRadioGroup radioGroup = new BindableRadioGroup(false); radioGroup.ItemsSource = answers; questionLayout.Children.Add(questLabel); questionLayout.Children.Add(radioGroup); surveyScrollView.Content = questionLayout; parentLayout.Children.Add(surveyScrollView); return parentLayout; }); return template; } Adding these Data Templates to a List. new CarouselView { Margin = new Thickness(0, 20, 0, 0), ItemsSource = dataTemplates, ItemTemplate = dataTemplates[0], }; Now when I swipe the Carousel, How do I load dataTemplates[1 or 2 or 3] ?? I have a Next Button in which in am setting the item source of the Carousel View to dataTemplates[1] but the template does not get updated Pls Suggest the right approach ? dataTemplates = new List<DataTemplate>(); dataTemplates.Add(CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_1, SurveyQuestion_1_Answers)); dataTemplates.Add(CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_3, SurveyQuestion_3_Answers)); dataTemplates.Add(CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_4, SurveyQuestion_4_Answers)); dataTemplates.Add(CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_5, SurveyQuestion_5_Answers)); A: You need a DataTemplateSelector for your CarouselView. in your code behind of the page: new CarouselView { Margin = new Thickness(0, 20, 0, 0), ItemsSource = dataTemplates, ItemTemplate = new SurveyDataTemplateSelector() }; SurveyDataTemplateSelector DataTemplate survey1Template; DataTemplate survey3Template; DataTemplate survey4Template; DataTemplate survey5Template; public SurveyDataTemplateSelector() { survey1Template = CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_1, SurveyQuestion_1_Answers); survey3Template = CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_3, SurveyQuestion_3_Answers); survey4Template = CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_4, SurveyQuestion_4_Answers); survey5Template = CreateQuestionAnswerRadioButtonTemplate(Constants.SurveyQuestion_5, SurveyQuestion_5_Answers); } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { // Here you define which DataTemplate is selected, for example: if (item == null) { return null; } SurveyAnswers answers = item as SurveyAnswers; if (answers.question == 1) { return survey1Template; } else if (answers.question == 3) { return survey3Template; } else if (answers.question == 4) { return survey4Template; } else if (answers.question == 5) { return survey5Template; } return null; } Check this link for a good documentation by Xamarin: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/templates/data-templates/selector/
{ "pile_set_name": "StackExchange" }
Q: Creating an association list with element evaluation So as far as I understand it you create association lists that look like '((rose . red) (violet . violet) (chrysanthemum . who-knows)) My question is, what do you do if you want rose, violet, etc., to be evaluated before they're put into the alist? For example, for normal lists you can do (list 1 2 3 4) instead of '(1 2 3 4) How do you replicate this functionality? I'm new to elisp and Emacs, so please forgive any errors or misnomers. A: Here you go: (list (cons rose red) (cons violet violet) (cons chrysanthemum who-knows)) each flower should be bound to a value.
{ "pile_set_name": "StackExchange" }
Q: Spring basic security confiugred userid/password not working Our application is based on Spring-boot 2.0. I've enabled basic security by adding the following dependency to pom.xml: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> <version>2.0.4.RELEASE</version> </dependency> I also have added properties so that I can define my own userid and password for basic security, instead of the generated ones. I defined them like this in /resources/applicaiton.properties file: security.user.name=user1 security.user.password=pass1 When I startup my application, I can see that is still generates the password for me in the log. Also, I am unable to login using user1/pass1 combination. I can only successfully login with the user=user and password=generated-password-from-log file. Why won't spring security allow me to login with user1/pass1? What could be the problem? A: Those properties need the spring prefix. spring.security.user.name=user # Default user name. spring.security.user.password= # Password for the default user name. If I want to configure something I often take a look at this List I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Opening .exe from java Codes Here is my code I wanted to open ODBC bridge through Java Code: try{ Runtime r = Runtime.getRuntime(); Process p = null; try{ String s = "C://windows/System32/odbcad32.exe"; p=r.exec(s); }catch(Exception ex){ System.out.println(ex.getMessage()); } }catch(Exception ex) { System.out.println(ex.getMessage()); } and here is the problem which I am facing Cannot run program "C://windows/System32/odbcad32.exe": CreateProcess error=740, The requested operation requires elevation A: Are you trying to edit the connections in odbcad32? If so I can't help you there, I have in my own projects caught the SQLException and used the Desktop class to open obdcad32 like: Desktop.getDesktop().open(new File("C:\\Windows\\SysWOW64\\odbcad32.exe")); That will open obdcad32 on 64bit systems if connecting to an access database. If your able to connect with 64 bit drivers then you can discard the SysWOW64 folder and replace it with System32 (or if using a 32 bit system.
{ "pile_set_name": "StackExchange" }
Q: Equality of GDI+ Regions Why does the assertion fail in the following code? Why aren't regions a and b equal? Region a = new Region(new RectangleF(0.0f, 0.0f, 10.0f, 10.0f)); Region b = new Region(); b.MakeEmpty(); b.Union(new RectangleF(0.0f, 0.0f, 10.0f, 10.0f)); Debug.Assert(a == b, "Regions not equal"); A: From what I can see, System.Drawing.Region does not override Object's implementation of Equals(). Therefore your == call is using ReferenceEquals and simply telling you a and b are not the same object. Try using the System.Drawing.Region.Equals(Region, Graphics) overload instead, passing in a Graphics object in the context you wish to compare the two regions.
{ "pile_set_name": "StackExchange" }
Q: How to split Nest.js microservices into separate projects? Let's say I want to create a simplistic cinema-management platform. It needs few microservices: movies, cinemas, payments, etc. How would you go about doing it in Nest.js? I don't want them in the same big folder as that feels like making a monolith. I want them to be separate Nest.js projects with their own git repositories so I can orchestrate them with Kubernetes later on. How? How to connect from service cinemas to service movies if they are two separate projects and only share, let's say, Redis? Edit: This is not a question about microservices in general. This is a question Nest.js specific. I read the documentation, I know there are decorators like @Client for connecting to the transport layer. I just want to know where to use that decorator and maybe see a short snippet of code on "having two separate Nest.js repositories how to connect them together so they can talk to each other". I don't care about the transport layer, that thing I can figure out myself. I just need some advice on the framework itself as I believe the documentation is lacking. A: I got it working. Basically the way to do it is to create two separate projects. Let's say - one is a createMicroservice and another is just an HTTP app (but could easily be another microservice). I used a "normal" app just so I can call it easily for testing. Here is the main.ts file that creates microservice. import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { Transport } from '@nestjs/common/enums/transport.enum'; async function bootstrap() { const app = await NestFactory.createMicroservice(AppModule, { transport: Transport.REDIS, options: { url: 'redis://localhost:6379', }, }); await app.listen(() => console.log('MoviesService is running.')); } bootstrap(); And one of the controllers: @Controller() export class AppController { constructor(private readonly appService: AppService) {} @MessagePattern({ cmd: 'LIST_MOVIES' }) listMovies(): string[] { return ['Pulp Fiction', 'Blade Runner', 'Hatred']; } } Now - in the microservice you declare to what kinds of events should controllers react to (@MessagePattern). While in the "normal" service you do this in the controller when you want to ask other microservices for something (the main.ts is the simplest example that you get when you create a new project using @nestjs/cli. The controller code: @Controller() export class AppController { private readonly client: ClientProxy; constructor(private readonly appService: AppService) { this.client = ClientProxyFactory.create({ transport: Transport.REDIS, options: { url: 'redis://localhost:6379', }, }); } @Get() listMovies() { const pattern = { cmd: 'LIST_MOVIES' }; return this.client.send<string[]>(pattern, []); } } So as long a client is connected to the same transport layer as the microservice - they can talk to each other by using the @MessagePattern. For nicer code you can move the this.client part from a constructor to a provider and then use dependency injection by declaring the provider in the module.
{ "pile_set_name": "StackExchange" }
Q: Is a paradoxical partition of a set smaller than the power set of that set? When it is said that almost every model of $\sf ZF + \neg AC$ do have paradoxical partitioning $\sf PP$, that is: there exists a set $X$ and a partition $P$ of $X$ that is strictly larger than $X$. Is it also provable that: $$|P|<|\mathcal P(X)| \text{ ?}$$ A: Yes. Note that trivially $|P|\leq|\mathcal{P}(X)|$ since $P\subseteq\mathcal{P}(X)$. If $|P|=|\mathcal{P}(X)|$, then we can define a surjection $X\to\mathcal{P}(X)$ by mapping each element of $X$ to the element of $P$ that contains it and then composing with a bijection $P\to\mathcal{P}(X)$. This is impossible by Cantor's theorem. A: Yes. If $P$ is a partition of $X$, then $$|P|\lt|\mathcal P(P)|\le|\mathcal P(X)|$$ by virtue of Cantor's theorem and the obvious injection $\mathcal P(P)\to\mathcal P(X)$. A: We can say a bit more. Note that if there is a surjection $f:A\to B$ then $f^{-1}:\mathcal P(B)\to\mathcal P(A)$ is an injection. Also, if $g:C\to D$ is an injection and $C\ne\emptyset$, then mapping $D\smallsetminus g[C]$ to a fixed point of $C$ and everything else to their preimage by $g$ is a surjection from $D$ to $C$. It follows that if $\sim$ is an equivalence relation on a set $X$ and $|X/{\sim}|>|X|$, then there are surjections from $X$ onto $X/{\sim}$ and also from $X/{\sim}$ onto $X$, and therefore there are injections from $\mathcal P(X)$ into $\mathcal P(X/{\sim})$ and vice versa. But then $|\mathcal P(X)|=|\mathcal P(X/{\sim})|$.
{ "pile_set_name": "StackExchange" }
Q: Find the index of a string in Javascript with help of first three characters I have numerous tsv files each with header row. Now one column name in header row is age. In few files, column name is age while in other files it has EOL charcter such as \r \n. Now how can i use str.indexOf('age') function so that i get index of age irrespective of column name age with EOL character such as \n , \r etc.. Foe eg: tsv file1: Name Address Age Ph_Number file 2: Name Address Age/r file 3: Name Address Age\n I am trying to find index of age column in each files header row. However when i do- header.indexOf('age') it gives me result only in case of file1 because in other 2 files we have age as age\r and age\n.. My question is how should i find index of age irrespective of \r \n character along with age in header row. i have following script now: var headers = rows[0].split('\t'); if (file.name === 'subjects.tsv'){ for (var i = 0; i < rows.length; i++) { var ageIdColumn = headers.indexOf("age"); console.log(headers) A: As I stated in the comments, indexOf() returns the starting position of the string. It doesn't matter what comes after it: var csvFile1 = 'column1,column2,column3,age,c1r1'; var csvFile2 = 'column1,column2,column3,age\r,c1r1'; var csvFile3 = 'column1,column2,column3,age\n,c1r1'; console.log(csvFile1.indexOf("age")); console.log(csvFile2.indexOf("age")); console.log(csvFile3.indexOf("age")); If you specifically want to find the versions with the special characters, just look for them explicitly: var csvFile4 = 'column1,age\r,column2,column3,age\n,c1r1'; console.log(csvFile4.indexOf("age\r")); console.log(csvFile4.indexOf("age\n")); Lastly, it may be that you are confused as to what, exactly indexOf() is supposed to do. It is not supposed to tell you where all occurrences of a given string are. It stops looking after the first match. To get all the locations, you'd need a loop similar to this: var csvFile5 = 'column1,age\r,column2,age, column3,age\n,c1r1'; var results = []; // Found indexes will be stored here. var pos = null; // Stores the last index position where "age" was found while (pos !== -1){ // store the index where "age" is found // If pos is not null, then we've already found age earlier and we // need to start looking for the next occurence 3 characters after // where we found it last time. If pos is null, we haven't found it // yet and need to start from the beginning. pos = csvFile5.indexOf("age", pos != null ? pos + 3 : pos ); pos !== -1 ? results.push(pos) : ""; } // All the positions where "age" was in the string (irrespective of what follows it) // are recorded in the array: console.log(results);
{ "pile_set_name": "StackExchange" }
Q: Copy constructor Class instantiation Here is my class that implements copy constructor public class TestCopyConst { public int i=0; public TestCopyConst(TestCopyConst tcc) { this.i=tcc.i; } } i tried to create a instance for the above class in my main method TestCopyConst testCopyConst = new TestCopyConst(?); I am not sure what i should pass as parameter. If i have to pass a instance of TestCopyConst then again i have to go for "new" which in turn will again prompt for parameter TestCopyConst testCopyConst = new TestCopyConst(new TestCopyConst(?)); what is missing here? or the concept of copy constructor is itself something different? A: You're missing a constructor that isn't a copy constructor. The copy constructor copies existing objects, you need another way to make them in the first place. Just create another constructor with different parameters and a different implementation.
{ "pile_set_name": "StackExchange" }
Q: How to disable colorbar in yhat's python ggplot? How does one disable colorbar in a plot like so: ggplot( aes(x='X', y='Y', color='C'), data=data_df ) + geom_line() + facet_grid("U", "V") The problem is that C is of a large cardinality and the point of the plot is just to see the various shapes altogether and not to label them. A: This is no direct answer, but after checking the github I don't think it is implemented yet. I would advise you to use plotnine, which is also a ggplot wrapper for mpl - but still under development. E.g.: from plotnine import * from plotnine import data (ggplot(data.mtcars, aes('wt', 'mpg', color='factor(gear)')) + geom_point(show_legend = False))
{ "pile_set_name": "StackExchange" }
Q: Windows 7 Window behavior in Ubuntu? Is it possible to get the windows 7 window behavior in ubuntu? The specific part I'm talking about is the gestures thing where you can throw your window to one side and have it resize to take up that side, or to the top and have it maximize. A: Not sure exactly if it does this or not but the Compiz desktop effects should come built in now with the latest ubuntu distros, you might want to download the Compiz manager (which I don't think is installed automatically) which will allow you to toggle all kinds of behaviour. The compiz window manager gives all kinds of whizz bang desktop effects!!
{ "pile_set_name": "StackExchange" }
Q: Is there any way to export the html page's data into PDF? I have an html page which contains multiple selectboxes, labels, input fields and checkboxes. I want to export entire html page into PDF. is there any way I can do so? Any javascript or library for exporting HTML into PDF? A: If you absolutely need to do generate your PDF using Javascript, you can use JsPDF : var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.addPage(); doc.text(20, 20, 'Do you like that?'); // Output as Data URI doc.output('datauri'); But you will have to recreate your html page with the library's syntaxe. If generating your document don't necessary have to be done with Javascript, a better way would be to use a php library. In the past I used (DomPdf)[https://github.com/dompdf/dompdf] : very powerfull. It just take a HTML/CSS document and create a PDF version of it. If you absolutely need a non-refresh loading, you can use Ajax to generate the document.
{ "pile_set_name": "StackExchange" }