text
stringlengths
64
81.1k
meta
dict
Q: PDE for Wave Equation I have a boundary value problem $u_{tt}$ + $u$ = $u_{xx}$ ; $0$ < $x$ < $\pi$, $t$ > $0$ $u(0, t)$ = $u(\pi, t)$ = $0$ $u(x, 0) = 0, u(x, 4) = 0, 0 < x < 2$ I want to find the solution for this BVP using the method of separation of varables. In other BVP problems using the method to solve, their form was like $u_{tt} = u_{xx}$, so I was able to transform them into $X^{''} + \lambda X = 0$ and $T^{''} + \lambda T = 0$ by letting $u(x, t) = X(x)T(t)$. However, in the problem above, we have three terms, $u_{tt}, u, u_{xx}$, so I was not able to solve this problem using the method I suggested. How can I deal with that $u$ in the $u_{tt}$ + $u$ = $u_{xx}$? A: Suppose there are functions $T$ and $X$ such that $u(x,t) = X(x)T(t)$ for all $t$ and $x$. Then $u_{tt}(x,t) = X(x)T''(t)$ and $u_{xx}(x,t) = X''(x)T(t)$, so the equation $u_{tt} + u = u_{xx}$ becomes $$ XT'' + XT = X''T. $$ Dividing this equation by $XT$, we get $$ \frac{T''}{T} + 1 = \frac{X''}{X}. $$ Note that the left-hand side is a function of $t$ only whereas the right-hand side is a function of $x$ only. Now $-$ this is the entire point of the separation of variables $-$ the only situation where a function of $t$ can be always equal to a function of $x$ up to a constant is when both functions are constants. Hence, we can introduce here a constant $\lambda$ such that $$ \frac{T''}{T} + 1 = \frac{X''}{X} = \lambda. $$ Now the partial differential equation becomes the system of ordinary differential equations $$ \left\{ \begin{array}{l} X'' - \lambda X = 0, \\ T'' - (\lambda - 1) T = 0, \end{array} \right. $$ which can be solved as usual.
{ "pile_set_name": "StackExchange" }
Q: Dungeon Generation with no corridors and room dependencies I'm making a game with a procedurally generated world created at the beginning of the game, consisting of several areas represented by grids (say, 8x8, 9x6, the sizes would ideally be arbitrary). These areas are supposed to be connected to each other through a dependency list. A connection exists when at least 3 spaces of that grid are exposed between those two areas. In the middle cell of that 3 space connection area is the doorway between areas: I've been trying to figure out a way to connect them, but it becomes increasingly complex the more areas you need to consider at the same time. I've tried some paper prototyping and while it's a very simple process when doing it visually, I haven't found out a good set of mathematical expressions that allows me to place rooms with the same efficiency by code. Here's a "simple" example I'm struggling with right now: Area 'a' needs to be connected to 'b' and 'c' Area 'b' needs to be connected to 'a' and 'd' Area 'c' needs to be connected to 'a' and 'd' Area 'd' needs to be connected to 'b' and 'c' Consider, for simplicity, we're placing the rooms by their order of appearance on the list (I've tried others). So I'm approaching this as your standard procedural Dungeon Generation algorithm. We place 'a' anywhere on the board, since it's the first area. Next, we pick a wall at random and, since nothing is connected to that wall, we can place 'b' there: Now we need to place 'c', but 'a' is already on the board, and has an occupied wall, so we decide to put it on another wall. But not every placement will do, because 'd' is coming up and it needs to be connected to 'b' and 'c' too: I tried a possible limitation that 2 rooms that have the same set of dependencies cannot be on opposite walls, but even that doesn't guarantee success: And in other cases, where the areas have different sizes, being on opposite walls can work: Also, not considering a used wall is a flawed assumption since it rules out valid solutions: I've tried looking up research on other Procedural Generation algorithms or similar, such as Optimal Rectangle Packing and Graph Layout algorithms, but usually those algorithms don't take into account every constraint of this problem and are hard to mix together. I thought about a bunch of approaches, including placing an area and backtrack until a suitable placement is found, but they seem very dependent on trial and error and costly in terms of computation. But, given the extensive research on the last two problems I mentioned, it might be the only/best solution? I just wanted to see if someone has had similar problems in the past or is willing to help me figure this out and give me a few pointers on where I should start with the algorithm. Or, failing that, I'll have to look into loosening the constraints I've set. A: Your generation priorities are in conflict. When generating levels, your first goal should be a web of planar (non-overlapping), connected points, irrespective of scale. Then proceed to create rooms from the points within that web. Creating room shapes first is a mistake, generally speaking. Create connectivity first, and then see what room forms can be accommodated within that. General Algorithm Create a quantised floor grid of sufficient size to support your level, using a 2D array or image. Scatter points at random across this empty floor space. You can use a plain random check on each tile to see whether it gets a point, or use standard / Gaussian distribution to scatter points. Assign a unique colour / numeric value to each and every point. These are IDs. (P.S. If after this step you feel you need to scale your space up, by all means, do.) For each such generated point, in sequence, incrementally grow a bounds circle or bounds rectangle out by a single step (typically a rate of 0.5-1.0 cells/pixels per step) in x and y. You can either grow all bounds in parallel, all starting from size zero at the same step, or you can start growing them at different times and at different rates, giving bias to the size of those that start earlier (imagine seedlings growing, where some start late). By "grow" I mean fill in the newly-incremented bounds with the colour / ID unique to the starting point for those bounds. A metaphor for this would be holding marker pens against the back of a piece of paper, and watching inkblots of different colours grow, until they meet. At some point the bounds of some point and another point are going to collide, during the grow step. This is the point at which you should stop growing the bounds for those two points -- at least in the uniform sense described in step 3. Once you've grown all points' bounds as far as possible and stopped all growth processes, you will have a map that should be largely, but not entirely filled. You may now want to pack up those empty space, which I will assume to be white, as if colouring in a sheet of paper. Post-process Space-filling A variety of techniques can be used to fill in the empty / white spaces that remain, per step 5: Have a single neighbouring, already-coloured area claim the space, by flood filling it that colour so it all joins up. Flood with new, as-yet-unused colours / numbers / IDs, such that they form entirely new areas. Round robin approach such that each already-filled neighbouring area "grows" a little bit into the empty space. Think of animals drinking around a watering hole: they all get some of the water. Don't totally fill the empty space, just cross it to link up existing areas using straight passages. Perturbation As a final step to make things look more organic, you could do edge-perturbation in varying degrees, on the edges cells of areas. Just be sure not to block crucial movement routes. Theory, for Interest's Sake This is similar to the approach taken in Voronoi Diagrams / Delaunay Triangulation, except that in the above you are not explicitly creating edges -- instead, when bounding areas collide, growth ceases. You will notice that Voronoi Diagrams are space-filling; this is because they do not cease growth merely on touching, but rather on some nominal degree of overlap. You could try similar. A: This is a cool problem. I believe it can be solved using action planning in the space of room placements. Define the State of the world as follows: //State: // A list of room states. // Room state: // - Does room exist? // - Where is room's location? // - What is the room's size? Define a Constraint as: // Constraint(<1>, <2>): // - If room <1> and <2> exist, Room <1> is adjacent to Room <2> Where "adjacent" is as you described (sharing at least 3 neighbors) A Constraint is said to be invalidated whenever the two rooms are not adjacent, and both rooms exist. Define a State to be valid when: // foreach Constraint: // The Constraint is "not invalidated". // foreach Room: // The room does not intersect another room. Define an Action as a placement of a room, given a current State. The Action is valid whenever the resulting state from the action is valid. Therefore, we can generate a list of actions for each state: // Returns a list of valid actions from the current state function List<Action> GetValidActions(State current, List<Constraint> constraints): List<Action> actions = new List<Action>(); // For each non-existent room.. foreach Room room in current.Rooms: if(!room.Exists) // Try to put it at every possible location foreach Position position in Dungeon: State next = current.PlaceRoom(room, position) // If the next state is valid, we add that action to the list. if(next.IsValid(constraints)) actions.Add(new Action(room, position)); Now, what you're left with is a graph, where States are nodes, and Actions are links. The goal is to find a State which is both valid, and all of the rooms have been placed. We can find a valid placement by searching through the graph in an arbitrary way, perhaps using a depth-first search. The search will look something like this: // Given a start state (with all rooms set to *not exist*), and a set of // constraints, finds a valid end state where all the constraints are met, // using a depth-first search. // Notice that this gives you the power to pre-define the starting conditions // of the search, to for instance define some key areas of your dungeon by hand. function State GetFinalState(State start, List<Constraint> constraints) Stack<State> stateStack = new Stack<State>(); State current = start; stateStack.push(start); while not stateStack.IsEmpty(): current = stateStack.pop(); // Consider a new state to expand from. if not current.checked: current.checked = true; // If the state meets all the constraints, we found a solution! if(current.IsValid(constraints) and current.AllRoomsExist()): return current; // Otherwise, get all the valid actions List<Action> actions = GetValidActions(current, constraints); // Add the resulting state to the stack. foreach Action action in actions: State next = current.PlaceRoom(action.room, action.position); stateStack.push(next); // If the stack is completely empty, there is no solution! return NO_SOLUTION; Now the quality of the dungeon generated will depend on the order in which rooms and actions are considered. You can get interesting and different results probably by just randomly permuting the actions you take at each stage, thereby doing a random walk through the state-action graph. The search efficiency will greatly depend on how quickly you can reject invalid states. It may help to generate valid states from the constraints whenever you want to find valid actions.
{ "pile_set_name": "StackExchange" }
Q: Criar JSONArray com objetos? Eu tenho 2 classes: Venda e ItemVenda. Eu quero criar um JSONArray com todas as minhas vendas e seus itens. Estou tentando usar o JSONObject com JSONArray para criar isso mas não estou conseguindo fazer. Por exemplo: Venda:{id:1, data:2015-09-28, cliente_id:1}, ItemVenda:[{produto:5, quantidade:10, valorUnitario:5.00, totalItem:50.00}, {produto:21, quantidade:1, valorUnitario:5.00, totalItem:5.00}], Venda:{id:33, data:2015-08-28, cliente_id:15}, ItemVenda:[{produto:42, quantidade:1, valorUnitario:10.00, totalItem:10.00}, {produto:61, quantidade:2, valorUnitario:25.00, totalItem:50.00}] No exemplo tenho 2 vendas com seus respectivos itens. Como posso fazer isso ? Estou tentando assim. private JSONObject getJSONObjectToSend(){ JSONObject jsonVendas = new JSONObject(); JSONArray jsonArrayVenda = new JSONArray(); JSONArray jsonArrayItems = new JSONArray(); VendaPersist vp = new VendaPersist(getActivity()); //lista de vendas List<Venda> lista = vp.getAllVendasFinalizadas(); try { if(lista.size() > 0){ for(Venda v : lista){ JSONObject jsonObjectVenda = new JSONObject(); //venda jsonObjectVenda.put("dataVenda", new SimpleDateFormat("yyyy-MM-dd").format(v.getDataVenda())); jsonObjectVenda.put("cliente", v.getCliente().getId_ws()); jsonObjectVenda.put("usuario", v.getIdUsuario()); jsonArrayVenda.put(jsonObjectVenda); //itens venda for(ItemVenda iv : v.getListaItems()){ JSONObject jsonObjectIV = new JSONObject(); jsonObjectIV.put("produto", iv.getProduto().getId_ws()); jsonObjectIV.put("quantidade", iv.getQuantidade()); jsonObjectIV.put("valorUnitario", iv.getValorUnitario()); jsonObjectIV.put("valorTotal", iv.getTotalItem()); jsonArrayItems.put(jsonObjectIV); } jsonArrayVenda.put(jsonArrayItems); jsonVendas.put("Venda", jsonArrayVenda); } } } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); } return jsonVendas; } A: Acho que o correto seria o array de ItemVenda estar dentro do objeto Venda Venda:[{id:1, data:2015-09-28, cliente_id:1, ItemVenda:[{produto:5, quantidade:10, valorUnitario:5.00, totalItem:50.00}, {produto:21, quantidade:1, valorUnitario:5.00, totalItem:5.00}]}, {id:33, data:2015-08-28, cliente_id:15, ItemVenda:[{produto:42, quantidade:1, valorUnitario:10.00, totalItem:10.00}, {produto:61, quantidade:2, valorUnitario:25.00, totalItem:50.00}]}] Código: private JSONObject getJSONObjectToSend(){ JSONObject jsonVendas = new JSONObject(); JSONArray jsonArrayVenda = new JSONArray(); VendaPersist vp = new VendaPersist(getActivity()); //lista de vendas List<Venda> lista = vp.getAllVendasFinalizadas(); try { if(lista.size() > 0){ for(Venda v : lista){ JSONObject jsonObjectVenda = new JSONObject(); //venda jsonObjectVenda.put("dataVenda", new SimpleDateFormat("yyyy-MM-dd").format(v.getDataVenda())); jsonObjectVenda.put("cliente", v.getCliente().getId_ws()); jsonObjectVenda.put("usuario", v.getIdUsuario()); //itens venda JSONArray jsonArrayItems = new JSONArray(); for(ItemVenda iv : v.getListaItems()){ JSONObject jsonObjectIV = new JSONObject(); jsonObjectIV.put("produto", iv.getProduto().getId_ws()); jsonObjectIV.put("quantidade", iv.getQuantidade()); jsonObjectIV.put("valorUnitario", iv.getValorUnitario()); jsonObjectIV.put("valorTotal", iv.getTotalItem()); jsonArrayItems.put(jsonObjectIV); } jsonObjectVenda.put(jsonArrayItems); jsonArrayVenda.put(jsonObjectVenda); } jsonVendas.put("Venda", jsonArrayVenda); } } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); } return jsonVendas; }
{ "pile_set_name": "StackExchange" }
Q: How to Use Infix (Comparison) operators as parameters in Go In GoLang, it is possible to use functions as parameters, such as in this simple example that compares two numbers based on either the less than or equal to (<=) or greater than or equal to operator (>=) package main func leq(x, y int) bool { return x <= y } func geq(x, y int) bool { return x >= y } func compare(x, y int, comparator func(int, int) bool) bool { return comparator(x, y) } func main() { println(compare(3, 5, leq)) //true println(compare(5, 3, leq)) //false println(compare(3, 5, geq)) //false println(compare(5, 3, geq)) //true } Is there a way to have infix operator, rather than a function, as a function parameter? Such as: func compare(x, y int, comparator <something here>) bool { return comparator(x, y) } func main() { println(compare(3, 5, <=)) //true println(compare(5, 3, <=)) //false println(compare(3, 5, >=)) //false println(compare(5, 3, >=)) //true } Or is my best bet just writing the wrappers for the operators as in the first example? Additionally, if the above is possible, is it possible to use the infix operator parameter with infix syntax? Such as func compare(x, y int, c <something here>) bool { return x c y } A: No, this is not a correct program according to the Go language specification. The function type is defined to contain, among other terms, a list of parameters which each consist of a parameter declaration: [ IdentifierList ] [ "..." ] Type. This requires that all parameters to functions have types, specified as the production Type, thus: TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType The built-in operands (such as equality and comparison operators) are language-internal and not exposed here as possible type literals. Moreover, the specification for function calls requires that arguments in a call are single-valued expressions. Binary operators are not themselves expressions. Accordingly, you may not pass "infix" Operators as arguments to a function call. You should define your own interface or function type which wraps the operator, and pass this to your comparison function.
{ "pile_set_name": "StackExchange" }
Q: Is MongoDB 2.x write concern { w : 1 } truly equals to { safe : true }? The title says it all, really. I can't seem to find a proper answer in doc for 'safe' keyword anymore, but w:1 = wait for standalone server (can be primary server in replicaSet env), which appears to fit my understanding of 'safe'. Furthermore, we enable journaling on mongodb, is {j:true} required to make it compatible to {safe:true} ? http://docs.mongodb.org/manual/core/write-operations/#write-concern A: Yes, the documentation is never very good at telling yyou this stuff however, yes, safe is w 1. There are numerous sources out there but here is one for the PHP driver I find useful: http://derickrethans.nl/mongoclient.html Whereby he states: All of the other MongoDB drivers are making a similar change. And: The biggest reason is that the new class will have acknowledged writes on by default—or expressed in deprecated wording: MongoClient has safe mode on by default. So yes is the answer. As for Journalling: we enable journaling on mongodb, is {j:true} required to make it compatible to {safe:true} ? No a journal acked write is different to journaling in general. MongoDB will still continue to use the journal even if you use w 1 but it will not wait for a journal write before responding to your request. j is normally false by default.
{ "pile_set_name": "StackExchange" }
Q: CSS images and texts hovering both I'm trying to apply an effect to my pics when I put the cursor over them. What I want is a greyscale filter and a that a text appears. I've used this code: HTML: <div class="upic_wrap"> <img class="upic" src="foo.jpg"> <div class="upic_text">Avenida Central</div> </div> CSS: .upic_text { position:absolute; top: 50%; left: 50%; transform:translate(-50%, -50%); visibility:hidden; opacity:0; } .upic:hover { opacity:0.5; -webkit-filter:grayscale(100%); filter:grayscale(100%); } .upic_wrap:hover .upic_text { visibility:visible; opacity:1; color:#000; text-align:center; text-shadow:1px 1px yellow; } I get this: (out of pic) (hover pic, yes! what I want!) Which is perfect, but the problem is when the cursor is over the text. That's what happen: (hover text, noooo!) I would like to always get the effect of "hover pic" (the second) when I hover the pic or the text. How could I solve that? Thanks! A: This should fix the issues. The thing is to set :hover of the .upic_wrap selector. This snippet is based on your initial code, but I think it needs some changes to look like the pictures you posted. .upic_text { position:absolute; top: 50%; left: 50%; transform:translate(-50%, -50%); opacity:0; } .upic_wrap:hover .upic { opacity:0.5; -webkit-filter:grayscale(100%); filter:grayscale(100%); } .upic_wrap:hover .upic_text { visibility:visible; opacity:1; color:#000; text-align:center; text-shadow:1px 1px yellow; } <div class="upic_wrap"> <img class="upic" src="https://i.stack.imgur.com/DKgfx.png"> <div class="upic_text">Avenida Central</div> </div>
{ "pile_set_name": "StackExchange" }
Q: EF6 CodeFirst - Dealing with OUTPUT parameters I'm trying to consume a stored procedure with EF6/CodeFirst. This SP returns couple of values via OUTPUT parameters. I have seen in other places that this might not be possible, but this article is pretty old and just wondering whether this is solved by now. My SP when executed with RAW Sql (In SSMS) works like this; declare @p10 int declare @p11 uniqueidentifier set @p10=NULL set @p11=NULL exec dbo.uspTestStoredProc @id = 2021, @name=N'qa1231321asda.txt', @documentId=@p10 OUTPUT,@documentStreamId=@p11 output select @p10,@p11 This one correctly prints out the documentId (p10) and documentStreamId (p11) However wWhen executed via EF both of these OUTPUT params are null. I've included both the .Net code and SQL generated via EF below for further investigation. .Net Code var sqlString = "exec dbo.uspTestStoredProc @id,@name,@documentId,@documentStreamId"; var paramCollection = new List<Object> { new SqlParameter("id", 81), new SqlParameter("name", "qa1231321asda2.txt"), }; var paramDocId = new SqlParameter { ParameterName = "@documentId", SqlDbType = SqlDbType.Int, Value = 0, Direction = ParameterDirection.Output }; paramCollection.Add(paramDocId); var paramStreamId = new SqlParameter { ParameterName = "@documentStreamId", SqlDbType = SqlDbType.UniqueIdentifier, Value = DBNull.Value, Direction = ParameterDirection.Output }; paramCollection.Add(paramStreamId); _context.Database.ExecuteSqlCommand(sqlString, paramCollection.ToArray()); var docId = (int) paramDocId.Value; //Fails because paramDocId is DBNull SQL generated by EF declare @p10 int declare @p11 uniqueidentifier set @p10=NULL set @p11=NULL exec sp_executesql N'exec dbo.uspTestStoredProc @id,@name,@documentId,@documentStreamId', N'@id int,@name nvarchar(45), @documentId int output,@documentStreamId uniqueidentifier output', @id=81,@name=N'qa1231321asda2.txt',@documentId=@p10 output,@documentStreamId=@p11 output select @p10, @p11 Now here @p10 and @p11 returns NULL. I'm trying to find out the following Can EF6/CodeFirst support OUTPUT parameters from stored procs? If so, what do I need to do differently? If not, any idea when that feature would be available? Thanks a lot. A: I think I finally found the answer. The trick is in the sqlString that you pass in to the command. var sqlString = "exec dbo.uspTestStoredProc @id,@name, @documentId OUT,@documentStreamId OUT"; Notice the keyword 'OUT' after the 2 output parameters. It does the trick. Of course you also need to specify the proper SQL Parameter options like ParameterDirection.Output when adding the parameters.
{ "pile_set_name": "StackExchange" }
Q: Rally ObjectID clarifications 2 clarifications needed for ObjectID fields: 1) Are ObjectID's globally unique across a subscription or across all of Rally's subscriptions? 2) Are The ObjectID's of built in Rally things constants and the exact same for all subscriptions? For example, in one of my workspaces, to get the allowed ScheduleState values for a UserStory, i have to hit this endpoint: /AttributeDefinition/-41562/AllowedValues where -41562 is the ObjectID. Can I assume that every other subscription uses -41562 for the ObjectID in this URL to get the valid Schedule States? A: 1) ObjectID's are unique per stack. So all of the ObjectID's on the SaaS stack (rally1.rallydev.com) are unique. 2) ObjectID's that are negative like the ScheduleState one mentioned above will be the same across workspaces. However things like custom fields and portfolioitem type and attributes will have unique ObjectID's across different workspaces. Are you wanting to cache these values for perf reasons or what is it you're looking to do with them?
{ "pile_set_name": "StackExchange" }
Q: giving the left shoulder a rest. can I train squats and\or the right arm? Despite being cautious with the bench press I noticed I feel my left shoulder a bit more when I do reverse grip lat pull down as per the picture below. I was considering training the right arms and\or squats, in order to give the left shoulder a rest. can I still have benefits buy training only the right side plus squats? where can I see more about this? A: can I still have benefits buy training only the right side plus squats? Let's first deal with the question of only training the right side. I would heavily caution against training one side more than the other side. This would be a surefire way to develop muscular imbalances which cause chronic injuries and pain down the line. Training should always be done equally on both sides. For the question of squats; yes and no. Yes, there are benefits to be had by doing squats while your upper body is injured, BUT, and this is a very serious but: You MUST confer with a physician before doing so. The reason for this is that we don't know if loading the bar onto your shoulders is going to worsen the shoulder injury you have. And it's very likely that it will. The same also goes for other exercises like deadlifts, because also there the weight is loaded onto your shoulders (via the arms). Due to the ambiguity of knowing there's an injury present, but not knowing enough about it, the answer can only be: Go see a doctor before doing any sort of weight training.
{ "pile_set_name": "StackExchange" }
Q: Xcode 6 fixed View in Table View Controller Good day, everyone. I've got a Table View Controller with an View on top as a header. My problem is, that if I scroll in the Table View, the View scrolls with it. How can I fix the header (View), so it stops scrolling with the table view? I was searching like crazy, but didn't find any solution. Thanks in advance. I am using XCode 6 (iOS8 and Swift) A: This can't be done. It's the default behavior of the tableViewController. You have two solution as I believe. One is to edit the content offset and ad a subview on the tableView itself. Or just change it to a view controller and add a table view as a subview and your view.
{ "pile_set_name": "StackExchange" }
Q: Setting a particular cell with a color (red/green /yellow) on Qtableview I been searching for how to set a color on a specific cell on a qtableview. Currently ,I am using the qt example frozen column to see how to set a color on a particular cell. I search on the forums about how to tell to use qitemdelegate or qstyleitemdelegate to paint the background or foreground cells but no valid. Could someone enlighten me or show an example on the code how I should go about it. A: The fastest way I can think about is using the setData method of a standard item: QStandardItemModel model; QStandardItem item; item.setData(QBrush(Qt::gray), Qt::BackgroundColorRole); //background color model.setItem(x, y, &item); In this example you set the background color. Different roles (to pass as the second argument) are described here
{ "pile_set_name": "StackExchange" }
Q: "In college" versus "at college" versus "at university" Possible Duplicate: Which one is more correct: “works at a university” or “works in a university”? It seems that only in the U.S. one says that they are or were "in college", even though the person attended a university, such as the University of Iowa. You are either in college, or majored in such and such while in college. You hear the phrase "at college" less often, but never "at university" in the U.S. Elsewhere, even next door in Canada, the equivalent phrase seems to be "at university": "I majored in English while at university." I don't think I have ever heard or read the phrase "in university" used. Likewise, in the U.S., one says, for example, "I will be going to college next year" whereas elsewhere one seems to say "I will be going to university next year." Is there anywhere else in the world besides the U.S. where the phrase "in college" is used instead of "at university"? How did the American English usage come about? A: There was nothing called a "university" for the first century and a half of English settlement in North America, and for even longer many of the best-known such institutions were known as "colleges" (some, like Dartmouth, remain so to this day). It should be no surprise then that college, not university, became the generic term for post-secondary education. Universities like Cambridge and Oxford— made up of various autonomous colleges— had already stood for centuries when the Massachusetts Bay Colony established its "New College" in the 1630s. This tiny institution would not have been recognizable as a university; it was, at best, like one of their constituent colleges. People like John Harvard, a graduate of Emmanuel College, Cambridge, would have understood this distinction. His endowment turned New College into Harvard College, not somehow suddenly Harvard University. Even at the Declaration of Independence, none of the institutions of higher learning in the United States were chartered as universities. Where they were reorganized as such, undergraduates usually remained under a single faculty, so a "college education" was synonymous with a "university education"— Yale College, Princeton College, and so on persist to this day. Some universities retained "College" in the overall institution's name, e.g. the College of William & Mary. All these factors would have further entrenched "college" as the generic term for that phase of education, regardless of whether it is undertaken at a university, college, institution, academy, conservatory, polytechnic institute, and so on. One is in college (i.e. enrolled as a postsecondary student) or at college (i.e. away from home on account of enrollment in some distant postsecondary program) just as one would be in elementary school, in apprenticeship, or in seminary.
{ "pile_set_name": "StackExchange" }
Q: Display marker using gmaps4jsf(not google api) I am using gmaps4jsf jar and trying to display marker on map. Marker is displaying fine but not automatic zoom functionality. every time i need to vary zoom value so is there any option in gmaps4jsf so that we can get auto zoom functionality? <m:map latitude="10.132567" longitude="10.132567" height="400px" width="400px" zoom="6"> <ui:repeat var="p" value="#{pointBean.points2}" varStatus="status" offset="0" step="1" size="#{pointBean.points2.size()}"> <m:marker latitude="#{p.latitude}" longitude="#{p.longitude}" > <m:htmlInformationWindow htmlText="#{p.latitude}-#{p.longitude}" /> </m:marker> </ui:repeat> </m:map> Thanks in advance!!! A: You need to put autoReshape="true" in map tag like, <m:map autoReshape="true">.....</map> autoReshape just do adjust marker on map and you will get marker display only.
{ "pile_set_name": "StackExchange" }
Q: Problems with passing objects in tree structure I'm new to C++ and arduino. I want to build an object Tree, but it did not behave like I expected. Here is the code: TreeNode.h class TreeNode { public: TreeNode(String inputNodeName); TreeNode *children[]; TreeNode &getChild(int index); int getLength(); String nodeName; void addChild(TreeNode &node); String getName(); private: int childLength; }; TreeNode.cpp TreeNode::TreeNode(String inputNodeName) { nodeName = inputNodeName; childLength = 0; } TreeNode &TreeNode::getChild(int index) { return *children[index]; } int TreeNode::getLength() { return childLength; } String TreeNode::getName(){ return nodeName.c_str(); } void TreeNode::addChild(TreeNode &node) { children[childLength] = &node; childLength++; } I'm initialising it in the setup function: void setup() { Serial.begin(9600); TreeNode mainTree("main"); TreeNode firstChild("first child"); TreeNode secondChild("second child"); TreeNode subChild("subschild"); Serial.println(mainTree.getName()); //prints "main" Serial.println(firstChild.getName()); //prints "first child"; Serial.println(secondChild.getName()); //prints second child"; mainTree.addChild(firstChild); mainTree.addChild(secondChild); Serial.println(mainTree.getName()); // prints an empty string Serial.println(secondChild.getName()); //prints second child" secondChild.addChild(subChild); Serial.println(secondChild.getName()); //prints an empty string } So my problem is, when I'm adding a child to a node, the node name is empty, or strange characters will be displayed. I think I misunderstood passing an object by reference. Can anybody explain what I did wrong? A: TreeNode *children[]; That declares an array of pointers however it also requires that you assign memory to it. I never see you allocate that memory. If you only expect a small amount of children then you can use that upper bound as a static allocation: #define MAX_CHILDREN 10 //... TreeNode *children[MAX_CHILDREN]; Otherwise use a vector instead: std::vector<TreeNode *> children;
{ "pile_set_name": "StackExchange" }
Q: Docker, Nginx and Supervisor nginx bind fail I am trying to mount a server ready for production using Nginx, Docker and Supervisor. The problem I'm facing is, even if it works and I can see index.html in my browser, this error is showing all time: 2016/08/28 12:05:12 [emerg] 12#12: bind() to [::]:80 failed (98: Address in use) nginx: [emerg] bind() to [::]:80 failed (98: Address in use) The dockerfile: FROM nginx:stable-alpine RUN rm -f /etc/nginx/conf.d/* && mkdir -p /var/www/app COPY config/nginx.conf /etc/nginx/conf.d/ COPY config/supervisord.conf /supervisord.conf COPY scripts /scripts RUN chmod -R 700 /scripts CMD [ "/scripts/start" ] In /scripts/start I have this: #!/bin/bash supervisord -n -c /supervisord.conf Then in supervisord.conf: [unix_http_server] file=/dev/shm/supervisor.sock ; (the path to the socket file) [supervisord] logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (log level;default info; others: debug,warn,trace) pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid) nodaemon=false ; (start in foreground if true;default false) minfds=1024 ; (min. avail startup file descriptors;default 1024) minprocs=200 ; (min. avail process descriptors;default 200) user=root ; [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [program:nginx] command=/usr/sbin/nginx autostart=true autorestart=true priority=10 stdout_events_enabled=true stderr_events_enabled=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr stderr_logfile_maxbytes=0 And when I run docker (without daemon -d option), I got this terminal output: 2016-08-28 12:05:10,474 CRIT Set uid to user 0 2016-08-28 12:05:10,481 INFO RPC interface 'supervisor' initialized 2016-08-28 12:05:10,481 CRIT Server 'unix_http_server' running without any HTTP authentication checking 2016-08-28 12:05:10,481 INFO supervisord started with pid 6 2016-08-28 12:05:11,484 INFO spawned: 'nginx' with pid 9 2016-08-28 12:05:11,497 INFO exited: nginx (exit status 0; not expected) 2016-08-28 12:05:12,499 INFO spawned: 'nginx' with pid 12 2016/08/28 12:05:12 [emerg] 12#12: bind() to 0.0.0.0:80 failed (98: Address in use) nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address in use) 2016/08/28 12:05:12 [emerg] 12#12: bind() to [::]:80 failed (98: Address in use) nginx: [emerg] bind() to [::]:80 failed (98: Address in use) ........ It seems like it spawned 2 nginx processes instead of one because first said it died by no reason, but in fact it wasn't dead. A: There are multiple problems here. One would be that usually it ain't recommended to run supervisord in containers unless you really know what you are doing. Also, make sure you set nodaemon in supervisord to true, otherwise docker will kill your container because there will be no more pid 1 (since it will fork). Same goes for nginx. Supervisord expects nginx to not fork but remain in foreground. Set daemon to off in the nginx configuration file.
{ "pile_set_name": "StackExchange" }
Q: additional NIB for view controller in tabbed app {Xcode 4.2, deployment target iOS4.3, not storyboard, using ARC} I started with a tabbed application template & chose the universal platform, which nicely gives me view controller classes & NIB files for an iPhone (ClassName_iPhone.xib) & an iPad (ClassName_iPad.xib) for 2 tabs, with an if statement in the AppDelegate to determine which to run - exactly how I wanted it set up. I wanted to add a 3rd & 4th tabs, so starting with the 3rd tab (doing 1 at a time) I created a new UIViewController subclass. As it doesn't give the option to create both NIBs at once, I selected "Targeted for iPad", & had intended to create the iPhone NIB manually. I added a "_iPad" suffix to the created NIB file, then I created a user interface view NIB file to which I added the "_iPhone" suffix. I then set up the code for the new view controller in the AppDelegate implementation file to include the 3rd view controller & tab, & I used the other view controller classes as a guide to set up the new class's code. For the 3rd _iPhone NIB, I dragged a view object from the objects library onto the canvas, & set it up as per the other 2 _iPhone NIBs. But when I went to connect the outlets, there is no view outlet in the referencing outlets of the connections panel to connect with, which I thought there should be. At this point I suspected something was wrong. I tried running it in the simulator, in iPad mode it works fine (all 3 tabs are clickable). But in iPhone mode clicking the 3rd tab crashes it with a "SIGABRT" on thread 1. It's obvious what I did didn't work. I don't see anything in the output window that gives me any clues. Being a newbie to obj-c, so not being too sure of the problem, I would have thought that I either: have used the wrong user interface template (view) should have used a view controller object from the object library (not a view) or that I should have declared some outlets in my view controller class files. But if I should have done either of the latter 2, then my question would be why does the iPad NIB work then, when it clearly has a view object in the NIB & no outlets declared in the class files (same with the other 2 view controllers for both devices)? Does the UITabView class somehow have outlets pre-declared within it for the first 2 tabs? But that still doesn't explain why the _iPad NIB works. As usual, any help & advice much appreciated, & if there's a link to an explanation somewhere that I've missed, please show me, because I'm happy to do the research. If what I've done wrong here is not determinable, then I guess ultimately what I'm asking is a clue to how best to create the second NIB file for iPhone to mesh with the class created with iPad NIB. A: Sorry to answer my own question but with further searching I found this answer that was the solution, although not quite the whole story. So I thought to put what I did in an asnwer so others can refer to it. As Piotr Czapla explains in the linked answer, for some reason Xcode doesn't populate the connectionRecords data, as you can see by my first red arrow. Having a look at the view controller that works (where second red arrow is), that's what the data should look like. So the answer is to cut the data & paste it into the NIB file, or type it. You can do this in Xcode by right-clicking the NIB file in the project navigatior & then Open As > Source Code, which is what you see in my screenshots. The bit I want to add to Piotr Czapla's explanation though is the destination reference pointed to by the second red arrow might not be correct for the NIB file you're pasting into (mine wasn't) & Xcode might not let you go back into IB mode. If so, you need to get the correct reference from the IBUIView class within your NIB file, as pointed to by the third red arrow. Once I copied that reference to my destination reference ref=, as shown by the fourth red arrow, all was ok & the problem was solved. I could then go back into IB mode (right click, Open As > Interface Builder - iOS) & the view works in the simulator.
{ "pile_set_name": "StackExchange" }
Q: pandas: smallest X for a defined probability The data is financial data, with OHLC values in column, e.g. Open High Low Close Date 2013-10-20 1.36825 1.38315 1.36502 1.38029 2013-10-27 1.38072 1.38167 1.34793 1.34858 2013-11-03 1.34874 1.35466 1.32941 1.33664 2013-11-10 1.33549 1.35045 1.33439 1.34950 .... I am looking for the answer to the following question: What is the smallest number X for which (at least) N% of the numbers in a large data set are equal or bigger than X And for our data with N=60 using the High column, the question would be: What is the smallest number X for which (at least) 60% of High column items are equal or bigger than X? I know how to calculate std dev, mean and the rest with pandas but my statistic understanding is rather poor to allow me to proceed further. Please also point me to tehoretical papers/tutorials if you know so. Thank you. A: For the sake of completeness, even though the question was essentially resolved in the comment by @haki above, suppose your data is in the DataFrame data. If you were looking for the high price for which 25% of observed high prices are lower, you would use data['High'].quantile(q=0.25)
{ "pile_set_name": "StackExchange" }
Q: Count an Attribute on a nested form? Rails 3.2.12 and Ruby 1.9.3 and Haml I would like to use the count of attribute to control the display of a 'link_to "remove"', but I am having problems with setting up the logic. Following is some code from my form as it is currently: .field = codeline.label :name, "Units Alloc" %br/ = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, :class => "ui-state-default" = codeline.hidden_field :_destroy = link_to "remove", '#', class: "remove_fields" this works well but I have the 'remove' link showing up and I would prefer it to only show if there are two :units_alloc attributes. This is what I tried: .field = codeline.label :name, "Units Alloc" %br/ = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, :class => "ui-state-default" - if :units_alloc.count > 1 = codeline.hidden_field :_destroy = link_to "remove", '#', class: "remove_fields" and here is my error: NoMethodError in Contracts#new Showing /home/tom/rails_projects/tracking/app/views/contracts /_codeline_fields.html.haml where line #9 raised: undefined method `count' for :units_alloc:Symbol if I use units_alloc in the argument instead of the symbol, I still get an error: NameError in Contracts#new Showing /home/tom/rails_projects/tracking/app/views/contracts /_codeline_fields.html.haml where line #9 raised: undefined local variable or method `units_alloc' for #<#<Class:0xadbde90>:0xa8956e8> I tried to use 'codeline.units_alloc' but this did not work and the same error was flagged. Any suggestions, or pointers to help me resolve this issue? Thanks. Solution: Thanks to James Scott Jr. app/controller/contracts_controller.rb def New @show_remove = false .... .... end app/views/contracts/_codelines_fields.html.haml .field = codeline.label :name, "Units Alloc" %br/ = codeline.text_field :units_alloc, :precision => 6, :scale => 2, :size => 10, :class => "ui-state-default" - if @show_remove = codeline.hidden_field :_destroy = link_to "remove", '#', class: "remove_fields" - else - @show_remove = true And that did it ... the remove button only shows in the second and subsequent row of attributes. A: By the time you're in the form (partial), codeline doesn't refer to an instance the instance of Codeline that the form (partial) is for, but an instance of an ActionView::Helpers::FormBuilder that simple knows how to associate information the the instance of Codeline. You knew that because in the first line of the partial, you have codeline.object.build_code. So, if you want to access the information about the units_alloc associated, you would access them with codeline.object.units_alloc. That will give you your data for your conditional.
{ "pile_set_name": "StackExchange" }
Q: How to explain hidden/undocumented properties off of SObjectType? In a recent question, I learned about seemingly magic variables/properties off of certain classes, such as SObjectType.Account, and SObjectType.Custom__c. I also learned that if you have a method expecting an argument of type DescribeSObjectResult, you can pass in one of these magic properties, like SObjectType.Account and the Apex compiler is happy to accept it. It appears that somehow Saleasforce knows that it should call the getDescribe() method if one is passing in SObjectType.Account. Even then that doesn't make sense to me because getDescribe() is a member method of SObjectType based on the docs. Also, from what I can tell, there's no documentation describing all the magic properties off of SObjectType. If you reference the docs for this class, it shows a messily 4 methods. How is one supposed to know about the magic Account property off of Schema.sObjectType? Why is it possible to pass Schema.sObjectType.Account as an argument in a method expecting DescribeSObjectResult? A: Short answer: System.debug(Schema.SObjectType.Account instanceof Schema.DescribeSObjectResult); Result: Operation instanceof is always true since an instance of Schema.DescribeSObjectResult is always an instance of Schema.DescribeSObjectResult Schema.SObjectType is a generic type for the sake of having a generic type, which is why theres methods you can use to interact with it. Somewhere in the compiler, apex is smart enough to replace: Schema.SObjectType.Account With: Account.SObjectType.getDescribe() I'd think of it less of a magic variables/property, and more like an enum, which returns a type, which also has a generic base type. You need the other methods for generic or unknown at compile time types. Having a generic type to use when you run something can be a real lifesaver: SObjectType accountType = Schema.getGlobalDescribe().get('Account'); From the base generic type, you can call accountType.getDescribe() to get the actual describe.
{ "pile_set_name": "StackExchange" }
Q: Get average CPU usage of a computer in last x minute This question "How to get the CPU Usage in C#?" shows some of the ways to get the current CPU usage (%) of a computer in .NET. Since the CPU usage fluctuates quite frequently, I think the current CPU usage is often not a good indicator of how busy a computer is (e.g. for scheduling or load balancing purpose). Is there an efficient way to get the average CPU usage in last x minute, e.g. last 5 minutes? I am thinking of something like a method GetAverageCpuUsage(int period) that can be called by a load balancing or scheduling module. A: Actually that is exactly what PerformanceCounter from the 2nd most upvoted answer in the other question does, they are just measuring over 1 second. The % it gives you is the average % of cpu seance the last NextValue() was made on the counter. So if you want the average cpu over the last 5 min, just call NextValue() only once every 5 min. Here is a good article explaining how to use the performance counters.
{ "pile_set_name": "StackExchange" }
Q: Apache SSL not working I've installed (from source) Apache 1.3 on a CentOS 5.2 and I'm trying to get SSL to work. I used --enable-module=so then added AddModule mod_so.c LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to httpd.conf. Now I'm getting this error from configtest: Syntax error on line 44 of /www/conf/httpd.conf: Cannot load /usr/lib/httpd/modules/mod_ssl.so into server: /usr/lib/httpd/modules/mod_ssl.so: undefined symbol: ap_set_deprecated Thanks for any help. A: mod_ssl.so is making a a request for the symbol ap_set_deprecated which is not available with the 1.3 but with 2.0 (I just downloaded the sources and checked). You'll need to rebuild mod_ssl.so. Download the sources here : http://www.modssl.org/source/mod_ssl-2.8.31-1.3.41.tar.gz . This doesn't make any calls to ap_set_deprecated. (I checked this too). -- Ram
{ "pile_set_name": "StackExchange" }
Q: Prevent duplicate choice in multiple dropdowns I'm using the following script which displays a pop-up error if a person has picked same values from multiple drop-downs. Works great, however after showing the pop-up, the duplicate selection still takes place. It should prevent this from happening. $(document).ready(function () { $('select').change(function () { if ($('select option[value="' + $(this).val() + '"]:selected').length > 1) { alert('You have already selected this option previously - please choose another.') } }); }); jsfiddle example here A: You could switch to the default option : $(this).val('-1').change(); Hope this helps. $(document).ready(function () { $('select').change(function () { if ($('select option[value="' + $(this).val() + '"]:selected').length > 1) { $(this).val('-1').change(); alert('You have already selected this option previously - please choose another.') } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value='-1'>Choose an option</option> <option value='1'>option 1</option> <option value='2'>option 2</option> <option value='3'>option 3</option> </select> <select> <option value='-1'>Choose an option</option> <option value='4'>option 4</option> <option value='1'>option 1</option> <option value='5'>option 5</option> </select>
{ "pile_set_name": "StackExchange" }
Q: Does the word "wizardry" have negative connotations? The Free Dictionary defines wizardry as The art, skill, or practice of a wizard; sorcery. The first part certainly sounds positive, but then the word sorcery is cited as a synonym. This word has the definition Use of supernatural power over others through the assistance of spirits; witchcraft. Ouch! Further, definition 2 of "wizardry" also sounds positive and exactly in line with what I'd like to express: 2. a. A power or effect that appears magical by its capacity to transform: computer wizardry. b. Great ability or adroitness in a pursuit: a pianist gifted with technical wizardry. The word "sorcery" really seems like the odd man out in the context of a definition of "wizardry". So can the latter safely be used as a compliment? A: The literal meaning of wizardry is exactly that of your first definition: the name for the practice of wizards. Yet when applied in a metaphorical or illustrative way, the term 'wizardry', by itself, has no negative connotation. For that matter, as we're no longer given to the practice of setting fire to people, nor does 'sorcery'. In fact both can be used to convey, quite neatly and playfully, a kind of baffled awe. For example, an article from The Economist remarked that 'MARIO DRAGHI seems more sorcerer than central banker', using the theme of magic and sorcery to illustrate the effect of his pronouncement of the Outright Monetary Transactions initiative, with such allusions as 'Who would bet against a central bank that can conjure money from thin air?' and 'Mr Draghi’s magic is powerful, but it won’t work without help from the politicians'. 'The ECB's bond-buying plan: casting a spell', The Economist. In the article, the author describes how the yields on bonds issued by enfeebled Euro-zone economies tumbled after Mario Draghi, the head of the European Central Bank, literally stated that he would do 'whatever it takes' to save the Euro. Yet he didn't need to actually do anything beyond announce the fact: as if by magic, the panic of investors abated at the spell of his reassurances. A Google search for your example of 'computer wizardry' reveals a number of companies who use the phrase 'wizardry' in either their names or tag-lines. I only checked the first page of results, but not one of those firms admitted to resorting to witchcraft and sacrifice in order to get great results. A further anecdotal example would be when, late last year, some delivery men were able to fit my new and large sofa through a my old and small door, showing outright contempt for the laws of physics in doing so. I remarked that they were 'wizards' or 'magicians' (I don't remember 'witch' of the two (HA!)) and said I'd like to buy them each a pint. Rather than initiating slander charges, they accepted the tip I offered them in lieu of an actual beer and went merrily on their way. 'Wizardry' is a fun and descriptive word, and is a wonderful compliment to pay to somebody. If you were actually able to find somebody who took offence to its connections to witchcraft, I would advise you that this is a dangerous person and is not your friend. A: Let me delve into realm of Role-Playing manuals and scripture, departing from dry dictionary definitions. A Wizard is a learned practitioner of magic, following study of arcane sciences and lengthy schooling in performing magic rituals, summoning magic to . A Sorcerer is a person gifted with magical power flowing from within. They may still need to learn how to control and shape their magic, but they don't need to study methods of summoning it to their bidding, more concerned with their wild magic not causing them harm as it manifests all by itself, for example coaxed by anger. A Witch is largely similar to a sorcerer, though learned to apply inherent magic in creation of magical tools or mixtures, often (at least allegedly) for nefarious purposes. These are the definitions of the practitioners of the different schools of magic and the metaphorical use follows them. If you perform something that shows your expertise and power, laymen may call it wizardry in appreciation. If effects of your actions are counter-intuitive, don't appear to follow logic, you may hear "What kind of sorcery is it?" Witchcraft is usually connected with evil actions, following bad reputation given to witches by the church, and as such describing some person's actions as "witchcraft" is usually derogatory on top of "mysterious".
{ "pile_set_name": "StackExchange" }
Q: What happens if I pass function body instead of a function name to setTimeout? I know the correct way of using setTimeout is as follows: setTimeout(function(){alert('hi!');}, 3000); or define the function outside, and pass the reference: var foo=function(){alert('hi!');} setTimeout(foo, 3000); What happens if I write it as: setTimeout(alert('hi!'), 3000); It looks like alert('hi!') was executed correctly. A: alert("hi") gets executed immediately and its result, undefined, is passed to setTimeout... Now, if you simply want to avoid a wrapper while specifying your arguments, try this: setTimeout(alert, 3000, "hi!");
{ "pile_set_name": "StackExchange" }
Q: How to recursively loop through array of objects and find the index of matching id using javascript and react? Hi i have data like below, const items = [ { id: '1', color: 'green', name: 'item1', polygons: [ { id: '1', coordinates: [ { latitude: '25.00', longitude: '-25.99', } { latitude: '15.00', longitude: '-25.99', } { latitude: '25.00', longitude: '-35.99', } ], } ] subItems: [ { id: '2', name: 'subitem-1', color: 'green', polygons: [ { id: '2', coordinates: [ { latitude: '25.00', longitude: '-25.99', } { latitude: '15.00', longitude: '-25.99', } { latitude: '25.00', longitude: '-35.99', } ], } ] } ], }, ] what i am trying to do? from the Items array i want to find the index that matches with id = '2' using javascript or typescript. so basically item and subItem have different ids and they never match and i want to loop through each item and check if its id matches with id 2 and check each subitem of that item and check if id matches to 2. if matches return the index. i have tried something like below, const ItemIndex = Items.findIndex( (Item: any) => Item.id === '2' ); this will check only for the Item but not within subItems. how can i modify this code to check for the subItems id too? could someone help me with this. thanks. A: This is a duplicate question, but OK, I can answer here too. The correct search can be done like this: items.findIndex((item) => item.subItems.some((sub) => sub.id == '2')) Example: const items = [{ id: '1', color: 'green', name: 'item1', polygons: [{ id: '1', coordinates: [{ latitude: '25.00', longitude: '-25.99', }, { latitude: '15.00', longitude: '-25.99', }, { latitude: '25.00', longitude: '-35.99', } ], }], subItems: [{ id: '1', name: 'subitem-1', color: 'green', polygons: [{ id: '2', coordinates: [{ latitude: '25.00', longitude: '-25.99', }, { latitude: '15.00', longitude: '-25.99', }, { latitude: '25.00', longitude: '-35.99', } ], }] }], }, { id: '2', color: 'red', name: 'item2', polygons: [{ id: '3', coordinates: [{ latitude: '25.00', longitude: '-25.99', }, { latitude: '15.00', longitude: '-25.99', }, { latitude: '25.00', longitude: '-35.99', } ], }], subItems: [{ id: '2', name: 'subitem-1', color: 'red', polygons: [{ id: '5', coordinates: [{ latitude: '25.00', longitude: '-25.99', }, { latitude: '15.00', longitude: '-25.99', }, { latitude: '25.00', longitude: '-35.99', } ], }] }], } ] const itemIndex = items.findIndex((item) => item.subItems.some((sub) => sub.id == '2')); console.log('Item index with subItems with id=2 is:', itemIndex)
{ "pile_set_name": "StackExchange" }
Q: Batch file hangs at SQL Error I am using a batch file my.bat as given below: @echo off setlocal enabledelayedexpansion for /F "tokens=*" %%A in (user.txt) do ( sqlplus -s -l %%A @fetch.sql ) >> output.txt where user.txt (list of all user details for which I need expiry date. this list may have around 40-50 rows) is: dbuser/password@database1 readuser/p@ssw0rd@database1 adminuser/Pa$$word@database2 ....... ....... ....... and fetch.sql is: set pagesize 200 set linesize 200 select username, expiry_date from user_users; exit; The problem I am facing is, script my.bat captures here all the required details in output.txt along with SQL ERRORS (ORA-01017: invalid username/password; logon denied ,ORA-12154: TNS:could not resolve the connect identifier specified, ORA-28000: the account is locked ) but its getting hanged at the point whenever it encounteres below error message : ERROR: ORA-28001: the password has expired Changing password for readuser Please can you let me know how I can ignore this ERROR message too and keep my script running further ? A: You can have whenever sqlerror exit failure in your SQL script, but because you only run that after a successful connection it won't catch this error. You could instead launch SQL*Plus without logging in, using the /nolog switch, and then connect explicitly: @echo off setlocal enabledelayedexpansion for /F "tokens=*" %%A in (user.txt) do ( ( echo whenever sqlerror exit failure echo connect %%A echo @fetch.sql ) | sqlplus -s /nolog ) >> output.txt This also means your credentials aren't supplied on the command line; not sure about Windows so much but on other platforms that is a considerable security risk. Of course you still have them stored in a plain text file which itself isn't very secure, so that's more of a general point. You could put your fetch.sql statements directly in the batch file if you prefer, by echoing those instead of the @ start command; same effect but one less file to maintain.
{ "pile_set_name": "StackExchange" }
Q: Error while installing netbeans I tried to install NetBeans 7.2 from a downloaded .sh file, but experienced problems. Here's text from the Terminal, which shows what I did and what happened: hridesh@ubuntu:~$ cd Desktop/ hridesh@ubuntu:~/Desktop$ cd full\ netbeans\ 7.2\ for\ linux\ in\ .sh\ format/ hridesh@ubuntu:~/Desktop/full netbeans 7.2 for linux in .sh format$ chmod +x netbeans-7.1.2-ml-linux.sh hridesh@ubuntu:~/Desktop/full netbeans 7.2 for linux in .sh format$ ./netbeans-7.1.2-ml-linux.sh Configuring the installer... Searching for JVM on the system... Extracting installation data... Installer file /home/hridesh/Desktop/full seems to be corrupted Why does the message Installer file /home/hridesh/Desktop/full seems to be corrupted appear? Is this file actually corrupted or something else going wrong? A: The setup showed this error Installer file /home/hridesh/Desktop/full seems to be corrupted Since the full path being used is "home/hridesh/Desktop/full netbeans 7.2 for linux in .sh format" it would seem that the installer is having problem with such a complex folder name. Renaming the folder "full netbeans 7.2 for linux in .sh format" to something simple like "netbeans_installer" should solve the problem the installer is reporting. cd Desktop mv full\ netbeans\ 7.2\ for\ linux\ in\ .sh\ format netbeans_installer cd netbeans_installer ./netbeans-7.1.2-ml-linux.sh
{ "pile_set_name": "StackExchange" }
Q: Why I can't get the data on a new page from mysql via Vue? Apologies for asking what looks like a common question but I cannot seem to be able to achieve. I would like to click 'a' tag and open a new page to show an article according to the id from MySQL Database. But I got 500. Could anyone tell me what's the matter with my codding? Thank You. Here is the 'a' tag <article v-for='item in dataGroup'> <a :href="'http://localhost:8090/articlePage.html?articlePage?id='+item.ID" :name='pageId' target="__blank"> <h4>{{item.title}}</h4> <p>{{item.intro}}</p> </a> </article> I use Vue-resource to send the 'get' request const vm = new Vue({ el: '#app', data: { dataGroup: [], }, methods: { renderArticle(url) { this.$http.get(url, { }).then((res) => { this.dataGroup = res.data; }, (res) => { alert(res.status) }) }, }, created() { this.renderArticle('/articlePage') } }) Here is my server code module.exports = () => { var router = express.Router(); router.get('/', (req, res) => { db.query(`SELECT * FROM articles_table WHERE ID='${pageId.id}'`, (err, page) => { if (err) { console.error(err); res.status(500).send('database error').end(); } else { res.send(page); } }) }) A: You have not defined a server side route for articlePage You're never actually sending pageId to the server, so therefore you can't utilize it in your query as the server doesn't know what that variable is, let alone how to access id off of it. You do not have a catchall (*) route defined to return a 404 error code, so the server is (presumably) responding with a 500 server error because it doesn't know how to handle the request. Edit Your URL doesn't make sense to me, it should be something like: https://localhost:8090/articlePage.html?articlePageId='+item.ID Then on the server side you can access any variables in the query string off of the request, like below: req.query.articlePageId The req.query part is where the magic happens
{ "pile_set_name": "StackExchange" }
Q: Refresh view on property change in Caliburn Micro WPF Got a view, which has a BindingList property. This is responsible to store workitems, add and remove. The backend is working fine, but the UI is not updated. The view: <ListBox Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2" x:Name="WorkPieces" HorizontalAlignment="Stretch"> <ListBox.ItemTemplate> <DataTemplate> <Grid HorizontalAlignment="Stretch"> <Grid.ColumnDefinitions> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> <ColumnDefinition Width="auto" /> </Grid.ColumnDefinitions> <TextBlock Grid.Column="1" x:Name="DisplayName" Text="{Binding DisplayName}" MinWidth="40 " FontWeight="Bold"/> <TextBlock Grid.Column="2" Text="{x:Static lang:Resources.Txt_W}" /> <TextBox Grid.Column="3" x:Name="Width" MinWidth="50" Text="{Binding Width}" TextAlignment="Right"/> <TextBlock Grid.Column="4" Text=" x " /> <TextBlock Grid.Column="5" Text="{x:Static lang:Resources.Txt_L}" /> <TextBox Grid.Column="6" x:Name="Length" MinWidth="50" Text="{Binding Length}" TextAlignment="Right"/> <Button Grid.Row="0" Grid.Column="7" Margin="5" BorderThickness="0" Background="Transparent" Visibility="{Binding IsLast, Converter={StaticResource Converter}}"> <Image Source ="/Images/plus-sign.png" Height="16" Width="16" /> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cal:ActionMessage MethodName="AddNewWorkPiece" /> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Button Grid.Row="0" Grid.Column="8" Margin="5" BorderThickness="0" Background="Transparent"> <Image Source ="/Images/minus-sign.png" Height="16" Width="16" /> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <cal:ActionMessage MethodName="RemoveWorkPiece"> <cal:Parameter Value="{Binding Id}" /> </cal:ActionMessage> </i:EventTrigger> </i:Interaction.Triggers> </Button> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> The property: public BindingList<WorkPieceModel> WorkPieces { get { return _workPieces; } set { _workPieces = value; NotifyOfPropertyChange(() => WorkPieces); NotifyOfPropertyChange(() => CanCalculate); } } The backend function to update display name and set icon display flags: private void UpdateWorkPiecesDisplayName() { var counter = 1; foreach (var item in WorkPieces) { item.DisplayName = Roman.To(counter); item.IsLast = false; counter++; } WorkPieces.Last().IsLast = true; NotifyOfPropertyChange(() => WorkPieces); } So when I click on the Add/Remove it is updating properly the number of elements, but the rest does not refreshing the buttons or the DisplayNumber. Tried to call NotifyOfPropertyChange() after adding and removing workpiece, without any desired result. The goal is to display a + - icon only on the last element, - icon for the rest, and the displayed numbers always be ascending, disregarding which element has been removed. As you can see: IV. is missing and III. has + icon (it shouldn't have) A: Since you are binding to IsLast, you should implement the INotifyPropertyChanged interface in the WorkPieceModel class and raise the PropertyChanged event in the setter of IsLast.
{ "pile_set_name": "StackExchange" }
Q: :o autocomplete Without any plugins, I am able to autocomplete :vsp filena<tab> I wonder why I don't get autocompletion of filenames with :o. I have tried this in different installations, terminals and OS. A: :o[pen] comes from Vi. It's intended to support so called "open mode" which is no-op in Vim. You should use :e[dit] instead.
{ "pile_set_name": "StackExchange" }
Q: custom config module validation with joi So I followed the guide on how to create a configuration for my Nest app https://docs.nestjs.com/techniques/configuration and due to the fact I have many configuration parts I wanted to split the parts into multiple configuration services. So my app.module.ts imports a custom config module @Module({ imports: [CustomConfigModule] }) export class AppModule {} This custom config module (config.module.ts) bundles all the config services and loads the Nest config module @Module({ imports: [ConfigModule.forRoot()], providers: [ServerConfigService], exports: [ServerConfigService], }) export class CustomConfigModule {} Lastly I have a simple config service server.config.service.ts which returns the port the application is running on @Injectable() export class ServerConfigService { constructor(private readonly configService: ConfigService) {} public get port(): number { return this.configService.get<number>('SERVER_PORT'); } } I would like to validate those services on application startup. The docs explain how to setup a validationschema for the configuration module https://docs.nestjs.com/techniques/configuration#schema-validation How can I use that for my service validation when using a custom config module? Do I have to call joi in each service constructor and validate the properties there? Thanks in advance A: I believe in your ConfigModule.forRoot() you can set the validation schema and tell Nest to run the validations on start up instead of having to add it to each custom config service. The docs show something like: @Module({ imports: [ ConfigModule.forRoot({ validationSchema: Joi.object({ NODE_ENV: Joi.string() .valid('development', 'production', 'test', 'provision') .default('development'), PORT: Joi.number().default(3000), }), validationOptions: { allowUnknown: false, abortEarly: true, }, }), ], }) export class AppModule {} Which would run validations on NODE_ENV and PORT. You could of course extend it out to more validations overall. And then you could just have one ConfigModule that has smaller config services that split each segment up so all validations are run on startup and only what you need is available in each module's context.
{ "pile_set_name": "StackExchange" }
Q: How can I find email messages older than 10 years in Gmail? As of today (Dec 28, 2015) I do not see any email in my gmail account older than 2006. How can I check older emails? I checked "All Mail" folder as well as other in my Gmail and none of them show messages older than 2006. A: You probably do not have any mail older then 2006. Gmail will display all mail irregardless of its overall age. After checking my own account which was created in November of 2004 (only 7 months after Gmail first came out). I can see all mail going back to the original welcome email. See the screenshot below as evidence.
{ "pile_set_name": "StackExchange" }
Q: Giving attributes to physical domains in gmsh Based on my previous question physical entities for gmsh I am moving forward trying to understand if it is possible to give domain characteristics to the physical entities defined in the *.geo file. I am developing a FEM code, and in this case I am trying to define everything in the mesh file, I mean: domains, boundaries, properties of domains, etc, everything that involves problem settings. See the following *.geo file: Point(1) = {0, 0, 0, 1.0}; Point(2) = {1, 0, 0, 1.0}; Point(3) = {1, 1, 0, 1.0}; Point(4) = {0, 1, 0, 1.0}; Point(5) = {0, 0.5, 0, 1.0}; Point(6) = {1, 0.5, 0, 1.0}; Line(1) = {1, 2}; Line(2) = {2, 6}; Line(3) = {6, 3}; Line(4) = {3, 4}; Line(5) = {4, 5}; Line(6) = {5, 1}; Line(7) = {5, 6}; Line Loop(8) = {4, 5, 7, 3}; Plane Surface(9) = {8}; Line Loop(10) = {7, -2, -1, -6}; Plane Surface(11) = {10}; Physical Surface('top') = {9}; Physical Surface('bottom') = {11}; It is my intention to write in the *.geo file the aforementioned definitions. Is this possible to do? A: In short, you should not (look at question 12 in this section of GMSH FAQ). According to GMSH philosophy, and this job is best left to the solver, GMSH provides a simple mechanism to tag groups of elements – which you are already using. The long version: I guess, the intention is to use *.msh file (obtained by GMSH processing the corresponding *.geo file) as an input to the FEM solver. Thus, we can use the specification of GMSH *.msh. (As GMSH just recently updated to v4, we can also look at the previous legacy MSH v2). In v4 (v2 offers even less), the following sections are available (some, optional): MeshFormat – header info PhysicalNames - the connection between physical groups numbers and names Entities, Partitioned Entities, Nodes, Elements, GhostElements – geometry definitions Periodic – info on the periodicity NodeData, ElementData, ElementNodeData - postprocessing-intent datasets. So, there is not a section that will naturally fit your needs. You are left with two bad choices (the ones that I can come up with): Since sections with unknown headers are ignored, you can manually (after *.msh is generated) add your data there and provide your solver with the required input functionality based on your needs try using postprocessing-intent ElementData, but that renders the use of Physical Group tags useless (as you'll have to do it based on individual element IDs) So, based on that, I would stop at properly assigning physical group tags and numbers and do the material properties assignment on the side of your FEM solver.
{ "pile_set_name": "StackExchange" }
Q: CSS3 borders no edges in other words lines don't meet in the corner This is a tough one. I want to cut the corners off. so the lines never meet at the corners. At first I thought maybe I could add two divs nested inside and just have border-right and border-bottom divs, but that won't work. any Ideas would be helpful. I have attached a image you can look at. ![enter image description here][1] A: You can use :before and :after :pseudo-elements. #container { width: 550px; height: 200px; background-color: #222426; } .box { display: inline-block; width: 275px; height: 100px; line-height: 100px; text-align: center; position: relative; color: #FFFFFF; } .box:first-child:after { content: ''; position: absolute; right: 0; top: 3%; background-color: #777777; width: 1px; height: 90%; } .box:nth-child(3):after { content: ''; position: absolute; right: 0; bottom: 3%; background-color: #777777; width: 1px; height: 90%; } .box:first-child:before { content: ''; position: absolute; left: 1%; bottom: 0; background-color: #777777; height: 1px; width: 90%; } .box:nth-child(2):before { content: ''; position: absolute; right: 1%; bottom: 0; background-color: #777777; height: 1px; width: 91%; } <div id="container"> <div class="box">Some Content</div ><div class="box">Some Content</div ><div class="box">Some Content</div ><div class="box">Some Content</div> </div>
{ "pile_set_name": "StackExchange" }
Q: Google Speech to text throwing java.lang.ClassCastException ** * Showing google speech input dialog * */ private void promptSpeechInput() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); try { startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); } catch (ActivityNotFoundException a) { Toast.makeText(getApplicationContext(), getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); } } Below exception: 03-04 16:33:13.281 W/Bundle ( 3741): Key android.speech.extra.LANGUAGE expected String but value was a java.util.Locale. The default value <null> was returned. 03-04 16:33:13.281 W/Bundle ( 3741): Attempt to cast generated internal exception: 03-04 16:33:13.281 W/Bundle ( 3741): java.lang.ClassCastException: java.util.Locale cannot be cast to java.lang.String 03-04 16:33:13.281 W/Bundle ( 3741): at android.os.BaseBundle.getString(BaseBundle.java:921) 03-04 16:33:13.281 W/Bundle ( 3741): at android.content.Intent.getStringExtra(Intent.java:4822) 03-04 16:33:13.281 W/Bundle ( 3741): at ihn.<init>(PG:97) 03-04 16:33:13.281 W/Bundle ( 3741): at com.google.android.voicesearch.intentapi.IntentApiActivity.onCreate(PG:37) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.Activity.performCreate(Activity.java:5953) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1128) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.ActivityThread.access$800(ActivityThread.java:148) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292) 03-04 16:33:13.281 W/Bundle ( 3741): at android.os.Handler.dispatchMessage(Handler.java:102) 03-04 16:33:13.281 W/Bundle ( 3741): at android.os.Looper.loop(Looper.java:135) 03-04 16:33:13.281 W/Bundle ( 3741): at android.app.ActivityThread.main(ActivityThread.java:5312) 03-04 16:33:13.281 W/Bundle ( 3741): at java.lang.reflect.Method.invoke(Native Method) 03-04 16:33:13.281 W/Bundle ( 3741): at java.lang.reflect.Method.invoke(Method.java:372) 03-04 16:33:13.281 W/Bundle ( 3741): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) A: Try hard coding language like intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US"); instead of intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); check whether it works or not, if it works then you its the problem with the Locale.getDefault()); your app can query for the list of supported languages by sending a RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS ordered broadcast like so: Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS); sendOrderedBroadcast( detailsIntent, null, new LanguageDetailsChecker(), null, Activity.RESULT_OK, null, null); You can write the broadcast reciever like public class LanguageDetailsChecker extends BroadcastReceiver { private List<String> supportedLanguages; private String languagePreference; @Override public void onReceive(Context context, Intent intent) { Bundle results = getResultExtras(true); if (results.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) { languagePreference = results.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE); } if (results.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) { supportedLanguages = results.getStringArrayList( RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES); } } } Check this link out toolkit for using Android's Sensing capabilities
{ "pile_set_name": "StackExchange" }
Q: Will different java versions create different serialVersionUID? I have updated my java version from 1.6 to 1.8. When I try to deploy my project in weblogic (12c), I am getting below error. java.io.InvalidClassException: org.springframework.beans.PropertyAccessException; local class incompatible: stream classdesc serialVersionUID = -5171479712008793097, local class serialVersionUID = 736080306599024264 Do I need to re generate serialVersionUID , which created using java version 1.6 ? Please help Thanks, Raj A: Yes, the compiler version matters. The Serializable Javadoc says (in part) If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.
{ "pile_set_name": "StackExchange" }
Q: Docusign webhook message does not have way to differentiate different compositetemplate I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row. This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row { "status": "sent", "emailSubject": "DocuSign API - Template Example", "eventNotification": { "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available", "loggingEnabled": "false", "requireAcknowledgment": "true", "useSoapInterface": "false", "soapNameSpace": "", "includeCertificateWithSoap": "false", "signMessageWithX509Cert": "false", "includeDocuments": "false", "includeEnvelopeVoidReason": "false", "includeTimeZone": "true", "includeSenderAccountAsCustomField": "false", "includeDocumentFields": "false", "includeCertificateOfCompletion": "true", "envelopeEvents": [ { "envelopeEventStatusCode": "Sent", "includeDocuments": null }, { "envelopeEventStatusCode": "Completed", "includeDocuments": "true" } ], "recipientEvents": [ { "recipientEventStatusCode": "Completed", "includeDocuments": "true" } ] }, "compositeTemplates": [ { "inlineTemplates": [ { "sequence": "1", "recipients": { "signers": [ { "clientUserId": "1", "recipientId": "1", "email": "[email protected]", "name": "Client Name", "roleName": "Client", "tabs": { "TextTabs": "Just a bunch of text tabs, radio group, etc" } }, { "clientUserId": "2", "recipientId": "2", "email": "[email protected]", "name": "Owner Name", "roleName": "Owner", "tabs": null } ] }, "customFields": { "ListCustomFields": [ { "name": "DocuInfoId", "required": "True", "show": "False", "value": "77", "listItems": null }, { "name": "OpportunityId", "required": "True", "show": "False", "value": "1", "listItems": null } ] } } ], "serverTemplates": [ { "sequence": "1", "templateId": "TemplateIDNumber1" } ] }, { "inlineTemplates": [ { "sequence": "2", "recipients": { "signers": [ { "clientUserId": "1", "recipientId": "1", "email": "[email protected]", "name": "Client Name", "roleName": "Client", "tabs": { "TextTabs": "Just another bunch of text tabs, radio group tab, etc" } } ] }, "customFields": { "ListCustomFields": [ { "name": "DocuInfoId", "required": "True", "show": "False", "value": "88", "listItems": null }, { "name": "OpportunityId", "required": "True", "show": "False", "value": "1", "listItems": null } ] } } ], "serverTemplates": [ { "sequence": "2", "templateId": "TemplateIDNumber2" } ] } ] } And once I finished signing, the webhook event notification is triggered and called my api with this response message { "EnvelopeStatus": { "EnvelopeID": "EnvelopeIDGivenByDocusign", "Status": "Completed", "CustomFields": [ { "Name": "ContactID", "Show": "True", "Required": "False", "Value": "" }, { "Name": "OpportunityID", "Show": "True", "Required": "False", "Value": "" }, { "Name": "AccountID", "Show": "True", "Required": "False", "Value": "" }, { "Name": "DocuInfoId", "Show": "False", "Required": "True", "Value": "88" }, { "Name": "OpportunityId", "Show": "False", "Required": "True", "Value": "1" }, { "Name": "LQAID", "Show": "True", "Required": "False", "Value": "" } ], "DocumentStatuses": [ { "ID": 1, "Name": "Document - TX - 1001.pdf", "TemplateName": "Document - TX", "Sequence": 1 }, { "ID": 2, "Name": "Rejection.pdf", "TemplateName": "Rejection Form", "Sequence": 2 } ] }, "DocumentPDFs": [ { "Name": "Document - TX - 1001.pdf", "DocumentID": "1", "DocumentType": "CONTENT" }, { "Name": "Rejection.pdf", "DocumentID": "2", "DocumentType": "CONTENT" }, { "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf", "DocumentID": null, "DocumentType": "SUMMARY" } ] } Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf). Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly? A: You can set compositeTemplateId for each CompositeTemplate and then use this Id in each envelope Custom Field. I have modified your JSON request to include CompositeTemplateId, { "status": "sent", "emailSubject": "DocuSign API - Template Example", "eventNotification": { "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available", "loggingEnabled": "false", "requireAcknowledgment": "true", "useSoapInterface": "false", "soapNameSpace": "", "includeCertificateWithSoap": "false", "signMessageWithX509Cert": "false", "includeDocuments": "false", "includeEnvelopeVoidReason": "false", "includeTimeZone": "true", "includeSenderAccountAsCustomField": "false", "includeDocumentFields": "false", "includeCertificateOfCompletion": "true", "envelopeEvents": [ { "envelopeEventStatusCode": "Sent", "includeDocuments": null }, { "envelopeEventStatusCode": "Completed", "includeDocuments": "true" } ], "recipientEvents": [ { "recipientEventStatusCode": "Completed", "includeDocuments": "true" } ] }, "compositeTemplates": [ { "compositeTemplateId": "1", "inlineTemplates": [ { "sequence": "1", "recipients": { "signers": [ { "clientUserId": "1", "recipientId": "1", "email": "[email protected]", "name": "Client Name", "roleName": "Client", "tabs": { "TextTabs": "Just a bunch of text tabs, radio group, etc" } }, { "clientUserId": "2", "recipientId": "2", "email": "[email protected]", "name": "Owner Name", "roleName": "Owner", "tabs": null } ] }, "customFields": { "ListCustomFields": [ { "name": "DocuInfoId_1", "required": "True", "show": "False", "value": "77", "listItems": null }, { "name": "OpportunityId_1", "required": "True", "show": "False", "value": "1", "listItems": null } ] } } ], "serverTemplates": [ { "sequence": "1", "templateId": "TemplateIDNumber1" } ] }, { "compositeTemplateId": "2", "inlineTemplates": [ { "sequence": "2", "recipients": { "signers": [ { "clientUserId": "1", "recipientId": "1", "email": "[email protected]", "name": "Client Name", "roleName": "Client", "tabs": { "TextTabs": "Just another bunch of text tabs, radio group tab, etc" } } ] }, "customFields": { "ListCustomFields": [ { "name": "DocuInfoId_2", "required": "True", "show": "False", "value": "88", "listItems": null }, { "name": "OpportunityId_2", "required": "True", "show": "False", "value": "1", "listItems": null } ] } } ], "serverTemplates": [ { "sequence": "2", "templateId": "TemplateIDNumber2" } ] } ] } Now, when you will receive WebHook response, you will be able to know which custom fields below to which composite template. I have one more suggestion, since you are not using any dropdowns, then it is better to use TextCustomFields instead of ListCustomFields.
{ "pile_set_name": "StackExchange" }
Q: Obj-C get JSON key name Hi I am trying to create a link between PHP and iOS, and I am using JSON. Although my JSON array is strange, I am not the creator, as this is in a closed API, I cannot change it. The JSON looks like this: {"success":true,"errors":[],"data":{"Servers":{"6":"Name here"}}} The 6 is the ID of the server, and the other one is the name. As you can see the key is the ID and the value is the name, but how do I get the ID in Objective-C? I know how to receive the server name, but to do that I need to find the server ID. Here is my current code: NSDictionary *json = [[NSDictionary alloc] init]; NSError *error; json = [NSJSONSerialization JSONObjectWithData:_responseData options:kNilOptions error:&error]; NSDictionary *test = [dataDict objectForKey:@"Servers"] NSLog(@"%@", [test objectForKey:@"6"]); // Server Name (ID of server is 6) _responseData is just the JSON data received from the PHP script. A: NSDictionary *jsonDict = @{@"success":@"true", @"errors":@[], @"data":@{ @"Servers":@{ @"6":@"Name here" } } }; NSDictionary *servers = jsonDict[@"data"][@"Servers"]; NSString *serverID = [[servers allKeys] firstObject]; NSLog(@"serverID: %@", serverID); Output: serverID: 6 For more than one server: for (NSString *serverId in servers) { NSString *serverName = servers[serverId]; NSLog(@"server key: %@, serverId: %@", serverId, serverName); } Or using an enumeration: [servers enumerateKeysAndObjectsUsingBlock:^(NSString* serverId, NSString *serverName, BOOL *stop) { NSLog(@"server serverId: %@, serverName: %@", serverId, serverName); }]; A: You would do something like: [test enumerateKeysAndObjectsUsingBlock:^(NSString* serverId, NSString *serverName, BOOL *stop) { // Process data here. }];
{ "pile_set_name": "StackExchange" }
Q: Excel Column Equal to Text and Cell I'm trying to fill a column with an url as the text and column data directly after the slash in the url from another column. For example i want to input http://xxx.xxx.xxx/ column data goes here The text would be the url address and right after the slash is where i need the column data to go. can anyone help me out? A: Try the CONCATENATE function. =CONCATENATE("http://xxx.xxx.xxx/", A1)
{ "pile_set_name": "StackExchange" }
Q: NMinimize stops with no more memory? I am using NMinimize function for simulation based optimization. So my objective function is a simulation that runs for every combination of variable values evaluated by NMinimize function. However, the problem I have is the Nminimize function ceases after the first run (I am printing the time stamp for every iteration) and eventually after a long time gives me out of memory error. I even tried with different methods such as "RandomSearch" and "SimulatedAnnealing" with custom method parameter values, but in vain. Can some one pinpoint where I am going wrong? edit: My code is long, but as requested is given below: f[a1_, a2_, a3_] := Module[{b1 = a1, b2 = a2, b3 = a3, L = 3, Flen = 1, Rlen = 1,SimTime = 60, Kj = 150,w = 20,Theta = 5, dt = 6,delta = 1,DemandDuration = 10,RMstart = 1,RMLocation = 3, TT = 0}, Print[DateString[]]; Vf = Theta w; dx = Vf dt/3600; capacity = w*Vf*Kj/(Vf + w);n = Round[Flen/dx];m = Round[SimTime/dt];p = Round[Rlen/dx];Rdensity = Table[0*i, {i, p}, {i, m}, {i, n}];Rflow = Table[0*i, {i, p}, {i, m}, {i, n}];Fdensity = Table[0*i, {i, n}, {i, m}];Fflow = Table[0*i, {i, n}, {i, m}];demand[n_, k_] := Min[k*Vf, n*capacity];supply[n_, k_] := Min[(n*Kj - k)*w, n*capacity];flo[demand_, supply_] := Min[demand, supply];den[k_, qin_, qout_] := k + (qin - qout)/Vf; merge[n_, Fu_, Fd_, Rd_] := Min[1, supply[n, Fd]/(demand[n, Fu] + 0.01)]*demand[1, Rd]/delta;Nsupply[n_, k_, qsum_] := Min[(n*Kj - k)*Vf - qsum, n*capacity]; RM[x_, t_] := N[b1 x^2 + b2 x + b3];alpha[a_] := 1500*a/Flen;beta[a_] := 0.1*a/Flen; For[k = 1, k <= n, k++, For[i = 1, i <= p, i++, Rdensity[[i, 1, k]] = 0;]; For[j = 1, j <= DemandDuration, j++, Rdensity[[p, j, k]] = alpha[n*dx]*delta/Vf; TT = TT + Rdensity[[p, j, k]]];]; For[j = 1, j <= 4, j++, For[k = 1, k <= n, k++, If[k == 1, Rflow[[1, j, k]] = merge[L, Fdensity[[k, j]], Fdensity[[k, j]], Rdensity[[1, j, k]]], Rflow[[1, j, k]] = merge[L, Fdensity[[k, j]], Fdensity[[k - 1, j]], Rdensity[[1, j, k]]]]; If[k == 1, Fflow[[k, j]] = flo[demand[L, Fdensity[[k, j]]], supply[L, Fdensity[[k, j]]]], Fflow[[k, j]] = flo[demand[L, Fdensity[[k, j]]], supply[L, Fdensity[[k - 1, j]]] - Rflow[[1, j, k - 1]]*dx]]; If[k > 1 && j < m, Fdensity[[k - 1, j + 1]] = den[Fdensity[[k - 1, j]], (Rflow[[1, j, k - 1]] - beta[(n)*dx]*Fflow[[k, j]])*dx + Fflow[[k, j]], Fflow[[k - 1, j]]]; TT = TT + Fdensity[[k - 1, j + 1]];]; If[k == n && j < m, Fdensity[[k, j + 1]] = den[Fdensity[[k, j]], Rflow[[1, j, k]]*dx, Fflow[[k, j]]]; TT = TT + Fdensity[[k, j + 1]];]; For[i = 2, i <= p, i++, If[i == RMLocation && j >= RMstart, Rflow[[i, j, k]] = Min[RM[k dx, j dt], flo[demand[1, Rdensity[[i, j, k]]], supply[1, Rdensity[[i - 1, j, k]]]]], Rflow[[i, j, k]] = flo[demand[1, Rdensity[[i, j, k]]], supply[1, Rdensity[[i - 1, j, k]]]]]; If[j < m, Rdensity[[i - 1, j + 1, k]] = den[Rdensity[[i - 1, j, k]], Rflow[[i, j, k]], Rflow[[i - 1, j, k]]]; TT = TT + Rdensity[[i - 1, j + 1, k]];]];];]; For[j = 5, j <= m, j++, For[k = 1, k <= n, k++, If[k == 1, Rflow[[1, j, k]] = merge[L, Fdensity[[k, j]], Fdensity[[k, j]], Rdensity[[1, j, k]]], Rflow[[1, j, k]] = merge[L, Fdensity[[k, j]], Fdensity[[k - 1, j]], Rdensity[[1, j, k]]]]; FQsum = 0; For[r = 1, r <= Theta - 1, r++, FQsum = FQsum + Fflow[[k, j - r]]]; If[k == 1, Fflow[[k, j]] = flo[demand[L, Fdensity[[k, j]]], supply[L, Fdensity[[k, j]]]], Fflow[[k, j]] = flo[demand[L, Fdensity[[k, j]]], Nsupply[L, Fdensity[[k - 1, j - Theta + 1]], FQsum] - Rflow[[1, j, k - 1]]*dx]]; If[k > 1 && j < m, Fdensity[[k - 1, j + 1]] = den[Fdensity[[k - 1, j]], (Rflow[[1, j, k - 1]] - beta[(n)*dx]*Fflow[[k, j]])*dx + Fflow[[k, j]], Fflow[[k - 1, j]]]; TT = TT + Fdensity[[k - 1, j + 1]];]; If[k == n && j < m, Fdensity[[k, j + 1]] = den[Fdensity[[k, j]], Rflow[[1, j, k]]*dx, Fflow[[k, j]]]; TT = TT + Fdensity[[k, j + 1]];]; For[i = 2, i <= p, i++, RQsum = 0; For[r = 1, r <= Theta - 1, r++, RQsum = RQsum + Rflow[[i, j - r, k]]]; If[i == RMLocation && j >= RMstart, Rflow[[i, j, k]] = Min[RM[k dx, j dt], flo[demand[1, Rdensity[[i, j, k]]], Nsupply[1, Rdensity[[i - 1, j - Theta + 1, k]], RQsum]]], Rflow[[i, j, k]] = flo[demand[1, Rdensity[[i, j, k]]], Nsupply[1, Rdensity[[i - 1, j - Theta + 1, k]], RQsum]]]; If[j < m, Rdensity[[i - 1, j + 1, k]] = den[Rdensity[[i - 1, j, k]], Rflow[[i, j, k]], Rflow[[i - 1, j, k]]]; TT = TT + Rdensity[[i - 1, j + 1, k]];]];];]; TT] NMinimize[{f[x, y, z], {x, y,z} \[Element] Integers}, {{x , 27, 30}, {y, 797, 800}, {z, 2497, 2500}}]; Ps. Also any suggestions to improve the performance of this code will be greatly appreciated!! A: The solution to release memory space is redefine functions (Fdensity, Fflow, etc) conveniently in order to reduce the number of excessive functional calls in the execution. Using the Alexey Popkov's routine ("Profiling memory usage in Mathematica") we have the following result for the allocated bytes: - 6739593360 Fdensity - 1984112096 Fflow - 1679274128 Rdensity - 1453549616 Rflow - 37327744 FQsum - 977560 RQsum Also, it is necessary the use of _?NumericQ restriction in the functions to avoid inconvenient symbolic processing.
{ "pile_set_name": "StackExchange" }
Q: How can I download a previous git commit in Netbeans? I see Revert Commit. Will that erase current commits? I just want to pull a previous commit without affecting the overall project. Thanks. A: I hope this is the answer for you Scenario: 1)User selects a versioned context and invokes 'revert' from the main menu 2)Dialog pops up asking for additional revert options - revisions etc. 3)A new revision is created which reverts the previous commits Command Line 1) You have to see all commits. Use git log. You will see the commits with hascode, then 2)Then use git reset --hard <SHAsum of your commit> See this
{ "pile_set_name": "StackExchange" }
Q: Android Problem with special character phone numbers and ACTION_CALL I found a problem which I can't find solution, maybe someone has seen this before? I use this to perform a call, now if the call is a special number such as *111#, the character # is not sent to the activity, resulting in a call to *111 without the # character. Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); Anyone understand what happens? A: You should url-encode your tel:*111#: String telUri = "tel:" + Uri.encode("*111#");
{ "pile_set_name": "StackExchange" }
Q: Update PostgreSQL tables with one SQL query I have these two tables which I would like to update with one SQL query using Java code: CREATE TABLE ACCOUNT( ID INTEGER NOT NULL, USER_NAME TEXT NOT NULL, PASSWD TEXT, FIRST_NAME TEXT, LAST_NAME TEXT, E_MAIL TEXT NOT NULL, COUNTRY TEXT, STATE TEXT, LAST_PASSWD_RESET DATE, DESCRIPTION TEXT, LAST_UPDATED DATE, CREATED DATE ) ; -- ADD KEYS FOR TABLE ACCOUNT ALTER TABLE ACCOUNT ADD CONSTRAINT KEY1 PRIMARY KEY (ID) ; ALTER TABLE ACCOUNT ADD CONSTRAINT USER_NAME UNIQUE (USER_NAME) ; ALTER TABLE ACCOUNT ADD CONSTRAINT E_MAIL UNIQUE (E_MAIL) ; -- TABLE ACCOUNT_ROLE CREATE TABLE ACCOUNT_ROLE( ID INTEGER NOT NULL, USER_NAME TEXT NOT NULL, ROLE INTEGER, PERMISSION TEXT, LAST_UPDATED DATE, CREATED DATE ) ; -- CREATE INDEXES FOR TABLE ACCOUNT_ROLE CREATE INDEX IX_RELATIONSHIP19 ON ACCOUNT_ROLE (ID) ; -- ADD KEYS FOR TABLE ACCOUNT_ROLE ALTER TABLE ACCOUNT_ROLE ADD CONSTRAINT KEY26 PRIMARY KEY (ID) ; ALTER TABLE ACCOUNT_ROLE ADD CONSTRAINT RELATIONSHIP19 FOREIGN KEY (ID) REFERENCES ACCOUNT (ID) ON DELETE CASCADE ON UPDATE CASCADE ; I use this SQL query to update first table data. For the second table I use similar SQL query: UPDATE ACCOUNT SET ID = ?, USER_NAME = ?, PASSWD = ?, FIRST_NAME = ?, LAST_NAME = ?, E_MAIL = ?, COUNTRY = ?, STATE = ?, " CITY = ?, ADDRESS = ?, STATUS = ?, SECURITY_QUESTION = ?, SECURITY_ANSWER = ?, DESCRIPTION = ?, LAST_UPDATED = CURRENT_DATE WHERE ID = ? How this can solve this? A: In Postgres, you can update two tables by using CTEs: with t1 as ( update . . . returning * ) update t2 . . . It is unclear how this fits into what you are trying to do. But it is possible to write one statement in Postgres that does two updates.
{ "pile_set_name": "StackExchange" }
Q: ARKit - how to place an object without attaching it to the surface? Using ARKit I can place an object on the surface by tapping on the screen. Is it possible to place an object "in the air" instead? For example, I want to open a portal in front of me. So when I tap on the screen I want the portal to appear at this location, but I don't want it to be attached to any surface. Probably I have to use coordinates of my finger tap and axes of my device, but for z-axis (distance between me and the portal) I want to use some predefined value, like 1 meter for example. How can it be made in C# (for ARKit in Unity)? A: ScreenToWorldPoint() will do what you want. This simple example places a cube 1 meter in front of the camera. Just replace the GameObject.CreatePrimitive() part and Instantiate() your "portal" prefab instead: public class PlaceObject : MonoBehaviour { float objDist = 1.0f; void Update() { if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began ) { Vector3 touchPos = Input.GetTouch (0).position; touchPos.z = objDist; Vector3 objPos = Camera.main.ScreenToWorldPoint (touchPos); GameObject myObj = GameObject.CreatePrimitive(PrimitiveType.Cube); myObj.transform.position = objPos; myObj.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); } } }
{ "pile_set_name": "StackExchange" }
Q: Running Database Script Error SQL Server/ Report Server I keep receiving this error and am unable to fix it - can anyone help? Before I start the below instructions, I set up SQL Server 2014 on my computer. What I did before? I change Use built-in account to Network Service; Then in Web Service URL section, I changed default IP-ADRESS setting All Assigned(recommended) into protocol form, and also TCP Port --> 80 to 800; After that, I came to Database section. I clicked on Change Database button --> Create a new report server database. At the end of creating process I receive this error message: Can anyone help me, please? A: Your database user must be a member of dbcreator server role to create the ReportServer and ReportServerTemp databases. To add a member to dbcreator, you must be a member of that role, or be a member of the sysadmin. With the following script you can add permission required: ALTER SERVER ROLE dbcreator ADD MEMBER YourDatabaseUser;
{ "pile_set_name": "StackExchange" }
Q: In python, how can I use timeout in subprocess *and* get the output I used the code in these 2 question how to get the return value from a thread in python subprocess with timeout And got this import subprocess, threading, os class ThreadWithReturnValue(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None): threading.Thread.__init__(self, group, target, name, args, kwargs, Verbose) self._return = None def run(self): if self._Thread__target is not None: self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs) def join(self, timeout = None): threading.Thread.join(self, timeout) return self._return class SubprocessWrapper(object): def __init__(self, cmd, timeout): self.cmd = cmd self.process = None self.timeout = timeout def run(self): def target(cmd): self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE) returnValue = self.process.communicate() return [returnValue[0], returnValue[1], self.process.returncode] thread = ThreadWithReturnValue(target=target, args=[self.cmd]) thread.start() returnValue = thread.join(self.timeout) if thread.is_alive(): print 'cmd = ',self.cmd self.process.kill() returnValue = thread.join() print 'rc = ', returnValue[2] output = returnValue[0] error = returnValue[1] rc = returnValue[2] return (output, rc) os.system('date +%T.%N') s1 = SubprocessWrapper("echo 'Process started'; sleep 2; echo 'Process finished'", timeout = 3) s1.run() os.system('date +%T.%N') s2 = SubprocessWrapper("echo 'Process started'; sleep 2; echo 'Process finished'", timeout = 1) s2.run() os.system('date +%T.%N') The problem is that the output is 11:20:34.963947950 11:20:36.986685289 cmd = echo 'Process started'; sleep 2; echo 'Process finished' rc = -9 11:20:38.995597397 So you can see the process which was supposed to be terminated after one second actually took 2 seconds. This happens because of the join() but in the question subprocess with timeout this works fine. This means that when I integrated both codes I caused this problem, my question is how to fix it? I was thinking that I might need to call threading.Thread.__init__ method in a different way but I can't understand how. A: This code doesn't return output in one second despite the timeout. It returns it in two seconds after the sleep: #!/usr/bin/env python3 from subprocess import TimeoutExpired, check_output as qx from timeit import default_timer as timer start = timer() try: qx("echo 'Process started'; sleep 2; echo 'Process finished'", shell=True, universal_newlines=True, timeout=1) except TimeoutExpired as e: print("Got %r in %.2f seconds" % (e.output, timer() - start)) else: assert 0 # should not get here Output Got 'Process started\n' in 2.00 seconds Alarm-based solution from "Stop reading process output in Python without hang?" question works: #!/usr/bin/env python import signal from subprocess import Popen, PIPE from timeit import default_timer as timer class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm start = timer() # start process process = Popen("echo 'Process started'; sleep 2; echo 'Process finished'", shell=True, stdout=PIPE, bufsize=1, universal_newlines=True) # set signal handler signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(1) # produce SIGALRM in a second buf = [] try: for line in iter(process.stdout.readline, ""): buf.append(line) # assume it is atomic except Alarm: process.kill() else: signal.alarm(0) # reset alarm finally: output = ''.join(buf) print("Got %r in %.2f seconds" % (output, timer() - start)) process.stdout.close() process.wait() Output Got 'Process started\n' in 1.00 seconds
{ "pile_set_name": "StackExchange" }
Q: Interactive Brokers Java API If I want to use the Interactive Brokers Java API to check current positions, and then rebalance those positions, by selling or buying shares of each position, do I just need to use the EWrapper.position() method to get the current positions in the account? Or do I use the EClientSocket.reqPositions() method to get it? It seems that Ewrapper is for receiving information from TWS to the client, while EClientSocket is for sending requests to TWS. In this case, do I use both position() and reqPosition() methods? In addition, when I am running the new Java class, do I need to put it in the same folder as the ib.client in order to inherit the other classes and methods? A: It seems that Ewrapper is for receiving information from TWS to the client, while EClientSocket is for sending requests to TWS. In this case, do I use both position() and reqPosition() methods? That's right. It's asynchronous so you make a request and hope that sometime soon, you'll get an answer. All requests go through the socket and all replies come through the wrapper. In addition, when I am running the new Java class, do I need to put it in the same folder as the ib.client in order to inherit the other classes and methods? This is very basic java and it's best if you do some tutorials from somewhere. In order to use the ib.client methods you import them into your file. eg. At the top of a file that needs to use this package you can put import com.ib.client.* and then make sure the files are in a folder in your source directory like src/com/ib/client/*.java Or you can make it into a library and include the library in you project.
{ "pile_set_name": "StackExchange" }
Q: how to set a variable to 0.001 in JAVA (android) when i want to get the result of 100/100000.. i got only 0. Example int one = 100; int two = 100000; int result = one/two; toast(result); //Result is 0 A: Hey there "int" data type only stores integer values and not the decimals. So if you divide 3 with 2 you would get 1 as answer instead of 1.5 . Int just ignores the decimals . You need to choose float or double data type for this to work. Your variable named result must be declared and casted to float data type. Appreciate the effort and mark this as answer if it helps you.....
{ "pile_set_name": "StackExchange" }
Q: Face Lock Authentication NPM which works for android using React Native I am searching NPM which can work to Authenticate using face, I have tried below NPM but none of below were not working , React-native-biometrics - works for android version greater or equal 10 react-native-fingerprint-scanner - working for Finger But not for the Face Authentication, React Native Face Recognition - not working gradle version issue Any developer already worked on face authentication using react native please guide me, A: My journey towards the success of execution of above question First I tried many library but none was working. Reason behind it was is React Native Version 0.59.9 which was not supporting Face Id. Then I thought to Customised Android Java Native Modules, When I learnt to Customised Native Modules, I Found Native Modules required Androidx to work Biometrics. Androidx required react native version greater or equal to 0.60.0+. so its not possible to use face Id using version 0.59.9. Finally I updated the version. So it is working in the latest version of React Native.
{ "pile_set_name": "StackExchange" }
Q: Setting dropdown to first value I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it: Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue()); Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have: var displayedValue = Global.getComponent("ddlVehicleType").getRawValue(); if (IsNumeric(displayedValue)) { } A: Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page: var newId = 0; var firstId = 0; var typeStore = Global.getComponent("ddlVehicleType").getStore(); firstId = typeStore.getAt(0).get('LookupID'); typeStore.each(function(rec) { if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue()) { newId = Global.getComponent("DefaultVehicleTypeId").getValue(); } }); if (newId != 0) { Global.getComponent("ddlVehicleType").setValue(newId); } else { Global.getComponent("ddlVehicleType").setValue(firstId); }
{ "pile_set_name": "StackExchange" }
Q: Is it legal to have multiple HTTP GET parameters with the name? Is it "legal", according to the HTTP protocol, to make an HTTP GET request that contains multiple parameters with the same name? For example /controller?name=John&name=Patrick&name=Jack I'm sure different clients and servers react differently, however I am asking best practices, for example if you were to write a new server from scratch, or a new browser, client or whatever code that writes or parses HTTP requests: how should you handle such requests? Is it allowed? In which case what is the interpretation? Or is it non-standard? Same question for POST applies. A: From HTTP's point of view, it doesn't matter - it doesn't put /any/ restrictions on what is in the query part of a an HTTP URI.
{ "pile_set_name": "StackExchange" }
Q: Skip RewriteCond in .htaccess file I already have defined the following condition in .htaccess file: RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif)$ RewriteRule ^products/(.*)/(.*)$ /browse.php?table=catalog&from=$2 Now, in this condition I have to add more. One of them is to skip defined rules if filename is: /products/util/calendar.php Can you help me how to add it in condition defined above. Thank you! A: Something like that should do it: RewriteCond %{REQUEST_URI} !^/products/util/calendar.php$ The Apache documentation is pretty dense, use it: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#RewriteCond
{ "pile_set_name": "StackExchange" }
Q: valgrind error Invalid read of size 8 So I have valgrind complaining with this error in this function: int getMembersNum(Party party){ assert(party != NULL); int i = 0; while (party->members[i] != NULL && i < party->maxMembersNum) <-- HERE i++; return i; } Party is a pointer to a struct and party->members is of type char**. When initialized with malloc all of party->members cells are set to NULL. What am I missing? A: You need to test before you use. while (party->members[i] != NULL && i < party->maxMembersNum) should be while (i < party->maxMembersNum && party->members[i] != NULL)
{ "pile_set_name": "StackExchange" }
Q: Calling a Function From Another Function in PowerShell First time in PowerShell 5 and I'm having trouble calling a function that writes messages to a file from another function. The following is a simplified version of what I'm doing. workflow test { function logMessage { param([string] $Msg) Write-Output $Msg } function RemoveMachineFromCollection{ param([string]$Collection, [string]$Machine) # If there's an error LogMessage "Error Removing Machine" # If all is good LogMessage "successfully remove machine" } $Collections = DatabaseQuery1 foreach -parallel($coll in $Collections) { logMessage "operating on $coll collection" $Machines = DatabaseQuery2 foreach($Mach in $Machines) { logMessage "Removing $Mach from $coll" RemoveMachineFromCollection -Collection $coll -Machine $Mach } } } test Here's the error it generates: The term 'logMessage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. + CategoryInfo : ObjectNotFound: (logMessage:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException + PSComputerName : [localhost] I've tried moving the logMessage function around in the file and even tried Global scope. In any other language I would be able to call logMessage from any other function. As that's the purpose of a function. What's the "Workflow way" of reusing a block of code? Do I need to create some logging module that gets loaded into the Workflow? A: You could move the functions and function call to an InlineScript (PowerShell ScriptBlock) inside the workflow like below. workflow test { InlineScript { function func1{ Write-Output "Func 1" logMessage } function logMessage{ Write-Output "logMessage" } func1 } } Would Output: Func 1 logMessage As @JeffZeitlin mentioned in his answer, workflows are not PowerShell and are much more restrictive. The InlineScript block allows for normal PowerShell code to be interpreted however the scope will be tied to the InlineScript block. For instance, if you define the functions in the script block then attempt to call the func1 function outside of the InlineScript block (but still within the workflow) it will fail because it is out of scope. The same would happen if you define the two functions either outside of the workflow or inside of the workflow but not in an InlineScript block. Now for an example of how you can apply this to running a foreach -parallel loop. workflow test { ## workflow parameter param($MyList) ## parallel foreach loop on workflow parameter foreach -parallel ($Item in $MyList) { ## inlinescript inlinescript { ## function func1 declaration function func1{ param($MyItem) Write-Output ('Func 1, MyItem {0}' -f $MyItem) logMessage $MyItem } ## function logMessage declaration function logMessage{ param($MyItem) Write-Output ('logMessage, MyItem: {0}' -f $MyItem) } ## func1 call with $Using:Item statement ## $Using: prefix allows us to call items that are in the workflow scope but not in the inlinescript scope. func1 $Using:Item } } } Example call to this workflow would look like this PS> $MyList = 1,2,3 PS> test $MyList Func 1, MyItem 3 Func 1, MyItem 1 Func 1, MyItem 2 logMessage, MyItem: 3 logMessage, MyItem: 2 logMessage, MyItem: 1 You will notice (and as expected) the output order is random since it was run in parallel.
{ "pile_set_name": "StackExchange" }
Q: D3 Display elements of inner list on tool tip as different lines A quick and short question in d3. I have the following data in json: {"KMAE":[-120.12,36.98,"MADERA MUNICIPAL AIRPORT",[26,1,2,5,6,3,2,1,2,7,29,12,3]]} I am plotting this point on a google map and applying a tool tip on the point. On the tool tip what I have given now is .on("mouseover", function(d) { div.transition() .duration(200) .style("opacity", .9); div .html(d.value[3]) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px"); }) Well what now I am getting when mouse over happens is 26,1,2,5,6,3,2,1,2,7,29,12,3. How can we make this in different lines inside the tool tip? Say like: 26 on top, 1 below that, 2 below that and so on. In my actual application this inner list's length wont be the same for many points like KMAE. Thanks A: Since you're using HTMl for the tooltip, it's easy -- join the array elements with <br>: div.html(d.value[3].join("<br>"))
{ "pile_set_name": "StackExchange" }
Q: QGIS How to draw lines from two points in a CSV? I have a largely identical query to How to draw lines from two points in a CSV?, however the solution listed isnt working for me. My original text format is PID, Start Northing, Start Easting, End Northing, End Easting. I've tried in excel to make into a WKT compatible format, i.e. BL2990;LINESTRING(490206.73 214102.673, 490236.94 214134.576) This works when pasting a single line into QuickWKT, however I can't paste multiple lines in...is QuickWMT intended for a quick preview of single objects only? In terms of importing as a delimited text file, I have arranged as: ID;GEOM "BL2990";"LINESTRING(490206.73 214102.673, 490236.94 214134.576)" Etc, and saved as a .txt file. When I import as delimited text and select ";" as delimiter, the import creates the 2 column headers but fails to split the data string into ID and Geometry fields. What am I doing wrong? I've tested importing the .txt while excluding the ID header and ID text string which works fine, however it is critical that the lines retain their identifier. A: Your data looks ok. In the Delimited text input form, the Geometry definition should be set to WKT, and the Geometry Field to the column containing the WKT. That way you get the linestring into QGIS. If you change the name of the second column from GEOM to WKT, QGIS automatically sets the Geometry definition and Geometry Field to that column.
{ "pile_set_name": "StackExchange" }
Q: Android - is there a possibility to make infinite canvas? Currently I am doing app allowing user to draw. Simple think, just extend Canvas class and most of the thing is done. That was my initial thinking and idea. But as the canvas is rather small because this is only what user see on the screen there is not much possible space to draw. Going through documentation I found translate() method allowing me to move canvas. What I did find out is when I move it, there is some kind of blank space just as you would move piece of paper. I understand that this is totally normal, as I've said before - canvas is only "the screen". My question is - is there a possibility to make something like infinite canvas so you can make a huge painting and move everything around? Before this question I was thinking about two things how something like this can be done: Move all objects on canvas simultaneously - bad idea, because if you have a lot of them then the speed of moving is very bad. Do something similar as it is done in ListView when you move it (or better see on the screen) only views that are on the screen together with one before and one after are loaded to memory and rest is uploaded dynamically when needed. I think this is the best option to achieve this goal. EDIT: Question/answer given by Kai showed me that it is worth to edit my question to clarify some of the things. Basic assumptions about what can be done by user: User is given opportunity to draw only circles and rectangles with some (around 80%) having drawable (bitmap) on them on canvas. I assume that on all screens there will be maximum 500-800 rectangles or circles. First of all thinking about infinity I was thinking about quite big number of screens - at least 30 on zoom 1x in each side. I just need to give my users bigger freedom in what they are doing. On this screen everything can be done as on normal - draw, scale (TouchListener, ScaleListener, DoubleTapListener). When talking about scaling, there is another thing that has to be concerned and connected with "infinity" of canvas. When user is zooming out then screens, or more precise objects on the invisible "neighbours" should appear with proper scaling as you would zoom out camera in real life. The other thing that I've just realised is possibility of drawing at small zoom level - that is on two or three screens and then zooming in - I suppose it should cut and recalculate it as a smaller part. I would like to support devices at least from API 10 and not only high-end. The question about time is the most crucial. I want everything to be as smooth as possible, so user wouldn't know that new canvas is being created each time. A: I think it really depends on a number of things: The complexity of this "infinite canvas": how "infinite" would it really be, what operations can be done on it, etc The devices that you want to support The amount of time/resource you wish to spend on it If there are really not that many objects/commands to be drawn and you don't plan to support older/lower end phones, then you can get away with just draw everything. The gfx system would do the checking and only draws what would actually be shown, so you only waste some time to send commands pass JNI boundary to the gfx system and the associated rect check. If you decided that you needs a more efficient method, you can store all the gfx objects' positions in 4 tree structures, so when you search the upper-left/upper-right/lower-left/lower-right "window" that the screen should show, it'll fast to find the gfx objects that intersects this window and then only draw those. [Edit] First of all thinking about infinity I was thinking about quite big number of screens - at least 30 on zoom 1x in each side. I just need to give my users bigger freedom in what they are doing. If you just story the relative position of canvas objects, there's practically no limit on the size of your canvas, but may have to provide a button to take users to some point on canvas that they are familiar lest they got themselves lost. When talking about scaling, there is another thing that has to be concerned and connected with "infinity" of canvas. When user is zooming out then screens, or more precise objects on the invisible "neighbours" should appear with proper scaling as you would zoom out camera in real life. If you store canvas objects in a "virtual space", and using a "translation factor" to translate objects from virtual space to screen space then things like zoom-in/out would be quite trivial, something like screenObj.left=obj.left*transFactor-offsetX; screenObj.right=obj.right*transFactor-offsetX; screenObj.top=obj.top*transFactor-offsetY; screenObj.bottom=obj.bottom*transFactor-offsetY; //draw screenObj As an example here's a screenshot of my movie-booking app: The lower window shows all the seats of a movie theater, and the upper window is a zoomed-in view of the same theater. They are implemented as two instances of the same SurfaceView class, besides user input handling, the only difference is that the upper one applies the above-mentioned "translation factor". I assume that on all screens there will be maximum 500-800 rectangles or circles. It is actually not too bad. Reading your edit, I think a potentially bigger issue would be if an user adds a large number of objects to the same portion of your canvas. Then it wouldn't matter if you only draw the objects that are actually shown and nothing else - you'd still get bad FPS since the GPU's fill-rate is saturated. So there are actually two potential sources of issues: Too many draw commands (if drawing everything on canvas instead of just drawing visible ones) Too many large objects in the same part of the screen (eats up GPU fill-rate) The two issues requires very different strategy (1st one using tree structures to sort objects, 2nd one using dynamically generated Bitmap cache). Since how users use your app are likely to different than how you envisioned it to be, I would strongly recommend implementing the functions without the above optimizations, try to get as many people as possible to do testing, and then apply optimizations to each of the bottlenecks you encounter until the satisfactory performance is achieved. [Edit 2] Actually with just 500~800 objects, you can just calculate the position of all the objects, and then check to see if they are visible on screen, you don't even really need to use some fancy data structures like a tree with its own overheads.
{ "pile_set_name": "StackExchange" }
Q: How i can pass information into a GET in node i dont know how i can pass some information into a GET in node. I have a .txt file and sometimes have a change in this file, so, i want to show this change when i enter in my webpage, but the change only occurs when the server refresh. var itens = func.readfile(); app.get("/inventario", function(req, res){ res.format({ html: function(){ res.render('inventario', {itenss: func.readfile()}); } }); i have a variable that receive a data from a function in other file. exports.readfile = function() { var texto = []; fs.readFile('./static/itens.txt', function(err, data) { if (err) { return console.error(err); } var palavra = ''; var linha = []; for (var i = 0; i < data.length; i++) { if (data[i] != 10) { palavra = palavra + (String.fromCharCode(data[i])); } else if (data[i] == 10) { texto.push(palavra); palavra = []; } } console.log(texto); }); return texto; } so if the variable is out of scope, the page can receive the data and show in html file, but, i want to refresh the data in array case i refresh the page and the new information in .txt file is shown too A: fs.readFile() is asynchronous. That means that when you call the function, it starts the operation and then immediately returns control back to the function and Javascript busily executes more Javascript in your function. In fact, your readFile() function will return BEFORE fs.readFile() has called its callback. So, you cannot return the data directly from that function. Instead, you will need to either return a promise (that resolves when the data is eventually available) or you will need to communicate the result back to the caller using a callback function. See this answer: How do I return the response from an asynchronous call? for a lot more info on the topic. You can modify your readFile() function to return a promise (all async functions return a promise) like this: const fsp = require('fs').promises; exports.readfile = async function() { let texto = []; let data = await fsp.readFile('./static/itens.txt'); let palavra = ''; let linha = []; for (var i = 0; i < data.length; i++) { if (data[i] != 10) { palavra = palavra + (String.fromCharCode(data[i])); } else if (data[i] == 10) { texto.push(palavra); palavra = []; } } console.log(texto); return texto; } And, then you can use that function like this: app.get("/inventario", function(req, res){ res.format({ html: function(){ func.readFile().then(data => { res.render('inventario', {itenss: data}); }).catch(err => { console.log(err); res.sendStatus(500); }); } }); For performance reasons, you could also cache this result and cache the time stamp of the itens.txt file and only reread and reprocess the file when it has a newer timestamp. I'll leave that as an exercise for you to implement if it is necessary (may not be needed).
{ "pile_set_name": "StackExchange" }
Q: Get original texture color in a Fragment Shader in OpenGL So, I need to make a shader to replace the gray colors in the texture with a given color. The fragment shader works properly if I set the color to a given specific one, like gl_FragColor = vec4(1, 1, 0, 1); However, I'm getting an error when I try to retrieve the original color of the texture. It always return black, for some reason. uniform sampler2D texture; //texture to change void main() { vec2 coords = gl_TexCoord[0].xy; vec3 normalColor = texture2D(texture, coords).rgb; //original color gl_FragColor = vec4(normalColor.r, normalColor.g, normalColor.b, 1); } Theoretically, it should do nothing - the texture should be unchanged. But it gets entirely black instead. I think the problem is that I'm not sure how to pass the texture as a parameter (to the uniform variable). I'm currently using the ID (integer), but it seems to return always black. So I basically don't know how to set the value of the uniform texture (or to get it in any other way, without using the parameters). The code (in Java): program.setUniform("texture", t.getTextureID()); I'm using the Program class, that I got from here, and also SlickUtils Texture class, but I believe that is irrelevant. A: program.setUniform("texture", t.getTextureID()); ^^^^^^^^^^^^^^^^ Nope nope nope. Texture object IDs never go in uniforms. Pass in the index of the texture unit you want to sample from. So if you want to sample from the nth texture unit (GL_TEXTURE0 + n) pass in n: program.setUniform("texture", 0); ^ or whatever texture unit you've bound `t` to
{ "pile_set_name": "StackExchange" }
Q: Merge [javascript] and [jquery] tags There is often confusion among beginners. Most of the time, when they ask a JavaScript question, what they really want is JQuery. In fact, every problem can be solved with JQuery. We should make javascript a synonym of jquery and merge the two. A: That sounds reasonable. It's about time everyone dropped Javascript and tried jQuery. A: I agree. There is no point in using esoteric javascript when the new jQuery language is available. jQuery should be used everywhere especially when creating native applications on mobile devices. jQuery jQuery jQuery bacon. Javascript is only for scripting, jQuery is for everything else. A: Unfortunately there are still a few legacy COBOL systems out there running JavaScript (mostly corporate financial systems). These older systems aren't powerful enough to run the full jQuery stack, so we may need to keep the JavaScript tag around for a while longer.
{ "pile_set_name": "StackExchange" }
Q: If matrix $A$ has entries $A_{ij}=\sin(\theta_i - \theta_j)$, why does $\|A\|_* = n$ always hold? If we let $\theta\in\mathbb{R}^n$ be a vector that contains $n$ arbitrary phases $\theta_i\in[0,2\pi)$ for $i\in[n]$, then we can define a matrix $X\in\mathbb{R}^{n\times n}$, where \begin{align*} X_{ij} = \theta_i - \theta_j. \end{align*} Then the matrices that I consider are the antisymmetric matrix $A=\sin(X)$ and the symmetric matrix $B=\cos(X)$. Through numerical experiments (by randomly sampling the phase vector $\theta$) I find that the nuclear norm of $A$ and $B$ are always $n$, i.e. \begin{align*} \|A\|_* = \|B\|_* = n. \end{align*} Moreover, performing SVD on $A$ yields the largest two singular value $\sigma_1 = \sigma_2 = n/2$ and all the other $\sigma_3 = \ldots = \sigma_n = 0$. Further, if we look at the matrix $A\circ B$, where \begin{align*} (A\circ B)_{ij} = \sin(\theta_i - \theta_j)\cos(\theta_i - \theta_j) = \sin(2(\theta_i - \theta_j))/2, \end{align*} then \begin{align*} \|A\circ B\|_* = n/2 \end{align*} with $\sigma_1 = \sigma_2 = n/4$ and $\sigma_3 = \ldots = \sigma_n = 0$. Is there any way to see why $A$ and $B$ have these properties? A: I will stick to your notation in which $f(X)$ refers to the matrix whose entries are $f(X_{ij})$. Note that by Euler's formula, we have $$ \sin(X) = \frac 1{2i}[\exp(iX) - \exp(-iX)] $$ To see that $\exp(iX)$ has rank $1$, we note that it can be written as the matrix product $$ \exp(iX) = \pmatrix{\exp(i\theta_1) \\ \vdots \\ \exp( i\theta_n)} \pmatrix{\exp(-i\theta_1) & \cdots & \exp( -i\theta_n)} $$ Verify also that $\exp(iX)$ is Hermitian (and positive definite), as is $\exp(-iX)$. So far, we can conclude that $\sin(X)$ has rank at most equal to $2$. Since $\exp(iX)$ is Hermitian with rank 1, we can quickly state that $$ \|\exp(iX)\|_* = |\operatorname{tr}(\exp(iX))| = n $$ So, your numerical evidence seems to confirm that $$ \left\|\frac 1{2i}[\exp(iX) - \exp(-iX)]\right\|_* = \left\|\frac 1{2i}\exp(iX)\right\|_* + \left\|\frac 1{2i}\exp(-iX)\right\|_* $$ From there, we note that $A = \sin(X)$ satisfies $$ 4 A^*A = [\exp(iX) - \exp(-iX)]^2 = \\ n [\exp(iX) + \exp(-iX)] - \exp(iX)\exp(-iX) - \exp(-iX)\exp(iX) =\\ n [\exp(iX) + \exp(-iX)] - 2 \operatorname{Re}[\exp(iX)\exp(-iX)] $$ where the exponent here is used in the sense of matrix multiplication. Our goal is to compute $\|A\|_* = \operatorname{tr}(\sqrt{A^*A})$. Potentially useful observations: We note that $$ \exp(iX)\exp(-iX) = \pmatrix{\exp(i\theta_1) \\ \vdots \\ \exp( i\theta_n)}\pmatrix{\exp(i\theta_1) & \cdots & \exp( i\theta_n)} \sum_{k=1}^n \exp(-2i\theta_k) $$ And $\operatorname{tr}[\exp(iX)\exp(-iX)] = \left| \sum_{k=1}^n \exp(2i\theta_k) \right|^2$. This product is complex-symmetric but not Hermitian. The matrices $\exp(iX),\exp(-iX)$ will commute if and only if $\exp(iX)\exp(-iX)$ is purely real (i.e. has imaginary part 0). I think that these matrices will commute if and only if $\sum_{k=1}^n \exp(2i\theta_k) = 0$ (which is not generally the case).
{ "pile_set_name": "StackExchange" }
Q: Call async method multiple time in window form application I have following method , i want to call this method multiple at same time. and want to check if any of the result string contains "Start" text then move control forward otherwise wait for "Start" in any result string. public async Task<string> ProcessURLAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam) { ExtendedWebClient oClient = new ExtendedWebClient(false); oClient.CookieContainer = oExtendedWebClient.CookieContainer; oClient.LastPage = "https://www.example.co.in/test/getajax.jsf"; byte[] PostData = System.Text.Encoding.ASCII.GetBytes(sParam); Headers.Add("User-Agent", "Mozilla/5.0 (Windows T 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36"); Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); Headers.Add("Content-Type", "application/x-www-form-urlencoded"); oClient.Headers.Remove("X-Requested-With"); oClient.Headers.Add("X-Requested-With", "XMLHttpRequest"); var byteArray = await oClient.UploadDataTaskAsync(url, PostData); string result = System.Text.Encoding.UTF8.GetString(byteArray); return result; } please suggest way to achieve this. A: What you could do, is edit your Task so that it runs in a while loop and only exits when your value is found. Then, create a list of tasks using a loop, iterating through as many tasks as you want it to run simultaneously . Then you can use Task.WhenAny public async Task<string> ProcessURLAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam) { string result = ""; while (!result.Contains("Start")) { ExtendedWebClient oClient = new ExtendedWebClient(false); oClient.CookieContainer = oExtendedWebClient.CookieContainer; oClient.LastPage = "https://www.example.co.in/test/getajax.jsf"; byte[] PostData = System.Text.Encoding.ASCII.GetBytes(sParam); Headers.Add("User-Agent", "Mozilla/5.0 (Windows T 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36"); Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); Headers.Add("Content-Type", "application/x-www-form-urlencoded"); oClient.Headers.Remove("X-Requested-With"); oClient.Headers.Add("X-Requested-With", "XMLHttpRequest"); var byteArray = await oClient.UploadDataTaskAsync(url, PostData); result = System.Text.Encoding.UTF8.GetString(byteArray); } return result; } And then use it like this: List<Task> taskList = new List<Task>(); for(int i = 0; i < 20; i++) //Run 20 at a time. taskList.Add(ProcessURLAsync(url, webClient, "whatever")); await Task.WhenAny(taskList); //Value found! Continue...
{ "pile_set_name": "StackExchange" }
Q: Android add ImageView programmatically I currently add images through xml with the whole R.id.x method with the following function: public void Image(int ID, int x, int y){ ImageView iv = (ImageView) findViewById(ID); RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); position.setMargins(x, y, 0, 0); iv.setLayoutParams(position); } I've written a new function to get these images on screen programmatically instead of parsing them in XML, with help from afore-mentioned topics/questions I searched and came up with this: public void ImageRAW(int ID, int x, int y){ ImageView iv = new ImageView(c); iv.setImageResource(ID); RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); position.setMargins(x, y, 0, 0); iv.setLayoutParams(position); rl.addView(iv); } But it did not work. I also tried adding the following line, to no avail: iv.setVisibility(View.VISIBLE); And in regards to the variables rl and c: private Context c; private RelativeLayout rl; public void SetUtilContext(Context context){ c = context; rl = new RelativeLayout(context); } The above function is called in every Activity's onCreate() function and sets the UtilLib's current Context and RelativeLayout for drawing accordingly. The function ImageRAW() is something I would like to use to replace the old Image() function, to make things easier for me. How would/could I get this working? A: Try add this before your SetUtilContext(): RelativeLayout menu = findViewById(R.layout.menu); And this at the end of your ImageRAW() method: menu.addChild(rl);
{ "pile_set_name": "StackExchange" }
Q: How to calculate Packet loss, Jitter and QoS parameters of video over an IP connection? I came across a mobile application which performs voice and video quality test to give a measure of the quality of voice/video experience over an IP connection. The test calculates the values of Jitter, Packet loss etc. for the remote stream. I am curious to know how this is being done? What would it take to write such an Mobile application? Help in any form is appreciated. Thanks. A: The easiest way to do this is to send data from a device through the network being tested and then receive it back again on the same device. This allows you to easily calculate the time taken for each packet (delay), the variance in time for different packets (jitter), and to detect any packet loss. Note that packet loss is a relative thing - a packet may be just delayed for a long time rather than lost. Typically if a packet is not received within a certain jitter window it may be declared as lost. In the real world you usually want to test from point 'A' to point 'B' (i.e. not just loping back to point 'A'). For a voice or video codec (encoder) which sends packets at a regular interval this is straightforward as you know that the second packet should arrive a given time after the first one and if it does not it is delayed (or has arrived early). From this you can calculate the jitter at point 'B'. Any packet not arriving (within the period you allow for packets to arrive) will be counted as a lost packet. Note that how a sample is encoded can cause issue with jitter calculation, although if you are creating a test application where you control the encoding yourself you can avoid these issues - see the link below for more on this: http://www.cs.columbia.edu/~hgs/rtp/faq.html#jitter One other thing to note is that you have not mentioned delay but it can be very important as you might have a network with no packet loss and excellent jitter, but with a large delay and this can have a dramatic affect on some applications (e.g. voice). As a simple and not very realistic example say you have a perfect network from a jitter and packet loss point of view, but with a router which does some sort of security lookup and hence adds a two second delay to every packet. Because it is the same delay for each packet your jitter will be fine, but for a two way voice application the two second delay between someone at point 'A' speaking and someone at point 'B' hearing them will be a major issue.
{ "pile_set_name": "StackExchange" }
Q: Sort colors by coordinates of a rectangle I am working on a program where I take a photo and find the squares in that photo then determine their RGB values. I am able to get this information successfully but when I find the RGB values and the coordinates where I got them from they come in the order of the contours I found them. My question is how can I take the colors and sort them in a way that I read it from the top left row to the bottom row like a book. Each color has the rectangles coordinates it was taken from, I want to use that to help me order them. I have an image showing what I want to order. When I get the RGB values from the images I print out the color and the coordinates. Here is what it looks like (Notice how they aren't ordered): 279,271 R: 106 G: 255 B: 183 188,270 R: 107 G: 255 B: 180 371,267 R: 102 G: 255 B: 169 274,178 R: 75 G: 255 B: 99 185,179 R: 84 G: 255 B: 103 369,175 R: 89 G: 255 B: 105 277,88 R: 96 G: 255 B: 103 184,85 R: 101 G: 255 B: 110 370,84 R: 124 G: 255 B: 126 My code that I use to get them is here: I just don't know how I could take the colors and store them sorted. private void getColors(Mat img2read , Rect roi){ int rAvg = 0 , bAvg = 0, gAvg = 0; int rSum = 0, bSum = 0, gSum = 0; img2read = new Mat(img2read, roi); //image size of rect (saved contour size and coordinates) img2read.convertTo(img2read, CvType.CV_8UC1); //convert to workable type for getting RGB data int totalBytes = (int) (img2read.total() * img2read.channels()); byte buff[] = new byte[totalBytes]; int channels = img2read.channels(); img2read.get(0,0,buff); int stride = channels * img2read.width(); for(int i = 0; i < img2read.height();i++){ for(int x = 0; x < stride; x+= channels){ int r = unsignedToBytes(buff[(i * stride) + x]); int g = unsignedToBytes(buff[(i * stride)+ x + 1]); int b = unsignedToBytes(buff[(i * stride)+ x + 2]); rSum += r; gSum += g; bSum += b; } } float[] hsv = new float[3]; rAvg = (int) (rSum / img2read.total()); gAvg = (int) (gSum / img2read.total()); bAvg = (int) (bSum / img2read.total()); Color.RGBtoHSB(rAvg, gAvg, bAvg, hsv); hsv[2] = 1; //Set to max value int rgb = Color.HSBtoRGB(hsv[0], hsv[1], hsv[2]); Color brightenedColor = new Color(rgb); System.out.println(); System.out.println(roi.x + "," + roi.y); System.out.printf("R: %s G: %s B: %s \n", brightenedColor.getRed(), brightenedColor.getGreen(), brightenedColor.getBlue()); Color colorToAdd = new Color(brightenedColor.getRed(), brightenedColor.getGreen(), brightenedColor.getBlue()); Point coords = new Point(roi.x, roi.y); //colorCoords.put(coords, colorToAdd); /*counter++; if(counter == 9){ sortColors(colorCoords); }*/ } int counter = 0; Map <Point, Color> colorCoords = new TreeMap<>(); Color[] colorArray = new Color[54]; int currentIndex = 0; //Not really sure what I'm doing here but I don't think it is right. private void sortColors(Map<Point, Color> colorCoords){ for(int i = 0; i < colorCoords.size();i++){ // colorCoords.get(key) } } A: Put those values in to an object, and store them into a List. To sort, you could add a static Comparator field, or make it implement Comparable something like this: public class Block implement Comparable<Block> { public int x, y; public Color color; @Override public int compareTo(Block other) { if (null==other) throw new NullPointerException(); // implement the logic, like: // this will compare X, unless difference in Y is more than EG 10 return Math.abs(y - other.y) > 10 ? y - other.y : x - other.x; } public Color getColor() { return color; } } public List<Block> blocks = new ArrayList<>(); To sort you can use Collections.sort(blocks); Edited the above comparison to make to your needs... With Java8's streams it should be doable to get a sorted array of Colors. But i am not a streams expert. Try something like this: Color[] colors = blocks.stream().sorted().map(Block::getColor).toArray(); For this to work Block.getColor() method is needed, see above.
{ "pile_set_name": "StackExchange" }
Q: Why I'm not able to print the value of list in jsp page? Why I'm not able to print the value of list in JSP page? I'm able to print the value of list in console but not in JSP page using Struts2 This is my jsp: getdetails.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <s:form action="details.action"> <s:submit value="getresponse" align="center" /> </s:form> </body> </html> This is my Struts.xml configuration file <package name="getdetails" extends="struts-default"> <action name="details" class="com.viewdetails"> <result name="success">/viewdetails.jsp</result> </action> My class viewdetails.java package com; import java.util.ArrayList; public class viewdetails{ public String firstname,lastname,teamname,reply; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getTeamname() { return teamname; } public void setTeamname(String teamname) { this.teamname = teamname; } public String getReply() { return reply; } public void setReply(String reply) { this.reply = reply; } public String execute() { getAction n1=new getAction(); String a=n1.getresult(this); System.out.println("the value of a is:"+a); return a; } My class getAction.java package com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.opensymphony.xwork2.ActionSupport; public class getAction extends ActionSupport{ public ArrayList<viewdetails> list=new ArrayList<viewdetails>(); public ArrayList<viewdetails> getList() { return list; } public void setList1(ArrayList<viewdetails> list) { this.list = list; } public String getresult(viewdetails r) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","sanjeev","sanjeev"); PreparedStatement ps=con.prepareStatement("select d.firstname, d.lastname,d.teamname,e.reply from newuser d INNER JOIN teamdetails e ON d.emailid = e.emailid "); ResultSet rs=ps.executeQuery(); while(rs.next()){ viewdetails view=new viewdetails(); view.setTeamname(rs.getString("teamname")); view.setFirstname(rs.getString("firstname")); view.setLastname(rs.getString("lastname")); view.setReply(rs.getString("reply")); list.add(view); System.out.println(rs.getString("teamname")); System.out.println(rs.getString("firstname")); System.out.println(rs.getString("lastname")); System.out.println(rs.getString("reply")); } con.close(); } catch(Exception e) { e.printStackTrace(); } return "success"; } } And my last jsp: viewdetails.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <center><h3>get response:</h3> </center> Welcome to see the response <table> <s:iterator var="i" step="1" value="list" > <tr> <td width="10%"><s:property value="%{teamname}"/></td> <td width="10%"><s:property value="%{firstname}" /></td> <td width="10%"><s:property value="%{lastname}" /></td> <td width="20%"><s:property value="%{emailid}" /></td> <td width="20%"><s:property value="%{reply}"/></td> </tr> </s:iterator> </table> </body> </html> A: The variable list is not available in the valueStack. To add a variable to the valueStack you can use an action getter for the property list and initialize it before the result. Since you already have a getter in another class you can remap your action with moving execute to the action class. Note, that you never create your action class with new, but you can let Struts build the action via ObjectFactory. struts.xml <package name="getdetails" extends="struts-default"> <action name="details" class="com.getAction"> <result name="success">/viewdetails.jsp</result> </action> </package> action class public class getAction extends ActionSupport{ ... public String execute() { String a=getresult(null); System.out.println("the value of a is:"+a); return a; }
{ "pile_set_name": "StackExchange" }
Q: Bordered 5-corners CSS element I need to create an element like this: 5 corners, border and text in <span> element. How can I achieve that result? I have only managed to create the normal element with 4 corners. .pin { position: absolute; top: 7px; right: 7px; display: inline-block; min-height: 34px; min-width: 42px; vertical-align: top; padding: 0px 4px; color: #fff; text-align: center; line-height: 1.2; text-transform: uppercase; border-radius: 4px; box-shadow: inset 0px 0px 0px 1px rgba(255, 255, 255, 0.28); } .pin__green { background-color: #689f39; border: 1px solid #59902b; } .pt { font-size: 13px; font-family: 'PT Sans'; display: block; margin-top: 10px; } <span class="pin pin__green"> <span class="pt"> <span>2</span> <span>new</span> </span> </span> A: I've created a single element solution. Basically you use the pseudo-elements ::before to create the tip (same styles as for your main element but rotated by 45°) and ::after to hide the left unwanted box-shadow. Some additional hints: Don't nest <span> elements and use 0 instead of 0px for CSS zero values. .pin { position: relative; display: inline-block; height: 34px; min-width: 42px; padding: 0 10px 0 2px; margin-left: 20px; color: #fff; font-size: 13px; font-family: Arial; text-align: center; line-height: 34px; text-transform: uppercase; border-radius: 4px; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.28); } .pin-green { background-color: green; border: 1px solid green; border-left: 0 solid; } /* the tip */ .pin::before { content: ""; position: absolute; left: -12px; top: 3px; height: 25px; width: 25px; background-color: green; border: 1px solid green; border-radius: 4px; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.28); z-index: -1; transform: rotate(45deg); } /* hide the left box-shadow */ .pin::after { content: ""; position: absolute; left: 0; top: 2px; height: 30px; width: 2px; background-color: green; } <div class="pin pin-green">2 new</div>
{ "pile_set_name": "StackExchange" }
Q: Storing one of two outputs of For loop I have a set of data: Rawdata={-0.462475, -0.477504, -0.393686, -0.217328, 0.105685, 0.443379, 0.627285, 0.534236, 0.165977, -0.296604, -0.432765, 0.0851257, 0.136757, 0.0293745, -0.411645, -0.322851, 0.046951, 0.492951, 0.59958, 0.294237, -0.182859, -0.398524, 0.0981432, 0.0930264, 0.0744801, -0.335487, -0.211728, 0.162959, 0.499504, 0.520212, 0.16799, -0.234034, -0.319659, 0.0952872, 0.107103, 0.335255, 0.43733, 0.146607, -0.190577, -0.261758, -0.0625729, 0.2634, 0.472639, 0.368261, 0.0979895, 0.0735513, 0.172949, 0.418761, 0.330992, 0.0074911, -0.216614, -0.215464, 0.0696046, 0.329594, 0.408547, 0.0894006, 0.126135, 0.165816, 0.307273, 0.185918, -0.0112422, -0.133738, -0.0724032, 0.101639, 0.292775, 0.301708, 0.0877797, 0.0876761, -0.025518, -0.0306193, 0.0928805, 0.199542, 0.243624, 0.1745, 0.0162858, -0.0430322, -0.0219115, 0.0896729, 0.0959586, 0.110228, 0.179314, 0.172237, 0.0997888, 0.0101023, -0.0105142, 0.0445394, 0.118966, 0.189803, 0.109097, 0.0858361, 0.100032, 0.143901, 0.115334, 0.125749, 0.0604358, 0.0409949, 0.083558, 0.117466, 0.137262, 0.094553, 0.0880441, 0.100834, 0.0929723, 0.0952319, 0.100924, 0.118724, 0.0820776, 0.103751, 0.0865428, 0.0833089, 0.101332, 0.0920292, 0.0639722, 0.0706576, 0.0882164, 0.11293, 0.134228, 0.124789, 0.0925625, 0.0566572, 0.0675977, 0.081165, 0.0899243, 0.117133, 0.0894329, 0.027364, 0.0357121, 0.0987479, 0.149997, 0.148336, 0.11258, 0.0753185, 0.113732, 0.115019, 0.101291, 0.160841, 0.187044, 0.116901, 0.038164, 0.0141272, 0.0476076, 0.123504, 0.170103, 0.0967143, 0.0901756, 0.010208, 0.0165788, 0.055284, 0.128853, 0.178452, 0.177033, 0.0751056, 0.00724638, 0.0312522, 0.0948593, 0.109623, 0.0539488, 0.00278435, 0.0385292, 0.112214, 0.179139, 0.171794, 0.105018, 0.0370275, 0.00582058, 0.116097, 0.0961575, 0.0632425, 0.151793, 0.164298, 0.130958, 0.0701233, 0.00879883, 0.0510383, 0.106122, 0.153237, 0.0852388, 0.0869375, 0.139951, 0.162659, 0.132968, 0.0719273, 0.0519352, 0.0302522, 0.111082, 0.145829, 0.148304, 0.0970358, 0.0906806, 0.0785693, 0.0470446, 0.063254, 0.0882698, 0.101144, 0.132672, 0.111858, 0.0790596, 0.0948081, 0.0792895, 0.094402, 0.0868104, 0.0774563, 0.0849362, 0.116133, 0.13637, 0.109352, 0.103358, 0.0842258, 0.0688512, 0.0901025, 0.119531, 0.0992231, 0.11737, 0.109138, 0.11662, 0.0969882, 0.0769638, 0.0877883, 0.10809, 0.119633, 0.101203, 0.0945034, 0.0861549, 0.0616248, 0.0666033, 0.0918489, 0.102061, 0.138445, 0.137202, 0.111695, 0.0843132, 0.0711831, 0.0577217, 0.0565093, 0.137122, 0.181921, 0.180176, 0.114756, 0.0663453, 0.0190868, 0.0620324, 0.120716, 0.10791, 0.118056, 0.11861, 0.0399656, -0.00972457, 0.0280447, 0.0976789, 0.188359, 0.203561, 0.145988, 0.0572668, 0.0970899, 0.117154, 0.0833913, 0.0192099, -0.0336157, 0.0212292, 0.126909, 0.186489, 0.213497, 0.16576, 0.0464841, 0.0928235, 0.0831726, 0.194656, 0.241966, 0.178094, 0.0685291, -0.0383825, -0.0222282, 0.0421295, 0.167092, 0.226146, 0.0840057, 0.113883, 0.0668346, 0.157052, 0.243934, 0.235909, 0.148691, 0.0298074, -0.0436559, -0.0196858, 0.087831, 0.118569, 0.0808441, 0.1652, 0.238137, 0.120931, 0.0284646, -0.0401501, -0.0219231, 0.0894716, 0.187669, 0.244263, 0.104944, 0.0957649, 0.0447436, 0.103991, 0.217513, 0.239228, 0.201135, 0.0951626, -0.0299545, -0.0548929, 0.031694, 0.107958, 0.150573, 0.18525, 0.080512, -0.00369004, -0.0468405, 0.0360111, 0.132843, 0.226403, 0.222974, 0.125393, 0.11251, 0.126242, 0.233834, 0.163337, 0.0939386, 0.0213852, -0.0165399, 0.0483103, 0.137372, 0.209622, 0.200961, 0.116739, 0.11108, 0.186125, 0.180642, 0.110386, 0.0564929, -0.0132962, 0.0471397, 0.106225, 0.170968, 0.186725, 0.118726, 0.09382, 0.073343, 0.12772, 0.151153, 0.161, 0.121048, 0.0730062, 0.0191693, 0.0229224, 0.103218, 0.101597, 0.101414, 0.127825, 0.160381, 0.123607, 0.077135, 0.0437015, 0.0413213, 0.0884286, 0.126512, 0.14602, 0.114284, 0.104335, 0.100021, 0.101678, 0.0803154, 0.0763461, 0.0535074, 0.0951762, 0.0963413, 0.115596, 0.112413, 0.105004, 0.108572, 0.0846231, 0.110065, 0.0755513, 0.0918242, 0.111067, 0.0843015, 0.0797037, 0.103031, 0.0974963, 0.0873716, 0.0974615, 0.121654, 0.0900736, 0.092349, 0.0899691, 0.0608037, 0.0774372, 0.10331, 0.13613, 0.111823, 0.0789723, 0.082949, 0.140698, 0.0948199, 0.0786218, 0.0472427, 0.0687623, 0.0749091, 0.118445, 0.141406, 0.124413, 0.10868, 0.11092, 0.118747, 0.121574, 0.10521, 0.073375, 0.053598, 0.0856549, 0.124248, 0.132137, 0.132778, 0.0954054, 0.107204, 0.0761265, 0.0843766, 0.10071, 0.135022, 0.147052, 0.114702, 0.0732644, 0.058628, 0.0827127, 0.110792, 0.109074, 0.0928544, 0.146601, 0.135908, 0.118201, 0.0717454, 0.0492275, 0.0608672, 0.0884621, 0.137157, 0.0785544, 0.0999297, 0.0866411, 0.0978298, 0.151161, 0.132314, 0.12448, 0.0741268, 0.0321637, 0.0712278, 0.117593, 0.109783, 0.0825315, 0.125198, 0.0847295, 0.0653004, 0.0783939, 0.0863342, 0.122781, 0.137911, 0.124709, 0.0834643, 0.106041, 0.0995328, 0.115609, 0.141324, 0.119285, 0.113149, 0.0841362, 0.0960893, 0.0908578, 0.119849, 0.136478, 0.106098, 0.08756, 0.101115, 0.0889186, 0.117936, 0.114559, 0.10105, 0.0935653, 0.0832678, 0.0925567, 0.102049, 0.0961035, 0.075863, 0.106154, 0.10837, 0.0950285, 0.104923, 0.0991505, 0.088163, 0.0930724, 0.103383, 0.107164, 0.10216, 0.0919158, 0.0920803, 0.0792764, 0.0870697, 0.107748, 0.116857, 0.143839, 0.133452, 0.0939433, 0.085644, 0.117072, 0.0934091, 0.0770135, 0.0878632, 0.0976638, 0.119022, 0.111126, 0.119448, 0.0959723, 0.0828836, 0.0531737, 0.0795022, 0.08512, 0.118981, 0.0838361, 0.0402141, 0.0434374, 0.0486867, 0.116763, 0.165252, 0.15056, 0.12431, 0.0964232, 0.119511, 0.132874, 0.103763, 0.0634226, 0.0648683, 0.0189996, 0.0839863, 0.127542, 0.158943, 0.146704} and I apply the For loop: For[(i = 1; j = 11), i < 540 && j < 540, (i += 11; j += 11), Print[nlm = NonlinearModelFit[Part[Rawdata, i ;; j], (a*Sin[b t + c]) + d, {{a, 1}, {b, 0.3}, {c, 8}, {d, -0.5}}, t], Max[Table[nlm[t], {t, 0, 10}]]]] This gives me two outputs, one is the equation of the fitted model and the other is the peak value of the sine wave that has been fitted to the data. I want to output these peak values as a table. Is there a way of doing this using, for example, PutAppend (it isn't necessary for the data to be stored to a separate file)? A: I used your data, and I'm not overly familiar with For loops so I rewrote the code using a Do loop. They're largely similar as far as I understand, but for what you need (outputting values to a table) a Do loop is very intuitive. A For loop takes the initial value (i=1), checks that the value is below a threshold (i<540) and as long as that's true it runs the code and applies an increment. I messed around with it but couldn't find exactly when the increment is applied - this is where Do loops come in. output = {}; incr = 11; Do[ j = i + (incr-1); nlm = Quiet@ NonlinearModelFit[ Rawdata[[i ;; j]], (a*Sin[b t + c]) + d, {{a, 1}, {b, 0.3}, {c, 8}, {d, -0.5}}, t]; xmax = Max[Table[nlm[t], {t, 0, 10}]]; AppendTo[output, xmax]; , {i, 1, 539 - (incr - 1), incr}]; Since i and j in your code are related I replaced j with i+(incr-1), with the increment you specified as incr=11. the code output={}; incr=11; Defines not only the list we're going to output values to (it doesn't have to be empty) and the incr we're going to apply. What happens: the Do loop opens, and i is defined as i=1 (bottom line). j is then defined as i+10 (so j=11 for the first round). Then your code is unchanged, the NLMF is run (I added a Quiet@ to remove annoying errors) and I changed your Part[Rawdata,i;;j] to Rawdata[[i;;j]] because they're equivalent but one takes less typing, I defined a new variable xmax = Max[Table[nlm[t], {t, 0, 10}]]; as the maximum value of the fit, and the AppendTo argument puts the value of xmax into the empty table output. The Do loop then restarts, with a new value of i = i + incr and it will continue to loop until j = 539 or i = j - 10 = 539 - (incr-1) When the loop finishes, the list output should have the required data. The result I got using your data was: ListPlot[output,Joined->True, PlotRange->All]
{ "pile_set_name": "StackExchange" }
Q: calculate statistics for the dataframe based on a column information There is a dataframe looks like as follows, which only shows 4 records Identification cost weekdays 1001 $20.02 Tuesday 1002 $30.03 Monday 1004 $20.05 Wednesday 1006 $10.05 Tuesday In Pandas, how to calculate the statistics, such as mean, standard deviation of the cost on each weekdays. Should I use groupby, and how to use it for this kind of scenario? A: This may contain two part , first convert accounting type data to numeric , then groupby with agg df.cost=df.cost.replace( '[\$,]','', regex=True ).astype('float') df.groupby('weekdays').cost.agg(['mean','std']) Out[958]: mean std weekdays Monday 30.030 NaN Tuesday 15.035 7.049855 Wednesday 20.050 NaN
{ "pile_set_name": "StackExchange" }
Q: Create array of not pre-determined size inside a structure I want to work with Images, and I want to create my structure Image with first 2 values to be it's size (grayscale) and the third - data (2D array of size m by n). How can I implement it? If I don't know the image's size in advance. Something like this: struct Image{ int n; int m; data = 2D array of size mxn } A: Ignoring encapsulation, something like this could work: #include <vector> struct Image { int n; int m; std::vector<std::vector<int>> data; // May want to change int type ? Image(int n, int m) : n(n), m(m), data(n) { for (int row = 0; row < n; row++) { data[row].resize(m); } } }; // Example Usage Image img(10, 10); for (int row = 0; row < img.n; row++) { for (int col = 0; col < img.m; col++) { img.data[row][col] = valueFromImageFile; } } If you're not just looking for something quick and dirty, and this is going to be an ongoing project, I would recommend that you learn more about object oriented concepts :)
{ "pile_set_name": "StackExchange" }
Q: Creating Rational Functions with Horizontal Asymptotes and More on Tikz I recently asked a question about how to use Tikz to create phase line diagrams. However I had a follow up question. The question is how I would go by creating a rational function or other types of functions during the plot portion of the code. The previous question is here - Is it possible to graph and draw phase lines in LaTex? What I initially wanted was to use Tikz to draw a graph plotting a horizontal asymptote at I=1 as a dashed line. I also wanted to draw two curves. One curve which approached I=1 from above, and another curve that approached I=1 from below. I looked everywhere for hours, but could not find what I needed to help me do this. What I ended up doing was just messing around with the coding until I moved the two curves, and dashed line to look like I wanted it. I am hoping there is a better way to do this, as it took me a very long time. \documentclass{amsart} \usepackage{fullpage} \usepackage{amsmath} \usepackage{amsthm} \usepackage{graphicx} \usepackage{caption} \usepackage{epstopdf} \usepackage{wrapfig} \usepackage{pgfplots} \usepackage{geometry} \usepackage{amsmath} \usepackage{pgfplots} \pgfplotsset{compat=1.8} \usepackage{mathtools} \usepackage{tikz} \newcommand*{\TickSize}{2pt}% \newcommand*{\AxisMin}{0}% \newcommand*{\AxisMax}{0}% \newcommand*{\DrawHorizontalPhaseLine}[4][]{% % #1 = axis tick labels % #2 = right arrows positions as CSV % #3 = left arrow positions as CSV \gdef\AxisMin{0}% \gdef\AxisMax{0}% \edef\MyList{#2}% Allows for #1 to be both a macro or not \foreach \X in \MyList { \draw (\X,\TickSize) -- (\X,-\TickSize) node [below] {$\X$}; \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \edef\MyList{#3}% Allows for #2 to be both a macro or not \foreach \X in \MyList {% Right arrows \draw [->] (\X-0.1,0) -- (\X,0); \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \edef\MyList{#4}% Allows for #3 to be both a macro or not \foreach \X in \MyList {% Left arrows \draw [<-] (\X-0.1,0) -- (\X,0); \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \draw (\AxisMin-1,0) -- (\AxisMax+1,0) node [right] {#1}; }% \newcommand*{\DrawVerticalPhaseLine}[4][]{% % #1 = axis tick labels % #2 = up arrows positions as CSV % #3 = down arrow positions as CSV \gdef\AxisMin{0}% \gdef\AxisMax{0}% \edef\MyList{#2}% Allows for #1 to be both a macro or not \foreach \X in \MyList { \draw (-\TickSize,\X) -- (\TickSize,\X) node [right] {$\X$}; \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \edef\MyList{#3}% Allows for #2 to be both a macro or not \foreach \X in \MyList {% Up arrows \draw [->] (0,\X-0.1) -- (0,\X); \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \edef\MyList{#4}% Allows for #3 to be both a macro or not \foreach \X in \MyList {% Down arrows \draw [<-] (0,\X+0.1) -- (0,\X); \ifnum\AxisMin>\X \xdef\AxisMin{\X}% \fi \ifnum\AxisMax<\X \xdef\AxisMax{\X}% \fi } \draw (0,\AxisMin-1) -- (0,\AxisMax+1) node [above] {#1}; }% \begin{document} \begin{tikzpicture} \draw[->] (0,0) -- (8,0) node[right] {$t$}; \draw[->] (0,0) -- (0,5) node[above] {$I$}; \draw[scale=0.5,domain=0:4,smooth,variable=\y,red] plot ({\y*\y},{- \y+8.1}); \draw[scale=0.5,domain=0:4,smooth,variable=\y,red] plot ({\y*\y},{\y}); \draw[scale=0.5,domain=0:16,dashed,variable=\y,black] plot({\y},{4.045})node[right] {$I=1$}; \end{tikzpicture} \end{document} A: As this is a graph and not a picture, I would recommend you use pgfplots instead of just tike: Code: \documentclass[border=2pt]{standalone} \usepackage{pgfplots} %% http://tex.stackexchange.com/questions/17438/how-to-properly-scale-a-tikz-pgf-picture-which-has-a-beginaxis-endaxis \pgfkeys{/pgfplots/Axis Labels At Tip/.style={ xlabel style={ at={(current axis.right of origin)}, anchor=west, }, ylabel style={ at={(current axis.above origin)}, yshift=1.5ex, anchor=center } } } \begin{document} \begin{tikzpicture} \begin{axis}[ scale=0.5, smooth, xmax=16, ymax=8.5, axis x line=middle, axis y line=center, ylabel=$I$, xlabel=$t$, axis on top=true, Axis Labels At Tip, clip=false, ] \addplot[domain=0:4, red] ({\x*\x},{- \x+8.1}); \addplot[domain=0:4, red] ({\x*\x},{\x}); \addplot[domain=0:16, dashed, black] (\x,4.045) node[right] {$I=1$}; \end{axis} \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: How to be effective as a Healing Cleric Some times things are just too much of a fun/stupid combo idea not to try your darnedest not to work out. What is the best way to make a Cleric that literally only does healing/buffing? Is this even a viable idea, or will it just serve to completely annoy the rest of a group? The Concept A healing/buffing/restoring centered human Cleric No Archetype, because mostly I just don't care for any of the existing Cleric archetypes I'm looking at the Resurrection and Protection Domains, though I can't find a deity that grants both so that might have to change. Oh yeah, did I mention the twist? She's going to be a pacifist. This means absolutely no damaging spells and no attacking with a weapon. From a roleplay perspective, this will be tons of fun. From a game perspective, I may have just taken one of the best classes and made it nearly useless. What's On the Table Healing. Lots of healing. Even more healing. Roleplay spells. The more merciful the better. Creating water and food? Oh definitely. Buffing Removing Negative effects. Seriously, lots of this too. Charms. I'd rather do this more as a roleplay perspective (What's better than the enemy you just faced resurrecting you?), but Command, Forbid, Geas, and etc. are all on the table. Basically anything else that can be used mercifully. What's Useful for the Answer Feats. I'm having a hard time coming up with useful feats. A lot of spell feats seem to rely on damage dice and I can't tell if they would also effect healing dice. Considering that I don't want to attack either, this leaves me actually low on feats to select. Spells. Ideas and options for spells are always welcome. The Cleric spell list comes with a ton of ones I know I can use, but inventive ways to use other spells to not hurt is more than welcome. Personal Experience. If you've done this, or at least something close to this, it's going to help a lot more than speculation. If you had a negative personal experience, I want to hear that too. The goal is to design a healer/support Cleric that doesn't raise ire the first time you don't go up and whack around the enemies. Multiclassing/Prestige Class options. This is completely optional and not needed. I'm perfectly intending to go with pure Cleric levels, but it goes back to personal experience. If you had an experience with a multiclassed Cleric/X then use it in the answer as well. A: So, depending on your definition, you may not be very much hindered by “pacifism” at all. As I discuss for a divine oracle with similar needs, buffing often is what a spellcaster should do; the “fighting aspects” of the game, as that questioner put it, are usually best left to other characters. However, I have concerns about what “pacifism” really means to you. It seems to me that, in Pathfinder, you have two choices: merely paying lip service to the idea, while still actively encouraging and enabling violence albeit without personally getting your hands dirty, or else being a significantly disruptive presence at the table, causing significant problems for the other players (and their characters too, but the players are the important part), because you have moved too far away from the things Pathfinder was made to do. I’ll start my answer off by discussing healing and buffing and charming, as you request, but the meat of my answer is going to be about pacifism and what that means. I do offer an idea for how one might be able to straddle the line between these two and have an effective and authentic pacifist Pathfinder character, but that will depend a great deal on the nature of your campaign. On healing Healing, for the most part, is an out-of-combat, as-needed activity. As much as possible, it is most efficient to heal using wands and scrolls, rather than spell slots. Use a wand of a low-level HP-healing spell (cure light wounds, unless you can stomach the [Evil] tag on infernal healing) to top off after battles, and use scrolls of status-effect-healing spells to remove those annoying persistent effects. In combat, healing is generally emergency-only. The cleric’s ability to spontaneously commute spells to cure spells is more than sufficient to cover this. Even stabilize is often enough at low levels. At high levels, the heal spell does change this somewhat; unlike every other healing spell in the game, heal is huge and effective even in the middle of combat. On buffing Buffing is hugely useful and powerful. In fact, buffing is so good and clerics are so good at it that, depending on your definition (see below), pacficism may be no hindrance at all. For the most part, buffing well is pretty much “be a cleric,” and going into detail on how is beyond the scope of a reasonable answer here. Reading a cleric handbook is your best bet here. The aforementioned Q&A about the buffing divine oracle is also worthwhile, I hope. Ultimately you just have to disregard the aspects that don’t apply to you. On charming Charms and compulsions are very effective against certain kinds of enemies, and useless against a lot of others. These are extremely campaign-dependent for how useful they are. In the right campaign, I’d recommend taking a domain that gives you more of them, since the cleric’s usual options (suggestion, command) are one-off effects and to focus on this you’d rather charm and dominate. But in many campaigns these are going to be useless. Also, again, the definition of pacficism is a big deal here. See below On pacifism There are a lot of different ways you could define pacifism. In your question, it seems to be very personal, to the point that it seems almost pointless. “I won’t hurt you— but I will empower my friend here to hurt you really, really badly.” You seem to OK “offensive” buffs, that don’t protect anyone, they just make someone more able to hurt others. That’s an extremely narrow definition of pacifism that doesn’t seem, well, honest – more like you’re deluding yourself into thinking you’re better, more moral, than those who actually get their hands dirty. A step below this is “I won’t help my friends hurt you, but I will make sure they suffer no injuries while they do so, that nothing you do can stop them from hurting you.” This would be focusing on just healing and defensive buffing – buffs that prevent injuries or status effects, rather than those that directly improve offensive capability. The problem is, this is ultimately not all that different to me, morally. You are actively enabling violence; avoiding personally striking a blow is really just semantics. Below these is when you are actively trying to avoid violence itself. One way to do that is with mind-affecting magic, but I would argue that forcibly taking control of another person’s mind is a much greater assault than just stabbing them. That’s not pacifism, that’s domination. But you could avoid that, too; try to genuinely convince people to avoid conflict. At most, a calm emotions spell to keep tempers from getting in the way (though in a lot of cases, both sides have a pretty good right to be angry). This is much more “real” pacifism, but now you run into a different problem: Pathfinder is a game centered around violence. It comes from Dungeons and Dragons, a game that has its roots in pure dungeon-delving and dragon-slaying, and those things are what the rules focus on. The overwhelming majority of the game, between its rules, its narrative, its tone, and its characters, is focused on that. The skills system is underdeveloped and largely uninteresting; the social skills are so poor that the overwhelming majority of groups ignore them entirely and just roleplay social interactions freeform, with ad hoc Bluff, Diplomacy, and/or Intimidate rolls thrown in occasionally. And not only is Pathfinder bad at the sort of game where you are well and truly a pacifist, but everything about it is telling the other players that this is not the sort of game where pacifism is a thing. Violence is an effective, accepted, and often morally-sanctioned solution to problems in Pathfinder. People show up to a Pathfinder game with this as an expectation. Trying to turn this on its head, eliminate the majority of the game, and sideline the other players’ characters, who are focused on combat because, hey, they’re Pathfinder characters and that’s what Pathfinder’s largely about, is simply rude. So I think you need to sit down and think what, exactly, you mean by “pacifism,” and you have to either accept that your character is really only paying lip service to the idea, or that this character is going to be disruptive and problematic, and that you need to talk through the issues with the rest of your group (not just the DM). It very well may be that Pathfinder is the wrong system for this character, and you need to either convince everyone to try a system better suited to it, or shelve the character for another game in another system. All that said, I will acknowledge a way to straddle the line, so to speak. Your character could have heartfelt ideals about pacifism, try to encourage violence-only-as-a-last-resort, and have personal boundaries on what the character is personally willing to do, but believe in the mission enough to support your allies even as they engage in violence. This is a difficult line to walk, I think; it would be all too easy to slip off one side or the other, becoming a pacifist in name only or else becoming an annoyance at the game table. The character absolutely needs a huge quest, something to justify their support of violent individuals as they engage in violence. This is a character that would be very difficult to justify joining an adventuring party, say in a sandbox game. But in a more directed, epic quest to save the world kind of game, a character can more reasonably and more authentically accept and even support violence while still personally promoting pacifism. A: Healing For most adventurers, healing is a chore. For you, healing can be a hobby. By itself, healing will solve few conflicts. If the weight of the deaths caused by your asymmetric assistance weighs heavily on your conscience you will discover providing mercy only to your companions is no longer acceptable. Do not put too much faith in undoing the atrocities of the world, instead put your faith into preventing them. Traits The Blessed Touch (faith) trait will make lay on hands, channel energy, and cure spells heal 1 more point of damage. Feats The most useful healing feat is Craft Wand. A wand of cure light wounds or infernal healing costs 375 gold to craft. A cure light wounds (caster level 1) wand heals for 50d8+50 damage and costs 1.36 gold per HP healed. An infernal healing wand heals for 500 damage and costs .75 gold per HP healed. Unusual healing spells There are spells that take more time to heal, but heal for more total hitpoints. These are useful if you are healing between encounters. They are also difficult to abuse to aid one side to victory over another in conflict. Infernal healing is a level 1 spell that will heal for 10 hitpoints over one minute. This is more healing on average than a Cure Light Wounds, which only heals for 1d8+1/level (maximum +5). The fourth level spell healing warmth can heal for a total of 10d8 of damage, used 1d8 at a time. Cure Critical Wounds heals for 4d8+1/level (maximum +20) all on the same target. Channel Energy Being able to channel positive energy helps your healing hobby. It depends on charisma for uses per day, but your wisdom will be far more important to your overall success. Channeling energy can provide mercy against the elements or liberation from captivity with some feat investment. Dominating There will be problems you won't be able to fix. Stop them with a spell. Your wisdom will be your most important attribute, since it determines the save DC for your spells. Feats The two feats in the chain Spell Focus and Greater Spell Focus will each increase the save DC for one school of magic by +1. The spells listed below are mostly from the enchantment school. Heighten Spell and Persistent Spell increase the difficulty of saving against your dominating spells when there isn't a higher level version of the spell. Which one's better depends on how likely the target is to make the save. Merciful spell will let you use spells with damaging side-effects without fear of causing real harm. When manipulating people, it's useful to be able to cast spells in the middle of a social situation. A Stilled, Silent spell is extremely difficult to detect, and can change the entire direction of a social encounter. In an extremely social campaign, starting with both metamagic feats and both of Wayang Spellhunter and Magical Lineage you can cast charm person undetected. Equipment A Metamagic rod of Persistent Spell can make even your most debilitating spells doubly difficult to resist. Domains The 1st level ability from the madness domain makes combatants amenable to your calming commands by lowering their saving throws and attack rolls by half your level. It can also be used to give a companion a big boost on a skill check. The most fitting deities granting madness are the lantern king and Tsukiyo. Spells The following spells let you dominate the living. Command is your basic first level compulsion spell. Compel hostility can be used to protect your allies or create new ones; it's great for solving problems in any low-level urban setting. Touch of truthtelling can dominate social situations, or turn them into conflicts. A well timed charm person can prevent conflict entirely. Hold person is your basic second level compulsion spell. Owl's wisdom increases the DC of your spells by two. A stilled, silent zone of truth is a no-save divination spell. share language is an early, backwards tongues. Dispel magic diffuses dangerous situations. Archon's aura reduces the attack and saves of nearby enemies. Debilitating portent reduces the target's damage dealt by half on a failed save, and has a save DC that scales with caster level. Clerics miss out on hold monster unless they get it from a domain - usually late. constricting coils is a 5th level hold monster that also helps bludgeon it into submission. charm monster is available from the charm domain; you can get both madness and charm from the lantern king. Chains of light is a 6th level conjuration spell that paralyzes its target. greater dispel magic is even better than dispel magic was. Waves of ecstasy is a cone that stuns and staggers. hymn of peace creates an aura in which any hostilities require a successful will save. Overwhelming presence compels multiple creatures to kneel helpless before you.
{ "pile_set_name": "StackExchange" }
Q: Very slow startup using SDL 2 on OS X 10.8 Even using the most basic SDL test, when I run the output file after compiling, I get a pinwheel for about 8 seconds, and then the program starts. This doesn't happen if I don't use SDL. I have tried both clang and g++ with the same results. #include <iostream> #include <SDL2/SDL.h> int main(int argc, char **argv){ if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } SDL_Quit(); return 0; } Is this normal, or is there a way to fix this? It's really annoying for quickly testing :( A: I've found initializing the joysticks tends to take a long time across multiple platforms. My solution is to initialize just the video to begin with, then later initialize other stuff separately. SDL_Init(SDL_INIT_VIDEO); // You can create your window and display a splash screen here SDL_InitSubSystem(SDL_INIT_JOYSTICK); SDL_InitSubSystem(SDL_INIT_AUDIO);
{ "pile_set_name": "StackExchange" }
Q: Add filter "Shipped by" Besides 'Category', 'Material', 'Brand', 'Color', 'By price range', 'Color Group', and 'Price', I'd like to add the filter 'Shipped by' This is what I have in my view: app/design/frontend/{my_theme}/template/catalog/layer/view.phtml Code: <dl id="narrow-by-list"> <?php $_filters = $this->getFilters() ?> <?php $allowedfilter = Array('Category', 'Material', 'Brand', 'Color', 'By price range', 'Color Group', 'Price'); ?> <?php foreach ($_filters as $_filter): ?> <?php if ($_filter->getItemsCount() && in_array($_filter->getName(), $allowedfilter)): ?> <dt> <span><?php echo str_replace(' Group', '', $this->__($_filter->getName())) ?></span> </dt> <dd> <?php echo $_filter->getHtml() ?> </dd> <?php endif; ?> <?php endforeach; ?> </dl> Now, this is what I have in my filter: app/design/frontend/{my_theme}/template/catalog/layer/filter.phtml Code: <ol> <?php $brandsort = Array(); if (preg_match('/Brand/i', $this->getName())) { $attribute = Mage::getModel('eav/entity_attribute')->load('brand', 'attribute_code'); $option_col = Mage::getResourceModel('eav/entity_attribute_option_collection')->setAttributeFilter($attribute->getId()) ->setOrder('sort_order'); foreach ($option_col as $theoption) { if ($theoption['sort_order'] < 1) $theoption['sort_order'] = 999; $brandsort[$theoption['option_id']] = $theoption['sort_order']; } } $items = $this->getItems(); $branditems = Array(); if (preg_match('/Brand/i', $this->getName())) { foreach ($items as $key => $item) { $items[$key]['sort_order'] = $brandsort[$item['value']]; } function cmp($a, $b) { return $a['sort_order'] - $b['sort_order']; } usort($items, "cmp"); } ?> <?php foreach ($items as $_item): ?> <li> <a href="<?php echo $this->urlEscape($_item->getUrl()) ?>"> <?php if ($_item->getCount() > 0): ?> <?php if (file_exists('skin/frontend/{my_theme}/images/colors/' . strtolower(str_replace(' ', '_', $_item->getLabel())) . '.jpg') && preg_match('/Color/i', $this->getAttributeModel()->getFrontendLabel())): echo '<img style="border:1px solid #CCCCCC;margin-bottom:3px !important;" src="/skin/frontend/{my_theme}/images/colors/' . strtolower(str_replace(' ', '_', $_item->getLabel())) . '.jpg" alt="' . $_item->getLabel() . '" />'; endif; ?> <?php echo $_item->getLabel() ?> <?php endif; ?> </a> <?php if ($this->shouldDisplayProductCount()): ?> (<?php echo $_item->getCount() ?>) <?php endif; ?> </li> <?php endforeach ?> I found this code that I think it does what I want, but I don't know how to integrate it to my existing code: $items->joinField('manages_stock','cataloginventory/stock_item','use_config_manage_stock','product_id=entity_id','cataloginventory_stock_item.use_config_manage_stock=1 or cataloginventory_stock_item.manage_stock=1'); What I want is to filter products given the values of use_config_manage_stock and manage_stock i.e. products that are shipped from the stores of shipped by the manufacturer. It doesn't have to be this way, I'm just bringing what I have so far. Any help will be appreciated. A: You can create your module according to this module https://github.com/Marko-M/Inchoo_Sale Hope this will be helpful.
{ "pile_set_name": "StackExchange" }
Q: How to change src value in UIWebView? In a UIWebview I want to change <iframe src=“//player.vimeo.com/video/164231311?autoplay=1” width=“700" height=“394” frameborder=“0" webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe> to <iframe src=“//player.vimeo.com/video/164231311" width=“700” height=“394" frameborder=“0” webkitallowfullscreen=“” mozallowfullscreen=“” allowfullscreen=“”></iframe> since I want the user to be presented with a play button instead of a pause button since autoplay is not allowed on iOS. It'll be more natural for the user to see a play button directly instead of the pause button as in the image below. How do I do that in a simple way? I’ve tried some stuff like webView.stringByEvaluatingJavaScript(from:“document.getElementsByTagName(…) without success so far. A: Here I made rough demo code to solve your issue. Put your logic with that and it will solve your issue. It was tested and had seems working perfectly. import UIKit class ViewController: UIViewController,UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() webView.delegate = self webView.loadRequest(URLRequest(url: URL(string: "file:///Users/user/Downloads/index.html")!)) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webViewDidFinishLoad(_ webView: UIWebView) { // get your current iframe src value let iframeSrcValue:String = webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('iframe')[0].src")! // Here is your current value with AutoPlay print(iframeSrcValue) //Create new URL without Auto Play let modifiedSrcValue = "https://www.youtube.com/embed/td8pYyuCIIs" // Apply it to webview let evaluate: String = "document.getElementsByTagName('iframe')[0].src='\(modifiedSrcValue)';" webView.stringByEvaluatingJavaScript(from: evaluate) } }
{ "pile_set_name": "StackExchange" }
Q: Group lines of code in vba I was wondering if it was possible to group lines of code in vba excel, in order to make the view more pleasant. Meaning I have 1000 lines of code and would like to group lines in order to hide/show them. I know this is possible in other coding languages, so I would like to know if it was possible in vba. Thanks A: The short answer is no, not out of the box. There is an open source tool that will be able to do this in a future release http://rubberduckvba.com/ If you have a lengthy procedure you may what to ask yourself if it does more than one thing. As a general rule, a procedure should only do one thing. If you break up each separate "thing" into individual procedures, then you can call each procedure in a parent subroutine. A good book on this is "Clean Code: A Handbook of Agile Software Craftsmanship" Sub ParentSub() ChildSub1() ChildSub2() End Sub
{ "pile_set_name": "StackExchange" }
Q: Attaching entity to ObjectContext without related entities with EF4 POCO Example: a product entity is loaded including its tags without tracking: repository.Product .Include("Tag") .Where(p => p.ProductID == 1) .Execute(MergeOption.NoTracking); Note that this is a many-to-many relationship; a product can have several tags, and tags can be associated with several products. Somewhere else, I want to save any changes made to the product entity, but without saving changes made to its related tags or its relationship with these tags. Meaning, neither of these changes may be saved: A tag has been removed from the product A tag has been added to the product A tag has been modified (e.g. name has been changed) So I was thinking that I could somehow attach only the product to a new ObjectContext and save changes. But for some reason I can't figure out how to only attach a single entity to the object context, and not the entire graph. Of course, I could attach the graph and then manually detach all other entities except the product in question, but this is a horrible solution, and I was hoping to find another. A: You can try to make a clone of your Product (not deep clone!), attach the clone and save changes. Your original object graph will remain detached. The only problem can be if you are using something like timestamp for concurrency handling. You will have to copy new timestamp from clone back to original entity otherwise you will not be able to save original entity again.
{ "pile_set_name": "StackExchange" }
Q: Multiple owners for photo albums - schema question How would i go about creating a relationship for photo albums that belong to either a user, event, group, network, page (I want to support x number of possible owners)? If possible even support multiple owners lateron. One way is to have columns in the album table for these with one of them have a FK ID and rest be null. But problem is as i add more owner types i have to keep altering the table to add more columns The other way is to have separate photo tables for each of these owner types. None of these methods scale well. Any other methods to own photo albums for different owner types from one table that will scale (meaning have less joins and be easy to query as read performance is my #1 requirement? Platform is MySQL/PHP. A: Think of your problem in a Conceptual Data Model instead of purely physical. If you do OO work, that's fine too. The semicircle is an inheritance operator. So Event, User, Network, Page all inherit from Owner. When you generate this to a Physical model you'll use these settings. This way you get one table of everything which can own a photo and all of the common attributes. Then each child table will inherit the PI from the parent, and have attributes specific to it. The FK of the photo table will go to the Owner table. Your future goal of many owners for a photo changes from a Owner ID as FK on the Photo table to a many:to:many mapping table between owner and photo. Really easy if you use these constructs.
{ "pile_set_name": "StackExchange" }
Q: How to know Package Name of a Top running app from my service running in background (android) How can i know the package name of top Running application. https://www.dropbox.com/s/2p4iuj7dj7zv5u4/Screenshot%20%28234%29.png (in the link , above application is temple run 2 and package is com.imangi.templerun2 ) I need to retrieve the package name(ie com.imangi.templerun2) from my service and store it in String named packageName . How can i do it ??? A: ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // Return a list of the tasks that are currently running, // with the most recent being first and older ones after in order. // Taken 1 inside getRunningTasks method means want to take only // top activity from stack and forgot the olders. List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; componentInfo.getPackageName(); // here it is
{ "pile_set_name": "StackExchange" }
Q: Dot Navigation JQuery Slide Show I am quite new to JQuery and I have a question about Dot Navigation... I have some Hero content which I have put together (using posts from here and JQuery site). Basically I have 3 div containers which are hidden and shown in a cycle. I also have three other div containers which have dots in them which I want to use as navigation. During the cycle the dots change colour to represent the "slide" the page is currently on. What I want to do now is add a click event to each dot so the cycle jumps to and displays the corresponding content. My Java Script is below. $('.heroContBG').each(function() { $(this).hide(0); }); $('.heroContBG').first().show(0); $('.heroDots').last().removeClass('heroNavOff').addClass('heroNavOn'); var delay = 6000; //Set delay time var divIdx = 0; //Set divIdx value var arrDiv = $('.heroContBG').toArray(); //Assign all heroContBG divs to array var arrDot = $('.heroDots').toArray(); //Assign all heroDots divs to array arrDot = arrDot.reverse(); //Reserve array index for Dot Navigation function heroBG(){ var $out = $(arrDiv[divIdx]); //Set $out variable to current array index (set by divIdx) var $dotOut = $(arrDot[divIdx]); //Set dotOut variable to current array index (set by divIdx) divIdx = (divIdx + 1) % arrDiv.length; //Convert array index 0-2 into 1-3 var $in = $(arrDiv[divIdx]); //Set $in to $arrDix[divIdx] var $dotIn = $(arrDot[divIdx]); //Set $dotIn to $arrDot[divIdx] $out.fadeOut(600).hide(); //Hide element $dotOut.removeClass('heroNavOn').addClass('heroNavOff'); //Swap classes on .heroDots $in.fadeIn(1600).show(); //Show next element $dotIn.removeClass('heroNavOff').addClass('heroNavOn'); //Swap classes on .heroDots } setInterval(heroBG, delay); //Tell browser to loop through elements. I think what I need to do is have a click event set the divIdx value to match that of the corresponding div container but as yet I have had no luck. I will keep playing around with this and if I have success I will post it here. If anyone else knows how to do this that would be great. I should also mention I don't really want to use a 3rd party plugin as I am quite keen to improve my JQuery skills. Cheers, Simon A: Simply use $('.heroDots').index(myClickedHeroDot) to get the position of the targeted sibling. Then assign the returned index value to divIdx. Hope this helps :)
{ "pile_set_name": "StackExchange" }
Q: How IPFS search files? In order to find the file in IPFS network by it's hash we should ask the adjacent nodes - "Do you have the file with hash H(F)?" and if not, then they propagate the question further. How IPFS resolve the issue in case of plurality of this kind of requests? How IPFS search engine works? A: IPFS is based on distributed netwotk each node are client/server so each nodes can create an request or respond an request. i think you can see around DHT : https://github.com/ipfs/go-ipfs/issues/1396 i hope it's helpfull for you A: The findProvs call will let you know if there are any current providers https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/DHT.md#dhtfindprovs
{ "pile_set_name": "StackExchange" }
Q: Need to copy single file to all subfolders recursively Please can someone help me create a powershell or CMD script, as simple as possible (1 line?) that will do the following... -Take file (c:\test.txt) -Copy to ALL subfolders within a given folder, including multiple levels deep eg, c:\test1\1\2\3\ and c:\test2\6\7\8\ -Without overwriting that file if it already exists -Not changing ANY existing files. Just adding the original txt file if it doesn't exist. I've tried a bunch of scripts I found online, changing them, but have been unsuccessful. Either it overwrites existing files, or doesn't go multiple levels deep, or skips all the folders between top/bottom levels, or throws errors. I give up. Thanks Matt A: How about something like this... $folders = Get-ChildItem -Recurse -Path C:\temp\1 -Directory $file = "c:\temp\test.txt" foreach($folder in $folders){ $checkFile = $folder.FullName + "\test.txt" $testForFile=Test-Path -Path $checkFile if(!$testForFile){ Copy-Item $file -Destination $folder.FullName } }
{ "pile_set_name": "StackExchange" }
Q: Transformation of electromagnetic potential under local U(1) transformation Let $\mathcal{L}=-(\partial _{\mu} \Phi^*)(\partial ^{\mu} \Phi)$ With $\Phi , \Phi^*$ being complex fields. When looking at local U(1) transformations in class, we saw that $\mathcal{L}$ is not invariant under the transformations of the form $\Phi \rightarrow e^{i\theta(\mathbf{x})}\Phi$. So we introduced covariant derivatives $\partial^{\mu} \rightarrow D^{\mu}=\partial^{\mu}-iA^{\mu}(\mathbf{x})$ As an exercise we should determine how $A^{\mu}$ has to transform to make $\mathcal{L}$ invariant. I got $A^{\mu} \rightarrow A^{\mu}+\partial^\mu \theta$ as a result. I also showed that $\mathcal{L}$ is indeed invariant under this transformation. Now what I am wondering is, how can I interpret the transformation of $A^{\mu}$? I haven't had electrodynamic classes so I don't really know much about electrodynamic potentials, but I think it might have something to do with U(1) transformations being rotations (atleast I think, they are). A: In a second semester electrodynamics course you would learn about the gauge freedom of electromagnetism. If you have electric and magnetic fields $\textbf{E}$ and $\textbf{B}$ these are determined by the 4-vector potential A. However there is no single A that determines $\textbf{E}$ and $\textbf{B}$ uniquely. This is merely a more complicated version of in Newtonian gravity how you can always add a constant to the potential without changing the dynamics. Given the $\textbf{E}$ and $\textbf{B}$ fields are contained in an antisymmetric tensor F, $$F^{\mu\nu} = \partial^\mu A^\nu - \partial^\nu A^\mu $$ you can see for example that $F^{00} = 0$, $F^{01} = \partial^0 A^1 - \partial^1 A^0 = E_x$, etc. Now if you add a divergence term to your 4-vector potential, $$ A'^{\mu} = A^{\mu} + \partial^{\mu}f$$ we can compute the new $\textbf{E}$ and $\textbf{B}$ fields, \begin{align} F'^{\mu\nu} &= \partial^\mu A'^\nu - \partial^\nu A'^\mu \\ F'^{\mu\nu} &= \partial^\mu (A^\nu +\partial^{\nu}f) - \partial^\nu (A^\mu + \partial^{\mu}f)\\ F'^{\mu\nu} &= F^{\mu\nu} + \partial^\mu \partial^{\nu}f - \partial^\nu \partial^{\mu}f\\ F'^{\mu\nu} &= F^{\mu\nu}. \end{align} So the vector potential is only well defined up to an overall divergence term. Now specifically towards your question, you found that you need the vector potential to transform by a divergence to impose local U(1) symmetry, $$ A^{\mu} \rightarrow{} A^{\mu} + \partial^{\mu}\theta(x) $$ but this would leave the $\textbf{E}$ and $\textbf{B}$ (along with energy, momentum, interactions) unchanged.
{ "pile_set_name": "StackExchange" }
Q: Basis to Hyperplane Given a hyperplane $\{x\in\mathbb R^n | a^T x=0\}$ where $a\in\mathbb R^n$, and I want to find some orthogonal basis to this hyperplane. I found many solutions for special cases, but non of which considers the general case. Thanks in advance! A: Adapted from the answer under the link in the comment by jibounet, but without the messy formulae. Without loss of generality assume $\|a\|=1$ (in other words replace $a$ by its normalisation, if necessary). Find one of the standard basis vectors, or its negative, that is different from $a$, say $e=\pm e_k\neq a$, which is clearly always possible (you can even make a choice such that $\|a-e\|>1$, for the sake of numeric stability in what follows). Then $v=a-e$ is a nonzero vector, and the orthogonal reflection $R$ with respect to the hyperplane perpendicular to $v$ will send $e_k\mapsto\pm a$. This means column $k$ of the matrix of $R$ equals$~\pm a$, and the remaining columns give you a basis of your hyperplane (remember, the columns of any orthogonal matrix, like that of a reflection, form an orthonormal basis of the space) Concretely, the matrix of $R$ is given by $I-\frac2{\|v\|^2}(v\cdot v^T)$.
{ "pile_set_name": "StackExchange" }
Q: url param not getting properly I have a two server.I am passing 4 variable in url ssid(36),rawstring(1024),sample_id,user_id. I simplely want to get parameter passed in url.When I hit my first server I am getting param,but same url(Only change server name),I get 3 parameters(not getting raw string). In my controller I am testing like this echo "<pre>"; print_r($_REQUEST); echo "</pre>"; echo $_REQUEST['rawstring'];die(); this is my desired output Array ( [ssid] => d41d8cd98f00b204e9800998ecf8427e [rawstring] => 303330363036422031333235353030323039ffffffffffffffffffffffffffff33333030302041202046542031333238203030303030323831ffffffffffffff31362f30372f323031332d2d313035343031ffffffffffffffffffffffffffff0ba504d203430aeeffffffffffffffff00db00db02ca00db02caffffffffffff00000000ffffffffffffffffffffffffbe51ffffffffffffffffffffffffffff8000ffffffffffffffffffffffffffff00ec856cffffffffffffffffffffffff2ea495a82eaa959dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff30303031303030350000000900000bbf0013ac9e0013aca300003504fffffffb06b706ae06aa06a2069c06990690068e0000086a00000ad80013acc60013acc70013acc90013accd000034f7fffffffb06b206ae06a806a1069f0697068e068a0000086f00000ac6000000020013acd7000000000000000000000000000008c400000000000000000000000000000773ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2e656e64 [readerid] => admin [sample_id] => 1111 ) But i am getting this Array ( [ssid] => d41d8cd98f00b204e9800998ecf8427e [readerid] => admin [sample_id] => 1111 ) I have gone through this.But i don't think its working for me.I have seen htaccess file also.Its fine. My url is like <server_name>/Nfc/test/fromXML?ssid=d41d8cd98f00b204e9800998ecf8427e&rawstring=303330363036422031333235353030323039ffffffffffffffffffffffffffff33333030302041202046542031333238203030303030323831ffffffffffffff31362f30372f323031332d2d313035343031ffffffffffffffffffffffffffff0ba504d203430aeeffffffffffffffff00db00db02ca00db02caffffffffffff00000000ffffffffffffffffffffffffbe51ffffffffffffffffffffffffffff8000ffffffffffffffffffffffffffff00ec856cffffffffffffffffffffffff2ea495a82eaa959dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff30303031303030350000000900000bbf0013ac9e0013aca300003504fffffffb06b706ae06aa06a2069c06990690068e0000086a00000ad80013acc60013acc70013acc90013accd000034f7fffffffb06b206ae06a806a1069f0697068e068a0000086f00000ac6000000020013acd7000000000000000000000000000008c400000000000000000000000000000773ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2e656e64&readerid=admin&sample_id=1111 I am using zend.Please someone help me. A: Well I found this solution if(@$_REQUEST['rawstring']=='' || !(@$_REQUEST['rawstring'])){ $str=($_SERVER['QUERY_STRING']); // print_r(parse_str($str)); $new=explode("&rawstring=",$str); $raw=explode("&readerid",$new[1]); $_REQUEST['rawstring']=$raw[0]; } Is there some better way to parse $_SERVER['QUERY_STRING']?
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2005: Need advice on handling multiple-language data in one table column I'm running SQL Server 2005 and .Net 2.0. I have some tables that need to store data in multiple languages, in the same column. E.g. an Article table, with ArticleID (identity) and ArticleName (nvarchar 100) The data in ArticleName might be in various languages. My database is using the default collation of SQL_Latin1_General_CP1_CI_AS, as most of our data is in English. Each user in my application can select his/her preferred culture. In the user interface, the articles data is displayed in a data grid and the user can sort them by ArticleName. Right now, the sort order is not correct because of my database collation. I am thinking of fixing this by using the ORDER BY ... COLLATE clause. But how do I map the correct user culture to the SQL Server collation? Do I have to specify for each culture, like this - eg. if culture = zh-CN (Chinese PRC), then use collation Chinese_PRC_CI_AS and so on... Is there a better way to get the collation? Is my approach correct? Or is there a better way to handle this? (I did think of actually performing the sorting in .Net, but that seems like a waste of CPU time.) Thanks for reading. A: SQL Server 2005 has a fn_helpcollations() table function, which returns all supported collations: select *, COLLATIONPROPERTY(name, 'CodePage') as CodePage, COLLATIONPROPERTY(name, 'LCID') as LCID, COLLATIONPROPERTY(name, 'ComparisonStyle') as ComparisonStyle, COLLATIONPROPERTY(name, 'Version') as Version from fn_helpcollations() This MSDN article deals with SQL Server collations in detail and states: However, because there is no direct mapping between LCID and collations, you cannot determine the correct collation from an LCID. This is inconvenient if you would like to be able automatically to assign the best sorting order for users, based on their locale ID. I suggest you build a custom table mapping SQL collations to the languages you support for your users, retrieve the user's collation from this mapping table, and use ORDER BY COLLATE as you intended.
{ "pile_set_name": "StackExchange" }
Q: finding the limit algebraically Struggling to find $$ \lim_{x\to-2}\left(\frac{1}{x+2}+\frac{4}{x^2-4}\right) $$ I know the answer is $-1/4$, but I still can't get to it algebraically, without a calculator A: Big Hint $$\frac{1}{x+2}+\frac{4}{x^2-4}=\frac{1}{x+2}+\frac{4}{(x-2)(x+2)}=\frac{1}{x+2}\left(1+\frac{4}{x-2}\right)=\frac{1}{x+2}\left(\frac{x+2}{x-2}\right)=\frac{1}{x-2}$$
{ "pile_set_name": "StackExchange" }
Q: Saving a photo attached in text message I have a Galaxy S2, running Android 4.0.3 I can open a photo attached to a text message. How can I save the photo (not the message)? A: When in the message window, "long press" the image (hold your finger down on the image for a second or two) and a menu should pop up giving you the option to download or save the attachment. When you go to your gallery you'll usually see attachments you've downloaded in a folder called "Downloads" or "Messaging."
{ "pile_set_name": "StackExchange" }
Q: How do I access a variable outside the scope it is declared? let playerone = document.querySelector(".dealItP1"); let playertwo = document.querySelector(".dealItP2"); let playerthree = document.querySelector(".dealItP3"); let playerfour = document.querySelector(".dealItP4"); let playerUserPot = [0]; let playerUserPotOriginal = [...playerUserPot]; let playerOnePot = [500]; let playerOnePotOriginal = [...playerOnePot]; let playerTwoPot = [500]; let playerTwoPotOriginal = [...playerTwoPot]; let playerThreePot = [500]; let playerThreePotOriginal = [...playerThreePot]; let playerFourPot = [500]; let playerFourPotOriginal = [...playerFourPot]; let deck = ["2 Club", "2 Spade", "2 Diamond", "2 Heart", "3 Club", "3 Spade", "3 Diamond", "3 Heart", "4 Club", "4 Spade", "4 Diamond", "4 Heart", "5 Club", "5 Spade", "5 Diamond", "5 Heart", "6 Club", "6 Spade", "6 Diamond", "6 Heart", "7 Club", "7 Spade", "7 Diamond", "7 Heart", "8 Club", "8 Spade", "8 Diamond", "8 Heart", "9 Club", "9 Spade", "9 Diamond", "9 Heart", "10 Club", "10 Spade", "10 Diamond", "10 Heart", "Jack Club", "Jack Spade", "Jack Diamond", "Jack Heart", "Queen Club", "Queen Spade", "Queen Diamond", "Queen Heart", "King Club", "King Spade", "King Diamond", "King Heart", "Ace Club", "Ace Spade", "Ace Diamond", "Ace Heart"]; let originaldeck = [...deck]; const shuffle = arr => arr.reduceRight((res, _, __, arr) => [...res, arr.splice(~~(Math.random() * arr.length), 1)[0]], []); var PlayPoker = { setGameStart: function() { this.startingPot(); this.activePlayers(); this.dealPlayers(); this.bigBlind(); this.loopPoker(); }, startingPot: function() { document.querySelector("#userPot").innerHTML = 'Pot:' + playerUserPot; document.querySelector("#p1Pot").innerHTML = 'Pot:' + playerOnePot; document.querySelector("#p2Pot").innerHTML = 'Pot:' + playerTwoPot; document.querySelector("#p3Pot").innerHTML = 'Pot:' + playerThreePot; document.querySelector("#p4Pot").innerHTML = 'Pot:' + playerFourPot; }, activePlayers: function() { var activePlayers1 = ["User", "Player1", "Player2", "Player3", "Player4"]; if (playerUserPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'User'); }; if (playerOnePot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player1'); }; if (playerTwoPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player2'); }; if (playerThreePot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player3'); }; if (playerFourPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player4'); }; }, dealPlayers: function() { var freshDeck01 = shuffle(originaldeck); var userDeal = freshDeck01.filter(function(value, index, arr) { return index < 2; }); Array.prototype.subtract = function(array) { array = array.slice(); return this.filter(function(freshDeck01) { var p = array.indexOf(freshDeck01); if (p === -1) { return true; } array.splice(p, 1); }); } var loadedDeck01 = freshDeck01.subtract(userDeal); var freshDeck02 = shuffle(loadedDeck01); var p1Deal = freshDeck02.filter(function(value, index, arr) { return index < 2; }); var loadedDeck02 = freshDeck02.subtract(p1Deal); var freshDeck03 = shuffle(loadedDeck02); var p2Deal = freshDeck03.filter(function(value, index, arr) { return index < 2; }); var loadedDeck03 = freshDeck03.subtract(p2Deal); var freshDeck04 = shuffle(loadedDeck03); var p3Deal = freshDeck04.filter(function(value, index, arr) { return index < 2; }); var loadedDeck04 = freshDeck04.subtract(p3Deal); var freshDeck05 = shuffle(loadedDeck04); var p4Deal = freshDeck05.filter(function(value, index, arr) { return index < 2; }); let xu = document.querySelector(".dealItUser"); /*Deal Cards*/ xu.innerHTML = '<p>User</p>' + userDeal; let x1 = document.querySelector(".dealItP1"); x1.innerHTML = '<p>The Mouth</p>' + p1Deal; let x2 = document.querySelector(".dealItP2"); x2.innerHTML = '<p>Snake Eyes</p>' + p2Deal; let x3 = document.querySelector(".dealItP3"); x3.innerHTML = '<p>10 gallon</p>' + p3Deal; let x4 = document.querySelector(".dealItP4"); x4.innerHTML = '<p>Glance A lot</p>' + p4Deal; }, bigBlind: function() {}, loopPoker: function() { for (let i = 0; i < 5; i++) { if (i = 1) { document.querySelector(".button").value = 1; }; if (i = 2) { document.querySelector(".button").value = 2; }; if (i = 3) { document.querySelector(".button").value = 3; }; if (i = 4) { document.querySelector(".button").value = 4; }; if (i = 5) { document.querySelector(".button").vlaue = 0; }; } } } .main { box-sizing: border-box; border: 3px solid green; height: 1200px; width: 1200px; position: absolute; background-color: black; } .title { box-sizing: border-box; border: 3px green solid; height: 200px; width: 200px; position: absolute; top: 1%; left: 1%; background-color: green; opacity: .8; font-family: coniferous, sans-serif; font-style: normal; font-weight: 300; color: black; } .User { box-sizing: border-box; border: 3px green solid; height: 200px; width: 400px; position: absolute; top: 28%; left: 67%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .dealItUser { box-sizing: border-box; border: 3px green solid; height: 200px; width: 150px; position: absolute; top: 10%; left: 85%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .UserFormBet { position: absolute; top: 40%; left: 10%; } .UserFormRadio { position: absolute; top: 25%; left: 35%; } .UserFormAmount { position: absolute; top: 25%; left: 50%; } .P1 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 400px; position: absolute; top: 28%; left: 32%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .dealItP1 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 150px; position: absolute; top: 10%; left: 70%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .P1FormBet { position: absolute; top: 40%; left: 10%; } .P1FormRadio { position: absolute; top: 25%; left: 35%; } .P1FormAmount { position: absolute; top: 25%; left: 50%; } .P2 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 400px; position: absolute; top: 45%; left: 1%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .dealItP2 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 150px; position: absolute; top: 10%; left: 55%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .P2FormBet { position: absolute; top: 40%; left: 10%; } .P2FormRadio { position: absolute; top: 25%; left: 35%; } .P2FormAmount { position: absolute; top: 25%; left: 50%; } .P3 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 400px; position: absolute; top: 62%; left: 32%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .dealItP3 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 150px; position: absolute; top: 10%; left: 40%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .P3FormBet { position: absolute; top: 40%; left: 10%; } .P3FormRadio { position: absolute; top: 25%; left: 35%; } .P3FormAmount { position: absolute; top: 25%; left: 50%; } .P4 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 400px; position: absolute; top: 45%; left: 67%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .dealItP4 { box-sizing: border-box; border: 3px green solid; height: 200px; width: 150px; position: absolute; top: 10%; left: 25%; background-color: green; opacity: .5; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 25px; color: red; font-weight: 500px; } .P4FormBet { position: absolute; top: 40%; left: 10%; } .P4FormRadio { position: absolute; top: 25%; left: 35%; } .P4FormAmount { position: absolute; top: 25%; left: 50%; } <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Untitled Document</title> <link href="../CSS/pokerTryOne.css" rel="stylesheet" type="text/css"> </head> <body> <div class="main"> <div class="dealItUser">7 </div> <div class="title"><button class="button" value="0" style="height:150px; width: 150px; background-color: red; color: yellow;" onclick="PlayPoker.setGameStart()">Click Button to Deal</button> <div class="counter" style="color: red; font-size: 2em">7</div> </div> <div class="User"> "Hold'en Fold'ems" User Player <p id="userPot">Pot:</p> <form method="post" action="form-handler.php"> <div> <div class="UserFormBet"> <p>Bet:</p> </div> <div class="UserFormRadio"> <input type="radio" name="bet" value="5"> 5<br> <input type="radio" name="bet" value="10"> 10<br> <input type="radio" name="bet" value="25"> 25<br> <input type="radio" name="bet" value="50"> 25<br> <input type="radio" name="bet" value="25"> 50<br> </div> <div class="UserFormAmount"> <label for="name">Amount: <span class="required">*</span> </label> <input type="text" id="name" name="name" value="" placeholder="Your Bet" required="required" autofocus /> <p> <input type="submit" value="Submit" id="submit" /> </p> </div> </form> </div> </div> <div class="dealItP1">7</div> <div class="P1"> "The Mouth" Phil Hellmuth <p id="p1Pot">Pot:</p> <form method="post" action="form-handler.php"> <div> <div class="P1FormBet"> <p>Bet:</p> </div> <div class="P1FormRadio"> <input type="radio" name="bet" value="5"> 5<br> <input type="radio" name="bet" value="10"> 10<br> <input type="radio" name="bet" value="25"> 25<br> <input type="radio" name="bet" value="50"> 25<br> <input type="radio" name="bet" value="25"> 50<br> </div> <div class="P1FormAmount"> <label for="name">Amount: <span class="required">*</span> </label> <input type="text" id="name" name="name" value="" placeholder="Your Bet" required="required" autofocus /> <p> <input type="submit" value="Submit" id="submit" /> </p> </div> </form> </div> </div> <div class="dealItP2">7 </div> <div class="P2">"Snake Eyes" Daniel Negreanu <p id="p2Pot">Pot:</p> <form method="post" action="form-handler.php"> <div> <div class="P2FormBet"> <p>Bet:</p> </div> <div class="P2FormRadio"> <input type="radio" name="bet" value="5"> 5<br> <input type="radio" name="bet" value="10"> 10<br> <input type="radio" name="bet" value="25"> 25<br> <input type="radio" name="bet" value="50"> 25<br> <input type="radio" name="bet" value="25"> 50<br> </div> <div class="P2FormAmount"> <label for="name">Amount: <span class="required">*</span> </label> <input type="text" id="name" name="name" value="" placeholder="Your Bet" required="required" autofocus /> <p> <input type="submit" value="Submit" id="submit" /></p> </div> </form> </div> </div> <div class="dealItP3">7 </div> <div class="P3">"10 Gallon" Doyel Brunsen <p id="p3Pot">Pot:</p> <form method="post" action="form-handler.php"> <div> <div class="P3FormBet"> <p>Bet:</p> </div> <div class="P3FormRadio"><input type="radio" name="bet" value="5"> 5<br> <input type="radio" name="bet" value="10"> 10<br> <input type="radio" name="bet" value="25"> 25<br> <input type="radio" name="bet" value="50"> 25<br> <input type="radio" name="bet" value="25"> 50<br> </div> <div class="P3FormAmount"> <label for="name">Amount: <span class="required">*</span> </label> <input type="text" id="name" name="name" value="" placeholder="Your Bet" required="required" autofocus /> <p><input type="submit" value="Submit" id="submit" /></p> </div> </form> </div> </div> <div class="dealItP4">7 </div> <div class="P4">"Sir Glance A Lot" Phil Ivy <p id="p4Pot">Pot:</p> <form method="post" action="form-handler.php"> <div> <div class="P4FormBet"> <p>Bet:</p> </div> <div class="P4FormRadio"><input type="radio" name="bet" value="5"> 5<br> <input type="radio" name="bet" value="10"> 10<br> <input type="radio" name="bet" value="25"> 25<br> <input type="radio" name="bet" value="50"> 25<br> <input type="radio" name="bet" value="25"> 50<br> </div> <div class="P4FormAmount"> <label for="name">Amount: <span class="required">*</span> </label> <input type="text" id="name" name="name" value="" placeholder="Your Bet" required="required" autofocus /> <p> <input type="submit" value="Submit" id="submit" /> </p> </div> </form> </div> </div> </div> <div class="dealBet"></div> <div class="flopIt"></div> <div class="flopBet"></div> <div class="turnIt"></div> <div class="turnBet"></div> <div class="riverIt"></div> <div class="riverBet"></div> </div> <script type="text/javascript" src="../JavaScript/pokerTryOne.js"></script> </body> </html> I have listed nested functions within the main function"setGameStart" which is set to the variable "PlayPoker". I would like to access the variable activePlayers1, declared in the activePlayers function, from the loopPoker function. I have tried declaring the variable activePlayers1 with var, and I figured that would work. Maybe it has something to do with parsing it into the function as an argument? A: return the activePlayers1 from activePlayer, then pass this to loopPoker, or You can use localStorage setGameStart: function() { this.startingPot(); let activePlayers = this.activePlayers(); this.dealPlayers(); this.bigBlind(); this.loopPoker(activePlayers); }, activePlayers: function() { let activePlayers1 = ["User", "Player1", "Player2", "Player3", "Player4"]; if (playerUserPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'User'); }; if (playerOnePot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player1'); }; if (playerTwoPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player2'); }; if (playerThreePot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player3'); }; if (playerFourPot == 0) { activePlayers1 = activePlayers1.filter(e => e !== 'Player4'); }; return activePlayers1; }, loopPoker: function(activePlayer) { console.log(activePlayer); }
{ "pile_set_name": "StackExchange" }
Q: One of my revert objects for drag n drop with function is half way wrong in Adobe Edge Animate I applied the answer here for revert on this thread (Adding a function to jQuery draggable revert "event") but I still have a problem. When placed in the wrong drappable, the manager icon for some reason instead of reverting to its place, just hides and shows the correct icon where it would if it did not revert and was correct. The feedback is wrong which is which is what should be. All the others do revert and show feedback as expected if I place them in the wrong droppable. This is strange that one would act differently. All the correct ones do what they are supposed to do. The setup: I have a long background with icons which is movable with keydown events. On the top I have a (fixed) bar with the droppables and hidden icons that will appear on correct draggable while the actual draggables will hide. This is because otherwise the draggables would move with the background since if is a different div than the bar where the droppable are. Hope this makes sense. var icons = ['GOALS','CUSTOMER','MANAGER','PRODUCT','PRICE','DELIVER','BALANCE']; for(j=0;j<icons.length;j++){ sym.$(icons[j]).addClass('drag'+j); // each draggable corresponds to a droppable // by class name indexed sym.$('.drag'+j).draggable({ revert: function(obj){ if(obj===false){ // add feedback screen and sound and revert icon sym.$('wrong').attr('src',"images/wrongSpot.png"); sym.$('wrong').animate({'top': 23},1000); sym.$("incorrectFX")[0].play(); return true; }else{ return false; }// end if else statement }// end revert });// end draggable sym.$('d'+j).droppable({ accept: ".drag"+j, drop: dropEvent }); // end droppable } // end for loop k = 0; function dropEvent(event, ui){ ui.draggable.position( { of: $(this), my: 'center', at: 'center' } ); ID = ui.draggable.attr("id").replace('Stage_',''); console.log('this is the id name: ' + ID); sym.$('wrong').animate({'top': 23},1000); // replace wrong image with goodJob image since it is correct sym.$('wrong').attr('src',"images/goodJob.png"); if (music.paused ) { sym.$("correctFX")[0].pause(); } else { sym.$("correctFX")[0].currentTime = 0; sym.$("correctFX")[0].play(); } // since the droppable area is independant of the bg which move // I implemented a substitute icon in the fixed area sym.$(""+ID+"Copy").css({'opacity':1.0}); // show icon on the bar sym.$(""+ID+"").css({'opacity': 0}); // hide the draggable icon // count the number of correct to show feedback k++; if(k==7){ sym.$('complete').animate({"left":0},700); sym.$("completionFX")[0].play(); sym.$('wrong').animate({'top':450},1000); } } // end dropevent function A: If you only encounter a problem from Index 2 of your array, that contains MANAGER, this would create the following code: sym.$('MANAGER').addClass('drag2'); If you have any other classes, that are drag2, this would cause a conflict in the selection. Check your code for any classes or IDs that might match other than
{ "pile_set_name": "StackExchange" }
Q: How do I change a list in python List: [['1', '2', '4'],['1', '4', '8'],['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']] below code on list : neighbor1 = [list[i:i + 2] for i in range(0, len(list), 1)] output: [[['1', '2', '4'],['1', '4', '8']],[['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']]] [[['1', '2', '4'],['1', '4', '8']],[['03', '8', '6', '1', '62', '7'],['53', '8', '2', '82']]] but i want : [[['1','2'],['2','4']],[['1','4'],['4','8']],[['03','8'],['8','6'],['6','1'],['1','62'],['62','7']],[['53','8'],['8','2'],['2','82']]] A: You were almost there, you just need to go one level deeper: [[x[i:i+2] for i in range(len(x)-1)] for x in List] btw never use keyword list as variable name, or you can run into some really weird things...
{ "pile_set_name": "StackExchange" }
Q: Get Amount like Balance-Sheet in sql query I have following data in one table... Name CourseFee AdditionalCharges ExpenseAmount Course-A 500 10 0 Course-B 250 0 0 Paid To Trainer 0 0 250 I want following output with sql query Name CourseFee AdditionalCharges ExpenseAmount NetAmount Course-A 500 10 0 510 Course-B 250 0 0 760 Paid To Trainer 0 0 250 510 NetAmount = (Course Fee + Additional Charges - ExpenseAmount) A: You seem to want a cumulative sum of the fields: select t.*, (select sum(t2.CourseFee + t2.AdditionalCharges - t2.ExpenseAmount) from onetable t2 where t2.id <= t.id ) as NetAmount from onetable t; Notes: This assumes you have a column of some sort that defines the ordering of the rows. It is called id in the query above, but it could be an id, date, or something else. SQL table represent unordered sets, so such a column is necessary. You can do this using outer apply instead of a correlated subquery. SQL Server 2012+ directly supports cumulative sums.
{ "pile_set_name": "StackExchange" }
Q: facets as in facet_grid, and axis.line as for facet_wrap? I am trying to build a plot using facets as in facet-grid, so plots separate in the x and y axes using two factors, as with: mtcars %>% ggplot() + geom_point(aes(x=mpg, y=wt)) + facet_grid(cyl ~ gear, scales="free") + theme(panel.background = element_blank(), axis.line = element_line(size=0.5)) The problem with the above approach is that only axis lines are shown for the up and left-most plots, so it is difficult to differentiate plots without using a colored panel.background. This problem does not occur with facet-wrap, but this function will apparently not group factors in the two axes, or the strips will be always in one of the sides (according to strip.position argument), but not up and right as for facet_grid. e.g.: mtcars %>% ggplot() + geom_point(aes(x=mpg, y=wt)) + facet_wrap(cyl ~ gear, scales="free") + theme(panel.background = element_blank(), axis.line = element_line(size=0.5)) Question Is it possible to create a plot with facet_grid, but lines in all axes, or alternatively use facet_wrap, but group factors as with facet_grid? A: I think you are looking for facet_rep_grid in the lemon package. Here is the code to produce the desired plot. library(tidyverse) library(lemon) mtcars %>% ggplot() + geom_point(aes(x=mpg, y=wt)) + facet_rep_grid(cyl ~ gear, scales="free", repeat.tick.labels = "all") + theme(panel.background = element_blank(), axis.line = element_line(size=0.5))
{ "pile_set_name": "StackExchange" }
Q: issue retrieving child input type. currently returning as 'undefined' so the best way for you to understand what I am trying to achieve is to view this demo: live demo. the problem is that the type being returned is 'undefined' rather that 'text'. Can anybody please explain why this happening? many thanks, A: If you don't want to change your HTML, this code is working : $(".question").each(function(){ var type = $('input[type != "hidden"]',this).attr("type"); alert(type); }); // Or $(".question").each(function(){ var type = $(this).find('input[type != "hidden"]').attr("type"); alert(type); });
{ "pile_set_name": "StackExchange" }
Q: How to compute conditional expected value $E(Y|X-Y)$ Is there any property that could help me out on how to compute $E(Y|X-Y)$, given that $X$ and $Y$ are independent? A: Yes. I also know $f_{Y|X},f_Y,f_X,f_{X,Y}$. My problem is $f_{Y|X−Y}$. $$f_{Y\mid X-Y}(y\mid z) ~{=~ \dfrac{f_{X-Y,Y}(z,y)}{f_{X-Y}(z)} \\=~ \dfrac{f_{X,Y}(z+y, y)}{{\small\displaystyle\int}_\Bbb R f_{X,Y}( z+t, t)\mathrm d t}}$$ Thus: $$\mathsf E(Y\mid X-Y) ~{=~ \dfrac{\displaystyle\int_\Bbb R t\;f_{X-Y,Y}(X-Y, t)\;\mathrm d t}{\displaystyle\int_\Bbb R f_{X-Y,Y}(X-Y,t)\;\mathrm d t} \\=~ \dfrac{\displaystyle\int_\Bbb R t\;f_{X,Y}(X-Y+t,t)\;\mathrm d t}{\displaystyle\int_\Bbb R f_{X,Y}(X-Y+t,t)\;\mathrm d t}}$$ $f_{\small X,Y}(x,y)~=~λ_{\small X}e^{−λ_{\small X}x}\cdot λ_{\small Y}e^{−λ_{\small Y}y}$ Presumably this supported over $\{(x,y): x>0, y>0\}$ ...? $$\mathsf E(Y\mid X-Y) ~{=~ \dfrac{\displaystyle\int_\Bbb R t\;e^{(-\lambda_{\small_X}(X-Y)-(\lambda_{\small X}+\lambda_{\small Y})t)}\;\mathbf 1_{X-Y+t\geqslant 0 ~\cap~ t\geqslant 0}\;\mathrm d t}{\displaystyle\int_\Bbb R e^{(-\lambda_{\small_X}(X-Y)-(\lambda_{\small X}+\lambda_{\small Y})}t)\;\mathbf 1_{X-Y+t\geqslant 0~\cap~ t\geqslant 0}\;\mathrm d t} \\ \phantom{= ~\dfrac{\displaystyle\int_{\max\{Y-X,0\}}^\infty t\;e^{-(\lambda_{\small X}+\lambda_{\small Y})t}\;\mathrm d t}{\displaystyle\int_{\max\{Y-X,0\}}^\infty e^{-(\lambda_{\small X}+\lambda_{\small Y})t}\;\mathrm d t} \\ =~ \max\{Y-X,0\}+(\lambda_{\small X}+\lambda_{\small Y})^{-1} }}$$
{ "pile_set_name": "StackExchange" }
Q: How to hide Django rest Framework schema? I use drf_yasg swagger for my Django API. I would like to know how to easily disable the schema and model. screenshot here is my code: from .models import Articles from .serializers import ArticlesSerializer from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import SessionAuthentication,TokenAuthentication, BasicAuthentication from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from rest_framework.parsers import JSONParser from django.utils.decorators import method_decorator from django.contrib.auth import authenticate, login, logout from rest_framework.decorators import api_view from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi @swagger_auto_schema(methods=['get'], operation_description="description", manual_parameters=[ openapi.Parameter('category', openapi.IN_QUERY, "category1, category2, category3", type=openapi.TYPE_STRING), openapi.Parameter('name', openapi.IN_QUERY, "full name", type=openapi.TYPE_STRING), ], responses={ 200: openapi.Response('Response', ArticlesSerializer), }, tags=['Articles']) # desactivate POST methode on swagger @swagger_auto_schema(method='POST', auto_schema=None) @api_view(['GET','POST']) def articles(request): """ List all articles. """ if request.user.is_authenticated: if request.method == 'GET': articles = Articles.objects.all() serializer = ArticlesSerializer(Articles, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ArticlesSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) return JsonResponse({"status":"403", "message":"User not authenticated"}) If i add this class UserList(APIView): swagger_schema = None i got error: AssertionError: `method` or `methods` can only be specified on @action or @api_view views Code Edited: the articles function is pretty simple nothing related to the API, only Python code. Here the views Class is also pretty simple. Class Views: from django.db import models class Articles(models.Model): STATUS = ( (1, 'PENDING'), (2, 'COMPLETED'), (3, 'DECLINED'), (0, 'BANNED'), ) name = models.CharField(max_length=100) ... status = models.PositiveSmallIntegerField( choices = STATUS, default = 1, ) A: I finally figured it out. I just had to overwrite the responses parameter with either plain text, markdown or html. @swagger_auto_schema(methods=['get'], operation_description="Get article information ", manual_parameters=[ openapi.Parameter('id', openapi.IN_QUERY, "Article Id", type=openapi.TYPE_STRING), ], responses={ 200: '**Example:** \ <div class="highlight-code"><pre>{ <br>\ "category": "string", <br>\ "image": "string",<br>\ "link": "string",<br>\ "birth_date": "string",<br>\ }</pre></div>'}, tags=['Get Articles']) To have the same css effect (background black) you can add this custom CSS in the file ...\site-packages\drf_yasg\static\drf-yasg\style.css .swagger-ui .markdown .highlight-code pre{ color: #fff; font-weight: 400; white-space: pre-wrap; background: #41444e; padding: 15px; } screenShot
{ "pile_set_name": "StackExchange" }
Q: How to select the row where the date is null or max date for that group I have a table with multiple columns, but I will make it easy and just use three. CREATE TABLE TEMPTBL( empl_id varchar(8), empl_no varchar(6), sep_dt date ); INSERT INTO TEMPTBL VALUES ('IS000001', '112233', NULL), ('00418910', '112233', '1/1/2019'); What I am trying to get is the row where either the sep_dt is null or the row where that has the max sep_dt grouped by the empl_no field. So in the case of my example, it would be that first row, 'IS000001' (I just want the select to return the empl_id). Say the Null was '6/8/2018' instead, then I would want to return '00418910'. I have tried, but I know it is wrong because you can't use max like that: SELECT empl_id FROM TEMPTBL empl WHERE empl_no = '112233' AND ( sep_dt IS NULL OR MAX(sep_dt) ) I know it must include a group by or maybe a join. So I came up with this: SELECT empl_id FROM TEMPTBL INNER JOIN ( SELECT empl_no, max(sep_dt) as sep_dt FROM TEMPTBL WHERE empl_no = '112233' GROUP BY empl_no ) emp ON TEMPTBL.empl_no = emp.empl_no AND TEMPTBL.sep_dt = emp.sep_dt This will give me the row with the date in it, not the one with the null value. So it will work if all the sep_dt fields have values, but if one in NULL, it doesnt work, because i want the row with the null value. What am I miss? A: I think you can simply use ROW_NUMBER with a special ORDER BY clause: SELECT * FROM ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY empl_no ORDER BY CASE WHEN sep_dt IS NULL THEN 1 ELSE 2 END, sep_dt DESC ) AS rn FROM t ) AS x WHERE rn = 1 Demo on db<>fiddle
{ "pile_set_name": "StackExchange" }
Q: Como fazer um bypass em um redirecionamento HTTP? Existe alguma forma de fazer um "bypass" e acessar a página? Por exemplo: if(!isset($variavel)) { header ('Location: error.php'); } else { echo 'oi'; } A: Não sei se você considera isto um bypass, mas a emissão do header não termina o script. Você deve fazer isso manualmente com exit após um redirect, ou o script segue em frente: if(!isset($variavel)) { header ('Location: error.php'); exit; } else { echo 'oi'; } // Chegaria aqui sem o exit Se a sua dúvida é quanto à execução do else do seu código, isso não tem relação com o redirecionamento. Tudo depende de a variável $variavel estar definida ou não. Logicamente, se o código de redirecionamento do seu exemplo for executado, não tem como o else também ser executado.
{ "pile_set_name": "StackExchange" }
Q: Stripping metadata from MP3 files Is there a way I can bulk strip mp3 meta data from files? Preferably from the command line on OS X or Linux? I recently tried to use TuneUp (an app that is supposed to located mis-named tracks and fix them) but it has completely ruined my music collection and I just want to start over. A: sudo apt-get install mid3v2 On newer versions of Linux you'll probably need to use the following instead: sudo apt-get install python-mutagen As its man page states, -D or --delete-all will delete all ID3 tags.
{ "pile_set_name": "StackExchange" }
Q: Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error I have two models in Django Users and Contexts.I have defined the models as below class User(models.Model): userId = models.PositiveIntegerField(null = False) pic = models.ImageField(upload_to=getUserImagePath,null=True) Email = models.EmailField(null = True) class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() context_priority = models.CharField(max_length=1) users = models.ManyToManyField(User, related_name='context_users') Now I get a POST request which contains the below JSON { "user" : 12, "action" : "add", "context_name": "Network debug", "context_description" : "Group for debugging network issues", "context_priority": "L" } I want to create a record in the Contexts table.Below is what I am trying to do from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse import json from .models import * import json @csrf_exempt def context_operation(request): if request.method == "POST": user_request = json.loads(request.body.decode('utf-8')) try: if user_request.get("action") == "add": conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), context_priority=user_request.get("context_priority"), users=user_request.get("user") ) conv.save() except Exception as e: print("Context saving exception", e) return HttpResponse(0) return HttpResponse(1) Here I am trying to add a context based on the action field in the JSON request.As you can see, in the Contexts model, the field users has many to many relation with the User model.But when I try to save the values to the Contexts table, I recieve the below error Context saving exception Direct assignment to the forward side of a many-to-many set is prohibited. Use users.set() instead. Based on this StackOverflow post, I tried doing something like this: users=User.objects.add(user_request.get("user")) But I still receive the same error. What am I doing wrong? A: The error should be clear; you cannot assign directly to a many-to-many field. Do it after you create the item. conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), context_priority=user_request.get("context_priority"), ) conv.users.add(user_request.get("user")) Also note, you don't need to call save() after either create() or adding the m2m values.
{ "pile_set_name": "StackExchange" }