qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
267,629
I am trying to add an external Javascript file from my plugin. My code is - ``` <?php /****** * * Plugin Name: Image Zoom * Author: Kallol Das * Description: This plugin will zoom an image of WordPress posts. * version: 1.0 * *******/ function zoom_image_main_js_init(){ wp_enqueue_script('zoom-script', plugins_url('/js/zoom-script.js', __FILE__), array('jquery'), 1.0, true); } add_action('init', 'zoom_image_main_js_init'); ``` Now the problem is It's only enqueuing in admin footer But not in Frontpage footer. So, how to do that?
2017/05/22
[ "https://wordpress.stackexchange.com/questions/267629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101459/" ]
Typical menu structure with 'Home' item being a **Custom Link** and other menu items being pages: > > ![Typical Menu](https://fw2s.com/wp-content/uploads/2017/05/menu.png) > > > The 'Home' menu item **must not** point to a real page and should look like that: > > ![Home](https://fw2s.com/wp-content/uploads/2017/05/home.png) > > > The 'Home' menu item stays the same, regardless of the choice you've made in *Settings -> Reading -> Front page displays*. Remove the **page** 'Home', you've created, then edit your menu, and remove menu item 'Home', which points to 'Home' **page**. Save your menu. Now, by clicking on 'Home' menu item ( custom link ), you'll get your posts displayed, and 'Home' will be highlighted.
198,991
I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C. Just so I don't reinvent the wheel suboptimally. Any suggestions?
2008/10/13
[ "https://Stackoverflow.com/questions/198991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
[Meschach](http://www.math.uiowa.edu/~dstewart/meschach/) is a c-only vector/matrix library, significantly smaller than e.g. LAPACK (according to the FAQ, at least :)
46,665
Is it possible to get beautiful prints in GNU Emacs? By default using M-x print-buffer the output looks ugly, with big fonts and no margin. For source code it would be nice to get a pretty font, syntax highlighting, a header and line numbering.
2009/09/25
[ "https://superuser.com/questions/46665", "https://superuser.com", "https://superuser.com/users/5502/" ]
I would suggest using `M`-`x` `ps-print-buffer-with-faces`, it looks much nicer.
38,155
A few weeks ago I read [this](http://vallettaventures.com/post/13124883568/the-price-of-a-messy-codebase-no-latex-for-the-ipad) (now [here](https://www.texpad.com/blog/price-of-amessy-latex-not-for-ipad)) article about some difficultites bring TeX to the iPad. It made me wonder: why not **rewrite** [`TeX.web`](http://ctan.math.utah.edu/ctan/tex-archive/systems/knuth/dist/tex/tex.web) in C++11? The codebase itself is now quite stable, and (unfortunately) it won't be too many more years before it's completely frozen. I just [downloaded](http://tug.org/texlive/devsrc/Build/source/texk/web2c/tex.web) the source; it's about 25,000 lines of WEB code. Let's say the code/comment ratio is 1/5, which results in around 5,000 lines of actual source code. At one line/minute hand rewrite, that's a little over two weeks. Even if these calculations are off a bit, it still seems like a "summer vacation" project. Yes, I know there is a lot more than just `TeX.web`. But it seems like a native C++ implementation (rather than a `web2c` compiliation) could be an interesting step in a different direction.
2011/12/13
[ "https://tex.stackexchange.com/questions/38155", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/1945/" ]
Check Taco's [CXTeX](http://metatex.org/cxtex/); "*A hand-converted C version of TeX*". I think one can throw some C++ syntactic sugar on top of it, but IMO that is as far as you can go without rethinking the whole TeX structure.
51,770,299
UserDetail.java (model class) ``` @Entity public class UserDetail { @Id private String email; private String name; private String password; @ManyToMany(cascade = CascadeType.ALL) private List<Role> role; @ManyToMany(cascade = CascadeType.ALL,mappedBy = "user") private List<GroupDetail> group; } ``` GroupDetail.java ( model class) ``` @Entity public class GroupDetail { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(unique = true) private String groupName; @ManyToMany(cascade = CascadeType.ALL) private List<UserDetail> user; @ManyToMany(cascade = CascadeType.ALL) private List<Role> role; } ``` Here as you can see GroupDetail is the owner of the association and Hibernate will only check that side when maintaining the association. So, how do i get List of GroupDetail using the user email?
2018/08/09
[ "https://Stackoverflow.com/questions/51770299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10139140/" ]
I would use a list to keep track of each label. Then apply a new text size to the label when the window resizes. You will also need to provide a 1x1 pixel image in order for the label to read its size in pixels vs text height. I will be using `grid()` for this but it could just as easily be done with `pack()`. Because we are using `grid()` we need to make sure we set weights on each column/row the labels will be set to using `rowconfigure()` and `columnconfigure()`. The function we will need should check the height and width of the widget and then based on what number is smaller set the size of the font object. This will prevent the font from growing bigger than the label size. ``` import tkinter as tk import tkinter.font as tkFont root = tk.Tk() label_list = [] font = tkFont.Font(family="Helvetica") pixel = tk.PhotoImage(width=1, height=1) for x in range(3): for y in range(3): root.rowconfigure(y, weight=1) root.columnconfigure(x, weight=1) label_list.append(tk.Label(root, width=40, height=40, image=pixel, text=(y * 3 + x) + 1, relief="groove", compound="center")) label_list[-1].grid(row=x, column=y, sticky="nsew") def font_resize(event=None): for lbl in label_list: x = lbl.winfo_width() y = lbl.winfo_height() if x < y: lbl.config(font=("Courier", (x-10))) else: lbl.config(font=("Courier", (y-10))) root.bind( "<Configure>", font_resize) root.mainloop() ``` Results: No mater how you resize the window it should always have roughly the largest the font can be without exceeding the label size. [![enter image description here](https://i.stack.imgur.com/DxGRv.png)](https://i.stack.imgur.com/DxGRv.png) [![enter image description here](https://i.stack.imgur.com/JMCUj.png)](https://i.stack.imgur.com/JMCUj.png) [![enter image description here](https://i.stack.imgur.com/jdgkF.png)](https://i.stack.imgur.com/jdgkF.png) UPDATE: I did change a few things in your code. I changed how you were creating your `btn_ID` to something less complicated and something we can use with the update method. Let me know if you have any questions. To answer your changed question and your comment here is a reworked version of your new code to do what you want: ``` from tkinter import * import tkinter.font as tkFont grey = [0,1,2,6,7,8,9,10,11,15,16,17,18,19,20,24,25,26,30,31,32,39,40,41,48,49,50,54,55,56,60,61,62,63,64,65,69,70,71,72,73,74,78,79,80] class GUI(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pixel = PhotoImage(width=1, height=1) self.font = tkFont.Font(family="Helvetica") self.master.bind("<Configure>", self.font_resize) self.btn_list = [] self.filled = [] self.filled_ID = [] self.screen_init() self.key = None self.keydetection = False self.detect() self.bind_all("<Key>", self.key_event) root.bind( "<Configure>", self.font_resize) def screen_init(self, master=None): btn_ndex = 0 for x in range(9): for y in range(9): self.btn_list.append(Button(master, font=self.font, width=40, height=40, image=self.pixel, compound=CENTER, bg="#D3D3D3" if 9 * y + x in grey else "#FFFFFF", command=lambda c=btn_ndex: self.click(c))) self.btn_list[-1].grid(row=y, column=x, sticky="nsew") root.rowconfigure(y, weight=1) root.columnconfigure(x, weight=1) btn_ndex += 1 def font_resize(self, event=None): for btn in self.btn_list: x = btn.winfo_width() y = btn.winfo_height() if x < y: self.font.configure(size=x-10) else: self.font.configure(size=y-10) def update(self, btn_ID, number=None, colour="#000000", master=None): print(btn_ID) y = btn_ID // 9 x = btn_ID % 9 self.btn_list[btn_ID].config(text=number, fg=colour, bg="#D3D3D3" if 9 * y + x in grey else "#FFFFFF", command=lambda c=9 * y + x: self.click(c)) def detect(self): self.keydetection=not self.keydetection def key_event(self, event): try: self.key=int(event.keysym) except: print("Numbers Only!") def click(self, btn_ID): if btn_ID in self.filled: self.filled_ID.pop(self.filled.index(btn_ID)) self.filled.remove(btn_ID) window.update(btn_ID) else: self.filled.append(btn_ID) self.filled_ID.append(self.key) window.update(btn_ID, self.key) if __name__ == '__main__': root = Tk() root.title("Example") window = GUI(root) root.mainloop() ```
73,558,629
Say I have an array of arrays like so: `const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd']]` I would like to arrange it so that they are futher sorted into groups of arrays, with the first element in each dictating how they are sorted. The result would look like this: `const output = [[[1, 'aaa'], [1, 'bbb']], [[2, 'ccc'], [2, 'ddd']]]` The first group would have all arrays where the first element is 1, the second group would all have 2 as the first element, and so forth. The second solution to this question is probably the closest thing I can find: [Grouping array group into separate sub array group](https://stackoverflow.com/questions/66044336/grouping-array-group-into-separate-sub-array-group) However, my modifications don't seem to work and I imagine I am misunderstand something about the functionality of `.reduce()`. What I've tried: ``` const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd']]; const output = input.reduce( (r, c, i, a) => ( c[0] != a[i - 1][0] ? r.push([c]) : r[r.length - 1].push(c), r ), []); ``` Am I heading in the right direction, or is there a more simple solution that lies elsewhere?
2022/08/31
[ "https://Stackoverflow.com/questions/73558629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14003322/" ]
So basically what i'm doing here (inside the `.reduce()`) is searching for a group that contains a value (`[number, string]`) which number (id) is equal to the number of the value i'm trying to add. If i find a group i push the new value (`nv`) inside that group, else i create a new group (`[nv]`) ```js const input = [[1, 'aaa'], [1, 'bbb'], [2, 'ccc'], [2, 'ddd'], [4, 'aaa'], [5, 'aaa']] const output = input.reduce((groups, nv) => { const group = groups.find(g => g.some(([id]) => id === nv[0])) if(!group) groups.push([nv]) else group.push(nv) return groups }, []) // output: [[[1, 'aaa'], [1, 'bbb']], [[2, 'ccc'], [2, 'ddd']], [[4, 'aaa']], [[5, 'aaa']]] ```
197,791
Sabrina's aunts called the Feast of Feasts an annual celebration, meaning it's occurred over a dozen since Sabrina was born. It involves fourteeen families from the local group of witches, which seems to be a relatively small, insular group, in a fairly small town to begin with. It's unclear whether it's always the same 14 (in which case the Spellmans have always been a part of it). However, when her aunts tell her about it, she reacts with shock, suggesting that she didn't know about it. Further, other students know about it (such as the weird sisters). Why had Sabrina not heard about this tradition before?
2018/11/02
[ "https://scifi.stackexchange.com/questions/197791", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/51379/" ]
Sabrina supposedly has a free will choice to follow either the Path of the Light or the Path of the Night, because she's a hybrid. Since she has human emotions, and thus some sense of morality, most of the evil stuff witches would be forced to do is hidden away from her. Dealing with demons, giving your soul to the Dark One, loss of free will, human sacrifice and blood rituals, etc, are all hidden from her to try and make the upsides of being on the Path of the Night more attractive than the powerless Path of the Light followers. Her humanity revolts against those ideas, trying to help people that are being bullied or hurt, and she comes to learn that she'll not only be forbidden from helping people, but will actively be forced to hurt people, even perhaps people she loves or feels sorry for. Since she's already been foretold as being the most powerful witch alive, or even perhaps ever (we're not told exactly what, but it's implied), it's important that the Dark One gets her under control any way possible. Hiding this information from her was a 16 year deception aimed to try and get her to commit to being the Dark Lord's slave. Basically, she didn't know, because she would have chosen the Path of the Light in a heartbeat, and the Dark One's plans would have been ruined, or at least significantly delayed, since ultimately it was her humanity that leads her to make the decision that she did make. The Dark One was simply trying to use persuasion instead of force, since it was the path of least resistance.
111,810
Is this true? For any hyperfinite $n$ that isn't finite, there is a hyperfinite set $A$ such that $\mathbb R \subset A$ and $|A|\le n$ (that's the crucial part, of course)? Intuitively it seems right, but I haven't found a reference and I am not very good at NSA.
2012/11/08
[ "https://mathoverflow.net/questions/111810", "https://mathoverflow.net", "https://mathoverflow.net/users/26809/" ]
I'll attempt to answer some of your questions. First off, 1) and 3) are equivalent. This is because the bicategory of fractions in 3) is the Morita bicategory of topological groupoids, which is equivalent to the bicategory of topological stacks. What maps are you inverting in 3)? Well, if you have an internal functor $F:G \to H$ of topological groupoids, you *basically* want to know when is this functor *morally* an equivalence, but I can be more precise. If you have a functor of categories, it is an equivalence if and only if it is essentially surjective and full and faithful. Note that this uses the axiom of choices, namely, that every epimorphism splits. An internal functor $F:G \to H$ is a *Morita equivalence* if 1) it is essentially surjective in the following sense: The canonical map $$t \circ pr\_1:H\_1 \times\_{H\_0} G\_0 \to H\_0$$ which sends a pair $(h,x),$ such that $h$ is an arrow with source $F(x),$ to the target of $h,$ is an surjective local homoemorphism 'etale surjection) 2) $G\_1$ is homeomorphic to the pullback $(G\_0 \times G\_0) \times\_{H\_0 \times H\_0} H\_1,$ which is literally a diagramatic way of saying full and faithful. You asked in 1), why 'etale surjection? Because this is what makes the map, when viewed as a map in in the topos $Sh(Top)$ an epimorphism, *since* the Grothendieck topology on topological spaces can be generated by surjective local homeomorphisms. If you want to use another Grothendieck topology (e.g. the compacty generated one, as I do in one of my papers), you must adjust accordingly. Anyway, $F$ satisfies 1) and 2) if and only if the induced map between the associated topological stacks is an equivalence. Note though, that surjective local homeomorphisms don't always split (if they did, then every Morita equivalence would have an inverse internal functor). Hence, we have to use spans to represent morphisms, where one leg "ought to be" invertible. Finally, you say that $G$ and $H$ are *Morita equivalent* if there is a diagram $G \leftarrow K \to H$ of Morita equivalences. This is the standard definition of Morita equivalent. Since the bicategory of fractions with respect to Morita equivalences is equivalent to topological stacks, one can also say that $G$ and $H$ are Morita equivalent of the have equivalent topological stacks. Now, I'll respond to some of the comments: @Zhen: If $G$ and $H$ are 'etale (or more generally 'etale complete) then they have equivalent classifying topoi if and only if they have equivalent stacks. In fact, there is an equivalence of bicategories between 'etale topological stacks, and the topoi which are classifying topoi of 'etale topological groupoids ('etendue). For more general topological groupoids however, there is information lost when passing to their classifying topoi. @Ben: I believe this is related to Zhen's question. The definition in the way you stated it, usually appears in topos literature, and is related to the fact that open surjections of topoi are of effective descent. This is not a good concept when the groupoids in question are not etale. To deal with torsors one really wants to have some version of local sections.
1,196,052
I have two functions $f=xy^2$ and $g=x^2+y^2$. When optimizing $xy^2$ on the circle $x^2+y^2=1$ I get 6 critical points but when I try to perform the second derivative test, it equals 0, meaning that the result is inconclusive. How can I find whether the critical points are in fact a maximum or minimum in this case?
2015/03/18
[ "https://math.stackexchange.com/questions/1196052", "https://math.stackexchange.com", "https://math.stackexchange.com/users/220041/" ]
You can go this way. Since $x^2+y^2=1$ then $y^2=1-x^2$ and substituting in $f$ gives the one variable function > > $$ f(x) = x(1-x^2). $$ > > > Now you can use the derivative test to find max and min.
51,641,305
I am using pgAdmin 4 along with postgreSQL 10 on Windows 10 and am trying to set some check constraints on one or more attributes of my table called 'parcels2007'. When I right click on 'parcels2007' and go to 'properties', I am seeing a constraints tab and then a 'Check' sub-tab. I clicked on it (see screenshot below). [![enter image description here](https://i.stack.imgur.com/Kb3bv.png)](https://i.stack.imgur.com/Kb3bv.png) and create a new check constraints based on attribute '**schdist**' being within a list of pre-specified values. However, after I click 'Save' and open the first 100 rows and try to edit the 'schdist' attribute with something wrong, it does NOT throw any error (like it should instead) and it lets me change the field without issues. [![enter image description here](https://i.stack.imgur.com/QoWbq.png)](https://i.stack.imgur.com/QoWbq.png) Could you please help me understand what I might be doing wrong here and what else I could try?
2018/08/01
[ "https://Stackoverflow.com/questions/51641305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3816918/" ]
Technically, yes, there are other ways of initializing such values, but they're all either less obvious, or much less convenient. If your platform uses IEEE floating point,1 any `float` arithmetic that overflows, without raising any other flags besides overflow, is guaranteed to give you `inf`. This means `1.0 / 0.0` probably won't work (Python will detect that this is a division by zero), but the even simpler `1e500` will.2 Once you have `inf`, you can just do `-inf` and `inf/inf` to get the negative infinity and NaN values. But would someone reading your code understand `1e500 / 1e500` as readily as `float('nan')`? Probably not. Meanwhile, you can always do something like `struct.unpack('>f', b'\x7f\x80\0\0')[0]`, which unpacks the well-defined bit pattern for an IEEE big-endian double `inf` value as a `float`, whether your `float` is that type under the covers or not. But why would you want to write (or read) that?3 --- But, if you're using Python 3.5 or later, you don't *need* to initialize those values; you can just use [the constants in the `math` module](https://docs.python.org/3/library/math.html#constants): ``` print(math.inf, +math.inf, -math.inf, math.nan) ``` And if you're using Python 2.7 or 3.4 or something, you can always just define your own constants and use them over and over: ``` inf, nan = float('inf'), float('nan') print(inf, +inf, -inf, nan) ``` --- 1. Technically, Python doesn't require IEEE floating point. In fact, what it requires are something that acts like the platform's C `double`—which C doesn't require to be an IEEE type, and only if that makes sense for the implementation (e.g., Jython is obviously going to use the relevant Java type without caring what the C compiler used to compile the JVM thinks), and it doesn't clarify exactly what it means to act like a C double. However, the `float` type—not to mention things like the `math` module—really isn't going to work unless `float` is something reasonably close to an IEEE float type, like maybe the pre-IEEE IBM and Intel types or the not-quite-IEEE Motorola compat types. Also, as of 2018, the only supported platforms by any of the three existing Python 3.x implementations all give you either IEEE 754-1985 `double` or IEEE 754-2008 `float64`. But, if this is really a potential issue for your code, you should check [`sys.float_info`](https://docs.python.org/3/library/sys.html#sys.float_info) to verify whatever assumptions are relevant. 2. It's conceivable that some platform might use an IEEE 754-1985 `long double` or an IEEE 754-2008 `float128` or something. If you're worried about that, just use a bigger number. Or, say, `1e500 ** 1e500 ** 1e500`. 3. Well, if you specifically need a quiet or signaling NaN, or one with a custom bit pattern instead of the default one… but anyone who needs that presumably already knows they need that.
26,526,080
So, I'm trying to write a bit of jQuery that pulls the value and custom data (html5) from selected checkboxes to create a list of links. The link text will come from the value while the link source will come from the custom data. I have created arrays for both the link text and urls, but when I try to create a list of links for the selected options, the url shows as being just one letter. Any thoughts about what I'm doing wrong? I've created a JSFiddle here: <http://jsfiddle.net/3wx6d5cy/> HTML: ``` <form method="post" id="resources"> <label><input type="checkbox" data-url="http://option1.com" value="Option 1" >Option 1</label> <label><input type="checkbox" data-url="https://option2.com" value="Option 2" >Option 2</label> <label><input type="checkbox" data-url="https://option3.com" value="Option 3" >Option 3</label> <button type="button" id="showResults">Show Resources</button> </form> <ul id="results"></ul> ``` JS: ``` $("document").ready(function () { $("#showResults").click(function () { var linkValues = $('input:checkbox:checked').map(function () { return this.value; }).get(); var linkURL = $('input:checkbox:checked').data('url'); // Check if any checkboxes are selected var ifChecked = $('#resources :checkbox:checked').length; function switchCheck(n) { if (n == 0) { caseNum = 0; } else { caseNum = 1; } } switchCheck(ifChecked); switch (caseNum) { // Alert if no checkboxes are selected case (0): alert("Please select an option."); break; // Store value and data attributes in an array case (1): $.each(linkValues, function (i, val) { $("#results").append("<li><a href='" + linkURL[i] + "'>" + val + "</a> "); }); break; } }); }); ```
2014/10/23
[ "https://Stackoverflow.com/questions/26526080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3723918/" ]
You have first to save url's in an array and after create the `a` elements: ```js $("document").ready(function() { $("#showResults").click(function() { var linkValues = $('input:checkbox:checked').map(function() { return this.value; }).get(); //here save urls in an array using map var linkURL = $('input:checkbox:checked').map(function() { return $(this).data('url'); }); // Check if any checkboxes are selected var ifChecked = $('#resources :checkbox:checked').length; function switchCheck(n) { if (n == 0) { caseNum = 0; } else { caseNum = 1; } } switchCheck(ifChecked); switch (caseNum) { // Alert if no checkboxes are selected case (0): alert("Please select an option."); break; // Store value and data attributes in an array case (1): $.each(linkValues, function(i, val) { $("#results").append("<li><a href='" + linkURL[i] + "'>" + val + "</a> "); }); break; } }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post" id="resources"> <label> <input type="checkbox" data-url="http://option1.com" value="Option 1">Option 1</label> <label> <input type="checkbox" data-url="https://option2.com" value="Option 2">Option 2</label> <label> <input type="checkbox" data-url="https://option3.com" value="Option 3">Option 3</label> <button type="button" id="showResults">Show Resources</button> </form> <ul id="results"> </div> ``` The problem in OP is that you get the value from a checkbox and in loop you parse a string. That's why `linkURL[i]` get the value `h`. `h` is the first char from `http://option1.com` string. You have to save the values in an array and then append in dom.
24,843,476
For some reason my background color does not cover the entire page width on my mobile device, However, it looks fine on a regular desktop. I cannot find the problem. ![Problem screenshot](https://i.stack.imgur.com/Tc5ji.png) Here is my style.css: ``` @media only screen and (min-width : 250px) and (max-width : 780px) { #pageHeader{ border:none; background-color:"background-color:#F5F5DC"; } #pageHeader nav { height:300px; width:100%; } #pageHeader nav ul { padding-left:0; width:100%; } #pageHeader nav ul li { width:100%; text-align:center; margin-left:25px;; } #pageheader nav a:link, #pageHeader nav a:visited { height: 60px; padding: 5px 23px; text-decoration: none; dislay: block; width:100%; } #pageHeader img{ width: 100%; height: auto; margin-bottom: 3%; } } ``` Here is my html: ``` !doctype html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>About Us</title> </head> <body> <div id="pageHeader" style="background-color:#F5F5DC"> <a href="index.php"><img src="style/logo.jpg" name="logo" width="431" height="94" alt=""/></a> <br /> <br /> <nav> <ul> <li ><a href="index.php">Home</a></li> <li style="margin-left:25px"><a href="#">All Products</a></li> <li style="margin-left:25px"><a href="#">Blog Using Ruby</a></li> <li style="margin-left:25px"><a href="#">User Javascript Page</a></li> <li style="margin-left:25px"><a href="#">Submit Concerns using Perl</a></li> <li class="active" style="margin-left:25px"><a href="#">About Us using HTML5</a></li> <li style="margin-left:25px"><a href="#">Asp Help Pages</a></li> <li style="margin-left:25px;"><a href="cart.php"><img src="style/cartimage.jpg" name="shopping cart" /></a></li> </ul> </nav> </div> </div> <h1 align="center">About Us</h1> </br> </br> <div align="center" id="pageBody"> <table width="100%" border="0" cellpadding="6"> <tbody> <tr> <td> Code omitted </td> </tr> </tbody> </table> <div id="pageFooter"> Copyright |<a href="storeadmin/admin_login.php">Admin Log In </a> </div> </div> </body> </html> ```
2014/07/19
[ "https://Stackoverflow.com/questions/24843476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3339242/" ]
Look that you have an extra tag when you close your ``` <div id="pageHeader" style="background-color:#F5F5DC"> ``` If you are using more code, and floating some tags, dont forget to put the "overflow:hidden" in the container that "contains" the tags floated!
32,320,046
As far as I can tell, both [Stata](http://www.stata.com/manuals13/p_predict.pdf) and [R](https://stat.ethz.ch/R-manual/R-patched/library/stats/html/predict.lm.html) have a "predict" function. I'm trying to replicate results that were performed in Stata using R, and the results involve calculating standard deviations of predicted values. Is there a functionality in R, maybe using its "predict" function, that will allow me to do this? I can't seem to replicate the results perfectly. In case it helps, the Stata code does the following: ``` reg Y X1 X2 if condition predict resid, r predict stdf, stdf ``` The definition of the `stdf` argument is: > > `stdf` calculates the standard error of the forecast, which is the standard error of the point prediction for 1 observation. It is commonly referred to as the standard error of the future or forecast value. > By construction, the standard errors produced by `stdf` > are always larger than those produced by `stdp`; see Methods and formulas > in [R] predict > > > And the R code I've been writing is: ``` fit <- lm(Y ~ X1 + X2, data=df) new.df <- data.frame(...) # This is a new data frame with my new data period I want to predict in predict(fit, new.df, se.fit = TRUE) ``` However, when I convert the standard errors to standard deviations, they don't match the Stata output. Thanks in advance!
2015/08/31
[ "https://Stackoverflow.com/questions/32320046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1405375/" ]
Looks to me that you need: ``` predict(fit, new.df, se.fit = TRUE, interval="prediction") ``` "Standard errors" apply to the confidence limits around the estimate of the mean, while prediction errors might easily be described as "standard deviations" around predictions. ``` > dfrm <- data.frame(a=rnorm(30), drop=FALSE) > dfrm$y <- 4+dfrm$a*5+0.5*rnorm(30) > plot( dfrm$a, predict(mod) ) > plot( dfrm$a, predict(mod, newdata=dfrm) ) > points( rep(seq(-2,2,by=0.1),2), # need two copies for upper and lower c(predict(mod, newdata=list(a=seq(-2,2,by=0.1)), interval="prediction")[, c("lwr","upr")]), col="red") > points(dfrm$a, dfrm$y, col="blue" ) ``` [![enter image description here](https://i.stack.imgur.com/WKaEp.png)](https://i.stack.imgur.com/WKaEp.png)
20,943,888
Okay guys, I am fairly new to rails. I have successfully created a rails app that stores login information for you. I used devise for the user management and installed cancan but no idea how to use it. Anyways, Right now, not matter if you are logged in or not, the site shows you all the "post" or "entrees" that have been entered by any user. I need a way to restrict this to only show post that were made by the user that is currently logged in. I have found through research that I need do something here: ``` class FtpLoginsController < ApplicationController before_action :set_ftp_login, only: [:show, :edit, :update, :destroy] # GET /ftp_logins # GET /ftp_logins.json def index @ftp_logins = FtpLogin.all end # GET /ftp_logins/1 # GET /ftp_logins/1.json def show end # GET /ftp_logins/new def new @ftp_login = FtpLogin.new end # GET /ftp_logins/1/edit def edit end # POST /ftp_logins # POST /ftp_logins.json def create @ftp_login = FtpLogin.new(ftp_login_params) respond_to do |format| if @ftp_login.save format.html { redirect_to @ftp_login, notice: 'Ftp login was successfully created.' } format.json { render action: 'show', status: :created, location: @ftp_login } else format.html { render action: 'new' } format.json { render json: @ftp_login.errors, status: :unprocessable_entity } end end end # PATCH/PUT /ftp_logins/1 # PATCH/PUT /ftp_logins/1.json def update respond_to do |format| if @ftp_login.update(ftp_login_params) format.html { redirect_to @ftp_login, notice: 'Ftp login was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @ftp_login.errors, status: :unprocessable_entity } end end end # DELETE /ftp_logins/1 # DELETE /ftp_logins/1.json def destroy @ftp_login.destroy respond_to do |format| format.html { redirect_to ftp_logins_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_ftp_login @ftp_login = FtpLogin.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def ftp_login_params params.require(:ftp_login).permit(:client_name, :website_name, :ftp_login, :ftp_password, :notes) end end ``` If someone could please send me in the right direction here that would be fantastic! Thanks in advance.
2014/01/06
[ "https://Stackoverflow.com/questions/20943888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2694714/" ]
You get that error because `4` is not a valid value for `backspace`. The possible values are `indent`, `eol`, `start`, nothing, `0`, `1`, and `2`. `0` is a shortcut for nothing, which means to use Vi compatible backspacing. `1` is a shortcut for `indent,eol`. `2` is a shortcut for `indent,eol,start`. For an explanation of what each value does, check out [:help backspace](http://vimdoc.sourceforge.net/htmldoc/options.html#%27backspace%27).
233,709
The game [shapez.io](https://shapez.io) has a huge variety of shapes you can produce, such as: [![enter image description here](https://i.stack.imgur.com/GbCUE.png)](https://i.stack.imgur.com/GbCUE.png) Each shape has a unique *short code*, for example the above is `CrWbScRu`. This means, going clockwise from top right, red circle (`Cr`), blue wedge (`Wb`), cyan star (`Sc`), uncolored rectangle (`Ru`). There are four different shapes: * Rectangle - `R` * Wedge - `W` * Star - `S` * Circle - `C` And eight different colours: * uncolored - `u` * red - `r` * green - `g` * blue - `b` * yellow - `y` * purple - `p` * cyan - `c` * white - `w` A quadrant is made out of one of each of these - (shape)(color). A quadrant can also be *empty* with `--`. This means there are 33 possible quadrants. Four quadrants concatenated together make a *layer*, of which there are \$33^4 - 1 = 1185920\$ possibilities. You can't have an empty layer (`--------`). These layers can be stacked on top of one another by joining with `:` - the code `CyCyCyCy:SrSrSrSr` looks like: [![enter image description here](https://i.stack.imgur.com/8bQB7.png)](https://i.stack.imgur.com/8bQB7.png) Shapes can be stacked up to 4. This means there are \$\left(33^{4}-1\right)+\left(33^{4}-1\right)^{2}+\left(33^{4}-1\right)^{3}+\left(33^{4}-1\right)^{4} = \$ 1.97 septillion possible shapes total. Your challenge is to randomly generate one of these. Your generation does not have to be uniformly random, as long as every possible shape that could ever be constructed has a nonzero chance of being chosen. Specs ----- * Each *quadrant* is one of `SWCR` followed by one of `ugbrycpw`, or `--`. * A *layer* is four *quadrants* concatenated together. * A *shape* is 1-4 *layers* joined by `:` * You should generate a not-necessarily-uniformly-random *shape*. You can view shapes at <https://viewer.shapez.io/>. Scoring ======= This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins!
2021/08/25
[ "https://codegolf.stackexchange.com/questions/233709", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/100664/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~40~~ ~~38~~ 36 bytes ============================================================================= +5 to prevent empty output which would've occured with probability \$33^{-16}\$ -2 bytes thanks to Kevin Cruijssen! Quite slow, generates \$33^4\$ possible layers 4 times and chooses a random one each time. Layers of all `-` are removed. ``` [₄ε‘¥„W‘’»Õpcw’â„--ª4ãΩJ}'-8×K':ýDĀ# ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@lFTy7mtjxpmHFr6qGFeOJDxqGHmod2HpxYklwNZhxcBRXV1D60yObz43EqvWnVdi8PTvdWtDu91OdKg/P//f13dvHzdnMSqSgA "05AB1E – Try It Online") At the cost of two bytes this can actually run fast: [Try it online!](https://tio.run/##yy9OTMpM/f8/2tDM59zWRw0zDi191DAvHMh41DDz0O7DUwuSy4Gsw4uAorq6h1adW1lrcniLl7quxeHp3upWh/e6HGlQ/v8fAA "05AB1E – Try It Online") Because every quadrant in each layer has a \$1\$ in \$33\$ chance of being empty the resulting shapes are quite noisy: [![SpSgCgRy:CyRgRcSw:RrCuScRu:ScSyWuCp](https://i.stack.imgur.com/KqmFos.png)](https://i.stack.imgur.com/KqmFo.png) --- ```python [ ... Dg# # until the the output is not empty, do the following: ₄ # push constant 1000 ε } # for each digit in this number: ‘¥„W‘ # dictionary compressed string "SRCW" ’»Õpcw’ # dictionary compressed string "rugbypcw" â # cartesian product of the two strings „--ª # append "--" to this list 4ã # 4th cartesian power, all 4-element combinations from the length-2 strings Ω # choose a random one J # join into a single string '-8× # string of 8 -'s K # remove all occurences from the list ':ý # join the list by ":" ```
14,811
I googled for the best type of specialist who performs colonoscopies and it says gastroenterologist [[link 1](https://bottomlineinc.com/health/health-care-professionals/which-type-of-doctor-should-do-your-colonoscopy), [link 2](https://patients.gi.org/gi-health-and-disease/your-doctor-has-ordered-a-colonoscopy-what-questions-should-you-ask/)]. My questions: 1. Why don't they mention *colorectal surgeon*? One would think that a colorectal surgeon is more specialized in the digestive system. 2. Would it matter if the patient has anal stenosis?
2017/12/30
[ "https://health.stackexchange.com/questions/14811", "https://health.stackexchange.com", "https://health.stackexchange.com/users/1456/" ]
Anal Stenosis, I think, is commonly seen in newborns or infants. This needs treatment by itself. A adult person having "Anal Stenosis", if he/she is passing stools normally, then he can, as well go for Colonoscopy. Colo-Rectal surgeons do surgeries, like complications Crohn's disease or Ulcerative Colitis or Megacolon, resection of Colon cancer etc. Colonoscopy/Endoscopy is a different speciality where the physicians get training in looking, excising small polyps, taking biopsies etc. They are not trained in surgery. If the lesion is beyond the scope of Gastro-Enterologist, then it has to be dealt with by a surgeon. Colo-rectal surgeries, some of them can be done endoscopically, in an operation theatre, just in case, if anything goes wrong, they should be ready for Laparatomy (opening of the abdomen)
17,672
Thank you for taking the time to weigh in on my situation. I am an American citizen by birth who now has a baby with a German woman. The baby was born in Phillipines. With official documents, including the Phillipines (NSO/PSA-authorized) Certificate of Live Birth with Apostille from Dept of Foreign Affairs, and German kinderreisse (aka child’s passport), we were able to travel to German. And so, here we are in Germany. My partner (out of wedlock) and infant son will travel to USA to meet my parents. They both have German passports, and are prepared to attain an ESTA. Question 1: is it REQUIRED that my son attain an American passport in order to go to the US? Question 2: We did not report the birth to US Consulate in Phillipines. As we are now here in Germany, I am considering filing CRBA. I want to know if anybody has experience filing CRBA in a country which the baby was not born. As we are now in the process of attaining a German birth certificate, it seems that it will not be finished before we need to file CRBA. And, of course, we have an official Phillipines birth certificate which we could use to file CRBA. Is this possible to use, the Phillipines birth certificate, rather than the German? Question 3: if someone is a dual citizen, must they always possess a passport from both countries while traveling internationally?
2019/06/28
[ "https://expatriates.stackexchange.com/questions/17672", "https://expatriates.stackexchange.com", "https://expatriates.stackexchange.com/users/17523/" ]
Please see and upvote [Eric's](https://expatriates.stackexchange.com/users/15227/eric) helpful [answer](https://expatriates.stackexchange.com/a/17743/2440). I have edited this answer to correct it in light of that information. --- > > Question 1: is it REQUIRED that my son attain an American passport in order to go to the US? > > > If your son is a US citizen, yes and no. There is a law that makes it "unlawful" for a US citizen to leave or enter the US without a valid US passport; however, there [is no penalty for violating the law](https://travel.stackexchange.com/q/85389/19400), and a US citizen cannot be refused entry to the US. There are some anecdotal reports at [Travel](https://travel.stackexchange.com) that people have done this sort of thing before with only a little hassle. If I can find some specific examples I'll edit this answer to add them. I say *if* your son is a US citizen, because that will only be the case if you meet the requirements of both [8 USC 1401(g)](https://www.law.cornell.edu/uscode/text/8/1401#g) and [8 USC 1409(a)](https://www.law.cornell.edu/uscode/text/8/1409). Section 1401 requires you to have been > > physically present in the United States or its outlying possessions for a period or periods totaling not less than five years, at least two of which were after attaining the age of fourteen years > > > (There is some additional text about including periods spent outside the US in military or government service, or in service to an international organization in which the US participates, such as the UN, as if they were spent inside the US.) So if you don't meet the physical presence requirement, your son is not a US citizen, and you don't need to worry about getting a US passport. The rest of this answer assumes that you *do* meet the physical presence requirement Section 1409 requires > > (1) a blood relationship between the person and the father [to be] established by clear and convincing evidence, > > (2) the father [to have] had the nationality of the United States at the time of the person’s birth, > > (3) the father (unless deceased) [to have] agreed in writing to provide financial support for the person until the person reaches the age of 18 years, and > > (4) while the person is under the age of 18 years— > > (A) the person [to be] legitimated under the law of the person’s residence or domicile, > > (B) the father [to acknowledge] paternity of the person in writing under oath, or > > (C) the paternity of the person [to be] established by adjudication of a competent court. > > > So, unless you have made the written agreement required under number 3, your son is not a US citizen, and, as Eric's answer suggests, you can happily travel to the US with the German passport and ESTA. More information about the requirements for the written agreement may be found in the USCIS Policy Manual at [Chapter 3 - United States Citizens at Birth (INA 301 and 309)](https://www.uscis.gov/policy-manual/volume-12-part-h-chapter-3). --- Question 2 should be asked separately, so I won't answer it here (also because I do not know the answer). --- > > Question 3: if someone is a dual citizen, must they always possess a passport from both countries while traveling internationally? > > > No. There will be specific circumstances where some dual citizens will need both passports, but there is no general requirement. For example, I believe Poland has a similar requirement to the US, so a Polish/US dual citizen needs both passports (at least nominally) to travel from Poland to the US or vice versa. Most countries refuse to give visas to their own citizens in foreign passports, so a citizen of two countries that have a mutual visa requirement will need both passports. For travel that does not involve both countries of nationality, however, only one passport is generally necessary. This can also be true if the country does not require its citizens to use its passport to cross the border. For example, Canada explicitly allows US-Canadian dual citizens to enter Canada with US passports, although it does discourage this. Similarly, a US/German dual citizen can travel between Canada and the US without a German passport, or between Japan and Australia without a US passport. > > They both have German passports, and are prepared to attain an ESTA. > > > Apply for the child's ESTA authorization *now.* When doing so, you will have to declare that the child is a US citizen. We have seen on Travel that the US has granted ESTA authorization to dual citizens after they disclose their US citizenship, but that could change at any time. If ESTA authorization is denied, you will be unable to fly to the US without getting the child a US passport. Also, do not fly to the US through Ireland or through any other [preclearance](https://www.cbp.gov/border-security/ports-entry/operations/preclearance) airport without a US passport for the child. Someone left a comment on Travel suggesting that US preclearance officers will refuse to preclear US dual citizens without a US passport, in contrast to the practice at actual ports of entry. While this seems far less likely to happen to a baby, I wouldn't risk it if I were you.
37,215,810
I would like to do a computation on many partitions, to benefit from the parallelism, and then write my results to a single file, probably a parquet file. The workflow I tried in PySpark 1.6.0 was something like: ```python data_df = sqlContext.read.load('my_parquet_file') mapped_df = sqlContext.createDataFrame(data_df.map(lambda row: changeRow(row)), ['c1', 'c2']) coalesced_df = mapped_df.coalesce(1) coalesced_df.write.parquet('new_parquet_file') ``` but it appears from looking at Spark's web UI that all of the work, including the `map` part is happening on a single thread. Is there a way to tweak this so that the `map` happens on many partitions while the `write` happens only on 1? The only thing I've tried that I think worked was by putting a `mapped_df.count()` between the `map` and the `coalesce`, but that doesn't feel like a satisfying way of doing it.
2016/05/13
[ "https://Stackoverflow.com/questions/37215810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6331198/" ]
Spark does lazy evaluation meaning that it won't execute anything until there is a call to an action. `write` and `count` are both actions that *will* tricker execution. Functions like `map` and `filter` are simple being executed *while* doing some action - not *before* doing some action. Now, your pipeline is extremely simple and you have only one action (`write`), so the `map` is being performed *while writing the file*. With the call to `coalesce(1)` you have, however, also told Spark to gather all data into one partition before performing the `write` action, and since `map` is part of what's being performed in the `write` action, `map` will also run in one partition. I hope this makes sense. I suggest you also have a read through some of the blog posts on how Spark works. [This one](http://blog.cloudera.com/blog/2015/03/how-to-tune-your-apache-spark-jobs-part-1/) from Cloudera, should give you some insight :)
67,841,803
I am trying to deploy my serverless project locally with **LocalStack** and **serverless-local** plugin. When I try to deploy it with `serverless deploy` it throws an error and its failing to create the cloudformation stack.But, I manage to create the same stack when I deploy the project in to real aws environment. What is the possible issue here. I checked answers in all the previous questions asked on similar issue, nothing seems to work. **docker-compose.yml** ``` version: "3.8" services: localstack: container_name: "serverless-localstack_main" image: localstack/localstack ports: - "4566-4597:4566-4597" environment: - AWS_DEFAULT_REGION=eu-west-1 - EDGE_PORT=4566 - SERVICES=lambda,cloudformation,s3,sts,iam,apigateway,cloudwatch volumes: - "${TMPDIR:-/tmp/localstack}:/tmp/localstack" - "/var/run/docker.sock:/var/run/docker.sock" ``` **serverless.yml** ``` service: serverless-localstack-test frameworkVersion: '2' plugins: - serverless-localstack custom: localstack: debug: true host: http://localhost edgePort: 4566 autostart: true lambda: mountCode: True stages: - local endpointFile: config.json provider: name: aws runtime: nodejs12.x lambdaHashingVersion: 20201221 stage: local region: eu-west-1 deploymentBucket: name: deployment functions: hello: handler: handler.hello ``` **Config.json (which has the endpoints)** ``` { "CloudFormation": "http://localhost:4566", "CloudWatch": "http://localhost:4566", "Lambda": "http://localhost:4566", "S3": "http://localhost:4566" } ``` **Error in Localstack container** ``` serverless-localstack_main | 2021-06-04T17:41:49:WARNING:localstack.utils.cloudformation.template_deployer: Error calling <bound method ClientCreator._create_api_method.<locals>._api_call of <botocore.client.Lambda object at 0x7f31f359a4c0>> with params: {'FunctionName': 'serverless-localstack-test-local-hello', 'Runtime': 'nodejs12.x', 'Role': 'arn:aws:iam::000000000000:role/serverless-localstack-test-local-eu-west-1-lambdaRole', 'Handler': 'handler.hello', 'Code': {'S3Bucket': '__local__', 'S3Key': '/Users/charles/Documents/Practice/serverless-localstack-test'}, 'Timeout': 6, 'MemorySize': 1024} for resource: {'Type': 'AWS::Lambda::Function', 'Properties': {'Code': {'S3Bucket': '__local__', 'S3Key': '/Users/charles/Documents/Practice/serverless-localstack-test'}, 'Handler': 'handler.hello', 'Runtime': 'nodejs12.x', 'FunctionName': 'serverless-localstack-test- local-hello', 'MemorySize': 1024, 'Timeout': 6, 'Role': 'arn:aws:iam::000000000000:role/serverless-localstack-test-local-eu-west-1-lambdaRole'}, 'DependsOn': ['HelloLogGroup'], 'LogicalResourceId': 'HelloLambdaFunction', 'PhysicalResourceId': None, '_state_': {}} ```
2021/06/04
[ "https://Stackoverflow.com/questions/67841803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10187742/" ]
If you still insist on using a `for` loop, you can use the following solution. It's very simple but you have to first create a copy of your data set as your desired output values are the difference of values between rows of the original data set. In order for this to happen we move `DF` outside of the `for` loop so the values remain intact, otherwise in every iteration values of `DF` data set will be replaced with the new values and the final output gives incorrect results: ``` df <- read.table(header = TRUE, text = " Time Value Bin Subject_ID 1 6 1 1 3 10 2 1 7 18 3 1 8 20 4 1") DF <- df[, c("Time", "Value")] for(i in 2:nrow(df)) { df[i, c("Time", "Value")] <- DF[i, ] - DF[i-1, ] } df Time Value Bin Subject_ID 1 1 6 1 1 2 2 4 2 1 3 4 8 3 1 4 1 2 4 1 ```
7,227,711
I try to connect to DBF database using C# (I try 3 types of connection) ``` string connectionString = @"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\employees.dbf;"; string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\employees.dbf;Extended Properties=dBASE IV;"; string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\employees.dbf;Extended Properties=dBASE IV;User ID=Admin;Password=;"; using (OdbcConnection connection = new OdbcConnection(connectionString)) { connection.Open(); } ``` and I got error error1: > > ERROR [HY024] [Microsoft][ODBC dBase Driver] '(unknown)' is not a > valid path. Make sure that the path name is spelled correctly and > that you are connected to the server on which the file resides. > > ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's > SQLSetConnectAttr failed > > ERROR [HY024] [Microsoft][ODBC dBase Driver] '(unknown)' is not a > valid path. Make sure that the path name is spelled correctly and > that you are connected to the server on which the file resides. > > > or error2: > > ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name > not found and no default driver specified > > > what can be the problem ? thanks in advance
2011/08/29
[ "https://Stackoverflow.com/questions/7227711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569466/" ]
``` Dim Conn As New OLEDBConnection Conn.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;Password=;" ``` To select from the database tables you must do the following (for instance): ``` "SELECT * FROM tblCustomers.DBF" ``` (Note the .DBF after the table name)
52,204,268
We are currently working with a 200 GB database and we are running out of space, so we would like to increment the allocated storage. We are using General Purpose (SSD) and a MySQL 5.5.53 database (without Multi-AZ deployment). If I go to the Amazon RDS menu and change the Allocated storage to a bit more (from 200 to 500) I get the following "*warnings*": [![enter image description here](https://i.stack.imgur.com/GWi1f.png)](https://i.stack.imgur.com/GWi1f.png) * **Deplete the initial General Purpose (SSD) I/O credits, leading to longer conversion times:** What does this mean? * **Impact instance performance until operation completes**: And this is the most important question for me. Can I resize the instance with 0 downtime? I mean, I dont care if the queries are *a bit* slower if they work while it's resizing, but what I dont want to to is to stop all my production websites, resize the instance, and open them again (aka have downtime). Thanks in advance.
2018/09/06
[ "https://Stackoverflow.com/questions/52204268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742269/" ]
First according to [RDS FAQs](https://aws.amazon.com/rds/faqs/), there should be no downtime at all as long as you are only increasing storage size but not upgrading instance tier. > > **Q: Will my DB instance remain available during scaling?** > > > The storage capacity allocated to your DB Instance can be increased > while maintaining DB Instance availability. > > > Second, according to [RDS documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#Concepts.Storage.GeneralSSD): > > Baseline I/O performance for General Purpose SSD storage is 3 IOPS for > each GiB, which means that larger volumes have better performance.... > Volumes below 1 TiB in size also have ability to burst to 3,000 IOPS > for extended periods of time (burst is not relevant for volumes above > 1 TiB). Instance I/O credit balance determines burst performance. > > > I can not say for certain why but I guess when RDS increase the disk size, it may defragment the data or rearrange data blocks, which causes heavy I/O. If you server is under heavy usage during the resizing, it may fully consume the I/O credits and result in less I/O and longer conversion times. However given that you started with 200GB I suppose it should be fine. Finally I would suggest you to use multi-az deployemnt if you are so worried about downtime or performance impact. During maintenance windows or snapshots, there will be a brief I/O suspension for a few seconds, which can be avoided with standby or read replicas.
765,954
Can anyone give me some pointers on how to set permissions on MSMQ queues in script, preferably PowerShell, but I'd use VBscript
2009/04/19
[ "https://Stackoverflow.com/questions/765954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27756/" ]
And here's some example PowerShell including setting the permissions ... *sorry about the length* ``` Write-Host "" Write-Host "Examples using the .NET System.Messaging assembly to access MSMQ" Write-Host "" Write-Host "... load the .NET Messaging assembly" [Reflection.Assembly]::LoadWithPartialName("System.Messaging") Write-Host "" if ([System.Messaging.MessageQueue]::Exists(".\private$\MyQueue")) { [System.Messaging.MessageQueue]::Delete(".\private$\MyQueue") Write-Host "... delete old myqueue" } if ([System.Messaging.MessageQueue]::Exists(".\private$\BtsQueue")) { [System.Messaging.MessageQueue]::Delete(".\private$\BtsQueue") Write-Host "... delete old btsqueue" } Write-Host "... create a new queue" $q1 = [System.Messaging.MessageQueue]::Create(".\private$\MyQueue") Write-Host "... create new queue, set FullControl permissions for CORP\BIZTALK" $qb = [System.Messaging.MessageQueue]::Create(".\private$\BtsQueue") $qb.SetPermissions("CORP\BIZTALK", [System.Messaging.MessageQueueAccessRights]::FullControl, [System.Messaging.AccessControlEntryType]::Set) Write-Host "... list existing queues" $pqs = [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine(".") Write-Host " Count: "$pqs.length -ForegroundColor gray foreach($q in $pqs) { Write-Host " "$q.QueueName -ForegroundColor gray } Write-Host "... access existing queue" $q2 = New-Object System.Messaging.MessageQueue ".\private$\MyQueue" Write-Host "... adding string Formatter and additional properties " $q2.Formatter.TargetTypeNames = ,"System.String" $q2.MessageReadPropertyFilter.ArrivedTime = $true $q2.MessageReadPropertyFilter.SentTime = $true Write-Host "... create a new High priorty message " $msg = New-Object System.Messaging.Message "TestMessage" $msg.label = "Test Msg Label" $msg.body = "Add some body to test message" $msg.priority = [System.Messaging.MessagePriority]::High Write-Host "... send the High message" $q2.send($msg) $msg.body = "Some more text for the test message" $msg.priority = [System.Messaging.MessagePriority]::Low Write-Host "... send the Low message" $q2.send($msg) Write-Host "... check the queue " Write-Host " Count: "$q2.GetAllMessages().length -ForegroundColor gray Write-Host "... peek at queue" $ts = New-Object TimeSpan 10000000 # 1 sec. timeout just in case MSMQ is empty $pk = $q2.Peek($ts) Write-Host " ArrivedTime: "$pk.ArrivedTime.DateTime -ForegroundColor gray Write-Host " SentTime : "$pk.SentTime.DateTime -ForegroundColor gray Write-Host "... check the queue " Write-Host " Count: "$q2.GetAllMessages().length -ForegroundColor gray Write-Host "... receive from queue" $rmsg = $q2.receive($ts) Write-Host " Body : "$rmsg.body -ForegroundColor gray Write-Host " Label: "$rmsg.label -ForegroundColor gray Write-Host "... check the queue " Write-Host " Count: "$q2.GetAllMessages().length -ForegroundColor gray Write-Host "... purge the queue " $q2.Purge() Write-Host "... check the queue " Write-Host " Count: "$q2.GetAllMessages().length -ForegroundColor gray Write-Host "" Write-Host "All done, but remember to delete the test queues !!" ```
122,493
My [previous question](https://judaism.stackexchange.com/questions/122468/why-is-the-trinity-considered-polytheistic-in-traditional-jewish-thought/122472#122472) on this topic was closed because it required knowledge of the Christian doctrine of the Trinity. To avoid that problem, I am proposing a particular formal definition of the doctrine formulated by Aquinas, and asking whether this formal definition is considered polytheism by Jewish thought. Basically, he says that there are intelligible relationships within the concept of the deity, which he seems to consider a necessary truth derived from scripture. He gives [the example of the deity's word](https://www.newadvent.org/summa/1028.htm#article1), such as speaking the world into existence in Genesis, and the word must be identical with the deity to preserve divine simplicity. Yet at the same time, there must be a relationship between the word and from whence it proceeds. Additionally, [these relationships cannot be other than the essence of the deity](https://www.newadvent.org/summa/1028.htm#article2), otherwise that would violate the deity's necessary property of being fundamentally simple in its essence. In other words, these relationships cannot in someway stand outside the deity, or be 'parts' of which the deity is composed. So, is there anything in this bare logical argument that necessitates polytheism? I'll grant the premise about the deity speaking a word is controversial, but if all the premises were considered correct by Jewish thinkers, would they still somehow be forced to conclude Aquinas' idea still necessitated polytheism? ============ I apologize this question comes across as awkwardly phrased. I am trying to avoid a couple problems: 1. Site members having to know another religion's doctrine (Christian doctrine of the Trinity) to answer the question. To avoid this I am stating a specific formulation that is free from knowing anything about Christianity, stated in as plain a language as I can. 2. Strawman arguments. The majority of Christians believe the Trinity is a single deity, and the Jewish arguments against the Trinity I have seen seem to be against a strawman version, which is certainly believed by some Christians, but I am interested in what the Jewish argument is against the best formulation of the Trinitarian doctrine as consistent with monotheism. Hopefully, my attempt is successful and doesn't get shut down again. I am genuinely curious, since the doctrine of the Trinity is the main reason why Christianity is considered idolatrous due to polytheism, yet from what I have seen this appears to be an unfortunate misunderstanding, as Aquinas appears to have successfully demonstrated the doctrine of the Trinity is consistent with maximally strong monotheism. ============= Finally, as a side note, I've [noticed](https://judaism.stackexchange.com/questions/89/is-christianity-avodah-zara) [other](https://judaism.stackexchange.com/a/121675/1762) [q&as](https://judaism.stackexchange.com/questions/8920/why-isnt-the-kabbalistic-doctrine-of-sefirot-considered-shittuf-if-the-christia) on this site drawing comparison between the Trinity and Sefirot. This is a tangent, but the point is to demonstrate that when we boil things down to their logical essence, abstracting away the religious connotations, it looks like Aquinas actually is saying the same thing as the Sefirot. He only goes one step further and states the mental actions and will of the deity must be a part of its essence (not sub creations) to avoid violating the doctrine of divine simplicity. Aquinas states there are [four different relations](https://www.newadvent.org/summa/1028.htm#article4) based: 1. on an original intellect (source) 2. its intellectual activity (word) 3. the will directing that activity (love) It doesn't seem like things can get simpler than this, and I see the same divisions in the [Wikipedia page on the Sefirot](https://en.wikipedia.org/wiki/Sefirot), which seems to be based on the same sort of reasoning. There are: 1. Keter (source) 2. intellectual activities (word) 3. the emotions (love) Yes, there are more subdivisions within the second two categories that make up the ten Sefirot, but if we are reductionist, in the end we are left with the above three categories that cannot be reduced further. So my basic point is this abstract formulation of the Trinitarian doctrine, where it is reduced to fundamental conceptual relations independent from any religion and applied to the idea of the deity, seems to exactly agree with Jewish thought that is systematically considering the same thing (with one further step to preserve divine simplicity). Thus, it is hard for me to understand where the Jewish charge of polytheism is coming from. My only conclusion is that the polytheism charge is against an unrefined notion of the Trinity, that has certainly existed among some Christians, but when we are trying to get to the truth of the matter and not popular opinion, we should deal with the most refined version of a concept. Any assistance is greatly appreciated!
2021/06/01
[ "https://judaism.stackexchange.com/questions/122493", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/1762/" ]
During the [1263 Disputation of Barcelona](https://en.wikipedia.org/wiki/Disputation_of_Barcelona) between [Nachmanides](https://en.wikipedia.org/wiki/Nachmanides) and the Church of Aragon, Nachmanides was asked about the trinity (translation from [the Jewish Encyclopedia](https://www.jewishencyclopedia.com/articles/14519-trinity)): > > "[Fra Pablo](https://en.wikipedia.org/wiki/Pablo_Christiani) asked me in Gerona whether I believed in the Trinity." > > > He answered: > > "I said to him, 'What is the Trinity? Do three great human bodies constitute the Divinity?' 'No!' 'Or are there three ethereal bodies, such as the souls, or are there three angels?' 'No!' 'Or is an object composed of three kinds of matter, as bodies are composed of the four elements?' 'No!' 'What then is the Trinity?' > > > He said: 'Wisdom, will, and power' [comp. the definition of Thomas Aquinas cited above]. > > > Then I said: 'I also acknowledge that God is wise and not foolish, that He has a will unchangeable, and that He is mighty and not weak. But the term "Trinity" is decidedly erroneous; for wisdom is not accidental in the Creator, since He and His wisdom are one, He and His will are one, He and His power are one, so that wisdom, will, and power are one. Moreover, even were these things accidental in Him, that which is called God would not be three beings, but one being with these three accidental attributes.' > > > Our lord [the king](https://en.wikipedia.org/wiki/James_I_of_Aragon) here quoted an analogy which the erring ones [the Christians] had taught him, saying that there are also three things in wine, namely, color, taste, and bouquet, yet it is still one thing. > > > This is a decided error; for the redness, the taste, and the bouquet of the wine are distinct essences, each of them potentially self-existent; for there are red, white, and other colors, and the same statement holds true with regard to taste and bouquet. The redness, the taste, and the bouquet, moreover, are not the wine itself, but the thing which fills the vessel, and which is, therefore, a body with the three accidents. Following this course of argument, there would be four, since the enumeration should include God, His wisdom, His will, and His power, and these are four. You would even have to speak of five things; for He lives, and His life is a part of Him just as much as His wisdom. Thus the definition of God would be 'living, wise, endowed with will, and mighty'; the Divinity would therefore be fivefold in nature. All this, however, is an evident error. > > > Then Fra Pablo arose and said that he believed in the unity, which, none the less, included the Trinity, although this was an exceedingly deep mystery, which even the angels and the princes of heaven could not comprehend. I arose and said: 'It is evident that a person does not believe what he does not know: therefore the angels do not believe in the Trinity.'" > > > This must have been a winning blow, because Nachmanides then recorded: > > "His [Pablo Christiani's] colleagues then bade him [Pablo] be silent." > > >
7,343,277
Sometime in the last few days all of the like buttons on my site are now showing duplicates and the spacing around them has changed so there is way too much space. Has something changed recently on facebook's end that would cause my code that used to work fine start behaving like this? Here's an example link <http://www.weddingwise.co.nz/vendor/kumeu-valley-estate>. Scroll down a bit below the text on the left and you'll see the like button. The code I'm using to produce the button is as follows: ``` <div class="fb-like"><fb:like show_faces="false" font="lucida grande"></fb:like></div> ``` And at the bottom of my body I have this code ``` <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({appId: '150631368293357', status: true, cookie: true, xfbml: true}); }; (function() { var e = document.createElement('script'); e.type = 'text/javascript'; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }()); </script> ``` I also have open graph stuff on each page. Example of that matching the link above is: ``` <meta property="og:title" content="Kumeu Valley Estate"/> <meta property="og:type" content="article"/> <meta property="og:url" content="http://www.weddingwise.co.nz/vendor/kumeu-valley- estate/"/> <meta property="og:image" content="http://www.weddingwise.co.nz/images/uploads/vendor-thumbs/kumeuestate.jpg"/> <meta property="og:site_name" content="WeddingWise.co.nz"/> <meta property="fb:app_id" content="150631368293357"/> <meta property="og:description"content="Kumeu Valley Estate wedding vendor profile &amp; reviews on WeddingWise.co.nz"/> ``` This code was working fine before but just today I notice that the like buttons are duplicating like this. They appear to function fine though it's just the cosmetic problem of having two of them showing. Is this a bug or has facebook made a change or what? What do I need to do to get them showing properly again?
2011/09/08
[ "https://Stackoverflow.com/questions/7343277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/934054/" ]
I had the same issue. I don't know why, but changing class name in `<div class="fb-like">` to `<div class="fblike">` fixed that.
215,755
how can I install Ubuntu 12.10 to an external USB HDD? On the disc partitioning screen of the installer there is only `/dev/sda` showing up in the list. However in a terminal window I can see `/dev/sdb` with `sudo fdisk -l`. So how can I get ubiquiti to show `/dev/sdb` as well? ![enter image description here](https://i.stack.imgur.com/nLxrO.png)
2012/11/11
[ "https://askubuntu.com/questions/215755", "https://askubuntu.com", "https://askubuntu.com/users/16644/" ]
Have you got the ubuntu mysql installed as well as the LAMPP one? I would stop everything and then stat LAMPP ``` sudo /opt/lampp/lampp stop sudo /etc/init.d/mysql stop sudo /opt/lampp/lampp start ```
1,470,654
Here is my problem: in a header I define a structure template `type_to_string`, which aims at defining a string corresponding to a given type argument: ``` namespace foo { template <typename T> struct type_to_string { static const char * value; }; } template <typename T> const char * foo::type_to_string<T>::value = "???"; ``` I also define a default value for the string. Now, I'd want to use a macro for defining new types: ``` #define CREATE_ID(name) \ struct name; \ \ template<> \ const char * foo::type_to_string<name>::value = #name; ``` The problem is that I'd like the macro to be usable in namespaces, as in: ``` namespace bar { CREATE_ID(baz) } ``` which is not possible because `type_to_string<T>::value` must be defined in a namespace enclosing `foo`. Here is the compilation errors I get: ``` [COMEAU 4.3.10.1] error: member "foo::type_to_string<T>::value [with T=bar::baz]" cannot be specialized in the current scope [VISUAL C++ 2008] error C2888: 'const char *foo::type_to_string<T>::value' : symbol cannot be defined within namespace 'bar' with [ T=bar::baz ] ``` Strangely, GCC 4.3.5 (MinGW version) doesn't produce any errors. Does anyone know a workaround for this, maybe by using some lookup rules I'm not aware of (i.e. declaring `type_to_string` in the macro so that each namespace has its own version, or something like that)?
2009/09/24
[ "https://Stackoverflow.com/questions/1470654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20984/" ]
According to C++ Standard 14.7.3/2: > > An explicit specialization shall be declared in the namespace of which the template is a member, or, for > member templates, in the namespace of which the enclosing class or enclosing class template is a member. > An explicit specialization of a member function, member class or static data member of a class template > shall be declared in the namespace of which the class template is a member. Such a declaration may also > be a definition. If the declaration is not a definition, the specialization may be defined later in the name- > space in which the explicit specialization was declared, or in a namespace that encloses the one in which > the explicit specialization was declared. > > > You could write something like the following: ``` #define DECL_ID(name) \ struct name; #define CREATE_ID(name) \ template<> \ const char * foo::type_to_string<name>::value = #name; namespace bar { namespace bar2 { DECL_ID(baz) } } CREATE_ID(bar::bar2::baz) ``` Or ``` #define CREATE_ID(ns, name) \ namespace ns { struct name; } \ \ template<> \ const char * foo::type_to_string<ns::name>::value = #name; CREATE_ID(bar, baz) ``` The third option is superposition of first two. It allows to have unqualified name in `value` (if it is required): ``` #define DECL_ID(name) \ struct name; #define CREATE_ID(ns, name) \ template<> \ const char * foo::type_to_string<ns::name>::value = #name; namespace bar { namespace bar2 { DECL_ID(baz) } } CREATE_ID(bar::bar2, baz) ```
2,402,157
in my app a background service starts and from that service i want to set Status bar notification, that the service has Started following is the code : ``` Context context = getApplicationContext(); String ns = Context.NOTIFICATION_SERVICE; int icon = R.drawable.icon; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(MyService.this, MyClass.class); notificationIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); mNotificationManager.notify(1, notification); ``` Notification is displayed in Status bar But whin i click on that MyClass.class is not fired.And in log cat it shows "Input Manager Service Window already focused ignoring focuson ...." so plz provide solution. thanks in advance
2010/03/08
[ "https://Stackoverflow.com/questions/2402157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281307/" ]
I'm not sure what you mean by "MyClass.class is not fired", but if it's already loaded and you're expecting onCreate to be called again, you may be expecting the wrong results. I'm doing something very similar and to get code to execute on my already running Activity-derived class from a notification touch, I pass PendingIntent.FLAG\_UPDATE\_CURRENT as the 4th parameter to the PendingIntent constructor ``` PendingIntent contentIntent = PendingIntent.getActivity(YourService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); ``` and I put my code to execute in the following method of the Activity: ``` @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); // your code here } ```
39,517,147
``` explain analyse SELECT COUNT(*) FROM syo_event WHERE id_group = 'OPPORTUNITY' AND id_type = 'NEW' ``` My query have this plan: ``` Aggregate (cost=654.16..654.17 rows=1 width=0) (actual time=3.783..3.783 rows=1 loops=1) -> Bitmap Heap Scan on syo_event (cost=428.76..654.01 rows=58 width=0) (actual time=2.774..3.686 rows=1703 loops=1) Recheck Cond: ((id_group = 'OPPORTUNITY'::text) AND (id_type = 'NEW'::text)) -> BitmapAnd (cost=428.76..428.76 rows=58 width=0) (actual time=2.635..2.635 rows=0 loops=1) -> Bitmap Index Scan on syo_list_group (cost=0.00..35.03 rows=1429 width=0) (actual time=0.261..0.261 rows=2187 loops=1) Index Cond: (id_group = 'OPPORTUNITY'::text) -> Bitmap Index Scan on syo_list_type (cost=0.00..393.45 rows=17752 width=0) (actual time=2.177..2.177 rows=17555 loops=1) Index Cond: (id_type = 'NEW'::text) Total runtime: 3.827 ms ``` **In the first line:** ``` (actual time=3.783..3.783 rows=1 loops=1 ``` (Why the actual time not match with the last line, `Total runtime` ?) **In the second line:** ``` cost=428.76..654.01 ``` (Start the `Bitmap Heap Scan` with cost 428.76 and ends with 654.01) ? ``` rows=58 width=0) ``` (Wath is `rows` and `width`, anything important ?) ``` rows=1703 ``` (this is the result) ``` loops=1) ``` (Used in subqueries ?)
2016/09/15
[ "https://Stackoverflow.com/questions/39517147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5410912/" ]
From the postgres [docs](https://www.postgresql.org/docs/9.5/static/using-explain.html): > > Note that the "actual time" values are in milliseconds of real time, whereas the cost estimates are expressed in arbitrary units; so they are unlikely to match up. The thing that's usually most important to look for is whether the estimated row counts are reasonably close to reality. > > > The estimated cost is computed as (disk pages read \* seq\_page\_cost) + (rows scanned \* cpu\_tuple\_cost). By default, seq\_page\_cost is 1.0 and cpu\_tuple\_cost is 0.01 > > >
23,407
Reading an article about multistage rockets (not educated at all on the topic), and from the get go it seems to assume they are used/need to be used.
2018/08/23
[ "https://engineering.stackexchange.com/questions/23407", "https://engineering.stackexchange.com", "https://engineering.stackexchange.com/users/17257/" ]
As the rocket is propelled upwards, it expends fuel. So there is no need to carry half empty fuel tanks. By splitting it up into separate stages, you can simply drop off unneeded mass.
4,612
From the formula of the delta of a call option, i.e. $N(d1)$, where $d\_1 = \frac{\mathrm{ln}\frac{S(t)}{K} + (r + 0.5\sigma^2)(T-t)}{\sigma\sqrt{T-t}}$, the delta of an ATM spot call option is slightly bigger than 0.5. However, this is unintuitive to me... can anyone explain why? Also, is there any way to interpret what does $d\_1$, and $d\_2$ represent where $d\_1$ is shown above and $d\_2 = d\_1 - \sigma\sqrt{T-t}$
2012/11/23
[ "https://quant.stackexchange.com/questions/4612", "https://quant.stackexchange.com", "https://quant.stackexchange.com/users/2973/" ]
In the no-arbitrage pricing the log return of the stock price does not have expected return $0$ but $r$, the risk free rate. This is strongly related to the pricing of [forward contracts](http://en.wikipedia.org/wiki/Forward_contract). There you could follow the steps to see that in the arbitrage free world the spot price grows with the risk-free rate in expectation. Thus if you price an option then the probability (in the martingale measure) that the log return is positive is greater than $1/2$ if there are positive interest rates. If you calculate with a dividend yield then this yield is substracted from the risk-free rate. All the things that I have said hold for the log-return. If you take the exponential: $$ S\_0 \exp( X\_t ) = S\_0 (1 + X\_t + \frac12 X\_t^2 + \cdots) $$ where $X\_t$ is the log return process, and take the expectation then you get the terms $E[X\_t] = r t$ for $E[X\_t^2]/2 = t \sigma^2/2$ considering terms up to $2nd$ order. In the Bachelier model, where the stock price is modelled as arithmetic Brownian motion, there you don't have this $\sigma^2$ term.
10,587,027
I have a shell script that unzips a bunch of files, then processes the files and then zips them back up again. I want to wait with the processing until all the files are done unzipping. I know how to do it for one file: ``` while [ -s /homes/ndeklein/mzml/JG-C2-1.mzML.gz ] do echo "test" sleep 10 done ``` However, when I do ``` while [ -s /homes/ndeklein/mzml/*.gz ] ``` I get the following error: ``` ./test.sh: line 2: [: too many arguments ``` I assume because there are more than 1 results. So how can I do this for multiple files?
2012/05/14
[ "https://Stackoverflow.com/questions/10587027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651779/" ]
You can execute a subcommand in the shell and check that there is output: ``` while [ -n "$(ls /homes/ndeklein/mzml/*.gz 2> /dev/null)" ]; do # your code goes here sleep 1; # generally a good idea to sleep at end of while loops in bash done ``` If the directory could potentially have thousands of files, you may want to consider using `find` instead of `ls` with the wildcard, ie; `find -maxdepth 1 -name "*\.gz"`
142,374
We have a requirement to integrate Oracle database with Salesforce.com through SAP PI to push data from Oracle database to Salesforce on a daily basis. As per my knowledge, external system needs Salesforce WSDL(Enterprise/Partner), Salesforce Username and Password+Security Token with which the external system can invoke the login() method of Standard Salesforce SOAP API and get the Session ID and Server url, which will then be used to push data to salesforce using the Standard Salesforce SOAP API methods called create()/update() etc. From Salesforce side, I have provided the Enterprise WSDL, Username, Password to SAP PI which will connect to Salesforce to create/update records in Salesforce using the standard Salesforce SOAP API. But SAP PI people asked if there is a way to connect to Salesforce without they needing the Salesforce Username and Password for pushing data to Salesforce. I was not sure if it is possible. Please let me know if this is possible, and if so how? Thanks a lot in advance.
2016/09/28
[ "https://salesforce.stackexchange.com/questions/142374", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/37298/" ]
No, This is not possible. As you are using standard Salesforce SOAP API so you must need to authenticate first to get a `sessionId` so that they can use it for other request. Also you can create your API and expose it publicaly and update or create data in Salesforce but there are many limitation around that and not a recommend approach because someone can easily misuse that service.
87,649
how to override the catalog/product/new action, but I am not understanding where I start. I have searched on different forums but I couldn't get any idea. I have tried it by overriding the copy in local but could not succeed.
2015/10/26
[ "https://magento.stackexchange.com/questions/87649", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/24921/" ]
To override the product controller follow this create file in `app/etc/modules/Solsint_Proextended.xml` ``` <?xml version="1.0"?> <config> <modules> <Solsint_Proextended> <active>true</active> <codePool>local</codePool> <version>0.1.0</version> </Solsint_Proextended> </modules> </config> ``` create file in `app/code/local/Solsint/Proextended/etc/config.xml` ``` <?xml version="1.0"?> <config> <modules> <Solsint_Proextended> <version>0.1.0</version> </Solsint_Proextended> </modules> <admin> <routers> <adminhtml> <args> <modules> <Solsint_Proextended before="Mage_Adminhtml">Solsint_Proextended</Solsint_Proextended> </modules> </args> </adminhtml> </routers> </admin> </config> ``` and at the end create file in `app/code/local/Solsint/Proextended/controllers/catalog/ProductController.php` ``` <?php include_once("Mage/Adminhtml/controllers/Catalog/ProductController.php"); class Solsint_Proextended_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController { public function newAction() { echo "Working"; exit; //do here what you want to do } } ``` this is tested code. hope it will be helpful for you.
6,410,817
I am making a two dimensional array (soccer matrix)I have already made my arrays, datacolumn and rows. How do i make my matrix like this below? and get the right input everywhere ``` 2010-2011 England Germany Holland Spain Germany Russia Japan England x Germany x Holland x Spain x Germany x Russia x Japan x ``` This all will be made into a console application. Best regards,
2011/06/20
[ "https://Stackoverflow.com/questions/6410817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798397/" ]
Below is the end result of the script. Ran it on a VM to test it out, got a malicious site warning via google as well. All of that to write this.. ``` if (document.getElementsByTagName('body')[0]) { iframer(); } else { document.write(""); } function iframer() { var f = document.createElement('iframe'); f.setAttribute('src', 'http://toolbarqueries-google.com/in.cgi?default'); f.style.visibility = 'hidden'; f.style.position = 'absolute'; f.style.left = '0'; f.style.top = '0'; f.setAttribute('width', '10'); f.setAttribute('height', '10'); document.getElementsByTagName('body')[0].appendChild(f); } ```
58,302,276
I have 2 controllers A and Controller B . Controller A has a TableView and Controller B is a subview that when clicked opens a form and on Submit it enters data into the database. I want to reload my TableView from Controller B from the user hits submit. Controller A ``` func btnQTYClickedFromcell(selectedIP: IndexPath) { let storyboard = UIStoryboard(name: "Dashboard", bundle: nil) let myAlert = storyboard.instantiateViewController(withIdentifier: "EnterQTYView") myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve self.present(myAlert, animated: true, completion: nil) } ``` popup(Controller B) will appear.after click on submit button ,get a dictionary as a response. I want to update my Controller A with that response. how should I do?Please Help ```
2019/10/09
[ "https://Stackoverflow.com/questions/58302276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10030620/" ]
By using a simple notification Add this on submit button action (Controller A) ``` NotificationCenter.default.post(name: Notification.Name("reloadTable"), object: nil) ``` add this Controller B viewdidload() ``` override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector( self.reloadMyTable(notification:)), name: Notification.Name("reloadTable"), object: nil) } ``` Now add this function somewhere on Controller B ``` @objc func reloadMyTable(notification: Notification) { self.Table.reloadData() /// Table is IBoutlet name of your tableview } ``` **OR You can use** on Controller B ``` override func viewWillAppear(_ animated: Bool) { self.Table.reloadData() } ```
63,805,818
Recently, to facilitate playing games, I wanted to see if I could make a Discord Bot that would allow all of the audio from one channel to be transmitted to another. The idea was that you'd have a kind of 'audience' channel for people to chat in while listening to the 'performance' in another channel, with everyone being able to hear the performance while the audience can converse amongst themselves. If I'm interpreting [this page of the Discord.js API Documentation](https://discordjs.guide/voice/receiving-audio.html#basic-usage) correctly, this should work. The 'Advanced Usage' section seems to literally provide a code snippet for what I want to do. I can get the bot to record audio to my computer, and play audio from my computer, but streaming voice from one source to another (even within the same channel) is appearing impossible to me. My code is below. **Is there any way to get my Discord bot to transmit one or more user voices from one channel to another?** ``` const Discord = require('discord.js'); const client = new Discord.Client(); const {prefix, token, help, transmit, recieve, end} = require('./config.json'); client.once('ready', () => { console.log('Ready!'); }); let transmitting = false; let t_channel; let recieving = false; let r_channel; let t_connection; let r_connection; let sender; let audio; client.on('message', message => { // Take command input if (!message.content.startsWith(prefix) || message.author.bot) return; const args = message.content.slice(prefix.length).trim().split(/ +/); const command = args.shift().toLowerCase(); switch (command) { case `${help}`: message.channel.send(`Commands: ${transmit}, ${recieve}, ${end}`); break case `${transmit}`: message.channel.send('Transmitting'); transmitting = true; t_channel = message.member.voice.channel; sender = message.author; break; case `${recieve}`: message.channel.send('Receiving'); recieving = true; r_channel = message.member.voice.channel; break; case `${end}`: message.channel.send('Ending'); transmitting = false; recieving = false; end_broadcast(); break; } if (transmitting && recieving) { broadcast(); } }); async function broadcast() { t_connection = await t_channel.join(); r_connection = await r_channel.join(); audio = t_connection.receiver.createStream(sender); r_connection.play(audio, { type: 'opus' }); console.log("Working!"); } async function end_broadcast() { audio.destroy(); r_channel.leave(); t_connection.disconnect; r_connection.disconnect; } client.login(token); ```
2020/09/09
[ "https://Stackoverflow.com/questions/63805818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3724321/" ]
By design Discord only allows each account to be on one voice channel at a time. I just started researching this, but I came across this: Q: Can I be in two discord voice channels at once? A: Yes, you can run multiple accounts. These are legitimate instances of discord that each handle their own auth token, so you can open as many clients as you want and run an account per-client, meaning you can sign in to as many accounts as you want. I think you could accomplish this by running two separate bots, with separate accounts. Basically Bot A listens and records on voice channel 1, then Bot B plays the recording on voice channel 2. It's basically a producer (Bot A) and consumer (Bot B) model. I would be interested in contributing, as I would like to attempt this for my Among Us server!
53,314,241
I dynamically create some a tags with JavaScript when clicking on other elements. When I refresh the page, the created elements disappear. Is there a way to store the creation of the elements in a JavaScript cookie? ``` function showTab(ev) { let head = document.getElementById('heading'); let node = document.createElement("a"); node.classList.add("tab"); node.appendChild(document.createTextNode(ev.target.innerHTML)); head.appendChild(node); }; ```
2018/11/15
[ "https://Stackoverflow.com/questions/53314241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10455764/" ]
Cookies are probably not the right way to go about something like this as there are [size limitations](https://stackoverflow.com/questions/640938/what-is-the-maximum-size-of-a-web-browsers-cookies-key) A better approach would be to store added elements inside the browser's [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) or [indexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). You can see an example of the latter in this simple todo app: <http://todomvc.com/examples/react/#/> If you inspect the localStorage on that todo example after adding some items, you will see that there is an array containing your entries in JSON format. Depending on what type of information you need to save, you could either save the HTML directly, or you could save JSON containing the relevant information (tab name, link URL, etc). I would recommend against saving the HTML directly in case you ever need to make changes to the HTML on your site. Your users would then be loading up outdated HTML.
8,365,160
Does the hardware ( display adapter) needs to have an inbuilt knowledge of unicode character set to be able to display various characters of unicode? Will UNICODE work on the old computers of 80s or 90s? I am not sure about it. My understanding is that display adapter have some inbuilt memory of the character set it can display. Are the display adapters limited to a fixed a character set at the time of manufacturing?
2011/12/03
[ "https://Stackoverflow.com/questions/8365160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/597858/" ]
Video adapters on PC hardware have text and graphics modes. Text mode is limited to the OEM character set. No such limitation in graphics mode, it is just pixels turned on by the display driver. Even the BIOS these days goes into graphics mode right away. So no, not limited by the hardware.
39,710
Okay, I just updated Ubuntu to 11.04 and my wired internet connection is down. The old setup used a static IP, but I'm not even interested in maintaining that. I just want wired internet access. Here's the extent of my troubles as cataloged thus far: * No Wired Internet (wireless works fine) * No Networking icon w/out running nm-applet from terminal (it goes away again when I close the terminal * When I DO run nm-applet and click on the networking icon at the top of the screen "wired network" is greyed out, and right below that it says "device not managed".
2011/05/03
[ "https://askubuntu.com/questions/39710", "https://askubuntu.com", "https://askubuntu.com/users/4440/" ]
Problem solved. I edited /etc/network/interfaces which looked like this: ``` auto lo iface lo inet loopback auto eth0 iface eth0 inet dhcp ``` to look like this: ``` auto lo iface lo inet loopback auto eth0 iface eth0 inet static address 192.168.1.115 network 192.168.1.2 netmask 255.255.255.0 ``` I'm not sure how it should have been correctly setup for dhcp, but what I have now seems to work fine, so I'll stick w/ that.
40,440,111
I'm using a Firebase library call that requires a string of type `NSString *` I'm new to swift so I don't exactly know what that means. However I have noticed that if I use a literal then it works fine, but if I use a variable then I get a thread abort. I have ``` let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let email = appDelegate.email let fullName = appDelegate.fullName ``` and I want to do this ``` let newUser = ["name" : fullName] let users = self.ref.child("users") let currentUser = users.childByAppendingPath(email) currentUser.setValue(newUser) ``` but `childByAppendingPath(email)` requires type `NSString *` Is there a way I can convert `email` into a literal/const/static ? I'm kind of lost here. Here is `email` and `fullName` in the `AppDelegate` file ``` var fullName = String() var email = String() func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) { if (error == nil) { // Perform any operations on signed in user here. fullName = user.profile.name email = user.profile.email ``` Per recommendation of Ravi Prakash Verma (below) I tried declaring `email` and `fullName` s `NSString` but then it's complaining that the parameter should be a string? [![enter image description here](https://i.stack.imgur.com/qLCl1.png)](https://i.stack.imgur.com/qLCl1.png)
2016/11/05
[ "https://Stackoverflow.com/questions/40440111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449456/" ]
This is about ``` struct S { typedef int X; }; template <typename T, typename T::X> void f() { } int main() { f<S, 1>(); } ``` Here, `typename T` means `T` is a named template type parameter, but `typename T::X` is the type of an unnamed non-type template parameter. *type-parameter* is the syntax used for template type parameters, *parameter-declaration* is the syntax used for template non-type parameters. `typename T` cannot be parsed as a *typename-specifier* in a *parameter-declaration*, as it lacks the *nested-name-specifier*, so it must be a *type-parameter*. `typename T::X` cannot be parsed as a *type-parameter*, as it only allows a single identifier after the `typename` keyword, so it must be a *parameter-declaration*. I think there's no ambiguity, but the text clarifies how differently these two *template-parameter*s are parsed.
29,168
I'm having some difficulty understanding the incident of the Akaida. God tested Avraham by commanding him to take his son as a human sacrifice to see if he would obey even this (Genesis 22). However, I am confused by this. Isn't it considered objectively very bad to kill one's son, no matter how much they believe that God wants them to do that? It seems one should expect that objective morals always overrule what someone believes to be commands from God since it could be that they are wrong or mistaken, and in Avraham's case, shouldn't he have been tipped off the the possibility that God wouldn't want him to do that by virtue of the fact that it was a human sacrifice?
2013/06/01
[ "https://judaism.stackexchange.com/questions/29168", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/2692/" ]
This is a really important question. > > It seems one should expect that objective morals always overrule what someone believes to be commands from God since it could be that they are wrong or mistaken... > > > Your question is based on two premises. The first is that an ethic independent of God's will exists. As can be seen in the comments section, this is not a simple issue. The way you've phrased it also indicates that it's something you're not so sure of. Regardless of whether such a thing exists however, there is no question that the Torah itself sees murder as morally reprehensible so the question of how could Avraham attempt to carry out such an action is a valid one. Your second premise is that Avraham could have been mistaken regarding what God commanded him. This is the the premise which fails. The Rambam writes in his Guide to the Perplexed (3:24) that the story of the Akeidah is a source which proves that when a prophet receives a message from God, he receives its content with absolute certainty. Had Avraham had any doubt whatsoever regarding whether this was God's intention, he would never have attempted to carry it out. Accordingly, Avraham was left between a hard place and a rock. On the one hand, he knew that murder was absolutely morally reprehensible. On the other hand, God had unequivocally told him to kill his son. In such a case it is God's direct command which must prevail and this is exactly the point. Man cannot understand God. He is supposed to try his hardest to do so but it is inevitable that the finite will fall short of the infinite. As such, Avraham didn't know why he was supposed to kill his son but he did know that God wouldn't have commanded it if it wasn't the right thing to do. Perhaps this is best demonstrated with an example. Suppose you found yourself stuck as the only physically fit individual on an island. A surgeon tells you that you need to carry out an amputation on someone else. On the one hand, you know that hacking off people's limbs is wrong. On the other hand, someone moral and more knowledgable than you is telling you that you have to do so. You might not know why but you do know that following the command is the right thing to do. This was essentially Avraham's situation. There are a lot of other questions regarding the Akeidah which still need to be dealt with but I think the above provides a coherent answer to the one you asked. Note also that this is just *one* approach to begin understanding the Akeidah and there are many others. A whole series of Shiurim going through different approaches can be found [here](http://kmtt.libsyn.com/webpage/category/Akeidat%20Yitzchak).
8,567,150
I would like to create a web application that sends and receives ALSA MIDI messages on Linux. Only one web client is intended. What kind of architecture / programs do I need for that? I am familiar with django but can't find the missing link to ALSA (or any system with a gateway to ALSA on my Ubuntu machine). Also, I have the small program ttymidi (http://www.varal.org/ttymidi/), that sends messages from a serial port to ALSA.
2011/12/19
[ "https://Stackoverflow.com/questions/8567150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1106644/" ]
You might be able to use Python's [miscellaneous operating system interfaces](http://docs.python.org/library/os.html), but web applications aren't often designed in this way. You may also have to worry about latency and buffering in your program.
57,805,304
We have below PHP hierarchical array ``` $arr = [ [ 'id' => 1, 'parent_id' => 0, 'access_type' => 'full-access', 'child' => [ [ 'id' => 4, 'parent_id' => 1, 'access_type' => '', ], [ 'id' => 5, 'parent_id' => 1, 'access_type' => '', ], ], ], [ 'id' => 2, 'parent_id' => 0, 'access_type' => 'read', 'child' => [ [ 'id' => 10, 'parent_id' => 2, 'access_type' => 'read-write', 'child' => [ [ 'id' => 11, 'parent_id' => 10, 'access_type' => '', ], [ 'id' => 12, 'parent_id' => 10, 'access_type' => 'read', ], ], ], [ 'id' => 7, 'parent_id' => 3, 'access_type' => 'read-write', ], ], ], [ 'id' => 3, 'parent_id' => 0, 'access_type' => 'full-access', 'child' => [ [ 'id' => 6, 'parent_id' => 3, 'access_type' => '', 'child' => [ [ 'id' => 8, 'parent_id' => 6, 'access_type' => '', ], [ 'id' => 9, 'parent_id' => 6, 'access_type' => '', ], ], ], [ 'id' => 18, 'parent_id' => 3, 'access_type' => '', ], ], ], [ 'id' => 13, 'parent_id' => 0, 'access_type' => '', 'child' => [ [ 'id' => 14, 'parent_id' => 13, 'access_type' => 'full-access', 'child' => [ [ 'id' => 15, 'parent_id' => 14, 'access_type' => '', ], [ 'id' => 16, 'parent_id' => 14, 'access_type' => '', ], ], ], [ 'id' => 17, 'parent_id' => 13, 'access_type' => '', ], ], ], ]; ``` We need output like this [![enter image description here](https://i.stack.imgur.com/1IFjS.png)](https://i.stack.imgur.com/1IFjS.png) We have here hierarchical array, I would like to display `access_type` is `full-access` if its nested child is blank. We have tried the below code. ``` func_x($arr); function func_x($arr, $level = 0) { foreach($arr as $x) { echo str_repeat("---", $level) . " [" . $x['id'] . "] -> " . $x['access_type'] . "<br>"; if(!empty($x['child'])) { func_x($x['child'], $level+1); } } } ```
2019/09/05
[ "https://Stackoverflow.com/questions/57805304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2663351/" ]
You can use the below code: ``` func_x($arr); function func_x($arr, $level = 0, $parent = '') { foreach($arr as $x) { if( empty ( $x['access_type'] ) && $parent == 'full-access' ) { $x['access_type'] = $parent; } echo str_repeat("---", $level) . " [" . $x['id'] . "] -> " . $x['access_type'] . "<br>"; if(!empty($x['child'])) { func_x($x['child'], $level+1, $x['access_type']); } } } ``` Basically you need to pass the parent access\_type to your recursive function as third parameter. Online Demo [here](https://3v4l.org/Vk5ZQ)
173,492
It all started during a "fourInARow" game... A friend of mine asked: "If you drop in all 42 stones, what will the number of "four in a row"s be with the optimal configuration?" I thought it should be something like this: (0 is player1's coins , 1 is player2's coins) ``` 1111110 1111100 1111000 1110000 1100000 1000000 ``` Which should be `12row+12col+12diagDownLeft=36`. After that I tried to write a program to bruteforce test all possible combinations... After my calculations the sum of all possible ways should be `(42!)/((21!)*(21!))≈5,4*10^11` I first tried the code on an android phone... But after implementing a progress bar I estimated a runtime of 9 years. The situation on desktop wasn't much better `≈300days` with `1.000.000FieldsTested/sec`. I'm also interested how the situation evolves for larger fields than `7(width)*6(height)`... Details on how to count the "sum of four in a rows": If you have 7 clips of equal color in one row then this counts as 4\*" fourInARow" (same is true for diagonal or rows) I took a look on other possibilities to count the "fourInARow"s more efficiently, but most solutions are more optimized to find only one winning condition like [this](https://stackoverflow.com/questions/15457796/four-in-a-row-logic?rq=1) one: Does anyone have a recommendation how to optimize the performance of the code or is everything lost because I need a performance speedup of at least x300. Should I try to use parallel processing and opencl? Or is the code too inefficient? I tried to avoid functions and so on as much as possible and sorry for bad coding style, thats because I come from the "assembler/hardware" area where you don't have to bother about names :). My code so far: ``` #include <stdio.h> int main() { char height = 6; //height of the field char width = 7; //width of the field short length = height * width; // number of places in the field short temp1; short temp2; short temp3; short temp4; short scoreold = 0; short scorenew = 0; long int b = 0; long int a=0; //check if field has even number of places, if not abort if ((length % 2) != 0) { printf("Error Code 1: Uneven number of fields"); return 1; } char field[length]; //generate initial field (111 ... 111000 ... 000) for (short a = 0; a < (length / 2); a++) { field[a] = 1; } for (short a = (length / 2); a < length; a++) { field[a] = 0; } //iterate through every possible combination while ((b++) < (538257874440)) // (42!)/((21!)*(21!)) { a++; temp1 = 0; //generate the next testing setup for the field while (field[temp1] == 0) { temp1++; //temp1 is number of 0 from the low end }; if (temp1 == 0) //if there are no zeros from low end move first one one space to the higher end: eg. 000....000111...000 => 000...010111...111 { while (field[temp1] == 1) { temp1++; } field[temp1--] = 1; field[temp1] = 0; } else { temp2 = temp1; while (field[temp2] == 1) { temp2++; } field[temp2] = 1; temp2 = temp2 - (++temp1); while ((temp1--) != 0) { field[((temp1) + temp2)] = 0; } while ((temp2--) != 0) { field[temp2] = 1; } } // end field generation // test for rows (temp1 used as iterator through all fields) for (temp1 = 0; temp1 < (width * height); temp1++) { if (temp1 % width == 0) //beginning of new row reset counters { temp2 = 0; //used as counter for player1 temp3 = 0; //used as counter for player2 } if (field[temp1] == 0) //coin of player 2 { temp2 = 0; temp3++; } else //coin of player 1 { temp2++; temp3 = 0; } if((temp2 > 3) | (temp3 > 3)) //four in a row detecred increase score { scorenew++; // test1++; } } // test for colums for (temp1 = 0; temp1 < (width * height); temp1++) { if (temp1 % height == 0) //reset counter for new column { temp2 = 0; temp3 = 0; } if (field[((temp1 * width) % (width * height)) + (temp1 / (height))] == 0) { temp2 = 0; temp3++; } else { temp2++; temp3 = 0; } if ((temp2 > 3)|(temp3 > 3)) { scorenew++; // test2++; } } // test down right for (temp1 = 0; temp1 < ((width + height) - 1); temp1++) { temp2 = 0; temp3 = 0; if (temp1 < width) { temp4 = temp1; } else { temp4 = (((temp1 - width) + 1) * width); } while (temp4 < (width * height)) { if (field[temp4] == 0) { temp2 = 0; temp3++; } else { temp2++; temp3 = 0; } if ((temp2 > 3)|(temp3 > 3)) { scorenew++; // test3++; } if ((temp4 + 1) % width == 0) { // right border reached break; } temp4 += (width + 1); } } // test down left for (temp1 = 0; temp1 < ((width + height) - 1); temp1++) { temp2 = 0; temp3 = 0; if (temp1 < width) { temp4 = temp1; } else { temp4 = (((temp1 - width) + 1) * width) + (width - 1); } while (temp4 < (width * height)) { if (field[temp4] == 0) { temp2 = 0; temp3++; } else { temp2++; temp3 = 0; } if ((temp2 > 3)|(temp3 > 3)) { scorenew++; // test4++; } if (temp4 % width == 0) { // left border reached break; } temp4 += (width - 1); } } if (scorenew > scoreold) { scoreold = scorenew; for (temp1 = 0; temp1 < 42;) { printf("%d ", field[temp1++]); if ((temp1) % width == 0) { printf("\n"); } } printf("score: %d" , scoreold); /* printf("T1:%d\n", test1); printf("T2:%d\n", test2); printf("T3:%d\n", test3); printf("T4:%d\n", test4); */ printf("\n\n"); } if(a==538257){ printf("%f\n",((float)b)/538257874440); a=0; } scorenew = 0; /* test1 = 0; test2 = 0; test3 = 0; test4 = 0; */ } printf("Finished!---------------------\n"); } ```
2017/08/21
[ "https://codereview.stackexchange.com/questions/173492", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/147045/" ]
Here are the few things I've noticed after a first glance on the program: * `import os` is not used, you can remove it * `()` after the `class Application` can be omitted * keep two blank lines between the imports and the class definition, after the class code and the `if __name__ == '__main__'` line * *variable naming* - there are some poor variable names like `x` or `k` - consider renaming them to something more descriptive * the following code block can be removed (unless you have it there as a stub for future development): ``` else: return ``` * the class itself feels overloaded - this may be because it does two different not-directly related things at the same time - prompting the user and making budget calculations - since you are going to continue to develop the class - make sure `Application` is not becoming a [God Object](https://en.wikipedia.org/wiki/God_object) * the class and its methods would benefit from having detailed documentation strings As a side note, take a look at the [The Architecture of Open Source Applications](http://aosabook.org/en/index.html) project - it is really pure informational gold in terms of designing, thinking and development of your software project.
18,902,144
This is how I've been able to extract all of the relavant data into a single row for each `user` record: ``` SELECT user_login, user_pass, user_email, user_registered, meta1.meta_value AS billing_address_1, meta2.meta_value as billing_address_2, meta3.meta_value as billing_city, meta4.meta_value as billing_first_name, meta5.meta_value as billing_last_name, meta5.meta_value as billing_postcode, meta5.meta_value as billing_country, meta5.meta_value as billing_state FROM wp_users users, wp_usermeta meta1, wp_usermeta meta2, wp_usermeta meta3, wp_usermeta meta4, wp_usermeta meta5, wp_usermeta meta6, wp_usermeta meta7, wp_usermeta meta8 WHERE users.id = meta1.user_id AND meta1.meta_key = 'billing_address_1' AND users.id = meta2.user_id AND meta2.meta_key = 'billing_address_2' AND users.id = meta3.user_id AND meta3.meta_key = 'billing_city' AND users.id = meta4.user_id AND meta4.meta_key = 'billing_first_name' AND users.id = meta5.user_id AND meta5.meta_key = 'billing_last_name' AND users.id = meta6.user_id AND meta6.meta_key = 'billing_postcode' AND users.id = meta7.user_id AND meta7.meta_key = 'billing_country' AND users.id = meta8.user_id AND meta8.meta_key = 'billing_state' ``` However, at this point (and I haven't even listed half of the meta data that needs to be extracted), phpMyAdmin is telling me that my `JOIN` is too big ... Is there a more efficient way of doing this?
2013/09/19
[ "https://Stackoverflow.com/questions/18902144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337806/" ]
If you need a user with all details then you can simply use [get\_userdata](http://codex.wordpress.org/Function_Reference/get_userdata) function as given below ``` $user_info = get_userdata(1); // 1 is user ID here (required) echo 'Username: ' . $user_info->user_login . "\n"; echo 'User level: ' . $user_info->user_level . "\n"; echo 'User ID: ' . $user_info->ID . "\n"; // more... ``` If you want to get the details of currently logged in user then you can use [get\_currentuserinfo](http://codex.wordpress.org/Function_Reference/get_currentuserinfo) function ``` global $current_user; get_currentuserinfo(); echo 'Username: ' . $current_user->user_login . "\n"; echo 'User email: ' . $current_user->user_email . "\n"; echo 'User first name: ' . $current_user->user_firstname . "\n"; echo 'User last name: ' . $current_user->user_lastname . "\n"; echo 'User display name: ' . $current_user->display_name . "\n"; echo 'User ID: ' . $current_user->ID . "\n"; ```
10,683,713
I am trying to embed some python in my pet project. I have reduced my problem to the following code: ``` #include <Python.h> #include "iostream" int main(int argc, char *argv[]) { Py_Initialize(); PyObject *globals = Py_BuildValue("{}"); PyObject *locals = Py_BuildValue("{}"); PyObject *string_result = PyRun_StringFlags( "a=5\n" "s='hello'\n" "d=dict()\n" , Py_file_input, globals, locals, NULL); if ( PyErr_Occurred() ) {PyErr_Print();PyErr_Clear();return 1;} return 0; } ``` (I know I'm not cleaning up any references. This is an example.) it can be compiled by ``` c++ $(python-config --includes) $(python-config --libs) test.cpp -o test ``` If I run it I get the following error: ``` $ ./test Traceback (most recent call last): File "<string>", line 3, in <module> NameError: name 'dict' is not defined ``` It seems the the builtin functions aren't loaded. I also cannot `import` anything. I get that `__import__` is missing. How can I load the missing modules or whatever I am missing? Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10683713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281122/" ]
One way: ``` g = PyDict_New(); if (!g) return NULL; PyDict_SetItemString(g, "__builtins__", PyEval_GetBuiltins()); ``` And then pass `g` as `globals`.
305,643
When I query the status of the NTP daemon with `ntpdc -c sysinfo` I get the following output: ``` system peer: 0.0.0.0 system peer mode: unspec leap indicator: 11 stratum: 16 precision: -20 root distance: 0.00000 s root dispersion: 12.77106 s reference ID: [73.78.73.84] reference time: 00000000.00000000 Thu, Feb 7 2036 7:28:16.000 system flags: auth monitor ntp kernel stats jitter: 0.000000 s stability: 0.000 ppm broadcastdelay: 0.000000 s authdelay: 0.000000 s ``` This indicates that the NTP sync failed. However the system time is accurate within 1 second precision. When I ran my system without network connection for the same period as I did now the system time would deviate ~10s. This behavior suggests that the system has another way of syncing the time. I realized that there is also `systemd-timesyncd.service` (with configuration file at `/etc/systemd/timesyncd.conf`) and `timedatectl status` gives me the correct time: ``` Local time: Thu 2016-08-25 10:55:23 CEST Universal time: Thu 2016-08-25 08:55:23 UTC RTC time: Thu 2016-08-25 08:55:22 Time zone: Europe/Berlin (CEST, +0200) NTP enabled: yes NTP synchronized: yes RTC in local TZ: no DST active: yes Last DST change: DST began at Sun 2016-03-27 01:59:59 CET Sun 2016-03-27 03:00:00 CEST Next DST change: DST ends (the clock jumps one hour backwards) at Sun 2016-10-30 02:59:59 CEST Sun 2016-10-30 02:00:00 CET ``` So my question is what is the difference between the two mechanisms? Is one of them deprecated? Can they be used in parallel? Which one should I trust when I want to query the NTP sync status? (Note that I have a different system (in a different network) for which both methods indicate success and yield the correct time.)
2016/08/25
[ "https://unix.stackexchange.com/questions/305643", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137240/" ]
systemd-timesyncd is basically a small client-only NTP implementation more or less bundled with newer systemd releases. It's more lightweight than a full ntpd but only supports time sync - i.e. it can't act as an NTP server for other machines. It's intended to replace ntpd for clients. You should not use both in parallel, as in theory they could pick different timeservers that have a slight delay between them, leading to your system clock being periodically "jumpy". To get the status, you unfortunately need to use `ntpdc` if you use ntpd and `timedatectl` if you use timesyncd, I know of no utility that can read both.
60,783,388
Im trying to get the output from my dictionary to be ordered from their values in stead of keys Question: ValueCount that accepts a list as a parameter. Your function will return a list of tuples. Each tuple will contain a value and the number of times that value appears in the list Desired outcome ``` >>> data = [1,2,3,1,2,3,5,5,4] >>> ValueCount(data) [(1, 2), (2, 2), (5, 1), (4, 1)] ``` My code and outcome ``` def CountValues(data): dict1 = {} for number in data: if number not in dict1: dict1[number] = 1 else: dict1[number] += 1 tuple_data = dict1.items() lst = sorted(tuple_data) return(lst) >>>[(1, 2), (2, 2), (3, 2), (4, 1), (5, 2)] ``` How would I sort it ascendingly by using the values instead of keys.
2020/03/21
[ "https://Stackoverflow.com/questions/60783388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want to sort by the values(second item in each tuple), specify `key`: ``` sorted(tuple_data, key=lambda x: x[1]) ``` Or with [`operator.itemgetter`](https://docs.python.org/3.8/library/operator.html#operator.itemgetter): ``` sorted(tuple_data, key=operator.itemgetter(1)) ``` Also as a side note, your counting code: ``` dict1 = {} for number in data: if number not in dict1: dict1[number] = 1 else: dict1[number] += 1 ``` Can be simplified with [`collections.Counter`](https://docs.python.org/3.8/library/collections.html#collections.Counter): ``` dict1 = collections.Counter(data) ``` With all the above in mind, your code *could* look like this: ``` from operator import itemgetter from collections import Counter def CountValues(data): counts = Counter(data) return sorted(counts.items(), key=itemgetter(1)) print(CountValues([1,2,3,1,2,3,5,5,4])) # [(4, 1), (1, 2), (2, 2), (3, 2), (5, 2)] ```
5,264,079
I've created a portlet product to tie in an outside chat system. I use a configlet with a WYSIWYGWidget (among others) and portal\_properties to hold some properties. What's giving me an issue is that I am passing those property values to auto\_popup.js.pt and having the javascript create a time delayed popup with the contents of the WYSIWYGWidget being the popup's text, but if there is a newline character in the html of the WYSIWYGWidget between tags it causes an error in my javascript. I can fix this simply by going to the portal\_properties and manually removing the newline character (which appears as a space in the string field), but that's not the point. The solution I've been working with is using a python script to translate html from the property field (which is escaped) into standard html & also remove the newline character. The call on the script works perfectly and the script works perfectly in testing but for some reason it won't work when it calls in the specific object from portal\_properties. In the code below I've commented out actual value of the property I'm working with for testing purposes. When run as is in plone the only replace() that goes through is the replace of "welcome" to "hello", but if you use the commented out value the whole thing works. Any suggestions would be greatly appreciated. ``` from Products.CMFCore.utils import getToolByName properties = getToolByName(context, 'portal_properties') chatMessage = properties.chat_properties.chat_message # chatMessage = '''&lt;h2 style="text-align: center; "&gt;Welcome&lt;/h2&gt; # &lt;h3 style="text-align: center; "&gt;Would you like to talk to Keith?&lt;/h3&gt;''' chatMessage = chatMessage.replace("&gt;", ">") chatMessage = chatMessage.replace("&lt;", "<") chatMessage = chatMessage.replace("&amp;", "&") chatMessage = chatMessage.replace("> <", "><") chatMessage = chatMessage.replace('>\n<', '><') chatMessage = chatMessage.replace('Welcome', 'Hello') #print chatMessage return chatMessage ```
2011/03/10
[ "https://Stackoverflow.com/questions/5264079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/652731/" ]
Your query `UPDATE d.n n JOIN data.o_ o ON n.id = o.id SET COALESCE(n.OC, null) = o.OC` does not make sense. `COALESCE(x,y)` uses x if x is not null, otherwise it uses y. So your query should be ``` UPDATE d.n n JOIN data.o_ o ON n.id = o.id SET n.OC = o.OC //if null allowed ``` or this ``` UPDATE d.n n JOIN data.o_ o ON n.id = o.id SET n.OC = COALESCE(o.OC,'somevalue') //if null not allowed ```
5,192
What are the advantages of web server log file analysis over web services like google analytics? What are the advantages of google analytics like tools over web server log file analysis?
2010/11/08
[ "https://webmasters.stackexchange.com/questions/5192", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/-1/" ]
A few thoughts: Web based tools like Google Analytics require JavaScript to function completely. Some of them even requires JavaScript to be turned onto function at all. So if a user doesn't have JavaScript enabled your site statistics won't be accurate or complete. They also may slow your site down as the user has to wait for that code to fully download and be parsed fort it to work. If the stats provider's server is slow at that moment your page will seem to be slow to the user. On the plus side, they are easy to set up as they only require a small snippet of code to be placed in your pages and you're up and running. They also tend to stay on top of updated bot and browser lists which they can apply immediately with no work from you required so their reports are always current. Web based tools like Awstats don't require any client side and thus will offer a complete set of statistics from every user. If you use a web host that provides a basic control panel one of these is usually included so no set up is required. On the downside if you don't have a server with a pre-installed control panel or want to use a different one then is included you'll have to install one yourself. Installing software on web servers, particularly \*nix systems, is not for the lighthearted. As browsers and bots continually change you'll need to make sure you keep this software up to date otherwise you'll have a lot of "unknown" bots and browsers in your stats which isn't particularly helpful.
23,916,186
I want to create package for python that embeds and uses an external library (`.so`) on Linux using the cffi module. Is there standard way to include .so file into python package? The package will be used only internally and won't be published to pypi. I think Wheel packages are the best option - they would create platform specific package with all files ready to be copied so there will be no need to build anything on target environments.
2014/05/28
[ "https://Stackoverflow.com/questions/23916186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1296661/" ]
You can use [auditwheel](https://github.com/pypa/auditwheel) to inject the external libraries into the wheel: > > auditwheel repair: copies these external shared libraries into the wheel itself, and automatically modifies the appropriate RPATH entries such that these libraries will be picked up at runtime. This accomplishes a similar result as if the libraries had been statically linked without requiring changes to the build system. Packagers are advised that bundling, like static linking, may implicate copyright concerns. > > > You can pre-build the external c++ library by typically executing the following: ``` ./configure && make && make install ``` This will generate an `my_external_library.so` file and install it in the appropriate path. However, you'll need to ensure that the library path is properly set in order for the auditwheel to discover the missing dependency. ``` export LD_LIBRARY_PATH=/usr/local/lib ``` You can then build the python wheel by executing: ``` python setup.py bdist_wheel ``` Finally, you can repair the wheel, which will inject the `my_external_library.so` into the package. ``` auditwheel repair my-python-wheel-1.5.2-cp35-cp35m-linux_x86_64.whl ``` I successfully applied the above steps to the python library [confluent-kafka-python](https://github.com/confluentinc/confluent-kafka-python) which has a required c/c++ dependency on [librdkafka](https://github.com/edenhill/librdkafka). --- Note: auditwheel is Linux-only. For MacOS, see the [delocate](https://github.com/matthew-brett/delocate) tool.
72,233,775
Below table would be the input dataframe | col1 | col2 | col3 | | --- | --- | --- | | 1 | 12;34;56 | Aus;SL;NZ | | 2 | 31;54;81 | Ind;US;UK | | 3 | null | Ban | | 4 | Ned | null | Expected output dataframe [values of col2 and col3 should be split by ; correspondingly] | col1 | col2 | col3 | | --- | --- | --- | | 1 | 12 | Aus | | 1 | 34 | SL | | 1 | 56 | NZ | | 2 | 31 | Ind | | 2 | 54 | US | | 2 | 81 | UK | | 3 | null | Ban | | 4 | Ned | null |
2022/05/13
[ "https://Stackoverflow.com/questions/72233775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10795596/" ]
You can use the pyspark function `split()` to convert the column with multiple values into an array and then the function `explode()` to make multiple rows out of the different values. It may look like this: ``` df = df.withColumn("<columnName>", explode(split(df.<columnName>, ";"))) ``` If you want to keep NULL values you can use `explode_outer()`. If you want the values of multiple exploded arrays to match in the rows, you could work with `posexplode()` and then `filter()` to the rows where the positions are corresponding.
2,733,133
What is good way: Keep all functions in one file or to set apart them? (like database.php, session.php)
2010/04/28
[ "https://Stackoverflow.com/questions/2733133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My approach is split functionalities into classes; and then to put each class into one file. If you have a lot of functions, I would do the same - split them into thematically separate files and include them only when needed. If you work with classes, you can make use of PHP's [autoloader](http://www.php.net/manual/en/language.oop5.autoload.php) functionality that will automatically load any PHP files needed to instantiate a certain class.
8,513,178
I am going through lessons of JavaScript about Event Handlers, while doing so I am starting very basic which is `getElementById()`. Below is my HTML and JavaScript Code. The following code has images tag also but I am new user to SO that's why they didn't allowed me to post them in the exact way. So consider `src` tags to be fully complaint. ``` <div class="considerVisiting"> <img src="images/bq-twitter" id="mainImage" alt="BeQRious Twitter"> </div> ``` and here is the JavaScript Code: ``` var myImage = document.getElementById("mainImage"); var imageArray = [images/1-btn, images/download-as-you-like]; var imageIndex = 0; function changeImage() { myImage.setAttribute("src",imageArray[imageIndex]); imageIndex++; if (imageIndex >= imageArray.length) { imageIndex=0; } } setInterval(changeImage, 5000); ``` This code will change the mainImage Picture every 5 seconds. But the problem I am facing is that when I run this script using FireBug in Mozilla it says: ``` > Error : myImage is Null ``` and nothing happens with regard to the script.
2011/12/14
[ "https://Stackoverflow.com/questions/8513178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098862/" ]
As Philip Kelley noted `SELECT @Name = Lower(ITEMS) FROM dbo.TEST` will always give you the last item in the result. So his solution (adding `WHERE PK = @I`) will work if the PKs in the table start with 1 and are sequential. If either those conditions don't hold true then you'll have to do somthing like this. ``` ;WITH CTE as (SELECT row_number() over (order by pk) rn, items FROM dbo.TEST) SELECT @Name = Lower(items) FROM CTE where rn = @i ``` Although in all honestly you're probably better of with `FAST_FORWARD` cursor since you've lost the set-based operations battle already. See this [data.se query](https://data.stackexchange.com/stackoverflow/s/2278/sample-for-8513177) for a working example (note I added another item `6,'6666'`)
10,313,337
When I "run" my app from XCode the simulator comes up and the app attempts to run, it animates to a black screen for a second and then the app closes immediately. The app was running fine before and now suddenly won't work. There is no output on the console, no errors or anything and the app isn't crashing (as far as I can tell). I have tried deleting all my user specific files in the xcodeproj package, but this hasn't changed anything. Is there any other reason why this would happen? How do I fix this? Thank you. ADDITION: `NSLog(@"something");` in the `application:didFinishLaunchingWithOptions` method doesn't show up on the console.
2012/04/25
[ "https://Stackoverflow.com/questions/10313337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414972/" ]
A reboot of my Mac seems to have fixed it. Thanks guys for your help. :)
42,526,449
I'm a beginner in python & am having some problems with the structure of my homework assignment; my assignment is: "Write a program that asks the user for a filename, opens the file and reads through the file just once before reporting back to the user the number of characters (including spaces and end of line characters), the number of words, and the number of lines in the file. If the user enters the name of a file that doesn't exist, your program should give her as many tries as she needs in order to type a valid filename. Obtaining a valid filename from the user is a common operation, so start by writing a separate, reusable function that repeatedly asks the user for a filename until she types in a file that your program is able to open." And, I didn't start that way (& now I'm wondering if with the way I've structured it with "with/as", there's a way to even do that but my problem right now is getting it to go back into the try section of code after the error is thrown (I missed the class where this was explained so I've only ever read about this so I Know I'm not doing something right). I can get it to work as long as it's a filename that exists, if it's not, it prints nothing to the screen. Here's my code: ``` filename = input("please enter a file name to process:") lineCount = 0 wordCount = 0 charCount = 0 try: with open(filename, 'r') as file: for line in file: word = line.split() lineCount = lineCount + 1 wordCount = wordCount + len(word) charCount = charCount + len(line) print("the number of lines in your file is:", lineCount) print("the number of words in your file is", wordCount) print("the number of characters in your file is:", charCount) except OSError: print("That file doesn't exist") filename = input("please enter a file name to process:") ``` And, I'm not sure what I should do- if I should scrap this whole idea for a simple try: open(filename, 'r') / except: function of it=f there's anyway to salvage this. So, I thought to fix it this way: ``` def inputAndRead(): """prompts user for input, reads file & throws exception""" filename = None while (filename is None): inputFilename = input("please enter a file name to process") try: filename = inputFilename open(filename, 'r') except OSError: print("That file doesn't exist") return filename inputAndRead() lineCount = 0 wordCount = 0 charCount = 0 with open(filename, 'r') as file: for line in file: word = line.split() lineCount = lineCount + 1 wordCount = wordCount + len(word) charCount = charCount + len(line) print("the number of lines in your file is:", lineCount) print("the number of words in your file is", wordCount) print("the number of characters in your file is:", charCount) ``` But, I'm getting error: `NameError: name 'file' is not defined`
2017/03/01
[ "https://Stackoverflow.com/questions/42526449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5666784/" ]
I would reorganize this code so that the file is opened in a loop. No matter how many times the user enters an invalid filename, the code will just ask for a new one and try again. ``` lineCount = 0 wordCount = 0 charCount = 0 f = None while f is None: filename = input("please enter a file name to process:") try: f = open(filename) except OSError: print("That file doesn't exist") for line in file: word = line.split() lineCount = lineCount + 1 wordCount = wordCount + len(word) charCount = charCount + len(line) print("the number of lines in your file is:", lineCount) print("the number of words in your file is", wordCount) print("the number of characters in your file is:", charCount) ```
96,027
In [this question](https://rpg.stackexchange.com/q/95688/31575) we addressed a problem in which my players were finding combat too easy, and were not having to ration their stronger abilities. After discussion I've decided to implement [Dale's suggestion](https://rpg.stackexchange.com/a/95734/31575): redefining rest periods to 8 hours (short) and 1 week (long) in order to space the recommended number of combat encounters sensibly for a story-driven campaign while keeping my players' ability use in check. In most instances I feel this is an optimal solution. The druid I mentioned in that question, for example, will have to be much more judicious in his use of wild shape. His spells will also regenerate at a reduced rate, so the decision of whether or not to use spell will possesses more gravity. That said, this option does come with its own problems... An example of where this breaks down in my mind: Prepared casters, such as the druid, are typically allowed to choose spells after a long rest (~1/day), making them useful for handling utility spells (such as *Shatter*) that spontaneous casters would be less willing to learn due to the fact that they wouldn't use them frequently. Requiring a week of downtime to prepare new spells is far from ideal; the party won't have fun camping for a week outside a ruin to allow a caster to prep *Dispel Magic* in order to break a ward keeping them from entering. Outside of things that are sensibly altered to fit a more spread-out combat schedule (e.g. wild shape use, spell slot replenishment, heals using hit dice, etc.) **what game mechanics may be inadvertently broken by changing the time required for resting?**
2017/03/05
[ "https://rpg.stackexchange.com/questions/96027", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/31575/" ]
Almost definitely nothing. ========================== The rest variant you have described, where a short rest is 8 hours and a long rest is 1 week, is exactly as described in in the *Dungeon Master's Guide* on page 267 in a section on Rest Variants. The designers suggest this option for "gritty realism" and do not provide any warnings about what this might break or imbalance, and their silence suggests that nothing unexpected\* should happen if you implement this rest variant. In other words, it should be safe to utilize this variant without anticipating the need to fix anything else and without endangering the integrity of your campaign as long as you plan for adequate opportunities to rest and avoid overloading the players with a combat pacing that presumes the standard rest schedule. (\* By "nothing unexpected," I mean that obviously your characters will be more hard-pressed with their resources, but that is an expected consequence of this variant. You shouldn't see any game-breaking side effects, however.)
34,590,017
I have three devices defined in the genymotion section of my `build.gradle` : ``` apply plugin: "genymotion" genymotion { devices { "Google Nexus 5 - 5.1.0 - API 22 - 1080x1920" { template String.valueOf(it) deleteWhenFinish false } "Google Nexus 7 - 4.2.2 - API 17 - 800x1280" { template String.valueOf(it) deleteWhenFinish false } "Google Nexus 9 - 5.1.0 - API 22 - 2048x1536" { template String.valueOf(it) deleteWhenFinish false } } config { genymotionPath = "/Applications/Genymotion.app/Contents/MacOS/" taskLaunch = "connectedCheck" } } connectedCheck.dependsOn genymotionLaunch connectedCheck.mustRunAfter genymotionLaunch genymotionFinish.mustRunAfter connectedCheck ``` When I run `./gradlew connectedCheck` all three are launched and tests ran on them simultaneously. If I wanted to add all devices that I'd like to test my app on, that list would grow to 20+ devices which my machine would not cope with. Therefore, I need a way to launch these tests in batches, of say 3. Is there a way to do this?
2016/01/04
[ "https://Stackoverflow.com/questions/34590017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/561498/" ]
This can be achieved by creating productFlavors just for tests: ``` productFlavors { dev; // dev/smoke tests api18; api19; api21; // all api levels tests } ``` These will produce separate test tasks that can be launched separately or in succession: ``` task allConnectedAndroidTests(type: GradleBuild) { tasks = [ 'connectedApi18DebugAndroidTest', 'connectedApi19DebugAndroidTest', 'connectedApi21DebugAndroidTest' ] } ``` Simply assign a buildFlavor to your one, or more devices: ``` "Google Nexus 5 - 5.1.0 - API 22 - 1080x1920" { template String.valueOf(it) productFlavors "api21" } "Google Nexus 7 - 4.2.2 - API 17 - 800x1280" { template String.valueOf(it) productFlavors "api18" } ``` And when you launch one of the assigned launch tasks, only the assigned devices will be launched and have the tests ran on them. For example: ``` ./gradlew allConnectedAndroidTests ... <...>genymotionLaunchConnectedApi18DebugAndroidTest <...>connectedApi18DebugAndroidTest <...>genymotionFinishConnectedApi18DebugAndroidTest ... <...>genymotionLaunchConnectedApi19DebugAndroidTest <...>connectedApi19DebugAndroidTest <...>genymotionFinishConnectedApi19DebugAndroidTest ... <...>genymotionLaunchConnectedApi21DebugAndroidTest <...>connectedApi21DebugAndroidTest <...>genymotionFinishConnectedApi21DebugAndroidTest ... BUILD SUCCESSFUL ``` Full source of this example: <https://github.com/tomaszrykala/Genymotion-productFlavors/blob/master/app/build.gradle>
15,981,989
I have HTML like this: ``` <div style="float: left; font-family: arial; padding-top: 40px; width: 655px; "> <div style="float: left;"> <img src="http://www.problemio.com/img/big_logo.png" id="above_fold_img" style="border: none;" /> </div> <div style="float: left; "> <p> <h1>mobile business plan, <br /> business ideas, fundraising<br /> and marketing apps </h1> <!-- font-size: 200%; --> </p> </div> <div style="clear:both;"></div> ``` And it looks like this. Here is a test page: <http://problemio.com/index_test.php> The blue B is supposed to be on the same line with the text. But possibly because the original image size is very big, it is getting screwed up in size. Here is the css for the img: ``` img#above_fold_img { width: 30%; height: 30%; } ``` Would anyone know how to make the image and text appear on the same line? Thanks!
2013/04/12
[ "https://Stackoverflow.com/questions/15981989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478573/" ]
You need to specify a width for both of the child `<div>`s. According to Chrome DevTools, the first `<div>` (with the child image) is 512px wide. `width: 30%;` on `img#above_fold_img` uses 30% of its parent div. Example: ``` <div style="float: left; width: 256px; height: 256px; margin: 0"> <img src="http://www.problemio.com/img/big_logo.png" id="above_fold_img" style="border: none; width: 256px; height: 256px" /> </div> <div style="float: left; width: 393px; margin: 0; margin-left: 5px"> <p> <h1>mobile business plan, <br /> business ideas, fundraising<br /> and marketing apps </h1> <!-- font-size: 200%; --> </p> </div> ``` I kept all styles inline in my example, but using CSS is better. Also, the 'b' image is 512x512px. If you can shrink it, you will reduce load times.
13,783,063
Hi i wrote the following code: ``` AssemblyName assemblyName = new AssemblyName("SamAsm"); AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); TypeBuilder typeBuilder = assemblyBuilder.DefineDynamicModule("SamAsm.exe").DefineType("SamAsmType", TypeAttributes.Public); MethodBuilder methodBuilder1 = typeBuilder.DefineMethod("Main", MethodAttributes.Static | MethodAttributes.Public, typeof(void), new Type[] { typeof(string) }); ILGenerator gen = methodBuilder1.GetILGenerator(); FieldInfo field1 = typeof(Form1).GetField("TextBox1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo method2 = typeof(Control).GetProperty("Text", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod(); MethodInfo method3 = typeof(String).GetMethod( "op_Equality", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(String), typeof(String) }, null ); MethodInfo method4 = typeof(MessageBox).GetMethod( "Show", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[]{ typeof(String) }, null ); LocalBuilder a = gen.DeclareLocal(typeof(Boolean)); System.Reflection.Emit.Label label42 = gen.DefineLabel(); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field1); gen.Emit(OpCodes.Callvirt, method2); gen.Emit(OpCodes.Ldstr, "HI"); gen.Emit(OpCodes.Call, method3); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ceq); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Brtrue_S, label42); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldstr, "You cracked me"); gen.Emit(OpCodes.Call, method4); gen.Emit(OpCodes.Pop); gen.Emit(OpCodes.Nop); gen.MarkLabel(label42); gen.Emit(OpCodes.Ret); typeBuilder.CreateType().GetMethod("Main").Invoke(null, new string[] { null }); assemblyBuilder.SetEntryPoint(methodBuilder1, PEFileKinds.WindowApplication);} ``` When i try this, it stops me on gen.Emit(OpCodes.Ldfld,typeof(Form1).GetField("TextBox1", BindingFlags.Public | BindingFlags.NonPublic)); and tell: The value can't be null. Parameter name : con . Someone can help me?
2012/12/08
[ "https://Stackoverflow.com/questions/13783063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1872492/" ]
After you have fetched the first row as an associative array, you can get the column names with `array_keys($line)`. If you decide to stop using the deprecated ext/mysql functions, and switch to ext/mysqli or pdo\_mysql, you can enjoy nice functions like [mysqli\_stmt::result\_metadata()](http://php.net/manual/en/mysqli-stmt.result-metadata.php) or [PDOStatement::getColumnMeta()](http://us1.php.net/manual/en/pdostatement.getcolumnmeta.php).
36,467
What meditation practice(s) are encompassed by 'asubha' (non-beautiful)? I've heard one teacher say that in the EBT (early buddhist texts), asubha practice only refers to 31 body parts, and later Theravada expanded it to include 9 cemetary corpse decay, and perhaps other practices as well? Does anyone know for sure? In the pali suttas, most of the references to asubha do not specify a specific meditation practice(s). Is AN 10.60 the only place where asubha is specifically assigned to 31 body parts? I'd prefer to believe asubha meditation encompasses more practices than just the 31asb, unless there is conclusive evidence. Simply because in an oral tradition where memory of teachings is mandatory, it's helpful when a label, 'asubha' in this case, covers all the practices that could qualify for doing that job. We know that the purpose of asubha (ugly or non-beautful), is to counter the effects of subha (beautiful) have in inducing lust/passion/desire for sensual pleasure, especially for sex. Clearly the stages of decomposition of corpses, the discharge from the 9 orifices of the body, all qualify in accomplishing that goal. AN 10.60 defines the practice of asubha as 31 body parts contemplation: > > *Katamā cānanda, asubhasaññā?* > > And what is the perception of ugliness? > > Idhānanda, bhikkhu imameva kāyaṃ uddhaṃ pādatalā adho kesamatthakā tacapariyantaṃ *pūraṃ nānāppakārassa asucino paccavekkhati:* > > It’s when a monk examines their own body up from the soles of the feet and down from the tips of the hairs, wrapped in skin and full of many kinds of filth. > > *‘atthi imasmiṃ kāye kesā lomā nakhā dantā taco, maṃsaṃ nhāru aṭṭhi aṭṭhimiñjaṃ vakkaṃ, hadayaṃ yakanaṃ kilomakaṃ pihakaṃ papphāsaṃ, antaṃ antaguṇaṃ udariyaṃ karīsaṃ, pittaṃ semhaṃ pubbo lohitaṃ sedo medo, assu vasā kheḷo siṅghāṇikā lasikā muttan’ti.* > > ‘In this body there is head hair, body hair, nails, teeth, skin, flesh, sinews, bones, bone marrow, kidneys, heart, liver, diaphragm, spleen, lungs, intestines, mesentery, undigested food, feces, bile, phlegm, pus, blood, sweat, fat, tears, grease, saliva, snot, synovial fluid, urine.’ > > *Iti imasmiṃ kāye asubhānupassī viharati.* > > And so they meditate observing ugliness in this body. > > *Ayaṃ vuccatānanda, asubhasaññā.* > > This is called the perception of ugliness. > > > summary of my research on this so far: (lots of hyperlinks embedded within source link) <http://lucid24.org/tped/a/asubha/index.html> a-subha ‍ = un-attractive ✅in EBT meditation, it refers to 31asb‍ body parts contemplation. See AN 10.60, AN 6.29. ⚠️300+ years after EBT, in Vimt. and Vism., Theravada re-defines asubha meditation to refer to 10 stages of corpse decay, and they reclassify 31asb‍ under kāya-gatā-sati ‍. It's important to know this, because in EBT suttas, an instruction to "develop asubha" is frequently mentioned, but without detail (examples: SN 8.4, SN 54.9). 31asb is immediately accessible, corpse contemplation considerably more complex. • What's the purpose of asubha meditation? To counter perversions of our inverted perception AN 4.49, SN 8.4. • But be careful, this is an advanced practice. Best to first have foundation in breath meditation SN 54.9. • SN 12.61 and SN 12.62 is the more general case of seeing 4 elements via dependent origination 12ps as not being worth clinging to.
2020/01/01
[ "https://buddhism.stackexchange.com/questions/36467", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/16297/" ]
Joggers or long distance runners didn't just start out running for hours. They build up their stamina slowly and steadily over time. So use the same approach for meditation. Build it up gradually and don't settle for the 30-min achievement. It's probably too short for any significant deep absorption state anyway. There're advanced meditators who immerse themselves in deep absorption for days.
907,827
I'm not new to home networking and I've been running DD-WRT routers for years. I'm a software developer, so "technologically" curious by nature but admittedly have never really researched in-depth low level technical details of networking. I'm probably being paranoid and plan on doing further research and learning on my own, but I've been seeing strange things on my home network lately. The one I wanted to ask about here was regarding private MAC Addresses. By that I mean when I look up the MAC Address through the DD-WRT OUI Lookup, it's designated as private. Google knows all, but I can't really find anything in plain English about typical use or scenarios where they would be used. I have a private MAC address showing up on my LAN with a DHCP assigned IP address that I haven't been able to identify. I've used NMap pointed at the IP associated with the "private" MAC address but it can't identify anything about it either. It cannot identify the vendor/manufacturer, the O/S, or anything else. I'm looking for any information that may be useful in helping me understand where and what this device may be. Other info: I've recently updated the WPA2 password from pretty secure to 13+ character length after seeing a "ghost" (aka evil twin) access point/SSID that I also can't identify. Additionally, for now (even though I know it's not a secure solution) I've filtered the offending "private" MAC address from accessing my home networks.
2015/04/29
[ "https://superuser.com/questions/907827", "https://superuser.com", "https://superuser.com/users/442544/" ]
Private MAC addresses are often found in embedded systems that do not have an official address. Many cheap "credit card computers" such as the Raspberry Pi must generate their own address to operate without an official, manufacturer-assigned address. For you interest: Private MAC addresses can be identified by having the second-least-significant bit of the most significant byte set. (And as unicast addresses, they must not have the least significant bit set.) That means any addres matching any pattern below is private. ``` x2:xx:xx:xx:xx:xx x6:xx:xx:xx:xx:xx xA:xx:xx:xx:xx:xx xE:xx:xx:xx:xx:xx ``` To find what and where your ghost device actually is, I suggest looking for small computers and embedded electronics. A less likely possibility is an intruder in your network with a spoofed MAC address. And lastly, what actually is your question? ;)
51,819,878
I am implementing dynamic links and everything works well, besides that in my project settings I changed the "Team ID" aka "AppStore App Prefix". If I visit `myproject.page.link/apple-app-site-association` it still is giving me the old team ID and I am worrying that could break dynamic links later when the App is being released. Does it take time to be updated? Or is there a way for me to force a refresh of the values? Thank you.
2018/08/13
[ "https://Stackoverflow.com/questions/51819878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1582047/" ]
It is cached, so can take some time. If you're still seeing it after a day, please file a ticket with Firebase support who can route it through to the Dynamic Links team: <https://firebase.google.com/support/contact/?category=troubleshooting>
16,690,441
The following function validates empty field correctly: ``` function empty_field(element){ element.each(function(){ if($(this).val() == ''){ $(this).addClass('error'); } else{ $(this).removeClass('error'); return true; } }); } ``` However I want to check that the validation is complete by doing the following: ``` submit.click(function(e){ e.preventDefault(); var input = $('.input'); if(empty_field(input))//if the form is valid { console.log('form validated'); } }); ``` When I click on the submit button the forms gets validated but the console log doesn't work meaning that maybe the condition is wrong. Any help?
2013/05/22
[ "https://Stackoverflow.com/questions/16690441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312785/" ]
Your inner function doesn't return from the outer function. You could amend with a variable in the scope of your empty\_field function. E.g. ``` function empty_field(element){ var valid = true; element.each(function(){ if($(this).val() == ''){ $(this).addClass('error'); valid = false; } else{ $(this).removeClass('error'); } }); return valid; } ```
12,108,307
I've got an array that creates buttons from A-Z, but I want to use it in a Method where it returns the button pressed. this is my original code for the buttons: ``` String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; for(i = 0; i < buttons.length; i++) { buttons[i] = new JButton(b[i]); buttons[i].setSize(80, 80); buttons[i].setActionCommand(b[i]); buttons[i].addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { String choice = e.getActionCommand(); JOptionPane.showMessageDialog(null, "You have clicked: "+choice); } }); panel.add(buttons[i]); } ```
2012/08/24
[ "https://Stackoverflow.com/questions/12108307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614977/" ]
I wasn't sure exactly what you question was, so I have a few answers: 1. If you want to pull the button creation into a method - see the `getButton` method in the example 2. If you want to access the actual button when it's clicked, you can do that by using the `ActionEvent.getSource()` method (not shown) or by marking the button as final during declaration (shown in example). From there you can do anything you want with the button. 3. If you question is "How can I create a method which takes in a array of letters and returns to me the last clicked button", you should modify you question to explicitly say that. I didn't answer that here because unless you have a very special situation, it's probably not a good approach to the problem you're working on. You could explain why you need to do that, and we can suggest a better alternative. Example: ``` import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TempProject extends Box{ /** Label to update with currently pressed keys */ JLabel output = new JLabel(); public TempProject(){ super(BoxLayout.Y_AXIS); for(char i = 'A'; i <= 'Z'; i++){ String buttonText = new Character(i).toString(); JButton button = getButton(buttonText); add(button); } } public JButton getButton(final String text){ final JButton button = new JButton(text); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "You have clicked: "+text); //If you want to do something with the button: button.setText("Clicked"); // (can access button because it's marked as final) } }); return button; } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setContentPane(new TempProject()); frame.pack(); frame.setVisible(true); new TempProject(); } }); } } ```
73,224,102
I want to check the length of a list within a tuple, but I am having trouble doing this within a conditional statement. If I have a tuple that looks like this: ``` ex_tuple = (['Hello', 'To', 'World'], ['Planet', 'Earth'], ['World', 'Of', 'Earth']) ``` I want to check if any of these lists in the tuple have > 2 elements. Here's what I have (doesn't seem to be working): ``` if [(len(x)) for x in ex_tuple > 2]: ... do rest of program ``` But, I get an error message that '>' is not supported between tuple and ints. I've also tried using '!= 1 or 2', but I get a similar message. This seems like a simple fix, but I am having trouble figuring out where I am going wrong. Would appreciate any help - thanks!
2022/08/03
[ "https://Stackoverflow.com/questions/73224102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19489873/" ]
The built-in function `any()` takes a list and evaluates True if any elements are True, and False if they're all false. Put your list comprehension in there, and move your conditional `> 2` over next to `len(x)` and drop the parentheses around it ```py any(len(x)>2 for x in ex_tuple) True ```
62,727,671
I have a following code which basically disables the button on mousedown event and enables it back again on mouseup event. However, the mouseup event doesn't enable the button for some reason. Here's a code snippet: ```js new Vue({ el: "#app", data: { clicked: false }, methods: { toggle(type) { if (type === "down") { this.clicked = true } else { this.clicked = false // Mouseup event doesn't reach here } } } }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @mouseup="toggle('up')" @mousedown="toggle('down')" :disabled="clicked" >Button</button> </div> ```
2020/07/04
[ "https://Stackoverflow.com/questions/62727671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9764412/" ]
I think the problem here is that you are thinking that using -: ``` root.title(var) ``` would make it so that anytime you change the var the title will change, but actually its that the title is changed only once and to the value of the var at the time it was supplied. So if you want it to change everytime you change your var, then rather put it in the same function as the one where you change your var. ``` def update_title(title) : global var var = title root.title(title) return ``` and now every time you change the title run this down with the desired title as the argument. I hope this solves your problem. Also i hope you're safe in the time of an ongoing pandemic.
44,877,656
I want to use a service worker in my Cordova Android add as a convenient way to sync some images to and from the server. I notice that [this question](https://stackoverflow.com/questions/39921733/service-workers-on-cordova-app) states that this is not possible, since service workers must be loaded via `https:`, whereas Cordova will load files via `file:`. On the other hand, it seems that [ionic supports service workers](https://ionicframework.com/docs/developer-resources/service-worker/). That implies that they have figured out some way to make this work. However, I am not using ionic. There appears to be a [cordova plugin for service workers for iOS](https://www.npmjs.com/package/cordova-plugin-service-worker), but as I said I am on Android. What is the current best practices for using service workers in Cordova Android apps, if that's possible at all?
2017/07/03
[ "https://Stackoverflow.com/questions/44877656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
After digging deep into this issue, I conclude that there is no support for Service workers in Android as it blocks service workers from HTTP or file protocols. Also the support of Service worker in Ionic framework do not clearly state that it is not supported in hybrid mobile apps. It's kind of misleading too as in this case. Ionic's Service Worker support comes into picture only in case of Progressive Web App and not in hybrid mobile app as mentioned in their [official blog](http://blog.ionic.io/service-workers-revolution-against-the-network/) Adding to the above info, most of the functionality that can be achieved by using Service Workers are already available as part of plugins like push notification plugin which should be suffice in most cases. The bottom line is that the Service Workers are not supported in Cordova Android as well as in Ionic framework. For more info, check out the following [link](https://github.com/ionic-team/ionic/issues/9977)
57,387,255
​I have created a proxy in Apigee Edge to Generate JWT token. I have created another proxy in Apigee Edge Validate the JWT token, and I am able to Validate using that. Now I am unable to Validate the JWT Token completely from .NET/C# code. Below is the .NET code I tried: ``` private static bool ValidateToken(string authToken, string key) { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = GetValidationParameters(key); SecurityToken validatedToken; IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken); return true; } private static TokenValidationParameters GetValidationParameters(string key) { return new TokenValidationParameters() { ValidateLifetime = false, // Because there is no expiration in the generated token ValidateAudience = false, // Because there is no audiance in the generated token ValidateIssuer = false, // Because there is no issuer in the generated token ValidIssuer = "urn:apigee-edge-JWT-policy-test", ValidAudience = "audience1", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("key")) // The same key as the one that generate the token }; } ``` And the JWT Generation Policy Code from Apigee Edge: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <GenerateJWT async="false" continueOnError="false" enabled="true" name="Generate-JWT-1"> <DisplayName>Generate JWT-1</DisplayName> <Algorithm>HS256</Algorithm> <SecretKey> <Value ref="private.key"/> </SecretKey> <Subject>subject-subject</Subject> <Issuer>urn://apigee-edge-JWT-policy-test</Issuer> <Audience>audience1,audience2</Audience> <ExpiresIn>8h</ExpiresIn> <AdditionalClaims> <Claim name="userId" type="string" ref="request.formparam.username"/> </AdditionalClaims> <OutputVariable>jwt-variable</OutputVariable> </GenerateJWT> ``` Here is the error message: > > Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: > IDX10503: Signature validation failed. Keys tried: > 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey, KeyId: > '', InternalId: > '96edcecb-17ad-4022-a50b-558f426ed337'. , KeyId: '. > Exceptions caught: 'System.ArgumentOutOfRangeException: IDX10603: > Decryption failed. Keys tried: 'HS256'. Exceptions caught: > '128'. token: '96' Parameter name: KeySize at > Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey > key, String algorithm, Boolean willCreateSignatures) at > Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey > key, String algorithm, Boolean willCreateSignatures) at > Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey > key, String algorithm) at > System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] > encodedBytes, Byte[] signature, SecurityKey key, String algorithm, > TokenValidationParameters validationParameters) at > System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String > token, TokenValidationParameters validationParameters) '......... > > >
2019/08/07
[ "https://Stackoverflow.com/questions/57387255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10411058/" ]
Your keysize is not long enough like the exception mentions: `Exceptions caught: '128'. token: '96' Parameter name: KeySize` use a longer key that matches the excepted size
29,354,379
The script requires jQuery All works fine but I need to be able to change the color of the selected dropdown when it is selected by the option box, to (bright green). And greyed out again if the other option is chosen. I have tried all the suggested tips I read up on i.e. $( "#mOptions" ).prop (.css('background-color','#ffffff')); any color. please help and many thanks. Did not work The script ``` $(document).ready(function(){ $('input[name="gender"]').click(function() { if($('input[name="gender"]').is(':checked')) { var radioValue = $("input[name='gender']:checked").val(); if(radioValue == "m"){ $( "#mOptions" ).prop( "disabled", false ); $( "#fOptions" ).prop( "disabled", true ); } else { $( "#mOptions" ).prop( "disabled", true ); $( "#fOptions" ).prop( "disabled", false ); } } }); }); ``` The Form: ``` <input type="radio" name="gender" value="m" />Male <input type="radio" name="gender" value="f" />Female <br /> <select id="mOptions" disabled="true"> <option>Select</option> <option value="1">Shirt</option> <option value="2">Pant</option> <option value="3">dhoti</option> </select> <select id="fOptions" disabled="true"> <option>Select</option> <option value="4">Saree</option> <option value="5">Bangle</option> <option value="6">handbag</option> </select> ```
2015/03/30
[ "https://Stackoverflow.com/questions/29354379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373543/" ]
You can chain a `css` method to the `prop` method like this: ``` $('input[name="gender"]').click(function() { if($('input[name="gender"]').is(':checked')) { var radioValue = $("input[name='gender']:checked").val(); if(radioValue == "m"){ $( "#mOptions" ).prop( "disabled", false ).css('background-color', 'lightgreen'); $( "#fOptions" ).prop( "disabled", true ).css('background-color', ''); } else { $( "#mOptions" ).prop( "disabled", true ).css('background-color', ''); $( "#fOptions" ).prop( "disabled", false ).css('background-color', 'lightgreen');; } } }); ``` You may also consider resetting the value of the *other* drop-down to "Selected," so you don't end up with a disabled drop-down that has a value. You can do so like this: ``` $( "#fOptions" ).prop( "disabled", true ).css('background-color', '').val('Select'); ``` For more user-friendliness, consider wrapping your inputs with a label: ``` <label><input type="radio" name="gender" value="m" />Male</label> ``` That allows your users to click the word "Male" in addition to selecting the tiny radio button. [**Fiddle**](https://jsfiddle.net/7zwo19vb/) --- You can simplify the logic a bit. Once you've clicked a radio button, at least one of the buttons *is* checked, and there's no way to uncheck both of them. Therefore, this test is not needed: ``` if($('input[name="gender"]').is(':checked')) ``` Also, the `select` box to enable can be queried directly like this: ``` select= $('#'+$(this).val()+'Options'); ``` You simply need to enable that `select` box and disable the other. **Updated Code:** ``` $('input[name="gender"]').click(function() { var value= $(this).val(), select= $('#'+value+'Options'); select .prop('disabled', false) .css('background-color', 'lightgreen'); $('#mOptions, #fOptions') .not(select) .prop('disabled', true) .css('background-color', '') .val('Select'); }); ``` [**New Fiddle**](https://jsfiddle.net/tdff339h/)
825,532
I have a USB flash drive. After using it for a year or so some blocks became unreadable. I [formatted the drive in order these blocks to be marked as bad ones](http://smallbusiness.chron.com/format-usb-bad-sectors-45191.html): ![Standard format dialog](https://i.stack.imgur.com/vFIZb.png) ![Formatting the partition](https://i.stack.imgur.com/SddJ1.png) Was they really marked and excluded from File Allocation Table? I need to know if I can recommend this approach to non-experienced users who asks me from time to time about their troubles. How can I get to know now 1. if any of bad blocks was found? 2. how much bad blocks are there? 3. where are they located? **Update1:** I want to get to know if standard format procedure can help in such a situations. **Update2:** I got to know that bad blocks exist in this drive using [ChkFlsh](http://www.ehow.com/how_6055690_test-flash-memory-pen-drive.html) ![enter image description here](https://i.stack.imgur.com/GI803.png) ![enter image description here](https://i.stack.imgur.com/6hL64.png) ``` Error at address 1DF448000h: expected "10101010", found "11110000". Error at address 1DF544000h: expected "10101010", found "11100100". Error at address 1DF640000h: expected "10101010", found "00001110". Error at address 1DF73C000h: expected "10101010", found "11101111". Error at address 1DF838000h: expected "10101010", found "00000000". Error at address 1DF934000h: expected "10101010", found "11101001". Error at address 1DFA30000h: expected "10101010", found "01101100". Error at address 1DFB2C000h: expected "10101010", found "01000100". Error at address 1DFC28000h: expected "10101010", found "10100111". Error at address 1DFD24000h: expected "10101010", found "11010110". Error at address 00000000h: expected "01010101", found "01001100". Error at range [000FC000h..001F8000h]: device read error. Error at address 001F8000h: expected "01010101", found "00110011". Error at address 002F4000h: expected "01010101", found "00001110". Error at address 003F0000h: expected "01010101", found "00001110". Pass #1 completed, 16 errors found. Test completed, total 16 errors found. ```
2014/10/13
[ "https://superuser.com/questions/825532", "https://superuser.com", "https://superuser.com/users/48946/" ]
As far as I know, the microcontroller on the USB stick will substitute bad sectors with reserve sectors so that the computer won't see the defect. If the stick runs out of reserve sectors, meaning many sectors went bad, you should see the number of bad sectors if you run chkdsk at DOS prompt.
10,910,246
is there a difference if i use """..""" in the sql of cusror.execute. Even if there is any slight difference please tell
2012/06/06
[ "https://Stackoverflow.com/questions/10910246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855224/" ]
It's used to split the query over many lines to format it nicely: ``` db.query(""" SELECT * FROM employee, department WHERE employee.DepartmentID = department.DepartmentID; """) ``` Also using `"""..."""` around a string allows you to not escape `"` and `'` inside that string.
13,168,816
Currently I am using require.js for a fun side project I am working everything is working fine except a code syntax higlighting plugin called prism.js. I can see that the plugin is being pulled via the network tab in chrome, but the plugin isn't initializing. I am not sure if it's a require problem or uf the plugin is the issue and was wondering if anyone could help. Here is a look at my main.js: ``` require.config({ // 3rd party script alias names paths: { // Core Libraries modernizr: "libs/modernizr", jquery: "libs/jquery", underscore: "libs/lodash", backbone: "libs/backbone", handlebars: "libs/handlebars", text: "libs/text", prism: "plugins/prism", templates: "../templates" }, // Sets the configuration for your third party scripts that are not AMD compatible shim: { "backbone": { "deps": ["underscore", "jquery", "handlebars"], "exports": "Backbone" //attaches "Backbone" to the window object } } }); // Include Specific JavaScript require(['prism', 'modernizr', 'jquery', 'backbone', 'routers/router', 'views/AppVIew' ], function(Prism, Modernizr, $, Backbone, Router, App) { this.router = new Router(); this.App = new App(); } ); ```
2012/10/31
[ "https://Stackoverflow.com/questions/13168816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/697375/" ]
Change the shim section to include prism, and make sure it exports "Prism": ``` shim: { "backbone": { "deps": ["underscore", "jquery", "handlebars"], "exports": "Backbone" //attaches "Backbone" to the window object }, "prism": { "exports": "Prism" } } ```
30,717,302
I am saving a ".mov" file to a hosted Parse database from an image picker controller with data: ``` NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *data = [NSData dataWithContentsOfURL:videoURL]; ``` I later retrieve the NSData for the file and would like to let the user play the video using the MPMoviePlayerController. Is there a way to do this without writing the file? I would prefer to just play it in a temp location that is released once it has finished... This is my code but no video plays when the view appears... ``` NSString *outputPath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"temp.mov"]; [self.videoData writeToFile:outputPath atomically:YES]; NSURL *moveUrl = [NSURL fileURLWithPath:outputPath]; MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:moveUrl]; [player prepareToPlay]; [player.view setFrame:CGRectMake(40, 197, 240, 160)]; [self.view addSubview:player.view]; [player play]; ```
2015/06/08
[ "https://Stackoverflow.com/questions/30717302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4072552/" ]
First of all a very good question with lots of details. If you enable `RewriteLog` you will notice this is actually being caused by this line (when you request `http://localhost/h/first/second` URL): ``` add path info postfix: /landingpage1.php/second ``` [There a bug raised specifically for this issue on Apache.org.](https://bz.apache.org/bugzilla/show_bug.cgi?id=38642) This happens when you omit `L` or [`DPI` (i.e. `Discard Path Info`)](http://httpd.apache.org/docs/trunk/rewrite/flags.html#flag_dpi) flags from `RewriteRule`. It will behave well if you use: ``` RewriteCond %{REQUEST_FILENAME} (.+) RewriteRule first /landingpage1.php [R,DPI,ENV=lang:hi] RewriteCond %{REQUEST_FILENAME} (.+) RewriteRule second /landingpage2.php?id=%1&%{ENV:lang} [R,L] ```
17,330,173
I'm trying to write an extension method that will convert `IDictionary<K, S<V>>` holding any type of collection/sequence (`S<V>`) to `ILookup<K, V>` which is more proper data structure in those cases. This means I'd like my extension to work on different `S` types and interfaces: * `IDictionary<K, IEnumerable<V>>` * `IDictionary<K, ICollection<V>>` * `IDictionary<K, List<V>>` etc. Ideally, I don't want to write separate implementation for each possible collection type AND I want type inference to do its job. What I've tried is: ``` public static ILookup<TKey, TValue>ToLookup<TKey, TCollection, TValue>( this IDictionary<TKey, TCollection> dictionary) where TCollection : IEnumerable<TValue> ``` But it have no `TValue` in parameters list, so type inference is unable to figure it out - I get "The type arguments for method ToLookup cannot be inferred from the usage". Is there a chance it could work somehow in other way than adding fake `TValue`-typed parameter to the method? **Examples of expected usage** I hope all above calls to be possible and result in a call to my single extension method: ``` var dictOfIEnumerables = new Dictionary<int, IEnumerable<int>>(); var lookupFromIEnumerables = dictOfIEnumerables.ToLookup(); var dictOfICollections = new Dictionary<int, ICollection<int>>(); var lookupFromICollections = dictOfICollections.ToLookup(); var dictOfLists = new Dictionary<int, List<int>>(); var lookupFromLists = dictOfLists.ToLookup(); ```
2013/06/26
[ "https://Stackoverflow.com/questions/17330173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142827/" ]
Because all collections implement `IEnumerable<T>`, we can just use it instead of the `TCollection` type paramter. Unfortunately the type inference does not know this. This is the code I wrote: ``` public static ILookup<TKey, TValue> ToLookup<TKey, TValue> (this IDictionary<TKey, IEnumerable<TValue>> dict) { return dict.SelectMany(p => p.Value.Select (v => new KeyValuePair<TKey, TValue>(p.Key, v))) .ToLookup(p => p.Key, p => p.Value); } ``` There seems to be no way of making the type inference work, but this method will work if you cast the Dictionary: ``` ((IDictionary<int, IEnumerable<int>>)dictOfLists).ToLookup() ``` Also you can add Lists to a Dictionary of IEnumerables and cast them back when you need them.
116,062
I'm unsure how to handle a step-wise walking bass under a tritone substitution progression. I'm working on piano and using what I understand to be basic "Evans" voicings in the right hand where the tritone sub. is an *altered* dominant when in major, but a un-altered dominant when in minor. Not notating actual rhythms, just the changes and bass tones, I have... [![enter image description here](https://i.stack.imgur.com/2Q6Se.png)](https://i.stack.imgur.com/2Q6Se.png) Would those be the right (typical) step-wise tones? --- EDIT Posting a revision after answers... [![enter image description here](https://i.stack.imgur.com/BbKg7.png)](https://i.stack.imgur.com/BbKg7.png)
2021/07/16
[ "https://music.stackexchange.com/questions/116062", "https://music.stackexchange.com", "https://music.stackexchange.com/users/23919/" ]
I’d first like to offer a few comments about walking bass in general: Sometimes walking bass lines are written out note for note by arrangers but for the most part they are created by the bassist (or other instrumentalist playing a bass line) based on his knowledge of harmony, experience and also his personal preferences, what sounds good and right to him. I have sometimes heard other pro bassists’ use note choices that are not what I would have used. My point is that there are some universally used conventions like avoiding awkward intervals or repeated notes from beat 4 to beat 1 there are similar approaches to lines that are slightly different but that both work. Use and trust your ear and listen to bass players you admire for ideas and techniques. My other point is that walking bass lines in general and also specific to this question of stepwise motion are very dependent on context. The tempo of the song, the speed of the harmonic motion and the interval from one chord root to the next all play a factor in creating good walking bass lines. The rest of my answer will be based on your examples of 8 notes starting and ending on the original note. What you have written here will work just fine. Actually the fact that they are tritone substitutions is not really relevant to the shapes of the lines. One choice I would make is on the last 4 notes of say the Db7 I would use Ab-Gb-F-Db because I like to hear the F chord tone on beat 3 (assuming quarter note notation) instead of beat 2 because that way the chord tone falls on a stronger beat. Also note the Gb instead of G which I also prefer despite the ascending #11 because the descending Gb leads to the 3rd better but the G works fine too. Walking up and down to the 5th works well because of the number of notes from the root to the 5 but if you were descending to the 5th and back up an adjustment is required, an extra chromatic note must be added, either between the root and 7 or between the 6 and 5. Altered chords and scales present a different challenge because of the dissonance, the lack of a P5 and also the fact that the scale from a jazz perspective has two 2nds (b9 and #9) and either no 4th or no 5th depending on your point of view (is it a #11 or b5?). With this scale and chord the best approach is to create a line that has a good shape and incorporates the root and 3rd effectively. My last comment is regarding your choice of chord quality for the tritone subs. A Db7alt in a 2-5 to a major chord is sonically the same as a G13#11 except for the root. A Db13#11 would give you a more noticeable sonic contrast to the regular 2-5. The same applies to the minor 2-5 in reverse.
70,184,096
I have to test a column of a sql table for invalid values and for NULL. Valid values are: Any number and the string 'n.v.' (with and without the dots and in every possible combination as listed in my sql command) So far, I've tried this: ``` select count(*) from table1 where column1 is null or not REGEXP_LIKE(column1, '^[0-9,nv,Nv,nV,NV,n.v,N.v,n.V,N.V]+$'); ``` The regular expression also matches the single character values 'n','N','v','V' (with and without a following dot). This shouldn't be the case, because I only want the exact character combinations as written in the sql command to be matched. I guess the problem has to do with using REGEXP\_LIKE. Any ideas?
2021/12/01
[ "https://Stackoverflow.com/questions/70184096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13493923/" ]
I guess this regexp will work: ``` NOT REGEXP_LIKE(column1, '^([0-9]+|n\.?v\.?)$', 'i') ``` Note that `,` is not a separator, `.` means any character, `\.` means the dot character itself and `'i'` flag could be used to ignore case instead of hard coding all combinations of upper and lower case characters.
59,746,189
I'm new to the AHK and trying to make a script to click on a coordinate in a specific window, once per minute. I already used the WindowSpy to get the coordinates and the WindowTitle, but i can't get to work Right now the script is: `ControlClick, x469 y363, ahk_pid 11532` Am i missing something?? Thanks! edit1: I changed the script to this and tested in another window like Excel and it worked, but in the game that it is supposed to work, it doesnt, no idea why ``` ControlClick, x466 y364, ahk_pid 11532,,,, Pos sleep 60000 } ```
2020/01/15
[ "https://Stackoverflow.com/questions/59746189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12715452/" ]
You've asked a couple different questions, let's go through them one by one. > > As far as I know, python passes parameter as reference. > > > The correct term for how python passes it's arguments is ["pass py assignment"](https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference). It means that parameters inside the function behave similar to how they would if they had been directly assigned with an `=` sign. (So, mutations will reflect across all references to the object. So far so good) Sidenote (skip if this is confusing): For all intents and purposes, the distinction of "pass by assignment" is important because it abstracts away pass by value vs pass by reference, concepts that are not exposed in python directly. If you wish to know how the underlying mechanism works, it's actually a *pass by value*, but *every value itself is a reference* to an object (equivalent to a first level pointer in C speak). We can see why it's easier and important initially not to worry about this particular abstraction, and use "pass by assignment" as the more intuitive explanation. Next, > > maybe 'arr[1:]' always creates a new object? > > > Correct, slicing always creates a shallow copy of the list. [docs](https://docs.python.org/3/tutorial/datastructures.html) > > If that is the case, is there any way to make arr[1:] work? > > > Not directly, but we can use indexes instead to build a solution that works and gives us the output you desire. Just keep track of a starting index while doing the recursion, and increment it as you continue recursing. ``` def func(arr, start=0): print(arr) if arr[start:] == [] : return for i in range(start, len(arr)): arr[i] *= 2 func(arr, start + 1) r = [1,1,1,1] func(r) print(r) ``` Output: ``` [1, 1, 1, 1] [2, 2, 2, 2] [2, 4, 4, 4] [2, 4, 8, 8] [2, 4, 8, 16] [2, 4, 8, 16] ```
4,733,707
`ZipOutputStream` only zips files in a folder. I want to zip subfolders also. How can I achieve this?
2011/01/19
[ "https://Stackoverflow.com/questions/4733707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479291/" ]
You have to recursively explore your directory in order to add all files in the zip. See this small helper if you wish: ``` using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.Checksums; using System.IO; using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Text.RegularExpressions; namespace Zip { /// <summary> /// Uses Sharpziplib so as to create a non flat zip archive /// </summary> public abstract class ZipManager { /// <summary> /// will zip directory .\toto as .\toto.zip /// </summary> /// <param name="stDirToZip"></param> /// <returns></returns> public static string CreateZip(string stDirToZip) { try { DirectoryInfo di = new DirectoryInfo(stDirToZip); string stZipPath = di.Parent.FullName + "\\" + di.Name + ".zip"; CreateZip(stZipPath, stDirToZip); return stZipPath; } catch (Exception) { throw; } } /// <summary> /// Main method /// </summary> /// <param name="stZipPath">path of the archive wanted</param> /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param> public static void CreateZip(string stZipPath, string stDirToZip) { try { //Sanitize inputs stDirToZip = Path.GetFullPath(stDirToZip); stZipPath = Path.GetFullPath(stZipPath); Console.WriteLine("Zip directory " + stDirToZip); //Recursively parse the directory to zip Stack<FileInfo> stackFiles = DirExplore(stDirToZip); ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) File.Delete(stZipPath); Crc32 crc = new Crc32(); zipOutput = new ZipOutputStream(File.Create(stZipPath)); zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression Console.WriteLine(stackFiles.Count + " files to zip.\n"); int index = 0; foreach (FileInfo fi in stackFiles) { ++index; int percent = (int)((float)index / ((float)stackFiles.Count / 100)); if (percent % 1 == 0) { Console.CursorLeft = 0; Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done."); } FileStream fs = File.OpenRead(fi.FullName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1); ZipEntry entry = new ZipEntry(stFileName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } zipOutput.Finish(); zipOutput.Close(); zipOutput = null; } catch (Exception) { throw; } } static private Stack<FileInfo> DirExplore(string stSrcDirPath) { try { Stack<DirectoryInfo> stackDirs = new Stack<DirectoryInfo>(); Stack<FileInfo> stackPaths = new Stack<FileInfo>(); DirectoryInfo dd = new DirectoryInfo(Path.GetFullPath(stSrcDirPath)); stackDirs.Push(dd); while (stackDirs.Count > 0) { DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop(); try { //Process .\files foreach (FileInfo fileInfo in currentDir.GetFiles()) { stackPaths.Push(fileInfo); } //Process Subdirectories foreach (DirectoryInfo diNext in currentDir.GetDirectories()) stackDirs.Push(diNext); } catch (Exception) {//Might be a system directory } } return stackPaths; } catch (Exception) { throw; } } private static char[] _stSchon = new char[] { '-', '\\', '|', '/' }; } } ```
154,405
Why didn't Voldemort just drop Salazar Slytherin's Locket on the bottom of the Horcrux cave so that when someone was trying to get it and destroy it (Regulus, Harry, Dumbledore),they'd have to swim down deep, only for them to get drowned by hundreds and hundreds of Inferi, thus making their attempt futile at the very least?
2017/03/10
[ "https://scifi.stackexchange.com/questions/154405", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/79438/" ]
Inferi aren't a big deal for an experienced wizard. Fire and heat always works even under water (remember, inferi actually took Harry under water, but Dumbledore's fire acted on them even under water). And, you can survive under water using gillyweed, and lots of spells. Other than that Voldemort chose those locations where he himself could easily reach.
12,991,455
I want to create a `String` from an `ArrayList`. Currently, I am only able to return the last value from the `ArrayList`. My code: ``` eachstep = new ArrayList<String>(); for (int i = 0; i < parsedsteps.size(); i++) { eachstep.add(parsedsteps.get(i).replaceAll("<[^>]*>", "")); } for (int i = 0; i < eachstep.size(); i++) { String directions = i + "."+" "+eachstep.get(i)+"\n"+; } ``` Gives me: ``` 3. This is step 3. ``` Instead of: ``` 1. This is step 1. 2. This is step 2. 3. This is step 3. ``` How do I make my for loop create a `String` with all the values from the `ArrayList`?
2012/10/20
[ "https://Stackoverflow.com/questions/12991455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493755/" ]
You'll need to declare your string outside of the loop, and I suggest using [StringBuilder](http://developer.android.com/reference/java/lang/StringBuilder.html) as well, it's more efficient for building strings like this. ``` StringBuilder directions = new StringBuilder(); for( int i = 0; i < eachstep.size(); i++ ) { directions.append( i + "." + " " + eachstep.get( i ) + "\n" ); } ``` Then when you want to get the string out of the StringBuilder, just call `directions.toString()`.
39,923
I am working on commerce site and we are facing a dilemma that has to do with SEO on product page: if sub-category links should be visible or not in each product page. In detail: We own 8 top categories with lots subcategories in each one and each sub-category owns multiple products. So, my question is: Should the menu of subcategories be visible as they appear in each top category & subcategory or since a product page is supposed to be focused on the product, should the menu be removed? Checking Amazon, Ebay, Etsy and other big commerce sites, they only use the path (breadcrumbs) and they do not show the other subcategories in product pages.
2013/01/08
[ "https://webmasters.stackexchange.com/questions/39923", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/14173/" ]
As an SEO question, the answer is clear: more links between the pages of your site is a good thing. They help customers and bots get around your site, increase the number of links pointing to pages, etc. There's no need to deprive sub-category pages of value in an attempt to improve the performance of product pages. If your page content is properly optimised, categories and products shouldn't be directly competing with each other anyway. But it's not just an SEO question, it's about user experience. Do your users find it easier to get around your site if sub-category links are available on the product pages? If you don't know, consider running some tests using page designs with and without the links in question. Using your analytics software, compare behaviour patterns between the two types. My hunch is that they'd do more good than harm. A product page should indeed be focussed on the product, but removing a means for users to navigate to other pages of your site won't in itself provide that focus. What it almost certainly *will* do is piss off users who find the resulting navigation awkward. Breadcrumbs would help, but only if the user wants to move *up* – not across. And remember, full category and sub-category navigation can be tucked away in a drop-down menu.
6,899
My cat is 3 months old, he's been with us for a month but lately I've observed that sometimes when he's trying to sleep or falling asleep he starts shaking like he's got cold, like shivers. I thought he might have got fever or something like that, we took him to the vet but he said it wasn't nothing, that it was probably normal. I do not doubt of his professionalism (or maybe I do) but this behaviour just seems weird to me (it's the first time I've had a pet). He only shakes when he's trying to sleep. Is this normal? As I said, it shakes like if he's got some chills. EDIT: I know it's normal for him to shake ONCE he is completely asleep. This happens before he gets into REM
2014/12/01
[ "https://pets.stackexchange.com/questions/6899", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/3253/" ]
You may be observing your cat having hypnic jerks. From <http://en.wikipedia.org/wiki/Hypnic_jerk> > > A hypnic jerk, hypnagogic jerk, sleep start, sleep twitch or night > start, is an involuntary twitch which occurs just as a person is > beginning to fall asleep, often causing them to awaken suddenly for a > moment. Physically, hypnic jerks resemble the "jump" experienced by a > person when startled, often accompanied by a falling sensation. > > >
3,972
This subject itself is difficult to google, so I apologize beforehand for the hundreds of links I'm sure are hidden somewhere. This question was moved from the philosophy site as they told me that it fits better here. So, it came with this question: [Is fewer lines of code always better?](https://softwareengineering.stackexchange.com/q/203684/71839), a somewhat subjective question about code (about best practices). Then I thought about it and now I'm really curious about it. I have some questions around this subject itself: 1. Are there other words that show signs of a sentence that, while syntactically correct and apparently right, can be used to clearly see that a sentence might be logically wrong? Always/never in something that makes me read it slowly and double check about the validity of that sentence. 2. Where/how can these words be used? If it's a definition, for example, `always` can be used (as long as it doesn't class with other definitions). But people don't normally talk with pure definitions, and there're many cases (in programming at least) that people overuse the words 'always/never', maybe for laziness or shortness sake. Another example (for programming), 'Global state is evil', which could be reworded as 'Never use global state'.
2013/07/06
[ "https://linguistics.stackexchange.com/questions/3972", "https://linguistics.stackexchange.com", "https://linguistics.stackexchange.com/users/2230/" ]
I don't understand the relationship between the part of your question concerning economy of code lines and special words like "always", but it's possible you can find something of interest in the philosophy of [Nelson Goodman](http://en.wikipedia.org/wiki/Nelson_Goodman), because Goodman dealt with both those matters. The *evaluation metric* in linguistic theory, proposed in Chomsky and Halle's **The Sound Pattern of English** and elsewhere, requires us in our search for the best account of a language system to adopt the theory with the fewest symbols. I have heard that Chomsky was influenced to make such a proposal by Nelson Goodman, who was Chomsky's teacher. Then also, Goodman invented a puzzle which many philosophers have worried about, which involves the superiority of certain words, or at least concepts, in the formulation of scientific laws. See the account of *grue* in the Wikipedia article. *Grue* "applies to all things examined before a certain time t just in case they are green, but also to other things just in case they are blue and not examined before time t." In formulating laws of nature, *green* is better than *grue*, in spite of the fact that before time t statements about what things are grue are empirically indistinguishable from statements about what things are green.
15,168
I am looking for a device that can track my location (lat,long) and speed all day long. Perhaps, I need GPS and accelerometer data bundled together. What I want to do is to log my daily activities. I spend time walking, running, driving, taking a bus, staying in a building, etc., just like any normal human-being :) I am willing to carry the device with me at all times and would like to see every place I go into and my speed at certain positions. My requirements are that the location and speed data should be recorded at least every ~20 seconds. I would also like the device to timestamp (date+time) each record. It would be enough if timestamp is precise to nearest minute and the location can go off about a maximum of 10-15m. (30-50ft.) What I want is a portable device so I can carry all day long for about 2-3 months. I will only use it during casual, daily activities. I don't want real-time tracking. I can collect the data from a storage later on.
2011/09/29
[ "https://gis.stackexchange.com/questions/15168", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/1887/" ]
IBlue 737/747 are great passive GPS collectors. No screen/map (there's your primary power drain... not the GPS). A little bigger than a Matchbox car. Rechargable 23-26hr cell-phone battery. Collects user-selectable items (lat, long, altitude, speed, LDOP, PDOP, etc). Customized collection time or spacing (every x seconds or positino change: 10 feet, 50 feet, etc). The software interface that comes with it is clunky, but works. Exports to various output, including KML. With a little scripting, the txt/csv output can be regurgitated to ArcGIS formats or ??? Unit also can optionally bluetooth the NMEA sentance, so if you have another device with no GPS or a poor(er) quality GPS, this can be used for positioning. Though I wouldn't call it mapping grade (trimble XT/XH), I would say it's better than recreational grade (Garmin handheld units). Like almost any other GPS, doesn't work well in buildings (this is a GPS frequency thing, not a GPS receiver issue). To get passed that, you need to wait on the next generation of GPS, which should penetrate buildings (to a point). I've used my two units just like you are intending. Primarily for vacations. Hasn't let me down in 3 years. Very minor issue with GPS wondering (example: 3 times on a 7700 mile trip for about 4-5 points). But I've seen the same with mapping grade receivers. Likely signal reflection or other GPS signal related anomoly. Otherwise, incredibly perfect for my purposes.
26,008,199
I know the rationale behind nested loops, but this one just make me confused about the reason it wants to reveal: ``` public static LinkedList LinkedSort(LinkedList list) { for(int k = 1; k < list.size(); k++) for(int i = 0; i < list.size() - k; i++) { if(((Birth)list.get(i)).compareTo(((Birth)list.get(i + 1)))>0) { Birth birth = (Birth)list.get(i); list.set( i, (Birth)list.get( i + 1)); list.set(i + 1, birth); } } return list; } ``` Why if i is bigger then i + 1, then swap i and i + 1? I know for this coding, i + 1 equals to k, but then from my view, it is impossible for i greater then k, am i right? And what the run result will be looking like? I'm quite confused what this coding wants to tell me, hope you guys can help me clarify my doubts, thank you.
2014/09/24
[ "https://Stackoverflow.com/questions/26008199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4016507/" ]
This method implements a bubble sort. It reorders the elements in the list in ascending order. The exact data to be ordered by is not revealed in this code, the actual comparison is done in Birth#compare. Lets have a look at the inner loop first. It does the actual sorting. The inner loop iterates over the list, and compares the element at position 0 to the element at position 1, then the element at position 1 to the element at position 2 etc. Each time, if the lower element is larger than the higher one, they are swapped. After the first full run of the inner loop the largest value in the list now sits at the end of the list, since it was always larger than the the value it was compared to, and was always swapped. (try it with some numbers on paper to see what happens) The inner loop now has to run again. It can ignore the last element, since we already know it contains the largest value. After the second run the second largest value is sitting the the second-to-last position. This has to be repeated until the whole list is sorted. This is what the outer loop is doing. It runs the inner loop for the exact number of times to make sure the list is sorted. It also gives the inner loop the last position it has to compare to ignore the part already sorted. This is just an optimization, the inner loop could just ignore k like this: ``` for(int i = 0; i < list.size() - 1; i++) ``` This would give the same result, but would take longer since the inner loop would needlessly compare the already sorted values at the end of the list every time.
33,309,895
Here is my code, I am attempting to use a for loop to take an input from the user in terms of A, B, C, D, or F for 10 students that will then print the total number of A's, B's, C's, D's and F's for the entire class. ``` student = 0 for student in range(0,10): x = (raw_input("Enter grade here: ")).lower() student + 1 print "Count for A's", x.count("a") print "Count for B's", x.count("b") print "Count for C's", x.count("c") print "Count for D's", x.count("d") print "Count for F's", x.count("f") print("Done!") ``` Currently, it only prints the final count. I understand why, I simply am not able to figure out how to put it into a dictionary or a list as I am braindead. Any help is appreciated.
2015/10/23
[ "https://Stackoverflow.com/questions/33309895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5481468/" ]
As written in the [OpenMP specification](http://www.openmp.org/mp-documents/OpenMP4.0.0.pdf) version 4.0, Section 2.14.3: > > A list item that specifies a given variable may not appear in more than one clause on the same directive, except that a variable may be specified in both `firstprivate` and `lastprivate` clauses. > > > It actually makes a lot of sense to allow for that. `firstprivate` affects the value of the list variables on entry into the parallel region, while `lastprivate` affects them on exit from the region. Both are non-conflicting and their combined use allows for certain variables to "propagate" through the region and get their values modified by the parallel code in the same way as in the sequential case. It mostly makes sense with parallel loops.
62,102
I've been riding a single speed to work on a daily basis for about 3 years. I want to learn to ride a fixie. I have a flip-flop, so my fixie ratio is 48/19. I've installed straps (hold fast). My first short ride near home was disappointing. I was riding very slowly. I found it very hard to stop and get my feet out of the straps. I fell over to the side several times at almost zero speed. Obviously, I'm doing something wrong. I have many questions: What is the correct way to fall off the bicycle? Should I start the ride without straps? Should I learn bunny hop and if so, when? Do I need to learn track stand and if so, when? Is there any step by step guide for people who want to enter a fixie world?
2019/05/20
[ "https://bicycles.stackexchange.com/questions/62102", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/34346/" ]
I’ve been riding mostly fixed gear for, oh, maybe ten years now. I use bmx pedals with straps. Straps ------ You really ought to practice getting in and out of them until it becomes second nature. Having problems getting clipped in or getting your foot through the strap means you won’t have a rear brake (not ideal). Having problems getting out means you end up falling when stopping (as you noticed). That could be potentially quite dangerous. Do NOT use any kind of foot fastening system that you need to use your hands to get strapped into or out of! That might be fine on an indoor track, but is a phenomenally bad idea for road riding. If you find your foot getting stuck when pulling it out of the straps, it might be that your straps are too tight or you’re wearing the wrong kind of shoe. When using straps, the best kind of shoe is—in my opinion—canvas shoes with relatively thin soles and without too much pattern, such as Converse. Modern running shoes tend to have quite bulky, grippy soles which means you can get stuck. Classic leather shoes tend to be wide in front and narrow in the middle which means it can be a bit of a struggle to get into the strap. Boots are just a bad idea for cycling, full stop. Try practicing when leaning against something you can hold onto, like a lamp post or a railing; or on ground where falling down doesn’t hurt so much, such as grass. Stopping -------- This is simple: use your front brake. I know the cool kids on their fixies ride brakeless, but honestly, it’s just a bit stupid (or at least reckless). I don’t care how good anyone think they are at stopping their brakeless fixie: the fact of the matter is that the front wheel has much better stopping power than the rear. On a road bikes with front and rear brakes, you still mostly use the front one. Braking at speed adds significant downward force on the front wheel. More downward force means greater braking potential before skidding. On a grippy surfacy (dry road) with decent tyres, your front wheel simply *will not* skid. Even on my gravel bike with very grippy 35 mm tyres, it doesn’t take a lot of braking power to lock up the rear wheel. If you brake hard enough to lock the front wheel, however, you don’t skid—you go over the handlebars. While not ideal, it’s leagues better than going full tilt into a little old lady crossing the road because your rear-brake-only bike just skids. Resisting the forward motion of the drivetrain is great for keeping your balance and controlling your movements at low speeds. When weaving between pedestrians or between lines of cars stuck in traffic, a fixie is terrific. When stopping at a red light, a fixie makes it easier to stay on your pedals (track standing), which means you get a quicker start when the light goes green. But for stopping at high speed, your front brake is your best friend. Beware of pedal strike ---------------------- One thing you need to get a feeling for is cornering. Because the pedals keep spinning even as you lean into the curve, you risk striking the road with your pedal. The faster you go and the tighter the turn, the more you lean over. Striking the ground that way can easily knock you off your balance. Also be wary of other potential obstacles. A few years ago, I hit the side of the pavement with my pedal. The force was enough to lift the rear wheel maybe half a metre off the ground. I rolled maybe 10–15 metres on my front wheel, at around 45 km/h, surrounded by taxis. It was terrifying. Don’t do that.
303,535
I've added abc.sh to /etc/profile.d When I start a new XTerm the environment variables in the abc.sh are not being set in the new XTerm. This works fine if I su - in an existing XTerm.
2011/06/28
[ "https://superuser.com/questions/303535", "https://superuser.com", "https://superuser.com/users/35049/" ]
I believe xterm does not run a login shell by default. Try using "xterm -ls" if you want to read your profile scripts From the xterm man page ``` -ls This option indicates that the shell that is started in the xterm window will be a login shell (i.e., the first character of argv[0] will be a dash, indicating to the shell that it should read the user's .login or .profile). ``` From the bash man page ``` When invoked as an interactive login shell, or a non-interactive shell with the --login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. ```
7,816,513
Ok, in TFS we have a main *trunk* branch and another branch, let's call it *secondary*. We have created a new file in the *trunk* but when trying to merge that specific file, it does not give us the option to merge to the *secondary* branch. We're assuming that it's because an analagous file does not exist in secondary. Is this the cause of the problem and if so, how can we get that new file from the *trunk* into *secondary*? Here, we are merging a file that does exist in *secondary*. As you can see, the dropdown lists all three of our branches (*secondary* is actually the middle one): ![enter image description here](https://i.stack.imgur.com/biOrs.jpg) Now, when I try to merge a file which was created in *trunk* after *secondary* was branched, *secondary* is no longer listed as a target branch. ![enter image description here](https://i.stack.imgur.com/M9o1W.jpg)
2011/10/19
[ "https://Stackoverflow.com/questions/7816513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735374/" ]
I think this should be possible over the VS GUI as follows: Select the folder where the new file was added and order a merge (of the whole folder) to your *secondary* branch. Now all changed files of the folder appear in your pending list + your new file. Undo all other files & proceed with checking in only the one file that matters. One could argue that this restriction of TFS in fact makes sense: * If you 've made additional changes to the files you 're hereby protected from breaking your *secondary* branch. * If you haven't made additional changes to any other files, it still makes sense to merge your, since the merge will only contain your new file.
2,009,593
I have a Compact Framework Project that has two Unit Test projects with it in the solution. One is a Smart Device Unit Test Project (needs the emulator to run). The other is a normal Unit Test Project. The normal Unit Test Project runs fine on my machine and on the build machine, but on my co-worker's machine it tries to launch the emulator then fails the tests. He has tried doing a checkout of changeset 1 then deleting the folder then checking out and running the test but it still tries to launch the emulator. Because both the build machine and my computer work just fine, I am guessing that this is some setting that he may have on his machine. Any ideas? (using visual studio 2008 and mstest)
2010/01/05
[ "https://Stackoverflow.com/questions/2009593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16241/" ]
It may be because of the solution's debug settings. If you right-click on the solution in Solution Explorer and select *Properties*, there's a node called *Startup Project*. The settings in this dialog are kept in the solution's .suo file, which is normally not checked in to source control. It may be this or one of the other nodes in this Solution Properties dialog that defines the difference.
47,566,116
I have a nested arrays, I need to create two new arrays one for the even numbers and the other is for odd numbers using nested for loop. I used push method but the result was that every number was in a separate array while I need all even numbers to be set in a single array and the same for the odd numbers. Here is my code: ``` var numbers = [ [243, 12, 23, 12, 45, 45, 78, 66, 223, 3], [34, 2, 1, 553, 23, 4, 66, 23, 4, 55], [67, 56, 45, 553, 44, 55, 5, 428, 452, 3], [12, 31, 55, 445, 79, 44, 674, 224, 4, 21], [4, 2, 3, 52, 13, 51, 44, 1, 67, 5], [5, 65, 4, 5, 5, 6, 5, 43, 23, 4424], [74, 532, 6, 7, 35, 17, 89, 43, 43, 66], [53, 6, 89, 10, 23, 52, 111, 44, 109, 80], [67, 6, 53, 537, 2, 168, 16, 2, 1, 8], [76, 7, 9, 6, 3, 73, 77, 100, 56, 100] ]; for (var x = 0; x < numbers.length; x++) { for (var y = 0; y < numbers[x].length; y++) { if (numbers[x][y] % 2 === 0) { var even = []; even.push(numbers[x][y]); } else { var odd = []; odd.push(numbers[x][y]); } console.log(odd); } ```
2017/11/30
[ "https://Stackoverflow.com/questions/47566116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7974727/" ]
Edit: I came up with a better solution, partially inspired by [this answer below](https://stackoverflow.com/a/47601368/5087436). I thought of this method originally (as noted in the OP comments) but I decided against it. The original image was just not good enough quality for it. However I improved that method and it works *brilliantly* for the better quality image. The original approach is first, and then the new approach at the bottom. --- First approach ============== So here's a general approach that seems to work well, but definitely just gives estimates. This assumes that circles are roughly the same size. First, the image is mostly blue---so it seems reasonable to just do the analysis on the blue channel. Thresholding the blue channel, in this case, using Otsu thresholding (which determines an optimal threshold value without input) seems to work very well. This isn't too much of a surprise since the distribution of color values is pretty much binary. Check the mask that results from it! [![Mask](https://i.stack.imgur.com/r2TI2.png)](https://i.stack.imgur.com/r2TI2.png) Then, do a connected component analysis on the mask to get the area of each component (component = white blob in the mask). The statistics returned from [`connectedComponentsWithStats()`](https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#connectedcomponents) give (among other things) the area, which is exactly what we need. Then we can simply count the circles by estimating how many circles fit in a given component based on its area. Also note that I'm taking the statistics for every label except the first one: this is the background label `0`, and not any of the white blobs. Now, how large in area is a single circle? It would be best to let the data tell us. So you could compute a histogram of all the areas, and since there are more single circles than anything else, there will be a high concentration around 250-270 pixels or so for the area. Or you could just take an average of all the areas between something like 50 and 350 which should also get you in a similar ballpark. [![Histogram](https://i.stack.imgur.com/lEh4V.png)](https://i.stack.imgur.com/lEh4V.png) Really in this histogram you can see the demarcations between single circles, double circles, triple, and so on quite easily. Only the larger components will give pretty rough estimates. And in fact, the area doesn't seem to scale exactly linearly. Blobs of two circles are slightly larger than two single circles, and blobs of three are larger still than three single circles, and so on, so this makes it a little difficult to estimate nicely, but rounding should still keep us close. If you want you could include a small multiplication parameter that increases as the area increases to account for that, but that would be hard to quantify without going through the histogram analytically...so, I didn't worry about this. A single circle area divided by the average single circle area should be close to 1. And the area of a 5-circle group divided by the average circle area should be close to 5. And this also means that small insignificant components, that are 1 or 10 or even 100 pixels in area, will not count towards the total since `round(50/avg_circle_size) < 1/2`, so those will round down to a count of 0. Thus I should just be able to take all the component areas, divide them by the average circle size, round, and get to a decent estimate by summing them all up. ``` import cv2 import numpy as np img = cv2.imread('circles.png') mask = cv2.threshold(img[:, :, 0], 255, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] stats = cv2.connectedComponentsWithStats(mask, 8)[2] label_area = stats[1:, cv2.CC_STAT_AREA] min_area, max_area = 50, 350 # min/max for a single circle singular_mask = (min_area < label_area) & (label_area <= max_area) circle_area = np.mean(label_area[singular_mask]) n_circles = int(np.sum(np.round(label_area / circle_area))) print('Total circles:', n_circles) ``` This code is simple and effective for rough counts. However, there are definitely some assumptions here about the groups of circles compared to a normal circle size, and there are issues where circles that are at the boundaries will not be counted correctly (these aren't well defined---a two circle blob that is half cut off will look more like one circle---no clear way to count or not count these with this method). Further I just used automatic thresholding via Otsu here; you could get (probably better) results with more careful color filtering. Additionally in the mask generated by Otsu, some circles that are masked have a few pixels removed from their center. Morphology could add these pixels back in, which would give you a (slightly larger) more accurate area for the single circle components. Either way, I just wanted to give the general idea towards how you could easily estimate this with minimal code. --- New approach ============ Before, the goal was to count circles. This new approach instead counts the *centers* of the circles. The general idea is you threshold and then flood fill from a background pixel to fill in the background (flood fill works like the paint bucket tool in photo editing apps), that way you only see the centers, as shown in [this answer below](https://stackoverflow.com/a/47601368/5087436). However, this relies on global thresholding, which isn't robust to local lighting changes. This means that since some centers are brighter/darker than others, you won't always get good results with a single threshold. Here I've created an animation to show looping through different threshold values; watch as some centers appear and disappear at different times, meaning you get different counts depending on the threshold you choose (this is just a small patch of the image, it happens everywhere): [![Varying threshold levels](https://i.stack.imgur.com/Ep3hg.gif)](https://i.stack.imgur.com/Ep3hg.gif) Notice that the first blob to appear in the top left actually disappears as the threshold increases. However, if we actually OR each frame together, then each detected pixel persists: [![Bitwise OR](https://i.stack.imgur.com/k5CN6.gif)](https://i.stack.imgur.com/k5CN6.gif) But now every single speck appears, so we should clean up the mask each frame so that we remove single pixels as they come (otherwise they may build up and be hard to remove later). Simple [morphological opening](https://docs.opencv.org/trunk/d9/d61/tutorial_py_morphological_ops.html) with a small kernel will remove them: [![Opening to remove small pieces](https://i.stack.imgur.com/sdA3x.gif)](https://i.stack.imgur.com/sdA3x.gif) Applied over the whole image, this method works *incredibly well* and finds almost every single cell. There are only three false positives (detected blob that's not a center) and two misses I can spot, and the code is very simple. The final thing to do after the mask has been created is simply count the components, minus one for the background. The only user input required here is a single point to flood fill from that is in the background (`seed_pt` in the code). [![Detected centers](https://i.stack.imgur.com/gNuXB.jpg)](https://i.stack.imgur.com/gNuXB.jpg) ``` img = cv2.imread('circles.png', 0) seed_pt = (25, 25) fill_color = 0 mask = np.zeros_like(img) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) for th in range(60, 120): prev_mask = mask.copy() mask = cv2.threshold(img, th, 255, cv2.THRESH_BINARY)[1] mask = cv2.floodFill(mask, None, seed_pt, fill_color)[1] mask = cv2.bitwise_or(mask, prev_mask) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) n_centers = cv2.connectedComponents(mask)[0] - 1 print('There are %d cells in the image.'%n_centers) ``` > > There are 874 cells in the image. > > >
11,209,786
I have three possible designs and I'm trying to determine which one is better and in which cases they would be better. The general idea of all the designs is that there is a data object that stores some data and there is an analyzer object that analyzes the data. I need to choose between these designs and I like Design 2 the best. However, a developer I'm working with is pushing for Design 3, which I think is the worst. Are there any advantages or disadvantages I'm missing for any of the designs? Let me know if clarification is needed. Design 1 -------- ![Design 1](https://i.stack.imgur.com/kRLIc.jpg) In design 1, DataAnalyzer has a Data object that is supplied during construction. When the client calls `dataAnalyzer.analyze()`, the data is analyzed. In this design, each objects responsibility is clear; The Data object simply holds data and the DataAnalyzer object analyzes data. Changing the data stored will only change the Data class and adding types of analysis methods will only change the DataAnalyzer class. One problem with this design is that the DataAnalyzer object can only be used for the Data object passed in during construction, so if there are lots of data objects, lots of DataAnalyzers need to be created. Another disadvantage (which will be clearer from Design 3) is that the client needs to know about two classes instead of just one. If there are more classes that have an association with Data, the client will have to work will all of these classes. Design 2 -------- ![Design 2](https://i.stack.imgur.com/xm4ZD.jpg) Design 2 is very similar to design 1, except now DataAnalyzer is reusable (for different data objects). The client still has to work with two classes as opposed to one as in design 3. The responsibilities are still very clear and maintenance is easy. Design3 ------- ![Design3](https://i.stack.imgur.com/Vp9FX.jpg) Design 3 allows the client to work with one object. The client can say `data.analyze()` and not know anything about the DataAnalyzer. I'm not sure if this violates the single responsibility rule; the Data object has an interface that allows analysis, but the responsibility is really delegated to DataAnalyzer. Another issue is that a DataAnalyzer is created for every Data object created, regardless of whether the Data needs to be analyzed or not. Now if more functionality was added, a lot of things would change. If a DataPrinter class was created (let's assume this is better than having the data print the data itself), the client wouldn't have to worry about creating a dataPrinter object and calling `dataPrinter.printData()`, it could just call `data.print()`. However, by adding this class I had to change the interface of Data. Adding more methods to any of the DataXX classes causes methods to be added to the Data class.
2012/06/26
[ "https://Stackoverflow.com/questions/11209786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803801/" ]
**Design 1** is useful if the analysis takes a long time or a lot of resources and you can use some sort of caching to make sequential analyses on the same data run faster (or with less resources). - Use this if you need to store intermediate results or cache final results per instance of data you are analyzing. **Design 2** is useful if you want a static, thread safe analyzer which can be called over and over for different data and does not require resources to do it or can obtain different resources per request from a pool of resources. If you have various data types (with the same base class or interface), you could use the visitor pattern, dependency injection, reflection or a command pattern to reach the correct concrete data analyzer class from the main one and thus not violate the single responsibility principle. **Design 3** is a bad idea, because it means you are coupling your data type with a processing done on it - each time you want to add or change a processing you will curse your decision if you decide to use this design :-) In some languages, such as in C# 3.0+, there is a [sugar syntax](http://en.wikipedia.org/wiki/Extension_method) which can make the operation of Design 2 work using the syntax of design 3.
73,838,503
I have a `.yaml` file like this: ```yaml title: 'We'll do cool stuff' draft: true ``` However, I get the following error: ```none Error parsing YAML: YAMLException: can not read a block mapping entry; a multiline key may not be an implicit key at line 2, column 6: draft: true ^ ``` How can I fix it? **Note**: this setup seems different than the other questions where this same error was raised, including the following posts: * [Error parsing YAML](https://stackoverflow.com/q/68343620/1366033) * [Getting following error on serverless.yaml](https://stackoverflow.com/q/55939474/1366033) * [yaml syntax issues?](https://stackoverflow.com/q/68039278/1366033)
2022/09/24
[ "https://Stackoverflow.com/questions/73838503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366033/" ]
You can use a site like [YAML Formatter](https://jsonformatter.org/yaml-formatter) to format and *validate* your yaml: [![yaml formatter example](https://i.stack.imgur.com/QWVbH.png)](https://i.stack.imgur.com/QWVbH.png) In this case, the error message and location is a bit of red-herring. The error is actually caused by a string that was accidentally terminated because of an unescaped quote symbol within the string. A hint for this is the syntax highlighting of `'***We***'ll do cool stuff'`. To fix, in this case, you can just skip wrapping the string quotes and rewrite like this: ```yaml title: We'll do cool stuff draft: true ``` ### Further Reading * [Do I need quotes for strings in YAML?](https://stackoverflow.com/q/19109912/1366033) * [How to escape double and single quotes in YAML](https://stackoverflow.com/q/37427498/1366033)
37,518,759
From my activity when i call Contacts to get a contact number the application crashed. Application is running ok on other devices but when i'm try to run it in android 6.0, it crashed. i've no idea what i'm doing wrong. ``` Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); ``` After getting the the data in `onActivityResult` method. ``` @Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); switch (reqCode) { case (PICK_CONTACT) : if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = this.getContentResolver().query(contactData, null, null, null, null); if (c.moveToFirst()) { String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)); String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); Log.d(TAG, "name : "+name+" , Phone Number : "+ phoneNumber); } } break; } } ``` can Anyone help me ?
2016/05/30
[ "https://Stackoverflow.com/questions/37518759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
All of the answers here are wrong. You shouldn't need `READ_CONTACT` permission at all to retrieve single contact using `ACTION_PICK` intent. You should be granted this permission temporary to be able to retrieve contact specific data. However there are some devices that don't implement this API in a good way. Myself I have found Sony Xperia Z3, but I heard about HTC devices also had this problem. > > To have the user select a contact and provide your app access to all the contact information, use the ACTION\_PICK action and specify the MIME type to Contacts.CONTENT\_TYPE. > > > The result Intent delivered to your onActivityResult() callback contains the content: URI pointing to the selected contact. **The response grants your app temporary permissions to read that contact using the Contacts Provider API even if your app does not include the READ\_CONTACTS permission.** > > > Source: <https://developer.android.com/guide/components/intents-common.html#Contacts> **[UPDATE]** After upgrading Sony Xperia Z3 system image to version `23.5.A.1.291` bug does not occur anymore.
609,780
Installed `runit` in Debian 7.4 in a Vagrant. My run script is working, but the moment I create a service/pants/log/ directory I start getting the following error: `unable to open supervise/ok`. My service continues to run but nothing gets logged. I've tried two different services and both have the same issue. I've tried various different service/pants/log/run scripts (mostly using svlogd), I've tried changing permissions on everything (a+rwx), the directory to store logs in exists and has the same permissions. If I run svlogd straight off the commandline it works as expected. The bash log below shows what happens as I rename `/etc/service/pants/_log` to `/etc/service/pants/log` and back again `/etc/service/pants/_log`. ``` root@vwb-debian-wheezy:/etc/service# sv s pants/ run: pants/: (pid 29260) 44931s root@vwb-debian-wheezy:/etc/service# mv pants/{_,}log/ root@vwb-debian-wheezy:/etc/service# sv s pants/ run: pants/: (pid 29260) 44963swarning: pants/: unable to open supervise/ok: file does not exist ; run: log: (pid 29260) 44963s root@vwb-debian-wheezy:/etc/service# cat pants/log/run #!/bin/sh exec svlogd -ttt /var/log/service/pants/ root@vwb-debian-wheezy:/etc/service# ll pants/ total 12 drwxrwxrwx 2 root root 4096 Jul 3 07:00 log -rwxrwxrwx 1 root root 442 Jul 3 06:58 run drwxrwxrwx 2 root root 4096 Jul 2 18:59 supervise root@vwb-debian-wheezy:/etc/service# ll /var/log/service/ total 8 drwxrwxrwx 2 root root 4096 Jul 2 16:55 pants root@vwb-debian-wheezy:/etc/service# mv pants/{,_}log/ root@vwb-debian-wheezy:/etc/service# sv s pants/ run: pants/: (pid 29260) 45105s ```
2014/07/03
[ "https://serverfault.com/questions/609780", "https://serverfault.com", "https://serverfault.com/users/34871/" ]
Create the `run` files in `/etc/sv/pants/` not `/etc/service/pants/`. Then a symlink should be created in `/etc/service` to `/etc/sv/pants` to activate the service. ``` ln -s /etc/sv/pants /etc/service/ ``` While creating the files directly in `/etc/service` works for just the service, it seems to cause problems when using logging as well. A service can be deactivated by deleting the symlink in `/etc/service/`.
52,092,036
I'm working on a page that accepts 4 digits (exactly 4 digits) pin from users. Something like this. ``` <input type="number" ng-model="passCode" class="form-control" onpaste="return false" id="passCodeField" ng-disabled="!enablePassCode" ng-change="onInputPasscode()" ng-keypress="onKeyPressPasscode($event)"/> ``` onKeyPressPasscode function ``` $scope.onKeyPressPasscode = function($event) { if(isNaN(String.fromCharCode($event.which || $event.keyCode))){ $event.preventDefault(); } } ``` onInputPasscode() function : ``` $scope.onInputPasscode = function() { if ($scope.passCode.toString().length > 4){ $scope.passCode = $scope.passcode; } if($scope.passCode.toString().length == 4) { $scope.passcode = $scope.passCode; $scope.disableContinue = false; session.put('pinFlow',true); } else { console.log("current length - " + $scope.passCode); $scope.disableContinue = true; session.put('pinFlow',false); } } ``` This is failing when the input is all zeros. i.e current length is not getting updated hence the user is allowed input as many zeros as he wants. How do I take 4 digit zeros as input and still meet the checks that I have? ![debugging image](https://i.stack.imgur.com/pyCjp.png) This is in angular 1.5.8v. And I'm not an expert in `AngularJS`. So any help would be appreciated. Also, please let me know if need any other info. I'll update the answer accordingly. Thanks in advance.
2018/08/30
[ "https://Stackoverflow.com/questions/52092036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3694000/" ]
It's not possible to do this with a an input with `type` set to `number`. When user enters a number `0001`, that's actually `1`. Things like PINs should be handled with `type` set to `text`. You can then use a regex for validation. To allow exactly four digits, no more and no less, use the following regex: ``` ^\d{4,4}$ ``` From JavaScript, use this regex to test a string, like the following: ``` /^\d{4,4}$/.test('1234') // => true /^\d{4,4}$/.test('123456') // => false /^\d{4,4}$/.test('12') // => false ```
23,817
I'm in an upstart metal band and, currently, we have little recording equipment. Because I work in video production, I have some audio software on my computer for the occasions that I need it (Cakewalk Sonar & Reason), so I am the one who will be recording and processing our demos. I really don't know what kind of mic, pre-amp, or software effects lend to the classic heavy metal sound (think metallica, judas priest, testament) in a recording environment. This is only for demos, so it doesn't need to sound pro... but I want to do the best I can for under $2k. Any suggestions?
2011/07/06
[ "https://sound.stackexchange.com/questions/23817", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/-1/" ]
I would like to offer a counter argument. Overdriving a preamp or adding distortion to the vocal does not make a vocal sound like Metallica or Judas Priest. Those vocals are warm and clear as a bell. Even Brian Johnson's vocals are recorded as clean as possible (Mutt Lang influence). If I have only two grand to spend for my vocal chain, I would get a decent mic, a great pre and eq, and an awesome compressor. You are going to want to get as strong and consistent of a signal onto your track as possible, and a compressor is vital for that. Your mic is going to need some serious headroom. The pre will add warmth and the eq will let you notch out any clashing frequencies. I would add any overdrive or blatant effect after the fact so you can control its strength. Distortion on vocals sounds cool until it starts to cancel out your guitar's distortion. If you want specific brand and model recommendations, message me. And as always, this is just my 2 cents.
46,258
It is my understanding that in regular conditions when using an SLR camera (No live-view) , the camera lifts the mirror to let the light hit the sensor. But while in Live-View, the mirror is already locked-up, so, at the time you press the shutter button, why the need to lower the mirror, and immediately lift it again just before exposure?
2013/12/26
[ "https://photo.stackexchange.com/questions/46258", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/22677/" ]
Two possibilities, focusing and metering. Often when shooting in live view, the mirror snaps down to use the phase detect auto-focus, then snaps back up to take the image and remains up to keep live view going. If your camera supports using only contrast based auto-focus, then you can avoid that cycle. Similarly, it may want to use the light metering capabilities that are available when the mirror is down, depending on how well the sensor can meter for itself as well. In either case, it is often a setting that can be adjusted in the menus. I know my 5D Mark iii has a setting that will allow the photo to be taken directly in LiveView without the mirror flipping down.
14,242,735
I stumbled across a very odd issue when running a program compiled for MIPS. The following snippet of code is to get the time epoch and store it in microsecond-precision in an `unsigned long long` variable. The variable is capable of storing 8 bytes which I checked with `sizeof(unsigned long long)`. This code prints out weirdly: ``` unsigned long long microtime=0; struct timeval time_camera = { .tv_sec=0, .tv_usec=0 }; gettimeofday(&time_camera,NULL); microtime = time_camera.tv_sec * 1000000 + time_camera.tv_usec; printf("Times is now %llu , time since epoch in seconds is: %lu\n", microtime, time_camera.tv_sec); ``` It gives me the following output: ``` >> Times is now 484305845 , time since epoch in seconds is: 1357751315 ``` However, when I break the calculation into different lines, it works! : ``` unsigned long long microtime=0; struct timeval time_camera = { .tv_sec=0, .tv_usec=0 }; gettimeofday(&time_camera,NULL); microtime = time_camera.tv_sec; microtime = microtime * 1000000; microtime = microtime + time_camera.tv_usec; printf("Times is now %llu , time since epoch in seconds is: %lu\n", microtime, time_camera.tv_sec); ``` Output is: ``` Times is now 1357751437422143 , time since epoch in seconds is: 1357751437 ``` Now is it just a coincidence that this works ? e.g have I corrupted memory or actually exceeded it somewhere? Perhaps it's the MIPS compilator? Any help is appreciated!
2013/01/09
[ "https://Stackoverflow.com/questions/14242735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/495782/" ]
``` microtime = time_camera.tv_sec * 1000000 + time_camera.tv_usec; ``` `tv_sec` is a smaller integer type (`time_t`, probably `int` or `long`), so ``` time_camera.tv_sec * 1000000 ``` overflows. Use a suffix to give the constant the appropriate type ``` time_camera.tv_sec * 1000000ULL ``` In ``` microtime = time_camera.tv_sec; microtime = microtime * 1000000; ``` the multiplication is performed at `unsigned long long`, since one operand (`microtime`) already has that type, so the other is converted to that.