text
stringlengths
64
89.7k
meta
dict
Q: phantomjs cannot find module webpage in node's child process I'm trying to run phantomjs in a node child process. Phantomjs complains it can not find module 'webpage'. Running the script from the cli works fine: phantomjs script.js I stripped the problem down to these two files: main.js: var script = require('./script'); var cp = require('child_process'); cp.exec('/usr/bin/phantomjs script.js'); script.js var page = require('webpage').create(); page.open("http://www.google.com", function(status) { console.log("opened google? ", status); var title = page.evaluate(function(s) { return s; }, 'Hello'); console.log(title); phantom.exit(); }); Running the following command fails: node main.js with error: module.js:340 throw err; ^ Error: Cannot find module 'webpage' I've tried to specify the working directory in cp.exec as an option without effect. Is there a way to set the node search path for modules in a global context so it can be found in a new node process? Or am I doing something else wrongly? A: PhantomJS is not a node.js module and cannot be directly used from node. I think you understand this, because you try to invoke it via child_process. The problem is the line var script = require('./script');. As I understand, it is the phantomjs script. Since node.js doesn't have a webpage module, but phantomjs does the require fails and everything with it. Simply remove the line. It doesn't seem like you use it anyway.
{ "pile_set_name": "StackExchange" }
Q: Find SSL version in TCP-packets in established TCP-connection is it possible to see the used SSL-Version in a TCP-dump in an established TCP-connection without killing the connection and re-establishing it to capture the "Client Hello"? If yes, where can I find it? BR and thanks in advance. A: Yes, absolutely, that is possible. The TLS record header is not encrypted. The two-octet version field is located at offset 1 in the TLS record header. Assuming a TLS record was not split into multiple TCP segments (which in practice is usually the case but cannot be relied upon), the second and third byte within the TCP payload indicate the TLS version used, e.g. 0x03 0x01 for TLS 1.0 or 0x03 0x03 for TLS 1.2. For more details, refer to the respective RFCs, e.g. RFC 5246 6.2.3 for the format of the TLS 1.2 record layer for encrypted payloads. Wireshark and its command line companion tshark will show you the decoded TLS version of any given TLS record as you would expect. To show that using tcpdump, you can use -x to get a hex dump and find offset 1 within the TCP data after removing the IP and TCP headers.
{ "pile_set_name": "StackExchange" }
Q: Load balancing tick After Ubuntu upgrade (some time ago, from rather ancient version), my Lenovo S10 netbook fan does not stop. $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 10.10 Release: 10.10 Codename: maverick $ uname -a Linux agladysh-s10 2.6.35-23-generic #41-Ubuntu SMP Wed Nov 24 10:18:49 UTC 2010 i686 GNU/Linux PowerTop reports high number of [kernel scheduler] Load balancing tick wakeups. I remember reading somewhere that this is a known issue in recent kernels. Any advice? PowerTOP version 1.13 (C) 2007 Intel Corporation Cn Avg residency P-states (frequencies) C0 (cpu running) ( 2.7%) 1.60 Ghz 2.4% polling 0.0ms ( 0.0%) 1333 Mhz 0.0% C1 mwait 23.6ms (41.5%) 1067 Mhz 0.0% C2 mwait 1.5ms ( 7.5%) 800 Mhz 97.6% C4 mwait 1.4ms (48.3%) Wakeups-from-idle per second : 403.7 interval: 1.2s no ACPI power usage estimate available Top causes for wakeups: 32.1% ( 70.0) [kernel scheduler] Load balancing tick 17.0% ( 37.0) [ehci_hcd:usb1, uhci_hcd:usb2] 11.5% ( 25.0) USB device 1-5 : USB2.0-CRW (Generic) 10.1% ( 22.0) [acpi] Q - Quit R - Refresh A: I fixed this by upgrading to Ubuntu 11+
{ "pile_set_name": "StackExchange" }
Q: existence of global good filtration for D-modules? Let $X$ be a smooth algebraic variety over $\mathbb{C}$ (or a field of characteristic zero). We have $D_X$ the sheaf of differential operators on $X$, which is a coherent sheaf of rings, and it carries the canonical increasing filtration $D_X^n$ by the order of differential operators, whose associated graded ring $grD_X$ is identified with the function ring of the cotangent bundle of $X$.For $M$ a coherent $D_X$-module (finite type as $D_X$-module and quasi-coherent as $O_X$-module), we can talk about the notion of good filtration on $M$: it is a increasing filtration $M_n$ by quasi-coherent $O_X$-modules, compatible with $D_X^n$ for the $D_X$-module structure of $M$, such that the associated graded module is of finite type over $grD_X$. For coherent $D_X$-module $M$, good filtration exists locally over $X$, and in many case this is already sufficiently useful. For example it leads to the notion of characteristic cycles, etc. But my question is when do we do have globally defined good filtration $M_n$ for $M$, such that $D_X^nM_m=M_{n+m}$ for all $m,n\geq 0$? A natural example one can find is in the D-affine case: $X$ is D-affine if the global section functor establishes an equivalence between coherent $D_X$ modules and coherent $\Gamma(X,D_X)$-modules. In this case a coherent $D_X$-module $M$ with global section $N$ is equipped with a global good filtration $D_X^nN$. Conversely, if every coherent $D_X$-module admits a global good filtration, how far is $X$ from being $D_X$-affine? This seems to be too optimistic. Another question: if we only consider coherent $D_X$-modules coming from flat connection on vector bundles (coherent as $O_X$-modules), do we always have global good filtration? By the way, for $X$ a Zariski open subset of $Y$ a smooth variety, does the D-affinity of $Y$ implies the D-affinity of $X$? Many thanks! A: Every coherent D-module admits a global good filtration. This is theorem 2.1.3 in the book by Hotta, Takuechi, and Tanisaki, D-modules, Perverse Sheaves and Representation Theory. They first prove that there is a $\mathcal O_X$ coherent $\mathcal O_X$-submodule $M_0$ which generates $M$, then define the filtration by $F_mM = (F_mD_X) M_0$. In particular $F_nD_X (F_m M) = F_{n+m}M$ for all $m,n \geq 0$. I believe that you other questions have been answered in the comments by Moosbrugger.
{ "pile_set_name": "StackExchange" }
Q: How does Skrillex perform live concerts? I went to a Skrillex concert last year. When Skrillex performs live, what is he doing? A: Electronic music live acts are normally performed using sequencers that trigger synthesizers and/or samplers, plus an array of controls like knobs and faders. It's common for the sequencers to control the rhythm and pitch, and the knobs and faders to control volume and timbre, but you can make the sequencers and knobs/faders control something else inside the limits of the device. From this video we can see that Skrillex is using Ableton Live as a sequencer, but it is more accurately defined as a non-linear DAW (you can think of it as a very powerful hybrid of sampler, synth, mixer, and drum machine). He is also using a M-Audio Trigger Finger as a control surface, which includes faders, knobs, and pads to control whatever you program them to control in Ableton Live. Maybe he bought this bundle: This type of setup (Ableton Live + a control surface) is the most common setup for electronic music live performance now days. When using analog synths, a common setup is to use Live as a sequencer (using MIDI tracks) that feed analog synths (you can see James Holden doing it here, Surgeon doing it here, both using modular synths). In general, that's what he is doing (ideally, more on that later). Using a control surface to control Ableton Live (if he is doing anything at all, electronic music has its own "lip-sync" issues). Inside Ableton Live you'll find synths, samplers, audio tracks, effects, and whatever audio processing and production dynamic you can think of. What synths, effects, etc is he using? The video suggests that Skrillex is using one knob to control a stutter effect (Live's beat repeat effect, most likely), but it's hard to know for sure. Because of some interviews (and this page, specifically) we know that he uses stuff like Massive (very common in Dubstep production), Sylenth1, and Reaktor. Through the Finger Trigger he probably controls things like envelopes, LFOs, delay times, distortion amount, etc. With that said, without having the actual Ableton Live patch it is hard to be specific about what he is doing. The control surface might not even be connected and everything is already automated and/or pre-recorded. Or maybe he has intimate control of every single dynamic.
{ "pile_set_name": "StackExchange" }
Q: Python2.7 prints wrong characters from unicode with hexadecimal chars sys.getdefaultencoding() -> utf8 test = u'tempête' test -> u'temp\xc3\xaate' print(test) -> tempête # WTF ? sys.setdefaultencoding('ascii') sys.getdefaultencoding() -> ascii test = u'tempête' test -> u'temp\xc3\xaate' print(test) -> tempête #... I observe these results when I do a set_trace() from pdb. In a python2.7 shell I have correct result : sys.getdefaultencoding() -> ascii test = u'tempête' test -> u'temp\xc3\xaate' print(test) -> tempête # WTF ? I'm struggling with this from hours... A: Ensure your locale encoding matches your terminal emulation. Type locale to check. sys.setdefaultencoding() has nothing to do with printing - Python uses your locale to set the stdout encoding used when printing. See sys.stdout.encoding. I can partially replicate your problem like this: Set terminal emulation to: UTF-8 Set locale to en_GB.ISO8859-1. I.e. Not UTF-8 export LANG=en_GB.ISO8859-1 Run your code: >>> test = u'tempête' >>> test u'temp\xc3\xaate' The fact that ê becomes à (U+00C3) and ª(U+00AA) is the crux of the problem, showing that Python thought the encoding of should be an 8bit character set. I can't replicate your final print but I suspect fiddling with setdefaultencoding() and cooked everything - See my answer about why it's a bad idea: https://stackoverflow.com/a/34378962/1554386
{ "pile_set_name": "StackExchange" }
Q: Git not pushing .bat files I do not (as far as I know) have a .gitignore file setup in my local repo, but when I commit and push (even after doing git add --all) the repo doesn't push .bat files (and several other file types). I am using Git bash with Windows. commands I am using: git add --all git commit -m "next commit here" . git push -u origin master git pull A: Whenever you are trying to troubleshoot Git ignores, the check-ignore command is useful: For each pathname given via the command-line or from a file via --stdin, show the pattern from .gitignore (or other input files to the exclude mechanism) that decides if the pathname is excluded or included. Later patterns within a file take precedence over earlier ones. I recommend pointing this at your problematic files with the --verbose / -v flag, e.g. git check-ignore --verbose path/to/file.bat You should either get output like .gitignore:5:*.bat path/to/file.bat indicating, in this case, that your file is ignored by the pattern *.bat found on line 5 of the file .gitignore, or no output and a return value of 1, indicating that the file is not ignored. Be careful running this against multiple files at once; if even one of them is ignored you will get a successful return value of 0.
{ "pile_set_name": "StackExchange" }
Q: Which voltage should I use with a component that allows between 3v and 5.5v? I have a DS18B20 temperature sensor that needs between 3v and 5.5v to work, as seen in its documentation. What's the difference? Should it work better which 5.5v? I know that a LED with more voltage will bright more but it will burn or a pump with more voltage will take water faster. But what about the temperature sensor? A: According to the datasheet the absolute maximum is -0.5 V to 6.0 V. The normal voltage for which it works according to the specifications in the datasheet is 3.0 V to 5.5 V. That means het DS18B20 works well with 3.3 V and just as well with 5.0 V. One voltage is not "better" than the other. There is not difference. You can use it with a 3.3 V Arduino board and with a 5 V Arduino board. The power it uses when being active is 1 mA * 5.0 V = 5 mW. It is possible that it causes some self-heating. But let's not go there. That is something for nerds.
{ "pile_set_name": "StackExchange" }
Q: Payment on a bill not working using QBFC12 for QuickBooks 2013 I am using C# to connect with QuickBooks desktop 2013. I need to record payments against a bill, but cannot figure out why it is not working. My current code keeps throwing an error of 3120 saying it can't find the bill, even though the bill object is open in my control. I've used the IDN Unified OSR provided by intuit for the BillPaymentCheckAdd object structure, but the "data" they pass in is just random and not helpful for what I actually need to pass in as values. So I could use some help. Here is my code for the pay bill method: IBillPaymentCheckAdd paymentAdd = requestMsgSet.AppendBillPaymentCheckAddRq(); paymentAdd.PayeeEntityRef.ListID.SetValue(vendorId); paymentAdd.TxnDate.SetValue(DateTime.Now); paymentAdd.BankAccountRef.ListID.SetValue(bankAccount.ListID.GetValue()); paymentAdd.ORCheckPrint.IsToBePrinted.SetValue(true); paymentAdd.Memo.SetValue(bankAccount.Name.GetValue()); IAppliedToTxnAdd appliedToTxnAdd = paymentAdd.AppliedToTxnAddList.Append(); appliedToTxnAdd.TxnID.SetValue(bill.TxnID.GetValue()); appliedToTxnAdd.PaymentAmount.SetValue((double)amount); ISetCredit setCredit = appliedToTxnAdd.SetCreditList.Append(); setCredit.CreditTxnID.SetValue(bill.TxnID.GetValue()); setCredit.AppliedAmount.SetValue((double)amount); paymentAdd.IncludeRetElementList.Add(bankAccount.Name.GetValue()); IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet); IResponse response = responseMsgSet.ResponseList.GetAt(0); IBillPaymentCheckRet paymentRet = (IBillPaymentCheckRet)response.Detail; A: I think the error that you are getting is referring to the setCredit section. The credits are used to apply a previous vendor credit to a bill. You are passing in the Bill TxnID as the credit, but it's a bill transaction, not a credit transaction so QuickBooks is saying it can't find the credit transaction as it doesn't really exist. If you remove the 4 line section for the ISetCredit, your payment should go through correctly.
{ "pile_set_name": "StackExchange" }
Q: Answers quickly deleted by owner should be permanently deleted You often have the scenario where you post an answer and you realize it's not good, other people have already posted the answer (which you find out when you post) in which case your answer is just noise or someone comes after you and posts a better answer. Also, technically you can "abuse" the delete process if you're above 10k+ rep. You just post 15 characters, delete it, edit it and then undelete it. This way you won't get downvoted for having a placeholder answer but can still get in first (timestamp wise). IMHO deleting something within the first 20 minutes (or pick some other arbitrary time frame) after you post it should simply permanently delete it. Less noise that way. A: I think as user bdonlan mentioned in his answer, permanently delete by default is a bad idea. But adding a "purge" button next to delete will be confusing and not intuitive. This is what I think should happen: The user deletes his or her own post within 20 minutes The user is shown the notification box that says "This post has been soft deleted but can still be seen by high reputation users. You can permanently delete it if you want." In the question controls a new "permanently delete" control will be added, that shows up only for already deleted questions within 20 minutes of the posting time, and only to the OP. It should also be styled differently to attract attention: A: You don't even need 10k rep to "abuse" the system the way you describe - people can see their own deleted answers at any reputation. However, I disagree that this is an effective way to game the system - the reason for posting first is not so that you can get that first timestamp, but rather so that people that are coming to the new post can see your answer and vote it up if it's correct. If your answer is deleted, they won't see it and won't vote on it, and even if you undelete it later, you miss a lot of that initial traffic. There are those that are concerned about others judging them by their deleted posts, usually when they failed to read or understand the question, and ended up posting an answer that makes no sense or one that the OP didn't ask for. I've even seen some users that go so far as to replace their post with a note for 10k+ users so there wouldn't be any confusion. Personally, I don't care what people say in deleted posts, but it might ease these users minds if they could permanently remove their answer within a certain window of time. I think 20 minutes is far too long - how about 5 minutes? This is the same time period in which users are allowed to make revisions that don't bump the answer or appear in the revision list, so it might make sense to allow them to permanently delete the answer within this time window as well, provided there were no comments or other revisions. A: If this is implemented, I think it would be best for it to be an option ('purge' or something) rather than the default - on occasion I've ended up answering the question, realizing I misread it, quickly deleting it to avoid confusion, then editing to something that does answer the question and undeleting it when done. Losing the answer completely the moment I hit delete would be somewhat surprising...
{ "pile_set_name": "StackExchange" }
Q: ArgParse ERROR. but working in Test.py file My test.py file in create_assessment (and all the CRUD operations) are working, e.g. populating the database that I have created. However, the ArgParse command line, made to interact with the database, is failing in create_assessment because of the category area. Assessment-Category share a many-to-many relationship. I believe the issue is due to the parser's category line (as shown in the TracebackError, but I haven't been able to figure this conundrum. The categories do exist in the db, the parser is not recognizing the categories, but recognizing them in the test.py file. It could be that args = parser.parse_args() isn't parsing correctly. ERROR: (venv)acks-MacBook-Pro:notssdb ack$ notssdb-cmd create_assessment 'Learning new things' 'this' dancinglady 'movie' ['Bats', 'Development', 'Swinging at nothing'] usage: API_ArgParse [-h] {create_user,retrieve_user,update_user,update_user_lastname,delete_user,create_assessment,retrieve_assessment,update_assessment,delete_assessment,create_video,retrieve_video,update_video,update_video_url,delete_video,create_category,retrieve_category,update_category,delete_category,create_element,retrieve_element,update_element,delete_element,create_assessment_results,retrieve_assessment_results,delete_assessment_results,create_category_rating,retrieve_category_rating,update_category_rating,delete_category_rating,create_element_rating,retrieve_element_rating,update_element_rating,delete_element_rating,create_comment,retrieve_comment,update_comment,delete_comment} ... API_ArgParse: error: unrecognized arguments: Development, Swinging at nothing] ADDED the parser = config. Code: parser = argparse.ArgumentParser(prog='API_ArgParse', description='Create, Read, Update, and Delete (CRUD) Interface Commands for NOTSSdb') subparsers = parser.add_subparsers(dest='cmd', title='subcommands', description='type subcommand name with -h for more details : e.g. notssdb-cmd create_user -h', help='additional help') api = ConvenienceAPI() # Create command for 'assessment' create_parser = subparsers.add_parser('create_assessment', help='create an assessment') create_parser.add_argument('name', type=str, help='name of the assessment') create_parser.add_argument('text', type=str, help='assessment text') create_parser.add_argument('username', type=str, help='name of user') create_parser.add_argument('videoname', type=str, help='name of video') create_parser.add_argument('category_names', type=str, help='list all category names')#THIS LINE # Parse the arguments args = parser.parse_args() api = ConvenienceAPI() api_method = getattr(api, args.cmd) arg_dict = vars(args) del arg_dict['cmd'] api_method(**arg_dict) Create_assessment method with category retrieval (convenience.py - inherits base): class ConvenienceAPI(BaseAPI): def create_assessment(self, name, text, username, videoname, category_names): user = self.retrieve_user(username) video = self.retrieve_video(videoname) cat_objects = [self.retrieve_category(category_name) for category_name in category_names] return super(ConvenienceAPI, self).create_assessment(name, text, user, video, cat_objects) Retrieve method for category (base.py): def retrieve_category(self, something_unique): if isinstance(something_unique, int): return self.session.query(Category).\ filter(Category.category_id == something_unique).all() # multiple categories elif isinstance(something_unique, basestring): print(something_unique) # added return self.session.query(Category).\ filter(Category.category_name == something_unique).one() Working test.py file example: api.create_assessment('How to be a leader', 'better decisions', 'wizard', 'good leadership', ['Leadership', 'Decision-Making', 'Teamwork and Communication', 'Situation Awareness']) A: The problem is the stuff in brackets. The comandline processor in the shell does not recognize them. Look at the sys.avgv that the parse works with. With a simple script that just echos the argv, your line produces: ['echoargv.py', 'create_assessment', 'Learning new things', 'this', 'dancinglady', 'movie', '[Bats,', 'Development,', 'Swinging at nothing]'] Notice the 2 strings in the error message: 'Development,' 'Swinging at nothing]' The positional 'category_names' gets '[Bats,', but there's no place to put the other strings. Putting extra quotes around the brackets, "['Bats', 'Development', 'Swinging at nothing']", would solve this, but assign that whole thing to 'category_names'. You'd then have to strip and parse it. Another option is to give 'category_names' a nargs='+' parameter and enter notssdb-cmd create_assessment 'Learning new things' 'this' dancinglady 'movie' 'Bats', 'Development', 'Swinging at nothing'
{ "pile_set_name": "StackExchange" }
Q: Why is my Zebra Danio bloated? Just a few days ago I added 8 Zebra Danios and 8 White Skirt Tetras to my 60 gallon tank of 8 Albino Corys. One of the Danios is chasing all of the other Danios around. In fact it is bossy - but this only started today and the bloated Danio has been bloated since I got it. I thought it was a normal female trait. However the fish keeps floating up easily, but manages to stay down at the same level - leading me to conclude it might be swim bladder disease. Google turns up inconclusive. (Maybe it's pregnant?) I've ruled out almost all disease, including dropsy, because it looks normal, just bloated. I feed the tank freeze-dried brine shrimp and bloodworms, daphnia, sinking wafers, fish flakes, and that's all. The Danios 90% of the time eat what's on the surface, which is just blood worms and daphnia. Brine shrimp as well, but the tetras usually get that. A: Breed Zebra Danios are extremely hardy fish. They are almost difficult to kill. They are indeed "bossy" and instill a rigid pecking order. Diagnosis Definitely sounds like swim bladder disease. Swim bladder disease bloats the fish, and they struggle to retain the proper depth. Treatment By the time you've identified a disease like dropsy or swim bladder, it's usually too late for the fish. The best treatment I've found is Melafix, but it's quite expensive, and very pungent and stinky. A single dose stunk up my entire bedroom and hallway for about a week, and the first few days I didn't want to come home because I didn't want to bear the smell. To medicate the fish you'd optimally put it in a separate tank by itself, so your other fish don't get the treatment, too. But separating it often means a smaller tank, and the smaller the tank, the easier it is for things like pH to get out of whack. Afterthoughts Where did you buy the fish? Department stores like Walmart are especially guilty of selling sick/diseased fish and not caring. Pet stores are generally a little better about it. Did you know that you might be able to get a new fish replacement for free? Check your receipt. I like to hang onto my receipts for this reason, especially for expensive fish (which Zebra Danios aren't). In the past, I'd stick my dead fish in a baggie with some water into the freezer and take the frozen baggie with fish to the store for a free "exchange" with receipt. A: My experience with Danios has that they always have been "bossy" fish. I don't recall one being the boss of the pack, but I recall that any Danio would usually go fin pecking the other species as well as their own species. This wasn't due to overpopulation, a small tank nor under-feeding. It just seems that Danios have that kind of temperament and are territorial.
{ "pile_set_name": "StackExchange" }
Q: Calculating $\int_{\gamma}f$ in $G = \{z : 0 < |z| < 1\}$ Let $G = \{z : 0 < |z| < 1\}$ and $f:G\to\mathbb{C}$ be analytic. Suppose $\gamma $ is closed rectifiable curve in $G$ such that $n(\gamma,a)=0$ for all $a$ in $\mathbb{C}\setminus G$. What is $\int_{\gamma}f$? Here's what I have thought. -The value is trivially $\int_{\gamma}f=Res(f,0)\cdot 2\pi i$, but I assume the problem asks for an especific answer. -If we had $\{z : |z| < 1\}$ instead of $\{z : 0 < |z| < 1\}$, by Cauchy's theorem we would have $\int_{\gamma}f=0$. Of course we can't apply this because $f$ could have either a pole or an essential singularity at $z=0$. Is there even an especific answer? I would say it depends of $f$, but maybe the integral is just zero. Any hints? A: $U := \{z : |z| < 1\}$ is simply connected and $f$ holomorphic in $G = U \setminus \{ 0 \}$. According to the residue theorem, $$ \int_{\gamma}f(z) \, dz = 2 \pi i \, n(\gamma, 0) \, Res(f, 0) $$ and that is zero because $n(\gamma, 0) = 0$.
{ "pile_set_name": "StackExchange" }
Q: $.getJSON request does not work on button click Hey guys I have tried to find a solution to this problem, I'm currently at a loss. I'm trying to gather info on streams using the twitch API. I am able to get a .getJSON request to work when I pass in an array of usernames, null is returned if the user is offline or invalid. $(document).ready(function() { var streamers = ["ESL_SC2","OgamingSC2","cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninjas","meteos","c9sneaky","JoshOG"]; var url = "https://api.twitch.tv/kraken/streams/"; var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?"; getInitialStreams(streamers, url, cb); //load hard-coded streams }); function getInitialStreams(streamers, url, cb) { //loop through the streamers array to add the initial streams for (var i = 0; i < streamers.length; i++) { (function(i) { $.getJSON(url + streamers[i] + cb, function(data) { //If data is returned, the streamer is online if (data.stream != null) { console.log("online"); } else { console.log("offline"); } }); })(i); } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-inline"> <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer"> <button id="addStreamerBtn" class="btn" type="submit">Add</button> </form> However, when I try to call the API through a click function (eventually pulling any input through the form) .getJSON fails. As seen below. $(document).ready(function() { var url = "https://api.twitch.tv/kraken/streams/"; var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?"; $("#addStreamerBtn").click(function(e) { addStreamer("Ben", url, cb); }); }); function addStreamer(streamer, url, cb) { console.log("I'm inside the function"); $.getJSON(url + streamer + cb, function(data) { console.log("WE DID IT"); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-inline"> <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer"> <button id="addStreamerBtn" class="btn" type="submit">Add</button> </form> I don't understand why the code won't work for the 2nd snippet. Any guidance would be greatly appreciated. A: The issue is because you've hooked to the click event of the submit button. This means that the form is being submit as your AJAX request happens, so the page is immediately unloaded and the AJAX cancelled. To fix this, hook to the submit event of the form, and call preventDefault() on the event. Try this: $(document).ready(function() { var url = "https://api.twitch.tv/kraken/streams/"; var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?"; $(".form-inline").submit(function(e) { e.preventDefault(); addStreamer("Ben", url, cb); }); }); function addStreamer(streamer, url, cb) { console.log("I'm inside the function"); $.getJSON(url + streamer + cb, function(data) { console.log("WE DID IT"); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-inline"> <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer"> <button id="addStreamerBtn" class="btn" type="submit">Add</button> </form>
{ "pile_set_name": "StackExchange" }
Q: I need to update the database how can I do it? I have been trying to create a to do list app and there has been no problems until when i was adding an edit button, when i press the edit button, it shows the edit page with the text that has to be edited but the submit button that is suposed to change the database is not working, I think I need to add something to the views.py file but I dont know what. viws.py def edit(request, id): created_items = Create.objects.get(id=id) return render(request, 'my_app/edit.html', {"created_items": created_items}) urls.py urlpatterns = [ path('edit/<int:id>/', views.edit, name='edit'), ] models.py class Create(models.Model): added_date = models.DateTimeField() text = models.CharField(max_length=200) edit.html {% extends 'index.html' %} {% block body %} <div align="center"> <h1>Edit your post!</h1> <div class="container form-group"> <h1>↓</h1> <form method="POST">{% csrf_token %} <textarea class="form-control" name="content" id="id" rows="3" style="text-align: center;">{{ created_items.text }}</textarea> <button type="submit" class="btn btn-outline-success" style="margin-top: 5px;">Submit</button> </form> </div> </div> {% endblock %} A: You will send POST request when you click submit and need to catch that request in some function like: if request.method == 'POST': edited_text = request.POST.get('text') ## 'text' might be changed. I don't know how you handle the request. related_id = request.POST.get('id') ## You need to take updated id. (somehow?) Create.objects.filter(id=related_id).update(text=edited_text) ## That will do the job. Hope it helps,
{ "pile_set_name": "StackExchange" }
Q: Load all technorati script ads tags asynchronously What is the issue? I have an issue with slow ads loading on my webpage, the Technorati ad tags I am using is blocking the page rendering until the advertising tags loads one by one, Example: if I have an ad tag in the middle of the page, I can't see the footer of the page until this ad tag loads completely. What I need ? I want a method to make the page loads faster and keep these scripts after the whole page is completely loaded (asynchronous), I tried multiple methods but it didn't work. Here's the Ad tag code I have to use: <script type="text/javascript"> document.write('<scri' + 'pt type="text/javascript" src="' + (document.location.protocol == 'https:' ? 'https://uat-secure' : 'http://ad-cdn') + '.technoratimedia.com/00/81/95/uat_19581.js?ad_size=300x250"></scri' + 'pt>'); </script> Here's a link to the page I am using the ad tags on: http://feat.youmobile.org/ A: My problem has been solved using a javascript library that lazyload ads asynchronously called "Postscribe" Example of page using PostScribe + HTMLParser http://www.youmobile.org/about/ Here a link for its Github https://github.com/krux/postscribe This is the code I used, Huge performance change: <center><div id="ad1" class="center grey-text">Advertisement</div></center> <script type="text/javascript"> $(function() { postscribe('#ad1', '<scri' + 'pt type="text/javascript" src="' + (document.location.protocol == 'https:' ? 'https://uat-secure' : 'http://ad-cdn') + '.technoratimedia.com/00/81/95/uat_19581.js?ad_size=300x250"></scri' + 'pt>'); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Using Launchy to open executable with notepad++ I'm trying to find an easy way using launchy to open files via n++ that might not normally be that way. For example, if I have an authohotkey (ahk) file that I want to edit, I'd like to be able to use a script or command to launch it in notepad++. I think there might be a way to do this with batch looking at this question, but I'm not sure how to make it so I can call it in launchy with the file name. A: Using the information given by Anaksunaman, I was able to come up with what appears to be a workable solution. I created a bat file in the directory I want to search through that simply says for /f %%i in ('dir /S /b %*') do SET FNAME=%%i START notepad++ %FNAME% This will search through the directory of the file as well as any subdirectories. This isn't really directly related to Launchy, but it does work when launched through Launchy.
{ "pile_set_name": "StackExchange" }
Q: Is this table in first normal form? I am currently studying SQL normal forms. Lets say I have the following table the primary key is userid userid FirstName LastName Phone 1 John Smith 555-555 1 Tim Jack 432-213 2 Sarah Mit 454-541 3 Tom jones 987-125 The book I'm reading states the following conditions must be true in order for a table to be in 1st normal form. Rows contain data about an entity. Columns contain data about attributes of the entities. All entries in a column are of the same kind. Each column has a unique name. Cells of the table hold a single value. The order of the columns is unimportant. The order of the rows is unimportant. No two rows may be identical. A primary key Must be assigned I'm not sure if my table violates the 8th rule No two rows may be identical. Because the first two records in my table 1 John Smith 555-555 1 Tim Jack 432-213 share the same userid does that mean that they are considered duplicate rows? Or does duplicate records mean that every peace of data in the row has to be the same for the record to be considered a duplicate row see example below? 1 John Smith 555-555 1 John Smith 555-555 EDIT1: Sorry for the confusion The question I was trying to ask is simple Is this table below in 1st normal form? userid FirstName LastName Phone 1 John Smith 555-555 1 Tim Jack 432-213 2 Sarah Mit 454-541 3 Tom jones 987-125 Based on the 9 rules given in the textbook I think it is but I wasn't sure that if rule 8 No two rows may be identical was being violated because of two records that use the same primary key. The class text book and prof isn't really that clear on this subject which is why I am asking this question. A: Or does duplicate records mean that every peace of data in the row has to be the same for the record to be considered a duplicate row see example below? They mean that--the latter of your choices. Entire rows are what must be "identical". It's ok if two rows share the same values for one or more columns as long as one or more columns differ. That's because a relation holds a set of values that are tuples/rows/records, and set is a collection of values that are all different. But SQL & some relational algebras have different notions of "identical" in the case of NULLs compared to the relational model without NULLs. You should read what your textbook says about it if you want to know exactly what they mean by it. Two rows that have NULL in the same column are considered different. (Point 9 might be summarizing something involving NULLs. Depends on the explanation in the book.) PS There's no single notion of what a relation is. There is no single notion of "identical". There is no single notion of 1NF. Points 3-8 are better described as (poor) ways of restricting how to interpret a picture of a table to get a relation. Your textbook seems to be (strangely) making "1NF" a property of such an interpretation of a picture of a table. Normally we simply define a relation to be a certain thing so if you have one then it has to have the defined properties. Then "in 1NF" applies to a relation & either means "is a relation" & isn't further used or it means certain further restrictions hold. A relation is a set of tuples/rows/records, and in the kind of relation your 3-8 describes they are sets of attribute/column/field name-value pairs & the values paired with a name have to be of the type paired with that name in some schema/heading that is a set of name-type pairs that is defined either as part of the relation or external to it. Your textbook doesn't seem to present things clearly. It's definition of "1NF" is also idiosyncratic in that although 3-8 are mathematical, 1 & 2 are informal/heuristic (& 9 could be either or both).
{ "pile_set_name": "StackExchange" }
Q: Why does Parasite have this ending? Parasite presents the tragedy of poor working class people in Korea in a kind of humorous way. The movie doesn't shy away from displaying this tragedy in detail about how this family of 4 lives, despite being skilled has to con their way into money. How the rich people treat these poor people etc. But despite all this, the movie ends with a sort of a "happy ending". Despite having his head bashed in repeatedly with a stone and profusely bleeding, Kevin survives, recovers, gets a job, becomes rich and buys the same house and rescues his father. Kim Ki-taek, despite murdering Mr. Park andhiding in the basement of the house to live out his days alone, gets rescued by his son. Chung-sook, despite murdering the previous housekeeper and having to live out her life alone andpoor (assuming Kevin dies from the incident), gets to live in the house and watch the sunrise over the lawn. Only Jessica is the one to die from her wounds. So, the question is, why did the director choose such a happy ending for the Kim family instead of a realistic and brutal one? A: Like the comment said, the happy ending is in his imagination. You can read this in an interview with Bong Joon Ho here. “Maybe if the movie ended where they hug and fades out, the audience can imagine, ‘Oh, it’s impossible to buy that house,’ but the camera goes down to that half-basement,” he says. “It’s quite cruel and sad, but I thought it was being real and honest with the audience. You know and I know — we all know that this kid isn’t going to be able to buy that house. I just felt that frankness was right for the film, even though it’s sad.” Ultimately, the ending communicated the same message the movie did throughout, that poverty is structural. The happy ending was a shared fantasy of the boy and society/the audience.
{ "pile_set_name": "StackExchange" }
Q: Does compliance to WCAG 2.0 AA use ul tab as navigation tabs in a master page? I've got an aspx web application that uses an unordered list tags to parse a tab menu inside a master page. My question is: is it ok to use an ul tag according to WCAG 2.0 AA? <div id="divTabsId"> <ul> <li class="home" id="elementId"> <a href="xxx.aspx"> Start</a> </li> <li> <a id="elementId2" href="zz.aspx"> T1</a> </li> <li> <a href="yyy.aspx"> Help</a> </li> </ul> </div> A: There is nothing wrong with using ul tag. But adding the appropriate aria tags in addition to it would be useful, such as role="menu" to the ul. Please see W3 recommendation here: https://www.w3.org/WAI/GL/wiki/Using_ARIA_menus Depending on your requirement you could read up these roles: role="menu" : https://www.w3.org/TR/wai-aria/roles#menu role="menu-item" : https://www.w3.org/TR/wai-aria/roles#menuitem
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC 4 - Simple Membership, Facebook login broken when using Email instead of Username I have a Code First MVC 4 App, I have swapped Username for Email in SimpleMembership - which works fine. I do that by changing Initialization to this: // Initialize database for Account WebSecurity.InitializeDatabaseConnection("MyEntities", "Users", "UserId", "Email", autoCreateTables: true); I have a Facebook App which I want to use for login. I have tested this on a vanilla (username based) Simple Membership site and it works fine. However, when I try and login using the Email/Password Simple Membership MVC 4 site - it works as far as this: Associate your Facebook account. Association Form You've successfully authenticated with Facebook. Please enter a user name for this site below and click the Confirm button to finish logging in. no matter what I enter here - I get this error: "The username supplied is invalid." db.UserProfiles.Add(new UserProfile { UserName = model.UserName }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); Any idea how I can get this to work (and secondarily request both a username and an email at this stage - or an email only if that's easier). Thanks. A: I fixed it by adding an email field to the confirmation form - then changing the code to this: db.UserProfiles.Add(new UserProfile { UserName = model.UserName, Email = model.Email }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.Email);
{ "pile_set_name": "StackExchange" }
Q: source of energy for expansion of the universe I know in order for something to expand or grow it has to be fueled by something? So, if the universe is expanding their must be something that's keeping the universe at a temperature high enough for it to expand. For something to expand it has to be heated to a certain amount, so I was thinking maybe the massive heat surge, blast and radiation from the big bang is heating the universe enough to expand. Then another thought occurred to me what happens when its not hot enough to expand will it just stop. A: The basic reason for cosmological expansion is simply inertia. Because the universe was in an expanding state soon after the big bang, it kept expanding. This is roughly analogous to Newton's first law of motion. In addition to this, dark energy is currently causing a significant acceleration of the expansion. (Its effect was not dominant in the past, and was negligible in the early universe.) I know in order for something to expand or grow it has to be fueled by something? Not true. In an ordinary explosion, there is some initial expenditure of energy, but once the matter is spreading apart, there is no further need for a source of energy. Cosmological expansion is also different from an ordinary explosion because in current cosmological models, there was no time before the big bang. Therefore there is no need to posit a cause for the big bang at an earlier time, or a preexisting supply of energy. As a side issue, energy is not globally conserved in general relativity in cosmological spacetimes.
{ "pile_set_name": "StackExchange" }
Q: SJCam SJ4000 Not Recognised by PC I have a new Action Cam. A copy of a GoPro, I think. When connected via USB it asks whether it should be used as a PC camera or a mass storage device. Whichever is chosen, the PC cannot 'see' it at all. Is there a work-around? Am I missing a 'driver'? A: Firstly, SCJAM is not a copy of GoPro. It is a Chinese manufacturer of miniature cameras, and one of their product lines are cuboid cameras. I've spent 50+ hours going through reviews and eventually decided to go for their top model - SJCAM SJ5000+ Ambarella (with Panasonic's "Ambarella" processor), because it is almost as good as GoPro Hero 4 Black and 4 times cheaper. When I say "almost" I mean "white balance is slightly different - in my view better, and slightly worse video stabilisation". And yes, housings of the SJ**** line are compatible with GoPro mounts for a reason - GoPro has the largest number of available mounts. Worth noting that "SJ****" is a fake of "SJCAM SJ****". With that out of the way... I've got Ubuntu 14.04.02 LTS, clean install with no extra drivers, software, etc., and my SJCAM SJ5000+ Ambarella with software ver. 2.4 mounts with no problem as "storage" (set up on camera end). Ubuntu recognises it with no problems. I'd suggest: firstly check if you have a microSD card in the camera. Is not the camera itself that the OS mounts but the microSD card. Secondly, I'd perhaps upgrade packages - just in case. In terminal type sudo apt-get update && upgrade Finally, it is time to see what devices plugged into all USB ports your computer can see. In terminal type: lsusb And check if you can see a line with no micro-controller description. This will be the SJCAM. For example mine looks like this: me@mylaptop:~$ lsusb Bus 002 Device 003: ID 8087:07da Intel Corp. Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 004: ID 0c45:644a Microdia Bus 001 Device 003: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub Bus 003 Device 003: ID 4255:1000 Bus 003 Device 002: ID 046d:c077 Logitech, Inc. Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub As I experimented by pluging in and out the camera, the one you should be looking for is the one without description (4255:1000). Please post the result.
{ "pile_set_name": "StackExchange" }
Q: No line found Scanner I'm tring to write a program that communicates with a server in Java. I tried to make a basic communication program but I am stuck on repeated messages. One message works but when I try and get multiple without closing the server and client I fail. On my mission to get it working I got an error which I can not fix. I have the following classes: Client import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class MainClass { private static int port = 40021; private static String ip = "localhost"; public static void main(String[] args) throws UnknownHostException, IOException { String command, temp; Scanner scanner = new Scanner(System.in); Socket s = new Socket(ip, port); Scanner scanneri = new Scanner(s.getInputStream()); System.out.println("Enter any command"); command = scanner.nextLine(); PrintStream p = new PrintStream(s.getOutputStream()); p.println(command); temp = scanneri.nextLine(); System.out.println(temp); } } Server import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class MainClass { public static void main(String args[]) throws IOException { String command, temp; ServerSocket s1 = new ServerSocket(40021); Socket ss = s1.accept(); Scanner sc = new Scanner(ss.getInputStream()); while(true){ command = sc.nextLine(); temp = command + " Dat dus"; PrintStream p = new PrintStream(ss.getOutputStream()); p.println(temp); } } } I am getting an error on the While loop. Exception in thread "main" java.util.NoSuchElementException: No line found I can understand why it gives an error but I am totally clueless how to get it working. I hope someone could help me out. Thanks in advance. A: In your server codes here the line runs forever even after the client has finished sending messages :- while(true){ command = sc.nextLine(); temp = command + " Dat dus"; PrintStream p = new PrintStream(ss.getOutputStream()); p.println(temp); } change that to :- while(sc.hasNextLine()){ command = sc.nextLine(); temp = command + " Dat dus"; PrintStream p = new PrintStream(ss.getOutputStream()); p.println(temp); } and also add your entire server code in a while loop that runs forever as you do not want your server to shutdown after the client disconnects that is :- public static void main(String args[]) throws IOException { String command, temp; ServerSocket s1 = new ServerSocket(40021); while(true) { Socket ss = s1.accept(); Scanner sc = new Scanner(ss.getInputStream()); while(sc.hasNextLine()) { command = sc.nextLine(); temp = command + " Dat dus"; PrintStream p = new PrintStream(ss.getOutputStream()); p.println(temp); } } }
{ "pile_set_name": "StackExchange" }
Q: Extracting a texture in watchOS 3 I am using the following code in iOS 10.0 in my GameScene.swift //Shape storage let playerShape = SKShapeNode(circleOfRadius: 10 ) ...Color setup etc //Get the texture from shape node let playerTexture = view?.texture(from: playerShape) The same code doesn't work in watchOS 3.0 Xcode 8.0 beta 2 complaints about the view: Use of unresolved identifier 'view' Does anyone know whats the equivalent of view in watchOS? Thank you. A: As mentioned above there are no views in Apple Watch's Sprite Kit. So that is why you are unable to use view in your code. Just use SKSpriteNode instead and do something like this if you want the texture for something else. E.g. here I want to use my circleOriginal texture on circle 2 let circleOriginal = SKSpriteNode(imageNamed: "circle") let circleTexture = circleOriginal.texture let circle2 = SKSpriteNode(texture: circleTexture) If you want an amazing overview of Apple Watch Game Tech check out Apple's WWDC lecture on it (The slides below are from there). This explains a lot and provides great code examples. https://developer.apple.com/videos/play/wwdc2016/612/ Here are the key differences. Here's Apple's Scene Graph for non-watchOS Here's Apple's Scene Graph corresponding Scene Graph for watchOS Here are the recommended alternatives for watchOS's SpriteKit / SceneKit
{ "pile_set_name": "StackExchange" }
Q: Cassandra-cli cant connect to remote cassandra server I have a cassandra server running on a server(serv1). cassandra-cli can connect to it when run on serv1. However, when i try to connect to it through some other server(serv2), i get the following exception: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused at org.apache.thrift.transport.TSocket.open(TSocket.java:183) at org.apache.thrift.transport.TFramedTransport.open(TFramedTransport.java:81) at org.apache.cassandra.cli.CliMain.connect(CliMain.java:80) at org.apache.cassandra.cli.CliMain.main(CliMain.java:256) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at org.apache.thrift.transport.TSocket.open(TSocket.java:178) ... 3 more Exception connecting to jckstore/9160. Reason: Connection refused. I looked in cassandra.yaml and found that the property "listen_address" is configured to "localhost" and using 0.0.0.0 is severely discouraged. I tried to change localhost to serv2, ip address of serv1 but nothing worked. Even commenting out didnt help. Is there a way i can make my cassandra server listen on all the ip's without using 0.0.0.0 A: I was able to solve the problem as following: changing the rpc_address property in cassandra.yaml to 0.0.0.0 instead of localhost. set the broadcast_rpc_address property in cassandra.yaml to a value other than 0.0.0.0 Then I can access. A: Cassandra cli uses thrift to connect to Cassandra. The rpc_address decides how the thrift clients can connect to Cassandra. Setting it to 0.0.0.0 will work, but setting it to the hostname of the server and then using the same hostname to connect will also work.
{ "pile_set_name": "StackExchange" }
Q: Start EXE Through Batch File So, I'm trying to setup a basic script to install WinRAR (as my test, others later on) and I' can't seem to get it to work. Here's what I have: @ECHO OFF IF EXIST "C:\Program Files (x86)\WinRAR" GOTO End IF EXIST "C:\Program Files\WinRAR" GOTO End IF DEFINED ProgramFiles(x86) ( START C:\WinRAR_4.20_(x64).exe ) ELSE ( START C:\WinRAR_4.20_(x86).exe ) :End PAUSE The first two EXIST checks work fine, but I can't get the START command to work. If I just type it out in the CMD window it starts up the installer, but it just wont do it from the batch file. Can someone point me to where I'm screwing up? A: The problem is with the FileName. Get rid of parenthesis in the file name and it should work fine. WinRAR_4.20_x64.exe and WinRAR_4.20_x86.exe
{ "pile_set_name": "StackExchange" }
Q: How to maintain sequence of output list while finding the difference of 2 lists I have to find the difference between a list with another list. But this process of finding the difference totally randomizes my output every time I run. Below is my script getALL = ["apple","ball","cat","dog","eagle"] // initial list Sourcee = ["eagle", "ball"] diff = list(set(getALL) - set(Sourcee)) for items in diff: print(items) Is there any way to keep the sequence of the the diff list same as getALL? I want my output like this: apple cat dog A: Just a list comprehension would work. Optionally converting Sourcee to a set would make it faster >>> source_set = set(Sourcee) >>> [e for e in getALL if e not in source_set] ['apple', 'cat', 'dog'] A: The set operation does not preserve order. However what you can do is to re-build the diff list, by checking what the order was in the original list. This works for any arbitrary order. If the original list contains duplicates this complicates matters. getALL = ["apple","ball","cat","dog","eagle"] # initial list Sourcee = ["eagle", "ball"] diff = list(set(getALL) - set(Sourcee)) original_order_diff = [x for x in getALL if x in diff] print(original_order_diff)
{ "pile_set_name": "StackExchange" }
Q: how to set OnEditorActionListener EditText lastedit = new EditText(this); lastedit.setHint("Last name"); blur.addView(lastedit); MarginLayoutParams params22 = (MarginLayoutParams) lastedit.getLayoutParams(); params22.width = 460; params22.leftMargin = 16; params22.topMargin = 265; lastedit.setLayoutParams(params22); Typeface font22=Typeface.SERIF; lastedit.setTypeface(font22); lastedit.setMaxLines(1); lastedit.setImeOptions(EditorInfo.IME_ACTION_NEXT); here i want that when i press enter it will automatically go to next field. I attact 4 edit text view in my code dynamically like above and then finally automatically button will press and go to next activity. A: use setInputType for EditText. It will solve your problem.
{ "pile_set_name": "StackExchange" }
Q: php Regular expression fails I'm trying to match string but it is going into last else loop. Can you please provide any help? $cstg = "<result>True<\/result>"; if (preg_match("/<result>True<\/result>/", $cstg)) { echo "result success"; } else if (preg_match("/\<result\>False\<\/result\>/", $cstg)) { echo "result fail"; } else { echo "Something went wrong."; } A: Issue is coming from your $cstg string. You don't have to escape \ in html text. So following code are working fine: $cstg = "<result>True</result>"; if( preg_match("/<result>True<\/result>/", $cstg)){ echo "result success"; } elseif (preg_match("/\<result\>False\<\/result\>/", $cstg)){ echo "result fail"; }else{ echo "Something went wrong."; }
{ "pile_set_name": "StackExchange" }
Q: Python - Unicode De/Encode How can I pass all the content from making a db-input(s1), loading it from there (s2) and pass it correctly back-formated to the file? import time,os,sys,base64 s = "Hello World!\r\nHeyho" #with s1 i make an input to the database; with s2 I select it -> works most time s1 = base64.b64encode(s.encode("UTF-8")).decode("UTF-8") #print("Base64 Encoded:", s1) s2 = base64.b64decode(s1.encode("UTF-8")).decode("UTF-8") #print(s2) #example that I try to save it in a file: s3 = "PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+" with open("C:\\Users\\001\\Downloads\\Output.txt", "w") as text_file: text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delete the signs Log: C:\Users\001\Downloads>python trythis.py Traceback (most recent call last): File "trythis.py", line 11, in <module> text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delelte signs File "C:\Users\001\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u25b7' in position 28: character maps to <undefined> EDIT: I am working on windows. C:\Users\001\Downloads>python -V Python 3.5.2 A: The problem is that you open the file in text mode, but don't specify the encoding. In that case the system default encoding is used, which may be different on any system. Solution: specify the encoding argument to open(). As a side-note: why do you .decode('UTF-8')? It does work, but since the data is Base64-encoded, I think ASCII decoding would make more sense. Besides, you should only encode/decode at the I/O binaries (so in this case when writing to file), although you may have done it for testing/demonstration purposes only in this case. Update: Apparently your Base64-encoded data is also UTF-8 encoded (first UTF-8, then Base64), so that's why you need to first Base64-decode then UTF-8-decode it. The following is a portable, working example: import base64 b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+' decoded_text = base64.b64decode(b64_encoded_text).decode('utf-8') with open('Output.txt', 'wt', encoding='utf-8') as text_file: text_file.write('Ausgabe: %s' % decoded_text) Although it's even easier to just write the raw binary (UTF-8 encoded) data to the file: import base64 b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+' with open('Output.txt', 'wb') as file: # file.write(b'Ausgabe: ') # uncomment if really needed file.write(base64.b64decode(b64_encoded_text))
{ "pile_set_name": "StackExchange" }
Q: Can not run angular2 in commonjs way First, I don't know the difference between @angular and angular2 in package.json. But I like angular2 way in package.json. Here is my github source. The problem is that I can't change "system" to "commonjs" in tsconfig_c.json, otherwise angular2 will throw error that I can't understand. HTML: <!DOCTYPE html> <html> <!-- #docregion head --> <!-- #docregion base-href --> <head> <base href="/" /> <!-- #enddocregion base-href --> <title>Angular 2 Seed</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- #docregion css --> <link rel="stylesheet" href="styles.css"> <!-- #enddocregion css --> <!-- 1. Load libraries --> <script src="libs/angular2-polyfills.js"></script> <script src="libs/system.src.js"></script> <script src="libs/Rx.js"></script> <script src="libs/angular2.dev.js"></script> <script src="libs/router.dev.js"></script> <!-- 2. Configure SystemJS --> <script> System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } } }); System.import('app/bootstrap') .then(null, console.error.bind(console)); </script> </head> <!-- 3. Display the application --> <body> <my-app>Loading...</my-app> </body> </html> Config: { "compilerOptions": { "target": "es5", "module": "system", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "moduleResolution": "node", "removeComments": false, "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true }, "exclude": [ "node_modules" ] } If compile the "system" way, all is good. But I prefer the "commonjs" way. Anyone could help me fix this? A: As said by @Sanket, the angular2 package is the old beta version of Angular 2. About your question, if you compile in commonjs, you must tell SystemJs that your app is in commonjs, so you have to change in index.html the configuration: System.config({ packages: { app: { format: 'cjs', // commonjs defaultExtension: 'js' } } });
{ "pile_set_name": "StackExchange" }
Q: Android Studio, Suddenly got GPU Driver Issue when running emulator I have a laptop that I mainly use for android development on android studio, today all of the sudden got this error message (or an outdated version of it) when i ran my emulator Your GPU driver information: GPU #1 Make: 8086 Model: Intel(R) HD Graphics Family Device ID: 0a16 Driver version: 10.18.10.3945 GPU #2 Make: 10de Model: NVIDIA GeForce 820M Device ID: 1140 Driver version: 22.21.13.8476 Some users have experienced emulator stability issues with this driver version. As a result, were selecting a compatibility renderer. Please check with your manufacturer to see if there is an updated driver available. Updated the geforce driver, but no use, tried to update the intel one but failed, is there a way to disable this? bypass the compatibility renderer and work as I used to, the emulator is awful now. Any explanation why that occurred all of the sudden? Also I'm using windows 7 64-bit if that will help with anything, had an update few days ago. A: I am using Win10 but have the same problem. Emulator started crashing my app after last emulator update. In my case, problem is that emulator does not run on hardware even though I never had a problem with my GPUs. Also, the "GPU driver issue" window that pops up doesn't even label WHICH one of the GPUs it thinks is the problem. For me the solution that worked is to run emulator from terminal, forcing it to run using hardware graphics (instead of letting emulator decide on which) using command emulator -avd avd_name -gpu mode where mode is host so that it will run with hardware. For example: Using Android Studio terminal move to folder where the emulator is located. Default on Win10 is: C:\Users\userName\AppData\Local\Android\sdk\emulator Find emulator to run by listing available ones: emulator -list-avds Run emulator with -gpu host option: emulator -avd avd_name -gpu host More info on this link A: A comment in the on the bug report pertaining to this issue by a Google employee is illuminating. If your system doesn't have a discrete GPU, we intended this change in order to make the emulator more reliably run on Intel GPU drivers. At your own risk, you may switch back to using the Intel GPU by going to settings page, then changing the OpenGL ES renderer to "ANGLE (D3D11)", "ANGLE (D3D9)", or "Desktop native OpenGL". It appears that this message is being displayed for all systems using Intel GPUs, not just systems running specific versions of a graphics driver. The solution is to, if possible, switch to using an external GPU for running the emulator. If an Intel GPU is the only GPU available on system it is possible to re-enable accelerated rendering of OpenGL ES, by overriding the default OpenGL ES renderer in settings (see below). Options are OpenGL, ANGLE and SwiftShader. SwiftShader is CPU based OpenGL ES emulation, so this setting will not provide a speedup. ANGLE is Direct3d based OpenGL emulation. As per the comment this is not guaranteed to work, indeed I am able to re-enable hardware acceleration for Android 7 emulators, but with hardware acceleration enabled, all I receive is a black screen for Android 8 emulators. Open settings with Ctrl-Shift-S then, depending on the version of the emulator, either go to Settings -> General -> OpenGL ES renderer or to Settings -> Advanced -> OpenGL ES renderer Newer emulator versions: Older emulator versions: Update #1: Another comment on the bug report provides further illumination on this issue: If you have just a Intel HD 4xxx running the emulator, it's intended that a compatibility renderer be used. I'm sorry about it, but we need to be able to switch to better-supported Intel GPU drivers especially when running high API levels (25+) of system images. Intel iGPUs of that generation (and older) have many issues with OpenGL compatibility. It appears that Intel iGPU drivers for Haswell (4th gen) processor and older don't support OpenGL well enough for Android 7.1+ devices. So they are purposely falling back to using software emulation which better supports the new Android emulators. This matches my experience. Using the Intel iGPU works great on Android 7, but is flaky on Android 7.1 and doesn't work at all on Android 8. My suggestion, stick with Android 7 emulators when using hardware acceleration for Intel Haswell and older iGPUs. Update #2: Official communication on this issue was finally provided in the form of comments in the release notes for Emulator 26.1.3: Which GPUs will be switched to use ANGLE or Swiftshader rendering is determined as follows: Older Intel iGPUs have driver issues on both OpenGL and ANGLE D3D drivers. Users with Intel HD Graphics 3xxx and older will use Swiftshader. Some users reported the inability to use API level 25 images because of a bug in which "Pixel Launcher keeps stopping." This seems to be a driver issue in some Intel HD 4xxx models. So they will be switched to use ANGLE automatically. For best results with GPU emulation, we recommend either to use a discrete NVIDIA or AMD GPU, or a newer Intel GPU (Iris, HD 5xxx, HD 5xx/6xx). A: I ran into this problem today. Per the suggestion from the Google emulator issue tracker, I installed the beta emulator 26.1.3. Problem fixed.
{ "pile_set_name": "StackExchange" }
Q: SQL Server CTE to find path from one ID to another ID I have a table in a SQL Server 2008 R2 database that defines transitions between different states. Example relevant table columns: TransitionID | SourceStateID | DestinationStateID | WorkflowID -------------------------------------------------------------- 1 | 17 | 18 | 3 2 | 17 | 21 | 3 3 | 17 | 24 | 3 4 | 17 | 172 | 3 5 | 18 | 17 | 3 6 | 18 | 24 | 3 7 | 18 | 31 | 3 8 | 21 | 17 | 3 9 | 21 | 20 | 3 10 | 21 | 141 | 3 11 | 21 | 184 | 3 ... etc. My goal is to be able to define a starting StateID, an ending StateID, and the WorkflowID, and hopefully find a logical path from the starting StateID to the ending StateID within that workflow. e.g. For the table above, if I supplied a starting StateID of 17, and ending StateID of 184, and a WorkflowID of 3, I could wind up with a 'path' of 17>21>184 (or more ideally, TransitionID 2 > TransitionID 11) The Good: The Starting and Ending StateID's defined will always have a possible path within the defined WorkflowID The Bad: There are certainly circular references on virtually every source/destination StateID (i.e. there's likely a transition from SourceStateID 1 to DestinationStateID 2, and also from SourceStateID 2 to DestinationStateID 1 There are certainly multiple possible paths from virtually any defined starting StateID and ending StateID I realize it's some manner of CTE I'm after, but admittedly I find CTE's hard to grasp in general, and doubly so when circular references are a guaranteed problem. The perfect solution would be one that selects the shortest path from the starting StateID to the ending StateID, but to be honest at this point if I can get something working that will reliably give me any valid path between the two states I'll be so happy. Any SQL gurus out there have some direction you could point me in? I honestly don't even know where to begin to prevent circular issues like getting a path along the lines of 17>18>17>18>17>18... DISGUSTING UPDATE I came up with this query which hurts me on an emotional level (with some help from this post: https://stackoverflow.com/a/11042012/3253311), but appears to be working. DECLARE @sourceStatusId INT = 17 DECLARE @destinationStatusId INT = 24 DECLARE @workflowId INT = 3 DECLARE @sourceStatusIdString NVARCHAR(MAX) = CAST(@sourceStatusId AS NVARCHAR(MAX)) DECLARE @destinationStatusIdString NVARCHAR(MAX) = CAST(@destinationStatusId AS NVARCHAR(MAX)) DECLARE @workflowIdString NVARCHAR(MAX) = CAST(@workflowId AS NVARCHAR(MAX)) ;WITH CTE ([Source], [Destination], [Sentinel]) AS ( SELECT CAST(t.[Source] AS NVARCHAR(MAX)) AS [Source], CAST(t.[Destination] AS NVARCHAR(MAX)) AS [Destination], [Sentinel] = CAST([Source] AS NVARCHAR(MAX)) FROM Transitions t WHERE CAST([Source] AS NVARCHAR(MAX)) = @sourceStatusIdString AND CAST([WorkflowID] AS NVARCHAR(MAX)) = @workflowIdString UNION ALL SELECT CAST(CTE.[Destination] AS NVARCHAR(MAX)), CAST(t.[Destination] AS NVARCHAR(MAX)), CAST([Sentinel] AS NVARCHAR(MAX)) + CAST('|' AS NVARCHAR(MAX)) + CAST(CTE.[Destination] AS NVARCHAR(MAX)) FROM CTE JOIN Transitions t ON CAST(t.[Source] AS NVARCHAR(MAX)) = CAST(CTE.[Destination] AS NVARCHAR(MAX)) WHERE CHARINDEX(CTE.[Destination], Sentinel)=0 ) SELECT TOP 1 [Sentinel] FROM CTE WHERE LEFT([Sentinel], LEN(@sourceStatusIdString)) = @sourceStatusIdString AND RIGHT([Sentinel], LEN(@destinationStatusIdString)) = @destinationStatusIdString ORDER BY LEN([Sentinel]) A: Similar to Quassnoi's answer, but prevents circular references that start after the first element: DECLARE @src int = 18, @dst int = 184; WITH cte AS (Select TransitionId, SourceStateId, DestinationStateID, SourceStateID as StartingState, 0 as Depth , cast(TransitionId as varchar(max)) + ',' as IDPath , cast(SourceStateID as varchar(max)) + ',' as States FROM Transitions WHERE SourceStateId = @src UNION ALL Select t.TransitionId, t.SourceStateId, t.DestinationStateID, StartingState, cte.Depth + 1 , cte.IDPath + cast(t.TransitionId as varchar(max)) + ',' , cte.States + cast(t.SourceStateID as varchar(max)) + ',' FROM cte JOIN Transitions t on cte.DestinationStateID = t.SourceStateId and CHARINDEX(',' + cast(t.SourceStateID as varchar(max)) + ',', States) = 0 --prevent loop starting after first element and t.DestinationStateID <> StartingState --prevent loop starting with first element where cte.Depth < 10 -- prevent going too deep ) select TransitionId, SourceStateId, DestinationStateID, Depth, left(IDPath, len(IDPath) - 1) IDPath, left(States, len(States) - 1) States from cte where DestinationStateID = @dst order by Depth
{ "pile_set_name": "StackExchange" }
Q: How Do I Properly Determine User File System Permissions for a File? I am currently writing an application that needs to examine the current user's permission for a file in the Windows file system given the file path. The application is written in C# .Net 4.0. I believe I am "in the right area", but am in need of help "driving it home". This question is in the right ballpark:Iterate through permissions on a file in the windows file system in C#, but is more concerned with multiple users - I am concerned with the current user. Here is what I have so far: FileSecurity fsObj = file.GetAccessControl(AccessControlSections.Access); foreach (FileSystemAccessRule fsar in fsObj.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { FileSystemRights fsr = fsar.FileSystemRights; // examine current fsr for permissions... } My goal is to determine whether the user has write access to the file. A: I believe it can be done as such (untested): if ((FileSystemRights.Write & fsar.FileSystemRights) != FileSystemRights.Write) return false; return true;
{ "pile_set_name": "StackExchange" }
Q: how to call a php function from a class and return the value in vue js? I'm learning vue but for some reason couldn't find an answer to this simple question. I have a php class called DataFetcher and i have a vue file and inside of it i wanna call a method from DataFetcher and print the result in the vue page. I've always done it with data passed from props like this (learned it from the tutorials i've watched): <form-input name="someName" id="someName" v-model="alien.id"></form-input> Now i wanna call the method getAlienName($alienId) of the class DataFetcher and put the result in the v-model. Something like this: <form-input name="someName2" id="someName2" v-model="DataFetcher.getAlienName(alien.id)"></form-input> How can I achieve this? getAlienName($alienId) is merely a method that has a db query that returns a name. A: You can't call PHP functions from a vue context. PHP is executed on the server side, while vue is executed on the client side. You will have to define an API of some sort to call the function. Just an example: vue: HTTP GET localhost/api.php?alienId=1337 php: <?PHP echo myFunction($_GET['alienId']);
{ "pile_set_name": "StackExchange" }
Q: MySQL - Using Order By result created by a subquery group_concat or join issue This is a query I've been puzzling over for quite some time, I've never been able to get it to work quite right and after about 40 hours of pondering I've gotten to this point. Setup For the example issue we have 2 tables, one being... field_site_id field_sitename field_admins 1 Some Site 1, 2 Other Site 1,2, And the other is admins like... field_user_id field_firstname field_lastname 1 Joe Bloggs 2 Barry Wills Now all this query is designed to do is the following: List all sites in the database Using a JOIN and FIND_IN_SET to pull each admin And GROUP_CONCAT(field_firstname, ' ', field_lastname) with a GROUP BY to build a field with the real user names. Also allow HAVING to filter on the custom result to narrow the results down further. All this part works perfectly fine. What I can't work out how to achieve is to sort the results by the GROUP_CONCAT result, I imagine this is being the ORDER BY works before the concat function therefore the data doesn't exist to order by it, so what would the alternative be? Code examples: SELECT * GROUP_CONCAT(DISTINCT field_firstname, ' ', field_lastname ORDER BY field_lastname SEPARATOR ', ') AS field_admins_fullname, FROM `table_sites` LEFT JOIN `table_admins` ON FIND_IN_SET( `table_admins`.`field_user_id`, `table_sites`.`field_site_id` ) > 0 GROUP BY field_site_id I also tried a query that used a subquery to gather the group_concat result as below... ( SELECT GROUP_CONCAT(field_firstname, ' ', field_lastname ORDER BY field_lastname ASC SEPARATOR ', ') FROM table_admins WHERE FIND_IN_SET( `table_admins`.`field_user_id`, `table_sites`.`field_admins` ) > 0 ) AS field_admins_fullname Conclusion Either way attempting to ORDER BY field_admins_fullname will not create the correct results, it won't error out but assume that's because the given ORDER BY is blank so it just does whatever it wants. Any suggestions would be welcome, if this is just not possible, what would be another recommend index methodology? A: Two things I see wrong: 1st, is the JOIN. It should be using s.field_admins and not field_site_id : ON FIND_IN_SET( a.field_user_id, s.field_admins ) > 0 2nd, you should use the CONCAT() function (to conactenate fields from the same row) inside the GROUP_CONCAT(). Try this: SELECT s.field_site_id , s.field_sitename , GROUP_CONCAT( CONCAT(a.field_firstname, ' ', a.field_lastname) ORDER BY a.field_lastname ASC SEPARATOR ', ' ) AS field_admins_fullname FROM table_sites s LEFT JOIN table_admins a ON FIND_IN_SET( a.field_user_id, s.field_admins ) > 0 GROUP BY s.field_site_id Friendly advice: Don't use Do use ------------ -------- table_sites site table_admins admin field_site_id site_id field_sitename sitename field_admins admins But what should really be stressed, is your setup. Having fields that have comma separated values lead to this kind of horrible queries that use FIND_IN_SET() for joins and GROUP_CONCAT() for showing results. Horrible to see, difficult to maintain and most important, very, very slow as no index can be used. You should have something like this instead: Setup suggestion Table: site site_id sitename 1 Some Site 2 Other Site Table: site_admin site_id admin_id 1 1 2 1 2 2 Table: admin user_id firstname lastname 1 Joe Bloggs 2 Barry Wills
{ "pile_set_name": "StackExchange" }
Q: Combining a passport openID-stategy with JWT I've run into a problem when trying to authenticate with passport.js using openID (passport-steam), and then using tokens (JWT) instead of sessions. My current code looks like this: app.post('/auth/steam', passport.authenticate('steam')); app.get('/auth/steam/return', passport.authenticate('steam', { failureRedirect: '/', session: false }), function(req, res) { var token = jwt.encode({ useridentifier: req.user.identifier}, tokenSecret); res.redirect('/'); }); However, the problem I'm having is: How should I communicate the token back to the client? Since it is a GET request that is run after coming back from Steam's site, I can't reply with a simple res.json(token) like I've seen people using local strategies together with JWT do. The only solution I've managed to come up with involves using a session (e.g. connect-flash) containing the token and communicating it through a REST API to the client after he's been redirected to '/', but the whole point of using JWT is to avoid using sessions, isn't it? A: After many days of thinking without getting anywhere I managed to figure out another way to solve it, using cookies. I found out about the custom callback that passport provides, where I can set the response's headers, so I set one like this before redirecting: res.cookie('token', token, { httpOnly: true }); (no secure yet, because I'm only testing on a local server) This is what the whole code looks like now: app.get('/auth/steam', passport.authenticate('steam')); app.get('/auth/steam/return', function(req, res, next) { passport.authenticate('steam', function(err, user, info){ var payload = { user: user.identifier }; var token = jwt.sign(payload, "thisisnotthesecretiactuallyuse", {expiresIn : 60*60*24}); res.cookie('token', token, { httpOnly: true /* TODO: Set secure: true */ }); res.redirect('/'); })(req, res, next) });
{ "pile_set_name": "StackExchange" }
Q: Excel - Sumifs with Match Good day, I have a table in one sheet (!Vide) which contains Zip Code ($F), Distance ($I), status ($H) and ID Number ($K) and all the zip codes ($A) for a region in another sheet (!NYI) I am trying to do a SUMIFS if the order is part of the the zip code in the NYI sheet using: =IFERROR(SUMIFS(Vide!$I:$I,Vide!$M:$M,Tableau!F1,Vide!$H:$H,"L",Vide!$K:$K,">0",IF(MATCH(Vide!$F:$F,!NYI$A:$A,0),"TRUE","FALSE"),"TRUE") all the part are working fine appart from the IF(MATCH()) part here is a sample of the data: Sheet "Vide": $F $H $I $K 11412 L 105 1390 90210 L 148.6 95.19 11422 E 135.9 2325.6 in this case only row 1 would be taken in account since it meets all the conditions and is present in the table in sheet NYI: Sheet NYI: $A $B 11412 Saint Albans 11413 Springfield Gardens 11422 Rosedale Any and all help will be appreciated. Thank you A: To make it simpler you have got to use a helper column first: =IFERROR(MATCH(F1,NYI!$A:$A,0),0) So that it will have this: $F $H $I $K $L 11412 L 105 1390 1 90210 L 148.6 95.19 0 11422 E 135.9 2325.6 3 Then change your formula to: =IFERROR(SUMIFS(Vide!$I:$I,Vide!$M:$M,Tableau!F1,Vide!$H:$H,"L",Vide!$K:$K,">0",Vide!$L:$L,">1"),"TRUE") If you need just the formula without a helper column here it is: =SUMPRODUCT(Vide!$I:$I*--(Vide!$M:$M=Tableau!F1)*--(Vide!$H:$H="L")*--(Vide!$K:$K>0)*--(Vide!$F:$F=NYI$A:$A)) You might wanna limit this last part to only rows with data as it will take so much overhead in formula processing, e.g. (Vide!$F$1:$F$100=NYI$A$1:$A$100) See Sample below:
{ "pile_set_name": "StackExchange" }
Q: Calculate Duration Omitting Overlapping Dates in R Sorry I'm very new to R and I'm not a data expert. I'm trying to calculate a duration omitting overlapping dates. I suspect lubridate is the answer. My data set looks like this: patientnumber rxnumber startdate stopdate 100 1 1/1/2014 1/5/2014 100 2 1/1/2014 1/5/2014 100 3 1/20/2014 1/22/2014 200 4 2/14/2014 2/14/2014 200 5 2/15/2014 2/20/2014 I'd like to calculate obtain a value for patient 100 of 8 (5 + 3) and 7 for patient 200 (1 +6) to calculate a total exposure for each patient. The way I think I need to approach this is. Calculate the minimum start date, and maximum stop date for each patient then use a counter variable to count starting from the minimum start date. If the counter variable overlaps with one of the intervals then add one and move along. If it doesn't, just move along until the max stop date is reached. I just don't know how to code this. This would be the most complex coding I've done in R and the first time I'd use a loop.Please help! Update @ Richard Appreciate the help. While scaling this up I noticed some problems. assuming 1 same patient number and increasing rx# startdate stopdate duration overlap 3/26/2014 3/26/2014 1 3 (this overlap is coming from the record above) 3/27/2014 3/27/2014 1 0 3/27/2014 3/27/2014 1 1 3/27/2014 3/30/2014 4 1 3/28/2014 3/28/2014 1 3 (this unfortunately I'm not sure hwo to fix) The code is working, just needs to be fine tuned. Hope you can help. I'll continue to try to figure this out. A: One solution would be to calulate the duration and then correct for an overlap with the preceeding entry. BEWARE: This solution assumes a certain type of ordering and will not work for unordered data.frames. It is assumed (like in the provided example) that the data are ordered by patientnumber and cronologically. If the data are in a different format, they have to be sorted accordingly. # example data dat <- read.table(header=TRUE, text= "patientnumber rxnumber startdate stopdate 100 1 1/1/2014 1/5/2014 100 2 1/1/2014 1/5/2014 100 3 1/20/2014 1/22/2014 200 4 2/14/2014 2/14/2014 200 5 2/15/2014 2/20/2014 300 5 2/19/2014 2/22/2014 300 6 3/27/2014 3/27/2014 300 7 3/27/2014 3/27/2014 300 8 3/27/2014 3/30/2014 300 9 3/28/2014 3/28/2014") # convert to date dat$startdate <- as.Date(dat$startdate, "%m/%d/%Y") dat$stopdate <- as.Date(dat$stopdate, "%m/%d/%Y") # base duration dat$duration <- difftime(dat$stopdate, dat$startdate, units="days")+1 # calculate overlap dat$overlap <- 0 for(i in 2:nrow(dat)){ samepat <- dat$patientnumber[i]==dat$patientnumber[i-1] curovl <- min(dat$stopdate[i],dat$stopdate[i-1]) - dat$startdate[i]+1 if(curovl>0 & samepat) dat$overlap[i] <- curovl } # aggregate duration and overlap res <- aggregate(duration ~ patientnumber, data=dat, sum) res$overlap <- aggregate(overlap ~ patientnumber, data=dat, sum)[,2] # calculate corrected value res$corrected <- res$duration - res$overlap Result: > res patientnumber duration overlap corrected 1 100 13 5 8 2 200 7 0 7 3 300 11 3 8 EDIT: Fixed some issues regarding the calculation of the overlap (if patientnumber changes, if overlap is only partial). See if the results match your expectations now. Thanks for pointing this out!
{ "pile_set_name": "StackExchange" }
Q: Is this "Explain this code to me" question on topic? Recently I found and answered this question. It garnered quite a few downvotes and before I posted my answer the only upvote on it was mine. I feel most downvoters fell into the hasty generalization trap. (Explain the code questions are often broad and low quality.) However, there are a few commenters who have, I would hope, read the question in more depth and still feel it is clearly off topic. Most meta answers (see broad/low quality links above) on the topic agree that if a "explain the code" question is specific and clear about what is not understood, it is solidly on-topic. The question is well-written, clearly points out what confuses the OP, and shows effort exerted to understand on their own before bringing the question here. It does end with a broad request to explain the code, but it seems implied that only the sections indicated really need clarification (I edited it slightly but this seemed implied even in the original). It also doesn't seem like a case of bait and switch. Essentially my question is, why did so many people feel this question was off-topic and only I thought it on topic? A: As Servy pointed out, whereas I interpreted the broader parts of the question as more fluff than actual questions (e.g. "Explain this code to me, specifically this line."), the wording was such that these broader parts could be interpreted as parts of the question as well (e.g. "Explain this line to me, but also tell me how the code works in general."). I disagree with the comments claiming this was a "debug my code for me" question and that the OP would have gotten all he needed from a debugger. From the question it seemed he had gone through the code by hand, tracing the path of execution, but even seeing the numbers change at each stage, couldn't deduce the semantic meaning of the changes. It took me a little while to grasp the reasoning behind some of the subtler changes, and I could see it being very challenging for someone inexperienced or completely new to coding. In any case, I think the best resolution to the broad or specific ambiguity is to make it clearly specific. I have done so, editing out the broader statements and expressly stating the points to be addressed. If anyone feels there are still parts that beget broadness, feel free to edit them out as well.
{ "pile_set_name": "StackExchange" }
Q: Is it posible to hook redis before key expired I have set an expiration value to a key in redis, and want to get the opportunity to run a piece of code before the key will be deleted by redis. Is it possible, and if so how...? Thanks A: My solution was to create a new key, with the same name as the one I wanted to hook, only I added a prefix for it indicating it's a key for timeouts usage ("TO") - something like: set key1 data1 set TO_key1 "" expire TO_key1 20 In the example above, as soon as "TO_key1" will expire, it will notify my program and I'll get the opportunity to run my code before I will manually delete "key1". I found this link very useful for creating the listener for redis: Redis Key expire notification with Jedis
{ "pile_set_name": "StackExchange" }
Q: The imagebutton isn't commiting to the change in recyclerView thanks for helping. I was trying to implement an add to favorite function in my recycler view, everything is working fine except for one thing. I am unable to commit the changed image button in my recycler view, every time I press the button, the post is added to the favorites and the image button turns yellow, but as soon as I move to some other fragment, the yellow button goes back to its initial stage. Can anyone of you help me on how can I make my button commit to the changes in recycler view. Below is my relevant code. Initialization of buttons in holder class: class UsersViewHolder1 extends RecyclerView.ViewHolder { View mView; private ImageButton mFavouritesBlack, mFavouritesYellow; private GestureDetector mGestureDetector; private Heart mHeart; public UsersViewHolder1(View itemView) { super(itemView); mView = itemView; mFavouritesBlack = mView.findViewById(R.id.ad_start_fav); mFavouritesYellow = mView.findViewById(R.id.ad_start_fav1); } } OnBindViewHOlder class(I omitted the irrelevant code): protected void onBindViewHolder(@NonNull final UsersViewHolder1 Holder, final int position, @NonNull Ad ad) { Holder.setTitle(ad.getTitle()); Holder.setPrice(ad.getPrice()); Holder.setCategory(ad.getCategory()); Holder.setImage(ad.getImage(), getContext()); Holder.setTime(ad.getTime()); String user_id = getRef(position).getKey(); final String kk = user_id.toString(); Holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mew = new Intent(getActivity(), ExpandActivity.class); mew.putExtra("user_id", kk); startActivity(mew); } }); Holder.mFavouritesBlack.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mFav.child(puid).child(kk).child("fav_status").setValue("Added as fav").addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(),"Added to Fav",Toast.LENGTH_SHORT).show(); if (Holder.mFavouritesBlack.isShown()) Holder.mFavouritesBlack.setVisibility(View.GONE); Holder.mFavouritesYellow.setVisibility(View.VISIBLE); } }); return true; } }); Holder.mFavouritesYellow.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mFav.child(puid).child(kk).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(),"Removed from Fav",Toast.LENGTH_SHORT).show(); if (Holder.mFavouritesYellow.isShown()) Holder.mFavouritesBlack.setVisibility(View.VISIBLE); Holder.mFavouritesYellow.setVisibility(View.GONE); } }); return true; } }); } A: What you are trying to implement is selection inside a recyclerview which requires saving state, that is you will have to save the favourite items say in a SparseBooleanArray which can be used to save favourite adapter positions, and inside onBindViewHolder check if the favourites array contains the adapter position and toggle imageview (There is no need to use two images instead you can change the color of drawable), please refer this artcle A: After 2 days of messed up searches and work I finally removed my the problem was that recycler view isn't able to hold the state by itself after change, that's why we need to provide a way to store the state (or the image in my case) so that it can remember it everytime it recycles the view, but instead I added the direct statement through which it checks whether the favourite node is present in database or not and based on that the buttons behaved. Below is the code. mFav.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(puid).hasChild(kk)){ Holder.mFavouritesBlack.setVisibility(View.GONE); Holder.mFavouritesYellow.setVisibility(View.VISIBLE); }else{ Holder.mFavouritesBlack.setVisibility(View.VISIBLE); Holder.mFavouritesYellow.setVisibility(View.GONE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); Holder.mFavouritesBlack.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mFav.child(puid).child(kk).child("fav_status").setValue("Added as fav").addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(), "Added to Fav", Toast.LENGTH_SHORT).show(); if (!itemStateArray.get(adapterPosition, false)) Holder.mFavouritesBlack.setVisibility(View.GONE); Holder.mFavouritesYellow.setVisibility(View.VISIBLE); } }); return true; } }); Holder.mFavouritesYellow.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mFav.child(puid).child(kk).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(), "Removed from Fav", Toast.LENGTH_SHORT).show(); if (itemStateArray.get(adapterPosition, false)) Holder.mFavouritesBlack.setVisibility(View.VISIBLE); Holder.mFavouritesYellow.setVisibility(View.GONE); } }); return true; } }); But huge thanks to everyone who tried to help.
{ "pile_set_name": "StackExchange" }
Q: Randomly chooses an $ f$ function of $F$ Consider the sets $A = \left\{0, 1, 2, 3,4\right\}$ and $B = \left\{1,2,3,4,5,6,7,8,9,10\right\}$. Let $F$ be the set of functions whose domain is $A$ and whose codomain $B$. If one randomly chooses an $ f$ function of $F$, the probability of $f$ being strictly increasing or being injective is? Attemp: I feel like there is a typo as aren't all strictly increasing functions also injective since both injective and strictly increasing functions have the condition that $\displaystyle \forall a,b\in X,\;\;f(a)=f(b)\Rightarrow a=b$. (It's a matter of a list) So all we have to do is count the number of injective functions for the function to be strictly increasing or injective. That's simply $ 10P5 = 30240$ as we can imagine giving a element of $B$ to a element of $A$. Correct? A: You're right, every strictly increasing function is also injective. If $S_1$ is the set of all strictly increasing functions and $S_2$ is the set of all injective functions, then $S_1 \subset S_2$ and thus $|S_1 \cup S_2| = |S_1|+|S_2|-|S_1\cap S_2| = |S_1|+|S_2|-|S_1| = |S_2|$, so your solution is correct.
{ "pile_set_name": "StackExchange" }
Q: Using blobs to store images as files via Javascript I'm working on this project and ran into some complications using AWS S3 to host images. So I pivoted and decided to store the image as a Blob and let Javascript do the work of transforming the file into and out of the Blob, so I could then use AJAX and the API to store it in our DB. While this might be less than ideal, I'm still learning Javascript and hadn't worked with blobs a lot so I figured why not, time to learn. My issue is that when I try to use a DataURI to show the image on the page it comes out as a string and not a DataURI, and therefore loads as a broken image. I haven't worked in ajax yet because I thought it better to take the image, turn it into an ascii string, put it in a blob, then get it back out before involving the API/server. Here is my html: {% extends 'mp_app/base.html' %} {% load staticfiles %} {% block content %} <div id="page-wrapper"> <pre id="fileDisplayArea"></pre> <form id="picForm" method='post'> {% csrf_token %} <input type="file" id='imgFile' name="pic" accept="image/*"> <input type="submit" id='submitBtn'> <input type="submit" id="showBtn"> </form> <div id="imageDisplay"></div> </div> {% endblock %} {% block javascript %} <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script type="text/javascript" src="{% static 'js/blob.js' %}"></script> {% endblock %} and my Javascript //js file to turn an image into a blob, then store the blob in our API. // next: retrive the blob and put it on the page function textToImg(text) { //get ascii string into binary then into an array then into a blob. //had some strange issues using ArrayBuffer() var file = new Array(atob(document.getElementById('fileDisplayArea').innerText)); file = new Blob(file, {type:'image/*'}); let displayArea = document.getElementById('imageDisplay') //currently doesn't seem to be loading as a DataURL. It's type is string and //shows up as a broken image. var reader = new FileReader(); reader.onload = function(event) { var content = event.target.result; img = new Image(); img.src = content; displayArea.append(img) console.log(img); } reader.onerror = function(event) { console.error('error, file could not be read: ' + event.target.error.code);; } reader.readAsDataURL(file); // TODO get data via ajax to our DB our restful API } //turns an image into a blob function imgToText() { // get file elem and get image let file = document.getElementById('imgFile'); let img = document.getElementById('imgFile').files[0]; let displayArea = document.getElementById('fileDisplayArea'); //open a file reader and read in file, then turn it from binary to ascii var reader = new FileReader(); reader.onload = function(event) { let contents = event.target.result; //turn to ascii string let asciiContents = btoa(contents); //add ascii string to form let form = { 'file': asciiContents, } displayArea.append(form.file); }; reader.onerror = function(event) { console.error('error, file could not be read'); } //read file as a bit string reader.readAsBinaryString(img); // TODO send data via ajax to our DB our restful API }; //add click event so that image is processed upon submit $('#submitBtn').click(function(event) { event.preventDefault(); imgToText(); }); $('#showBtn').click(function(event) { event.preventDefault(); textToImg(); }) The img src reads as the blob string makes me think the something is wrong with the DataURI, perhaps it isn't getting the file in the proper format. I couldn't post a screen shot because I need a better reputation. Sorry this is so verbose but I wanted to try and make a quality post. Thank you! A: I solved the issue. Will post here for future learners who may need this option. textToImg() already has the string it needs, so all you need to do is get the string, add it to the file input element, (I added it as a 'value' attr), then let image.src = 'data:image/*;base64, + value attr. And you're good to go.
{ "pile_set_name": "StackExchange" }
Q: Custom glossary style not left aligning I have an issue with using glossaries for my abbreviations. I have defined my own glossary style, because I wish all acronym descriptions to be written with non-capital first letters in the text, but I wish to capitalize the first letter in the glossary. With this, I get left-alignment issues, see example here: The output above is generated with this MWE: \documentclass[11pt, a4paper]{article} \usepackage[nogroupskip, nonumberlist, toc]{glossaries} \newglossarystyle{myglossary}% {% \renewenvironment{theglossary}% {\begin{longtable}{l lp{\glsdescwidth}}}% {\end{longtable}}% \renewcommand{\glossaryheader}{% \Large \bfseries Term & \Large \bfseries Description \\\endhead}% \renewcommand{\glossentry}[2]{% \textbf{\glsentryitem{##1}\glstarget{##1}{\glossentryname{##1}}} & \Glossentrydesc{##1}\glspostdescription\space ##2\tabularnewline }% } \setglossarystyle{myglossary} \setacronymstyle{long-short} \makenoidxglossaries \newacronym{adc}{ADC}{analog to digital converter} \begin{document} This is my acronym: \gls{adc} \printnoidxglossary[sort = letter, type=\acronymtype, title = {Abbreviations}]% \end{document} Is there anyone with the slightest idea of what's happening here? I have tried all sorts of things, but I don't seem to get it. A: This (i.e. centered) is the default alignment for longtable. You can make it left aligned by using the optional argument, i.e. say \begin{longtable}[l]{l l p{\glsdescwidth}} instead of \begin{longtable}{l l p{\glsdescwidth}}
{ "pile_set_name": "StackExchange" }
Q: MFMailComposer not working in the device? I have an iPhone application where I am sending mails from 3 different buttons in three defferent viewcontrollers. I use MFMailComposerDelegates to achieve this in my viewcontrollers. Everything is working fine in my simulator, but when I put it on the device none of the three are woking. The buttons will not providing anything, simply behaving like a button with no actions. I implemented the delegate methods and everything and I am getting the desired result in the simulator. Can anybody help me please... A: Before pushing the mail composer, call MFMailComposeViewController's canSendMail to find whether you can be able to send mail. You might not have configured mail in your device. You can configure that through Settings.
{ "pile_set_name": "StackExchange" }
Q: Manual crop in Image Transforms I would like to manually crop the image transforms for an uploaded image. I know there are crop plugins for Craft (image-resizer, AviaryImageEditor), but these plugins crop the original image and not the image transforms.. I'm looking for something very similar to the manual crop module in Drupal. So you can upload one image, afterwards you manually crop the different image styles / image transforms.. Any suggestions? A: I don't know a plugin like this for Craft. But this solution does a similar thing. Maybee it works for you: Let clients set crop position for images. Otherwise you could also take a look on the focuspoint plugin: https://github.com/smcyr/Craft-FocusPoint
{ "pile_set_name": "StackExchange" }
Q: How to calculate position of a canard? does anybody know how one can calculate the position, shape and size of an aircraft with a canard? So the main goal of a canard configuration: increase lift + increase agility/maneuverability So at least I can calculate the centre of pressure of the whole aircraft, which has to be behind the CoG to guarantee static stability in pitch. But still, I have a range in x-direction , where I can place the canard. What do I have to define or know in order to place my canard? Lift: I can design my main wing and its lift A_W_wing. In horizontal flight A=W=A_Wing +A_Canard ; So I could now design my A_Canard (shape, size). But what about the maneuverability? What do I need to now? So for my opinion: for a curve to fly with a specific rotating rate, my control surfaces (tail + canard) need to create a specific moment. Since Moment = Force * Arm I could make calculate the needed Arms/ positon ? Thank you for any tips on literature or calculations A: There are several factors to consider, and depending on your preferences there is not one ideal size and place for a canard. For a first rough concept look at similar designs and use the same canard volume. That is the product of canard area and the distance between its and the wing's neutral points, relative to the aircraft's reference parameters. $$V_{Canard} = \frac{S_{Canard}}{S_{ref}}\cdot\frac{X_{NP, wing}-X_{NP, Canard}}{l_{ref}}$$ Collect as many canard volumes as you can from different but similar designs and use that for a first draft. Next, decide on your priorities. Do you want good pitch damping for a pleasant ride even in rough air, use a smaller canard area on a longer lever arm. Damping grows with the square of the canard lever arm while its stabilising effect is only linear. Do the opposite if you prefer more agility. Next, what center of gravity range do you desire? If, for example, you plan a tandem two seater where due to engine weight and pilot position the second seat is at some distance from the center of pressure, increase canard area accordingly. So far we looked only at area and lengthwise position. But the vertical position must also be considered. Ideally, the wake of the canard will be above the wing for all practical angles of attack (from cruise to stall), which can be achieved by placing the canard wing high on the fuselage and the wing low. In that position, however, the canard wing might obstruct the pilot's view, so maybe you want to strike a compromise where the wake is below the wing in cruise but above near stall. This can only be achieved with a short lever arm, however. Regarding the shape: A straight, high-aspect-ratio wing will be best. After all, the canard will fly at the highest lift coefficient of all surfaces so it should have the highest aspect ratio. Use a trapezoidal planform with a ratio of tip chord to root chord of 0.6 - 0.7, or, for simplicity, a rectangular planform which needs only one rig/mold for both sides. But if what you really want is a good airplane and aren't determined on making it a canard: Place that smaller surface behind the main wing.
{ "pile_set_name": "StackExchange" }
Q: Why does creating a collection of const pointers work with `for val in a.iter()` but not `a.iter().map(|val| val)`? This code works: let mut b: Vec<*const SimpleStruct> = Vec::with_capacity(a.len()); for val in a.iter() { b.push(val); } This code does not work: let b: Vec<*const SimpleStruct> = a.iter().map(|val| val).collect(); Playground Why is this? A: When you push &SimpleStruct to a Vec<*const SimpleStruct>, Rust knows that it can coerce the reference into a pointer. However, when you collect it, Rust is trying to coerce a Vec<&SimpleStruct> to a Vec<*const SimpleStruct>, which it can't do, so you should be more explicit: let b: Vec<*const SimpleStruct> = a.iter().map(|val| val as *const SimpleStruct).collect(); or let b: Vec<*const SimpleStruct> = a.iter().map(|val| -> *const SimpleStruct { val }).collect();
{ "pile_set_name": "StackExchange" }
Q: Why does iReport keep adding tags that aren't supported and then crashing? First, iReport is the worst reporting tool I've ever used. Now to my question..... iReport keeps adding tags it doesn't support, which causes a bunch of errors. tag <band splitType="Stretch" /> Can some please tell me how to turn this auto coding off it's really driving me up the wall. It keeps screwing up my code. Oh I'm using 3.5.2 and don't tell me to upgrade because I can't because of the version of jasper server. A: I had this problem as well, but I changed the version I used back to 3.5.0 to match the version of jasper report server as well. EDIT: In fact this is a known problem. The splitType functionality was introduced in 3.5.2, and this is incompatible with 3.5.0. You can see this in the Jasper server forums. So your options are to use iReport 3.5.0 or to upgrade the jar jasperreports-3.5.0.jar to jasperreports-3.5.2.jar on the Tomcat server.
{ "pile_set_name": "StackExchange" }
Q: Socket.io firing callback function multiple times I'm working on a multiplayer canvas game using node.js and socket.io and I'm having problems with my node server throwing a ton of the same error immediately after the client handshake is established. Here's a copy/paste from the console: info - handshake authorized GeDlfwyEdfEIJXGvoZjG new player connected: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG 22:3:26 - (onMovePlayer) Player not found: GeDlfwyEdfEIJXGvoZjG You can check the full code here: http://github.com/storrdev/delta-wing Basically I'm having a problem where the node console for server.js (node script) spits out "(OnMovePlayer) Player Not Found: CONNECTION ID" where CONNECTION ID is the id of the client connected. I wrote that error message to display when the function onMovePlayer() is called when the server receives a "move player" message from the client and the player's id cannot be found in array of players stored on the server. What I can't understand is that the server shouldn't even be invoking the onMovePlayer() function until the client emits the "move player" message to the server, and the client shouldn't emit the "move player" message until after the connection is established, and it emits a "new player" message to the server. Why is it throwing this error so many times? Are socket.emits sent out of order? I'm so confused. I know this is convoluted so I appreciate any help or ideas I can get. I honestly was hoping that typing the situation out would help me figure it out, but unfortunately it has not. A: There is some problem in the Game.update in game.js, it seems to be calling itself recursively. if (Game.players[0].update()) { //This seems to execute recursively. socket.emit('move player', {x: Game.players[0].getX(), y: Game.players[0].getY(), angle: Game.players[0].getAngle()}); Game.background.update(Game.players[0].getX(), Game.players[0].getY()); } I checked it by count=0; if (Game.players[0].update()) { socket.emit('move player', {x: Game.players[0].getX(), y: Game.players[0].getY(), angle: Game.players[0].getAngle()}); count +=1; console.log(count); Game.background.update(Game.players[0].getX(), Game.players[0].getY()); } I could not understand the logic by looking at the code and tell if it is right behaviour. But it keeps sending move player requests to server. Edited After some testing, I found that the issue is due to synchronization. When a client loads the page, it starts emitting the move player right away, even before it connects to the server and runs onSocketConnected. The number of lines you get on the error console are equal to the number of messages sent before Connected to socket server is shown in console. Try the code I used for debugging. So it is breaking the assumption that client shouldn't emit the "move player" until after the connection is established. Hope this helps you.
{ "pile_set_name": "StackExchange" }
Q: Passing an inner array to a function I am trying to pass an inner array to a function in Perl. Here is my Perl program. #!/usr/bin/perl use strict; use warnings; my %data = ( 'a' => ( x => 'Hello', y => 'World' ), 'b' => ( x => 'Foo', y => 'Bar' ) ); #prototype sub p(\%); { #main p(%data{'a'}); # should print "Hello Wolrd". } sub p(\%) { print "$_[0]{x} $_[0]{y}\n"; } Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice). This works: #!/usr/bin/perl use strict; use warnings; #prototype sub p(\%); { #main my %a = ( x => 'Hello', y => 'World' ); p(%a); } sub p(\%) { print "$_[0]{x} $_[0]{y}\n"; } So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn’t a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing? A: Your definition of the structure is wrong. Inner hashes need to use {}, not (). my %data = ( a => { x => 'Hello', y => 'World' }, b => { x => 'Foo', y => 'Bar' } ); Also, to get a single hash element, use $data{'a'} (or even $data{a}), not %data{'a'}. Moreover, see Why are Perl 5's function prototypes bad? on why not to use prototypes. After correcting the syntax as above, the code works even without the prototype. If you really need the prototype, use %, not \%. But you clearly don't know exactly what purpose prototypes serve, so don't use them. A: There are no arrays in your code. And there are no method calls in your code. Your hash is defined incorrectly. You cannot embed hashes inside other hashes. You need to use hash references. Like this: my %data = ( 'a' => { x => 'Hello', y => 'World' }, 'b' => { x => 'Foo', y => 'Bar' } ); Note, I'm using { ... } to define your inner hashes, not ( ... ). That still gives us an error though. Type of arg 1 to main::p must be hash (not hash element) at passhash line 20, near "})" If that's unclear, we can always try adding use diagnostics to get more details of the error: (F) This function requires the argument in that position to be of a certain type. Arrays must be @NAME or @{EXPR}. Hashes must be %NAME or %{EXPR}. No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference. See perlref. Parameter type definitions come from prototypes. Your prototype is \%. People often think that means a hash reference. It doesn't. It means, "give me a real hash in this position and I'll take a reference to it and pass that reference to the subroutine". (See, this is why people say that prototypes shouldn't be used in Perl - they often don't do what you think they do.) You're not passing a hash. You're passing a hash reference. You can fix it by dereferencing the hash in the subroutine call. p(%{$data{a}}); But that's a really silly idea. Take a hash reference and turn it into a hash, so that Perl can take its reference to pass it into a subroutine. What you really want to do is to change the prototype to just $ so the subroutine accepts a hash reference. You can then check that you have a hash reference using ref. But that's still overkill. People advise against using Perl prototypes for very good reasons. Just remove it.
{ "pile_set_name": "StackExchange" }
Q: While starting the jboss server with IBM Sterling V9.3 (ISCCS included), im getting the below error. please help me with it ERROR [[/isccsdev]] Servlet /isccsdev threw load() exception java.lang.IllegalStateException: Profile file final.profile.js not found at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.initializeProfile(SCUIInitializerServlet.java at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.initializeDojo(SCUIInitializerServlet.java:18 at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.init(SCUIInitializerServlet.java:144) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:981) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4071) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4375) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:790) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:770) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:553) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296) at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.apache.catalina.core.StandardContext.init(StandardContext.java:5312) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296) at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.web.tomcat.service.TomcatDeployer.performDeployInternal(TomcatDeployer.java:301) at org.jboss.web.tomcat.service.TomcatDeployer.performDeploy(TomcatDeployer.java:104) at org.jboss.web.AbstractWebDeployer.start(AbstractWebDeployer.java:375) at org.jboss.web.WebModule.startModule(WebModule.java:83) at org.jboss.web.WebModule.startService(WebModule.java:61) at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289) at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.server.Invocation.invoke(Invocation.java:86) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978) at $Proxy0.start(Unknown Source) at org.jboss.system.ServiceController.start(ServiceController.java:417) at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.server.Invocation.invoke(Invocation.java:86) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy44.start(Unknown Source) at org.jboss.web.AbstractWebContainer.start(AbstractWebContainer.java:466) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142) at org.jboss.mx.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:97) at org.jboss.system.InterceptorServiceMBeanSupport.invokeNext(InterceptorServiceMBeanSupport.java:238) at org.jboss.wsf.container.jboss42.DeployerInterceptor.start(DeployerInterceptor.java:87) at org.jboss.deployment.SubDeployerInterceptorSupport$XMBeanInterceptor.start(SubDeployerInterceptorSupport.java:188) at org.jboss.deployment.SubDeployerInterceptor.invoke(SubDeployerInterceptor.java:95) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy45.start(Unknown Source) at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025) at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1015) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782) at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy9.deploy(Unknown Source) at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421) at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:634) at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263) at org.jboss.deployment.scanner.AbstractDeploymentScanner.startService(AbstractDeploymentScanner.java:336) at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289) at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.server.Invocation.invoke(Invocation.java:86) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978) at $Proxy0.start(Unknown Source) at org.jboss.system.ServiceController.start(ServiceController.java:417) at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.server.Invocation.invoke(Invocation.java:86) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy4.start(Unknown Source) at org.jboss.deployment.SARDeployer.start(SARDeployer.java:304) at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782) at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155) at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94) at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142) at org.jboss.mx.server.Invocation.invoke(Invocation.java:88) at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy5.deploy(Unknown Source) at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482) at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362) at org.jboss.Main.boot(Main.java:200) at org.jboss.Main$1.run(Main.java:508) at java.lang.Thread.run(Thread.java:662) The server starts fine. But I am unable to hit the ISCCS url (:7002/isccs/isccs/login.do) Thanks in Advance A: This is caused due to the VM arguments used while building the ear or war file. Don't use -Ddevmode and -Duidevmode. Try building a war instead with the following command. buildwar.cmd -Dwarfiles=isccs -Dappserver=jboss For dev buildwar.cmd -Dwarfiles=isccsdev -Dappserver=jboss
{ "pile_set_name": "StackExchange" }
Q: A confusion about rotation group. Definition: Let $G$ be a group and $S$ a set. Suppose to each group element $g$ there corresponds a function $f_g: S\to S$ in such a way that $f_g(f_h(s))=f_{gh}(s)$ for any $s\in S$ and any ${g,h}\subset G$. Then we say that the group $G$ acts on $S$. In this case we will write $gs$ or $g\cdot s$ instead of $f_g(s)$. Suppose a group $G$ acts on sets $S_1$ and $S_2$(in particular, $S_1$ and $S_2$ may coincide). Then there is a natural way to define the action of $G$ on the set of functions $f:S_1\to S_2$:$$g\cdot f(s)=(g\cdot f)(g\cdot s)$$ If I have a 3-D rotation matrix group $SO(3)$. Let $A$ be a $3\times3$ matrix, which can also be viewed as a linear transformation on $\Bbb R^3$. How to prove that $R \cdot A=RAR^{-1} $ for $R\in SO(3)$ ? A: Recall a function $S_1\to S_2$ (or any relation) is formalized as a subset of $S_1\times S_2$. If $G$ acts on both domain and codomain then it acts on functions by replacing every point $(x,y)$ on its graph with the point $(gx,gy)$. That is, $(g\cdot f):gx\mapsto gy$ whenever $f:x\mapsto y$. Or as you put it, $$(g\cdot f)(gs)=gf(s) \quad \textrm{for all }s\in S_1.$$ (I will use concatenation of letters for $G$ acting on $S_1$ and $S_2$ but use $\cdot$ for $G$'s action on the functions $S_1\to S_2$ so this doesn't get too confusing.) As $s$ varies over all of $S_1$, so does $gs$ because $g$ acts bijectively. Substitute $\sigma=gs$ so that $$(g\cdot f)(\sigma)=gf(g^{-1}\sigma) \quad \textrm{for all }\sigma\in S_1. $$ This is precisely what you wanted to prove as a special case with matrices.
{ "pile_set_name": "StackExchange" }
Q: Uncaught TypeError: Cannot read property 'length' of null - Three.js I've trying to draw the square wall by getting mouse clicks coordinates and extrude it. I've picking up the mouse coordinates by clicking at the scene. var onDocumentMouseDown = function ( event ) { //update the mouse variable mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1; var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = - camera.position.z / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance)); console.log('mouse_x ' + pos.x + ' mouse_y ' + pos.y); if (clickCount <= 3){ coord[clickCount] = {'x' : pos.x, 'y' : pos.y}; clickCount ++; } else { //make new wall and stop function newshape = new THREE.Shape(); shape.moveTo(coord['0'].x ,coord['0'].y); shape.lineTo(coord['0'].x, coord['1'].y); shape.lineTo(coord['2'].x, +coord['2'].y); shape.lineTo(coord['3'].x, coord['3'].y); shape.lineTo(coord['0'].x, coord['0'].y); var newextrudeSettings = { //*******/ }; } And when I've recived four coordinates, three.js throw the error: Uncaught TypeError: Cannot read property 'length' of null at Object.triangulateShape (three.js:26140) at ExtrudeGeometry.addShape (three.js:26330) at ExtrudeGeometry.addShapeList (three.js:26235) at new ExtrudeGeometry (three.js:26211) at HTMLDocument.onDocumentMouseDown (script.js:116) A: To find points of intersection I prefer to use THREE.Raycaster() (though I've never used THREE.Projector() for this purpose). This is the result of my code: I hope I got your conception. Thus, all the stuff you need is here: var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(); var intersects; var controlPoints = []; var clickCount = 0; function onMouseDown(event) { mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; raycaster.setFromCamera(mouse, camera); intersects = raycaster.intersectObjects(objects); // objects is an array which contains just the mesh of the plane if (intersects.length > 0) { if (clickCount <= 3) { // I took your idea of 4 clicks controlPoints[clickCount] = intersects[0].point.clone(); // add a control point to the array // visualization of a control point var cp = new THREE.Mesh(new THREE.SphereGeometry(0.125, 16, 12), new THREE.MeshBasicMaterial({color: "red"})); cp.position.copy(intersects[0].point); scene.add(cp); clickCount++; } else { // on the fifth click we'll create our wall shape = new THREE.Shape(); shape.moveTo(controlPoints[0].x, -controlPoints[0].z); shape.lineTo(controlPoints[1].x, -controlPoints[1].z); shape.lineTo(controlPoints[2].x, -controlPoints[2].z); shape.lineTo(controlPoints[3].x, -controlPoints[3].z); shape.lineTo(controlPoints[0].x, -controlPoints[0].z); var extrudeSettings = { steps: 1, amount: 2, bevelEnabled: false }; var extrudeGeom = new THREE.ExtrudeGeometry(shape, extrudeSettings); extrudeGeom.rotateX(-Math.PI / 2); var wall = new THREE.Mesh(extrudeGeom, new THREE.MeshStandardMaterial({ color: "gray" })); scene.add(wall); controlPoints = []; // we clear the array of control points clickCount = 0; // and reset the counter of clicks }; }; }; jsfiddle example. 4 clicks for setting control points, the fifth click creates a wall, and so on.
{ "pile_set_name": "StackExchange" }
Q: How to perform CRUD Operations on sharepoint lists using React and PnP-JS Core with SharePoint FrameWork (SharePoint 2016) I would like to create forms using react and PnP-JS Core with sharepointframework to perform CRUD Operations on sharepoint lists. Do you have any simple examples I can look at and test on SharePoint 2016 to help me to get familiarized with this new concept Thanks, Arioule A: We have taken multiple initiatives where in we are developing client side web-parts using react for our clients. Traditionally we had been using jquery for making ajax requests in script editors. But with Typescript we are able to use ES6(which is compiled to ES5 at runtime). Using PnP-JS Core with Typescript, we have not only saved a lot of time( by avoiding addition of headers), but our code is more: Indented Readable Debug-gable ( synchronous like debugging by using ES6 promises) Scalable Supports batching ( executing multiple requests in a set order) Supports caching ( loading the content from browser storage, thus less loading time for client) I have given you few reasons, you might find a lot more on your way.
{ "pile_set_name": "StackExchange" }
Q: How to check if a socket client-server is on same network? I'm working with socket and to this I'm using TIdTCPClient and TIdTCPServer. I need to check if the TIdTCPServer that the TIdTCPClient connected is on the same network. How can I do this ? at. A: You need to know the client's subnet mask in order to do that kind of comparison. Sockets do not expose that information, so you will have to ask the OS directly (for instance, on Windows, you can look for the client's connected local IP in the list returned by GetAdaptersInfo() or GetAdapterAddresses()). Once you have the mask, you can then mask the client's IP and the server's IP with it and see if the resulting values are the same. A: Tks for hits, to solve my case I just needed to verify if the host is a local host or not. The solution: function IsLocalHost(AHost : string) : Boolean; var LStrRegexRedeLocal : string; begin if LowerCase(AHost) = 'localhost' then result := True else begin LStrRegexRedeLocal := '(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)|(^127\.0\.0\.1)'; result := ExecRegExpr(LStrRegexRedeLocal, AHost); end; end;
{ "pile_set_name": "StackExchange" }
Q: rails server not working, Rails 4.2.0 I'm following the Rails tutorial by Michael Hartl and after i bundle install all the required gems the rails server gives me an error when i run it. Im using Windows here's the error: C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web_console/slave.rb:1:in `require': cannot load such file -- pty (LoadError) C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web_console/slave.rb:1:in `require': cannot load such file -- pty (LoadError) from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web_console.rb:13:in `require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web_console.rb:13:in `<top (required)>' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web-console.rb:1:in `require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/web-console-2.0.0.beta3/lib/web-console.rb:1:in `<top(required)>' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:76:in `require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:76:in `block (2 levels) in require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:72:in `each' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:72:in `block in require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:61:in `each' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler/runtime.rb:61:in `require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.7/lib/bundler.rb:133:in `require' from C:/sites/sample_app/config/application.rb:7:in `<top(required)>' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:78:in `require' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:78:in `block in server' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:75:in `tap' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:75:in `server' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!' from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>' from bin/rails:4:in `require' from bin/rails:4:in `<main>' here is the Gemfile: source 'https://rubygems.org' gem 'rails', '4.2.0' gem 'bcrypt', '3.1.7' gem 'faker', '1.4.2' gem 'carrierwave', '0.10.0' gem 'mini_magick', '3.8.0' gem 'fog', '1.23.0' gem 'will_paginate', '3.0.7' gem 'bootstrap-will_paginate', '0.0.10' gem 'bootstrap-sass', '3.2.0.0' gem 'sass-rails', '5.0.2' gem 'uglifier', '2.5.3' gem 'coffee-rails', '4.1.0' gem 'jquery-rails', '4.0.3' gem 'turbolinks', '2.3.0' gem 'jbuilder', '2.2.3' gem 'sdoc', '0.4.0', group: :doc group :development, :test do gem 'sqlite3', '1.3.9' gem 'byebug', '3.4.0' gem 'web-console', '2.0.0.beta3' gem 'spring', '1.1.3' end group :test do gem 'minitest-reporters', '1.0.5' gem 'mini_backtrace', '0.1.3' gem 'guard-minitest', '2.3.1' end group :production do gem 'pg', '0.17.1' gem 'rails_12factor', '0.0.2' gem 'puma', '2.11.1' end all help is greatly appreciated A: Looking at the error it seems the web-console gem in your dev group is causing the issue. Some looking around online and it appears that this particular gem does not work well in a Windows environment (Arguably, Rails as a whole does not cooperate on a Windows machine). Try commenting out web-console and then bundle install, rails c If still no luck add: gem 'rubysl-pty', :platforms => :ruby gem 'web-console', :platforms => :ruby then bundle install, rails c and let us know if that resolves your problem! Alternatively, I would recommend using cloud9 or if you want to work locally on a rails app, and are using a Windows machine, try installing Linux/Unix...
{ "pile_set_name": "StackExchange" }
Q: url rewrite leads to 404 not found for both urls I am trying to rewrite website.com/events/event_page.php?id={id} so that users can go to this URL: website.com/event/{id} this is what I am trying: RewriteRule ^event/([0-9]+)$ event_page.php?id=$1 Am I missing something? not only does it not redirect, but the original URL stops working at the same time. A: The folder /events/ is missing, try this: RewriteRule ^event/([0-9]+)$ /events/event_page.php?id=$1
{ "pile_set_name": "StackExchange" }
Q: How to bind properties of a @State variable in a ForEach? class Form { var id = UUID() var name: String = "" var fields: [FormField] = [] } class FormField { var id = UUID() var name: String = "" } struct LogCustomizationView: View { @State var form: Form var body: some View { VStack { ForEach(form.fields.indices) { idx in TextField("Name", text: self.$form.fields[dynamicMember: idx]) } } } } The problematic line is: TextField("Name", text: self.$form.fields[dynamicMember: idx]) The first error I got was Missing argument label 'dynamicMember:' in subscript So I added dynamicMember:, which is how it's shown above. Now the error I get is: Cannot convert value of type 'Int' to expected argument type 'WritableKeyPath<_, _>' A: SwiftUI errors can be really nebulous. You are effectively trying to bind a FormField object to a Binding<String> where neither the object adopts BindableObject nor the name ivar (which you assumably want to bind) has a publisher attached to it (@Published). I guess you want to bind the name ivar to the TextField: ForEach(form.fields.indices) { idx in TextField("Name", text: self.$form.fields[idx].name) }
{ "pile_set_name": "StackExchange" }
Q: Quotienting $SU(3)$ by $U(1)$? As is well-known, if we quotient $SU(2)$ by the action of $U_1$, embedded in the diagonal as $(e^{i \theta}, e^{-i \theta})$, we get the $2$-sphere. As is also well-known, if we quotient $SU(3)$ on the diagonal by $U(1) \times U(1)$, embedded in the diagonal as $(e^{i \theta_1}, e^{i \theta_2}, e^{-i(\theta_1 + \theta_2})$ then we get the full flag manifold of $SU(3)$. However, we can also embed $U(1)$ into $SU(3)$ on the diagonal as $(e^{i \theta}, e^{-i \theta}, 1)$. What is the corresponding quotient? Is it somehow pathological? A: The various different ways that $\mathrm{U}(1)\simeq S^1$ can appear as a subgroup of $\mathrm{SU}(3)$ are indexed by a lattice of rank $2$, and the $7$-dimensional quotients are now known as Aloff-Wallach manifolds, after a paper by Simon Aloff and Nolan Wallach, An infinite family of distinct 7-manifolds admitting positively curved Riemannian structures (Bulletin of the AMS 81 (1975), 1–222). Your particular one is not singular in any way, nor do I think it has any particular pathologies. In recent years, a great deal has been learned about Aloff-Wallach manifolds, more than I can recount here. I suggest a literature search.
{ "pile_set_name": "StackExchange" }
Q: What NFC protocol is used to read information on a Passport? I'm experimenting with NFC and realized that my passport actually stores data that is only available when the passport is opened. (A closed passport doesn't seem to divulge any information) What sequence of instructions is required to read data from a passport? I assume a passive reading is insufficient, and some challenge / response is required. (I base this on how existing 3rd party NFC applications interact with passport data) A: Information in passports is protected by the Basic Access Control protocol, the standard can be found here. In order to read from the passport you need certain pieces of information; the passport number, the D.O.B and the date of expiry. NFC TagInfo is quite a nice app that can read passports amongst other things, make sure you enter the correct information before attempting the read though. It can take a few seconds to read due to the amount of information being transferred. In the USA there are foil covers over the passport which prevent the NFC working without the passport being open however with my UK passport I can read it just fine when it's closed.
{ "pile_set_name": "StackExchange" }
Q: Adding “required” text to an HTML form via CSS I have a <form> that looks like this: <form> <input type="text" name="name" id="name" /><span class="required"></span> </form> What I want to do is show some text, such as * or Required in the <span> element, instead of "hard coding" the text for every such place I need the text so the form looks something like this: [input box] Required I googled around and found that it could be done by a CSS style using content such as: .required:before { content: "aaaa" } But, should I be using this technique (is it supported in every major browser for example) or is there a more preferred way to do this sort of thing? Thanks UPDATE Ps. I don't want to use JavaScript for this, just plain CSS. A: Check this : Content aslo check this compatiblity Don't use I feel that we shouldn't use the content declaration at all. It adds content to the page, and CSS is meant for adding presentation to the page, and not content. Therefore I feel that you should use JavaScript if you want to dynamically generate content. CSS is the wrong tool for this job. A: I agree that adding content using CSS is not right in most cases. However, visually highlighting a required field I find totally okay to do this way. content is not supported widely enough (IE doesn't support it at all IIRC). What you could do is have the "required" span contain a background image containing the "required" text or an asterisk. Using graphical text has some downsides, but none that a jQuery based solution wouldn't have either.
{ "pile_set_name": "StackExchange" }
Q: How long does sp_blitz take to execute? I'm trying to run sp_blitz on SQL Server 2014 and it seems to be taking a long time. What is the normal length? We only have around 30 databases. One is 300GB, but it's going on for 15 min. A: Can be anywhere from 5 seconds to 15 minutes depending on your server, workloads, databases, etc. If you have thousands of databases, for example, you can check out the documentation and use switches like @CheckUserDatabaseObjects = 0 to go faster by skipping stuff.
{ "pile_set_name": "StackExchange" }
Q: In Java, is a global variable always put on the heap? Also, how does having a static variable affect things? (If at all) For example: class MyClass{ static int[][] data; static { data = new int[some number][some number]; /*read data into array*/ } static void run() { /*now use data here*/ } } Is this put on the heap? Comparing that example with class MyClass{ static void run() { int[][] data = new int[some number][some number]; /*now use data here*/ } } How much difference is there between these two code examples? Please shed any insight. A: Java has a concept of PermGen space - this is the space used to store all class definitions, static variables, interned strings, etc. here is link This Java heap memory is structured again into regions, called generations. The longer an object lives, the higher the chance it will be promoted to an older generation. Young generations(such as Eden on Sun JVM) are more garbage collected than older generations(survivor and tenured on Sun JVM). However, there is also some separate heap space called permanent generation. Since it is a separate region, it is not considered part of the Java Heap space. Objects in this space are relatively permanent. Class definitions are stored here, as are static instances. A full description of PermGen space can also be found here, although note that this is changing with Java 8: here is link Static variables are stored there, dynamically allocated things are stored in the regular heap. (Note that even for the static array the things placed within the array are dynamically generated). Your second example is better for this case though unless you really need to remember the contents of that array between calls. You are using up memory all the time to store an array that you only need while you are inside the method. Additionally by having the static data like that your method is not re-entrant. That means that if two threads call the method at the same time then they will interfere with each other and give bad results.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to encrypt my files without full disk encryption I want to encrypt my files and folders without full disk encryption and encrypted volumes. Can anyone help me? A: This site should give you all the information you need. The link was found at upubuntu.com. Here is a direct quote from the site: "encrypt or decrypt your files using the Nautilus context menu (right-click menu) under Ubuntu" Add a PGP key so that you can encrypt your files with it, by opening "Passwords and Keys", click the add button, select "PGP Key", then click Continue. Add the seahorse-nautilus plugin with sudo apt-get install seahorse-nautilus && nautilus -q && nautilus Right click to pick any file and then select Encrypt In a pop-up, pick your key, set "Sign message as: Your key" and click OK. Another pop-up asks for the passphrase which matches up w/ the PGP key.
{ "pile_set_name": "StackExchange" }
Q: parallelly execute blocking calls in python I need to do a blocking xmlrpc call from my python script to several physical server simultaneously and perform actions based on response from each server independently. To explain in detail let us assume following pseudo code while True: response=call_to_server1() #blocking and takes very long time if response==this: do that I want to do this for all the servers simultaneously and independently but from same script A: Use the threading module.
{ "pile_set_name": "StackExchange" }
Q: GXT 3, editable grid, need to perform action on enter I am new to GXT 3, and am confused by the API. Perhaps you could clarify. In Editor Grid, how do I catch and examine keyboard keys pressed inside a cell in focus? A: Create your grid and pass it to GridEditing instance: final GridEditing<MyType> ge = new GridInlineEditing<MyType>(grid); // note: final Grid grid = new Grid(store, cm); // note: ColumnModel cm = new ColumnModel(configs); // note: List> configs = new ArrayList>(); Construct your ColumnConfig ColumnConfig<MyType, String> kanji = new ColumnConfig<MyType, String>(kfgProps.kanji()); // note: kfgProps here extends PropertyAccess Add your editor ge.addEditor(kanji, text); // note: text = new TextField(); Add your DomHandler text.addDomHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode()) { // do whatever } } }, KeyDownEvent.getType());
{ "pile_set_name": "StackExchange" }
Q: How do you make a .mov "click to watch" so that it is not downloaded immediately? On my website, I have an embedded video (.mov) which opens and begins to play immediately when the user opens the page. I would like to make the site easier to use by making an image of the first frame which users can click on to begin the video. What's the best way to do this in HTML/javascript? A: The way I did this was to make a javascript function which updated the innerHTML line when clicked, like this: function displayVideo() { document.getElementById('videoContainer').innerHTML = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="320" height="480" style="float:left"><param name=src value="resources/screencast.mov" /><param name=controller value=false /><param name=autoplay value=true /><param name=loop value=true /><embed src="resources/screencast.mov" width="320" height="480" controller=false autoplay=true loop=true pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" /></object>'; }
{ "pile_set_name": "StackExchange" }
Q: how to split the string in one column and compare it with other column in Python Let's say I have a dataframe as follows: Paste_Values AB_IDs AC_IDs AD_IDs AE-1001-4 AB-1001-0 AC-1001-4 AD-1001-2 AE-1964-7 AB-1964-2 AC-1964-7 AD-1964-1 AE-2211-1 AB-2211-1 AC-2211-3 AD-2211-2 AE-2182-4 AB-2182-4 AC-2182-7 AD-2182-5 I would like to split the column Paste_value into AE and 1001-4 and compare the 1001-4 is in Ab_IDS by split Ab IDS by AB and 100-4 if 1001-4 is same in the Paste value and AB_IDS we need create a new columns called AB_Match and return "Match" in that row AS produce get followed compare Paste_value with AC_ids and create new column called AC_match if its match it show have "match" in it result should look like this : Paste_Values AB_IDs AC_IDs AD_IDs AB_match Ac_match AD_match AE-1001-4 AB-1001-0 AC-1001-4 AD-1001-2 Match AE-1964-7 AB-1964-2 AC-1964-7 AD-1964-1 Match AE-2211-1 AB-2211-1 AC-2211-3 AD-2211-2 Match AE-2182-4 AB-2182-4 AC-2182-7 AD-2182-5 Match I have a new question with the same Problem 1.I have to create a new column called new_Paste_value in the last digit of paste value should not match with any of the AB_IDS, AC_IDs, and AD_IDs I need to generate a random number which the last digit should not match all three IDS Last digit number My result looks like this Paste_Values AB_IDs AC_IDs AD_IDs AB_match AC_match AD_match new_p_v AE-1001-4 AB-1001-0 AC-1001-4 AD-1001-2 Match AE-1001-5 AE-1964-7 AB-1964-2 AC-1964-7 AD-1964-1 Match AE-1964-4 AE-2211-1 AB-2211-1 AC-2211-3 AD-2211-2 Match AE-2211-8 AE-2182-4 AB-2182-4 AC-2182-7 AD-2182-5 Match AE-2182-6 A: You can use: m=df.filter(like='ID').apply(lambda x: x.str.split('-',n=1).str[1]) m.columns=[i.split('_')[0]+'_Match' for i in m.columns] m[:]=np.where(m.eq(df.Paste_Values.str.split('-',n=1).str[1],axis=0),'Match','') df_final=df.join(m) Paste_Values AB_IDs AC_IDs AD_IDs AB_Match AC_Match AD_Match 0 AE-1001-4 AB-1001-0 AC-1001-4 AD-1001-2 Match 1 AE-1964-7 AB-1964-2 AC-1964-7 AD-1964-1 Match 2 AE-2211-1 AB-2211-1 AC-2211-3 AD-2211-2 Match 3 AE-2182-4 AB-2182-4 AC-2182-7 AD-2182-5 Match A: You can do with s=df.apply(lambda x : x.str.split('-',1).str[-1]) s=s.drop('Paste_Values',1).eq(s.Paste_Values,0).replace({False:'',True:'Match'}) s.columns=s.columns.str.replace('IDs','match') df=pd.concat([df,s],axis=1) df Out[221]: Paste_Values AB_IDs AC_IDs AD_IDs AB_match AC_match AD_match 0 AE-1001-4 AB-1001-0 AC-1001-4 AD-1001-2 Match 1 AE-1964-7 AB-1964-2 AC-1964-7 AD-1964-1 Match 2 AE-2211-1 AB-2211-1 AC-2211-3 AD-2211-2 Match 3 AE-2182-4 AB-2182-4 AC-2182-7 AD-2182-5 Match
{ "pile_set_name": "StackExchange" }
Q: LINQ - querying top 5 with rank number How do I return a top 5 with rank number using linq? Dim Top5 = From A In DAO.Cache.Select(Of VO.Empresa).Take(5) Select A.Nome I would like this result: Rank Name 1 "Example Name" 2 "Example Name" 3 "Example Name" 4 "Example Name" 5 "Example Name" A: You need to use the Select overload which provides the index: Dim Top5 = DAO.Cache.Take(5).Select(Function(A, Index) New With { .Rank = Index, .Name = A.Nome }) (I kept the property spelling .Nome - though I suspect it may need to be .Name)
{ "pile_set_name": "StackExchange" }
Q: Object initialization - why are object attributes initialized with " : " not " = " Been going through Angular tutorials and realized that : is used for type declarations, while = is used for value assignment. Looking at the following code export class HeroesComponent implements OnInit { hero: Hero = { id: 1, name: 'Windstorm' } I don't understand why id and name are using : as opposed to = since the type was already declared and we are assigning a value to the attributes of hero. export class HeroesComponent implements OnInit { hero: Hero = { id = 1, name = 'Windstorm' } Above is code that I would expect to work but is incorrect. A: Objects can be initialized using different methods in JavaScript. One method you are probably more familiar with is by first creating an instance of an object and assign properties through the constructors, getters and setters, or by directly mutating the object property // Creates a hero object with no properties let hero = new Hero(); // Creates a hero object with defined properties let hero = new Hero(1, 'Windstorm'); // Creates a hero object then sets the object property let hero = new Hero(); hero.id = 1; hero.name = 'Windstorm'; While these methods of creating objects in JavaScript are valid, you will most often see developers use Object Literals, which is a list of name-value pairs, separated by commas. You may have noticed, but JSON adopts the same syntax that Object Literals use, with one difference in being language-independent (Object Literals are unique to JavaScript). To extend my explanation a bit, you can assign any data type to object literal property values: it can be an array, a string, an integer, ANOTHER OBJECT LITERAL, etc. all at the simple press of the ":" on your keyboard. Hopefully I was able to help, best of luck!
{ "pile_set_name": "StackExchange" }
Q: Can somebody help we draw following complex figure using tikz? Can somebody help we draw following complex figure using tikz? A: I can't help you with TikZ, but here is an effort in Metapost. I've only done the first bit so far Here is the source. Compile with mpost. prologues := 3; outputtemplate := "%j%c.eps"; def ? = infont"pcrr8r"scaled.9 rotated 2 normaldeviate enddef; beginfig(1); -z1 = z2 = 100 right; z3 = z2 rotatedabout(z1, 61); path t; t = z1 -- z2 -- z3 -- cycle; drawoptions(withpen pencircle scaled 2); draw t; draw for i=1, 5, 7, 2.2, 4, 8: point i/3 of t shifted (normaldeviate, normaldeviate) -- endfor cycle; z0 = 1/3 (z1 + z2 + z3); label("text1"?, 1/3 (point 5/3 of t + point 6/3 of t + point 7/3 of t)); label("text2"?, 1/3 (point 7/3 of t + point 8/3 of t + z0)); label("text3"?, 1/3 (point 7/3 of t + point 5/3 of t + z0)); label("text4"?, 1/3 (point 4/3 of t + point 5/3 of t + z0)); label("text5"?, 1/3 (point 0/3 of t + point 1/3 of t + point 8/3 of t)); label("text6"?, 1/3 (z0 + point 1/3 of t + point 8/3 of t)); label("text7"?, 1/3 (z0 + point 1/3 of t + point 2.2/3 of t)); label("text8"?, 1/3 (z0 + point 2.2/3 of t + point 4/3 of t)); label("text9"?, 1/3 (point 2.2/3 of t + point 3/3 of t + point 4/3 of t)); label.bot("text"?, origin); picture brk; brk = image(draw origin {dir 40} ... {dir 82} 2(5, 15) withpen pencircle scaled 2; draw origin {dir -30} ... {dir -84} 2(6, -13) withpen pencircle scaled 2;); z10 = point 2 of t shifted -(50, 30); draw brk shifted z10; label.lft("text10" ?, z10); z12 = point 0 of t shifted (-16, 27); draw brk shifted z12; label.lft("text12" ?, z12); z11 = point 3/2 of t shifted 36 right; draw brk reflectedabout(up, down) shifted z11; label.rt("text11"?, z11); endfig; end. (PS. Don't take this too seriously...)
{ "pile_set_name": "StackExchange" }
Q: Templates_c permissions differ when rebuilt on command line or by apache This is related to, but not a duplicate of, CiviCRM rebuilding templates_c with permissions. I am using civicrm 5.1.2 / Drupal 7 / Apache / Linux. It is best practice not to let www-data own files in the Drupal tree. By the principle of least privilege, the web server should not be allowed to write to directories that it does not need to write to. And obviously someone needs to be able to write to them so that you can log on and upgrade and so on. So I set up the permissions as suggested here . User jane has ownership of all the files and directories apart from the files directory, which is owned by www-data. This does not work with CiviCRM and drush. When you do a drush cc or drush cvupdb in the command line, as jane, the templates_c and ConfigAndLog directories get files added to them with owner jane and group www-data (I have set the setgid bit in order to ensure that the group remains www-data) and they get created with group write permissions. That is all well and good - the web server has write permissions via the group, and then is able to update the files when it needs to. But when the web server creates the files itself, it creates them with www-data as both the group and the user. This is of course all it can do. However, it does not set group write permissions. That means that the next time jane logs on to do something from the command line that writes to those directories, she can't. What do you suggest? A: civibuild shows a few ways to tackle this problem. File Permission ACL's work well if they are available on your system. Edit: You will need to set the ACLs to cover future files created in the directory as well as existing ones. For this, use the -d flag as shown here https://serverfault.com/a/445096. Further edit: Set the ACLs on the civicrm directory above the templates_c directory. Sometimes the whole templates_c directory gets deleted and rebuilt.
{ "pile_set_name": "StackExchange" }
Q: How do I use protobuf on a Mac with Python? I installed the package and ran all of the correct commands. I did this for 2.6.1, 2.7, and 3.2. Between each I subsequently uninstalled the previous version. Within each version I went into the python folder and ran the python installation commands. I ran brew install protobuf (and subsequently uninstalled it). I ran sudo pip install protobuf (and subsequently uninstalled it). The issue I am constantly getting is that the generated .py protobuf file calls imports from google.protobuf, but I am returned an error: ImportError: No module named google.protobuf I then copy in the google folder (which you shouldn't have to do) and it stops returning that error, but the file and examples won't work. A: I was/am using PyCharm. The protobuf library doesn't automatically get linked to the PyCharm interpreter. If you run python script.py from the command line, there are no issues with missing modules.
{ "pile_set_name": "StackExchange" }
Q: Why do we need dual space In functional analysis there are many places where dual space is mentioned, but I still don't understand the real power of that concept. Why do we need the dual space? A: More generally, if $X$ and $Y$ are sets (resp. vector spaces over a common field $k$), we can consider the set $Y^X$ of all mappings (resp. the vector space $\mathrm{Hom}(X,Y)$ of all linear mappings) from $X$ to $Y$. These are obviously interesting to study if you think in terms of structures and structure preserving maps; and dual spaces are simply a special case (namely $\mathrm{Hom}(X,k)$). Also $\mathrm{Hom}$ behaves very nicely with respect to short exact sequences, and is deeply related to the tensor product. Now apparently you are interested in a functional analysis point of view: here we assume that the dual space is the topological dual space (i.e. continuous linear functionals); the dual space is always complete (regardless of whether $X$ is complete or not) and points can be separated by elements of the dual space, which is often useful. A dual space which is particularly interesting is $\mathscr{D}'$: the space of distributions (here $\mathscr{D}$ is $C^\infty_0$ endowed with its canonical LF topology); it can be shown that if $P(\partial)$ is any linear constant coefficient partial differential operator, then there is a distribution $E$ (called a fundamental solution for $P(\partial)$) such that $P(\partial)E=\delta_0$ in the sense of distributions (this is the theorem of Malgrange-Ehrenpreis). This is a very important result because of the following corollary: if $f\in C^\infty_0$, then the PDE $P(\partial)u=f$ admits a $C^\infty$ solution explicitly given by $u=E\ast f$. In physics (say electrodynamics) this is used all the time to solve PDE's. Also, one often seeks weak solutions for the PDE $P(\partial)u=f$ (i.e. this equation is satisfied in the distribution sense) and then tries to prove that they are strong (usual) solutions; this is a very convenient method.
{ "pile_set_name": "StackExchange" }
Q: cURL doesn't seem to work in a while loop I'll just post the whole thing since it would be a bit confusing otherwise: <?php echo "<html> <head> <title>ARMORY.</title> <meta http-equiv='Content-Type' content='text/html' charset=iso-8859-1> </head> <body> <table width='50%' border='1' cellpadding='10' cellspacing='10'>"; $server = "Sunstrider"; $guild = "Mist"; $url='http://eu.wowarmory.com/guild-info.xml?r='.$server.'&gn='.$guild.'&p=1'; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); $xml = curl_exec($ch); $rosterxml = new SimpleXMLElement($xml); curl_close($ch); $array = array(); foreach($rosterxml->guildInfo->guild->members->character as $char) if(strtolower($char['level']) === '80') { $array[] = $char['name']."<br />"; } echo " <tr> <td valign='middle'>Name</td> <td valign='middle'>TEST</td> </tr>"; $i = 0; while($array[$i] != null) { $name = $array[$i]; $raidurl='http://eu.wowarmory.com/character-achievements.xml?r='.$server.'&cn='.$name.'&c=168'; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $raidurl); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1"); $xml2 = curl_exec($ch); $achievementxml = new SimpleXMLElement($xml2); curl_close($ch); var_dump($achievement); echo "<tr> <td>$array[$i]</td> <td></td> </tr>"; $i++; } ?> </body> </html> That var_dump of $achievement just produces NULL over and over again (obviously due to the loop) instead of any information about the array. Doing a var_dump of $rosterxml produces the expected effect though, so cURL seems to work fine outside of the while loop. A: That is because your variable is called $achievementxml and not $achievement. I would advise you to code with error_reporting=E_ALL so you can catch errors like this. Undefined variables will result in an E_NOTICE level error message.
{ "pile_set_name": "StackExchange" }
Q: How to check if someone is on Google+ by email address? We're trying to get some Google reviews for a company by contacting their past clients and asking them to leave reviews. The process is substantially easier if they already have a Google+ account. Is there an easy way to search by email to see if they have an account? A: In Google Contacts (or through Gmail Contacts) the user information will show a "Connected Profile" if they're on Google+.
{ "pile_set_name": "StackExchange" }
Q: Modifying a jQuery ajax request intercepted via ajaxSend() I'm using ajaxSend() to intercept requests originating from a jQuery plugin on my page and then filtering irrelevant requests using the ajaxOptions url. $('some-selector').ajaxSend(function(e, xhr, settings) { var ajaxUrl = settings.url; if (ajaxUrl.search('targetpage.aspx') == 0) { //need to add an additional parameter to my request here } } I need to insert an additional parameter into relevant requests. Is it possible to modify the request at this point? A: You could append the parameter to the settings.data hash by checking that it is not null before: if (settings.data == null) { settings.data = { }; } settings.data['param'] = 'value'; or just modify the url: settings.url += (settings.url.match(/\?/) ? "&" : "?") + 'param=value';
{ "pile_set_name": "StackExchange" }
Q: What does the ~ in front of the SASS/SCSS @import mean/do? I was told on GitHub to start using a ~ before my SASS/SCSS @import paths. Tried to Google it but couldn't find a proper answer. I guess it's too newbie to even bother writing about, but I would like to learn it. A: It refers to the node_modules directory (or its equivalent). For instance, in an Angular app (which uses node.js and webpack, of course) you could have this: A nav-bar.component.scss which references (@import) ~bootstrap/scss/functions. The ~ part refers to node_module and the rest of it (bootstrap/scss/functions) refers to the rest of the path inside the node_module directory (see images below)
{ "pile_set_name": "StackExchange" }
Q: Is there a a way to make this function calculate sd as well as mean? setNames(apply(cats, 1, , na.rm = TRUE), df[[1]])) I would like mean and sd to be outputted by one function. A: Here is an option with dplyr library(dplyr) iris %>% summarise_at(vars(Sepal.Length), list(mean = ~mean(., na.rm = TRUE), sd = ~sd(., na.rm = TRUE))) # mean sd #1 5.843333 0.8280661
{ "pile_set_name": "StackExchange" }
Q: SUM a field with distinct grouped records I have a really tricky SQL issue which I can't get to the bottom of. I have a SQL view which lists servers and their power connections to power strips (around 44,500 connections to around 8,000 power strips. What I now need to do is create a view which shows a single entry for each power strip and its total load in watts. This is a short example of the table that I'm working from: POWERSTRIP_VOB_ID DEVICE_VOB_ID WATTS 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 988BD4A4-CAC7-4CC9-B1F8-274D75C48796 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 67174BE5-9065-4131-8817-EB584F940A39 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 44713911-F1D8-45E6-9FFA-DCD29F0A5EDA 1164 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 D4495808-AE45-4F8E-ADB0-A97C5F79FD70 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 A9B17915-85F2-4FE1-915A-044312177845 7481 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 5AC7AA8A-8A56-4E09-A607-98985782B32B 1746 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 A9B17915-85F2-4FE1-915A-044312177845 7481 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 A9B17915-85F2-4FE1-915A-044312177845 7481 As you can see, all of the lines have the same POWERSTRIP_VOB_ID. In this example all of the servers have at least one connection to this powerstrip. You will also note that the Device starting with A9B17915 has three connections to the power strip. If I use DISTINCT and GROUP BY the POWERSTRIP_VOB_ID with a SUM on Watts I get a result of 25,404. What I need to do is essentially ignore any of the duplicate connections so that the query only sums the servers once for the powerstrip . In this example I would be looking for the sum of: POWERSTRIP_VOB_ID DEVICE_VOB_ID WATTS 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 988BD4A4-CAC7-4CC9-B1F8-274D75C48796 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 67174BE5-9065-4131-8817-EB584F940A39 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 44713911-F1D8-45E6-9FFA-DCD29F0A5EDA 1164 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 D4495808-AE45-4F8E-ADB0-A97C5F79FD70 17 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 A9B17915-85F2-4FE1-915A-044312177845 7481 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 5AC7AA8A-8A56-4E09-A607-98985782B32B 1746 This should result in 1 record in the view which would be something like: POWERSTRIP_VOB_ID WATTS 5FA38587-FA3E-4BF0-B87C-B782B0FD9284 10442 Hopefully I've explained that well enough. I've played with GROUP BY, DISTINCT and SUM(DISTINCT) and can't seem to get the output that I need. Any help would really be appreciated. Many Thanks Simon A: I think this is what you need: SELECT POWERSTRIP_VOB_ID, SUM(WATTS) FROM ( SELECT DISTINCT POWERSTRIP_VOB_ID, DEVICE_VOB_ID, WATTS FROM myTable ) GROUP BY POWERSTRIP_VOB_ID; The inner query excludes the duplicates, and the outer query makes the sums. From your description I get that it is impossible for 2 records to have the same POWERSTRIP_VOB_ID and DEVICE_VOB_ID values, but differing WATTS. I suppose that would be an indication of database inconsistency. Anyway, if this occurs, the above query will sum both values.
{ "pile_set_name": "StackExchange" }
Q: What's a good metric for determining the performance of my ethernet link across my optical comm. channel? I have a system that I've built for using optical signals to communicate underwater. I'm using a GNURadio + USRP system to test this and I have a program that creates an ethernet connection across my system. I need to measure the link quality as a function of communication distance, water quality, etc. My question is what method should I use to measure ethernet link quality, and how? Say I have a FTP connection, how would I go about measuring and plotting the retransmits? Or, is there an easy way to directly measure TCP packet CRC failures? What other useful metrics could I gather? I want something more high-level than bit-error rate vs. signal/noise. A: Wireshark is a very useful tool for examining ethernet links. Ethernet has its own check that it performs before TCP's check. It is the Ethernet layer that catches line errors and is probably the best place to be investigating. A: Netperf seems to be a popular tool for analyzing ethernet links. I think it is installed by default in Ubuntu.
{ "pile_set_name": "StackExchange" }
Q: Passing an array.push function in javascript I have a problem passing an array.push function in javascript having a code like this: const array = []; addToArray("works", (e) => array.push(e)); addToArray("notWorks", array.push); doConsoleLog("hello", console.log); function addToArray(element, pushFn) { pushFn(element); } function doConsoleLog(message, log) { log(message); } Just curious how's that first call of addToArray works, but second causes TypeError: Cannot convert undefined or null to object. How is it possible? Type of array.push is a function. It is not possible to pass functions directly like in the case of console.log above, which works pretty well? A: push is a method of array. When invoked, it uses this as a reference to the object it is being called on. If you pass it around like a normal function, you will lose that reference, the method will use the value of this defined at the moment of the call (inside addToArray, this is probably document.window), and will therefore fail. In order to pass around a method, you need to bind it to the object you want it to operate on, in this case array. This is true for any object method in JavaScript. Function.prototype.bind() exists exactly for this purpose: it "binds" a function (in this case your method) to a given value of this, in order to work correctly. const array = []; addToArray("now it works", array.push.bind(array)); // or addToArray("now it works", Array.prototype.push.bind(array)); function addToArray(element, pushFn) { pushFn(element); }
{ "pile_set_name": "StackExchange" }
Q: Durand-Kerner with derivative in denominator The correction term for Durand-Kerner root finding method is $w_k = -\frac{f(z_k)}{\prod_{j\not=k}(z_k - z_j)}$ Wikipedia Talk page mentions that it is also possible to use derivative in denominator, instead of the above product. How to form such derivative? All I have are coefficients of the polynomial and the approximations of the roots. How to come up with coefficients of the derivative so I can evaluate it with Horner scheme like I do it for evaluation of polynomial (the $f(z_k)$)? Am I correctly assuming that the derivative is looks perhaps like $g'(x)$ where $g(x) = \prod(z_k - z_j)$? PS: I tried to implement the expression by Bo Jacoby from the Talk page but I cannot get it to work: I tried to sum all the products of all the approximations but one and put the result into denominator but it doesn't seem to work that way... A: Yes, you assume correctly that the update can also be written as $$ w_k=-\frac{f(z_k)}{g'(z_k)}. $$ And correct, the derivative of $g$ can be written as sum of products according to its construction as product of linear factors $$ g(x)=(x-z_1)…(x-z_n) $$ (note that the leading coefficient of $g$ is $1$, so that this must also hold for $f$) $$ g'(x)=\sum_{k=1}^n\;\prod_{j\ne k}(x-z_j). $$ However, for small to medium degrees ($\deg f < 70$ or so) there is no gain in going the route via the construction of $g$ and $g'$. The standard evaluation of the products and of the value of $g'$ have about the same number of operations, and in the second case there is the overhead of constructing $g$. For larger degrees one can use Karatsuba or FFT based methods to speed up the multi-point evaluation of $g'$ so that this way becomes faster. (But then the question is of how viable numerical results in general are due to the high degree.)
{ "pile_set_name": "StackExchange" }
Q: How to reload / refresh model data from the server programmatically? Background I have the most basic "newbie" AngularJS question, forgive my ignorance: how do I refresh the model via code? I'm sure it's answered multiple times somewhere, but I simply couldn't find it. I've watched some great videos here http://egghead.io and went quickly over the tutorial, but still I feel I'm missing something very basic. I found one relevant example here ($route.reload()) but I'm not sure I understand how to use it in the example below Here is the setup controllers.js function PersonListCtrl($scope, $http) { $http.get('/persons').success(function(data) { $scope.persons = data; }); } index.html ... <div> <ul ng-controller="PersonListCtrl"> <li ng-repeat="person in persons"> Name: {{person.name}}, Age {{person.age}} </li> </ul> </div> ... This all works amazingly well, each time the page is reloaded I see the list of people as expected The questions Let's say I want to implement a refresh button, how do I tell the model to reload programmatically? How can I access the model? it seems Angular is magically instantiating an instance of my controller, but how do I get my hands on it? EDIT added a third question, same as #1 but how can it be done purely via JavaScript? I'm sure I'm missing something basic, but after spending an hour trying to figure it out, I think it deserves a question. Please let me know if it's duplicate and I'll close + link to it. A: You're half way there on your own. To implement a refresh, you'd just wrap what you already have in a function on the scope: function PersonListCtrl($scope, $http) { $scope.loadData = function () { $http.get('/persons').success(function(data) { $scope.persons = data; }); }; //initial load $scope.loadData(); } then in your markup <div ng-controller="PersonListCtrl"> <ul> <li ng-repeat="person in persons"> Name: {{person.name}}, Age {{person.age}} </li> </ul> <button ng-click="loadData()">Refresh</button> </div> As far as "accessing your model", all you'd need to do is access that $scope.persons array in your controller: for example (just puedo code) in your controller: $scope.addPerson = function() { $scope.persons.push({ name: 'Test Monkey' }); }; Then you could use that in your view or whatever you'd want to do.
{ "pile_set_name": "StackExchange" }
Q: Native VC++ using external (not project) dll reference how to specify path to dll I have a native VC++ project that uses a dll (which is not in a project). Now, I must to put the dll in one the "Search Path Used by Windows to Locate a DLL" link but I don't want the dll to sit in the exectuable or current or windows or system directory. So my only option according to that is adding the path to the %PATH% environment variable. Is there any other way? Is there an elegant way to do so (adding to PATH)? should I do this on installation? should I be concerned if i'm doing this? A: Summing up all the techniques I have found: If you use a managed project as the startup project (which is actually my case) use Enviroment class string temp = "myFullDirectoryPathToDll"; string temp2 =Environment.GetEnvironmentVariable("PATH") + ";" + temp; Environment.SetEnvironmentVariable("PATH", temp2); this, and I think MSDN should have stressed that, changes the environment variable PATH only in this process. when debugging in VS the appPath doesn't 'work' use properties->debug->environment and merge environment variables link If you use a native: do explicit linking - seems like big work for something simple, maybe use appPath registery key on deployment link, nobody had a tested-and-proved answer A: Here are a few suggestions: You could embed the dll as a resource in your main executable and then extract it to a temporary directory and load it from their using LoadLibrary and then get the relevant function addresses using GetProcAddress. You could modify you main processes search path using SetDllDirectory() to include the location of the DLL. This avoids having to make any global changes to the system. And again use LoadLibrary/GetProcAddress to resolve the function addresses.
{ "pile_set_name": "StackExchange" }
Q: PHP Laravel - Display a collection string in blade view I have a controller and want to display the collection to my blade view as is. here's my code public function reserveSchedule($id){ $schedule = DB::table('schedules AS s') ->select('s.lesson_name AS title','s.time_start AS start','s.time_end AS end') ->where('s.teacher',$id) ->get(); return view('pages.reserve',compact('schedule')); } in my blade view I need to display the schedule variable. So i did {{$schedule}} but it is giving me an error htmlentities() expects parameter 1 to be string, array given I know that the collection is an array, but I need the array to be just a string of array so I can parse it as a JSON in my javascript and use it with my fullCalendar events. Appreciate any help. I am using Laravel 5.1 by the way. Thanks guys! A: Re - Edited Answer --- If you want to parse $schedule as JSON, you can just json_encode() it before you assign it to the view. $schedule = json_encode($schedule);
{ "pile_set_name": "StackExchange" }
Q: error occurred when run site this error occurred when run site Login failed for user 'NT AUTHORITY\NETWORK SERVICE A: Sorry I solved It The Connection string information wasn't right
{ "pile_set_name": "StackExchange" }
Q: Alternative proof of the Bolzano-Weierstrass Theorem The proof I know of the Bolzano-Weierstrass Theorem (i.e. that every bounded sequence has a point of accumulation, and hence a convergent subsequence) proceeds by constructing an increasing sequence between the two bounds, not necessarily a subsequence of the original sequence. It goes on to show that there exists a subsequence of the original sequence that converges to the same limit as the increasing sequence. Now the fact that every convergent sequence has either an increasing subsequence or decreasing subsequence (or both) follows from the Theorem that every convergent sequence is a Cauchy sequence. It follows that every bounded sequence has either an increasing or decreasing (or both) subsequence. My question is can this be turned on its head and used to prove the Bolzano-Weierstrass Theorem in the first place. i.e. can we prove that every bounded sequence has either an increasing or decreasing (or both) subsequence (without first proving the Bolzano-Weierstrass Theorem) and hence actually prove the Bolzano-Weierstrass Theorem that every bounded sequence has a convergent subsequence since every bounded increasing or decreasing sequence converges. Thank you. A: Yes, you can. You can refer to Theorem 3.4.7 on Page 80. Given a sequence $(x_n)$, we can define $x_m$ is a peak if $x_m\ge x_n$ for all $n\ge m$. Then we separate the discussion into two cases, that is, $(x_n)$ has infinite many peaks (hence a decreasing subsequence) or $(x_n)$ has finite many peaks (hence an increasing subsequence).
{ "pile_set_name": "StackExchange" }
Q: Set default rightBarButtonItem for UINavigationController Sup guys, I have a tabBarController with a navigationController on each tab. I wanted to set de default right bar button of navigation bar so I wouldn't have to write the same code on 3 different view controllers. I tried [[UINavigationBar appearance] setRightBarButtonItem:myButton]; but had no success, is says: -[_UIAppearance setRightBarButtonItem:]: unrecognized selector sent to instance Then I tried to create my own UINavigationController subclass so I could set the button like: self.navigationItem.rightBarButtonItem = myButton but again no success, nothing seems to happen probably because I dont have a navigationItem at this time. Anyone have another solution? A: If you inherit from the UIViewController you can set the right button like this UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"foobar.png"] style:UIBarButtonItemStylePlain target:self action:@selector(myAction)]; self.navigationItem.rightBarButtonItem = rightButton; [rightButton release];
{ "pile_set_name": "StackExchange" }
Q: What does $0 mean in an HTML tag? <hr size="3" noshade $ 0> I'm learning the basics of HTML through an online course, and recently I was taught the <hr> tag. I understood the purpose of the <hr> tag, and the use of its attribute size - but what does the $0 mean in it? What function is it performing there? A: The $0 symbol is not part of HTML, it appears in the DOM Inspector to indicate the currently selected element. The $0 variable, when typed in the Console, will be a reference to that element which you can use for ad-hoc JS.
{ "pile_set_name": "StackExchange" }
Q: App works in ios simulator, but changes to index.ios.js not showing up I just installed react-native and did: react-native init AwesomeProject I've opened the project in xcode (version 7.2), and clicked the run button. The build completed and the app launched in a simulator. I turned on live reloading and made a simple edit to "index.ios.js", but the change did not show up. I even closed the simulator, cleaned the project, and rebuilt and relaunched it. Still, the change did not show up. What could be causing this and how can I fix it? A: Make sure the index.ios.js file you're editing is the same one running in the simulator. I know this seems obvious, but I've caught myself working on a file I thought was the file in the simulator but actually wasn't.
{ "pile_set_name": "StackExchange" }
Q: Link between forward and inverse regression ($\text{E}(X|Y)$ and $\text{E}(Y|X)$ ;$ \text{var}[\text{E}(X|Y)]$ and $\text{var}[\text{E}(Y|X)]$) In a multivariate context, that is with at least X or Y being a random vector, are there formulae or theorems that link (even remotely) the forward and inverse regression, $\text{E}(X|Y)$ and $\text{E}(Y|X)$ ? Or alternatively $\text{E}(X_i|Y)$ and $\text{E}(Y|X_i)$, where $X_i$ is a given component of $X$. Similarly, can something be said about $\text{var}[\text{E}(X|Y)]$ and $\text{var}[\text{E}(Y|X)]$ ? Or alternatively $\text{var}[\text{E}(X_i|Y)]$ and $\text{var}[\text{E}(Y|X_i)]$, where $X_i$ is a given component of $X$. Both $X$ and $Y$ are supposed to be random. The typical application case is that $X$ follows a chosen distribution (for instance a multigaussian) and $Y$ is a function of $X$. The link function is too complicated to be used or even unknown (it is typically a numerical model). The distribution of $X$, however, is controlled. Thus, one should formulate hypothesis on $X$ if needed. *Note : this question is related to dimension reduction trhough the sliced inverse regression technique. It is also related to sensitivity analysis, as $\text{var}[\text{E}(Y|X)]$ is the numerator of Sobol' index (surprisingly, the tag sensitivity-analysis does not exist -- if someone with sufficient reputation read this, he might want to create it).* A: Note that $\mathbb{E}(X \vert Y)$ heavily depends on this joint distribution, which is not determinated by $\mathbb{E}(Y \vert X)$. Consider the simple case where $X$ and $Y$ are scalar r.vs and $Y=X+\varepsilon$ where $\varepsilon$ has mean zero and is independent of $X$. Depending on the distribution of $\varepsilon$, one can find examples where the function $\mathbb{E}(X \vert Y=y)$ is respectively increasing, constant or decreasing in $y$ for large $y$. Yet in all cases, $\mathbb{E}(Y \vert X=x) \equiv x$.
{ "pile_set_name": "StackExchange" }
Q: Does Google Chrome Frame break IE8 console output? This is a question about debugging a project, not about writing the code. I am on the final stages of developing an HTML5 web app. Fairly last minute, our client tells us it should run on IE8. Since I use the HTML5-canvas in the app, this required the addition of Google Chrome Frame. Once installed and testing, however, IE8's developer console no longer prints any data, and the HTML viewer never loads. Is this a bug? Is there a way to fix it? It will really suck if I need to debug with alerts... A: From Google Chrome Frame documentation: You can use the Web Inspector in GCF just as you would in the Google Chrome browser. To use it, right-click and choose "Inspect Element". Logging is available via the console.log method, and you can set breakpoints and inspect network activity.
{ "pile_set_name": "StackExchange" }
Q: How do I create arrays with different types I need my array to store a bool and string pair. MyType[,] array1 = { {true, "apple"}, {false, "orange"} }; // Later in my code. for (i = 0; i < array1.Length; i++) { if(array1[i, 0] == true) { Console.WriteLine(array1[i, 1]); } } How do I get the above in C# without using collection? If not possible, which collection should I use? A: Arrays can't have different datatypes. It is the design principle of Arrays. Instead, create a class/struct and then create array/list of that class. Something as following, class MyClass { bool flag; string myStr; } List<MyCLass> myList=new List<MyClass>(); ArrayList arrList = new ArrayList(); //or use this option You should be able to access list using foreach in c#.
{ "pile_set_name": "StackExchange" }
Q: How long does it take a Widow Mine to attack an enemy unit? I have been trying to incorporate the new Widow Mine unit into my army. When I burrow the Widow Mine their is a circle that indicates it's attack radius. However, I have noticed that when enemy units enter into it's attack radius, the Widow Mine's ability Unstable Payload doesn't activate instantly. Instead the Widow Mine takes "a few seconds" and then fires it's missile. This has become increasingly perplexing as I have seen: Zerglings run partly into and then out of the firing radius of a Widow Mine without the ability triggering. Zerglings on Creep with the Metabolic Boost run through the attack radius of a Widow Mine without it detonating. How long does an enemy unit need to be in the attack radius of a Widow Mine for the Unstable Payload ability to be triggered? A: A Widow Mine takes 1.5 in game seconds to lock on to an enemy and fire. This translates to different real time seconds based on game speed: Slower - 2.49s Slow - 1.875s Normal - 1.5s Fast - 1.241s Faster - 1.088s Source
{ "pile_set_name": "StackExchange" }
Q: Dividing entities into groups I have a LINQ entity framework query that returns something like this: {Start: 1/1/2000T18:00:00, FirstName: John, LastName: Doe}, {Start: 1/1/2000T18:00:00, FirstName: Bob, LastName: Doe}, {Start: 1/1/2000T18:00:00, FirstName: Jack, LastName: Doe}, {Start: 1/1/2000T22:00:00, FirstName: John, LastName: Doe}, {Start: 1/1/2000T22:00:00, FirstName: Bob, LastName: Doe}, {Start: 1/1/2000T22:00:00, FirstName: Jack, LastName: Doe}, {Start: 2/1/2000T10:00:00, FirstName: John, LastName: Doe}, {Start: 2/1/2000T10:00:00, FirstName: Bob, LastName: Doe}, {Start: 2/1/2000T10:00:00, FirstName: Jack, LastName: Doe}, {Start: 2/1/2000T14:00:00, FirstName: John, LastName: Doe}, {Start: 2/1/2000T14:00:00, FirstName: Bob, LastName: Doe}, {Start: 2/1/2000T14:00:00, FirstName: Jack, LastName: Doe}, e.g shifts of people in different days and different times. I want to create an object where the shifts are divided into days and hours like so: 1/1/2000: [ 18:00:00: [ {FirstName: John, LastName: Doe}, {FirstName: Bob, LastName: Doe}, {FirstName: Jack, LastName: Doe} ] ] etc... Is there a convenient way to do that with LINQ to entities? Thanks! A: You can use "group by" to group by multiple properties, but you first need to extract out the date and time portions of the Start. You could group first by date and then by time, or a syntactically simpler way is to group by both and then group the inner collection by the time: var x = from shift in Shifts let date = EntityFunctions.TruncateTime(shift.Start) let time = EntityFunctions.CreateTime(shift.Start.Hour, shift.Start.Minute, shift.Start.Second) group shift by new { date, time } into groupedByDate select new { Date = groupedByDate.Key.date, ShiftsByTime = from g in groupedByDate group g by groupedByDate.Key.time }; You could also just group by pairs of {date, time} if you don't care about the hierarchy: var x = from shift in Shifts let date = EntityFunctions.TruncateTime(shift.Start) let time = EntityFunctions.CreateTime(shift.Start.Hour, shift.Start.Minute, shift.Start.Second) group shift by new {date, time}; This is a more verbose but semantically equivalent query to the first one above. I checked the generated SQL and it's more or less equivalent: var x = from shift in Shifts let date = EntityFunctions.TruncateTime(shift.Start) group shift by date into groupedByDate select new { Date = groupedByDate.Key, ShiftsByTime = from g in groupedByDate let time = EntityFunctions.CreateTime(g.Start.Hour, g.Start.Minute, g.Start.Second) group g by time };
{ "pile_set_name": "StackExchange" }
Q: java.lang.reflect.InvocationTargetException for date JSON serializer converts a list into string When i try to convert my list JSON serializer coverts a list into string with following code JSON jsonString = JSONSerializer.toJSON(myList); It give following exception java.lang.reflect.InvocationTargetException java.lang.IllegalArgumentException java.sql.Date.getHours(Date.java:143) A: Hope this helps https://forums.oracle.com/forums/thread.jspa?threadID=83378 Solution is to use java.sql.Time instead of java.sql.Date
{ "pile_set_name": "StackExchange" }