text
stringlengths
70
452k
dataset
stringclasses
2 values
88 level on a particular digit in a numeric array? I was working on a brute-force implementation of this RosettaCode challenge. I wanted to be able to handle numbers bigger than USAGE BINARY-DOUBLE so I wrote a dead simple bignum routine for adding. If I want to limit myself to a certain number of iterations and that number is greater than 9(18) then that's tricky. So I hit upon the idea of an 88 on a particular element of the array, thus the code below. 03 DIGITS1 OCCURS 40 TIMES PIC 9. 03 FILLER REDEFINES DIGITS1. 05 FILLER pic<PHONE_NUMBER>. 05 FILLER pic 999999999. 05 filler pic 9. 88 EOR value 1. 05 filler pic<PHONE_NUMBER>. 05 filler pic<PHONE_NUMBER>. So I'm still wondering if this is the only way to go or is there some other way of handling when I get to 10^20. This is the full "solution". It's a mess but it almost working. identification division. program-id. Program1. data division. working-storage section. 01 COUNTER. 03 DIGITS1 OCCURS 40 TIMES PIC 9. 03 FILLER REDEFINES DIGITS1. 05 filler pic<PHONE_NUMBER>. 05 FILLER pic<PHONE_NUMBER>. 05 filler pic<PHONE_NUMBER>. 05 filler pic 999. 05 filler pic 9. 88 EOR value 1. 05 filler pic 999999. 01 INCREMENTOR. 03 DIGITS1 OCCURS 40 TIMES PIC 9. 01 ACCUMULATOR. 03 DIGITS1 OCCURS 40 TIMES PIC 9. 01 IN-NUMBER usage binary-double unsigned. 01 I USAGE BINARY-DOUBLE UNSIGNED. 01 N USAGE BINARY-DOUBLE UNSIGNED. 01 THREE-COUNTER USAGE BINARY-CHAR value 1. 88 IS-THREE VALUE 3. 01 FIVE-COUNTER USAGE BINARY-CHAR value 1. 88 IS-FIVE VALUE 5. 01 ANSWER pic x(40). procedure division. initialize COUNTER ACCUMULATOR incrementor. 10-MAIN-PROCEDURE. move 1 to IN-NUMBER. call "MOVENUMTOBIGNUM" using by content in-number by reference incrementor. move 1 to IN-NUMBER. call "MOVENUMTOBIGNUM" using by content in-number by reference counter. PERFORM 20-INNER-LOOP WITH TEST AFTER UNTIL eor. move ACCUMULATOR to ANSWER. inspect answer REPLACING LEADING '0' by space. DISPLAY answer. STOP RUN. 20-INNER-LOOP. IF IS-THREE OR IS-FIVE call "ADDBIGNUMS" using by content counter by reference accumulator IF IS-THREE MOVE 1 TO THREE-COUNTER ELSE ADD 1 TO THREE-COUNTER END-IF IF IS-FIVE MOVE 1 TO FIVE-COUNTER ELSE ADD 1 TO FIVE-COUNTER END-IF ELSE ADD 1 TO FIVE-COUNTER END-ADD ADD 1 TO THREE-COUNTER END-ADD END-IF. call "ADDBIGNUMS" using by content INCREMENTOR by reference counter. EXIT. end program Program1. identification division. PROGRAM-ID. MOVENUMTOBIGNUM. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 num-MOD usage binary-CHAR. 01 num-DIV usage binary-DOUBLE unsigned. 01 IN-COUNTER usage binary-char. LINKAGE SECTION. 01 num usage binary-double. 01 BIGNUM. 03 DIGITS1 OCCURS 40 TIMES PIC 9. PROCEDURE DIVISION USING NUM BIGNUM. 10-MOVE. move 40 to IN-COUNTER. perform until num = 0 divide num by 10 giving num-DIV REMAINDER num-MOD end-divide move num-MOD to DIGITS1 of BIGNUM(IN-COUNTER) move NUM-DIV to NUM subtract 1 from IN-COUNTER end-subtract END-PERFORM. GOBACK. END PROGRAM MOVENUMTOBIGNUM. *Add Bignum to Bignum, modifying second Bignum in situ identification division. program-id. ADDBIGNUMS. DATA DIVISION. WORKING-STORAGE SECTION. 01 IN-COUNTER usage binary-char. 01 ADD-FLAG pic 9. 88 STILL-ADDING VALUE 0. 88 DONE-ADDING VALUE 9. 01 CARRIER usage binary-char. 01 REGISTER-A usage binary-char. LINKAGE SECTION. 01 BIGNUM1. 03 DIGITS1 OCCURS 40 TIMES PIC 9. 01 BIGNUM2. 03 DIGITS1 OCCURS 40 TIMES PIC 9. PROCEDURE DIVISION USING BIGNUM1 BIGNUM2. 10-ADD-WITH-CARRY. move zero to CARRIER. move 40 to IN-COUNTER. move zero to ADD-FLAG. perform until DONE-ADDING add DIGITS1 of BIGNUM1(IN-COUNTER) DIGITS1 of BIGNUM2(IN-COUNTER) CARRIER GIVING REGISTER-A END-ADD move zero to CARRIER if REGISTER-A > 9 divide REGISTER-A by 10 giving CARRIER remainder REGISTER-A end-divide else if REGISTER-A = zero move 9 to ADD-FLAG END-IF end-if if STILL-ADDING move REGISTER-A to DIGITS1 of BIGNUM2(IN-COUNTER) subtract 1 from IN-COUNTER end-subtract end-if END-PERFORM. goback. END PROGRAM ADDBIGNUMS. (blush) umm ok, will fix. You know that GnuCOBOL can take 36 digits in a numeric? And that for you testing of one digit to work, you have to know that there are only zeros in all digits prior to that one? I do now. I had no idea. I started doing this thing in MFCOBOL then went to GnuCOBOL (using OpenCOBOLIDE) then back to MFCOBOL. The label "gnu-cobol" is thus a tad misleading. Standard COBOL can indeed only have 18 digits. 'initialize COUNTER ACCUMULATOR incrementor.' takes care of the zeros in all digits. I didn't know at the time that the value only rises from the bottom, so you can use the 88 as a "stopper". Did you mean to post that as a comment? For (more) compatibility with Micro Focus you could use -std=MF, I've not got the fastest CPU, but just counting to a full 11 digits took four minutes. 40 digits with the rest of the code is going to take "some considerable while" Yeah, this is worse than than "brute force"; this is "blunt trauma" Shouldn't the code be much faster if you internally work on "native" numerics? So for emulating PIC X(40) you'd use 3 PIC 9(18) with overlapping ranges (simple REDEFINES to access the original data, then MOVE to PIC 9(18) COMP and calculate with those? Although you already don't seem to like the structure, I'll stick to it. It will work with your structure as well. No need for the REDEFINES or those other FILLERs. 05 FILLER. 10 FILLER OCCURS 40 TIMES. 15 DIGITS1 PIC 9. 88 DIGITS1-MEANS-SOMETHING VALUE 1. 01 NAME-THAT-REVEALS-INFORMATION BINARY PIC 9(4). IF DIGITS1-MEANS-SOMETHING ( NAME-THAT-REVEALS-INFORMATION ) do some stuff END-IF I've changed you PIC 9 to PIC X. Unless you are doing calculations, there is never a need to define a field as 9 for "numeric". If a field happens to contain numbers, or happens to have the word number, or something like that in its name, don't be tricked into defining it as a number. Extra (generated) code ensues and it carries the meaning "numeric stuff will be done with this", so misleads. If/when you need to do a "numeric edit" for output, there's always the REDEFINES at that point. Doesn't have to have these other costs to make that happen. I've now reverted to your PIC 9, as, after your edit, I can see you are using it for calculations :-)
common-pile/stackexchange_filtered
create new table - missing parenthesis need to create this but its saying missing left parenthesis? CREATE TABLE active_units2(agency_code varchar2(10) not null, unit varchar2(10) not null, supp_unit_1 varchar2(10) not null, supp_unit_2 varchar2(10) not null, supp_unit_3 varchar2(10) not null, supp_reqmt varchar2(10) not null, alt_priority varchar2(1) not null, alt_group varchar2(1) not null, crew_type varchar2(10) not null, status_control varchar2(1) not null, onduty_status varchar2(10) not null, dependant_res_type varchar2(10) not null, mdt_state varchar2(10) not null, brigade int not null, node int not null, port int not null, breathing_apparatus int not null, manual_crewing int not null, udf1 varchar2(10) not null, udf2 varchar2(10) not null, udf3 varchar2(10) not null, udf4 varchar2(10) not null, CONSTRAINT active_units2_PK PRIMARY KEY CLUSTERED (agency_code ,unit)) Remove 'CLUSTERED' - what are you expecting that to do? I assume it's form another DBMS but I'm not familiar with it... thanks..working now! When you run that statement in SQL*Plus the output you get is: CONSTRAINT active_units2_PK PRIMARY KEY CLUSTERED (agency_code ,unit)) * ERROR at line 24: ORA-00906: missing left parenthesis The * indicates where the problem is - not always helpful but it is in this case. The CLUSTERED key word isn't valid in Oracle, as you can see from the syntax diagram, so you just need to remove that word.
common-pile/stackexchange_filtered
Kinetic energy from Euler and continuity equations vs work done by buoyancy force I have a feeling there's something elementary to it, but I can't seem to understand why I get these answers. I am interested in a stationary 1D inviscid fluid described by the Euler and anelastic continuity equations: \begin{equation} \rho u\frac{du}{dz}=-\frac{dP}{dz}-\rho g=-\Delta\rho g \end{equation} \begin{equation} \frac{d(\rho u)}{dz}=0. \end{equation} Where gravity is downwards, doesn't vary appreciable and the fluid is considered to be always in pressure equilibrium with the surroundings. I can rewrite the continuity equation as \begin{equation} -u^2\frac{d\rho}{dz}=\rho u\frac{du}{dz} \end{equation} and then the term on the left of the Euler equation as \begin{equation} \rho u\frac{du}{dz}=\frac{1}{2}\frac{d(\rho u^2)}{dz}-\frac{u^2}{2}\frac{d\rho}{dz}=\frac{d(\rho u^2)}{dz}. \end{equation} Thus I can write the difference of the fluid's kinetic energy as: \begin{equation} \Delta K=-\frac{g}{2}\int\Delta\rho dz=\frac{W_b}{2}, \end{equation} which is half of the work done by the buoyancy force. Why this factor of two? Did I get anything wrong? EDIT: Maybe for 1D inviscid fluids buoyancy is not a conservative force? But where does the dissipation goes? If $\Delta\rho =\frac{d\rho}{dT}\Delta T$, surely it can't heat further the fluid. But then, the energy conservation equation is missing. It ought to link $\Delta T$ and $u$, so the system is overspecified. Then we need to relax the pressure equilibrium constraint, which probably doesn't really makes sense for a ID fluid anyway, so that heat is dissipated by lowering the fluid's pressure?
common-pile/stackexchange_filtered
How to set ps as shortcut to open powershell The question says it all. I want to learn and use powershell as my go to terminal in windows and I want powershell to open if I type Win+R followed by ps. Much like how cmd is used to open command prompt. https://superuser.com/questions/193000/running-programs-by-typing-some-alias-in-windows You can create a symbolic link (similar to a shortcut) to Powershell with any name you want. This will create one called ps.exe in the powershell folder, this folder is already listed in PATH so will enable you to run ps from the RUN box like you want. mklink %SystemRoot%\system32\WindowsPowerShell\v1.0\ps.exe %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe Be sure to run the command in an elevated command prompt. Great! I modified your simbolic link. Now I can call PowerShell 7 from the windows explorer by typing "ps" in the Adress bar (after installing pwsh7): mklink "%SystemRoot%\system32\WindowsPowerShell\v1.0\ps.exe" "C:\Program Files\PowerShell\7\pwsh.exe" The "default" command for opening PowerShell is powershell. If you want to make it ps, your best bet is to create a batch file named ps.bat containing the single line @powershell %* and place it in one of the directories named in your system PATH variable.
common-pile/stackexchange_filtered
Did AD&D players use Leomund's Tiny Hut to keep out enemies? Brandes Stoddard has a fun article called Leomund's Tiny Problem, where he discusses ways in which Leomund's Tiny Hut is "highly exploitable" in D&D 5e, and offers suggestions on how to fix it. The article provides an interesting history of the way the spell has evolved since AD&D. He writes that beginning with AD&D the spell "only implicitly hedges out creatures other than the caster and six friends", and that even in 3.5e "It's still only implying that unwelcome creatures would be unable to intrude." The relevant wording in AD&D (2e is fairly similar) is as follows: In no way will Leomund's Tiny Hut provide protection from missiles, weapons, spells, and the like. Up to 6 other man-sized creatures can fit into the field with its creator, and these others can freely pass in and out of the tiny hut without harming it, but if the spell caster removes himself from it, the spell will dissipate. So, the spell can't block physical objects (missiles, weapons) or spells. But Stoddard writes that it "implicitly" keeps out enemies, presumably because "these others" refers exclusively to the "6 other man-sized creatures" that can fit into the hut, rather than to whatever any 6 creatures, enemies or allies, could fit. My question is whether there is any historical evidence as to how AD&D (1e or 2e) players actually used this in play. (My own memory is of this spell never being used, which weakly implies that it could not actually function as an impregnable fortress, but I also don't remember the question ever coming up.) The main historical source that comes to mind is Dragon or White Dwarf magazines, but considering some recently published books on the history of D&D (such as Game Wizards: The Epic Battle for Dungeons & Dragons) and how 5e and Stranger Things have sparked an interest in the history of D&D, there might be articles, conference panels, or other sources that can shed light on this. Related (rules) question concerning D&D 4e: Should Leomund's Tiny Hut keep enemies out? Dragonsfoot forums has an active community of people who played 1st Ed back in the day, and many still do. You might ask this question there or even make a poll. Just as a quick search I found this post saying "[magically safe places start] with Leomund's Tiny Hut which is safe, if a bit exposed - you can see the monsters massing around your little bubble!" which implies that at least that player used it as a barrier to monsters. This thread debates to what extent it protects against weather but does not mention monsters. Do note if you try a forum search there that most hits for LTH are for the article series that Len Lakofka wrote for Dragon Magazine, not for the spell itself (Len was the author of the spell and the player of Leomund in Gygax's game). ...why did? Some folk still play AD&D :) @Kirt: Xabloyan's comment there is fairly insightful: "The Leomund spells were invented by Len Lakofka, who, IMHO, was fond of making his spells quite weak." On rechecking, this is pretty accurate. I don't know the complete list of spells Len invented, but the 2E Leomund's spells are mostly long-duration non-combat utilities significantly higher level than they should be (the main spell with combat potential, Leomund's Lamentable Belaborment, is a 5th level spell that heavily overlaps the 2nd level Hypnotic Pattern, and the improvements it grants mostly apply to non-combat scenarios). @ShadowRanger In a game where MUs have to actually find their spells and an imperfect chance of learning them, having two spells, say Alice's Amazing Amuser and Bobs Bewildering Balderdash, that do virtually the same thing but operate at different spell levels may offer some interesting gameplay... @Dave: So redundancy exists to handle bad "Chance to learn spell rules"? I gotta say, if you've been trying to learn Hypnotic Pattern from level 3 (when you first get access) through 9 (when Leomund's Lamentable Belaborment becomes available), with one attempt per level up (so, seven failed attempts), I'm thinking either you shouldn't be playing a wizard with a 9 Int, need to make amends with whatever deity you offended, or both. Maybe just give up on entrancing people, rather than sacrificing more useful 5th level spells just to emulate a low level spell. :-) @ShadowRanger or it's flavor that can tie in to adventure hooks: Magic School A is good at entrancing magic, so if your mentor is from that school, you can learn hypnotic pattern. Magic School B is less good at it, so if you study there, you'd only have access to Leomund's, higher spell slot, spell that is similar. PC had been studying with magic school B, but gets intrigued that they could have different options if they managed to get accepted by school A. @ShadowRanger that and it provides "cover" for the inevitable fact that as the DM adjudicates custom spells, they're not going to always perfectly balance spell levels. I believe that spell research was much more common in AD&D that more current iterations. Bob researches a spell, DM says "it's 5th level". Gameplay ensues, spell seems underpowered. Bob, or any other MU in the campaign, learns that there's Charlie's spell: only 3rd level and does much the same as Bob's hard won spell does. In-lore explanation of this mechanics change. Spell research was assumed to be a common activity at "name level" (9+). Also, first edition had no rules for upcasting. Thus, having spells of similar effects at different levels also provided some more flexibility in achieving the effects you wanted with the slots you had available. Given how much of the 1E and 2E period pre-dates the Internet, I doubt there'd be much actual data to base an answer off of. I played 2E, and personally, I never treated the rules on how many people could fit as implying that it was only specific designated individuals that could enter or exit. The relevant wording describing protective capabilities in 2E was: When this spell is cast, the wizard creates an unmoving, opaque sphere of force of any desired color around his person. [...] Up to seven other man-sized creatures can fit into the field with its creator, and these can freely pass into and out of the hut without harming it, but if the spellcaster removes himself from it, the spell dissipates. ... The tiny hut also provides protection against the elements, such as rain, dust, sandstorms, and the like. The hut can withstand any wind of less than hurricane force without being harmed, but wind force greater than that destroys it. ... Note that although the force field is opaque from the outside, it is transparent from within. Missiles, weapons, and most spell effects can pass through the hut without affecting it, although the occupants cannot be seen from outside the hut. The hut can be dispelled. The spell itself is just creating a sphere around the wizard. The spell specifies how many man-sized creatures can fit in it (so there are no arguments about the precise capacity of a 15' diameter sphere, and how the slope of the sphere reduces space and the like), but those creatures are not targets of the spell (only the caster is special), and there is no indication that the ability to move through the sphere is tied to being within it at casting time, being designated by the caster, being friendly to the caster, etc. This is unlike 5E, which explicitly says: Creatures and objects within the dome when you cast this spell can move through it freely. All other creatures and objects are barred from passing through it. The 2E sphere is clearly not intended as a strong protection; it's essentially an environmental shield that provides one-way visibility of the surroundings, protecting against nothing but the weather, especially at night, where you could stay warm, without drawing attention with a fire visible (potentially) for a few miles around the camp site, with your guards still able to keep watch without exposing themselves to view. You'd even get some defensive benefit from ranged attacks needing to fire blind (basically all rules for concealment and invisibility and the like describe a -4 to hit modifier for attacking blind, which isn't nothing). In a game with dangerous wilderness and a DM who would inflict more random encounters on a party that doesn't take precautions, or a game using more detailed environmental rules (e.g. like those introduced in 2E's Dark Sun setting, where environmental heat and cold effects were thoroughly quantified, and reducing the heat by 30 degrees could make the difference between life and death) this could be worth it by itself. For folks from later editions, you might erroneously interpret "sphere of force" as being impassable by default (because "magical force" gets more strict, consistent and reused definitions in later editions), but there was no fixed concept of what constituted "(magical) force" in 2E. Very few spells referred to force at all, and when they did, the parameters for what was blocked by the force were spelled out in exhausting detail (or incorporated by reference to another spell, usually a similar spell of lower level). For example, Otiluke's Resilient Sphere's wording is: The resilient sphere contains its subject for the spell's duration, and it is not subject to damage of any sort except from a rod of cancellation, a wand of negation, or a disintegrate or dispel magic spell. These cause it to be destroyed without harm to the subject. Nothing can pass through the sphere, inside or out, though the subject can breathe normally. The subject may struggle, but all that occurs is a movement of the sphere. The globe can be physically moved either by people outside the globe or by the struggles of those within. While Wall of Force says: A wall of force spell creates an invisible barrier in the locale desired by the caster, up to the spell's range. The wall of force cannot move and is totally unaffected by most spells, including dispel magic. However, a disintegrate spell will immediately destroy it, as will a rod of cancellation or a sphere of annihilation. Likewise, the wall of force is not affected by blows, missiles, cold, heat, electricity, etc. Spells and breath weapons cannot pass through it in either direction, although dimension door, teleport, and similar effects can bypass the barrier. Wall of Force actually describes itself primarily as "an invisible barrier", because, without some word that says "This blocks things", things are not blocked merely because the word "force" was used; a "force" can be a tingly static field, a slightly resisting membrane in the air, etc., etc., it's not (in older editions) automatically an indestructible, impermeable barrier. This is how much of older editions worked; there was very little pre-defined terminology that could be used to minimize verbosity by referring to a common, explicitly defined game term. Either the words had a plain English meaning, they got defined in place (and the DM had to adjudicate gaps in the definition), or they referenced a specific other thing for details (e.g. Otiluke's Telekinetic Sphere incorporated the base effects of Otiluke's Resilient Sphere by reference). Basically, without the existence of 5E's overpowered Tiny Hut, there'd be no reason to suspect the 2E version was intended to restrict the movement of people, when it allows everything else save rain, dust and sand through. "An opaque sphere of force." Force effects are generally unpassable in AD&D and 2E; the text describing the seven man-sized creatures that can fit in there and how they can freely pass in and out of the sphere is the specification of an exception to the general impermeability of force effects, letting you know that they can pass through it freely, but for other creatures, it's still a sphere of force, and they can't. It's still not the safest bubble in the world to hinge your security on. It's meant to pop a rest, but if you don't have a plan for the massing mobs, you're boned. @TheFallen0ne: You're trying to read 2E under the more rigid/well-defined categorizations introduced in later editions. 2E had no single reusable concept of "force"; the strictures were generally redefined from scratch in each spell, or incorporated by reference to some other (typically lower level) spell. Heck, the actual spell Wall of Force never uses the word "force" except when repeating its own name (it creates "an invisible barrier"; the spell goes on to describe the various things it protects against, and specific exceptions). Even when "force" is used, they specify the protections. Compare Leomund's Tiny Hut to other "force" spells like Otiluke's Resilient Sphere (one of the few other spells that actually says "force" in describing the barrier) and Wall of Force. The latter two explicitly describe the exact parameters for what can and cannot get through the barrier, and list, individually, slightly different sets of spells and items that can destroy/bypass the barrier (and it's not consistent; Wall of Force, the higher level spell, can be destroyed by a subset of the things that end the sphere, plus one thing that doesn't affect the sphere). Amusingly, Wall of Force doesn't explicitly say creatures/objects can't pass through it (just that the spell fails if the wall is created intersecting an object or creature), but it does at least describe it as a barrier (something that blocks things by definition), where, without the strict definition of magical force from later editions of D&D, a "sphere of force" could describe something like the atmospheric shields seen in stuff like Star Wars, where ships can freely pass through them without causing the bay to vent atmosphere (quite similar to what this spell provides actually). The hut did keep out wild animals Leomund's Tiny Hut in AD&D 1e says: (...) In no way will Leomund's Tiny Hut provide protection from missiles, weapons, spells, and the like. Up to 6 other man-sized creatures can fit into the field with its creator, and these others can freely pass in and out of the tiny hut without harming it (...) Leomund's Tiny Hut in AD&D 2e says: (...) Up to seven other man-sized creatures can fit into the field with its creator, and these can freely pass into and out of the hut without harming it, (...) Missiles, weapons, and most spell effects can pass through the hut without affecting it, although the occupants cannot be seen from outside the hut (...) While it is not explicit stated that the six or seven creatures are selected by the caster, if they were not it would not be these creatures that can pass in and out, it would be any creature, as long as no more than the caster and six or seven are in the hut. So the spell did hedge out creatures. Wild animals did not have any means to cast spells, or make weapon attacks into the hut, and it did protect against those, as they themselves could not physically pass in. Even so, it was not worthwhile as a defensive measure against opponents -- while you can read the spell to keep out enemies physically, they still could hit you with spells and weapon attacks, so the Hut did not really provide meaningful protection against orcs or goblins. It was more of a glorified tent. You might prepare it as a creature comfort spell, at best. How much people used the spell to do this is hard to say. There is no survey data. I think I used it a couple of times in Desert of Desolation with a gnome that was focused on comfort, until I found Leomund's Secure Shelter, which was much better at keeping you safe. However, I think the spell was also rare back then, for the following reason: Back in the day, you found most your spells I did play in the 1E/2E era, and like in your case, nearly nobody "picked" the spell back then. The 1e DMG (p. 39) has you roll randomly at first level what offensive, defensive and utility spells you have, and then advises on gaining spells beyond first level: Naturally, magic-user player characters will do their utmost to acquire books of spells and scrolls in order to complete their own spell books. To those acquired, the magic-user will add 1 (and ONLY 1) spell when he or she actually gains an experience level (q.v.). Therefore, most will be frantically attempting to purchase or cozen spells from non-player character magic-users, or even from other player character magic-users. So you had but a single spell to gain on a given level, and because Tiny Hut was rather weak back then, it would have been unusual to burn your pick on it. It also was not that clear if you even get to pick or if you should roll randomly for your new spell. At least in our community, we used to roll randomly, like for first level. All the rest of the spells came from finding them in adventures, either on scrolls or in the spellbooks of defeated opposing evil mages. These spellbooks ususally contained spells that were geared to empower the evil mage to fight the party, like invisibilty, fly, or fireball -- your typical "the spellbook contains the spells the mage has memorized plus spells x, y, z". Leomund's Tiny Hut, as a party-oriented utility spell, was not commonly on the menu of memorized spells for opposing mages, so it is unsurprising it was not commonly found and therefore not used much. Also in second edition, it is not a given the player gets to pick their spells. Page 32, PHB on specialist wizard spell selection: Whenever a specialist reaches a new spell level, he automatically gains one spell of his school to add to his spellbooks. This spell can be selected by the DM or he can allow the player to pick. As a flavor item of interest, Gary Gygax was a fan of Jack Vance's works, including those set on the Dying Earth, which is also listed as inpspirational reading in Appendix Y of the DMG. The spellcasting mechanism of D&D stems from Dying Earth. He particularily liked the stories about Cugel the Clever. In story The Eyes of the Otherworld Cugel uses a magic item that much like Tiny Hut to protect himself from weather and natural predators during his travels and travails. That would fit with other creaturs, but not weapons or spells, being hedged out. "... it would not be these creatures ..." : observation : IMO, the paragraph can be read as contrasting the caster himself vs. these. That is, the these is there because n creatures can pass/fit, but if the caster leaves it dissipates. @Martin: Yeah, that's how I read it. It can fit a certain number of man-sized creatures. Anyone who can fit can enter, and they can freely leave and return unless the sphere is full when they return. If you want to read it very strictly, I suppose it might protect against creatures that aren't man-sized, but really, I read that as defining capacity, not strict "only man-sized can pass"; it would be very strange if you could use this spell to trap the party gnome/halfling. Perfectly reasonable to house rule some minimum size to enter based on its ability to block rain/dust/sand of course. @Martin The "these" would not be needed in that case, you could just say Up to 7 other creatures can fit, and (other creatures) can freely pass in and out of the hut, but the spellcaster himself…". However you read it though, it's just a relatively situational spell for your precious level 3 pick (if you have one), and one rarely found. We at least played it that way, so to the question, which is if people did the answer is yes, even if you think the wording is ambiguous. Agreed. The answer to "How was Leomund's Tiny Hut used back in 1e, 2e?" is, "It Wasn't". I actively played AD&D several times a week for over a decade (including many conventions) and other than random spell rolls and maybe one published module, I NEVER saw any player, nor even any DM ever use it. (And DM's don't necessarily have to worry about spell slots). Virtually everyone considered it to be nigh-useless, and a real head-scratcher as to why it was even in the spell lists.
common-pile/stackexchange_filtered
Is it possible to change the playback rate value of a Spotify track playing on my website? The thing is... Spotify doesn't seem to create an audio or video element to play these tracks so I can change the playback rate from the element reference, it creates an <iframe> element instead: <iframe src="https://sdk.scdn.co/embedded/index.html" alt="Audio Playback Container" allow="encrypted-media; autoplay"> <html> <head> <meta charset="UTF-8"> <title>Spotify Embedded Player</title> </head> <body> <script src="index.js"></script> </body> </html> </iframe> The script source is: https://sdk.scdn.co/embedded/index.js Is the 'allow="encrypted-media"' telling me something? I know this is possible on the official Spotify website, because a video or audio element is created, but since I'm using the Spotify Web Playback SDK, I can't do that. Are you referring to the open/embedded player? I don't see an iframe in this sample 5+ hour audio (maybe they've changed things). https://open.spotify.com/embed-podcast/episode/4N8VtcWq3A2FSCiFrexzHl Though I still can't find any object to apply/update the playbackRate. Can you provide an example (url) where Spotify changes the playback speed? Totally forgot those embedded players existed, my bad, I was talking about the Web Playback SDK: https://developer.spotify.com/documentation/web-playback-sdk/ If you get this on your own website, it creates an iframe. Search for any Spotify Playback Speed browser extension. That's the way I know it can be changed. I can only suspect that Spotify is using HTMLAudioElement or WebAudioAPI without an HTML element. This question, or this one may give you clues, but my attempts at modifying the Spotify playbackRate were unsuccessful.
common-pile/stackexchange_filtered
Calling a method from another class inside JSF Managed Bean In a Java Web Project(JSF+Spring), i want to do this: i have a search box in index.xhtml, i want that when i click search button, a method called from a class, and then result get's back: this is index.xhtml: <h:body> <h:form> <h:inputText value="#{searchBean.phrase}"></h:inputText> <h:commandButton value="Search" action="result"></h:commandButton> </h:form> </h:body> this is result.xhtml: <h:body> #{searchBean.result} </h:body> this is searchBean.java: @ManagedBean @SessionScoped public class SearchBean { private String phrase; private String result; private SearchClass searchObject; public String getPhrase(){ return this.phrase; } public void setPhrase(String value){ this.phrase = value; } public String getResult(){ this.result = searchObject.search(getPhrase()); // here throws to an error return this.result; } public void setResult(String value){ } } and this is searchClass: public class SearchClass{ public String search(String searchPhrase) { return "this is a sample result"; } } but when i run this, this sections throws to an error: public String getResult(){ this.result = searchObject.search(getPhrase()); // here throws to an error return this.result; } it seems calling a method from another class not allowed. this is error 500 that i get: java.lang.NullPointerException com.media.search.web.controller.SearchBean.getResult(SearchBean.java:35) i just want to get some information from a method, whats the wrong here? should i do something in xml config files related to JSF or Spring? Where is searchObject instantiated? If you want the container to create it you must inject it it seems my problem is related to instantiation of searchObject. i use a interface. i do this and it works: public SearchService searchService = new SearchServiceImpl();
common-pile/stackexchange_filtered
Confusion about proving there is no finite measure on a countable set $X$ other than the trivial measure which assigns measure $0$ to every set. A measure $\nu$ is finite if $\nu(X) < \infty$. Let $X$ be a countable set and let $\mathcal A$ be the $\sigma$-algebra of all subsets of $X$. Prove there is no finite measure on $X$ other than the trivial measure which assigns measure $0$ to every set. What if $X$ is finite? We can assign to each set in the $\sigma$-algebra, the cardinality of the set. So $\nu(X)=|X|$. You need to put some restriction to ensure such a measure does not exist. For example there is no translation invariant finite measure on a countably-infinite set. Otherwise there are as many measures as there are convergent series. The claim is not true. Let $(x_k)_{k=1}^{\infty}$ be an enumeration of $X$. Then let $\mu(\{x_k\}) = 2^{-k}$. This generates a finite measure on $X$ with $\mu(X) = \sum_{k=1}^{\infty} 2^{-k} = 1$. Why would $\mu({x_1} )=1/2$ but $\mu({x_2} )= 1/4$? A measure can behave like that. You haven't said that $\mu$ should be symmetric in any way. Oh, I am not sure. The question in the book is posed as such. Does it matter at all that we are considering the sigma algebra consisting of the power set of $X$? No, it doesn't. I am having trouble understanding why we are allowed to define $\mu$ in such a way. Can you please elaborate. We're taking $\mathcal A$ to be the power set of $X$. Therefore singleton sets (i.e. sets containing only one point) are measurable. And nothing forces every singleton set to have the same measure. For an arbitrary set $E \subseteq U$ we set $\mu(E) = \sum_{x \in E} \mu({x})$. This satisfies all the axioms of a measure. Check it! But wouldn't different enumerations of $X$ lead to different values for a subset? Yes, it would. So what? Then $\mu$ would not be well defined. Would it? Yes it would. We take a specific enumeration. If you want a specific example, take $X=\mathbb N$ with its natural enumeration (and no other enumeration).
common-pile/stackexchange_filtered
Adding Vector Data - GML format with WFS Transport (possible bug?) I'm trying to add features to my OpenLayers map, by querying a publicly available WFS server which serves GML data. // initalize the map var map = new ol.Map({ layers: [ new ol.layer.Tile({ // OpenLayers public map server source: new ol.source.OSM() }), ], target: 'map', view: new ol.View({ // center on Murica center: [-10997148, 4569099], zoom: 4 }) }); var xmlhttp = new XMLHttpRequest(); // execute this once the remote GML xml document has loaded xmlhttp.onload = function() { console.log("GML XML document retrieved. executing onload handler:"); var format = new ol.format.GML3(); var xmlDoc = xmlhttp.responseXML; console.log("you will see multiple features in the xml: "); console.log(xmlDoc); // Read and parse all features in XML document var features = format.readFeatures(xmlDoc, { featureProjection: 'EPSG:4326', dataProjection: 'EPSG:3857' }); console.log("for some reason only a single feature will have been added: ") console.log(features); console.log("Why is this?"); var vector = new ol.layer.Vector({ source: new ol.source.Vector({ format: format }) }); // Add features to the layer's source vector.getSource().addFeatures(features); map.addLayer(vector); }; // configure a GET request xmlhttp.open("GET", "http://geoint.nrlssc.navy.mil/dnc/wfs/DNC-WORLD/feature/merged?version=1.1.0&request=GetFeature&typename=DNC_APPROACH_LIBRARY_BOUNDARIES&srsname=3857", true); // trigger the GET request xmlhttp.send(); Here is a CodePen with the bug demonstrated. http://codepen.io/anon/pen/yamOEK Here you can download it packaged into a single HTML file: https://drive.google.com/open?id=0B6L3fhx8G3H_cmp1d3hHOXNKNHM I can successfully download an entire feature collection with multiple features into my variable xmlDoc, using a valid typename. However, when I use format.ReadFeatures(xmlDoc), the OpenLayers GML format parser appears to only be extracting a single feature from the feature collection, whereas it should be extracting many more. It would be wonderful if someone could take a look and see if they can figure out if I'm doing something stupidly wrong or it's a legitimate bug in OpenLayers3. Thanks so much for anyone who's able to help! Cross-posted as https://gis.stackexchange.com/q/216125/115 Single feature is added because entire document is read so instead of format.readFeatures(xmlDoc) parse each feature.Here is source code: var vector; var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), ], target: 'map', view: new ol.View({ center: [-8197020.761224195,8244563.818176944], zoom: 4 }) }); var xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { var format = new ol.format.GML3(); var xmlDoc = xmlhttp.responseXML; vector = new ol.layer.Vector({ source: new ol.source.Vector({ format: format }) }); for (var i = 1; i < xmlDoc.children[0].children.length; i++) { var features = format.readFeatures(xmlDoc.children[0].children[i], { featureProjection: 'EPSG:4326' }); features.getGeometry().transform('EPSG:4326', 'EPSG:3857'); vector.getSource().addFeature(features); } map.addLayer(vector); map.getView().fit(vector.getSource().getExtent(), map.getSize()) }; xmlhttp.open("GET", "http://geoint.nrlssc.navy.mil/dnc/wfs/DNC-WORLD/feature/merged?version=1.1.0&request=GetFeature&typename=DNC_APPROACH_LIBRARY_BOUNDARIES&srsname=3857", true); // trigger the GET request xmlhttp.send(); Here is a CodePen result. http://codepen.io/anon/pen/bwXrwJ IT WORKS PRAISE dev9 GOD OF ALL EPSGs
common-pile/stackexchange_filtered
Google SQL instance stuck after operation "restore from backup" After I proceed to restore database from automated backup file generated on Mar 13, 2019, the SQL instance stuck in this state forever:" Restoring from backup. This may take a few minutes. While this operation is running, you may continue to view information about the instance." The database size is very small, less than 1MB. Google Cloud Support here! To investigate the issue, there are more information needed, that are private and can not be posted here. If you have a Google Cloud support, please fill a support ticket. If you do not have support, please open a private Google issue using your project ID. Than post the link to issue that you created as a comment here. With this link I can take a look into your project. As a workaround you can try to restore backup on a new Cloud SQL Instance @PawelCzuczwara The SQL instance is backup running now. Thanks. It took longer time than usual and showed An unknown error occurred. But the instance works now and recovered itself. For future users that experience problems like this is in the future, here is how you can handle it: If you have a Google Cloud support package, file a support ticket directly with support for the quickest response. Otherwise please file a private GCP issue describing the problem, remembering to include the project id and instance name. However - Cloud SQL instances are monitored for stuck states like this, so often the issue will resolve itself within a few hours.
common-pile/stackexchange_filtered
How can I make Onboard, the visual keyboard, open in Ubuntu on startup? I am working with an application using a touch screen. For this, I need Onboard (the on-screen keyboard) to open from Ubuntu's startup time with a fixed width and height. I also need to get a reserved screen position for placing Onboard (which means that Onboard should not be in front of any application windows). I'm using Ubuntu 12.04 LTS. Onboard was not installed in my system. I installed it by typing sudo apt-get install onboard in the terminal. It doesn't work properly. Now the system shows Onboard when I type onboard in the terminal. Onboard closes itself when I close the terminal. Open Gedit and type: #!/bin/bash # you can change the size of the window below (1000x300) onboard -s 1000x300 Now save this file somewhere as filename.sh and open a terminal window. Navigate to this file location by using: cd /home/user/blah/blah/../filename.sh When you get there type in sudo chmod a+x 'filename.sh' (quotes are there for avoiding space character problems). Now you've made it an executable bash script. Open 'gnome-session-properties' from terminal and click on Add. Name: Onboard Command: "Browse to the file location" Comment: Onboard on startup Click add and you're done! Logout and login to see if it worked. Thanks brother,It works. But it shows only on login time so that i can enter my User_password with Onboard. I lost it when i logged in to my account. can i do anything more? Is "Start Onboard hidden" checked in Onboard preferences? That might be it; Because it works quite fine for me. No. I took Onboard Preferences. But in the 'general' tab the only unchecked thing is this "Start Onboard hidden". Thanks Python, i did the same thing again as you said and it works fine.Thank you very much.
common-pile/stackexchange_filtered
Google Sheets conditional formatting a row based on finding either of two words in a string Users are able to enter a string into a cell. If the string contains either the word "Letter" and/or the word "Note", the entire row needs to turn red. These words are not case sensitive. I can create two conditional formats for the same row but would prefer one that looks for either word. One person had me try =OR(SEARCH(“LETTER”,$M6),SEARCH(“NOTE”,$M6)) in the "Conditional Formula_ Custom Formula is", it did not work. This works for the word "letter" in a string: =SEARCH("LETTER",$M6). This works for the word "note" in a string: =SEARCH("note",$M6). I would like to put them into one statement. try: =REGEXMATCH($M6, "(?i)LETTER|NOTE")
common-pile/stackexchange_filtered
Opposition members in cabinet After the recent collapse of government and appointment of a new Premier in British Columbia, it was suggested by MLA Andrew Weaver that — as he was not a member of the governing party — he could not be appointed as a member of the new Cabinet. Our Constitution Act is pretty vague on this, saying only that the Executive Council is composed of the Premier and “persons the Lieutenant Governor appoints.” Is there any precedent in Westminster parliaments for a minister being appointed from a party other than the government’s? The US is obviously not a Westminster system, but there are many examples of this in the US federal cabinet. How far back do you want to go? The UK has some odd examples from before the 1920s when the party system wasn't quite as it is now. @origimbo as far back as you want. One of the fun things about our system of government is that so little is written down, so precedents can be pulled out of all sorts of “nooks and crannies!” The South African constitution allows 2 ministers to be appointed from outside parliament, although both the current ministers appointed in this way are members of the governing ANC. South Africa has a parliamentary system with a president elected by parliament, and the president appoints ministers. This all comes down to party, and how parties cooperate. In theory, in the Westminster system, the definitions of Government and Opposition don't inherently go along party lines -- however, as you might guess from the italics, there's a 'but' just over the horizon... Political parties originally grew out of two Parliamentary factions. And it's still the case, even in this era of formal parties (and party-funded election candidates), that all of the members can be grouped into two factions: if you're formally counted as supporting the government (i.e. the ministers) then you're part of "the Government"; if you're not, then you're "the Opposition" How parties work in a legislative body is not always in line with their (initial) formal organisation: see, for example, MPs who have been elected under their party banner but then "had the whip withdrawn" i.e. had their party membership withdrawn or suspended; however, they still sit with their party, on the Government or Opposition benches. Or, in the US Congress (which is a slightly different system, I know) you sometimes get the inverse: legislators like Bernie Sanders who aren't elected under a party nomination, but nevertheless "caucus with" a party and so get some of the benefits that come with that (committee assignments) in exchange for the party getting the benefits of increased "membership" (like a larger share of the committee assignments). In the US those "sides" are termed "Majority" and "Minority" rather than "Government" and "Opposition", but what matters is that it's divisible into two broad factions. In Congress, if you caucus with the Majority then you might get one of the gifts that the Majority are in a position to hand out (like being Chair of a Committee). In Parliament (Canadian, or British), if you sit with the Government, vote with the Government (grunt and squeak and squalk with the Government), then in exchange for your support you might get a Ministerial post. So being on the "Government" or "Opposition" sides isn't inherently allied with party membership: SJuan76's answer points out the wartime National Government in Britain. During the National Government, when Government positions were variously occupied by members of the Conservative, Labour, Liberal National, Liberal, National Labour, and National parties, there was still a nominal 'Leader of the Opposition', but that post was held by a member of the Labour Party (even though 'Labour' were in government: quoth Wikipedia, "During World War II a succession of three Labour politicians acted as Leader of the Opposition for the purpose of allowing the House of Commons to function normally, however as in the mid World War I ministry, opposition did not run under a party-whipped system."). But... All other things being equal, the normal practice is for the Government benches to be populated by members of the Government party or parties, and the Opposition benches to be populated by the rest. The Government could give a ministerial post to someone from another party without expecting the support of that party, but (to put it in cold, hard politics) why would they when those positions are such valuable bargaining chips, and are normally only exchanged for significant support in Parliamentery votes? Importantly, once in a Cabinet position one has a say over general government policy – that's not a privilege that a governing party would give to an 'outsider' without needing to. Typically, the largest party only let another party's members join them in Government if they are a long way short of a majority, and need a lot of extra seats on their side: by giving a second party a share of the Ministerial posts (and the commensurate influence over policy) they can ensure that all of that party's members will vote in line with the (collective) Government line. The level of influence that comes with a ministerial post is significant enough that in many cases those posts aren't handed out even if the Government's in the minority: see, for example, the current situation in Britain where the minority Conservative government have promised to tweak some policies in exchange for the support of the Democratic Unionist Party, thereby acquiring an extra ten votes in the House of Commons. Even needing those ten votes, there was no suggestion that the Conservatives would give the DUP a ministerial post. It's also worth noting that, even if a Government party extended the offer of ministerial positions, a party may not be inclined to join the Government. Worse, if the offer were made to an individual member, rather than to a party, that person probably wouldn't accept it, or if they did might be kicked out of their party for trying to serve two masters (see, for example, Ramsay MacDonald, the first British Labour Prime Minister – who headed a Conservative-supported government and was kicked out of his own party for doing so). Note that in Weaver's tweet, he states that "[The BC Green Party] haven't entered a coalition so such a position is off table" – as ever, it comes down to the party line. If Weaver were appointed Minister of the Environment that wouldn't just put him in charge of the Environment Ministry's administration. It would mean that he would be responsible ("collective responsibility") for the actions and policies of the whole Cabinet and, accordingly, would get a say in those decisions. That's not power that most Governments would willingly give to someone from another party unless they were already beholden to that party for some other reason – for example, if they needed that party's votes to pass a budget. ...so there's no inherent reason why Weaver couldn't be Environment Minister, but (unless there's some great issue – like a war – on which (nearly) everyone can agree) the general convention is to only give that degree of influence to parties who you need votes from, trading influence for support. My messiest ever stackexchange answer by far, but the draft has been kicking around my browser for too long. Edits are very welcome. I replied to Weaver's tweet shortly after I wrote this question, and he clarified that it was indeed a party decision to stay in opposition while assuring the government of their support on confidence votes. "there was no suggestion that the Conservatives would give the DUP a ministerial post" thank god for that! +1. A relevant example from the UK is Shaun Woodward, who in 1999 defected from the Conservatives (then in opposition) to Labour (then in government) and was subsequently made a Cabinet minister, as Secretary of State for Northern Ireland (2007-10). The key point is that he defected to Labour well before he was offered a ministerial job. An interesting precedent is the South African politician Jan Smuts, who served in the British War Cabinet in 1917-18. He was not a member of either house of the UK Parliament, or of any UK political party. The obvious reference would be governments of "national unity" in times of crisis, to avoid political dissent to damage the national effort. Examples of it would be: The most known would be the British government during WWII, which included members of the Conservative, Labour and National parties. Already before that, there were some national governments to deal with the 1929 stock crash effects. I'm not sure this really answers the question. A unity government or coalition has more than one governing party; as I understand it, the OP asks about ministers not in any governing party. There are recent precedents for coalition; the UK had a coalition government from 2010-15, with ministers from both the Conservative and Liberal Democrat parties. Theoretically yes, they can. But practically no party with a majority does it. The closest example I can think of is independent India's first cabinet which included opposition politicians who were fierce critics of both PM Nehru and his mentor Gandhi. It is an apt example, as the Indian National Congress that had lead India's freedom movement was so popular that it eclipsed all other parties and had no viable opposition to it. So Gandhi and Nehru decided to include opposition members too in the cabinet: Weeks before India became independent, Jawaharlal Nehru invited B R Ambedkar to join his new cabinet as the minister of law. Unlike most other members of the cabinet, Ambedkar was not part of the Congress party, nor did he share much of the values that Nehru and other senior leaders of the Indian Independence movement believed in. For that matter, Ambedkar was not Nehru’s choice for the portfolio at all. It was Mahatma Gandhi who believed that since it was India and not the Congress that had attained freedom, outstanding men of other political leanings must also be asked to lead the government, especially Ambedkar. - From caste reservations to Kashmir, the many conflicts between Nehru and Ambedkar Nehru enjoyed unprecedented adulation and power ... But Nehru never lost an opportunity to reinforce democratic practices, even if as a ritual. The most telling example is the composition of Nehru’s first Cabinet, formed from the Constituent Assembly (CA) in 1947, much before India became a republic and much before the first election of 1952. In the Assembly, the Congress enjoyed 82 per cent strength, and the PM could have handpicked his cabinet. But he chose Ambedkar as the law minister. Remember, Ambedkar was a fierce critic of Mahatma Gandhi, Nehru’s mentor. But he was the right man as law minister. Nehru chose Dr Shyama Prasad Mookerji as the industries minister. Dr Mookerji had many differences with Nehru, and later broke away and founded the Bharatiya Jana Sangh, the precursor of the BJP. Sardar Patel was Deputy PM and home minister, which went to C Rajagopalachari after Patel’s death in 1950. Rajaji was another detractor of Nehru and also broke away later, to found the right wing Swatantra Party. He was sharply critical of Nehru’s policies, but that did not come in the way of Nehru appointing him a Union minister in the first Cabinet. A government is accountable to all the people of India, not just who voted it to power. The Cabinet, in theory, can appoint the best persons who can deliver as ministers. After 1952, we have never seen a PM reaching outside party limits, to (say) appoint a minister from the opposition MPs. This is not unthinkable, and indeed we saw this in Nehru’s first Cabinet. It may not happen again, but that founding gesture at India’s birth was an important step. - Nehru's first cabinet Another more realistic example is when no political party gets a majority and thus parties have to band together to form coalition governments. In such cases, when a cabinet is formed, they often include members from different parties. So yes, in theory, the Parliamentary system allows any MP to be included in the cabinet, regardless of his party affiliation. But in practice, no political party with an absolute majority does so as political parties too have evolved to become one of the democratic institutions of the system.
common-pile/stackexchange_filtered
Extracting Specific record from webservice XML How would i go about extracting specific information from the XML returned from a webservice. The webservice is called from an embedded webbrowser in a C# windows form. I was thinking that mabey i could save the displayed data as XML file and read from that though it would need to be automatic and not use the save dialog that webbrowser control has. I was also thinking that i could read from the browser and load as xmlDocument. If anyone could point me in the right direction here it would really help, thanks. Is there are reason you are using an embedded webbrowser instead of a WebRequest? Using a WebRequest getting the sourcecode would be trivial. I think the ActiveX internet explorer control had a string property containing the sourcecode which should be what you want. Hmm thats a good point i could use WebRequest, the browser needs to be embedded for the tool, however i dont necessarily need to use the browser for this specific task. i shall look into this thanks.
common-pile/stackexchange_filtered
How can Mybatis generates duplicate Id?Or I should not blame it? I got duplicate ID by the following CREATE STATEMENT and Mapper file. The Datebase I using is DB2. Could anyone help? Thanks a lot! [CREATE TABLE] CREATE TABLE SUP_BCP_TRANS_FLOW (ID INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY, SERIAL_NO VARCHAR(40), BAT_NO VARCHAR(32), PAYER_ACC_NO VARCHAR(40), PAYER_ACC_NAME VARCHAR(255), PAYEE_ACC_NO VARCHAR(40), PAYEE_ACC_NAME VARCHAR(255), PAYEE_PARTY_ID VARCHAR(20), TRAN_AMT DECIMAL(16,2), FEE_AMOUNT DECIMAL(16,2), POSTSCRIPT VARCHAR(300), MEMO VARCHAR(255), RET_TYPE VARCHAR(1), RET_CODE VARCHAR(8), RET_MSG VARCHAR(255), OLD_RET_CODE VARCHAR(32), OLD_RET_MSG VARCHAR(255), STR1 VARCHAR(1024), STR2 VARCHAR(1024), STR3 VARCHAR(1024), STR4 VARCHAR(1024), STR5 VARCHAR(1024), SER_NO VARCHAR(20), OTH_SERIAL_NO VARCHAR(40), NOTICE_STATUS VARCHAR(1), CREATE_TIME TIMESTAMP DEFAULT CURRENT TIMESTAMP, UPDATE_TIME TIMESTAMP DEFAULT CURRENT TIMESTAMP, NOTICE_TIME INTEGER); [Mapper File] https://i.sstatic.net/MmaTa.png insert into SUP_BCP_TRANS_FLOW (BAT_NO,SERIAL_NO,PAYER_ACC_NO,PAYEE_ACC_NO,PAYEE_ACC_NAME,PAYEE_PARTY_ID,TRAN_AMT,FEE_AMOUNT,POSTSCRIPT, MEMO,RET_TYPE,RET_CODE,RET_MSG,OLD_RET_CODE,OLD_RET_MSG,STR1,STR2,STR3,STR4,STR5,SER_NO,OTH_SERIAL_NO,NOTICE_STATUS,NOTICE_TIME) values ( #{item.batNo,jdbcType=VARCHAR}, #{item.serialNo,jdbcType=VARCHAR}, #{item.payerAccNo,jdbcType=VARCHAR}, #{item.payeeAccNo,jdbcType=VARCHAR}, #{item.payeeAccName,jdbcType=VARCHAR}, #{item.payeePartyId,jdbcType=VARCHAR}, #{item.tranAmt,jdbcType=DECIMAL}, #{item.feeAmount,jdbcType=DECIMAL}, #{item.postscript,jdbcType=VARCHAR}, #{item.memo,jdbcType=VARCHAR}, #{item.retType,jdbcType=VARCHAR}, #{item.retCode,jdbcType=VARCHAR}, #{item.retMsg,jdbcType=VARCHAR}, #{item.oldRetCode,jdbcType=VARCHAR}, #{item.oldRetMsg,jdbcType=VARCHAR}, #{item.str1,jdbcType=VARCHAR}, #{item.str2,jdbcType=VARCHAR}, #{item.str3,jdbcType=VARCHAR}, #{item.str4,jdbcType=VARCHAR}, #{item.str5,jdbcType=VARCHAR}, #{item.serNo,jdbcType=VARCHAR}, #{item.othSerialNo,jdbcType=VARCHAR}, #{item.noticeStatus,jdbcType=VARCHAR}, #{item.noticeTime,jdbcType=INTEGER} ) please edit your question to add missing information, the full text of the exception showing which constraint is involved. Things might not be what you assume. Thank you for reply, mao. No exception occurs in my application. All my question is about the column ID. As the CREATE TABLE statement shows above, the ID column is defined by "ID INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY", so I don't need to set the value in the Service layer of my application. I assumed it would be generated by Mybatis, or DB2. And in fact, when I query from database, I find the ID column has its value in every object. But...but...what makes me puzzled is the ID column duplicate its value in different object occasionally!Please help me, mao. Thanks a lot. This has nothing to do with Mybatis - instead, it is caused by the table design. What you observe is the expected behaviour for the GENERATED BY DEFAULT... clause. But you seem to expect the behaviour should correspond with GENERATED ALWAYS AS IDENTITY... clause along with a PRIMARY KEY(id) clause. The combination of these two clauses will guarantee uniqueness. But specifying only the GENERATED BY DEFAULT... clause, with no unique index or primary key constraint will not guarantee uniqueness for that column. The GENERATED BY DEFAULT means that Db2 will generate a unique value only when the appplications do not provide a value. But if any application chooses to supply a value then Db2 will use that value instead (and will not generate a new value), and that application-supplied value does not need to be unique unless your DDL also specified the PRIMARY KEY(id) clause. Remember that more than one application (or person) may be able to insert rows into the table. If you want to ensure the column named 'id' has rows with a unique value in the 'id' column then you must arrange for the table to have a unique index. The easiest way to do that at the time of table-creation is to specify PRIMARY KEY(id) in the CREATE TABLE... statement. You can also create the unique index afterwards, separately, with the create unique index statement, or with an alter table ... add constraint... clause to specify the primary key, although you must first remove any duplicate values by adjustments beforehand. Thanks a lot, mao. Where are you based? We can have a cup of coffee, haha... I will follow your suggestion. But I want to ask another question. Perhaps, I should ask it together with the one above. The fact I missing is that I find two objects just the same--Yes, every attribute(column) is the same,including ID. Could you tell me how this happens? Thank you, mao. @JiajieDu If you have rows with all columns duplicated, it is caused by errors in the application.
common-pile/stackexchange_filtered
Can you reset the nether? Im new to minecraft . I finally got into the nether and was disapointed. I could not find a nether fortress . Can i reset the nether? If i can please let me know. Im on Pc You can't reset the nether, but there are some tricks for finding Nether fortresses. From the Minecraft Wiki article for Nether Fortresses: Nether fortress tend to cluster together in strips that run north and south. When you're searching for your first nether fortress, traveling east or west will give you the best chances of running into one. If you travel north or south, you could travel a long distance between two strips of fortresses. But if you have already found a fortress, you should travel either north or south to find another, which will likely be within a few hundred blocks. Note that north and south spawning is just a tendency and you may not find additional fortresses simply by going north and south from a located fortress in every case. Be flexible in your search and note that additional fortresses may still be east or west from a located fortress. You can see which direction you're traveling by pressing F3. There are also tools for finding nether fortresses given a world seed. Try chunkbase.com. To answer your question, you can reset the nether, but the new one that will generate will be the same as the old one, except without any changes you may have made. (This could be used to cheat, go to the nether, gather resources, reset the nether, gather the same resources in the same location, and so on…) To reset the nether, go to C:\Users\<your windows username>\AppData\Roaming\.minecraft\saves\New World on Windows or ~/Library/Application Support/minecraft on OS X. Next go to the "/saves" folder, and then into the folder that corresponds with the world in which you want to reset the nether. Usually the folder will have the same name as the world it corresponds with. Finally go to the "/DIM-1" folder and delete anything inside. Next time you enter the nether, minecraft will reset the nether to how it was before you made any changes to it. Note: This answers the question "how to reset the nether", but this just erases any changes you may have made to it, thus "reset". You can't really use this to find nether fortresses. Thanks. For actual servers, delete the content in: WORLD_NAME/dim-1 within your server directory. Btw: The respawned nether was not the same as we had before. :/ + there is a new block now, Magma Block or similar to that. We didn't have that one before. :) It is probably different becouse of changes to the world generator in newer updates ;) This was the answer I was looking for, because a power outage caused the nether chunks to be corrupted. You cannot reset the nether without making a new world. There always are nether fortresses in the nether so keep looking. I would install a mini-map mod so you can way point your portal so you can venture further without the worry of loosing your portal. Perhaps the morph mod or another mod so it can allow you to fly so you can travel faster. Do note that they can be affected by the Generate Structures option, so make sure that's on (It's on by default.) Make sure you are using a version of minecraft that have fortresses though. @Skye do not signal your edits in the text. Contrary to most other websites, Arqade (and SE in general) has a full revision history (click on "edited X ago"), so it's not needed. I think you can reset the nether using things like mc edit, but the seed won't change Resetting the nether won't change the position of fortresses, as they are based on the seed which you cannot change without messing other things up. You can use some tools on the internet that show you the exact position of all the fortresses. I would recommend Amidst: https://github.com/toolbox4minecraft/amidst/releases Or if you don't want to install something to your computer, here's a handy online tool (be sure to read the "How To Use" section at the bottom): http://chunkbase.com/apps/nether-fortress-finder Actually, yes you can, in your settings of your world you can find two options (reset nether) and (reset end) you can try looking for those two buttons You can actually reset the nether. Make a new world in creative and go into the nether. If it has a fortress then leave the nether, exit the game then go to C:\Users\username\AppData\Roaming.minecraft\saves then click on the creative world that you created then go to DIM-1 folder copy the contents then move them to your survival world or any other world. Make sure the world you are moving it into you delete all of the contents in the DIM-1 folder.
common-pile/stackexchange_filtered
Can not read property "document" of undefined - ApexCharts I'm attempting to import apexcharts into my nuxt project. I've used both the vanilla lib and vue wrapper. Simply importing the library causes the following error Like I said, i've attempted importing both import ApexCharts from "apexcharts" and import VueApexCharts from "vue-apexcharts" Both return the same error. Is this something I have to configure in the nuxt.config.js file? This is because you are using Nuxt.js which does SSR for you. Since document does not exist on the server-side it will break. To work around it there a couple of approaches: First you can create a plugin/apex.js which is responsible for registering your components import Vue from 'vue'; import ApexChart from 'vue-apexcharts'; Vue.component('ApexChart', ApexChart); and in your nuxt.config.js make sure to load the plugin file on the client-side: module.exports = { // ... plugins: [ // ... { src: '~/plugins/charts', ssr: false } ], // .... }; Now you can reference the ApexChart component anywhere in your app, also make sure to wrap it with ClientOnly component to prevent Nuxt from attempting to render it on the server-side: <ClientOnly> <ApexChart type="donut" :options="chartData.options" :series="chartData.series" /> </ClientOnly> The other approach is you can import Apex charts as async components, which do not get rendered on the server-side, but it has been a hit and miss with this approach, feel free to experiment. Generally when using Nuxt or any SSR solution, be careful of the libraries you use as they might have an implicit dependency on the execution environment, like requiring browser-specific APIs in order to work like window or document.
common-pile/stackexchange_filtered
Auto reloading Flask app when source code changes I know for a fact that Flask, in debug mode, will detect changes to .py source code files and will reload them when new requests come in. I used to see this in my app all the time. Change a little text in an @app.route decoration section in my views.py file, and I could see the changes in the browser upon refresh. But all of a sudden (can't remember what changed), this doesn't seem to work anymore. Q: Where am I going wrong? I am running on a OSX 10.9 system with a VENV setup using Python 2.7. I use foreman start in my project root to start it up. App structure is like this: [Project Root] +-[app] | +-__init__.py | +- views.py | +- ...some other files... +-[venv] +- config.py +- Procfile +- run.py The files look like this: # Procfile web: gunicorn --log-level=DEBUG run:app # config.py contains some app specific configuration information. # run.py from app import app if __name__ == "__main__": app.run(debug = True, port = 5000) # __init__.py from flask import Flask from flask.ext.login import LoginManager from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.mail import Mail import os app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) #mail sending mail = Mail(app) lm = LoginManager() lm.init_app(app) lm.session_protection = "strong" from app import views, models # app/views.py @app.route('/start-scep') def start_scep(): startMessage = '''\ <html> <header> <style> body { margin:40px 40px;font-family:Helvetica;} h1 { font-size:40px; } p { font-size:30px; } a { text-decoration:none; } </style> </header> <p>Some text</p> </body> </html>\ ''' response = make_response(startMessage) response.headers['Content-Type'] = "text/html" print response.headers return response My guess is you started using foreman run instead of python run.py - Flask isn't in control when you run it under gunicorn and so it can't do the auto-reloading. @SeanVieira I use foreman start from command line. Should I do foreman run python run.py? Yes, that is what you would want to do (most likely) - if that doesn't work, use python run.py instead. The issue here, as stated in other answers, is that it looks like you moved from python run.py to foreman start, or you changed your Procfile from # Procfile web: python run.py to # Procfile web: gunicorn --log-level=DEBUG run:app When you run foreman start, it simply runs the commands that you've specified in the Procfile. (I'm going to guess you're working with Heroku, but even if not, this is nice because it will mimic what's going to run on your server/Heroku dyno/whatever.) So now, when you run gunicorn --log-level=DEBUG run:app (via foreman start) you are now running your application with gunicorn rather than the built in webserver that comes with Flask. The run:app argument tells gunicorn to look in run.py for a Flask instance named app, import it, and run it. This is where it get's fun: since the run.py is being imported, __name__ == '__main__' is False (see more on that here), and so app.run(debug = True, port = 5000) is never called. This is what you want (at least in a setting that's available publicly) because the webserver that's built into Flask that's used when app.run() is called has some pretty serious security vulnerabilities. The --log-level=DEBUG may also be a bit deceiving since it uses the word "DEBUG" but it's only telling gunicorn which logging statements to print and which to ignore (check out the Python docs on logging.) The solution is to run python run.py when running the app locally and working/debugging on it, and only run foreman start when you want to mimic a production environment. Also, since gunicorn only needs to import the app object, you could remove some ambiguity and change your Procfile to # Procfile web: gunicorn --log-level=DEBUG app:app You could also look into Flask Script which has a built in command python manage.py runserver that runs the built in Flask webserver in debug mode. The solution was to stop using foreman start as stated in the comments and directly execute python run.py. This way, the app.run method with the debug=True and use_reloader=True configuration parameters take effect. Sample Application where app is our application and this application had been saved in the file start.py: from flask import Flask app = Flask(__name__) @app.route('/') def hallo(): return 'Hello World, this is really cool... that rocks... LOL' now we start the application from the shell with the flag --reload gunicorn -w 1 -b <IP_ADDRESS>:3032 start:app --reload and gunicorn reloads the application at the moment the file has changed automaticly. No need to change anything at all. if you'd love to run this application in the background add the flag -D gunicorn -D -w 1 -b <IP_ADDRESS>:3032 start:app --reload -D Demon mode -w number of workers -b address and port start (start.py) :app - application --reload gunicorns file monitoring Look at the settings file: http://docs.gunicorn.org/en/latest/settings.html all options and flags are mentioned there. Have fun! just note that --reload is incompatible with the preload option https://docs.gunicorn.org/en/latest/settings.html#reload
common-pile/stackexchange_filtered
Force landscape in specific view controller using swift I have app in portrait oriantation for all the view's. I need to make a landscape for specific views. I found this. Put this in the viewDidLoad(): let value = UIInterfaceOrientation.LandscapeLeft.rawValue UIDevice.currentDevice().setValue(value, forKey: "orientation") and, override func shouldAutorotate() -> Bool { return true } the problem is that this function only works if I enable landscape right and left mode, and i don't want my app to support landscape. It seems that you could mark Landscape Right and Landscape Left, then use shouldAutorotate in your views accordingly, but the link below suggests a better method. I believe this will answer your question: http://swiftiostutorials.com/ios-orientations-landscape-orientation-one-view-controller/ You can check if the rootViewController contains a "presented controller" and if it does then that class is checked. Thus, if the "check" goes through the UIInterfaceOrientationMaskAll (allowing Landscape mode) is returned. If it doesn't then Portrait mode defaults. I downloaded the sample project in swift and got everything up and running smoothly. Hope this helps. fun application can't return more than 1 !! could you describe it for swift 2 !? If you do not want your app to support landscape, you can not have a specific view controller forced in landscape, when it loads or whenever you need it. are you sure about this !! ,, cuz i see many apps doing this , that's why i ask !
common-pile/stackexchange_filtered
Why does this Ruby method need to be a class level method? Here's a classic fizzbuzz in Ruby: class PrimeChecker def print_em 1.upto 100 do |fizzbuzz| if (fizzbuzz % 2) == 0 && (fizzbuzz % 5) == 0 puts "fizzbuzz: " + fizzbuzz.to_s elsif (fizzbuzz % 5) == 0 puts "fizz: "+fizzbuzz.to_s elsif (fizzbuzz % 2) == 0 puts 'buzz: ' + fizzbuzz.to_s else puts "-" + fizzbuzz.to_s end end end end PrimeChecker.print_em When I execute this, I get this error: undefined method 'print_em'. I change the method to self.print_em and it works. Does this mean it's a class method (I think so)? Was the method "not found" before because I can only call such methods in a class on actual instances of the object? If I wanted it to be a instance method what is the syntax for that? I'm trying to understand Ruby, classes and methods better. Class methods are just that: called on the class. Whereas instance methods are called on an instance of that class. An example is more useful: class Foo def self.bar "This is a class method!" end def bar "This is an instance method!" end end Foo.bar # => "This is a class method!" foo = Foo.new # This creates "foo" to be a new instance of Foo foo.bar # => "This is an instance method!" Note that "class methods" in Ruby are actually methods on the class object's singleton. This is a rather difficult concept to explain, and you can read more about it if you'd like. Great, it's kinda what I thought. Accepted and also +1 for the examples. Thanks! woops sorry, I didn't have 15 rep so couldn't upvote. But I did accept.! Q: When I run ruby.rb I get undefined method 'print_em'. I change the method to self.print_em and it works. Does this mean it's a class method (I think so). A: Yes. class Bar; ... def self.foo defines a class method foo for class Bar. Q: Was the method "not found" before because I can only call such methods in a class on actual instances of the object? A: You were first defining it as an instance method. In that case, it is only available to instances of the class. Q: If I wanted it to be a instance method what is the syntax for that? A: The way you had it originally: class Bar; def foo defines instance method foo for class Bar Yes, you are completely correct. Currently, the way you define it, you can evaluate the method with: PrimeChecker.new.print_em The reason def self.my_awesome_method defines it on the class side is because the stuff inside class MyAwesomeClass end is being executed in the context of MyAwesomeClass. It's all Ruby code, as you can see! This enables you to do things like this: class MyAwesomeClass puts "Hello from innards of #{self}!" #=> Hello from the innards of MyAwesomeClass! end Method definitions will also only work if you call them after the definition location, for example: class MyAwesomeClass my_awesome_method # produces a nasty error def self.my_awesome_method puts "Hello world" end my_awesome_method # executes just fine end Hope this clears some things up. It's not a class method as written; you need to run it with an instance of PrimeChecker: pc = PrimeChecker.new pc.print_em Using self. turns it into a class method, runnable with the syntax you show. It doesn't need to be a class method, it's just that that's how you're trying to execute it.
common-pile/stackexchange_filtered
jsonwebtoken Typescript Compiling issue? I'm trying to compile a typescript file and it keeps throwing this error from the compiler: error TS2339: Property 'payload' does not exist on type 'string | object'. Property 'payload' does not exist on type 'string'. Code in question: decode(token: string): any { const decodedJWT = jwt.decode(token, { complete: true }); const issuer = decodedJWT.payload.iss; ^^^^^^^^^ return {}; } I'm using the @types/jsonwebtoken library to define the types. Any help would be much appreciated. What type does jwt.decode return? This error is caused by TypeScript type checking, the return type of jwt.decode() is null | object | string, if you're sure jwt.decode() always returns an object, you can cast decodedJWT to any type to avoid this error: decode(token: string): any { const decodedJWT = jwt.decode(token, { complete: true }); const issuer = (decodedJWT as any).payload.iss; return {}; } In the above example, it might cause exception at runtime, because jwt.decode() might return null or a string, but only an object contains property payload, so you'd better handle the return value in a safer way: decode(token: string): any { const decodedJWT = jwt.decode(token, { complete: true }); if (decodedJWT === null) { // deal with null } else if (typeof decodedJWT === 'string') { // deal with string } else { const issuer = (decodedJWT as any).payload.iss; // cast to `any` type } return {}; }
common-pile/stackexchange_filtered
Using cmake, how to link an object file built by an external_project statement into another library? In our project, we want to use a third-party library (A) which is built using autotools and which generates an object file (B) which we need @ link time of one of our libraries (C). external_project( A ... ) set_source_files_properties(B PROPERTIES DEPEND A) add_library(C ... A) add_dependency(C B) I had the impression that this should do the trick, but the cmake command fails by stating that it cannot find file A during the check for add_library. Any fixes or alternative solutions would be greatly appreciated! (changing the third-party library is not an option) thanks! There are a few issues here: external_project should be ExternalProject_Add Source files have no property called DEPEND available - the set_source_files_properties command has no effect here. (Here are the properties available on source files) add_library expects a list of source files to be passed, not another CMake target (which A is) add_dependency should be add_dependencies Apart from those 4 lines it's all OK :-) So the issue is going to be that you want to include the object file B in the add_library call, but it's not going to be available at configure-time (when CMake is invoked), only at build time. I think you're going to have to do something like: ExternalProject_Add( A ... ) set_source_files_properties( ${B} PROPERTIES EXTERNAL_OBJECT TRUE # Identifies this as an object file GENERATED TRUE # Avoids need for file to exist at configure-time ) add_library(C ... ${B}) Thanks a lot, perfect answer! (I did not intend to write effective cmake code, but maybe that would have been clearer ;) ) @RaulLuna In the original question, the OP has mentioned that there's an object file which he's called "B" - I'm assuming it's defined as a variable earlier in the CMakeLists.txt
common-pile/stackexchange_filtered
Sum involving harmonic series and sine of integers Consider the sum $$ S_n= \sum_0^n \frac{\sin^2(k)}{2k+1}.$$Is it convergent ? Can it be evaluated in the form of a closed expression for any $n \in \mathbb N$ or for large $n.$ Can we somehow use Fourier series? Thank you for any help in advance Every time $k$ goes around the unit circle (i.e. goes through $2\pi$ radians), we get at least one $k$ in $[2 \pi m + \pi/2 - 1/2, 2 \pi m + \pi/2 + 1/2)$ for $m$ an integer. What's a lower bound of the sum of just the terms for these $k$? Hint: to prove divergence, check $\sum_0^n\frac{\cos2k}{2k+1}$ converges. Doesn't Dirichlet's test suggests that the series converges? I'm not sure how to show $\sum (\sin k)^2$ is bounded beyond, saying $(\sin k)^2 \leq |\sin k|$ and $\sum (\sin k)$ is bounded. I'm not familiar with Claude's method, but if I assume he's correct, then the absolute values in my inequality must make $\sum |\sin k |$ unbounded. Clearly, the other conditions for Dirichlet's test apply. I found this, so I guess so. https://math.stackexchange.com/questions/127381/is-the-series-sum-sinnn-divergent?rq=1 Too long for comments. In terms of special functions, there is a closed form for the partial sum $S_n$ (have a look here). But you must also notice is that $$I_n=\int_0^n\frac {\sin^2(k)} {2k+1}\,dk$$ is quite easy to compute $$I_n=\frac{1}{4} (\cos (1) (\text{Ci}(1)-\text{Ci}(2 n+1))+\sin (1) (\text{Si}(1)-\text{Si}(2 n+1))+\log (2 n+1))$$ does not converge and tends to infinity. Now, since the integral exists, use the simplest form of Euler-MacLaurin summation formula and show that $$S_n\sim C+\frac 14 \log(n)+O\left(\frac{1}{n}\right)$$ where $C$ is a small number. What is Ci and Si?kindly explain @AgnostMystic. Sine and Cosine integrals
common-pile/stackexchange_filtered
Could Wolverine survive a nuclear bomb? According to the Marvel wiki on adamantium , A sufficient amount is capable of surviving multiple nuclear explosions with no damage. And an answer on another question here says that Wolverine can regenerate with only his skeleton left (the other, IIUC, says he doesn't even need his whole skeleton). So, does wolverine have enough adamantium arranged in such a way that he could survive even a nuclear strike? And if even "nuke it from orbit, it's the only way to be sure" doesn't work, can he be killed? Seems to me that there's a dependency on his nearness to the blast itself. While his skeleton should be able to withstand the blast, I believe there are weakness at points allowing marrow and joints to operate as needed and, probably most importantly, he has orifices in his skull that would leave his brain incredibly vulnerable to the power of a blast if too near. If Indiana Jones can in a refrigerator smh, I'm betting Wolverine can... @Josh if you think you can give an answer with at least an educated guess at how far away he could survive, please do. Of what yield and at what distance? He survived the bomb at Hiroshima. :) @Random832 if you have evidence it would matter, i.e. limits on either, please post them. It would all depend on how close to the bomb he was. After all regular humans survived the bombing of Japan :) I remembered this comic after mulling over this discussion. Here is a summary from comics.ign.com: In Brian K. Vaughan's mini-series Logan, the titular hero is a prisoner of the Japanese. He escapes along with a fellow prisoner and finds solace and love in a local girl. Unfortunately, the girl's hut happened to be in Hiroshima, and thus Wolverine became a survivor of the atomic bomb. From what I remember, this is before Logan had the adamantium skeleton. It is safe to assume that he would survive an atomic bomb after he had obtained his skeleton. Additionally, In Venom #8, I believe, Venom and Wolverine are in a town called Voici, and a nuclear bomb is dropped. In Venom #9, Wolverine wakes up in the rubble, and his only injury is a missing shirt. Very interesting. Is it mentioned how far he is from the epicenter? @Kevin he had just finished being with said Japanese love interest when the flying V formation of bombers flew overhead in the last panel of book one. Then it cuts back in time for book two, he fights a guy, and in book three, it starts out with that frame, so fairly close, I would assume. @Kevin Also added to my answer a second time when Wolverine survives nukage. Not sure why I've bothered to sign in to say this, but the bombers at Hiroshima did not actually fly in a V formation during the bombing. There were only 3 flying over Hiroshima while the bomb was being dropped, and one of those was the observation/photography plane which should have been following a short ways behind the other two. Short answer: No. If he were standing directly near the epicenter of a nuclear weapon, his organic materials would be incinerated and destroyed, even as his skeleton survived relatively undamaged. His organic flesh having no special invulnerability to fire, radiation, radiated energy and blast over-pressure would certainly be destroyed completely at ground zero. His survival at Hiroshima was due to the weapon being detonated 500 meters above ground with the fireball ending only 100 meters from the weapon's detonation. More detailed answer and comic references: Wolverine's ability to survive a nuclear weapon is directly related to these forces: Yield of nuclear weapon. Since no particular weapon was specified we cannot be certain of his survival rate. Relatively speaking, both Fat Man and Little Boy were approximately 18-20 KT yield weapons. Since both of these weapons were detonated at 500 meters above sea level, the thermal fireball would not have reached the ground (area of that thermal effect was approximately 100 meters) so Logan risked only the secondary burning effects of the weapon, commonly called the flash effect. This would give him third degree burns but not completely destroy the tissues of his body. Both Fat Man and Little Boy would be considered tiny by modern nuclear weapon standards in terms of yield or area affected by the blast, fire, and radiation effects. His distance from the epic-center of the explosion: Today's modern nuclear weapons are measured in Megatons yields of TNT. If we are to assume that Wolverine's power is purely a physical one (which is a matter of debate considering the amazing regenerative process he undergoes, particularly when his body is supposedly nearly destroyed) we have to inquire how it is that his highly regenerative but otherwise unremarkable flesh could survive at the point of detonation of a nuclear blast, when temperatures greater than 3000 degrees Fahrenheit can be reached. At such temperatures, flesh is completely vaporized. And while his adamantium skeleton would not be harmed, his flesh, organs, blood, and non-metallic elements of his skeleton would certainly be consumed by the conflagration. If he were standing on top of either of the nuclear weapons even as relatively low yield as the two weapons used in Japan, while his adamantium skeleton would be intact, all other organic matter would be immediately and completely vaporized. If he were within the actual blast fireball radius all organic matter would be incinerated. If he is able to return to being Logan as long as a single cell of him remained, implies there is another component to his regenerative process as all of his memory would be lost, since his entire brain was lost as well. You can see the yields of famous nuclear weapons below. Explanation of his survival at Nagasaki: Logan was able to survive Nagasaki because he would have had a very tiny area in which to have been caught by the actual fireball to risk total dissolution. This area would have been less than 100 meters. Since the weapon was detonated at 500 meters, he did not risk any direct effects of the fireball. Outside of that area, he would risk shockwave damage, being blown across the area and smashed into any objects that survive the explosion, flying debris and over-pressure damage (which includes embolisms in his lungs and brain) but as long as enough of his organic matter remained he would survive. The most potent effect on whether Logan can be killed is whether the writer wants him to be able to survive or not. Alternative timeline Wolverine was killed by forces much less potent than a nuclear weapon. The blast from that timeline's Sentinel was sufficient to reduce him to his skeletal remains in the Days of Future Past series of story arcs (X-men #142). The most powerful representative of those Sentinels is the time-traveling X-man enemy, Nimrod. Whoa! Now thats an answer! Even if wolverine were to survive, he would believe he shouldn't if he read your answer. I'm especially happy with this answer as it bring up not only excellent science but the first thing that came to my mind: ISSUE 142 of UNCANNY. Possibly the only time the 'Cover Blurb' doesn't mislead the reader; Everybody DOES Die including Wolvie. No. Wolverine can regenerate from BIOLOGICAL skeleton... Not from Adamantium skeleton. As biological part of his skeleton will be vaporized by Nuclear bomb, there's no point of his regeneration from Adamantium based skeleton. His mutant power isn't attached with Adamantium part of his body! Even if you consider Adamantium could block heat to protect biological stuff inside it, its impossible to regenerate from that. If there's no gap for heat to reach there.. means, its fully isolated from rest of body. And, for regeneration to work, there's need to break Adamantium shield which is impossible... This comic strip attached with linked answer displays temperature of mere 500 degrees C which can't take guarantee to wipe out entire organic lump thru small gap. There's high chance of super burn residues. But, condition of this question is fully different. Heat produced by Nuclear bomb can't leave residue! If the adamantium completely sheathes his bone structure, wouldn't it shield his organic skeleton from the blast? @Beofett updated my answer.. see last paragraph.. I think you should read the linked answer in his question. Your answer is clearly wrong in light of it. @Gabe Yes, I read that question.. This situation is different. Even a small gap would allow heat to vaporize organic stuff.. And, this will happen if you take that question in account. @Gabe The comic stripe from that question displays 500 degrees C on which organic stuffs would not be guranteed disappear. That's like super burn residue.. That doesn't say 500 degrees was the upper limit; it says "You don't feel anything after the first 500 degrees." That would imply it got much hotter. It doesn't mean it can match Nuclear bomb.. This is the only possible explanation for both questions due to gap based ju-ju.. YES. There are many documented cases of ordinary people surviving nuclear bombs; even the military uses probability charts to estimate percentage of people killed as a function of distance to the blast. Therefore, it is certainly possible for Wolverine to survive. I believe he can, if we consider the events of the X-Men movies canon. Jean has the ability to disintegrate matter completely, but when her powers are directed at Wolverine (last battle of X-Men: Last Stand, I believe), he continually regenerates. While this is not directly supported by canon sources (I confess I haven't read many comics), it appears that Wolverine would begin regeneration even before the nuclear blast has started to subside. Perhaps the organs covering the orifices in his skull (eyes, ears) will continually regenerate as the blast bears down on him, protecting his brain. There should be enough bone marrow inside his adamantium protected skeleton to regenerate the rest of him. Not gonna downvote, but the X-Men movies are yet another universe with some substantial changes made - it's not one I'd use as support. wolverine could regenerate with the left over matter after the rest is disintegrated by jean, so it has nothing to do with jeans ability to disintegrate matter. He can just simply regenerate from wounds that are slow damaging, unlike nuclear bomb which could vaporize him almost instantly. @MozenRath My point was that the same power when applied on other people just vaporized them instantly. Wolverine's tissues remained. It depends how and where the bomb hits. Wolverine sitting on a bomb when it explodes would destroy him irreversibly, but nukes are usually deployed as air-burst against cities. A few lucky humans can survive that, so Wolverine would probably have a good chance in that case. Of course, the writers can write anything, so this assumes they don't come up with something ludicrously insane, which violates all physics and logic... as we can see, Wolverines regeneration abilities got already elevated many times in newer and newer versions. Yes, at one point in the comics Wolverine is reduced to only his metal skeleton, yet he is able to come back from that state. Admuntium is described as several times denser than lead which probably means it hols its radioactivity adsorption. The heat most likely will not last long enough to flash burn his skeleton. Yes. I believe he has actually but I can't find the reference. Here is a link to an article on i09.com The article is from April 30th 2009 and it goes into more specifics. But basically Wolverine has come back from a single drop of blood before so if just his skeleton was around there would still be marrow. Wolverine has suffered from the same thing that eventually killed interest in Superman, basically his powers keep escalating until he's basically unstoppable.
common-pile/stackexchange_filtered
Next JS code inside getInitialProps not executes after page reload I'm integrating NextJS into my React app. I face a problem, on page reload or opening direct link(ex. somehostname.com/clients) my getInitialProps not executes, but if I open this page using <Link> from next/link it works well. I don't really understand why it happens and how to fix it. I have already came throught similar questions, but didn't find any solution which could be suitable for me. Clients page code: import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { ClientsTable } from '../../src/components/ui/tables/client-table'; import AddIcon from '@material-ui/icons/Add'; import Fab from '@material-ui/core/Fab'; import { AddClientModal } from '../../src/components/ui/modals/add-client-modal'; import CircularProgress from '@material-ui/core/CircularProgress'; import { Alert } from '../../src/components/ui/alert'; import { Color } from '@material-ui/lab/Alert'; import { AppState } from '../../src/store/types'; import { thunkAddClient, thunkGetClients } from '../../src/store/thunks/clients'; import { SnackbarOrigin } from '@material-ui/core'; import { IClientsState } from '../../src/store/reducers/clients'; import { NextPage } from 'next'; import { ReduxNextPageContext } from '../index'; import { PageLayout } from '../../src/components/ui/page-layout'; const Clients: NextPage = () => { const [addClientModalOpened, setAddClientModalOpened] = useState<boolean>(false); const [alertType, setAlertType] = useState<Color>('error'); const [showAlert, setAlertShow] = useState<boolean>(false); const alertOrigin: SnackbarOrigin = { vertical: 'top', horizontal: 'center' }; const dispatch = useDispatch(); const { clients, isLoading, hasError, message, success } = useSelector<AppState, IClientsState>(state => state.clients); useEffect(() => { if (success) { handleAddModalClose(); } }, [success]); useEffect(() => { checkAlert(); }, [hasError, success, isLoading]); function handleAddModalClose(): void { setAddClientModalOpened(false); } function handleAddClient(newClientName: string): void { dispatch(thunkAddClient(newClientName)); } function checkAlert() { if (!isLoading && hasError) { setAlertType('error'); setAlertShow(true); } else if (!isLoading && success) { setAlertType('success'); setAlertShow(true); } else { setAlertShow(false); } } return ( <PageLayout> <div className='clients'> <h1>Clients</h1> <div className='clients__add'> <div className='clients__add-text'> Add client </div> <Fab color='primary' aria-label='add' size='medium' onClick={() => setAddClientModalOpened(true)}> <AddIcon/> </Fab> <AddClientModal opened={addClientModalOpened} handleClose={handleAddModalClose} handleAddClient={handleAddClient} error={message} /> </div> <Alert open={showAlert} message={message} type={alertType} origin={alertOrigin} autoHideDuration={success ? 2500 : null} /> {isLoading && <CircularProgress/>} {!isLoading && <ClientsTable clients={clients}/>} </div> </PageLayout> ); }; Clients.getInitialProps = async ({ store }: ReduxNextPageContext) => { await store.dispatch(thunkGetClients()); return {}; }; export default Clients; thunkGetClients() export function thunkGetClients(): AppThunk { return async function(dispatch) { const reqPayload: IFetchParams = { method: 'GET', url: '/clients' }; try { dispatch(requestAction()); const { clients } = await fetchData(reqPayload); console.log(clients); dispatch(getClientsSuccessAction(clients)); } catch (error) { dispatch(requestFailedAction(error.message)); } }; } _app.tsx code import React from 'react'; import App, { AppContext, AppInitialProps } from 'next/app'; import withRedux from 'next-redux-wrapper'; import { Provider } from 'react-redux'; import { makeStore } from '../../src/store'; import { Store } from 'redux'; import '../../src/sass/app.scss'; import { ThunkDispatch } from 'redux-thunk'; export interface AppStore extends Store { dispatch: ThunkDispatch<any, any, any>; } export interface MyAppProps extends AppInitialProps { store: AppStore; } export default withRedux(makeStore)( class MyApp extends App<MyAppProps> { static async getInitialProps({ Component, ctx }: AppContext): Promise<AppInitialProps> { const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}; return { pageProps }; } render() { const { Component, pageProps, store } = this.props; return ( <> <Provider store={store}> <Component {...pageProps} /> </Provider> </> ); } } ); Looking for your advices and help. Unfortunately, I couldn't find solution by myself. This is the way Next.js works, it runs getInitialProps on first page load (reload or external link) in the server, and rest of pages that where navigated to with Link it will run this method on client. The reason for this is to allow Next.js sites to have "native" SEO version. What is the right way to load data after page reload? I have tried to load it by the same way as without next, but it didn't work. (Dispatched action inside useEffect on component load) useEffect hook will run only in the browser, do u see the request in the network tab? well, I see request for the page by the route, but returned page have no any daat from API. (I don't see that data call gave been triggered after page relaod) You won't see your api call on the browser when it runs on the server, put console.log after your api call, check that you see your data in the terminal hmm, I have rebuilded project some time and it started work again. seems like next run dev script not working properly sometimes. But thank you .
common-pile/stackexchange_filtered
How to make a realistic boucle material? I studied geometry nodes for a few days. Actually it was very easy, here is the result: https://drive.google.com/file/d/1X0YZoqVyWqt7sBbAFg85wSHSf1k4qmHg/view?usp=sharing I am working on a project with bouclé material, but the bouclé material always looks very bad. I have tried BlenderKit and Poliigon, but it does not work, the result looks terrible. Maybe I should use geometry nodes to create the bouclé material? I saw one that made a very nice bouclé material; perhaps someone knows how to do it? It looks like it was made with geometry nodes. https://www.youtube.com/watch?v=pYFM1r3spVU Updates: I tried geometry nodes cloth simulation to get the surface, here is the result, but it should be more https://drive.google.com/file/d/1bLvpsX1mgfM-flVTc_1-M8rnjpcrBP6G/view?usp=sharing What object is it for? Could you share what you have as far? Use particles? Or use a normal map to fake it? @MartynasŽiemys it was a very basic sofa https://drive.google.com/file/d/1jFRGj3WREoEBItUa6-99Bqznq-kUowdw/view?usp=sharing @moonboots i tryed a lot textures, norm, dislacement.....not work https://blender.stackexchange.com/questions/279402/how-can-i-get-a-detailed-fleece-texture-in-blender https://blender.stackexchange.com/questions/295787/how-to-make-a-fleece-texture-for-my-cap-model https://blender.stackexchange.com/questions/58339/how-do-i-make-a-fur-for-my-teddybear @DuarteFarrajotaRamos Thanks for your answers. The seceond one is the material i try to acheive, i should study particle System maybe One unusual way, I have used a few times to make this material is to offset a few layers of geometry(4-5) to form a few millimeter layer of sort of a volume approximation and then use noise texture(object texture coordinates so it's 3d) remapped to more appropriate range to make a volumetric mask. It requires 2 materials: 1 for the object and another for the "volume", but if sort of works OK for carpets and furniture sometimes. It seems to be easier and more efficient than displacement since you can have "volume" material slightly transparent/translucent and it's somewhat efficient in terms of resources: It's not perfect when zoomed in too much, but it could work well in some situations. It works in the viewport(EEVEE) as well, but it sometimes looks different scale than in the render(Cycles), so it needs test renders. At least it used to in 4.0, not sure about 4.1. The nodes for the "volume material": I keep color variation from the image texture and add some sheen. I am sure one could make a more elaborate shader for it to look better, but that happens to be enough for me in this case. thanks for the answer, but it is not what i really want Why so? I was hoping this might work. What is it that you want? It could probably be possible to use geometry nodes to set it up procedurally and use one material separating the "volume" layers with an attribute. it looks nice from afar, but if zoom in, the details are not fitting Yeah, that's a good reason not to use it. Might be possible to push it a bit though. If you are doing displacement, and you have some forms that are relatively smooth and can normally be defined with less geometry it might still be efficient with more layers and it is should also be possible to change attributes of the noise per layer with geometry nodes so the clumps could be made to get smaller the closer they are to the outer surface, but that would be a fair bit of work with geometry nodes I guess. I think with geometry nodes or partickel system zu rebuild the surfsce maybe the right may, because the surface changes so much because of boucle material Personally I find particle systems not so practical for everyday kind of stuff. They take a lot of effort to make and require a lot of resources to render. Yes, a sofa alone might look good after a day of working with particles, but if you need it in an interior full of other stuff to fit into GPU memory and want to spend an hour on the material, I think this layered solution might be really great. This can be extremely efficient in terms of memory in some situations. You are right, for interior it does not matt when die details are not so fit, but for sofa produkt there are views of details….. i solved it, look the file on top @MeiyingLu, please observe the rules of the platform. You must not edit the title of the question if it's solved, but instead accept an answer that solved it or if there are no good answers, provide one yourself and post it as an answer.
common-pile/stackexchange_filtered
Haman's sons in three p'sukim Me (quoting Ester 9:7–10): 7 And Parshandasa and Dalfon and Aspasa 8 and Porasa and Adalya and Aridasa 9 and Parmashta and Arisay and Ariday and Vayzasa, 10 the tensome of the sons of Haman ben Ham'dasa, terrorizer of the Jews, they killed.... My kid: Why are the ten names split up over three p'sukim? Me: I don't know. Maybe it was too long for one? My kid: I've seen p'sukim longer than all three put together! Me: Good point. The truth is that, as noted in a comment, this question may be a little weak — perhaps that's just how the authors of Ester liked to write — but the same question applies to Sh'mos 1:2–4, where I expect a stronger answer than "the author just liked to write that way". So consider my question to be about those (and similar) p'sukim in Chumash instead, if you prefer, although I ideally would still like an answer about the specific p'sukim in Ester quoted above. I don't think you have such a strong question. It just is that way. See for example Chronicles I 1:1-4 and many many other places in Chronicles and around Tanach. @DoubleAA, like Sh'mos 1:2–4. I agree it's not the strongest question (and it's not mine), but I couldn't, and can't, answer it, so am asking it here. I find it hard to believe, especially in Chumash, that it "just is that way" with no reason. (In Nach, fine, maybe it's for poetic reasons or that's just how the author liked to write, but in Chumash I'm not as happy with that answer.) I'll edit my question to be about Sh'mos rather than Ester. Somewhat related: http://judaism.stackexchange.com/q/68720 somewhat related: https://judaism.stackexchange.com/questions/88343/is-there-a-list-of-three-word-pesukim-in-tanakh. Looking through the list (as well as searching tanach for 4 word pesukim) should help you prove that in general, long lists of names are broken up into multiple Pesukim, sometimes even into three and four word pesukim. It seems to me that in general, pasukim are broken up so that there are no more than 3-4 names in a verse, especially a list. Why this is done I imagine is up to speculation. Does it have mystical numerical meanings? (i.e. stability), does it have to do with human memory and good oration? (Saying things in threes makes it a stronger point, and more likely to be remembered), or is it just the style that the people who decided to break verses up into verses chose to use? (Normally christian monks btw) I imagine all the possible answers are correct on some level. "[T]he people who decided to break verses up into verses" are "[n]ormally [C]hristian monks"?? The g'mara refer to p'sukim as that which "paskeh Moshe", "Moshe demarcated it". @msh210 could be, but we have no idea if they are the same as not. Infact we know that the Torah described in the Talmud is marked differently than our own, regarding the middle word/letter. @msh210 The gemara in Nedarim 38a "Amar Rav Acha bar Ahava" says that there was a dispute between the Babylonians and the Israelis how to break up the pasuk that we call Shemot 19:9 It seems we can't be too sure that all of our pasuk breaks are LeMoshe MiSinai. @DoubleAA, then we see that we do have a tradition (in that case, two traditions) about how to split up p'sukim. Perhaps, avi, the Babylonians and Israelis in question got their traditions from monks? Benedict, who (it seems) started the tradition of monkhood, lived before the chasimas haTalmud, so I suppose you could argue that. I, for one, highly doubt it. @msh210 No, the breaking up of chapter and verse is from the 1300s way after the Rambam and the mesorites made their tekunim. It seems that in later years the monks corrected their verses to match up with the trope. avi, I'm not sure what you're saying in your last comment. I am not trying to argue that the division into chapters (and therefore numbering of verses) was late. I'm only saying the division into verses was early. Did your last comment address that at all? @msh210 I agree that much of our text is based on mesorah. All I'm saying is that we know some of the psukim stops have changed, and it's not unreasonable to assume that some monks had the final word in which opinions ended up being printed around the world. @avi, the numeration of chapters and verses is from the 1300s. The division into verses goes back long before that, as msh210 said. (And most of ours do match up with the ones from the time of the Gemara, as evidenced by the fact that Kiddushin 30a says that the Torah contains 5888 verses, where we have 5846 - an agreement of over 99%.) @Alex (Those numbers are insufficient to prove our divisions match the G'mara's: perhaps they're ~equal in number but not in actual dividing points.) Only that the trope and therefore verse endings, we have today come from Rambam's time, or Allepo, I'm a bit foggy on exactly who won that debate. Let's settle this SE style http://judaism.stackexchange.com/q/13524/759
common-pile/stackexchange_filtered
Create unique array based on property I want to create an array that does not have repeated object(all objects are unique) based on object property and if it is unique I want to push it to this array. Before sending it to my function I use: vm.initResponse = angular.fromJson(response); That push $$hashKey to each object. function initDropDown(list){ console.log('initDropDown', list); for (var key in list) { //remove angularjs $$hashKey var obj = JSON.parse(angular.toJson(list[key])); //the object I want to push into new array var filter = {}; filter.prop = obj.SUGNIA; //if indexOf returns -1 the array does not have this object if(vm.stockOptionsSelect.indexOf(filter) < 0){ vm.stockOptionsSelect.push(filter); } } } the list array has many objects with different SUGNIA and I want to create an array with all unique ones. I have removed $$hashKey has explained remove-hashKey and using indexOf - indexOf. List data - [ { "uid": "23", "time": "2017-10-01 16:00:35.515", "SUGNIA": "stock", "SECURITYNAME": "IBM", "INDEX_IN_UI": 5 }, { "uid": "29", "SECURITYNUM": 629014, "time": "2017-09-28 16:32:26.432", "SUGNIA": "holdings", "SECURITYNAME": "FaceBook", "INDEX_IN_UI": 10 }, { "uid": "id", "time": "2017-09-28 16:33:20.25", "SUGNIA": "stock", "SECURITYNAME": "google", "INDEX_IN_UI": 0 } ] And my result should be : [{"prop":"stock"}, {"prop":"holding"}] But I get duplicates. The indexOf function does the comparison using strict equality === and since the object you're passing to this function is an object that was just created, it will always return -1. To fix that, you can use the ...some(...) function instead. Here is an example: if(!vm.stockOptionsSelect.some(e => e.prop == obj.SUGNIA)){ vm.stockOptionsSelect.push({prop:obj.SUGNIA}); } @ItsikMauyhas I'm glad I could help. Good luck. You can't use indexof object as that isn't looking at object properties but it's looking for reference to that filter object. Use some instead and look for identical object properties. var hasItem = vm.stockOptionsSelect.some(item) { return item.prop === filter.prop } if(!hasItem) { vm.stockOptionsSelect.push(filter); } If you cant use some var results = vm.stockOptionsSelect.filter(item) { return item.prop === filter.prop; } if(results.length === 0) { vm.stockOptionsSelect.push(filter); } You can use Set and array#map to get the unique SUGNIA value from your array list. var list = [{"uid": "23","time": "2017-10-01 16:00:35.515","SUGNIA": "stock","SECURITYNAME": "IBM","INDEX_IN_UI": 5},{"uid": "29","SECURITYNUM": 629014,"time": "2017-09-28 16:32:26.432","SUGNIA": "holdings","SECURITYNAME": "FaceBook","INDEX_IN_UI": 10},{"uid": "id","time": "2017-09-28 16:33:20.25","SUGNIA": "stock","SECURITYNAME": "google","INDEX_IN_UI": 0}]; var result = [...new Set(list.map(x => x.SUGNIA))] .map(x => ({prop: x})); console.log(result);
common-pile/stackexchange_filtered
How to update mkdir in order to install express-generator without warnings? I was going to install express-generator on windows computer. I used this npm install -g express-generator command in cmd and it gave me this npm WARN deprecated<EMAIL_ADDRESS>Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.) warning. Then I usednpm install mkdirp@1and successfully installed<EMAIL_ADDRESS>version. CMD confirmed it showing me this message +<EMAIL_ADDRESS>updated 1 package and audited 1 package in 1.981s found 0 vulnerabilities But unfoutunately when I try to reinstall express-generator using npm install -g express-generator, cmd shows me the same warning. Exactly the same warning. How Can I update mkdirp?? Help Me.. In this case, you can't. Because the<EMAIL_ADDRESS>is a dependency of express-generator package and when you install this package, npm will install all of it's dependencies automatically. it's caused by generally access copyright; you can avoid the access to modify directory by : $ sudo npm install -g<EMAIL_ADDRESS>or the latest version to install: nicolas alien -technology - zone 51 You can run the application generator with the npx command (available in Node.js 8.2.0). $ npx express-generator Run all this in window terminal CMD or powershell Step-1 update the mkdirp. $ npm install mkdirp@1* in CMD Step-2 Install express globlly. $ npm i -g express-generator* in CMD Now its works Try this command(from the official website): npm install express --save The question is about express-generator not express itself Use the application generator tool, express-generator, to quickly create an application skeleton. You can run the application generator with the npx command (available in Node.js 8.2.0). $ npx express-generator
common-pile/stackexchange_filtered
About the pattern matching algorithm in OCaml I am writing a compiler for a functional language I designed with OCaml. I want my little language to have the feature of pattern matching, however, I got stuck in coming up with an algorithm to implement it. It seems really complicated as I dig into the problem. I can't find much useful information about the corresponding algorithm with google. I will be appreciated if someone can give me some hint or point me to the resources. Or are there any tricks to take advantage of OCaml's power in pattern matching to solve this problem so that I don't need to implement it? Thanks! There's a few good papers on compiling pattern matching by some of the people behind OCaml. In particular see Compiling Pattern Matching to Good Decision Trees and Optimizing Pattern Matching. It might also be useful to go over this stackoverflow post.
common-pile/stackexchange_filtered
ESP8266 Stops Working After A While (Unknown Problem) have an esp8266. i'm trying to create a DDNS updater. it has to wait 5 min then do a GET request to a URL. Here's my code: /* Code For DNS Updater.*/ #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #define LOOP_TIME 300000 const char* ssid = "SomeSSID"; const char* password = "SomePSWD"; const String address="http://dynamicdns.park-your-domain.com"; const String path="update"; const String pathHost="host"; const String pathPassword="password"; const String pathDomain="domain"; const String dnsName="my-example-host.com"; const String ddnsPassword="my-example-password"; const String updateHosts[]={ "@", "subdomain1", "subdomain2", }; void setup() { Serial.begin(115200); connectWiFi(); } long nextUpdate=0; void loop() { if(nextUpdate<millis()){ if (WiFi.status() == WL_CONNECTED) { updateDNS(); }else{ connectWiFi(); } nextUpdate=millis()+LOOP_TIME; } } void updateDNS(){ Serial.println("Updating Hosts:"); for(int host=0;host<(sizeof(updateHosts)/sizeof(String));host++){ Serial.print(updateHosts[host]+": "); String assembledURL=address+"/"+path+"?"+pathHost+"="+updateHosts[host]+"&"+pathDomain+"="+dnsName+"&"+pathPassword+"="+ddnsPassword; // Serial.println("Host: "+updateHosts[host]+" URL: "+assembledURL); HTTPClient http; http.begin(assembledURL); http.GET(); http.end(); Serial.println("Done"); } } void connectWiFi(){ WiFi.begin(ssid, password); Serial.print("Connecting To "); Serial.println(ssid); Serial.print("Password: "); Serial.println(password); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected To "); Serial.println(ssid); } and it stops after a couple of hours - which isnt good for a DDNS updater. EDIT: maybe it has something to do with my timer. will try an unsigned long instead. Hi @NadavTasher and welcome to the Arduino Stack Exchange community. Unfortunately your question doesn't meet our quality standards.Your question is rather terse. Please edit and improve it. See [ask] and How to ask a good question for Arduino Stack Exchange. what version of esp8266 arduino package? shouldn't if(nextUpdate<millis()){ be if(nextUpdate>millis()){, as in the timeout is past the current time? no, cause if nextUpdate is for example 5000 and millis is 4000 we dont yet wanna run the update. I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more. My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit. Alternate: avoid using the String type and other Heap usages.
common-pile/stackexchange_filtered
Any major difference between Eclipse and Eclipse-EE? Any major difference between those two? In terms of code editing and compilation - no. The Eclipse EE has features to support "enterprise stuff". If you do About Eclipse -> Installation Details, you can see the features that get installed with each one
common-pile/stackexchange_filtered
How to query an array list in a Firebase document? I'm trying to query my database for an android application, if a username is in the 'fave' array field of my database and if so then change the background of an image. My database is set up like this... I don't know if i'm doing it right but currently i think i may be checking the whole collection rather than a specific document and it's not even returning anything. Any suggestions would be appreciated! I suggest starting with the documentation to learn how to do queries. https://firebase.google.com/docs/firestore/query-data/queries @DougStevenson sorry maybe i should have been more clear. In the documentation the query objects search a whole collection but i only want to search a specific document, as the user can be in multiple trainers 'fave' arrays Then just get() the document you're looking for. https://firebase.google.com/docs/firestore/query-data/get-data @DougStevenson if i add the .document() path afterwards i can no longer use the .whereInArray()_ Yes, you can't filter when identifying a specific document. There's no need to - you already know the document ID. You wanted this? FirebaseFirestore.getInstance().collection("Trainers").document("Air Force 1 Low").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { List<String> list = (List<String>)documentSnapshot.get("fave"); for (String name : list){ if (name.equals("Admin")){ //do if user is admin return; } } //do if user is not admin } }); Top lad. I've been struggling to get my head round how to query documents but this has helped a lot. Thanks!
common-pile/stackexchange_filtered
subscribe function in angular 2 I want to see the result returned from the service in the same subscribe method or in the ngOninit method(commented one) but neither of the place it showing the result even it is fetching the result from the service.. ngOnInit() { this.cityAreaService.getCities().subscribe(data => { this.cities = data; //console.log(this.cities); }); //console.log(this.cities) } Service getCities() { return this.http.get(globalVar.serviceUrl + 'Cities').map((res: Response) => res.json()); } how does your service look like? Show your service. If results in service are fetched you should be able to see results using first console.log in your code. try logging error in subscribe.. debug it This is my service... getCities() { return this.http.get(globalVar.serviceUrl + 'Cities') .map((res: Response) => // console.log("Checking... " + res.json()); res.json() ); } see the thing I am getting the result in cities bcoz i am able to see in my template.. Post your service code to the question. but when I am logging it in the ngOnInit it is showing undefined Both console.log() calls are commented out. The first one should log the citites. The second one will always log undefined. You get the response asynchronously. Unless of course the service fils: add a second callback to subscribe(). Use your debugger. check if data fetched from service are ok by using console.log(data) instead of console.log(this.cities) in subscribe method yeah first console.log is working now.. Thanks to all for the quick responses You could try to read response in other blocks of subscribe this.cityAreaService.getCities().subscribe( response => { this.cities = response; }, error => { // maybe error }, () => { // anything else? } ); There is no difference between the code from OP and yours.
common-pile/stackexchange_filtered
How to create 2 incompatible number-like types in TypeScript? I've been trying to figure out how to create 2 mutually-incompatible number-like/integer types in TS. For example, in the code below, height and weight are both number-like, but the concept of adding them together or treating them equivalently is nonsensical and should be an error. type height = number; // inches type weight = number; // pounds var a: height = 68; var b: weight = operateScale(); // Call to external, non-TS function, which returns a weight. console.log(a+b); // Should be an error. Is there a way to create 2 types which are both numbers, but are not compatible with each other? EDIT: As mentioned in the comments section, this behavior appears to be analogous to haskell's newtype behavior. EDIT2: After several hours of poking the problem with a pointy stick, I managed to reach an answer, which I have posted below. In Haskell, that would be a newtype as opposed to a type alias. @JörgWMittag, yes, that looks like what I would want in TS. Googling for "newtype typescript" yields some libraries. Looks like this isn't possible right now. GitHub issue @Gerrit0 I've just done it. Answer is below. The closest thing to a newtype in TypeScript is to create a new "nominal" type (TypeScript doesn't have nominal types but there are workarounds like branding) and create a value constructor and a field accessor function which just uses type assertions in the implementation. For example: interface Height { __brand: "height" } function height(inches: number): Height { return inches as any; } function inches(height: Height): number { return height as any; } interface Weight { __brand: "weight" } function weight(pounds: number): Weight { return pounds as any; } function pounds(weight: Weight): number { return weight as any; } const h = height(12); // one foot const w = weight(2000); // one ton The types Height and Weight (sorry, can't bring myself to give new types a lowercase name) are treated as distinct types by the compiler. The height() function is a Height value constructor (takes a number and returns a Height), and the inches() function is its associated field accessor (takes a Height and returns a number), and weight() and pounds() are the analogous functions for Weight. And all of those functions are just identity functions at runtime. So JavaScript treats them as pure numbers with a bit of function-call overhead that's hopefully optimized away by a good compiler, and if you're really worried about that overhead, you can do the assertions yourself: const h = 12 as any as Height; const w = 2000 as any as Weight; Now you have distinct named types you can use so you don't accidentally use a Height where a Weight is needed or vice versa. But, just like with a newtype, the compiler will not treat these as a number. Yes, you could make Height and Weight subtypes of number (via intersection types), but that's probably a mistake: the arithmetic operators like + are able to operate on number values and if both h and w are subtypes of number, then h + w will not be an error. And if h and w are not subtypes of number, then h + h will be an error. And you can't change that, since TypeScript does not let you alter the type declarations of operators the way it does with functions. I prefer to prevent both h + h and h + w from compiling, so the Height and Weight types are not numbers. Instead, let's create our own add() function that behaves how you want: type Dimension = Height | Weight; function add<D extends Dimension>(a: D, b: D): D { return ((a as any) + (b as any)) as any; } The add() function accepts either two Height or two Weight parameters, and returns a value of the same type. Actually, with the above it's still possible to pass in something like Height | Weight as D, so if you're really serious about locking it down you can use overloads instead: function add(a: Height, b: Height): Height; function add(a: Weight, b: Weight): Weight; function add(a: any, b: any): any { return a+b; } And, behold: const twoH = add(h, h); // twoH is a Height const twoW = add(w, w); // twoW is a Weight const blah = add(h, w); // error, Height and Weight don't mix So we're almost done. For your external measureScale() function you'd just declare the return type to be a Weight: declare function measureScale(): Weight; var a = height(68); var b = measureScale(); And verify the intended result: console.log(add(a,b)); // err console.log(add(a,a)); // okay Playground link to code So, after banging my head against the wall for several hours, I managed to come up with this: class height extends Number {} class weight extends Number {} By sub-classing the Number class, Typescript allows you to create distinct numeric types. And then you can go and use the variables as specified above. var a: height = 68; var b: weight = 184; console.log(a+b); // Should be an error. The issue that I run into is that this also returns an error: console.log(a+a); // Should NOT be an error. Unfortunately this doesn't seem to stop you from saying height = weight.
common-pile/stackexchange_filtered
Combination of line profiles When combining two line shapes (for example a Gaussian and a Lorentzian), the effect of Both of them combined is the convolution of both (with a Gaussian and a Lorentizan,this is the Voigt function). I am wondering what is the reason that a convolution arises. I saw the explanation here: https://phys.libretexts.org/Bookshelves/Astronomy__Cosmology/Stellar_Atmospheres_(Tatum)/10%3A_Line_Profiles/10.04%3A_Combination_of_Profiles but it is not clear to me why "At a distance $ξ $ from the line centre, the contribution to the line profile is the height of the function $(ξ)$ weighted by the function $(−ξ)$". A clear explanation would be helpful. It might be from a point that the sum of two random variables give a distribution with probability density function which is the convolution of both. In case when two variables are independent. You can check this in a statistics book, for exemple, in [Papoulis "robability, Random Variables and Stochastic Processes", 2001] This is mathematically a formal thing. Take a random variable $z$ as a sum of two independent random variables $z = x+y $ and get the distribution of $z$. There is a chapter on "two variables" in the mentioned book calculating the distribution of $z$ I did not think about it this way. Thank you so much Suppose we sample a function $f(x)$, but our resolution possesses a finite width $w=\Delta=const$: For each point $x_0$ we do not measure $f(x_0)$, but we obtain the moving average of the function $f$ with width $w$. Next, we generalise this idea, and allow the finite resolution to be described by a function $w(x)$. We can think of it as a weighting function. At each point the same logic as above applies. However, instead of cutting out a finite part around $x=x_0$, and giving each point in this interval the same weight, the weight now depends of the distance to $x_0$. Thus, what we obtain is $$ g(x_0) = \int f(x-x_0) w(x) dx $$ which is identical to the convolution. Note, if we use a rectangular function to describe the finite resolution, we obtain the initially described moving average, where each point within a certain distance to $x_0$ gets the same weight. However, if we like to a continuous function to describe the contribution to each point, the Gaussian is a "natural" choice, because it possesses the largest entropy.
common-pile/stackexchange_filtered
reading in many tables from SQLlite databases and combining in R I'm working with a program that outputs a database of results. I have hundreds of these databases that are all identical in structure and I'd like to combine them into ONE big database. I'm mostly interested in 1 table from each database. I don't work with databases/sql very much, but it would simplify other steps in the process, to skip outputting a csv. Previously I did this by exporting a csv and used these steps to combine all csvs: Vector of all CSVs & combine library(DBI) library(RSQLite) library(dplyr) csv_locs<- list.files(newdir, recursive = TRUE, pattern="*.csv", full.names = TRUE) pic_dat <- do.call("rbind", lapply(csv_locs, FUN=function(files){data.table::fread(files, data.table = FALSE)})) How to do this with sql type database tables?? I'm basically pulling out the first table, then joining on the rest with a loop. db_locs <- list.files(directory, recursive = TRUE, pattern="*.ddb", full.names = TRUE) # first table con1<- DBI::dbConnect(RSQLite::SQLite(), db_locs [1]) start <- tbl(con1, "DataTable") # open connection to location[i], get table, union, disconnect; repeat. for(i in 2:length(db_locs )){ con <- DBI::dbConnect(RSQLite::SQLite(), db_locs[i]) y <- tbl(con, "DataTable") start <- union(start, y, copy=TRUE) dbDisconnect(con) } This is exceptionally slow! Well, to be fair, its large data and the csv one is also slow. I think I honestly wrote the slowest possible way to do this :) I could not get the do.call/lapply option to work here, but maybe I'm missing something. This looks similar to "iterative rbinding of frames", in that each time you do this union, it will copy the entire table into a new object (unconfirmed, but that's my gut feeling). This might work well for a few but scales very poorly. I suggest you collect all tables in a list and call data.table::rbindlist once at the end, then insert into a table. Without your data, I'll contrive a situation. And because I'm not entirely certain if you have just one table per sqlite3 file, I'll add two tables per database. If you only have one, the solution simplifies easily. for (i in 1:3) { con <- DBI::dbConnect(RSQLite::SQLite(), sprintf("mtcars_%d.sqlite3", i)) DBI::dbWriteTable(con, "mt1", mtcars[1:3,1:3]) DBI::dbWriteTable(con, "mt2", mtcars[4:5,4:7]) DBI::dbDisconnect(con) } (lof <- list.files(pattern = "*.sqlite3", full.names = TRUE)) # [1] "./mtcars_1.sqlite3" "./mtcars_2.sqlite3" "./mtcars_3.sqlite3" Now I'll iterate over each them and read the contents of a table allframes <- lapply(lof, function(fn) { con <- DBI::dbConnect(RSQLite::SQLite(), fn) mt1 <- tryCatch(DBI::dbReadTable(con, "mt1"), error = function(e) NULL) mt2 <- tryCatch(DBI::dbReadTable(con, "mt2"), error = function(e) NULL) DBI::dbDisconnect(con) list(mt1 = mt1, mt2 = mt2) }) allframes # [[1]] # [[1]]$mt1 # mpg cyl disp # 1 21.0 6 160 # 2 21.0 6 160 # 3 22.8 4 108 # [[1]]$mt2 # hp drat wt qsec # 1 110 3.08 3.215 19.44 # 2 175 3.15 3.440 17.02 # [[2]] # [[2]]$mt1 # mpg cyl disp # 1 21.0 6 160 # 2 21.0 6 160 # 3 22.8 4 108 ### ... repeated From here, just combine them in R and write to a new database. While you can use do.call(rbind,...) or dplyr::bind_rows, you already mentioned data.table so I'll stick with that: con <- DBI::dbConnect(RSQLite::SQLite(), "mtcars_all.sqlite3") DBI::dbWriteTable(con, "mt1", data.table::rbindlist(lapply(allframes, `[[`, 1))) DBI::dbWriteTable(con, "mt2", data.table::rbindlist(lapply(allframes, `[[`, 2))) DBI::dbGetQuery(con, "select count(*) as n from mt1") # n # 1 9 DBI::dbDisconnect(con) In the event that you can't load them all into R at one time, then append them to the table in real-time: con <- DBI::dbConnect(RSQLite::SQLite(), "mtcars_all2.sqlite3") for (fn in lof) { con2 <- DBI::dbConnect(RSQLite::SQLite(), fn) mt1 <- tryCatch(DBI::dbReadTable(con2, "mt1"), error = function(e) NULL) if (!is.null(mt1)) DBI::dbWriteTable(con, "mt1", mt1, append = TRUE) mt2 <- tryCatch(DBI::dbReadTable(con2, "mt2"), error = function(e) NULL) if (!is.null(mt1)) DBI::dbWriteTable(con, "mt2", mt2, append = TRUE) DBI::dbDisconnect(con2) } DBI::dbGetQuery(con, "select count(*) as n from mt1") # n # 1 9 This doesn't suffer the iterative-slowdown that you're experiencing. hi! I'm working on getting this to run (some errors that I'm trying to understand/fix), but this looks like a fantastic solution. I've just been swamped and need to get to this! Thanks, this totally works & is WAY faster than my snowballing-loop! Now I just need to get comfortable with the database-instead-of-dataframe... but that's a different problem. Consider ATTACH to create schemas for the databases you import from: library(DBI) file1 <- tempfile(fileext = ".sqlite") file2 <- tempfile(fileext = ".sqlite") con1 <- dbConnect(RSQLite::SQLite(), dbname = file1) con2 <- dbConnect(RSQLite::SQLite(), dbname = file2) dbWriteTable(con1, "iris", iris[1:3, ]) dbWriteTable(con2, "iris", iris[4:6, ]) # Main connection con <- dbConnect(RSQLite::SQLite(), ":memory:") dbExecute(con, paste0("ATTACH '", file1, "' AS con1")) #> [1] 0 dbExecute(con, paste0("ATTACH '", file2, "' AS con2")) #> [1] 0 dbGetQuery(con, "SELECT * FROM con1.iris UNION ALL SELECT * FROM con2.iris") #> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> 1 5.1 3.5 1.4 0.2 setosa #> 2 4.9 3.0 1.4 0.2 setosa #> 3 4.7 3.2 1.3 0.2 setosa #> 4 4.6 3.1 1.5 0.2 setosa #> 5 5.0 3.6 1.4 0.2 setosa #> 6 5.4 3.9 1.7 0.4 setosa Created on 2019-10-08 by the reprex package (v0.3.0)
common-pile/stackexchange_filtered
How to create a custom discount “Gift card” in Magento 1.9 at cart page The functionality will be = Enter Gift Card number(16 digit) Enter Gift Card Pin(6 digit) Enter Amount(amount entered by user) I have already created the above mentioned input fields in the cart page.but dont know how to proceed further. website: https://www.happyvalleytea.com/ cart page view: https://www.happyvalleytea.com/checkout/cart/ (add any product to cart) When the user clicks on gift card apply button, the transaction will happen on a 3rd party vendor(via curl api call). The response received from the api should be used as a discount amount on the cart page.
common-pile/stackexchange_filtered
Assigning too many parameters for procedure when having just only one table value parameter I'm using asp.net(C#), .NET 4, SQL Server 2012, IIS7. I want to import the excel data to sql server by using table valued parameters. but I'm experiencing a problem. Here is the partial code: C# //extract excel data, only 10 fixed rows. myEXcnnstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + Exfullname + "; Extended Properties=Excel 12.0;"; myEXcnn = new OleDbConnection(myEXcnnstring); myEXcnn.Open(); myEXsql = "select '" + ExCompany + "' as mycompany,'" + ExProject + "' as myproject,'" + Exdate.ToShortDateString() + "' as mydate,* from [sheet1$A1:N10]"; myEXcmd = new OleDbCommand(myEXsql, myEXcnn); myEXda = new OleDbDataAdapter(myEXcmd); myEXdt = new DataTable(); myEXds = new DataSet(); myEXda.Fill(myEXds); myEXdt = myEXds.Tables[0]; myEXcnn.Close(); // load to SQL SERVER mycmd.CommandType = CommandType.StoredProcedure; mycmd.CommandText = "dbo.loadCost"; SqlParameter tvpParam = mycmd.Parameters.AddWithValue("@TVPCost", myEXdt); tvpParam.SqlDbType = SqlDbType.Structured; tvpParam.TypeName = "dbo.TVP_Cost"; mycmd.ExecuteNonQuery(); myCnn.Close(); SQL server define TVP CREATE TYPE [dbo].[TVP_Cost] AS TABLE( [mycompany] [nvarchar](50) NOT NULL, [myproject] [nvarchar](50) NOT NULL, [mydate] [date] NOT NULL, [mytype] [nvarchar](50) NOT NULL, [Area1] [numeric](18, 8) NOT NULL, [Area2] [numeric](18, 8) NOT NULL, --etc ) GO SQL Server Stored Procedure ALTER PROCEDURE [dbo].[loadCost] @TVPCost dbo.TVP_Cost readonly AS BEGIN SET NOCOUNT ON; INSERT INTO Costtest (co1, co2,co3,co4,co5) SELECT co1, co2, co3, co4, co5 from @TVPcost END The error message is that I'm given too many parameters to procedure. But I only have one parameters, a table-valued parameters. I noticed that you're not declaring mycmd. Is it possible that you used that Command object earlier, and that it has already some parameters in it? Command objects are cheap, I always grab a new one: var cmd = MyConnection.CreateCommand(); Thanks. I've made a stupid mistake. forgot to initial a new one.
common-pile/stackexchange_filtered
Symmetrical monoidal $2$-category of cohomological correspondences My question is whether a symmetric monoidal $2$-category of ``cohomological correspondences'' has been been rigorously constructed anywhere in the literature. Let me be more precise about what I mean. Let us fix a base field $k$ and a prime $\ell$ invertible in $k$. This ``category'' is supposed to be a $2$-category such that its objects are pairs $(X,\mathcal{F})$ of a finite type $k$-scheme $X$ and an object $\mathcal{F}\in D(X; \mathbf{F}_\ell)$; $1$-morphisms between $(X, \mathcal{F})$ and $(Y, \mathcal{G})$ are given by $(S, f, g, \varphi)$, where $S$ is a correspondence $X\xleftarrow{f} S\xrightarrow{g} Y$ and $\varphi\colon f^*\mathcal{F}\to g^!\mathcal{G}$ is a morphism in $D(S, \mathbf{F}_\ell)$. Composition of $1$-morphisms $(S,f, g, \varphi_S)\in \mathrm{Hom}\left((X, \mathcal{F}), (Y, \mathcal{G})\right)$ and $(S', f', g', \varphi_{S'})\in\mathrm{Hom}\left((Y, \mathcal{G}), (Z,\mathcal{H})\right)$ is $(S\times_{Y}S', f\circ p_1, g'\circ p_2, \psi)$ where $p_1\colon S\times_Y S' \to S$ (and similarly $p_2$) is the projection map, and $\psi$ is the composition $$ p_1^*f^*\mathcal{F}\xrightarrow{p_1^*(\varphi_S)} p_1^*g^!\mathcal{G} \to p_2^!{f'}^*\mathcal{G}\xrightarrow{p_2^!(\varphi_{S'})} p_2^!{g'}^!\cal{H}, $$ where the middle morphism is the base change transformation. $2$-morphisms between $(S,f, g, \varphi_S)$ and $(S', f', g', \varphi_{S'})$ are given by proper morphisms $h\colon S \to S'$ such that $f=f'\circ h$, $g=g'\circ h$, and the composition $$ {g'}^*\mathcal{F} \to \mathrm{R}h_*h^*(g')^*\mathcal{F} \simeq \mathrm{R}h_!g^*\mathcal{F}\xrightarrow{\mathrm{R}h_!(\varphi)}\mathrm{R}h_!f^!\mathcal{F} \simeq \mathrm{R}h_!h^!{f'}^!\mathcal{F}\to {f'}^!\mathcal{F} $$ is equal to $\varphi'$, where the first and the last maps are induced by adjunctions. Symmetric monoidal structure should be given by $(X, \mathcal{F})\otimes (Y,\mathcal{G})=(X\times Y, \mathcal{F} \boxtimes \mathcal{G})$. In order to make this into an actual symmetric monoidal $2$-category, one needs to specify higher data and check certain compatibilities. However, it seems pretty tricky to do explicitly. One reason is that one needs to check that certain morphisms are equal in the derived category, and this seems quite tricky (because, on the nose, functors depend on a choice of projective/injective resolutions). The second issue is that (to the best of my understanding) it is pretty difficult to write down explicitly all higher coherence data needed to define a symmetric monoidal $2$-category. However, I have seen various authors using this $2$-category without really specifying higher data. Has it been really worked out anywhere? P.S. As far as I understand, an $(\infty, 2)$-analogue of this category has been claimed in a book of Gaitsgory and Rozenblyum, and that category has not been constructed since then. But I wonder if even the usual $2$-categorical version was rigorously constructed. I suppose there's a chance that this is one of the papers that generated your question rather than one that will help answer it, but have you looked in Lu, Q., & Zheng, W. (2022). Categorical traces and a relative Lefschetz–Verdier formula. In Forum of Mathematics, Sigma (Vol. 10). Cambridge University Press. https://arxiv.org/abs/2005.08522 @pupshaw Yes, this is exactly one of the papers that was a reason of this question!
common-pile/stackexchange_filtered
Where exactly the data-cy or data-test-id attribute to the element to test can be added? I am a beginner for the Cypress automation testing. I have gone through the good practice document for Cypress E2E where it suggests to use data-cy or data-test-id for element selection. This might be a simple and dumb question but I am really curious to know the answer from you guys. I tried googling but no luck. Where exactly the data-cy or data-test-id attribute to the element to test can be added? a. Do I have to checkout the code from the developers team, then add the attribute in there? b. Can I use the invoke command in cypress (just like we can add/remove attr using invoke in jquery)? c. Any other method? If the option a. is your answer, then what are the steps you follow? Does the app code and testing code need to be in one project? What hierarchy of element selection you follow? (More info: I have frontend in Typescript and React, backend in sql, test project in cypress) If data-cy or data-test-id attributes are not added to the elements in your project, you can not access the elements using these attributes. Basically, it is a decision that team should take while developing front end application that all testable elements should have proper data-cy or data-test-id which gives more information about the element and it makes easy to write more stable and readable tests. So I would suggest to discuss within a team to define strategy to add these attributes to the existing code and new code. Read more about it at best practices for selecting elements in cypress Thanks for addressing that @Krishna If this answers your question, please consider upvoting/accepting the answer. Thanks!
common-pile/stackexchange_filtered
Filter and display data Here was my last question, and here is the solution i've adopted. But i have another issue. This is how i want to display my categories but i have also sub-categories inside a category. <ul> {{#each group in groups}} <li class="col-md-2"> <ul> {{#each category in group}} <li class="dropdown-header>{{category.category}}</li> // <li>*Subcategories</li> this is where i want to display it {{/each}} </ul> </li> {{/each}} </ul> This is how my data is structured var data = [ { category : "Cat1", subcategory : "Scat1" }, { category : "Cat1", subcategory : "Scat2" }, { category : "Cat2", subcategory : "Scat3" }, { category : "Cat2", subcategory : "Scat4" }, { category : "Cat3", subcategory : "Scat1" }, { category : "Cat3", subcategory : "Scat2" }, { category : "Cat4", subcategory : "Scat3" }, { category : "Cat4", subcategory : "Scat4" }, { category : "Cat5", subcategory : "Scat5"}, { category : "Cat6", subcategory : "Scat6"}, { category : "Cat6", subcategory : "Scat7"}, { category : "Cat6", subcategory : "Scat8"}]; You can see, a category can have many sub-categories. So, how can i display both categories and sub-categories so that i don't get a category twice I think you should use (sub)aggregations here : Pure Mongo db.myData.aggregate([{"$group": {_id: "$category", subcategoriess: { $addToSet: "$subcategory" }}}]); Gives you : { "_id" : "cat3", "subcategoriess" : [ "subcat3.2", "subcat3" ] } { "_id" : "cat2", "subcategoriess" : [ "subcat2" ] } { "_id" : "cat1", "subcategoriess" : [ "subcat1.3", "subcat1.2", "subcat1" ]} Then you can iterate over your results to get the category (_id), then iterate on subcategories to get the list under each category. Meteor : var myDataCol = new Mongo.Collection('myData'); var pipeline = [ {"$group": {_id: "$category", subcategoriess: { $addToSet: "$subcategory" } }} ]; var result = myDataCol.aggregate(pipeline);
common-pile/stackexchange_filtered
Are there additional benefits to fielding max-rank soldiers? One of my soldiers is rapidly approaching Colonel, the highest rank. Once he gets there, is there any incentive to keep bringing him for missions, apart from the obvious advantage of having a strong soldier on the field, i.e. will the additional kills advance him in any way? As far as I know, once your soldiers reach Colonel rank, they no longer advance (unless you count Psi training as advancement, but as far as I know, that has nothing to do with killing aliens in the field). The only advantage of having elite soldiers is the fact that you have elite soldiers on the field - more powerful, higher HP and more perks. There is also an achievement related to having 1 soldier surviving all the missions. @IlyaMelamed does that mean that they must engage in all missions or merely that they should survive till the end of the game? @Alex, they must engage in all missions and survive. They will not improve in any way unless they are Psi-gifted and haven't yet advanced down that path (then you will have to field them, to improve them - not via kills, but by using their abilities). Still, if you play on Classic difficulty, you will rarely have the luxury of leaving your best soldiers at home. You'll need them. Desperatly. Missions keep surprising you with tougher enemies (or even just unexpectly bad RNG-numbers). Good squad members can be the difference between one or two deaths and a wipe. Usually the downtime from injuries will be (more than) enough to train other rookies. The game sort of forces a rotation on you anyway.
common-pile/stackexchange_filtered
VS2010 Publish website not copying some files My web application has two build configurations, Dev and Prod. There is a custom build step that will copy some extra config files to the bin folder, and the files are different depending on the build configuration. This all works well when I do a build, but when I Publish to a FileSystem, these files are not copied over from my bin folder to the publish destination path. Any ideas how to get around this? How are you copying your files? Are you setting the "Copy Local" property to true? When you publish to the local file system, this will copy the files locally.
common-pile/stackexchange_filtered
Use same instance of socket across React application The goal is to initiate a socket connection in App.js on app start and then make this exact socket instance available to other components that are loaded with Router. Online research suggests passing socket to a nested component as follows: const socket = io(); ... render() { return(<div className="App"><NestedComponent socket={socket} /></div>) } This does not work if socket is passed via Router <Route path='/somepath' socket={socket} component={SomeComponent}/> If I attempt using socket in SomeComponent (e.g.: this.props.socket.emit('hi', {})), this breaks app as socket turns out to be undefined in SomeComponent. I was not able to look up a working solution to either pass same instance of a socket with a Router, or use Redux to make socket part of the app state and provide it to lower level components. Any input on this is much appreciated. If this socket is a singleton, can't you just import it? If you must really unit test it, you could mock it. Otherwise, why not use the context API? You can use render method and pass the socket like this: <Route path='/somepath' render={(props) => (<SomeComponent socket={socket} {...props} />)} /> Notice: {...props} is being passed to access router props like location, history, match etc. In SomeComponent: // to access socket props this.props.socket So, this should work fine now: this.props.socket.emit('hi', {}) You're awesome! Thank you so much! I'm doing the exact same thing but when I try access props.socket (using hooks) it says props.socket is undefined
common-pile/stackexchange_filtered
Tensorflow .batch does not separate tensors correctly I have an array of shape (1, 6354944) array([[ 9.15527344e-05, -6.10351562e-05, 6.10351562e-05, ..., 1.01928711e-02, 7.92236328e-02, -2.69470215e-02]]) And converted them to tensor slices stream = tf.data.Dataset.from_tensor_slices(reshaped_data) But when I batch them seqs = stream.batch(1000, drop_remainder=True) It returns <BatchDataset shapes: (1000, 6354944), types: tf.float64> When it's supposed to have a shape of (1000, 6354) a batch of 1000 is too large! Do you want that all your dataset be ONE big batch of 1000 elements? You can reshape your data before creating the dataset : r = tf.reshape(a[ : , :6354000 ], (1000, 6354)) stream = tf.data.Dataset.from_tensor_slices(r) seqs = stream.batch(1000) #(1000,6354) You should set drop_remainder=False to produce an smaller batch as stated in the docs: Batch: batch( batch_size, drop_remainder=False, num_parallel_calls=None, deterministic=None ) The components of the resulting element will have an additional outer dimension, which will be batch_size (or N % batch_size for the last element if batch_size does not divide the number of input elements N evenly and drop_remainder is False). If your program depends on the batches having the same outer dimension, you should set the drop_remainder argument to True to prevent the smaller batch from being produced.
common-pile/stackexchange_filtered
Number of edition in git repository Please, how can i compute the total number of line edited in git repository ? i'm trying this line commande: git log --oneline --shortstat but it returns the number of edition per files. How can i obatain the total number ? the addition of all edition ? How can i obtain the total line (inserted+deleted) in git repository ? by edition do you mean commit? Do you want the sum of all edited lines for each commit? the sum of all edited lines (for each commit) in all git repository I think that you have to do it yourself, parsing the output git log --shortstat and do the maths If i know how can i do it alone, i don't ask :) Sure, but it's a script to write, and maybe nobody will write it for you (I won't, I'm at work). Or maybe not. There are not a commande line directly ? You probably want git diff --shortstat If you want the total lines changed between two commits simply use git diff --shortstat $commit1 $commit2 However your question is not completely precise. Giving the following situation: ,-- a -- b --, o---x m --o `-- c -- d --' Starting at some commit x someone adds 100 lines in commit a and then deletes the same commits in commit b. Someone else adds 10 lines at commit c and deletes the same 10 line at commit d. Afterwards d and b are merged in commit m. In this case x and m contains exactly the same files. What would you expect to be the number of changed lines? 0 - because the files are still the same? 220 - because adding all individual changes would result in this number? 200 or 20 - because those are the changes on each path? something different? Try to answer this question for you. If you come up with 0 use git diff --shortstat. If you come up with 220 use git log --shortstat and add the values manually. If you do not specify any arguments it will work on the diff between you working tree and the index, which is likely to be empty. Use git help diff to learn how to specify what you want. If i give the last commit with the first commit, i obtain the total line edited in all git repository ? you get the lines differing between the first and the last commit. which is not necessarily the same as the total lines edited.
common-pile/stackexchange_filtered
firebase serve and debugging functions? I ran firebase serve --only-functions Then ran functions inspect addMessage So I could debug the addMessage function. Debugging however did not work. Running firebase deploy addMessage --trigger-http firebase inspect addMessage Did work and allow me to debug but it doesn't seem to support hot reloading. Is it possible to have hot reloading and debugging working at the same time? My index.js: const functions = require('firebase-functions'); // The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(); exports.addMessage = functions.https.onRequest((req, res) => { // Grab the text parameter. const original = "123";//req.query.text; // Push the new message into the Realtime Database using the Firebase Admin SDK. return admin.database().ref('/messages').push({original: original}).then((snapshot) => { // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console. return res.redirect(303, snapshot.ref.toString()); }); }); If the reload kills the emulator process, probably not. You'll need to attach to the replacement process. @DougStevenson Upon further investigation it looks like using firebase serve does not allow me to debug even if I run the inspect addMessage command aftewrards, I have to do a firebase deploy addMessage --trigger-http followed by functions inspect addMessage to have debugging working. Is it possible to run firebase serve and debug firebase functions locally? No, background functions won't fire locally. You can debug http functions, though. Well i tried firebase serve --only functions and debugging my addMessage function but the breakpoints did not hit :-/ @tweetypi I have the same problem. You find solution? @tweetypi did you get this working? try: ndb firebase serve debugger breakpoints are hit with stack traces visible, note it's a little slow so give the debugger time to instrument the child processes Additionally I was able to debug cloud functions in isolation using (caps for removed values): GCLOUD_PROJECT=THE-FIREBASE-PROJECT node --inspect-brk /path/to/functions-framework --target FUNCTION-NAME --port=5000 where functions-framework simply expands to the full path for the installed functions-framework (global in my case) from the working directory where the index.js file is for the target functions. Alternately when or where the FIREBASE_CONFIG is needed try this format adjusted to fit: FIREBASE_CONFIG="{\"databaseURL\":\"https://YOUR-FIREBASE-PROJECT.firebaseio.com\",\"storageBucket\":\"YOUR-FIREBASE-PROJECT.appspot.com\",\"projectId\":\"YOUR-FIREBASE-PROJECT\"} https://github.com/GoogleChromeLabs/ndb https://cloud.google.com/functions/docs/functions-framework https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/15 As of firebase-tools v7.11.0, the Firebase emulator now supports attaching a debugger with the --inspect-functions option. This answer shows WebStorm-specific instructions that can be easily adapted to other debuggers.
common-pile/stackexchange_filtered
How to prevent one specific app from reopening, or delay it I'm on Catalina 10.15.7, this reopening feature is awesome and really useful but some of my apps when opened by it since it's too early when this happens, they won't function property I have to close them and open them again, is there any ways that I can delay or even exclude an app from the reopening windows feature? The picture is just for showing you what I'm talking about but I do the restart not log out. Which app is causing issues? @nohillside It's called Intellij, when it boots using this it doesn't recognize its license, I have to close it and reopen it then it does, I guess by the time this happens its license agent hasn't still been booted or something Here's how it's done. We go to ~/Library/Saved Application State/ we find the folder for our app mine is com.jetbrains.intellij.savedState Open the folder, remove everything inside. Go back to ~/Library/Saved Application State/ Press CommandI on the folder name (mine is com.jetbrains.intellij.savedState) now check the locked Now your app can't fill the folder again, causing it to be removed from the restore of the windows, all other apps will still be restored.
common-pile/stackexchange_filtered
ggplot: how to plot a stack bar plot with dodge position I have a dataset like: region country urban_rural treatment potential ---------------------------------------------------- Africa Kenya 1 chlorine compatible Europe England 2 non_clorine not compatible Africa Kenya 1 other potential And I want to make a figure like : can anyone help with this? What have you tried so far? Can you share your code? I hope I understood your question/problem correctly. I made up some more lines of dummy data to get a nicer plots. The graphs can (and probably should) be further polished. library(dplyr) library(ggplot2) library(data.table) # for the dummy data read in from plain text # reading in some dummy data I made up buy copy and pasting plus minor changes df <- data.table::fread("region,country,urban_rural,treatment,potential Africa,Kenya,1,chlorine,compatible Europe,England,2,non_clorine,not compatible Africa,Kenya,1,other,potential Africa,Kenya,1,chlorine,compatible Africa,Kenya,2,non_clorine,not compatible Europe,England,1,other,potential Europe,England,1,other,potential Europe,England,1,non_clorine,compatible Africa,Kenya,2,non_clorine,not compatible Africa,Kenya,1,non_clorine,potential Africa,Kenya,1,other,potential Europe,England,1,chlorine,compatible Africa,Kenya,2,non_clorine,not compatible Europe,England,1,other,potential Africa,Kenya,1,other,potential Africa,Kenya,1,non_clorine,compatible") # one plot for Kenya with title and modified X axis label df %>% # build the counts to display in graph dplyr::count(region, country, treatment, potential) %>% # filter Kenya dplyr::filter(country == 'Kenya') %>% # plot ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) + ggplot2::geom_bar(stat="identity") + # visual enhancement ggplot2::ggtitle("Africa") + ggplot2::xlab("Kenya") # fast way to plot data for all countries df %>% # build the counts to display in graph dplyr::count(region, country, treatment, potential) %>% # plot ggplot2::ggplot(aes(x = treatment, y = n, fill = potential )) + ggplot2::geom_bar(stat="identity") + # build the subplots from country variable ggplot2::facet_wrap(~country) Sorry I didn't make it clear. But I want the x-axis to be multiple countries, and the treatment to be dodge position. I have edited the figure I want. @YiruChen you could use my second example and just include a line to filter for region equals to Africa. dplyr::filter(region == 'Africa') %>% is the line you have to put before the first ggplot2 call (where now is written #plot)
common-pile/stackexchange_filtered
Symfony 1.4: Programmatically set environment for CLI I have a project built on Symfony 1.4 and it has multiple environments - each developer has their own copy installed on their local machine and therefore has their own environment. I am able to dynamically set the environment in index.php, but how can I do this for CLI tasks? I could of course use --env=myenvironment on all tasks, but I would prefer it to be able to use the same logic as I have in index.php How are you determining the environment for the developer in index.php? Host name? GET parameter? can you show us some code? It looks for the existence of environment.cfg file in the main config directory. The contents of this file specify the environment as a string. The advantage is that this file is not committed to SVN, so each developer can specify their own configuration without affecting the config in svn. sfContext::getInstance()->getConfiguration()->getEnvironment() You could do something similar to this in your task perhaps: class MyTask extends sfBaseTask { protected function configure() { // Env config file $file = sfConfig::get("sf_config_dir") . DIRECTORY_SEPARATOR . "environment.cfg"; $env = (file_exists($file) ? file_get_contents($file) : "prod"); $this->addOptions(array( new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', $env), } } The above should work; it defaults to the 'prod' environment if the environment.cfg file doesn't exist. This also assumes that you have just the environment in the file (eg 'prod', 'dev', 'slappythefish' etc). Thanks, this should work - but is there a global way to do it, so that when I type symfony propel:insert-sql-diff, it automatically works out which environment to use?
common-pile/stackexchange_filtered
Passing an Argument in a periodic runnable task execution using handler in Android I have created a periodic execution of runnable task by using handler in android, but I want to pass an argument in that periodic task execution, I have tried 2 approaches to pass an argument, 1 - By declaring a class in the method void Foo(String str) { class OneShotTask implements Runnable { String str; OneShotTask(String s) { str = s; } public void run() { someFunc(str); } } Thread t = new Thread(new OneShotTask(str)); t.start(); } 2 - and by putting it in a function String paramStr = "a parameter"; Runnable myRunnable = createRunnable(paramStr); private Runnable createRunnable(final String paramStr){ Runnable aRunnable = new Runnable(){ public void run(){ someFunc(paramStr); } }; return aRunnable; } Reference for these above 2 approach can be found on Runnable with a parameter? below is my code in which I have used the 1 approach, but either I use 1 or 2 approach there are two problems that remains by passing an argument in a periodic runnable task, 1 problem - the counter variable inside my class is overwritten every time the code repeats itself. If I define this counter variable outside of class and method as a global variable instead of a local variable then it works fine, but that is not my requirement. 2 problem - assume 1 problem is solved by using the counter variable as a global variable then the counter increments after the first execution and with the second execution it unregistered the sensor i.e. mSensorListener but it is unable to remove the further Callbacks with this command, // Removes pending code execution staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null)); this above command is also not working with the onPause method, it still periodically execute after this command execution ? I don't able to understand what is happening, can anyone provide a solution for this ? below is my code, Runnable staticDetectionRunnableCode(String str){ class staticDetectionRunnableClass implements Runnable{ String str; private int counter = 0; staticDetectionRunnableClass(String str){ this.str = str; } @Override public void run() { // Do something here Log.e("", "staticDetectinoHandler Called"); Debug.out(str + " and value of " + counter); // Repeat this runnable code block again every 5 sec, hence periodic execution... staticDetectionHandler.postDelayed(staticDetectionRunnableCode(str), constants.delay_in_msec * 5); // for 5 second if(counter >= 1){ // Removes pending code execution staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null)); // unregister listener mSensorManager.unregisterListener(mSensorListener); } counter++; } } Thread t = new Thread(new staticDetectionRunnableClass(str)); return t; } the first approach is ok, i dont see what problems you have with it though @pskink the problem is by passing an argument with this above periodic task by using the 1 approach, that is the above 2 problems I am facing right now ! sorry but i dont see any problem @pskink you run this above code by making a handler, you will sure able to see i made many times classes that implements Runnable and it worked like a charm with a Handler If I understand the question right, he is having a problem removing the callback. I am little confused about the counter logic. Won't it be always 1 second time around and if you really don't want to run this at all second time around, why do you even do postDelayed? Can you post the counter value that you see? I think your task executes again because you are doing postDelayed before removeCallbacks. Why not put the postdelayed inside else condition? @Raghu thanks man, you have solved my 2 problem, I have putted it into the else part and now it is able to remove the Callbacks, but still I have to take the counter variable as a global variable. If I use counter variable locally its value is always zero, means its overwriting the value of counter, I am always see the counter value as counter = 0 the logic is that, I have use the postDelayed to post a delay of 5 second for every periodic execution, so after first execution the counter value should increment by 1 so for the next execution it will unregistered the sensor and remove callBacks
common-pile/stackexchange_filtered
JMeter: Unzip request while recording Is there a way to decompress HTTP requests while recording them with JMeter (v5.0)? The request body contains zipped (gzip) JSON data. The current solution is very cumbersome. We are extracting the unzipped request body from the browser (Internet Explorer / private mode). We are using the developer tools to set a breakpoint in the JavaScript file "compress.js" and start the request to get to it. The body tag contains the JSON data. We copy it to a text editor and replace backslash+quotation-mark with quotation-mark. In the last step, we replace real values by JMeter user-defined variables. any feedback on answer ? If useful you should accept it and upvote. thanks This is not possible as of JMeter 5.0. See this enhancement request: https://bz.apache.org/bugzilla/show_bug.cgi?id=61748 You may want to test using BURP proxy to decompress request: https://portswigger.net/burp/documentation/desktop/options/http
common-pile/stackexchange_filtered
Second Order differential equation problem I this trying to solve $y'' = yy'$ with $y(0) = 1, y'(0) = 1.$ I know $y' = 1/x'$, $y'' = -x''/(x')^3$ . Then I tried substitute $u = x'$. So $du = x''$. $y'' = -du/u^3$. Then $\int y'' = \frac{1}{2u^2}$. I am a bit confused at this point. Could someone point out how to proceed? One way is to integrate both sides. Then things should look familiar. @AndréNicolas: Are you talking about $y'' = yy'$? Yes, the original equation. @André is referring to the fact that both $y''$ and $yy'$ are the derivatives of simple functions of $y'$ and $y$. What does "$y'=1/x'$" mean? Is that your way of saying $dy/dx=1/(dx/dy)$? @GerryMyerson: yes Even though this can be done just by integrating both sides, the following technique might be of interest.. sometimes for such equations it helps to write $y'(x) = z(y(x))$. Taking derivatives you get $y''(x) = z'(y(x)) y'(x) = z'(y) z $. So the equation $y'' = y y'$ becomes, when viewed as functions of $y$: $$z'(y) z = yz$$ Which is the same as $$z'(y) = y$$ So $z(y) = {1 \over 2}y^2 + C$ So you are reduced to solving $${dy \over dx} = {1 \over 2}y^2 + C$$ You can separate variables to solve this.
common-pile/stackexchange_filtered
Django with two __in queries slower than retrieving separate querysets I have a reasonably complex database consisting of a model, Bar which may have several Spams, implemented by a ForeignKey relationship (each Spam knows which Bar it belongs to). A further model, Foo has exactly two Bars. Here's the relevant bit of models.py: class Bar(models.Model): g = models.IntegerField() ... class Spam(models.Model): name = models.CharField(max_lendth=20) val = models.CharField(max_length=10) bar = models.ForeignKey(bar) class Foo(models.Model): bar1 = models.ForeignKey(Bar, related_name='foo_bar_2') bar2 = models.ForeignKey(Bar, related_name='foo_bar_1') I'd like to know which Foo has a particular pair of bars, where each is identified by its set of Spams. Getting the bars matching the two sets is fine and reasonably fast: def get_bars_queryset(spam_tuples): bars = Bar.objects for name, val in spam_tuples: bars = bars.filter(spam__name=name, spam__val=val) return bars bars1 = get_bars_queryset(spam_tuples=[('eggs', '5'), ('bacon', 'yes')]) bars2 = get_bars_queryset(spam_tuples=[('eggs', '1'), ('toast': '4'), ('milk', '2')]) But when I try the obvious way of retrieving the Foo I want: foos = Foo.objects.filter(bar1__in=bars1, bar2__in=bars2) the performance is very bad. It turns out to be much quicker to retrieve the two sets of Foos separately and find their union: foos1 = Foo.objects.filter(bar1__in=bars1) foos2 = Foo.objects.filter(bar2__in=bars2) foo_bar1_ids = set(foos1.values_list('pk', flat=True)) foo_bar2_ids = set(foos2.values_list('pk', flat=True)) foo_id = foo_bar1_ids & foo_bar2_ids foos = Foo.objects.filter(pk__in=foo_id) I'm guessing this is because the native Django approach is not joining my tables efficiently. How can I force it to? I think you can log the SQL of foos = Foo.objects.filter(bar1__in=bars1, bar2__in=bars2) by using foos.query then you can tuning your database to serve better for that query. Well, in case it helps anyone else, the solution was to force evaluation of the bar querysets: bars1 = list(get_bars_queryset(spam_tuples=[('eggs', '5'), ('bacon', 'yes')])) bars2 = list(get_bars_queryset(spam_tuples=[('eggs', '1'), ('toast': '4'), ('milk', '2')])) before filtering the Foos with foos = Foo.objects.filter(bar1__in=bars1, bar2__in=bars2) This is hinted at in the documentation (Performance considerations): https://docs.djangoproject.com/en/1.7/ref/models/querysets/#in as particularly a problem for MySQL. Thanks to @Minh-Hung Nguyen for pointing me in thr right direction.
common-pile/stackexchange_filtered
How can I repeatedly read user input using Scanner java I am trying to create a simple menu for my program that reads user input. Here's the code: public void menu() { String command; System.out.println("To operate with words write: a"); System.out.println("To operate with products write: b"); System.out.print("\nGive the command: "); Scanner scanner = new Scanner(System.in); command = scanner.nextLine(); if (command.equals("a")) { System.out.println("\nGood job! You have chosen the word program\n"); System.out.println("You can only use the following commands: "); System.out.println("exit - to exit the program"); System.out.println("add - to add a word into the map"); System.out.println("lookup - to lookup a word into the map\n"); System.out.print("Give a command: "); command = scanner.next(); while(scanner.hasNext()){ command = scanner.next(); if(command.equals("add")){ this.addWord(); } System.out.print("Give a command: "); command = scanner.next(); //Here I get the ERROR that throws Exception } } scanner.close(); } public static void main(String [] args) { HashTableInterface table = new HashTable(); Dictionary d = new Dictionary(table); RepositoryInterface repo = new Repository(d); ControllerInterface controller = new Controller(repo); Console c = new Console(controller); c.menu() } And here's a test with the exception I get: To operate with words write: a To operate with products write: b Give the command: a Good job! You have chosen the word program You can only use the following commands: exit - to exit the program add - to add a word into the map lookup - to lookup a word into the map Give a command: add add Give the word: mar Give the word's plural: mere The hash code for mar is: 3 Give a command: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1416) at console.Console.menu(Console.java:56) at test.Prog.main(Prog.java:26) I removed the second command = scanner.next() from the while loop but then it let's me read user input only once. How can solve this? UPDATE: the AddWord method: public void addWord() { Scanner scanner = new Scanner(new InputStreamReader(System.in)); System.out.print("Give the word: "); String word = scanner.nextLine(); System.out.print("Give the word's plural: "); String plural = scanner.nextLine(); scanner.close(); controller.addTheWord(word, plural); } Can you show your main please. @AliAlamiri This is my main: HashTableInterface table = new HashTable(); Dictionary d = new Dictionary(table); RepositoryInterface repo = new Repository(d); ControllerInterface controller = new Controller(repo); Console c = new Console(controller); c.menu(); Can you post your addWord() method? Is it reading user input using nextLine()? @CodingBird updated post with the method are you getting user input from text file? One possible cause for NoSuchElementException to be thrown is because you try to read an input which has reach the end of the data @CodingBird No, I'm using the keyboard input. I'm not reading from a file You can use InputStreamReader str= new InputStreamReader (System.in); BufferedReader uinp= new BufferedReader (str); String val; val= uinp.readLine(); while (!".".equals(val)) { //do your stuff //..and after done, read the next line of the user input. val= uinp.readLine(); } Until and unless you give a "." , it keeps on asking for user input. @MoldovanRazvan We cannot see your screen, actually. Please tell us, what the exception is. "I have an exception" is close to no useful information. @Fildor Sorry! Here's the exception: java.io.IOException: Stream closed at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162) at java.io.BufferedInputStream.read(BufferedInputStream.java:325) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:154) at java.io.BufferedReader.readLine(BufferedReader. There was a typo in my code , i just edited,(typed unip instead of uinp), give a try now. @BharathRallapalli The typo wasn't the problem. I am using Eclipse and it shows me if something's written wrong I checked again , this code seems fine, i am able to supply input continuously. @BharathRallapalli It works in a simple prgram. But if I move all the code in my menu method I still get the exception @_@ @MoldovanRazvan the error may be you are closing InputStreamReader or BufferedReader.If yes then close them in a finally block.. @BharathRallapalli I finally found the error. I was closing the scanner in my addWord() method. You should use switch case inside the while loop instead of if. The switch case should provide the functionality depending on the input provided by the user. That seems irrelevant to the problem. @ViliamBúr Please elaborate. The benefits of replacing an if block with switch case block is that if multiple branches test the same expression, the expression is evaluated only once. The expression in this specific case is command.equals("add"), and it is evaluated only once in the loop anyway. Calling the equals method on a String value repeatedly may be inefficient, but it wouldn't throw a NoSuchElementException, which is the problem. Why not do something like this: public class test { private static Scanner scanner; public static void main(String args[]) { scanner = new Scanner(System.in); printmenu(); getinput(); } private static void printmenu(){ System.out.println("To operate with words write: a"); System.out.println("To operate with products write: b"); } private static void getinput(){ System.out.print("\nGive the command: "); String command = ""; while (!scanner.hasNext()) { } command = scanner.next(); if (command.equals("a")) { System.out.println("\nGood job! You have chosen the word program\n"); System.out.println("You can only use the following commands: "); System.out.println("exit - to exit the program"); System.out.println("add - to add a word into the map"); System.out.println("lookup - to lookup a word into the map\n"); System.out.print("Give a command: "); while(scanner.hasNext()){ command = scanner.next(); if(command.contains("add")){ addWord(); } else{ System.out.println(command); } getinput(); } } else{ scanner.close(); } } public static void addWord() { System.out.print("Give the word: "); String word = scanner.next(); System.out.print("Give the word's plural: "); String plural = scanner.next(); //controller.addTheWord(word, plural); } }
common-pile/stackexchange_filtered
How to dump memory of virtual machine running in linux? I have a windows virtual machine installed using qemu. I want to know how can I dump the entire ram memory of guest system from host system like bin2dmp do in windows. I have read here that it is possible but not able find out how to do that. So any help with that will be appreciated. Is this helpful? https://stackoverflow.com/q/45397607/1974978 You may also be able to suspend the VM and simply read the ram out of the dump file that is automatically created. Have you tried using pmemsave? Thanks, I will try pmemsave which is also mentioned on the link commented by @multithr3at3d and will update you if get successful.
common-pile/stackexchange_filtered
Parsing UTC time to CET/CEST The data I fetch from DB is in UTC time. I need to convert it to CET/CEST. I am using below code. I am not sure if both CET and CEST will be taken care of. Please let me know if it takes care of CET and CEST ? DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); return LocalDateTime.parse(ptu, formatter) .atOffset(ZoneOffset.UTC) .atZoneSameInstant(ZoneId.of("Europe/Amsterdam")) .format(formatter); Could you not test with a CET date and a CEST date? Rather than getting a string from the database and parsing it into a LocalDateTime, why not fetch a LocalDateTime from the outset? yourResultSet.getObject(yourColumn, LocalDateTime.class). With all of the time zone changes that happen all over the world, Don't think of "CET/CEST" and instead think of "the time in Amsterdam", or wherever you happen to be talking about. One can't make the assumption that the time in Amsterdam is the exact same for other places using similar abbreviations for all points in time. In fact, it's likely that many dates are quite different between these various locations. CET and CEST are not always the same, so you can't guarantee that one result will satisfy both timezones. Consider using OffsetDateTime for your example Printing the time now, and in "CET" is straightforward: OffsetDateTime odt = OffsetDateTime.now(); System.out.println(odt); // 2018-10-26T11:25:49.215+01:00 System.out.println(odt.atZoneSameInstant(ZoneId.of("CET"))); // 2018-10-26T12:25:49.215+02:00[CET] However, I don't believe there is a "CEST" in the ZoneID class. So you could print the time of a particular country you know is in CEST and compare them. For example, Algiers is currently in CET, but Amsterdam is in CEST: System.out.println(odt.atZoneSameInstant(ZoneId.of("Europe/Amsterdam"))); System.out.println(odt.atZoneSameInstant(ZoneId.of("Africa/Algiers"))); Output: 2018-10-26T12:42:29.897+02:00[Europe/Amsterdam] 2018-10-26T11:42:29.897+01:00[Africa/Algiers] The class you should be using is ZonedDateTime; as it has full time-zone support(including daylight savings). Your code should be replaced with: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); ZonedDateTime utcTime = LocalDateTime.parse(ptu,formatter).atZone(ZoneId.of("UTC")); ZonedDateTime yourTime = utcTime.withZoneSameLocal(ZoneId.of("Europe/Amsterdam")); return yourTime.format(formatter); The asker is already using ZonedDateTime . The code in the question is correct. Please refer below snippet : ZonedDateTime dateTime =null; Date finalDate = null; DateTimeFormatter format =null; String date = yourdate; LocalDateTime lid = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(""yyyy-MM-dd")); ZoneId id = ZoneId.of("GMT");//Add yours ZonedDateTime gmtZonedDateTime = lid.atZone(id); ZoneId zoneId = ZoneId.of("America/Los_Angeles"); //in case your add your dateTime = gmtZonedDateTime.withZoneSameInstant(id); format = DateTimeFormatter.ofPattern("yyyy-MM-dd"); SimpleDateFormat sfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); finalDate = sfmt.parse(format.format(dateTime)); While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem.
common-pile/stackexchange_filtered
Is there an MSSQL service or app that can act as a router of traffic? I am aiming to setup a router/jump/forwarder/gatekeeper where the service sits on internal network and is whitelisted to connect to AWS RDS. So instead of internal apps connecting directly to AWS RDS, they can connect via this jump server. This wouldn't really be a function that SQL Server would serve .... your best bet would be a web-server of some sort that would take requests from your internal network clients, forward them on, and then return the response. However, if the external IP address for your network is a static one, then that IP address could be whitelisted, and as long as your apps are only making calls from within the internal network, they'll be able to connect. It sounds like maybe you're trying to solve a problem that doesn't exist ....? Thanks for the reply. But what i am trying to control is the traffic going into that external IP. I need a forwarder so that external IP can only be accessed by this forwarder, and this forwarder can have a different type of authentication in place. The hard requirement is to have a whitelist on the external component. Nginx worked perfectly for me. Just a simple service that forwards request on a specified port.
common-pile/stackexchange_filtered
How to read a json file in databricks from any workspace folder I have a simple json file(test.json) located in workspace folder(TestWS) I created as shown below: I want to read the json file from a notebook present in Repo Workspace. I am using simple command in python import json with open(f"/TestWS/test.json","r") as f: js = json.load(f) but all try in vain, I read and checked in workspace only Repo folder is accessible not other, but if its true is there any other workaround we can have to read it that way. If I am using dbutils then only notebook I can execute using (dbutils.notebook.run('location',timeout)) but I need to read json for my use case. Any help will be appreciated. You need to use path like /Workspace/TestWS/test.json or file:/Workspace/TestWS/test.json in spark context. Below is the notebook in Repo. and Json file in workspace. Code: import json with open(f"/Workspace/TestWS/one_piece.json","r") as f: js = json.load(f) display(js) Or spark.read.json("file:/Workspace/TestWS/one_piece.json").show() Hey @JayashankarGS Thanks alot for your answer, I have checked your answer but I don't know why in my dbx its not working, Its still showing FileNotFoundError: [Errno 2] No such file or directory: '/Workspace/TestWS/test.json' But I have checked the json is present in given workspace. I think is there any plugin or options in settings I have to enable to read it or it because of my dbx version, I am using 9.1 LTS I think yes, I tried to spin cluster more than 9.1 LTS like 12.1 LTS and I can clearly see the folders there in workspace but in 9.1 LTS I only see Repo folder. But in my client environment the Prod cluster is 9.1 only so for now I have to see the workaround only. For Databricks Runtime (DBR) 9.1, the Workspace File System (WSFS) is available only for Databricks Repos and only if it's explicitly configured in the Admin settings (another option is only to start with DBR 11.x). As documentation says: Workspace files are enabled everywhere by default for Databricks Runtime 11.2 and above. so you need to upgrade if you want to use it outside of Repos.
common-pile/stackexchange_filtered
make raspberry appear as SSID I have a nodejs server in my raspberry and I want people to be able to connecto to it just connecting to the raspi. The ideal scenario is where in my phone I see the raspi SSID, I connect to it. Then I open chrome enter the ip:port of the raspi itself and it works. Nothing fancier. What I don't know how to search for in the internet is how to set my pi in a way that it opens itself to the world and appears in the SSID list in my phone. I don't need internet sharing nor anything. Just accessing the nodejs server in the pi. This can be easily achieved depending on the OS you are using in your pi. Use basically need to use hostapd and a DHCP Server. You can use a script like create_ap. Im using raspbian
common-pile/stackexchange_filtered
Keeping User Logged In With JWT Please I would like to know how do I keep a user logged in using JWT through a REST API. Because the token given by JWT expires within a particular time frame and within this time frame it could be possible that the user is still on the app. I am thinking of allowing the client side application to make asynchronous requests when the token expires. But the one would also make the client side stall a bit because the token is invalid. If you have this kind of expiration time, you must renew the token before it expires. You need to add this feature to the client side code. It will be hard with a sync client. Another way is renewing it when the sync client runs on the error message about the expiration and resend the last request, so it can be added to the error handling. If so, then it can be generalized in the error handling code.
common-pile/stackexchange_filtered
Phonegap basics - designing ui for iphone and android I'm developing an application both for Iphone and Andriod using Phonegap. I came up with all kinds of plugins JQuery, JQTouch and more, What is the recommended way of doing this? Meaning-designing a generic UI (tabbars, tables, navigation bars etc') for both Iphone,Android that will "feel" native? Thanks, Asaf If you want your application to look as native as possible I'd try jQuery Mobile. The documentation is brilliant and all of elements look native to the iPhone. It's also incredibly easy and quick to build up your UI as all of the design and colour scheme has already been done. I've used this in an Android application that I've made and I've so far received very positive reviews. You may also want to look out for Kendo UI which is out this month! Again, very similar to what jQuery mobile is about with a few exceptions. It has great support for graphs and data, and promotes native Android look and feel. Forget jQueyr mobile.. check this out .. http://pkula.blogspot.com/2011/12/kendo-ui-mobile-and-phonegap-leaked.html Sencha Touch has just released version 2 and it is a good JS toolkit as well. Hi Simon,Is the Sencha touch limited only to Chrome and Safari? if so what will be the result of a user without any of the following browsers operating the application? I feel I have to put my hat in the ring for jQTouch. Although the version downloadable from their site is a bit oldish, if you get it from GitHub it is currently maintained and works well on both iOS and Android. https://github.com/senchalabs/jQTouch Also, if you want the fixed headers or footers with scrollable elements in-between, DataZombie's fork of jQTouch includes iScroll which does a great job of this. https://github.com/DataZombies/jQTouch I am also in the process of developing a theme for jQTouch that will allow apps on Android to feel quite a bit more "native" than the other js kits as they all seem to have a very iOS-cenrtic navigation style (e.g.: back buttons on toolbars instead of relying on the hardware back button, etc). Even if you don't want to wait for my theme, making your own is pretty easy on jQTouch. I would not call myself a designer and I managed. ;) Feel free to choose one of the other answers, but keep jQTouch in mind. I tried and tried other JavaScript frameworks and it was the only one that made it possible to look good on both platforms. jQuery Mobile works awesomely.. and with the theme roller coming soon it will be pretty good. Kendo Mobile UI - Pre release rip.. I have a working Eclispe project here.. markup is identical to jQuery mobile.. but this is faster, nice native looking apps. Take a look
common-pile/stackexchange_filtered
Unable to invoke method setAutomaticRecoveryEnabled for ConnectionFactory in Rabbitmq I am trying to setAutomaticRecoveryEnabled for my connection factory. However, I get a compile error unable to recognize the method setAutomaticRecoveryEnabled for factory object. import com.rabbitmq.client.ConnectionFactory; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); factory.setAutomaticRecoveryEnabled(true); // unable to recognize the //method setAutomaticRecoveryEnabled. pom dependency <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>2.8.4</version> </dependency> Thanks for taking the time to read this and give some advice. I changed the dependency version to 3.5.1: <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>3.5.1</version> </dependency> This worked.
common-pile/stackexchange_filtered
How can I extract font information while isolating the scope of the target font? (I had to change the title of this question, sorry early viewers.) I knew all along that I had serious scope issues, but the code was "good enough" until now. My code was working fine for me because I was using fonts that had enough glyphs to cover both keys and values in my table shown in the example. When I started using FontAwesome, I had to face my fears. extracting information about a target font, but typeset info itself in \normalfont list glyph slot numbers in \normalfont while illustrating each glyph in target font Example The keys/values should all be in \normalfont, while values themselves should be from the target font: Font Name: <value from target font> Type of font: <value from target font> Number of glyphs: <value from target font> Number of features: <value from target font> First character: <value from target font> Last character: <value from target font> 1. <glyph in target font> 2. <glyph in target font> 3. <glyph in target font> Code \documentclass{article} \usepackage{fontspec}% typeset with xelatex \usepackage{tikz} \usepackage{xstring} \usepackage{multicol} \defaultfontfeatures{Extension=.otf}% Add .otf to \newfontfamily\FA{FontAwesome} fontawesome packagusepackage{fontawesome} % adds defs for easy access to characters \usepackage{fontawesome} % Add defs for easy access to characters \begingroup\lccode`\|=`\\ \lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}} \newcommand{\macroname}[1]{\expandafter\removebs\string#1} \newcommand{\fonttable}[1]{% \section{Font: \macroname{#1}} \fontinfo{#1} #1 \pgfmathtruncatemacro\maxstep{\the\XeTeXcountglyphs\font-1} \typeout{XeTeXcountglyphs maxstep is \maxstep} % Prints maxstep to log \begin{multicols}{6} \foreach \charstep in {1,...,\maxstep}{% \makebox[3em][l]{\tiny\charstep}% \bgroup\fontsize{12}{13}\selectfont\textcolor{red}{\XeTeXglyph\charstep}\egroup \endgraf }% \end{multicols} }% \newcommand{\fontinfo}[1]{% \fbox{ \begin{minipage}{\textwidth} Font: #1\fontname\font \\ Type of font: \getfonttype\\ Number of glyphs: \the\numexpr\XeTeXcountglyphs\font-1\relax\\ Number of features: \the\XeTeXcountfeatures\font\\ First character: \char\XeTeXfirstfontchar\font{} corresponding to unicode base-10 character \the\XeTeXfirstfontchar\font \\ Last character: \char\XeTeXlastfontchar\font{} correponding to unicode base-10 character \the\XeTeXlastfontchar\font \\ \end{minipage}} }% \newcommand{\getfonttype}{% \IfEq{\the\XeTeXfonttype\font}{0}{% \hologo{TeX} font (a legacy TFM-based font) }% {}% \IfEq{\the\XeTeXfonttype\font}{1}{% AAT font }% {}% \IfEq{\the\XeTeXfonttype\font}{2}{% OpenType }% {}% \IfEq{\the\XeTeXfonttype\font}{3}{% Graphite }% {}% }% \begin{document} \fonttable{\normalfont} \fonttable{\FA} \end{document} Output Emphasizing Scope Problem You have to confine the font selection only where needed. \documentclass{article} \usepackage{fontspec}% typeset with xelatex \usepackage{tikz} \usepackage{xstring} \usepackage{multicol} \defaultfontfeatures{Extension=.otf} \usepackage{fontawesome} \begingroup\lccode`\|=`\\ \lowercase{\endgroup\def\removebs#1{\if#1|\else#1\fi}} \newcommand{\macroname}[1]{\expandafter\removebs\string#1} \newcommand{\fonttable}[1]{% \section{Font: \macroname{#1}} \fontinfo{#1} \begin{multicols}{6} #1% \pgfmathtruncatemacro\maxstep{\the\XeTeXcountglyphs\font-1} \typeout{XeTeXcountglyphs maxstep is \maxstep} % Prints maxstep to log \foreach \charstep in {1,...,\maxstep}{% \makebox[20pt][l]{\normalfont\tiny\charstep}% \textcolor{red}{\XeTeXglyph\charstep} \endgraf } \end{multicols} } \newcommand{\fontinfo}[1]{% \fbox{% \begingroup#1\edef\x{\endgroup\def\noexpand\fontinfofont{\the\font}}\x \begin{minipage}{\textwidth} Font: \fontname\fontinfofont \\ Type of font: \getfonttype\\ Number of glyphs: \the\numexpr\XeTeXcountglyphs\fontinfofont-1\relax\\ Number of features: \the\XeTeXcountfeatures\fontinfofont\\ First character: {\fontinfofont\char\XeTeXfirstfontchar\font} corresponding to unicode base-10 character \the\XeTeXfirstfontchar\fontinfofont \\ Last character: {\fontinfofont\char\XeTeXlastfontchar\font} correponding to unicode base-10 character \the\XeTeXlastfontchar\fontinfofont \\ \end{minipage}% } } \newcommand{\getfonttype}{% \IfEq{\the\XeTeXfonttype\font}{0}{% \hologo{TeX} font (a legacy TFM-based font) }% {}% \IfEq{\the\XeTeXfonttype\font}{1}{% AAT font }% {}% \IfEq{\the\XeTeXfonttype\font}{2}{% OpenType }% {}% \IfEq{\the\XeTeXfonttype\font}{3}{% Graphite }% {}% } \begin{document} \fonttable{\normalfont} \fonttable{\FA} \end{document} What does \begingroup#1\edef\x{\endgroup\def\noexpand\fontinfofont{\the\font}}\x do? We open a group, where the font selection is executed; thus in the group \font will refer to the font to be tested and \the\font will expand to the control sequence that selects it. We need to expand \the\font, so \edef is the tool; the \x temporary control sequence is defined to expand to \endgroup\def\fontinfofont{<the needed control sequence>} so that executing it will close the group and undo the font selection (and remove the definition for \x as well); however <the needed control sequence> is already in the replacement text for the definition when it will be executed. The code you posted creates many fontspec errors. Missing character: There is no p in font [FontAwesome.otf]/OT:! In my real document, it creates errors for nearly the entire Latin alphabet. Do you know why and how to fix this? Thanks for the explanation below by the way.
common-pile/stackexchange_filtered
Date of birth fields We're trying to have the date-of-birth field for our contacts displayed in dd-mm-yyyy format when using mailings but despite me altering every single relevant setting in Civi...our test mailings still display the date of birth in yyyy-mm-dd format? Why might this be? It would help if you could state what version of CiviCRM you are using with what CMS? Civi 4.6. With Joomla. It might well be that the relevant function does (wrongly) not use the date formatting based on the settings. Could you check that? Well we're using CiviMail for these mailings but that function doesn't appear to have a separate date formatting setting. I am sure it does not :-) I meant if you have any PHP skills and would be able to check in the code?
common-pile/stackexchange_filtered
Map xml file with extracted information I am trying to map one xml file to another, based on a configuration file (that too can be an xml file). Input <ia> <ib>...</ib> <ic>...</ic> </ia> Output <oa> <ob>...</ob> <oc>...</oc> </oa> Config <config> <conf> <input>ia</input> <output>oa</output> </conf> <conf> <input>ib</input> <output>ob</output> </conf> ..... </config> So, the intention is to parse an xml file and retrieve the information interesting to me, and write into another xml file where the mapping information is specified in the config file. Due to the scripting nature (and extending with plugins lateron), and the support for xml processing I was considering python. I just learned the syntax and basics of language, and came to know about lxml One way of doing this parse the config file (where , tag can have xpath to the node I am interested in) read the input file write into output, using etbuilder based on the config file Being new to python, and not seeing xpath support for etbuilder I wonder is this the best approach. Also not sure all the exceptional cases. Is there an easier way, or native support in any other libraries. If possible, I do not want to spend too much time on this task as I could focus on the core task. thanks ins advance. If you wish to transform an XML file into another XML file then XSLT was made for this purpose. You have to define a .xslt file that describes the transformation of XML content and what the eventual output should look like. That's one way to do it. You can also read the XML file using lxml and generate the output XML with lxml.etree.ElementTree. I'm not familiar with etbuilder but I don't think generating the desired output is that difficult. Once you have parsed the input files, you can build the config XML and write it to a file. XPath is primarily for reading XML content, you don't need it for constructing XML files. In fact, if you use a proper XML parser then you don't need XPath either to read the file contents, although XPath could make life a bit easier.
common-pile/stackexchange_filtered
Sorting ng-repeat elements dynamically according to date I want to order by elements according to date. <ion-item ng-repeat="item in PortfolioIdeaList | orderBy:'CreatedDate'" style="background-color:rgb(25, 26, 0);" ng-click="ShowIdeaDetails(item.Id)"> <div class="row"> <div class="col col-80"> <p> {{item.Title}}</p> </div> <div class="col col-20"> <b> {{item.Status}}</b> </div> </div> <div class="row"> <div class="col col-70"> {{item.CreatedDate}} </div> <div class="col col-30"> <i class="icon ion-chevron-right icon-accessory"></i> </div> </div> </ion-item> I am getting Title,Created Date and Status from webservices in JSON format. Created Date is coming as String format MM/DD/YYYY HH:MM:SS e.g 6/2/1991 2:33:43 PM or 12/23/2015 11:55:12 AM. but its not ordering properly. How to convert string into date and then order it. Best way to do is to get the sorted data from the server. possible duplicate of OrderBy Date values, which are just strings in Angular JS With your code, if CreatedDate is a string, your objects will be orderBy alphanumerical order. If you want to order by date, you can : Convert this property to Date when you get your objects from the server new Date(item.CreatedDate) Create a custom filter who convert values into Date and order it : .filter("customOrderBy", function () { return function (input) { input.sort(function(a,b){ return new Date(a.CreatedDate) > new Date(b.CreatedDate); }); return input; } }); And call it in your template : ng-repeat="item in PortfolioIdeaList | customOrderBy" But in all case, you need to convert your strings to YYYY-MM-DD format But what if we have the date coming from database as 2/22/2015 2:33:44 PM You have two solutions : You can create your own parser to create a Date : see example here or you can use an helper library like momentjs Add :false after orderBy works for me <ion-item ng-repeat="item in PortfolioIdeaList | orderBy:'CreatedDate':false" style="background-color:rgb(25, 26, 0);" ng-click="ShowIdeaDetails(item.Id)">
common-pile/stackexchange_filtered
documents4j not saving file after conversion I have converted a .docx file to .pdf using documents4j however the pdf is not showing even the logs shows successful conversion. 26-Jun-2020 21:45:38.163 INFO [http-nio-80-exec-423] com.documents4j.conversion.msoffice.MicrosoftWordBridge.startUp From-Microsoft-Word-Converter was started successfully 26-Jun-2020 21:45:38.163 INFO [http-nio-80-exec-423] com.documents4j.job.LocalConverter.<init> The documents4j local converter has started successfully 26-Jun-2020 21:45:38.187 INFO [pool-50-thread-1] com.documents4j.conversion.msoffice.AbstractMicrosoftOfficeBridge.doStartConversion Requested conversion from C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\stock\batimp\RECTO_BAT20200045.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document) to C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\stock\batimp\RECTO_BAT20200045.pdf (application/pdf) 26-Jun-2020 21:45:38.440 INFO [http-nio-80-exec-423] com.documents4j.conversion.msoffice.MicrosoftWordBridge.shutDown From-Microsoft-Word-Converter was shut down successfully 26-Jun-2020 21:45:38.440 INFO [http-nio-80-exec-423] com.documents4j.job.LocalConverter.shutDown The documents4j local converter has shut down successfully Also debugging showed the following: LocalConversion{pending=false, cancelled=false, done=true, priority=Priority{value=500, creationTime=1593207938174}, file-system-target=C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\stock\batimp\RECTO_BAT20200045.pdf} Why is the pdf not being shown in the directory? program snippet File wordFile = new File(FILE_NAMEX), target = new File(outputFile1); IConverter converter = LocalConverter.builder().baseFolder(new File(path+"batimp")) .workerPool(20, 25, 2, TimeUnit.SECONDS) .processTimeout(5, TimeUnit.SECONDS).build(); Future<Boolean> conversion = converter.convert(wordFile).as(DocumentType.DOCX).to(target).as(DocumentType.PDF) .schedule(); converter.shutDown(); Adding conversion.get() throws the following error > 29-Jun-2020 08:52:21.475 INFO [http-nio-80-exec-1] > com.documents4j.conversion.msoffice.MicrosoftWordBridge.startUp > From-Microsoft-Word-Converter was started successfully 29-Jun-2020 > 08:52:21.475 INFO [http-nio-80-exec-1] > com.documents4j.job.LocalConverter.<init> The documents4j local > converter has started successfully 29-Jun-2020 08:52:21.511 INFO > [pool-1-thread-1] > com.documents4j.conversion.msoffice.AbstractMicrosoftOfficeBridge.doStartConversion > Requested conversion from C:\Program Files\Apache Software > Foundation\Tomcat > 9.0\webapps\stock\batimp\FICHE_TECHNIQUE_BAT20200045.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document) > to C:\Program Files\Apache Software Foundation\Tomcat > 9.0\webapps\stock\batimp\FICHE_TECHNIQUE_BAT20200045.pdf (application/pdf) java.util.concurrent.ExecutionException: Could not > complete conversion > at com.documents4j.job.FailedConversionFuture.get(FailedConversionFuture.java:35) > at com.documents4j.job.FailedConversionFuture.get(FailedConversionFuture.java:10) > at com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:205) > at com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:10) > at downloadbatimp.doGet(downloadbatimp.java:145) > at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) > at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) > at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) > at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) > at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) > at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) > at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) > at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) > at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) > at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) > at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) > at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) > at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) > at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) > at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) > at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) > at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) > at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) > at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) > at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) > at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) > at java.base/java.lang.Thread.run(Thread.java:832) Caused by: com.documents4j.throwables.ConverterAccessException: The converter > seems to be shut down > at com.documents4j.util.Reaction$ConverterAccessExceptionBuilder.make(Reaction.java:117) > at com.documents4j.util.Reaction$ExceptionalReaction.apply(Reaction.java:75) > at com.documents4j.conversion.ExternalConverterScriptResult.resolve(ExternalConverterScriptResult.java:70) > at com.documents4j.conversion.ProcessFutureWrapper.evaluateExitValue(ProcessFutureWrapper.java:48) > at com.documents4j.conversion.ProcessFutureWrapper.get(ProcessFutureWrapper.java:36) > at com.documents4j.conversion.ProcessFutureWrapper.get(ProcessFutureWrapper.java:11) > at com.documents4j.job.AbstractFutureWrappingPriorityFuture.run(AbstractFutureWrappingPriorityFuture.java:78) > at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) > at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) What does conversion.get() return? It shows converter is shutdown. The weird thing that the same code runs on cmd with no issues but not on tomcat even all lib jar files included The File objects for your Word document and PDF document need to explicitly include the paths to their locations. The below sample assumes that the same location is used for both documents - and this is the same as the baseFolder location (where the converter places its temporary files): final String dir = "C:/tmp/conversions/"; File wordFile = new File(dir + "sample.docx"); File pdfFile = new File(dir + "sample.pdf"); IConverter converter = LocalConverter.builder() .baseFolder(new File(dir)) .workerPool(20, 25, 2, TimeUnit.SECONDS) .processTimeout(5, TimeUnit.SECONDS) .build(); Future<Boolean> conversion = converter .convert(wordFile).as(DocumentType.DOCX) .to(pdfFile).as(DocumentType.PDF) .schedule(); converter.shutDown(); So, in the above example, I start with my Word document already in the conversions directory. Just for the record, I use the following dependencies: <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-api</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-local</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-transformer-msoffice-word</artifactId> <version>1.1.3</version> </dependency> UPDATE: For Tomcat, I installed it not as a Windows service, but as a standalone using the "64 bit Windows zip", from this page. I created a very basic servlet, which does nothing except run the conversion code - the same code as I show in this answer. I tried it with 2 different directory locations: One external to CATALINA_BASE and one the same as CATALINA_BASE. Everything worked as expected, with no issues, or need to manage any permissions, etc. My user ID has Windows admin privileges on the PC. My program runs successfully while executing it on cmd but fails with tomcat 9. If i add conversion.get() the message i get converter is shutdown. Why am i not having the issue while running the same code on cmd? Please add all the relevant new information to the question. For example, the Tomcat config and any Catalina error messages. Also, is Tomcat running locally? Thank you @moalex @MoAlex - In case it helps: I ran the above code inside an instance of Tomcat 9 without any issues. This was on my local PC (where MS-Word is installed). It would not work, of course, if Tomcat was running on another server, without access to MS-Word. Tomcat and ms word runs on same server. Still cannot figure out why should it work without any issue using cmd but fails on tomcat Yes - that is odd. Without more information (e.g. config and logs), I don't think it will be easy to help you, unfortunately. I have updated the question to include the stack trace I believe it is an access issue. are there any policies or settings that should be enabled to let tomcat run MS Word? No explicit policies or settings were needed in my set-up, no. I am using Windows 10, with the latest version of Word installed locally. Are you writing the PDF file to an accessible directory (and is that directory inside or outside of the Tomcat installation (CATALINA_HOME) directory)? I do have full Windows admin access on my PC, by the way. Yes sure. Full admin access and the folder within catalina home Also i am not ablee to run processbuilder or runtime exec. My setup is tomcat 9 with jdk 14 and windows 10 I am still unable to recreate your issue. I think it makes sense for me to delete my answer, since it is not relevant to your issue. I have reproduced my issue on tomcat 7 and 9. Thus i still cannot tell what the issue is. Can you advise how didnyou start tomcat? As windows service? I added some notes to my answer, here. tomcat 9 by default, as a windows service, runs under "Local Service". changing the log on to local system account, the mentioned error vanished. however, now i am stuck with another error: java.util.concurrent.ExecutionException: Could not complete conversion at com.documents4j.job.FailedConversionFuture.get(FailedConversionFuture.java:35) at com.documents4j.job.FailedConversionFuture.get(FailedConversionFuture.java:10) at com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:205) at com.documents4j.job.AbstractFutureWrappingPriorityFuture.get(AbstractFutureWrappingPriorityFuture.java:10) at downloadbatimp.doGet(downloadbatimp.java:165) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:832) Caused by: com.documents4j.throwables.ConversionInputException: The input file seems to be corrupt at com.documents4j.util.Reaction$ConversionInputExceptionBuilder.make(Reaction.java:159) at com.documents4j.util.Reaction$ExceptionalReaction.apply(Reaction.java:75) at com.documents4j.conversion.ExternalConverterScriptResult.resolve(ExternalConverterScriptResult.java:70) at com.documents4j.conversion.ProcessFutureWrapper.evaluateExitValue(ProcessFutureWrapper.java:48) at com.documents4j.conversion.ProcessFutureWrapper.get(ProcessFutureWrapper.java:36) at com.documents4j.conversion.ProcessFutureWrapper.get(ProcessFutureWrapper.java:11) at com.documents4j.job.AbstractFutureWrappingPriorityFuture.run(AbstractFutureWrappingPriorityFuture.java:78) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) Again, i believe this has to do with access rights that i am not able to figure out, does anyone know why this message shows? note that even with a simple .docx file containing a single character, the same stack trace shows. You should probably post this as a question, not as an answer - either as an edit to your existing question, or as a new question. But first, take a look here - and note the comment: giving access right as the domain administrator not the machine administrator solved the problem. Maybe that will help. Hi andrew, i have posted it as an answer because it solved a partial issue. I tried the access right that you mentioned with no luck.
common-pile/stackexchange_filtered
Replacement of old modules with updated ones in PERSONAL.XLSB I have written a vba code in a workbook (with many modules) and I need to send the archive (such as Setup.XLSB) including the new code to other people at my work. After they open the Setup.XLSB and click an installer button in order to Call the install_new_modules_inside_personal() , it should replace old modules inside the PERSONAL.XLSB with the new ones. If the user has already his own modules in PERSONAL.XLSB, I don’t want them to be deleted. I just want my modules including the new code to replace my old ones with the same name. Private Sub Install_new_modules_inside_personal() Dim Ver As String Ver = "3" 'Number of version. Insert manually. Dim startupFolder As String startupFolder = Application.StartupPath 'Setup archive check If ActiveWorkbook.Name <> "Setup.XLSB" Then MsgBox ("Error message.") Exit Sub End If 'Version check. This one here is OK. 'Check if PERSONAL.XLSB else save Setup.XLSB as PERSONAL in Application.StartupPath 'export – import code goes here End Sub http://www.cpearson.com/excel/vbe.aspx explains in detail how to use VBA to edit code within a workbook's VB project It will not be easy for the users I refer to, to set Microsoft Visual Basic For Applications Extensibility 5.3. Is there any other easier way to enable Extensibility? I think the following could work: Function CopyModule() I'm not sure if/how you can do that programmatically. I tried to put the file with different name in Startup folder but every time I close the excel, I have to click the x close button twice... Is there any solution for this?
common-pile/stackexchange_filtered
How to deal with big files in Git? We have a Maven project that is a testing suite, composed of some relatively big xml files (+30mb and one file of 1gb), which are actually SoapUI projects. The usual development cycle is that the testers are going to modify these files and add/or add new ones. How do we should versionate these kind of projects? If we compress the files we won't have history but if we don't compress then the project becomes very unhandy to deal with. Usually you use git lfs for large files ...I made the experience that the overhead of using lfs is usually not worth the effort just store it...and what are the real problem with that files? I would like to understand where these very large files come from. I guess you didn't write them manually? So, instead of versioning these files, could you version the procedure that generates them? @JFMeier no, they are not generated. So how did you write 1gb by hand? @JFMeier I'm not sure how it was created, but most probably by copy&paste. But yes, I also think that particular file could be possible to be generated. But in any case, there are other big files that for sure are hand-crafted. The thing is that the main goal is to optimize the project how it is now. We all know how legacy code is painful... Maybe you could split the files into many separate files. Then the burden for git to deal with the changes would be smaller. Really a single file 1 GiB size? This file/approach should be reconsidered. Who really knows what inside that file? Is that file handled/created with/by a tool? I got the same problem... a dataset of xml, svg, 3d files... 2.5gb total... about 10,000 files, not sure what the biggest is yet... yes, all written by hand using other composer technical software. Critical dataset that can't be changed without official order... we want to track it like git, its basically code in xml form, but size limits are a concern with github, and .git folder itself might get big. Looking for common solution, not sure lfs is the answer. You need to use GIT large file storage. (On PC) Install GIT. Install GIT-LFS Open Bash ( that comes with GIT). Go to your repository folder. (where the .git folder is). type "git lfs install" (that'll setup LFS). type "git lfs track "*.psd" (or whatever file type/extension you want to add to the LFS). add the new file ".gitattributes" to your repository. Note, as per doc : "Note that defining the file types Git LFS should track will not, by itself, convert any pre-existing files to Git LFS, such as files on other branches or in your prior commit history. To do that, use the git lfs migrate1 command, which has a range of options designed to suit various potential use cases." Also, see documentation. Could you explain more on how this works? Does this require extra infrastructure? I'm using it, but I did not implement it; I will try setting it up on my home PC.
common-pile/stackexchange_filtered
What does 'The Dark Side of the Moon' mean? One of the most famous albums of Pink Floyd is 'The Dark Side of the Moon'. Besides the title of the album, this phrase also appears in the lyrics of one of the last songs of the album, 'Brain Damage' And if the cloud bursts, thunder in your ear You shout and no one seems to hear And if the band you're in starts playing different tunes I'll see you on the dark side of the moon Pink Floyd are known for using allegories in their philosophical lyrics. So, what is the meaning behind the phrase I'll see you on the dark side of the moon? Don't forget the hidden comment that states There is no dark side in the moon, really. Matter of fact, it's all dark. The moon revolves around the Earth at the exact same speed at which it rotates, due to a phenomenon having to do with the uneven weight distribution of the moon itself. Because of this, on Earth, we only can ever see one side of the moon. The other side of the moon is sometimes referred to as the dark side of the moon, as it is never visible to us. There is much folklore and mythology about the mysterious ‘dark side of the moon.’ In actuality the other side of the moon is lit up just as much as the side we see. The phase of the moon depends on its position relative to the Earth and the sun. The term “lunatic” evolved from the Latin word luna for moon, due to the ancient belief that insanity varied with or was caused by the phase of the moon. No such correlation has been scientifically proven however. This does establish a connection between the moon and madness though, helping us to understand the symbolism of the song. Waters is essentially stating, if you go mad then “I’ll see you on the dark side of the moon.” The dark side of the moon is something that we never see, but is always there, just on the opposite side. Waters seems to be relating this to madness, implying that it is always there, but invisible, waiting to be exposed. Waters elaborates further: "The line 'I'll see you on the dark side of the moon' is me speaking to the listener, saying, I know you have these bad feelings and impulses, because I do too, and one of the ways I can make contact with you is to share the fact that I feel bad sometimes." The ‘dark side of the moon’ can be considered the dark side of ourselves; the side that we try to hide from those around us. Waters is coming out and saying that we all have that side, but we need to keep it in check, or it will take control of us; driving us to madness. Sources: Roger Waters and Pink Floyd: The Concept Albums alum.wpi.edu I think there are two other important lines: "And if the band you're in starts playing different tunes" seems like a clear reference to Syd Barrett and his particular "crazy shining diamond" breed of insanity, and the quote at the very end of the album "There is no dark side of the moon, really--matter of fact it's all dark" seems to indicate that insanity (in some form or another) is far more common than we'd like to admit (hence Roger Waters' "I do too" quote). +1, but nitpick re: "having to do with the uneven weight distribution of the moon itself": It's not an uneven weight distribution, but something called tidal locking. The side of the moon nearer to Earth feels a stronger gravitational force than the other side, because it's closer. The uneven pull has a stabilizing effect, locking the rotational speed to the orbital period as you said. The phrase uses a different sense of the word ‘dark’ meaning ‘unknown, hidden, secret’; you can still see it in expressions such as ‘keep someone in the dark’, ‘darkest Africa’, ‘keep it dark’, and ‘dark horse’.  (So it never had anything to do with the far side of the moon being lit or not.) And if the cloud bursts, thunder in your ear You shout and no one seems to hear And if the band you're in starts playing different tunes I'll see you on the dark side of the moon During the moon explorations and moon landings - the first landing only occurred four years prior to this album's release - viewers of these historic events came to understand a basic problem of radio communications. There is no contact between Earth and astronauts traveling on the opposite side of the moon. The "dark side of the moon" isn't necessarily without light - it's without communication with humanity. It's technically more correct to say "the far side of the moon," but radio communications go "dark" when astronauts travel to the far side of the moon, and since it isn't a place (it's a condition) they would occasionally refer to it as the dark side of the moon. This is a place where you cannot communicate with others, where you are alone locked away in your own thoughts. Thus: You shout and no one seems to hear It is a place where, because the cacophony of humanity is gone, it seems things are irresolvably different from the rest of humanity: the band you're in starts playing different tunes The dark side of the moon is a place apart from humanity where you are likely to be if you find yourself out of step with society. The meaning of Brain Damage can only really be guessed from inferences in the actual lyrics..as no one but Roger Waters truly knows what it means. I'm not sure he has publicly stated that meaning either. However, the inferences suggest it is about some form of mental illness or psychosis; perhaps schizophrenia or other mental disorder. That pretense helps to explain the lyric in a framed context that when your out of your mind, it's isolating; like being on the opposite (dark) side of the moon. It is interesting to note that the original band member Syd Barrett (whom many lyrics are based around - Shine on you crazy diamond is perhaps the most well known) possibly suffered from schizophrenia from excessive drug use and the inability to deal with the fame and spotlight associated with being in Pink Floyd in their early years. Brain Damage Lyrics "Brain Damage" The lunatic is on the grass The lunatic is on the grass Remembering games and daisy chains and laughs Got to keep the loonies on the path The lunatic is in the hall The lunatics are in my hall The paper holds their folded faces to the floor And every day the paper boy brings more And if the dam breaks open many years too soon And if there is no room upon the hill And if your head explodes with dark forbodings too I'll see you on the dark side of the moon The lunatic is in my head The lunatic is in my head You raise the blade, you make the change You re-arrange me 'till I'm sane You lock the door And throw away the key There's someone in my head but it's not me. And if the cloud bursts, thunder in your ear You shout and no one seems to hear And if the band you're in starts playing different tunes I'll see you on the dark side of the moon "I can't think of anything to say except... I think it's marvellous! HaHaHa!" In his autobiography, Nick Mason says that as far as he was aware, Shine On You Crazy Diamond was not actually about Syd. This isn't really an answer to the question. It just says The meaning of the song can only be guessed at while speculating, with nothing to back it up. @DarrickHerwehe I disagree - with some songs we are never going to find out exactly what they were about. Many song writers would rather you worked it out for yourself rather than tell you. Pink Floyd songs are a good example of this and considering the fracturing of the band, I suspect that not even the other members of the band truely know what Roger Waters was getting at in his lyrics... @DarrickHerwehe please read paragraph two again... This is where the answer is. Paragraph one is simply a disclaimer that states unless ROger releases his thoughts on WHAT HE MEANT, we can only make educated guesses with the inferences made. @CarlH - Check here: http://en.wikipedia.org/wiki/Shine_On_You_Crazy_Diamond or Here: http://www.independent.co.uk/news/uk/this-britain/syd-barrett-the-crazy-diamond-407618.html or here: http://brainworldmagazine.com/schizophrenia-and-syd-barrett-shine-on-you-crazy-diamond/ @Phlume Unfortunately I don't have Nick's book to hand so I can't quote it, but his take on Shine On being written about Syd is interesting, to say the least. In any case, I'd then be in the realms of me speculating on Nick's speculation, and this site is about facts that can be backed up. I think the line "if the band you're in starts playing different tunes" seems like a clear reference to Syd, since his behavior during concerts (playing random stuff that wasn't related to what the rest of the band was playing) was a large part of why they replaced him with David Gilmour. It means that you have gone mad. Most, if not all, of the album is about the onset of madness. Here is a detailed analysis of the lyrics. Those lyrics are actually from Brain Damage, which fades into Eclipse. Do you have anything to back up that meaning? @Dom That's my own interpretation of it, which is backed up by a quite a few articles on the net. I've edited the answer to include a link to one of them. I laughed a bit when I first read this question - I'm not sure you understand its scope. One could literally write a book about this album and its meanings. First of all, you absolutely must not take this lyric (or its song) out of context as you interpret the album. This album, like most art (and the moon), revolves around many concepts and ideas. Interpretations may vary. There are many, and ALL of them are potentially correct. A work of art like the Dark Side DOES NOT have a single 'point.' Its meanings are numerous and subjective. However, here is the one I prefer: At the beginning of the album, we hear the lyrics All you touch and all you see Is all your life will ever be Run, rabbit, run Dig that hole, forget the sun When at last, your work is done Don't sit down, it's time to dig another one The above is a major message constantly regurgitated to us by society. Work, work, work, work, work. Just work for the good of the whole. Your life consists only of your perceptions and actions, and it has no special meaning whatsoever. This sets the stage for a statement about the nature of the human society in which we live. In Time / Breathe (Reprise), they further reiterate this dull, clocklike, mechanical existence. When the lyrics 'Home, home again' appear, the subject is essentially taking a break from reality for a moment returning to the dwelling of his personal thoughts and internal existence. Presumably, this break continues throughout The Great Gig in the Sky, after which further statements about the superficial and sometimes hostile nature of society are made in Money and Us and Them. Any Colour You Like is harmonically related to Breathe and its Reprise - this implies that another break from society / reality is being taken. When we come to the final moments of the album, the clocklike existence of the exposition is about to come to an end. It is difficult to put this into words, but I will try. The idea is not to over-interpret every word here, but to get a general idea for what they might be saying. And if the cloud bursts, thunder in your ear You shout, and no one seems to hear Here you've clearly perceived something that was loud or monstrous in nature (note that the cloud is REAL and concrete - not an insane musing), you are shouting about it, and no one SEEMS to hear you. Do they actually hear you? Perhaps they do, but they are too caught up in their monotonous existence to acknowledge your shouting. This may also imply a certain apathy by the people (society) to whom you are shouting. And if the band you're in starts playing different tunes I'll see you on the dark side of the moon The first part of this is an idiom, commonly used in a few different variations: He plays to a different tune. or He marches to the beat of a different drum. This implies that, though the subject may or may not be insane, his perception of reality and / or behavior is decidedly different from that of the rest of society. "The band you're in" may imply that this unique behavior / view of reality can apply to a group or collective at times as well as to the individual, or it may be in reference to multiple aspects of self. So if you march to the beat of a different drum, I'll see you on the dark side of the moon. The dark side of the moon is the same idea as was presented in the lines about shouting about something you've seen, and no-one seeming to hear you. Society either cannot see what you are seeing (in the same way that we cannot see the dark side of the moon), or they are so caught up in their lame, clockwork existence that they are unwilling to acknowledge you. This has so many implications - spiritual, religious, societal, psychological. It works on many levels. And at the very end of the album, we are assured that no matter what we perceive or do, be it right or wrong - sane or insane - that everything is working in tune. The clockwork, apathetic, monotonous existence of society, the moon, the Earth, and indeed everything in existence - both concrete and abstract, seen and unseen - all work together to create and sustain the reality in which we live. It is both a lamentation and a warning. But it is also a message of hope. Very full answer - I'd suggest there may also be references to Syd Barrett, the band's original guitarist, particularly in lines like "And if the band you're in starts playing different tunes / I'll see you on the dark side of the moon", anticipating later songs like "Shine on you Crazy Diamond" Related: Absurdism The album is about various insanities that we all experience as a result of mind and ego. The moon represents the mind and the darkside of the mind is ego. The sun represent a heavenly state of being or the beauty of life but we can't see it because it is eclipsed by the ego.
common-pile/stackexchange_filtered
Some source code not showing at all when not formatted correctly I came across a question where some of the HTML was missing in the question, and the OP had posted it in a comment underneath, so I took it upon myself to edit this code into the question. However, when I went to edit the question, that code was already there! Just, not visible at all outside of edit, because it wasn't indented enough. I appreciate that we should fix these cases when we come across them: applying formatting when needed, but it seems wrong that some code would actually just not render at all - a lazy answerer who would provide an answer but no edit could potentially provide an incorrect answer based on incomplete information. Compare the rendered output / markdown on the edit suggestion. Shouldn’t this be a [tag:feature-request] then? How would you expect it to render, instead? @Xufox It struck me as a bug with how it rendered, but I guess there are arguments for it being a feature-request. Cross-site dupe: Why are HTML tags silently ignored?. @Cerbrus As standard words underneath the code block, like I've seen other times code has not been correctly formatted @Cerbrus Or atleast an indication that something here was stripped out automatically - silently removing it makes it easy to miss for both the asker and answerer @Scoots: A indication like that would make quite a few posts quite messy, I imagine. Related: Please block posts containing unsupported HTML. @Cerbrus I take your point that it wouldn't be pretty, but one could argue that by missing half their code, they're already messy, and attracting equally messy answers. @Scoots: My point is that adding a indication like that will break existing posts. Stack Overflow only allows a very strict subset of HTML to be rendered in a question / answer. Any HTML tags that aren't in that subset will be stripped from the (rendered) post, unless you properly indent your code to format it as code.
common-pile/stackexchange_filtered
Asp NetCore 2 Required validation - ModelState Valid is true when in error I'm trying to get some required field validation working in AspNetCore 2, and what I expect to happen, isn't happening. Model [Required(ErrorMessage = "The game name cannot be blank")] [StringLength(100,ErrorMessage = "The game name must be between 2 and 100 characters", MinimumLength = 2)] [Display(Name = "Name")] public string GameName { get; set; } Controller [HttpPost] [ValidateAntiForgeryToken] public IActionResult GameDetail(GameDetail model, IFormCollection form) { if (!ModelState.IsValid) { return View(model); } // code removed for clarity } View <div asp-validation-summary="ModelOnly" class="text-danger"></div> <form class="form" method="post"> <div class="form-group"> <label class="form-label" asp-for="GameName"></label> <span asp-validation-for="GameName" class="text-danger"></span> <input class="form-control" asp-for="GameName" class="form-control" /> </div> <div class="form-group"> <input class="button" type="submit" value="Continue"> </div> </form> In MVC5, if this form was posted with no value entered, ModelState would be invalid and an error would be returned to the view. However, in this instance, ModelState.IsValid is true, but the error count is 1 and the error list does show the field is required as an error. I have tried a few things including adding [Bind("GameName")] on the post parameters against the model and also [BindRequired] on the model as well as this post: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation Yet, the form submits and redirects to the next page (code removed for clarity) without showing any errors. I would expect to see the view returned with the field error message showing the required error message and an error summary showing the same error. I think you have to add AllowEmptyString=false on the required attribute. [Required (AllowEmptyStrings = false)] this has no effect. Goddamnit! Right, it was a complete and utter screw up on my part and I don't know why I didn't see this first! I coded the page with a simple form first just to get a layout sorted, so just used IFormCollection to save me writing a model public IActionResult GameDetail(GameDetail model, IFormCollection form) Removed the IFormCollection form and it works exactly as I expect it to.
common-pile/stackexchange_filtered
How to call the result from another method in the same Activity in Android I am working on a calculator, and I faced some problems with it. When I try to run the program, it is okay to show the first screen to let me enter the number (in the situation that I ignored the last 2 code of setText for result). After I put the data in the Edittext fields and press the button, it is going to be stopped (Unfortunately the application has been stopped) The code shown below is the method that will be called when I press the button after all information is filled, and I have the formula created in another method separately (the totalCost and profit variable). I am not sure if it is the right way to assign the result from another method to the variable, and not sure why the toString() method in setText doesn't work (error saying that double cannot be dereferenced) Here is the code for ref: public void sendInput(View view) { EditText editTextPurPrice = (EditText) findViewById(R.id.editText_PP); EditText editTextSelPrice = (EditText) findViewById(R.id.editText_SP); EditText editTextStkQty = (EditText) findViewById(R.id.editText_QTY); EditText editTextLotSize = (EditText) findViewById(R.id.editText_LS); TextView resultTTCost = (TextView) findViewById(R.id.resultTTCost); TextView resultProfit = (TextView) findViewById(R.id.resultProfit); Double msgPurPrice = Double.parseDouble(editTextPurPrice.getText().toString()); Double msgSelPrice = Double.parseDouble(editTextSelPrice.getText().toString()); int msgStkQty = Integer.parseInt(editTextStkQty.getText().toString()); int msgLotSize = Integer.parseInt(editTextLotSize.getText().toString()); double totalCost = getTotalCost(msgPurPrice, msgSelPrice, msgStkQty, msgLotSize); double profit = getProfit(msgPurPrice, msgSelPrice, msgStkQty, msgLotSize); resultTTCost.setText(totalCost.toString()); resultProfit.setText(profit.toString()); } Hope someone could help me out... If you have a crash, please copy paste logcat resultTTCost.setText(String.valueOf(totalCost)); resultProfit.setText(String.valueOf(profit)); You need to convert double to String. The other implemention is like this: double aDouble = 0.11; String aString = Double.toString(aDouble); Appreciated! the answer is helpful and inspired. After that I also find out the reason why the toString() method doesn't work in setText in my case. @TroyKC if it was helpful marked as correct answer then buddy !! Problem ia setext it should as below resultTTCost.setText(""+totalCost); resultProfit.setText(""+profit); Or resultTTCost.setText(String.valueOf(totalCost)); resultProfit.setText(String.valueOf Empty String concatenation is regarded as bad coding style! Appreciated! the answer is helpful and inspired
common-pile/stackexchange_filtered
How to use foreach loops in one foreach loop How to use two foreach loops in one foreach loop. foreach ($user_package as $package_id) { $package_detail = Package::all()->where('id','=',$package_id->package_id); } foreach ($package_detail as $package) { $package_amount = $package->price; $package_tagline = $package->tagline; } You simply put the foreach inside the other foreach (inside the {...}). The above code are running them after each other. You're also overwriting all the variables on each iteration so they will only contain the value from the last iteration. I'm guessing you suppose to use those variables for something? Yes @MagnusEriksson is right if you want to get variables outside the foreach then make a one array outside the foreach and put the value in array variable try this if you want to get the variables in out side the foreach You can pluck the id's to an array $userPackageIds = UserPackage::pluck('package_id')->toArray(); im assuming your model name is UserPackage. And retrieve all packages using the ids $package_detail = Package::whereIn('id',$userPackageIds); Your code will be like this $userPackageIds = UserPackage::pluck('package_id')->toArray(); $package_detail = Package::whereIn('id',$userPackageIds); foreach( $package_detail as $package ){ $package_amount = $package->price; $package_tagline = $package->tagline; }
common-pile/stackexchange_filtered
Subversion Merge between multiple working copies? We've completely lost our repository and we have 8 developers with uncomitted changes. Restoring from backup is assumed to be not possible. If one person could have access to all the working copies (either file copy or remote share) is it possible to merge changes in our working copies to one working copy? The final working copy could then be imported into a new repo. In short, can you merge two different working copies without the server? edit: please don't poo poo me for not having backups; that part is beyond my control. It was assumed they were getting backed up nightly. Followup: this is what we did: Started with the most up to date working copy of all the developers. Imported that into the new repo. Working from newest working copy revision to oldest, copied in ONLY the files with changes then committed. wash-rinse-repeat 6 times. (2 devs didn't have uncomitted changes). exported all the old working copies, zipped them up and stored them for safe keeping if needed. Updated our revisions in the release management database to the now very young repo. When faced with the need to merge in work from multiple developers, I have leveraged Git. Git is very good at creating and merging branches. git-svn works quite well. Basically, you tag the code you "started" from in SVN. Create a git repository based on that tag using git-svn. Copy your changed files over. Check the diff. Commit the changes. Then update to the latest from SVN (which will merge SVN changes into the local changes). Then push your changes back to SVN. One git repo can be used to perform multiple merges and pushes. Jacob Since you lost your repository (sorry for that), you also lost the whole history. All you can do now is start from scratch. create a new repository create the folder structure export the working copy of the first user to a new folder import the exported folder into the repository all other users now check out a new working copy all other users now 'export' their original working copy over the new working copy by 'export', I mean creating a copy of the working copy, but without the hidden .svn folders in it. Thanks that makes it sound easy enough. Not fun, but not hard ;) Hi tricky problem this one. But this is what I would do. Create a new repository. Create 8 branches and 1 trunk Import the developers work on the branches. Developer 1 on branch 1 Developer 2 on branch 2 etc etc Then start to merge from branch 1 to trunk. And when you have a stable condition in the trunk, you continue with branch 2 etc etc And when you are done with this horrible work, teach the developers about checkin early and often... And how to use branches... /Johan Your problem is not that you have lost the server but the repo itself. Apart from re-creating a new repo and carefully sort the various working copies for import, I do not see what you could do. Good luck. PS: bad on you to not having backups... PPS: this is the sort of problem DVCS solve naturally by having for most of them a complete copy of the repo in every developer's sandbox. I simplified my question. also added note about backups. :D Understood. My point still stand anyway, both for having your own backup of such an important thing and for DVCS :) I would try just picking one working copy off which to do an import for the new repo, and then repoint the remaining 7 working copies at that new repo using svn switch, possibly with relocate, to make them believe it's the same repo but relocated. Just try to pick a working copy for the initial import that has no (or as few as possible) structural changes from the lost repository: e.g. just file edits. Of course, make tons of backups of your working copies in case the above doesn't work :) That was what I thought I'd have to do. Don't know how the WC will cope with having a high rev than that of the head. And yeah, I've already made two copies of my own WC. You might be able to use svnadmin dump/load to modify the revision # after doing the initial import. Not sure how easy that is, I've never worked with the dumpfile format from svnadmin dump. Workingcopies should never be switched/hacked/editted to point to a repository with a different history than the original repository.. as this is impossible with subversions update strategy (only sending differences with a base version that is known by both sides). Subversion keeps the original version of a file in the local working copy. Create a new repository, make a copy of the oldest working copy, revert changes on the COPY of the working copy, then import that working copy to your new repository. svn import: http://svnbook.red-bean.com/en/1.0/re12.html Once you've imported, you can use svn switch --relocate to repoint the other working copies to your new repository, and commit the changes. svn switch --relocate: http://svnbook.red-bean.com/en/1.1/ch04s05.html switch --relocate probably won't work, because the revision numbers etc won't match... switch --relocate should only be used if the repository moved.. NOT if you altered history.. (The uuid in the workingcopy is there to prevent this; and to make sure you won't lose work if you try anyway) The easiest way would be to create your own server, create a test repo, add one (most stable) build in it, and merge the working copies one at a time. But yes you lost all history because you lost your old repo. You can then create you main repo from that test one. Create a new repository in the same location as the old one from the most original working copy (That way you catch more history in the new repository). If and where it doesn't work, put in .svn-directories from a checkout of the new repository. (For example checkout, and delete everything but the .svn-directories)
common-pile/stackexchange_filtered
Object_list always empty the app is working this way. That i have a simple news adding model as below: class News(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField(auto_now_add=True) content = models.TextField() the view def homepage(request): posts= News.objects.all() #.get(title="aaa") return render_to_response('homepage.html', {'a':posts}) and finally the tamplate: {% for b in a.object_list %} <li> title:{{ b.title }}</li> {%empty %} EMPTY {% endfor %} Unfortunately it always sais 'EMPTY'. However if i take the '.get(title="aaa")' option instead of '.all()' (the commented part) I got the right title and content of the message with title 'aaa'. Can anyone explain what am I doing wrong? Thanks in advance for Your expertise. EDIT I'm sorry I didn't have written the template for the get option Well off course the 'get' verion of template differs. It looks like this: {{a.title}} {{a.content} And it works printing the expected title and message content So the 'get' works with the template and the 'for' didn't iterate over the QuerySet returned by all(). I am beginner but object_list is supposed to be the representation for querySet passed in render_on_request as a element of dictionary? Please post the exact code you are running. There is no way that either of your alternatives would work with a.object_list, because there is no definition of object_list anywhere and it's not a built-in Django property. And assuming you actually mean that for b in a doesn't work in the first code but does in the second, this is not true either, because with .get you won't have anything to iterate through with for. However, let's assume what you actually did was pass the results of .all() to the template, and the template didn't have the for loop. That wouldn't work, because all() - like filter() - returns a QuerySet, which must be iterated through. For the same reason, get() wouldn't work with a for loop. Edited after comment "object_list is supposed to be the representation for querySet passed in render_on_request " - no, it isn't. Where did you get that idea? If you pass a queryset called a to the template, then you iterate through a, nothing else. object_list is the name that is used by default in generic views for the queryset itself - ie what you have called a - but in your own views you call it what you like, and use it with the name you have given it. Edited after second comment I don't know why this should be confusing. You've invented a need for object_list where there is no such variable, and no need for one. Just do as I said originally - {% for b in a %}. I'm sorry I didn't have written the template for the get option Well off course the 'get' verion of template differs. It looks like this: {{a.title}} {{a.content} And it works printing the expected title and message content So the 'get' works with the template and the 'for' didn't iterate over the QuerySet returned by all(). I am beginner but object_list is supposed to be the representation for querySet passed in render_on_request as a element of dictionary? Well this seems confusing. The code I gave You is all I put from the tutorial i have been working on. What is missing then? I just want to distplay in the 'for' tag all simple blog entries with title, content. Where and how should be the 'object-list definition' You were mentioning put? When you use get, the variable posts contains an instance of News. On the other hand, if you use .all(), posts will contain a queryset. So first I would suggest you use filter instead of get, so posts would always be a queryset, and therefore you wouldn't have such an inconsistent behaviour ... When you want to iterate over something like this: for object in object_list: print object object_list needs to support iterating. list, tuple, dict, and other types support that. You can define your own iterator class by giving it a iter method. See the docs for that. Now, in your example return render_to_response('homepage.html', {'a':posts}) posts is a Queryset instance that supports iterating. Think of it this way: {% for b in News.objects.all %} this is what you would like to have, but what you actually did is this: {% for b in News.objects.all.object_list %} But News.objects.all does not have an object_list attribute! News.objects.all is what your object_list should be, so just write: {% for b in a %}
common-pile/stackexchange_filtered
Name for a tax that captures all goods and services produced? Is there a name for a consumption tax that basically captures the GDP (all goods and services produced in the nation)? Value-Added Taxes (VAT) are supposed to capture most goods and services produced in the private sector, but there can be exceptions within a country’s laws. Even if the exceptions were eliminated, there are some non-market components to GDP that would be missed (e.g. imputed values, like the “rental value of owner-occupied housing”). (You need to go into each country’s GDP definition to find the list of imputations.) Can you clarify the "non-market" components of GDP that would be missed? Imputed values, like the value of free chequing accounts. Imputations vary from country to country, so you need to go to the national statistical agency for details.
common-pile/stackexchange_filtered
Limit identical input in database to a certain count I know that we can limit an identical input in database to only one by the keyword UNIQUE, but how about limiting it to more than one? For example, 3,4? Is there a way to achieve this? The only way is to do it on your way by checking that amount before doing a new insert. Before insert a new row, check how many identical rows there are and handle that case (e.g. don't perform the insert and/or show a message to the user).
common-pile/stackexchange_filtered
What is the difference between a function expression vs declaration in JavaScript? What is the difference between the following lines of code? //Function declaration function foo() { return 5; } //Anonymous function expression var foo = function() { return 5; } //Named function expression var foo = function foo() { return 5; } Questions: What is a named/anonymous function expression? What is a declared function? How do browsers deal with these constructs differently? What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right? Here's a good article on named function expressions. Function expressions vs declarations are addressed in the first section. The main difference IMO is hoisting. Here is a good article on the topic: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html Fixed link to the good article on named function expressions. They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context. Function declarations load before any code is executed. Function expressions load only when the interpreter reaches that line of code. So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded. Example: Function Expression alert(foo()); // ERROR! foo wasn't loaded yet var foo = function() { return 5; } Example: Function Declaration alert(foo()); // Alerts 5. Declarations are loaded before any code can run. function foo() { return 5; } As for the second part of your question: var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does. The last one is not the same than var foo = function() { return 5; }. Because here, foo.name is '', in the last one it is 'foo'. @JCM AFAIK, the name property is not part of ECMAScript and is only implemented in some browsers. Function.name at MDN @ZachL Just used as example, what I wanted to say is that the second function has a name, where the first one doesn't. "But if you call a function declaration, it'll always work." So then is there ever a benefit of using a function expression? Why not just always use declarations? It's actually considered a best practice to use function expressions as then the behavior is more intuitive than with declarations. It reads better as it follows a logical flow, You define it and then call it, if you don't you get an error, which is the expected behavior. Actually I think function declarations are not allowed in non function scopes...I recommend this post on the subject: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ Check function hoisting in javascript for more clarifications. http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html Thanks for the explanation, but what is the use of having function expressions over function declarations ? Can I assume that Function Expression implements kind of lazy behaviour, similar to lazy initialization? I mean, it gets loaded only upon the request of interpreter. Function Declaration function foo() { ... } Because of function hoisting, the function declared this way can be called both after and before the definition. Function Expression Named Function Expression var foo = function bar() { ... } Anonymous Function Expression var foo = function() { ... } foo() can be called only after creation. Immediately-Invoked Function Expression (IIFE) (function() { ... }()); Conclusion Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression. Welcome to Stack Overflow! Thanks for posting your answer! Please be sure to read the FAQ on Self-Promotion carefully. Also note that it is required that you post a disclaimer every time you link to your own site/product. point of interest: js is case-sensitive. Your caps-locked examples don't work ;-) also, you can have a Named IIFE: (function myFunc() { ... }()); Shorter and widely used way to write IIFE: If you don't care about the return value, or the possibility of making your code slightly harder to read, you can save a byte by just prefixing the function with a unary operator. Example: !function(){ /*code*/ }(); (source: linked article) @naXa - +1 for the link, well written article on IIFE :) function hoisting & variable hoisting & IIFE As my investigation, any functions in an expression will be function expression. Regarding 3rd definition: var foo = function foo() { return 5; } Heres an example which shows how to use possibility of recursive call: a = function b(i) { if (i>10) { return i; } else { return b(++i); } } console.log(a(5)); // outputs 11 console.log(a(10)); // outputs 11 console.log(a(11)); // outputs 11 console.log(a(15)); // outputs 15 Edit: more interesting example with closures: a = function(c) { return function b(i){ if (i>c) { return i; } return b(++i); } } d = a(5); console.log(d(3)); // outputs 6 console.log(d(8)); // outputs 8 You don't need to declare the function with a different name to make it recursive. In fact, I'd say that confuses things. a = function a(i) and doing return a(++i) produces the same result But using a different name for the function than the variable illustrates the point more clearly. Kudos for providing an example for usage of named function expressions. The first statement depends on the context in which it is declared. If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program. If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()" EDIT: I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code. END EDIT Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore var foo = function foo() { return 5; } Is the same as var foo = function fooYou() { return 5; } fooYou is not ignored. It is visible in function body, so the function can reference itself (e.g. to implement recursion). That's a good point. I didn't think about that :) Also, named function expressions are useful for debugging: var foo = function fooYou() { return 5; }; console.log(foo); console.log(foo.name); will print fooYou() / fooYou (Firefox), [Function: fooYou] / fooYou (node.js), function fooYou() { return 5; } / fooYou (Chrome) or something alone these lines, depending on where you execute it. Named function expressions is the recommended practice since it allows you to refer the function internally, if you need. For instance, to call the function recursively or deal with its name or properties. The major benefit, by the way, is debugging. If you use unnamed functions it's hard to debug if something happen right there, since you will get a reference to an anonymous function and not its name Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same. To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.
common-pile/stackexchange_filtered
hide/disable <div> and <a> onlick of and image but restore them when it backs to original status Please see the live example: http://jsfiddle.net/greedylan/ftmg4kbs/ Is there a way to turn off the div.mask and <p>resistor</p> after clicking the thumbnail? I don't need the mask and title bar when the it shows the bigger image. But I do them to be restored when we click the .close link to close the enlarge picture. I have tried to use CSS selectors as follow but they don't work. .boxes li#one:target + div.mask {display:none} .boxes li#one:target ~ a {display:none} .boxes li#one:target ~ p {display:none} do we need javascript in this case? Thank you in advance!! /*changed*/ li:not(:target) .view:hover p { opacity: 1; transform: translateY(150px); } The :not(selector) selector matches every element that is NOT the specified element/selector. /*added*/ li:target .view .mask { display:none; } ------> jsfiddle
common-pile/stackexchange_filtered
Ubuntu Font Family and Mac OS X confusing font name and font I really like the Ubuntu Font Family, and frequently use it in my documents. At school, I want to be able to use the font family so my documents that make at home using Ubuntu show up correctly at school. However, we do not have permission to use Font View (which also allows you to install fonts), so I copied the .ttf files for the Ubuntu font into the /home/Library/Fonts directory. The fonts now show up in the list of available fonts. However, when I click on Ubuntu Light, it uses the Ubuntu font, and when I click on Ubuntu, it uses the Ubuntu Light font. This is irritating because my documents that I make on my home computer show up in the opposite font at school, and documents I make at school show up in the opposite font at home. This is really irritating. My school uses Mac OSX 10.4. Any help would be greatly appreciated. Edit: This happens with Windows too, so it's something wrong with the font that Ubuntu put on the website. This issue is present on a Ubuntu system also. When Font Viewer is used to compare Ubuntu-R.ttf (regular) and Ubuntu-L.ttf (light), the Light typeface is definitely lighter than the Regular typeface but when compared in Libreoffice Ubuntu light is the heavier typeface. This also shows up on the Ubuntu fonts web page. As an experiment I tried switching the names around. It did not change anything. Hmm... so this is a recognized problem. As indicated in the comments, this sounds like a known problem with the Ubuntu Font Family. I would suggest filing a bug on Launchpad against this project so the developers know and can try doing something about it. Also, forgot to mention: if you do report a bug for this, it'd be helpful if you could post a link to the bug report back here so others will be able to find it easily and mark themselves as affected. Thanks!
common-pile/stackexchange_filtered
The afternoon light streamed through the conservatory windows as Daksh adjusted his glasses, studying the geometric patterns cast by the latticed roof structure above. This whole business of how we perceive depth fascinates me, Collins. When I look up at those intersecting beams, they seem to converge toward a vanishing point, yet I know they're parallel. That's the projective geometry of visual space at work. Hume had an interesting take on this - he argued that our sense of things being extended comes from their color and solidity attributes, not from some inherent spatial container in our minds. But here's what puzzles me. If the brain can't literally contain images, as the modern view suggests, then how do we maintain this
sci-datasets/scilogues
Redirect if query string match on nginx How can I do a redirect if there's a query string on nginx? Additionally, the query string must not come with a trailing slash before, for example: www.url.com?id=xxx Any help would be very appreciated. rewrite does what you want
common-pile/stackexchange_filtered
Slug URL Generator Just a slug generator. I'm wondering if this can be simplified any further. Many thanks. <?php function slug($string) { // Replace all non letters, numbers, spaces or hypens $string = preg_replace('/[^\-\sa-zA-Z0-9]+/', '', mb_strtolower($string)); // Replace spaces and duplicate hyphens with a single hypen $string = preg_replace('/[\-\s]+/', '-', $string); // Trim off left and right hypens $string = trim($string, '-'); return $string; } echo slug('-- This is an example of an ------ article - @@@ ..,.:~&**%$£%$^*'); // outputs "this-is-an-example-of-an-article" Updated version based on feedback: <?php function createSlug($slug) { $lettersNumbersSpacesHyphens = '/[^\-\s\pN\pL]+/u'; $spacesDuplicateHypens = '/[\-\s]+/'; $slug = preg_replace($lettersNumbersSpacesHyphens, '', $slug); $slug = preg_replace($spacesDuplicateHypens, '-', $slug); $slug = trim($slug, '-'); return mb_strtolower($slug, 'UTF-8'); } echo createSlug('-- This is an example ű of an ------ article - @@@ ..,.%&*£%$&*(*'); ?> You could create a few explanatory local variables: $lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/'; $spacesAndDuplicateHyphens = '/[\-\s]+/'; Usage: $lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/'; $slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug)); $spacesAndDuplicateHyphens = '/[\-\s]+/'; $slug = preg_replace($spacesAndDuplicateHyphens, '-', $slug); These would eliminate the comments. (I haven't checked the regexps, other names might be more appropriate.) Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler: Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose. And Clean Code by Robert C. Martin, G19: Use Explanatory Variables. slug could be renamed to cleanSlug (contains a verb) to describe what the function does. I'd rename the $string variable to $slug It would be more descriptive, it would express the intent of the variable. I'd use a whitelist instead of the blacklist. Defining the allowed characters (A-Z, 0-9 etc) would create proper URLs from URLs which contain special characters like é or ű. Thanks. I've updated my original question with some changes. Didn't notice the problem with different characters before, this has now been fixed. @AlexGarrett: You're welcome. I've updated the answer a little bit. Just a small extension to what has been written. If your slug generator is not for an assignment but for actual deployment a lot of frameworks use slug helpers already. I use Laravel, however Laravel has an entire class so that might be messy. Before Laravel, Codeigniter was the rapid deploy system and their slug system is pretty robust. Take a look at the slug file. Now mind you they have formatted it into a class with a lot of comments - but if you omit everything you can compare their's and yours and see where the middle ground can be. Codeigniter Slug Class Note - I'm adding this extra bit because as always you shouldn't re-engineer code if its been done and done well. Great, thanks for the advice. I actually adapted this code from the Laravel framework. It's for education purposes, so wanted to simplify it so it's easier for beginners to grasp. But I completely agree, good hardened code shouldn't be rewritten if not necessary. I recommend the codeigniter's version instead because i had to reverse engineer it for legacy non MVC code and it works better as as stand-alone function rather than a class (once you take out the clutter)
common-pile/stackexchange_filtered
help with a simple equation with powers and logs I've been trying to prove $n^\frac{1}{n} > (n+1)^\frac{1}{n+1}$ and I got to an equation in the midst of it, don't know whether it's correct or not $x^\frac{1}{x} + x^{1+\frac{1}{x}} = 1/3$ for a lower boundary point for the correctness of the eq. above. I'm doing it for fun and I don't remember how to solve this type of equations. Need help! Even if the equation itself is incorrect in the context of the proof - how would I approach solving it? I can rewrite it as $3(x^2 + x) = x^{\frac{x-1}{x}}$ or $log_x{3(x^2 +x)}=\frac{x-1}{x}$ but what should I do next? Edit: My main question is really not about the inequality, but rather about the equation I got: $$x^\frac{1}{x} + x^{1+\frac{1}{x}} = 1/3$$ is it possible to solve it by taking logs and such? Can't wrap my head around it! Edit 2: Turns out there's a special function for this kind of equations, called Lambert W, which is an inverse of $f(z)=ze^z$! So the answer to my question is no, I cannot solve it with my high-school level math chops! Let $y=x^{\frac{1}{x}}$ ... find the turning point (it should be at $x=e$) ... etc ... In such symmetrical cases we generally assume a function ($y=x^{1/x}$) and try to show if it's increasing or decreasing. For this, we'll take log on both sides and differentiate to get $$\frac{dy} {ydx}=\frac{1-lnx}{x^2}\rightarrow dy/dx=x^{1/x}\frac{1-lnx}{x}$$ It is zero at $x=e$. As observed, graph of $y$ will increase for $x<e$ and decrease for $x>e$. Hence, $\forall n\geq3, f(n+1)<f(n)\rightarrow {n+1}^{\frac{1}{n+1}}<n^{1/n}$. For reference: the exact graph of the function $y=x^{1/x}$: I get it, thanks, that's a great way to prove it! But how would I solve the equation that I got for x, if it's in real numbers, like just as a separate equation? The root for it will not be $e$! It's around 0.4847... but how do I get to it? @Non-chemist_dude We generally try to separate any two functions on the RHS and LHS of the equation, and then draw the graphs for each of them, then find intersection point. Or we might have a bounded function (eg: $sinx$) on one side. However, in this equation, $x^\frac{1}{x} + x^{1+\frac{1}{x}} = 1/3$ it's neither the case. Let me think more. HI, Gaurang, I found the answer to my question, and it's negative - there's https://en.wikipedia.org/wiki/Lambert_W_function which helps solve similar equations. @Non-chemist_dude Oh, thanks for notifying me. I haven't studied maths this deep, and am unsure of how it works. But, anyway.
common-pile/stackexchange_filtered
How to maintain session after successful user login in node.js in API call I have tried this but this is not working. Please help me to understand what I'm doing wrong. app.js var session = require('express-session'); app.use(session({ secret: 'intelligenseintelligensein', // session secret resave: true, saveUninitialized: false })); passport_controller.js exports.authenticateUser = function (req, res, next) { passport.authenticate('local-login', function(err, user,info) { if(err) { return functions.sendErrorResponse(req, res, 400, 'Error occured while login. Please try after some time'); } if(!user){ return functions.sendErrorResponse(req, res, 400, 'Invalid email or password'); } if(user && user.status == false){ return functions.sendErrorResponse(req, res, 400, 'Please confirm your account by clicking on activation link sent to your email address', false, false); } if (user && user.status== true){ req.session.user = user; req.user = user; next(); } })(req, res , next); } Follow these two post https://dzone.com/articles/securing-nodejs-managing-sessions-in-expressjs https://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/ @Deeksha Gupta After creating Build by running command npm run build in reactJS app the build will automatically maintain session for react app.
common-pile/stackexchange_filtered
What are the two closest countries that do not share a border? Are there any closer than Namibia/Zimbabwe (which are separated by "less than 200 metres of riverbed", belonging to Botswana, according to Wikipedia)? I'm interested specifically in the case where the countries don't share a land border, but are separated by a short overland distance. Can you clarify your question? I am not sure that qualifies as not sharing a border. They share a border. It's simply a river. Somewhere in the river there's the "imaginary" lines that separates both countrys. @nsn: no, that riverbed is in Botswana. Are you counting maritime borders? Eg if there's a 50m gap in the ocean between two countries, is that 50m, or do you count the fact that they probably each own half the distance. What do you mean by "overland"? the riverbed between Namibia and Zimbabwe is not an overland area. @Vince: I mean not in the ocean. @andra: I'm asking for the closest. Since I gave an example of less than 200 m, any closer would have to be less than that. @andra, Actually, Netherlands and France share a land border in Saint Martin/Sint Maarten island. I would think it clearly covers any two countries separated by some area which is not either country, be it another country or international space between them, or something else I can't think of... @hippietrail: true, but there are very few (if any) non-ocean "international spaces" that border a country. @Max: I didn't feel confident that I knew everything about that. Since there are very few that would probably make a good factoid question since it couldn't be too broad! Do embassies count? @JiříBaum: "Contrary to popular belief, diplomatic missions sometimes do not enjoy full extraterritorial status and are generally not sovereign territory of the represented state. ... Rather, the premises of an embassy remain under the jurisdiction of the host state while being afforded special privileges" https://en.wikipedia.org/wiki/Diplomatic_mission#Extraterritoriality Since nobody has found a shorter distance, it seems that Namibia and Zimbabwe are the closest pair around 200 meters of Botswana territory lies between Namibia and Zimbabwe Tajikistan and Pakistan are 16 km from each other, separated by the Wakhan Corridor which belongs to Afghanistan. Bangladesh and Nepal come within about 25 km of each other, with India in between. Egypt and Saudi Arabia come within about 30 km overland through Israel and Jordan (closer straight-line distance over water). Mongolia and Kazakhstan are separated by about 35 km of rather mountainous terrain. Germany and Italy are separated by about 45 km through Austria. Germany - Liechtenstein is <40 km, with Austria inbetween. I'm trying to find countries with a tight corridor to sea, so that the countries on both sides are close to each other. Bosnia's corridor is only a few km, but both sides of it are Croatia, so that doesn't count. Israel's Red Sea corridor is about 10km wide I think, with neighbouring Egypt and Jordan being that close to each other. This is probably the closest of the ones I've looked at. I think Iraq's connection to the Gulf (bringing Iran and Kuwait close to each other) is slightly larger, but all these "measurements" were made by on zooming on Google Maps and squinting. Slovenia's corridor between Italy and Croatia is similar. Armenia and Iran get within a few km of each other, with Turkey in between, here. But that is spoiled by the fact that they share an actual border on the other side of Azerbaijan's exclave to the right. I want to finish this by mentioning Baarle-Nassau-Hertog, which doesn't qualify (it's all either Netherlands or Belgium) but it's fun. There are also six Dutch exclaves located within the largest Belgian exclave, one within the second-largest, and an eighth within Zondereigen. I was pretty sure Armenia and Iran do have a border because I was hoping to cross it a couple of years ago, but didn't get to. Indeed: Wikivoyage Armenia→Iran and Iran→Armenia. The easternmost tip of Sughd Province, Tajikistan, east of the town of Isfara, has a panhandle squeezed between Uzbekistan to the north and Kyrgyzstan to the south. Using the Maps Labs Distance Measurement Tool on Google Maps, its skinniest part is only around 2.2 km wide. The national borders in the whole Fergana Valley region are generally just ridiculous thanks to Stalin, but this was the thinnest three-country sandwich I could find. ...and I just realized I missed the qualification "that do not share a border", since Uzbekistan and Kyrgyzstan do. Oh well, it's still an interesting oddity of geography. Heh, I've been to that province (to Khujand/Khojand). Thinking though, this answer should probably be a comment, given that it doesn't address all the qualifications specified by the question :/ What are you two smoking? It's an answer, just an incorrect one ;) How about Laos and Myanmar, which are separated by the Mekong River? How wide is it and which country lies between them (that is what the question is about and don't share a common border) Sealand to UK: 13 kilometers Spain to Morocco: 14.3 kilometers Saudi Arabia to Bahrain: 27 kilometers Bahrain to Qatar: 101 Kilometers Sealand's claim to be a separate country is rather shaky. Can you provide a link to the Sealand you claim to be a country in Europe? @Willeke https://en.m.wikipedia.org/wiki/Principality_of_Sealand This answer doesn't fulfill the criteria of the question: where the countries don't share a land border, but are separated by a short overland distance. Spain and Morocco share a common border in 2 places (Ceuta and Melilla). Saudi Arabia/Bahrain/Qatar have a common sea border, but are not seperated by a overland distance. That very weak, I do not think it is a country, Saeland claim also does not meet the overland distance requirement, with only water between it and the UK, it being in UK waters. Wrong answers do not need to be flagged, downvotes is the way to indicate you think it is a wrong answer. The U.S and Russia are 2.5 miles away from each other at it's closest point. You probably want to clarify where this is for those who don't know the Diomede Islands. But no country lies in between the 2. That is what the question is about. Also, in a clarifying comment, the OP stated the separation was not to be ocean.
common-pile/stackexchange_filtered
Pandas Dataframe keep rows where date is between two dates (seperate columns) I have a dataframe that looks similar to this : Price From To 300€ 2020-01-01 2020-01-07 250€ 2020-01-04 2020-01-08 150€ 2020-02-01 2020-02-04 350€ 2020-02-04 2020-02-08 And then I have a list of dates. For example: list = [2020-01-03, 2020-02-04] I would like to keep only the rows of the dataframe where the dates are in between the From column and the To column. So, after transformation I would have the following dataframe. Price From To 300€ 2020-01-01 2020-01-07 150€ 2020-02-01 2020-02-04 350€ 2020-02-04 2020-02-08 First I thought of using a lambda with an apply but I thought it was not very efficient because my dataset is very large. Is there a simpler way to do this with pandas ? The result would be contained in one single dataframe Can you specify more precisely the list of dates? Is it guaranteed to have one entry for each row of the pandas Dataframe? Or is it a two-element list and you want to compare the first element to the From and the second element to To column in the dataframe? The list contains a list of dates of the following format: year-month-day just (could be of type string or of type date I can convert them if needed). The dates in the list have the same format as the dates in the dataframe. There are no NAN values in the dataframe and the list will contain at least one date. the list could contain more dates. In the example I only put 2 days but it could've been 3 dates or even 4 Okay, so which date in the list should be compared to which date in the dataframe? Or is the outcome several dataframes, one for each item in the list? If I look at the example I gave above, I would like to take the first date in the list and keep all the rows where this date is between the From and the To. Then I would take the second date of the list and then keep also all the rows where this date is in between the From and the To dates. Is it clear enough ? When you take the second date, do you apply the filtering to the outcome of the first iteration, or to the original dataframe. That is, do you want one final dataframe or do you want multiple dataframes in the end? For example in pandas there is this method : data[data['colname'].isin(list)] where it looks at value of 'colname' column and if the value is also in the list then it will keep the row. Well it is the same thing with my list of dates. I want to keep only the rows where the dates are in between the From and To column I would like one dataframe at the end Okay. Then note that you can take the min and the max of your dates in the list and filter on those. That reduces the problem in case you many more dates. Then a simple df.query() should suffice. Do you run into speed problems for this scenario? Actually, your example output doesn't work with the description. For instance, the first row would not be included if filtered on the second date as the 2nd of February is not between the 1st and 7th of January @colla. But the row should be kept if at least one date in the list is in between the From and To Let's try with numpy broadcasting: x, y = df[['From', 'To']].values.T a = np.array(['2020-01-03', '2020-02-04'], dtype=np.datetime64) mask = ((x[:, None] <= a) & (y[:, None] >= a)).any(1) df[mask] Price From To 0 300€ 2020-01-01 2020-01-07 2 150€ 2020-02-01 2020-02-04 3 350€ 2020-02-04 2020-02-08 Nice solution, Shubham! You got my upvote! Thank's @DanailPetrov happy holidays! Thank you very much but I get only False in the mask when I should get some True. I am not sure I understand the last line (mask = ...) could you please provide a little explanation? @colla Check df.dtypes the data type of From and To columns should be be datetime64, if not you first need to use pd.to_datetime to convert them to datetime type.. Both my To and From columns were converted as datetime64 : df['From'] = df['From'].astype('datetime64[ns]') Ok I will go there One option is with Pandas IntervalIndex: dates = ['2020-01-03', '2020-02-04'] dates = pd.to_datetime(dates) intervals = pd.IntervalIndex.from_arrays(df.From, df.To, closed='both') df.iloc[intervals.get_indexer_for(dates)] # for duplicates, you can use .unique Price From To 0 300€ 2020-01-01 2020-01-07 2 150€ 2020-02-01 2020-02-04 3 350€ 2020-02-04 2020-02-08
common-pile/stackexchange_filtered
PHPUnit: How do I create a function to be called once for all the tests in a class? I have a PHPUnit test case class (consisting of some test functions). I would like to write a oneTimeSetUp() function to be called once for all my tests in the class (unlike the standard setUp() function which is called once for each test in the class). In other words, I'm looking for a PHPUnit equivalent to the JUnit @BeforeClass annotation. Same question with a oneTimeTearDown() function. Is it possible to do so in PHPUnit? I fully understand the need to do this sometimes for performance. It's recommended to avoid this if possible so you're not sharing state between tests. @Greg: I agree. Still, there are situations where it's better to initialize once for all the tests (to establish a connection to the db, for instance). I try to avoid requiring a DB server by mocking Zend_Db / PDO adapter in my datamapper, I then run assertions on the SQL my classes produce. I appreciate sometimes its unavoidable for functional / end-to-end tests. @Greg: The tests I'm working on are functional tests. They test the highest level, the end-product. Take a look at setUpBeforeClass() from section 6 of the PHPUnit documentation. For the one time tearDown you should use tearDownAfterClass();. Both this methods should be defined in your class as static methods. I was about to write the same thing... Your answer is THE answer Is there any non-static alternative? @Martijn unfortunatelly right now there isn't a method for that in phpunit. Fortunatelly you can override this missing feature by using some "initialized" flag or lazy loading in setUp(). It's still get executed before each test, but does nothing if test class has been already initialized. For setUp, fencing with a flag initialized works, but not for tearDown because you don't know which is the last test. note that this only works if processIsolation is not true in xml or parameters. So, Is there any other option to setupBeforeClass() ? @Martijn maybe the constructor and destructor? setUpBeforeClass() is the way to do this if all of your tests are literally contained within a single class. However, your question sort of implies that you may be using your test class as a base class for multiple test classes. In that case setUpBeforeClass will be run before each one. If you only want to run it once you could guard it with a static variable: abstract class TestBase extends TestCase { protected static $initialized = FALSE; public function setUp() { parent::setUp(); if (!self::$initialized) { // Do something once here for _all_ test subclasses. self::$initialized = TRUE; } } } A final option might be a test listener. This was helpful, but remember to add parent::setUp(); as the first line of the public function setUp(). This is what I said 2 days before you and somehow you're getting all the up-votes. I wonder why. @cprn Because maintainers don't like using @before comment-way, or anything that hides code-flow in comments. @Top-Master Yeah, I don't think that's the reason - my example used to contain setUp() as well before edits. There's a ton of people boosting their SO content with fake accounts before sending resume or a job interview. AFAIR it was my suspicion back in a day. Nowadays I couldn't care less. @cprn Now I get you: 1. someone did copy your answer 2. and instead of that "copy" getting deleted by moderator, they even got more upvotes 3. Finally, you was forced to edit to avoid being a duplicate (even though you was the first to answer). @Top-Master Exactly. On top of that OP specifically didn't want to use setUp() because it's called before every test so I addressed that in my answer and wanted to use setUpBeforeClass() but while writing the code I used setUp() out of habit. I later fixed that but this guy didn't even notice the mistake so his code still uses setUp(). It's kind of funny how obvious it is he copied my answer. lifesaver - I can't believe how misleading the documentation is about this. I was pulling my hair out wondering why setUpBeforeClass was running multiple times when the docs said it would only run once. Not clear at all. I came to this page with the same question, however the accepted answer is ran on all classes, and for me was not the correct answer. If you are like me, your first "Integration test" is to clear out the DB, and run migrations. This gets yourself at a database baseline for all test. I am constantly changing migration files at this point, so setting up the baseline is truly part of all tests. The migration takes a while, so I do not want it run on all tests. Then I needed to build up the database testing each piece. I need to write an order test, but first I need to create some products and test that, then I need to test an import fuction. So, what I did is SUPER easy, but not explained extremely well on the internet. I created a simple test to setup the database. Then in your phpspec.xml file add a testsuite.... <testsuite name="Products"> <file>tests/in/SystemSetupTest.php</file> <file>tests/in/ProductTest.php</file> <file>tests/in/ProductImportTest.php</file> </testsuite> And in the the SystemSetupTest.php .... class SystemSetupTest extends ApiTester { /** @test */ function system_init() { fwrite(STDOUT, __METHOD__ . "\n"); self::createEM(); //this has all the code to init the system... } } Then execute it like: phpunit --testsuite Products In the end, its a ton easier. It will allow me to build up my system correctly. Additionally I am using laravel 5. When using setUpBeforeClass() I end up with bootstrap issues, which I am sure I can fix, but the method I use above works perfect. Better than that run tests like so: ./artisan migrate --datebase CONNECTION_NAME && ./vendor/bin/phpunit. Not a big deal if you use your shell's command history. @x-yuri how come, mate? if you run it locally with DatabaseRefresh trait, you are killing your local db first. running artisan locally would run on local .env file, then the unit tests would run on test db as it is flagged in phpunit.xml as testing env with all the consequences, this approach is not sustainable. bootstrap file is the proper place to enclose your custom code that shall run before all tests, the migrate - seed is the perfect candidate for bootstrap. @ValentinRusk Haven't used Laravel in a while, but apparently my idea was that rather than create a test that migrates the db, you can migrate the db before running the tests. No one suggests to kill the local database. Did you notice the --database switch? What does DatabaseRefresh have to do with ./artisan migrate?.. And there are a number of ways to hide migrating the db (npm run test, ./test, make test, ...). If there's a way to make phpunit migrate the db once, that would be a better way. But what I did is suggested a better (in my view) solution than the one in the answer. Also it's not clear if the author suggests only migration (SystemSetupTest.php), or adding data to the database as well. If both, I don't really like the idea, but can't rule out that it might make sense in some cases. The bootstrap option can be used on these cases. You can call it from the command line phpunit --bootstrap myBootstrap.php Or put it in the XML file, like this: <phpunit bootstrap="myBootstrap.php"> ... </phpunit> Most of the times for me, this attribute contains vendor/autoload.php for loading composer dependencies. Since there can't be multiple bootstrap files, this solution isn't too much suitable @Chris You can require vendor/autoload.php from the bootstrap file though. For example require __DIR__.'/../vendor/autoload.php'; This is the right answer! autoloader to go into bootstrap with additional custom code to be run before tests, like setting up your application, etc. Expanding on accepted answer: None of the setUpBeforeClass(), tearDownAfterClass(), @beforeClass, @afterClass runs in the object context (static methods). You can work around that restriction by guarding any @before code with a static property instead, like so: class MyTest extends PHPUnit\Framework\TestCase { private static $ready = false; /** * @before */ protected function firstSetUp() { if (static::$ready)) return; /* your one time setUp here */ static::$ready = true; } } It can't be used for @after, however, because there's no way of saying when the last test was called.
common-pile/stackexchange_filtered
How much time to wait for an action on my question after offering a bounty I've offered my first bounty on one of my questions, and I'm not sure how long I should wait to notice a movement or at least increased number of views. It's been about an hour and only one new user read my question after that! Is that normal, or am I rushing things? You're rushing things. Relax a bit, and give it time. Your bounty lasts 7 days, if you don't manually award it early. For your best bet, wait the 7 days for answers, and award your bounty to the most helpful answer in the grace period. This meta post may help your question get more views. @InfiniteRecursion, Not much actually, only 4 new views You should be aware that the planet rotates about its axis and that contributors need to sleep, work etc. in different time-zones. 24 hours is a good time to wait before checking. Geeks don't sleep my friend :) post any question, someone will pop up and give you a great answer, especially if it was on a technology, not an application like in my case ;) I've never known bounties to be particularly effective in attracting attention (or good answers). The answers you do attract are often of such poor quality that it hurts to think that your bounty (or at least half of it) must be awarded to one of them. @HotLicks, this is part of the risk, if your question wasnt receiving a good attention, and it is a good question, it worth to spend some reputation on it @simsim - Except that it doesn't seem to work. There are currently 362 featured questions on Stack Overflow, and yours is one of the newest. You should start to see more views as your question moves to the front of that list, which will be near the end of the bounty period. Before then, you should see some increased traffic from users who hunt bounties in the SQL tag. I've red the help regarding adding a bounty, didn't notice a tip about where it will be placed among the other bounty offering questions, but I will wait of course, thanks
common-pile/stackexchange_filtered
How to use htaccess to redirect all but one subdirectory It's been a while since I've messed with .htaccess and I can't seem to get this quite right. I have a site, say example.com, where I want example.com/* to redirect to example.com/collector.html except for URLs under the subdirectory example.com/special, which I want to continue working. For example: example.com/page.html should redirect to example.com/collector.html example.com/foo/bar should redirect to example.com/collector.html example.com/special/page.html should not redirect I would have thought that something like RedirectMatch 302 ^/[^(special)]/.* /collector.html RedirectMatch 302 ^/[^(collector.html)/]* /collector.html would do the trick, but it doesn't seem to work the way I want it to. Maybe this? (needs mod_rewrite) RewriteEngine On RewriteRule !^(special(/.*)?|collector\.html)$ collector.html [R,L] I thought about this but i think he wants to explicitly redirect the user with a 302 code... That's what the [R] flag does Had to make a small modification, changed "special/" to "special/?" so that "example.com/special" doesn't redirect, but other than that this worked, thanks! @Tyler: You might want to make the regex part "!^(special(/.*)?|collector.html)$" then, because your version will not redirect on URLs like "http://example.com/specialpage.html". I'll edit my answer. This works fine for me on Apache 2.2.13 where I recreated the directory structure you described. RedirectMatch 302 /(?!special) http://www.example.com/collector.html The pattern in the brackets is saying do NOT match if the URI contains the string 'special'. Also mod rewrite is not always available and in this case is not needed. Try this: RedirectMatch 302 /\/[^(special)]\/.+/ /collector.html RedirectMatch 302 /\/[^(collector\.html)]/ /collector.html This works to get all subdirectories to go to the collector, but doesn't work to redirect files in the root, e.g. example.com/page.html What's happen ? Does the page is retrieved correctly without any redirect ? Try this on the same line : RedirectMatch 302 //[^(special/)|(collector.html)].*/ /collector.html Maybe...? RewriteEngine on RewriteRule ^(?!special) collector.html [R,NC]
common-pile/stackexchange_filtered
Windows ML's OS requirement What is the minimum Windows OS Version required for Windows ML. I understand it needs Windows 10 SDK build 17723 and above, however will WinML apps built using this SDK work on Windows 10 RS4? Figured it. You need Windows 10 RS5 and above for running Windows ML if you don't want to install Windows 10 Preview builds. Win ML is a machine learning API provided with windows 10 update and is available in build versions above 17723. The purpose of which is to carry out inference locally in windows 10 devices. In order to use a win ml based application you must have the system with the win ml API, which is available on build versions above 17723. RS4 (17134) shipped with a preview API and will not work for production deployment. Windows.AI.MachineLearning is the production version of this API, and officially shipped in RS5 - build 17763 . All of your machines will need to have 17763 in order to run that new production API .
common-pile/stackexchange_filtered
Implementing Runnable vs. extending Thread Why is implementing Runnable a better option than extending from Thread class? This way you decouple the computation (the what) from the execution (the when and/or the how). With Runnable or Callable, you can for instance submit many work/computation to an Executor which will take care to schedule the stuffs. Here is an excerpt form ExecutorService: pool = Executors.newFixedThreadPool(poolSize); ... pool.execute(new Handler(serverSocket.accept())); ... class Handler implements Runnable { ... } Using Runnable/Callable gives you more flexibility that using Threads directly. also so your runnable can extend other non-Thread classes The actual point to take away is that implements is ALWAYS preferred over extends on any questionable cases. Extends binds two class files very closely and can cause some pretty hard to deal with code. When I first "understood" OO programming I was extending EVERYTHING, but it turned my whole design into mush. Now I extend just the few things that clearly and obviously pass the "is-a" test and everything else is an interface... Many many problems just stopped happening (Confusing multiple inheritance situations, time wasted refactoring hierarchies, the tendency to have "protected" variables then wonder why they are changing when you didn't change them in the current class, chaining requirements for constructors, figuring out how different inheritance-trees interact with each other, ... It seems like every 3 years (for the last 20) I think I really "Get" programming and look back at the stupid things I did 3 years ago in shame... This was one of those instances (but from closer to 7 years ago at this point) Because IS-A really isn't what you want. Your class wants to be Runnable, but IS-A Thread feels too strong. That's what inheritance is saying. You really just want to implement the run() method, not all the other attendent stuff in the Thread class. This falls in line with Scott Meyers very good advice in "More Effective C++": Make non-leaf classes abstract. Substitute interfaces and you're spot on. It might not make any sense in your inheritance hierarchies to extend Thread. Only extend Thread if you wish to modify the functionality of Threads. With Runnable, any class in any inheritance hierarchy can expose a task that can be seen as a unit of work to have a Thread perform. The reasons why you might prefer implementing the Interface Runnable to extending the Class Thread are the following: less overhead in a sequencial context (source) When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads. Source: a blog - I'm not quite sure if that's correct you can send tasks over the network with Runnable (Thread is not serializable, source) better OOP-style it's very likely that you don't have a "is a" relationship you have the possibility to extend other classes (Java has no multiple inheritance) To answer the question first: If you extend thread, an instance of your class (extended thread) will always call the constructor of the superclass thread. So MyClass myclass = new MyClass() will always calls "super()" inside the constructor of MyClass which instantiates a thread, and in the end you may implement some overhead into your class (if you don't use any method of the superclass thread). So implementing only Runnable allows your class running faster without any inherited overhead. Further, there are some wrong answers here: Now I extend just the few things that clearly and obviously pass the "is-a" test and everything else is an interface... Didn't you ever consider to create an object without any interface? Because it would be very wrong to implement an interface for every object! When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads. Wrong, everytime you call the constructor of a class, you will get an own object, it doesn't matter from where it is extended or what it implements! Conclusion: In java, EVERY class instance is an object, and extends the class Object (while primitives aren't...only array of primitives like int[] classes extends Object, and such arrays have the same methods like any object - but sadely they're not mentioned in the Javadoc! The Sun guys probably didn't want us to use them). Btw there are at least two advantages of inheritance: Code sharing and a clear Javadoc. Because if you inherite from a class, you can see all subclasses in the Javadoc. You could do that with an interface too, but then you can't share code. Even more, then you would need to create "nested" objects and call the constructor of two or more objects instead of only one, and this again would mean you implement some overhead from the superclass Object itself! Because there is no object in Java without overhead, and creating as less objects as possible is quite important for high performance applications. Objects are the greatest thing, but unnecessairy objects aren't...
common-pile/stackexchange_filtered
Find n minimum. There are $100$ countries participating in an Olympiad. Suppose $n$ is a positive integer such that each of the $100$ countries is willing to communicate in exactly $n$ languages. If each set of $20$ countries can communicate in at least one common language, and no language is common to all $100$ countries, what is the minimum possible value of $n$ ? I have tried to solve this, and I am getting $n\ge 21$, This problem is from RMO 2016,the correct answer is $20$. Please give easy solution. Probably I do not understand. We have 100 countries, and 100 languages $L_1$ to $L_{100}$; Imagine all countries has decided to communicate in languages $L_1$ to $L_{20}$, except one specific country, who communicates with language $L_{21}$ to $L_{40}$ . All sets which have this specific country will be unable to communicate. So the correct answer is 51. @Lourrran: That shows the answer is at least $51$ but does not show that is enough. Divide the languages into five groups of $20$ and let each country speak the $80$ languages from four groups. Now take one country that doesn't speak each group and they cannot communicate, so $n \ge 81$ @Lourrran I think the question is asking for the smallest $n$ for which it is still possible that the countries' language selections is such that every set of 20 countries has a common language. You seem to be looking for the lowest $n$ for which it all language selections work, whereas the question wants the lowest $n$ for which at least one language selection works. The problem and its "solution" are online here as Problem 4 of the Series 5 (Rajasthan, Chhattisgarh, Jharkhand & Orrisa Region) version of RMO-2016. The problem does not directly say how many languages are involved, and the "solution" begins summarily, "Let there be 20 languages everybody speaks." Further reading of the "solution" suggests to me that it was assumed $n$ is the same as the number of languages available. But this doesn't seem to be implied by the problem statement. There is an answer here, if my answer and this collides, please just use their answer. My own answer is like this: The answer is $20$. Suppose there are $21$ languages, $20$ major and $1$ minor. For each of the $20$ major languages, exactly one of the countries (we call it odd countires) does not speak it, and they can speak the minor language. So if there are $\le 19$ odd countries and some other countries picked, one of the major language can be spoken among them. If all the odd countries picked, they can speak the minor language. $19$ is not okay, since if there is one country speak $19$ languages, we can pick other $19$ (possible same, but same is better) countries such that they cannot speak each of the language this country says.
common-pile/stackexchange_filtered
Creating an array of custom objects from nested data structure I'm working on a project that requires me to massage some API data (shown in the snippet below as 'apiData'). The data structure I ultimately need for the charting library I'm using (Recharts) is this: [ { date: '2018-04-24', TSLA: 283.37, AAPL: 250.01 }, { date: '2018-04-25', AAPL: 320.34 } ] I've put together the function below and it works well enough, but I'm having trouble getting all the data to show up, even if there's no match between dates. In the below example, you'll notice that the object for date "2018-04-23" in the apiData is excluded. Ideally, the final ds would look like this: [ { date: '2018-04-23', TSLA: 285.12 } { date: '2018-04-24', TSLA: 283.37, AAPL: 250.01 }, { date: '2018-04-25', AAPL: 320.34 } ] Also, there's probably a more performant way to do this, but I've been hacking away for a while and not seeing a better solution at the moment. E.g. the forEach isn't ideal as the data set grows, which it will when I need to plot long time periods of data. So my questions are: 1) How can I make sure objects that match in date are combined while objects that don't are still included and 2) what's a more performant way to do this operation? If anyone has any input or critique of my approach and how I can improve it, I'd greatly appreciate it. Here's a link to a repl if it's more convenient then the code snippet below. formatChartData = (data) => { const chartData = data .reduce((arr, stock) => { const stockArr = stock.chart.map((item) => { let chartObj = {}; chartObj.date = item.date; chartObj[stock.quote.symbol] = item.close; if (arr.length > 0) { arr.forEach((arrItem) => { if (arrItem.date === item.date) { chartObj = { ...arrItem, ...chartObj }; } }); } return chartObj; }); return stockArr; }, []); console.log(chartData) } const apiData = [ { chart: [ { date: "2018-04-23", open: 291.29, close: 285.12, }, { date: "2018-04-24", open: 291.29, close: 283.37, }, ], news: [], quote: { symbol: "TSLA" }, }, { chart: [ { date: "2018-04-24", open: 200.29, close: 250.01, }, { date: "2018-04-25", open: 290.20, close: 320.34, }, ], news: [], quote: { symbol: "AAPL" }, } ] formatChartData(apiData) EDIT: I ended up using charlietfl's solution with an inner forEach as I found this easier to read than using two reduce methods. The final function looks like this: const chartData = data .reduce((map, stock) => { stock.chart.forEach((chart) => { const chartObj = map.get(chart.date) || { date: chart.date }; chartObj[stock.quote.symbol] = chart.close; map.set(chart.date, chartObj); }); return map; }, new Map());` Is there a reason you are using a reduce to loop through the array items? I figured since I needed to reduce my raw data structure down to something smaller, using reduce might get me there. Though it does, I'm wondering if splitting up the responsibilities might be easier/clearer. A cleaner way than having to loop through the accumulated new array each time to look for a date is to use one master object with dates as keys Following I use reduce() to return a Map (could be an object literal also) using dates as keys and then convert the Map values iterable to array to get the final results const dateMap = apiData.reduce((map,stock)=>{ return stock.chart.reduce((_, chartItem)=>{ // get stored object for this date, or create new object const dayObj = map.get(chartItem.date) || {date: chartItem.date}; dayObj[stock.quote.symbol] = chartItem.close; // store the object in map again using date as key return map.set(chartItem.date, dayObj); },map); }, new Map) const res = [...dateMap.values()]; console.log(res) .as-console-wrapper {max-height: 100%!important;} <script> const apiData = [ { chart: [ { date: "2018-04-23", open: 291.29, close: 285.12, }, { date: "2018-04-24", open: 291.29, close: 283.37, }, ], news: [], quote: { symbol: "TSLA" }, }, { chart: [ { date: "2018-04-24", open: 200.29, close: 250.01, }, { date: "2018-04-25", open: 290.20, close: 320.34, }, ], news: [], quote: { symbol: "AAPL" }, } ] </script> This is great! Thanks for taking the time to share this. Sorry, one more question: out of curiosity, could you explain exactly how the second reduce is working? I see you're passing as the accumulator to the inner reduce the map that's initialized in the outer reduce... and then that inner map is being combined with the outer map? It is all one Map and as you point out it starts in outer and gets passed into inner. So instead of returning accumulator in outer... am simply returning same thing as resultant of inner I actually did this at first just using a forEach loop inside outer reduce. Switching to inner reduce removed one line. Could use any loop inside outer reduce and return the map(accumulator) I ended up using the forEach inside the outer reduce. I found this easier to read than using an inner reduce. Thanks again. The problem is that your reduce function is running for each item in the data array. When it runs on the first item in the data array it returns: [ { date: '2018-04-23', TSLA: 285.12 }, { date: '2018-04-24', TSLA: 283.37 } ] When it runs on the second item in the array it returns this: [ { date: '2018-04-24', TSLA: 283.37, AAPL: 250.01 }, { date: '2018-04-25', AAPL: 320.34 } ] This is because when the reduce runs on the last array item it is returning the result from that item. You are only merging items from the accumulator variable "arr" if their date is in the current array item as well. Since 2018-04-23 is in the first but not the second it is not being added. I have added two things to your code. First if the current date being looped on is in the accumulator variable "arr" I delete it from "arr" after it is merged in. The second change is after each .reduce loop there is still some dates left in "arr" that aren't in the current "stockArr". To deal with this I merge both "arr" and "stockArr" which will give you what you are looking for. formatChartData = (data) => { const chartData = data .reduce((arr, stock) => { const stockArr = stock.chart.map((item) => { let chartObj = {}; chartObj.date = item.date; chartObj[stock.quote.symbol] = item.close; if (arr.length > 0) { arr.forEach((arrItem, index) => { if (arrItem.date === item.date) { chartObj = { ...arrItem, ...chartObj }; arr.splice(index, 1); } }); } return chartObj; }); return [...arr, ...stockArr]; }, []); console.log(chartData) } const data = [ { chart: [ { date: "2018-04-23", open: 291.29, close: 285.12, }, { date: "2018-04-24", open: 291.29, close: 283.37, }, ], news: [], quote: { symbol: "TSLA" }, }, { chart: [ { date: "2018-04-24", open: 200.29, close: 250.01, }, { date: "2018-04-25", open: 290.20, close: 320.34, }, ], news: [], quote: { symbol: "AAPL" }, } ] formatChartData(data) Just correcting your code only, else reduce should be used instead of map, for charts also. formatChartData = (data) => { const chartData = data .reduce((arr, stock) => { const stockArr = stock.chart.map((item) => { let chartObj = {}; chartObj.date = item.date; chartObj[stock.quote.symbol] = item.close; if (arr.length > 0) { arr.forEach((arrItem, i) => { if (arrItem.date === item.date) { chartObj = { ...arrItem, ...chartObj }; delete(arr[i]); } }); } return chartObj; }); return [...arr, ...stockArr].filter(e=>!!e); //to remove undefined elements left by delete above. }, []); console.log(chartData) } const apiData = [ { chart: [ { date: "2018-04-23", open: 291.29, close: 285.12, }, { date: "2018-04-24", open: 291.29, close: 283.37, }, ], news: [], quote: { symbol: "TSLA" }, }, { chart: [ { date: "2018-04-24", open: 200.29, close: 250.01, }, { date: "2018-04-25", open: 290.20, close: 320.34, }, ], news: [], quote: { symbol: "AAPL" }, } ] formatChartData(apiData)
common-pile/stackexchange_filtered
JAVA_HOME errors when run without sudo Hello I am on Linux Mint 16 KDE 64. I have OpenJDK 7 installed and Oracle JDK 7 and if I run Intellij as a normal user I get: 'tools.jar' seems to be not in IDEA classpath. Please ensure JAVA_HOME points to JDK rather than JRE Also if I run gradle build on any of our projects as a normal user I get: Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory. If I run echo $JAVA_HOME Then I get: /usr/lib/jvm/default-java I get the same thing if I run it with sudo. As per the comments below javac -version produces: javac 1.7.0_51 Same result with sudo. What am I doing wrong? You installed only JRE. Try to install JDK: sudo apt-get install openjdk-7-jdk Wow that actually worked. I guess I just didn't have everything setup properly when I installed the oracle jdk. Thank you. try to run javac -version to get version of your java compiler. You should get answer like javac 1.7.0_something. if it's not available then you have only Java Runtime Environment (jre), not Java Development Kit (jdk) installed and you should install the openjdk-7-jdk as Anton suggested. I have updated my question with the results of javac -version Thank you. If it was run after installing openjdk-7-jdk then it makes sense, if it was before installing openjdk-7-jdk then it's weird. Yea that output was before I ran the sudo apt-get install openjdk-7-jdk command. Then I don't understand it. The intellij and gradle complain about nonexisting JDK, the javac is part of JDK but not part of JRE and it still displays javac version even without JDK installed. Yea I didn't have any idea either. I tried everything I could think of before asking.
common-pile/stackexchange_filtered
I can not install ClamAV to my Ubuntu 18.04 machine I'm trying install ClamAV antivirus to my Ubuntu desktop machine, but I got some errors: $ sudo apt-get install clamav clamav-deamon -y Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: clamav : Depends: clamav-freshclam (>= 0.103.2+dfsg) but it is not going to be installed or clamav-data Depends: libclamav9 (>= 0.103.2) but it is not going to be installed clamav-daemon : Depends: clamav-freshclam (>= 0.103.2+dfsg) but it is not going to be installed or clamav-data Depends: libclamav9 (>= 0.103.2) but it is not going to be installed Recommends: clamdscan but it is not going to be installed E: Unable to correct problems, you have held broken packages. How can I fix this? Machine: Nvidia jetson TX2 ARM architecture OS: Ubuntu desktop 18.04 LTS you have requested an impossible situation and you have held broken packages suggest that you have unwisely installed non-Ubuntu or wrong-version packages that are incompatible with your 18.04 system. You fix the problem by uninstalling those non-Ubuntu or wrong-version packages, and by disabling/deleting their source. Please edit your question and include the output of apt policy Xwhere X is all the packages listed in your error output. One command per package; please continue to post text, not pictures.
common-pile/stackexchange_filtered
Run nginx in static IP of server Sorry for my bad English, I can't explain it well. I have a VPS with Windows Server 2012 with Nginx and run a Node server at port 4000 and React client at port 3000. In remote desktop website run at localhost address but when I use static IP of server in other device, I get any response from server. This site can’t be reached XXX.XXX.192.176 took too long to respond. I setup IIS and connected to the server, but when IIS is started, nginx can't start. nginx is configured as follows: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name _; location /api { proxy_pass http://localhost:4000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location /socket.io { proxy_pass http://localhost:4000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } Finally I solved the problem: I just add IP of server as server_name and checked the windows firewall for port 80. server { listen 80; server_name XXX.XXX.192.176; // IP of server location /api { proxy_pass http://localhost:4000; } location /socket.io { proxy_pass http://localhost:4000; } location / { proxy_pass http://localhost:3000; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
common-pile/stackexchange_filtered