text
stringlengths
64
89.7k
meta
dict
Q: How to parse to a type in Scala I'm trying to write a parser in Scala that gradually builds up a concrete type hierarchy. I started with: private def word = regex(new Regex("[a-zA-Z][a-zA-Z0-9-]*")) private def quicktoken: Parser[Quicktoken] = "/" ~> word <~ "/" <~ (space?) ^^ { new Quicktoken(_) } which is fine. /hello/ will get parsed to a quicktoken Now I want to add the quicktoken to a composite expression. I have a class class MatchTokenPart(word:String,quicktoken:RewriteWord){ } I would have thought that I could write... private def matchTokenPartContent: Parser[MatchTokenPart] = word<~equals~quicktoken ^^ { case word~quicktoken => new MatchTokenPart(word, quicktoken)} but it doesn't work. It says that word is of type Option[String] and quicktoken of type String. What am I missing? A: Another precedence issue: a <~ b ~ c is interpreted as a <~ (b ~ c), not (a <~ b) ~ c. This is because infix operators starting with < have lower precedence than ones starting with ~, (see the list in 6.12.3 of the language specification). You want (word <~ equals) ~ quicktoken, so you'll need to supply the parentheses.
{ "pile_set_name": "StackExchange" }
Q: Recentering D3 force layout diagram on node click I am trying to create a force diagram that gets re-centered on click. I am following this as a base: I tried to adjust the click function to set d.fixed=true and also assign fixed points for d.x and d.y. However, I need to turn d.fixed=false for all the other nodes. Also, the node does not transition to the center on click. My question is how do I set all other fixed properties to false and then redraw the force diagram with the new center? I have prepared an example here: The click function is fairly straightforward: function click(d) { d.fixed=true; d.x=10; d.y=10; update(); } I tried adding this to the function: root.forEach(function (d) { d.fixed = false; }); A: You can access the nodes using force.nodes() and iterate to set the fixed attribute to false. force.nodes().forEach(function(d) { d.fixed = false; }); and then update the graph. I forked your example here and added a double click listener that restart the force layout. Regards, A: A few things, in the order I approached the problem. Here's the final fiddle if you want to follow along. First, your update() method does a lot more than just update the position of the nodes; it recalculates the whole tree. It's overkill for what you're trying to do, and while in the end it turned out to not be the source of the problem, I'd still recommend just using force.resume() to get the timer ticking and the nodes moving again. Second, you were on the right track with adding a forEach statement to turn off the former fixed nodes. But forEach works on arrays, and root is an object. So either reuse the flatten method (slow) or do as @Pablo suggested and use force.nodes() to get the nodes as an array (better). Third, and this took a bit to figure out: Once you set a node to be "fixed", the force layout ignores any new d.x and d.y values, resetting them back to d.px and d.py (the previous values). (I assume this is so that if the node is dragged, it will automatically jump back to its fixed position). So to move it to be fixed where you want it to be, you have to set the "previous" values, not the new values. The only problem is that this causes an immediate jump in position, instead of a smooth movement. You might want to add in a transition for that one node (to make it look like it's being dragged to the centre) before calling force.resume().
{ "pile_set_name": "StackExchange" }
Q: changing a Char to the short with the same bit structure. (2's complement issue) I want to Change a Char to the short with the same bit structure. Both are 16 bits I understand that short are 2s complement if they were 1s complement I could use if a < 0 {return (short) math.abs a + 2 ^ 15;} else {return (short) a;} //right? How do I do this to 2s complement negative? I simply want to be able to manipulate the innards of a Char in the same way as I can a Integer. If the answer is just add one I am going to become emotional :) A: The simple solution is to do char ch = ... short s = (short) ch; char ch2 = (char) s; // ch == ch2 Perhaps you imagine it has to be more complicated than it is ;) I simply want to be able to manipulate the innards of a Char in the same way as I can a Integer. In that case you don't even want a short, you want an int which is even simpler. e.g. // sum all the chars of a string String s = "Hello World"; int sum = 0; for(char ch: s.toCharArray()) sum += ch; If the answer is just add one I am going to become emotional No, even less than that. :j BTW you can do char ch = 'A'; int i = ch + 0; int j = ch;
{ "pile_set_name": "StackExchange" }
Q: Issue in Server.Target while navigation I'm developing a .net application using twitter bootstrap. I'm navigating from Default1.aspx to Default2.aspx using Server.Target and on the page load of Default2.aspx, i'm saving Default2.aspx page as html page and mailing that html file to the user. I'm facing some issues here. After sending mail to the user, it should be back to Default1.aspx. Here is my code Default.aspx: <asp:Button ID="btnNavigate" Text="Navigate to Default2.aspx" runat="server" class="btn btn-sm btn-danger" OnClick="btnNavigate_Click"> </asp:Button> Default.aspx.cs protected void btnNavigate_Click(object sender, EventArgs e) { Context.Items.Add("Id", "10"); string targetPath = "~/Reports/Default2.aspx"; Server.Transfer(targetPath); } Default2.aspx.cs protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Context.Items["Id"] != null) { int Id=Convert.ToInt32(Context.Items["Id"]); if (SendDashboardHTMLfileAsEmail(Id)==true) { Context.Items.Add("TestId", Id.ToString()); string targetPath = "~/Reports/Default1.aspx"; Server.Transfer(targetPath); } } } } private void SendDashboardHTMLfileAsEmail(int Id) { //create Default2.aspx page as html file in a path //Send a email to user with an attachment //newly created html file is the attachment } I'm getting an error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack while i'm navigating to Default1.aspx page. After sending mail to the user it is not getting navigated to Default1.aspx,but it is in Default2.aspx still. Please help me out. A: Try to use the Response.Redirect method instead. Response.Redirect("~/Reports/Default1.aspx", false); However, you cannot use Context to transfer information to the next page, use Session instead: Session["Id"] = 10; To retrieve the information on the next page, use a cast on the Session object var Id = (int)Session["Id"];
{ "pile_set_name": "StackExchange" }
Q: Validation check to see if item on list exists c# I'm trying to perform a validation check on my list in C#. The list contains a username and hashed password. It looks like: Shaun,ewoaih3243nfeiwo John, fewafwea231232 Alex, fhi34325325325 So for example Shaun is the Username and ewoaih3243nfeiwo is the password. I am reading this list in from a database in the function Read. Here is my code: private void LoginButton_Click(object sender, EventArgs e) { List<string> List = Read(); label3.Text = null; textBox2.Text = null; string Username = textBox1.Text; string Password = textBox2.Text; String hashPassword = passHash.HashPass(Password); for (int i = 0; i < List.Count; i++) { if (List[i].Contains(Username)) { if (List[i].Contains(hashPassword)) { MessageBox.Show("Welcome, " + textBox1.Text + ". Logging in...", "Welcome"); Form.ActiveForm.Hide(); Main.FrontWindow Start = new Main.FrontWindow(); Start.ShowDialog(); } else { label3.Text = "Username and password do not match."; } } else { label3.Text = "User does not exist"; } } } However, when I fill in the text boxes and run I always get the result that the user does not exist, even though it quite clearly does. For example when I input Shaun and an incorrect password it should say Username and Password do not match when it says instead User does not exist. EDIT: Here is how I am creating the dictionary public Dictionary<string, string> Read() { string username; string password; string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\A2 Computing\C# Programming Project\Database1.accdb"; string SelectQuery = "SELECT Username, Password FROM users"; OleDbConnection Connection = new OleDbConnection(ConnectionString); OleDbCommand Command = new OleDbCommand(SelectQuery, Connection); Command.Connection.Open(); OleDbDataReader Reader = Command.ExecuteReader(CommandBehavior.CloseConnection); List<string> usernameList = new List<string>(); List<string> passwordList = new List<string>(); while (Reader.Read()) { username = (string)Reader["Username"]; string usernameAdd = Convert.ToString(username); usernameList.Add(usernameAdd); password = (string)Reader["Password"]; string passwordAdd = Convert.ToString(password); passwordList.Add(passwordAdd); } var userDictionary = usernameList.Zip(passwordList, (u, p) => new { u, p }) .ToDictionary(x => x.u, x => x.p); var userList = userDictionary.ToList(); listBox1.DataSource = userList; return userDictionary; } A: You should really separate your username and password. Please use a Dictionary<string, string>. Also, do not use a for-loop and then check if it Contains() the item. That would just be absurd! You can do something as follows: Dictionary<string, string> namesPasswords = Read(); // ... hashing, etc. if(namesPasswords.Keys.Contains(Username)) if(namesPasswords[Username].Equals(hashPassword)) // Welcome... else // Error...
{ "pile_set_name": "StackExchange" }
Q: Demonstrative pronoun: does it have to match the subject? I'm a little confused about German grammar, the demonstratives to be specific (this, that, these, those). Does the demonstrative pronoun have to match the subject being described? Example: Would This woman be Diese Frau? A: It's actually quite straightforward: this = dieser/diese/dieses that = jener/jene/jenes these = diese those = jene So you are correct, "this woman" is "diese Frau".
{ "pile_set_name": "StackExchange" }
Q: Instrumentação de JVM. Saber quantas vezes um método foi chamado durante a execução do programa Tenho uma aplicação de processamento de batch, atualmente ela é multithreads, preciso saber quantas vezes estamos executando o método salvar. Alguém teria alguma ideia? Pois preciso aumentar o número de threads durante a noite e gostaria de ter algum parâmetro para esta minha decisão. A: De acordo com o que você falou, você tem um método salvar, deve ser estático ou não. Seja como for, você quer saber quantas vezes ele é executado. durante um período de tempo. Use AspecjJ Com AspectJ, você será capaz de lastrear o numero de execuções de determinados métodos. Sugiro que você decida entre salvar essa informação para um arquivo de log, ou incrementar uma variável que você possa ler posteriormente. Como? Vou partir do pressuposto de que você está utilizando Maven para gerenciar o ciclo de vida dos seus builds. Primeiramente, tenha as dependencias do AspectJ, você vai precisar dos seguintes artefatos: <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> Agora, crie um JoinPoint Para os métodos desejados: //A seguinte classe deve servir de template para você: import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class TrackingMethodsAspect { public long volatile executedTimes = 0; @Before("execution(* SuaClasse.seuMetodo(..))") public void track(JoinPoint joinPoint) { executedTimes++; } } Nesta estratégia, posteriormente você pode ler o valor escrito para variável executedTimes e tomar decisões de como melhor gerenciar suas threads, e a quantidade de objetos. O que o AspectJ fará serpa instrumentar suas classes, no caso seu método e permitir que você insira byde-codes. Tanto em runtime quanto em buildtime E por último e não menos importante utilize o plugin do AspectJ para que efetivamente a instrumentação aconteça. Você deve ter este plugin na sessão de plugins do POM.XML <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.2</version> <executions> <execution> <goals> <goal>compile</goal><!-- to weave all your main classes --> <goal>test-compile</goal><!-- to weave all your test classes --> </goals> </execution> </executions> <configuration> <weaveDependencies> <weaveDependency> <groupId>com.seuprojeto</groupId> <artifactId>ProjectB</artifactId> </weaveDependency> </weaveDependencies> <showWeaveInfo>true</showWeaveInfo> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> No exemple acima a instrumentação ocorrerá em build-time E não em runtime, é importante se atentar a esse detalhe.
{ "pile_set_name": "StackExchange" }
Q: Database write delayed in rails controller? I'm using authlogic to generate a perishable token and send it on to the user for activation of his account, and send the mail later in a delayed job. Like so: def deliver_activation_instructions! reset_perishable_token! Notifier.send_later(:deliver_activation_instructions, self) end What I'm seeing is that the perishable token written by the 'reset_perishable_token' call is not the one that has been emailed to the user. If I'm using send_later, is there a chance that the worker will pick up old values from the database? I thought that the Notifier.send_later call would only occur after the token had been written.... Or is there something I don't understand about how this works? A: To answer my question, the problem was not a bad database write - it was that the authlogic library automatically updates the perishable token every time you save the database record. I was sending the token, then saving the user record which reset the token! There is a config setting that I needed: disable_perishable_token_maintenance = true That did the trick and fixed my bug
{ "pile_set_name": "StackExchange" }
Q: Discover all services in the network using android NSD I´m trying to find all services in the network using: mNsdManager.discoverServices( SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); but you have to define SERVICE_TYPE for example: public static final String SERVICE_TYPE = "_http._tcp."; so it will discover all http services using tcp, but it wouldn´t find https services at the same time or any other kind of services how can i set all this in order to find any service using tcp? Thank you in advance. A: I am using private static final String SERVICE_TYPE = "_services._dns-sd._udp"; which gives me a list of all available services on the LAN: D/MHC-NSD: Service discovery found: name: _workstation, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _UnoWiFi, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _udisks-ssh, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _airplay, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _raop, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _xbmc-events, type: _udp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _xbmc-jsonrpc, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _xbmc-jsonrpc-h, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _http, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _sftp-ssh, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _ssh, type: _tcp.local., host: null, port: 0 D/MHC-NSD: Service discovery found: name: _arduino, type: _tcp.local., host: null, port: 0
{ "pile_set_name": "StackExchange" }
Q: Why is sizeof giving wrong answer ok I've come across a weirdness, maybe someone can explain it. Source code is (c++ 11) : ‪#‎include‬ <stdio.h> struct xyz_ { float xyz[3]; float &x = xyz[0]; float &y = xyz[1]; float &z = xyz[2]; }; int main(int argc, char *argv[]) { xyz_ xyz; xyz.x = 0; xyz.y = 1; xyz.z = 2; xyz.xyz[1] = 1; printf("as array %f %f %f\n",xyz.xyz[0],xyz.xyz[1],xyz.xyz[2]); printf("as elements %f %f %f\n",xyz.x,xyz.y,xyz.z); int sizexyz = sizeof(xyz); int sizefloat = sizeof(float); printf("float is %d big, but xyz is %d big\n",sizefloat,sizexyz); return 0; } output is: as array 0.000000 1.000000 2.000000 as elements 0.000000 1.000000 2.000000 float is 4 big, but xyz is 24 big So the structure works as I would expect, but the size is twice as large as it should be. Using chars instead of float in the structure gives a segfault when run. I wanted to use struct xyz_ as either an array of floats or individual float elements. A: It is unspecified whether references require storage. In this case your output suggests that your compiler has decided to use storage to implement the references x, y and z. A: How about this: struct xyz_ { float xyz[3]; float &x() {return xyz[0];} float &y() {return xyz[1];} float &z() {return xyz[2];} }; Not as beautiful or elegant, but might reduce the size a bit, though I think the this pointer might occupy additional space, not sure... Of course you would have to use x(), y() and z().
{ "pile_set_name": "StackExchange" }
Q: How can I fix issue with clock being improperly displayed after exiting pause screen? I have created maze game in pygame (this being my first). However when ever I enter and then leave the pause screen the clock is stuck on 00:00:-15. What is even wierder is that if I enter and leave the pause screen again the code works the way I intended it to work (continuing the clock at where it was before entering the pause video. Here is the code which generates the clock: # creates the string that displays time def get_time(hours,minutes,seconds): if len(str(hours)) > 1: a = str(hours) else: a = "0" + str(hours) if len(str(minutes)) > 1: b = str(minutes) else: b = "0" + str(minutes) if len(str(seconds)) > 1: c = str(seconds) else: c = "0" + str(seconds) return a + ":" + b + ":" + c # creates the time counter def draw_time(start_time,pause_time): hours = 0 minutes = 0 seconds = 0 current_time = time.time() - pause_time - start_time if current_time > 3600: while True: if current_time - 3600 > 0: hours += 1 current_time -= 3600 else: while True: if current_time - 60 > 0: minutes += 1 current_time -= 60 else: seconds += int(current_time) break break else: while True: if current_time - 60 > 0: minutes += 1 current_time -= 60 else: seconds += int(current_time) break return [font1.render(get_time(hours, minutes, seconds), True, (0, 0, 0), (255, 255, 255)), get_time(hours, minutes, seconds)] This displays it: screen.blit(text[0], (700, 15)) This activates / deactivates the pause screen: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.key == pygame.K_p: if pause: pause = False pause_time = time.time() - pause_time_start else: pause = True pause_time_start = time.time() - game_time - start if event.key == pygame.K_RETURN: done = True This is the whole code: import pygame import random import time pygame.init() # all fonts used font1 = pygame.font.SysFont("comicsansms", 49, True) font2 = pygame.font.SysFont("comicsansms", 150, True) font3 = pygame.font.SysFont("comicsansms", 28, True) # creates the string that displays time def get_time(hours,minutes,seconds): if len(str(hours)) > 1: a = str(hours) else: a = "0" + str(hours) if len(str(minutes)) > 1: b = str(minutes) else: b = "0" + str(minutes) if len(str(seconds)) > 1: c = str(seconds) else: c = "0" + str(seconds) return a + ":" + b + ":" + c # creates the time counter def draw_time(start_time,pause_time): hours = 0 minutes = 0 seconds = 0 current_time = time.time() - pause_time - start_time if current_time > 3600: while True: if current_time - 3600 > 0: hours += 1 current_time -= 3600 else: while True: if current_time - 60 > 0: minutes += 1 current_time -= 60 else: seconds += int(current_time) break break else: while True: if current_time - 60 > 0: minutes += 1 current_time -= 60 else: seconds += int(current_time) break return [font1.render(get_time(hours, minutes, seconds), True, (0, 0, 0), (255, 255, 255)), get_time(hours, minutes, seconds)] class cell: def __init__(self,up,down,left,right): self.visited = False self.walls = [up,down,left,right] class labyrinth: # generates the maze def __init__(self,id): self.id = id self.walls = [] self.maze_walls = [] self.cells = [] x = 0 t = 0 # creates all cell within the maze for f in range(22): for s in range(28): # if command makes sure no cellls are created where the clock is supposed to be if not (f in (0,1,2) and s > 20): self.cells.append(cell((x + 8, t, 25, 8), (x + 8, t + 33, 25, 8), (x, t + 8, 8, 25), (x + 33, t + 8, 8, 25))) x += 33 x = 0 t += 33 # generates maze using prim's algorithm for v in self.cells[0].walls: self.maze_walls.append(v) self.walls.append(v) self.cells[0].visited = True while len(self.walls) > 0: wall = random.choice(self.walls) # checks which cells are divided by the wall divided_cells = [] for u in self.cells: if wall in u.walls: divided_cells.append(u) if len(divided_cells) > 1 and (not ((divided_cells[0].visited and divided_cells[1].visited) or ((not divided_cells[0].visited) and (not divided_cells[1].visited)))): # checks which cells have been visited for k in divided_cells: k.walls.remove(wall) if k.visited == False: k.visited = True for q in k.walls: if not q in self.walls: self.walls.append(q) if not q in self.maze_walls: self.maze_walls.append(q) if wall in self.maze_walls: self.maze_walls.remove(wall) self.walls.remove(wall) for j in range(0,736,33): for i in range(0,951,33): self.maze_walls.append((i, j, 8, 8)) # draws the maze def draw(self, goal): screen.fill((0, 0, 0)) for k in self.maze_walls: pygame.draw.rect(screen, color, pygame.Rect(k[0],k[1],k[2],k[3])) pygame.draw.rect(screen, color, pygame.Rect(695, 0, 300, 105)) # clock background pygame.draw.rect(screen, (0, 255, 0), goal) # finish id = 0 running = True while running: screen = pygame.display.set_mode((930, 733)) done = False color = (0, 128, 255) # color of the walls x = 16 y = 16 clock = pygame.time.Clock() start = time.time() id += 1 maze = labyrinth(id) goal = pygame.Rect(899,701,25,25) victory = False speed = 4 # movement speed pause = False pause_time = 0 # time spent in pause menue game_time = 0 # time spent playingg while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.key == pygame.K_p: if pause: pause = False pause_time = time.time() - pause_time_start else: pause = True pause_time_start = time.time() - game_time - start if event.key == pygame.K_RETURN: done = True if pause: screen.fill((0, 0, 0)) pause_text = font2.render("PAUSE",True,(255,255,255)) screen.blit(pause_text, (468 - (pause_text.get_width() // 2), 368 - (pause_text.get_height() // 2))) # the actual game if not victory and not pause: game_time = time.time() - pause_time - start move_up = True move_down = True move_left = True move_right = True pressed = pygame.key.get_pressed() # movment if pressed[pygame.K_w] or pressed[pygame.K_UP]: # checks if their is a overlap with the wall for m in maze.maze_walls: player = pygame.Rect(x, y - speed, 10, 10) if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])): move_up = False break if move_up: y -= speed if pressed[pygame.K_s] or pressed[pygame.K_DOWN]: player = pygame.Rect(x, y + speed, 10, 10) for m in maze.maze_walls: if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])): move_down = False break if move_down: y += speed if pressed[pygame.K_a] or pressed[pygame.K_LEFT]: player = pygame.Rect(x - speed, y, 10, 10) for m in maze.maze_walls: if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])): move_left = False break if move_left: x -= speed if pressed[pygame.K_d] or pressed[pygame.K_RIGHT]: player = pygame.Rect(x + speed, y, 10, 10) for m in maze.maze_walls: if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])): move_right = False break if move_right: x += speed # checks if player has reached the goal if goal.colliderect((x, y, 10, 10)): victory = True # draws the screen maze.draw(goal) text = draw_time(start, pause_time) pygame.draw.rect(screen, (255, 100, 0), pygame.Rect(x,y,10,10)) screen.blit(text[0], (700, 15)) # victory screen if victory: screen.fill((0, 0, 0)) time_text = font1.render("Time Taken: " + text[1],True,(255,255,255)) victory_text = font2.render("VICTORY!",True,(255,255,255)) reset = font3.render("(Press Enter to Start New Game)",True,(255,255,255)) screen.blit(victory_text,(468 - (victory_text.get_width() // 2), 328 - (victory_text.get_height() // 2))) screen.blit(time_text, (468 - (time_text.get_width() // 2), (248 - (time_text.get_height() // 2)) + victory_text.get_height())) screen.blit(reset, (468 - (reset.get_width() // 2), (248 - (reset.get_height() // 2)) + victory_text.get_height() + time_text.get_height())) clock.tick(60) pygame.display.flip() A: You are dealing with two different kinds of time measurement here, instants and durations. What you get from time.time() is an instant - it describes a specific point in time. When you substract two instants you get a duration - the time elapsed between those two specific points. By getting confused between the two, you're seeing confusing results. start = time.time() # ... pause_time = 0 # time spent in pause menue game_time = 0 # time spent playingg Here you're saying that start is an instant, the moment the game started. You're saying that pause_time and game_time are durations. They are intended to be the time elapsed since the start of the game spent in the paused/unpaused mode. Every frame that you're not paused, you update game_time: game_time = time.time() - pause_time - start Here start and time.time() are instants, and pause_time is a duration. This works, although it is a little awkward to read. Subtracting start from time.time() gives you the total elapsed time since the game started in either paused or unpaused mode, and subtracting pause_time gives the time spent in unpaused mode. Great. Here's your on-pause behaviour: pause = True pause_time_start = time.time() - game_time - start So time.time() and start are again instants. Subtracting them gives you total elapsed time in any game more. Subtracting game_time gives you the total elapsed time in pause mode, a duration. I'm not certain this is what you actually want, because the next time you use it is in your unpause code: pause = False pause_time = time.time() - pause_time_start So time.time() is an instant, and pause_time_start is a duration. Subtracting them like this will give you another instant, some moment in time before your game started. But you're using this instant like a duration! An instant is still a number, but generally it's a pretty huge number. (Technically it's the number of seconds since the epoch, a specific moment in time that is going to be midnight, Jan 1 1970 in most operating systems you'll likely run Pygame.) Things go obviously wrong when you update game_time again: game_time = time.time() - pause_time - start Now that pause_time has a bad value, you're trying to add one instant (time.time()) and subtract two others. This gives you a huge negative value. When you try to render it, your time rendering code is very confused because it is not expecting negative numbers. It's not displaying "-15" seconds. It's displaying a number like "-1545616400" which doesn't fit on the screen! The reason it works the second time round is that the errors cancel out. This calculation makes game_time hugely negative, which affects the next calculation of pause_start_time, making it hugely positive, and finally causing the next calculation of pause_time to be back to a small duration. You can minimally fix this by deciding what pause_time_start is supposed to be and fixing the corresponding calculations. I think you probably meant it to be the instant the game was paused. If so, you can update your unpause/pause code: if pause: pause = False pause_time += time.time() - pause_time_start else: pause = True pause_time_start = time.time() At the moment we pause, all we do is remember that instant for later. At the moment we unpause, we add the time we spent paused to the accumulated pause time. Our instants stay instants and our durations stay durations.
{ "pile_set_name": "StackExchange" }
Q: Can't start android app on device I can start my android app in android simulator and it works fine for all resolutions and from android 2.1. But I want to test the app on real device, too. So I copied the apk file from the bin folder of my app to the sd card of my device and installed the app successfully. My device is a HTC HD2 with an android mod. The app starts but shows just a black screen. Any ideas what might be wrong? A: You can get the logcat information from the device, too. Just connect it and start adb logcat or select the device in eclipse. You can also install your app on the device using eclipse. Connect it and see if it shows up in the device view. If not, try to restart adb by using adb kill-server and adb start-server. Debugging works the same way. Unfortunately a blank screen doesn't provide enough information to help you. I guess you need to dig deep into the app, add some log.d calls to see until where it loads.
{ "pile_set_name": "StackExchange" }
Q: Use IP instead of localhost ASP.Net with SSL I'm trying to enable SSL on my ASP.Net project, and, it actually work fine with localhost, but when I try to replace localhost with my IP, I got the following error : After some research, I've edited the applicatihost.config bindings like this : <sites> <site name="SansSoussi" id="1"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="C:\Projects\SansSoussi\SansSoussi" /> </application> <bindings> <binding protocol="https" bindingInformation="*:44372:localhost" /> <binding protocol="https" bindingInformation="*:44372:*" /> </bindings> </site> <siteDefaults> <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" /> <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" /> </siteDefaults> <applicationDefaults applicationPool="Clr4IntegratedAppPool" /> <virtualDirectoryDefaults allowSubDirConfig="true" /> </sites> Still got the same error.. Thanks for your help :) A: On visual studio, go to your project properties -> Web and uncheck the box that says "override application root URL".
{ "pile_set_name": "StackExchange" }
Q: Why PyCryptodome RSA public key generation is so slow? I am using PyCryptodome libray for my cryptography tasks. I want to generate RSA key as shown in example. I have typed this code: from Cryptodome.PublicKey import RSA key = RSA.generate(2048) and it takes forever to execute. (While typing this question it has passed 10 minutes already and it is still not completed). I am running it in Jupyter Notebook on Windows 10. Do you maybe have any idea why is it so slow or how to make it work? I have read documentation and tried to find similar questions but without any success. A: I have reinstalled Anaconda to the latest version and this time I have installed pycryptodomex through pip(as shown on github), previously I installed it through Anaconda cloud (I think this doesn't matter, but let it stay here, just to be sure)
{ "pile_set_name": "StackExchange" }
Q: jordans lemma application Doing complex analysis, I encountered a problem that I do not know how to solve. I am to prove the Fresnel integrals from $x = 0$ to infinity, using a contour integral of $e^{i x^2}$. The hint said to use Jordan's lemma, but that pertains to a function $e^{ix}$ times a function $G(x)$, but as far as I can tell there is no way to pick $G$ so that the total ends up as $e^{i x^2}$. Does anyone know what to do? A: If you're using the "usual" contour to do these integrals you don't even need Jordan's lemma: $$\Gamma:=[0,R]\cup\gamma_R\cup\{z\in\Bbb C\,:\,z=te^{\pi i/4}\,,\,0\leq t\leq R\}\,,\,R\in\Bbb R^+ $$ with $\,\gamma_R:=\{z\in \Bbb C\,:\,z=Re^{i\theta}\,,\,0\leq \theta\leq \pi/4\}\,$ . Then, as $\,f(z):=e^{iz^2}\,$ analytic everywhere, we get $$0=\oint_\Gamma f(z)\,dz=\stackrel{I}{\int_0^R e^{ix^2}dx}+\stackrel{II}{\int_{\gamma_R}e^{iz^2}dz}-\stackrel{III}{\int_0^Re^{iz^2}dz}$$ (the minus sign before III is due to the fact that we "walk" the contour in the positive direction) , and we have: $$I\,\longrightarrow\,\int_0^Re^{ix^2}dx\xrightarrow[R\to\infty]{} \int_0^\infty\cos x^2\,dx+i\int_0^R\sin x^2\,dx$$ $$II\,\longrightarrow\,\left|\int_{\gamma_R}e^{iz^2}dz\right|\leq\max_{z\in\gamma_R}\left|e^{iz^2}\right|\cdot\frac{R\pi}{3}=\frac{R\pi}{3\,e^{R^2}}\xrightarrow [R\to\infty]{} 0$$ $$III\,\longrightarrow\,z=te^{\pi i/4}\Longrightarrow dz=e^{\pi i/4}dt\,,\,z^2=it^2\Longrightarrow \int_0^Re^{iz^2}dz=e^{\pi i/4}\int_0^Re^{i^2t^2e^{\pi i/2}}dt=$$ $$=e^{\pi i/4}\int_0^Re^{-t^2}dt\xrightarrow [R\to\infty]{}\frac{1}{\sqrt 2}(1+i)\sqrt{\frac{\pi}{2}}=\frac{\sqrt \pi}{2\sqrt 2}+i\frac{\sqrt \pi}{2\sqrt 2}$$ From the above, letting $\,R\to\infty\,$ and comparing real and imaginary parts, we finally get $$0=\int_0^\infty\cos x^2\,dx=\int_0^\infty \sin x^2\,dx=\frac{\sqrt \pi}{2\sqrt 2}$$
{ "pile_set_name": "StackExchange" }
Q: Strange results with execute() on SwingWorker task Java newbie here...caution! I've set this practice app up using this example as a base. Unfortunately I'm having a problem. If I just run the program, the SwingWorker task works for very small datasets but will just stall part way through larger ones. I know this app isn't the most efficient, but I can't work out why it just stalls (or even where). I've put the code up here. Thanks in advance. A: Create a stack trace or use a debugger if you believe the thread has stalled. Should give you an idea. Looking at your code: Make sure you change swing components only in the swing event thread, i.e. your done code should set the text field to the result of your computation.
{ "pile_set_name": "StackExchange" }
Q: Print from JAVA Web App - Applet or Java Web Start right now i'm developing an application for a company in Seam 2 for Point Of Sales, and my client wants to print the invoice directly from the application. Currently, i just generate the PDF of the invoice and the user chooses the printer and press the print button, but they want to do that faster, also they have 2 printer: An EPSON TM U220 for the tickets and a normal printer for the invoices. So, i want to investigate about printing directly from web page. I've heard about the most accurated alternatives: Java Web Start and Applets, but i don't know which is the best in order to achieve that. I read that with applets you have to deal with authentication stuff or permissions (well, maybe with JWS too but a little bit less) and that Applets are discontinued; and on the other side with Java Web Start, i can develop basically a simple application that prints something in the printer, but i don't know if that can be achieved with JWS. One of the things that i don't know if are possible with JWS is, if i can pass data from the web application (a bean because i'm using Seam 2) for example, pass the stream of the print or the stream of the PDF, to the JWS application, and pass the name of the printer, i mean, i just want to have in the JWS app/Applet the logic to print the invoice or ticket, i wanna generate the PDF or stream from my web app, so i don't know if that's possible. What alternative you consider is the best? JWS or Applets? About the printing library, i read about JAVA POS, but i can use any library, a paid library even if is necessary. Regards. A: What alternative you consider is the best? For 'least clicks' use a fully trusted applet or JWS app. signed with a digital certificate that has been issued by a CA (e.g. Verisign). The user will be prompted once to accept the code, and have the option to select the check-box that always remembers the decision to 'always trust'. Either the JWS app. or applet could then make use of the Java AWT printing API. As to the choice between embedded applet or free-floating JWS. Use whatever works best for the use-case, but note that applets require higher maintenance.
{ "pile_set_name": "StackExchange" }
Q: How should I explain volunteering for future layoffs in interviews? I got wind that my boss was going to need to reduce his headcount by 1 (technically three, but there were two open positions). I volunteered as all four of my co-workers just had kids in the past year so were recovering from reduced family incomes with maternity leave and whatnot. I was also there only three months. I have already lined up a bunch of interviews, but I haven't been officially fired so I am not sure that I can tell the interviewers why I am leaving (I heard our manager's manager say it after he thought we all left the standup video call and confronted my manager later) as I am technically not supposed to know. I am leaving after 3 months, so I suspect it will come up. Here are the steps I have taken. I overheard the layoff conversation I confirmed that the layoff thing was happening with my boss I basically told my boss to choose me, if I didn't find another job by the time the order came down. He offered me time to interview/prep/do whatever. Everything is good at the company. Manager's boss wouldn't be happy that I learned, but whatever. I just need to figure out how to explain all this during the interviews (which I already have) as I seem like I am casually hopping to a new position a few months later. How should I frame this? A: With the clarification in the comments that you've already confirmed the layoffs with your boss and offered to quit to save them the problem simply because it would impact you least of your coworkers, honestly, I can't think of a better "why I left" way to spin this whole thing because what you did it exactly right. You didn't jump the gun on the rumor - you went to confirm it, and then, taking everything into account, you've offered to resign in exchange for having a letter of recommendation and interview flexibility - while still working for the company and delivering the good work during the transition period. You really do not need to say anything else but the truth, it's really the story interviewers will want to hear as it shows integrity, sensibility and amazing amount of empathy - more so as you didn't know who will be fired and whether that will be you (unless you are in Germany or a country with similarly rigid firing order). A: Just tell the interviewers the truth, the company is having financial difficulties. There are rumors of impending layoffs. You don't need to say more than that. There is a pandemic going on. Everyone understands. A: First up - make sure you understand what an interviewer's interest will be. If I was interviewing someone for a role, my primary concerns would be the following: Do they have the right skills? What's their attitude to work like? How long will they stay? / Am I wasting my time here? Your willingness to sacrifice yourself "for the team" shows you're considerate to others (perhaps), a team player (perhaps), but on the flip-side, none of this is yet certain, so if we make you an offer, will you turn around and reject it in a month when the redundancy DOESN'T happen? Let's be clear - it's of little or no value to my business that you are prepared to be made redundant because your colleagues need the job more. If I believe you, it makes me like you, but liking someone, and deciding they're the right person for the job are not necessarily the same thing. Edit: A lot of people will tell you that quickly moving jobs is a bad thing - it's not - only if you do it repeatedly! Joining a business and deciding quickly it's not for you and moving on is common and can show decisiveness and ambition. So I would try to spin this so THEY HEAR what THEY want to hear - like this. Because of x (covid?) the role wasn't what I expected - the business is struggling... redundancies forthcoming.... My team is going to be diminished, the opportunities I'd hoped for aren't going to be there, so I decided that rather than waste time settling into a role that may not even be there in 6 months, I'd leave now and find somewhere more suitable. I've discussed it with my manager and he's happy. So here I am - I think YOUR business is going to suit me much better BECAUSE..... Edited after the OP was changed to indicate they'd only been there for 3 months.
{ "pile_set_name": "StackExchange" }
Q: Bytes Received always returning 0 I'm trying to use the C# PerformanceCounter class to return system metrics. // Initialisation // Threads (total threads for all processes) PerformanceCounter performThreads = new System.Diagnostics.PerformanceCounter(); ((ISupportInitialize)(performThreads)).BeginInit(); performThreads.CategoryName = "System"; performThreads.CounterName = "Threads"; ((ISupportInitialize)(performThreads)).EndInit(); // Bytes received (cumulative total bytes received over all open socket connections) private PerformanceCounter m_pcSys_BytesSent; PerformanceCounter performBytesR = new System.Diagnostics.PerformanceCounter(); ((ISupportInitialize)(performBytesR)).BeginInit(); performBytesR.CategoryName = ".NET CLR Networking"; performBytesR.CounterName = "Bytes Received"; performBytesR.InstanceName = "_global_"; ((ISupportInitialize)(performBytesR)).EndInit(); // Later on ... periodically poll performance counters long lThreads = performThreads.RawValue; // Works! long lBytesR = performBytesR.RawValue; // Always returns 0 :o( The last line above works in the sense that it does not throw an exception but always returns 0. I have tried both NextSample and NextValue with the same result. If I change InstanceName to the process name I again get the same result. If InstanceName is set to anything else the exception Instance 'XYZ' does not exist in the specified Category. is thrown when I call RawValue. Any ideas? A: According to Networking Performance Counters: Networking performance counters need to be enabled in the configuration file to be used. If networking counters are enabled, this will create and update both per-AppDomain and global performance counters. If disabled, the application will not provide any networking performance counter data.
{ "pile_set_name": "StackExchange" }
Q: moment.js diff showing wrong result I am working on a small script using momentjs, that shows me how many hours and minutes (seperate) I have until a specific hour. But for some reason the result is wrong. Thats my code so far: var TimeA = moment('08:00:00', 'HH:mm:ss'); var TimeB = moment('16:00:00', 'HH:mm:ss'); var DiffAB = moment(TimeA.diff(TimeB)).format('HH:mm:ss'); var DiffHours = moment(DiffAB, 'HH:mm:ss').format('H'); var DiffMinutes = moment(DiffAB, 'HH:mm:ss').format('mm'); console.log('TimeA: ' + moment(TimeA).format('HH:mm:ss')); console.log('TimeB: ' + moment(TimeB).format('HH:mm:ss')); console.log('Difference A-B: ' + DiffAB); console.log('Diff Hours: ' + DiffHours); console.log('Diff Minutes: ' + DiffMinutes); And thats the Output: TimeA: 08:00:00 TimeB: 16:00:00 Difference A-B: 17:00:00 Diff Hours: 17 Diff Minutes: 00 The difference of A - B should be 8 but its showing 17. A: As per momentjs documentation If the moment is earlier than the moment you are passing to moment.fn.diff, the return value will be negative. To translate it to your example: If TimeA is earlier than TimeB passed to moment.diff then the value will be negative and since it's returned as milliseconds -28800000 is an instruction like: take that amount of miliseconds from midnight, that gives you the different time so what you should be doing is var DiffAB = moment(TimeB.diff(TimeA)).utcOffset(0).format('HH:mm:ss'); Diff documentation https://momentjs.com/docs/#/displaying/difference/ Example from doc An easy way to think of this is by replacing .diff( with a minus operator. // a < b a.diff(b) // a - b < 0 b.diff(a) // b - a > 0
{ "pile_set_name": "StackExchange" }
Q: create header of xml file with php I want to create the header of a xml saved file http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">, but I get error message $uru = "urlset xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'"; $xml = new DOMDocument("1.0"); $xml->formatOutput=true; $urlset=$xml->createElement("$uru"); $xml->appendChild($urlset); end the error is this PHP Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in /blablabla/blabla/file.php:11 Stack trace: #0 /blablabla/blabla/file.php(11): DOMDocument->createElement('urlset xsi:sche...') #1 {main} thrown in /blablabla/blabla/file.php on line 11 Thx A: You should use $urlset->setAttribute to add attributes. $urlset->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'); Also you need an element to append it to. Here is an example on how your code should look like $xml = new DOMDocument("1.0"); $urlset = $xml->createElement('SetURL'); $urlset->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'); $xml->appendChild($urlset); A little sitenote: You should also set your xmlns and xmlns:xsi and not only the xsi:schemaLocation. In your case when working with sitemaps you should set theese attributes then. $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9'); This is for the XMLNS (here is the source) $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); And for the XMLNS:XSI(Same source)
{ "pile_set_name": "StackExchange" }
Q: Database Engine not appearing in SQL Server listing I don't know if I'm searching for the wrong queries in google but I can't seem to find an answer to this. I have SQL Server 2008 installed in my pc and according to services.msc, I've got 2 database engines running: SQLEXPRESS (probably one that came along with Visual Studio) and MSSQLSERVER. When I try to connect only SQLEXPRESS is visible in the Server Name drop down list. I tried to explicitly state MSSQLSERVER by typing in MYPCNAME\MSSQLSERVER Didn't work. The best solution I could find in the internet was to enable stuff at Configuration Manager. Didn't work either (although I did find that TCP/VIA and all other options were disabled for MSSQLSERVER). Anyone have any other ideas on what I should try next or probably something that I overlooked? A: By default SQL Express installs itself as a named instance (\SQLExpress) so you need to specify that when connecting to it. SQL Server doesn't do this (unless you tell it to during setup) so you connect to it with just the machine name.
{ "pile_set_name": "StackExchange" }
Q: Dozer: map single field to Set How do you map a single field into a Set in Dozer? I have a class like: class FooDTO { private IdDto bar; private IdDto baz; } class FooDomainObject { private List<Id> ids; } I'd like to map bar and baz into the ids list, but I can't get it to do this. A: I found this on the Dozer support list: http://sourceforge.net/projects/dozer/forums/forum/452530/topic/1557144 Basically, you use this syntax: <field> <a>bar</a> <b>ids[0]</b> <b-hint>org.foo.Id</b-hint> </field> <field> <a>baz</a> <b>ids[1]</b> <b-hint>org.foo.Id</b-hint> </field>
{ "pile_set_name": "StackExchange" }
Q: Is it better to have one class for a new item dialog and an edit item dialog or different classes? I'm making a program in which I have a list of items. You can add a new item or you can edit an existing one. The dialog window for editing an item and adding a new one is practically the same, one small detail that changes is that well, one edits and the other one adds the item, very little else is different. I was wondering if it's generally a better design choice to have two separate classes or to have only one class to which a parameter is passed that specifies whether the dialog is for editing or for adding. I'm using C++ with Qt but I think the same design choice would apply to any OOP language/framework. Thanks in advance. A: I usually use the same MVC classes for both CREATE and EDIT mode. The model holds a flag to indicate which mode. The View would read the flag in the Model to determine which controls to be displayed/enabled etc. The Controller would also read the flag on the Model to determine which service layer method to call when the user submits the form (e.g. update or create). I find that this is a more maintainable solution because it avoids duplication and it keeps the logic in one place. i.e. view logic in one view as opposed to two, controller logic in one controller as opposed to two....
{ "pile_set_name": "StackExchange" }
Q: In Lightning is there Inline-Editing like we know it from the Aloha-UI or VF pages? Our clients are using inline-edit quite heavily, it saves a lot of time and feels also way better than pressing "Edit" to get in the full edit mode all the time. Is there a similar functionality existing or planned also for Lightning? If not, I would advocate to provide a functionality like that again - at least for desktop usage. But also for mobile scenarios it would be very handy (of course the current Aloha hover-pencil-display and invocation method "double-click" is not good enough for mobile cases). To always have to switch a record between full view- and edit-mode even if you e. g. just want to fix a typo in one certain field is less comfortable. Also in SPAs it leads to updates of huge parts of the UI, possible scrolling position got lost in long tapestries and you might get a disruptive feeling. So I am sure: inline editing was great and would be great in the future. A: I asked this question yesterday on a Salesforce event and this seems to be the current status: There is no Inline-Editing support in current version of the Salesforce1 mobile app. It has been discussed but Salesforce decided against having this functionality for the mobile app at least for now. They plan also to provide a desktop app based on Lightning. For that it is yet not decided if it will provide Inline-Editing or not. Further updates and more information on the roadmap for Inline-Editing is appreciated.
{ "pile_set_name": "StackExchange" }
Q: Explicit contraction for the universal simplicial bundle WG For a simplicial group $G$, there is a universal bundle $WG \to \overline{W}G$ in the category of simplicial sets, detailed in for example May's book (djvu). Now $WG$ has a simple enough description in terms of $G$ that I would expect one could construct a contracting homotopy directly. Has this been done in the literature? The proof in May's book (and in the original sources) that $WG$ is contractible goes via showing that $WG$ is 'of type (W)', and that such simplicial sets are Kan, simply-connected and have trivial homology. A: Pages 75-81 of Appendix A of ``On the theory and applications of differential torsion products'', Memoirs AMS 142 (1974), by V.K.A.M. Gugenheim and myself, gives a detailed treatment of the $W$-construction for simplicial augmented algebras over a commutative ring $R$. Not the answer to your question, but if I remember rightly, it should lift to an answer when suitably specialized; more precisely, the chain homotopy of Lemma A.16 (up to signs coming from variant choices) should specialize to one coming from a contracting homotopy as desired. When $G$ is a group regarded as a constant simplicial group, Lemma A.15 lifts to give an isomorphism between $WG$ and the simplicial set $E_*G$ whose realization is $EG$.
{ "pile_set_name": "StackExchange" }
Q: Compare two timestamps in mysql, then return a custom field I'm building a small scale forum script in PHP, and I am having difficulty demonstrating the read/unread status of a given thread. So, I have a particularly gargantuan query which returns the thread information, including the date it was first posted in, the date it was last posted in (if any) as well as the date it was last looked at by the currently logged in user (if such a date exists. The query then returns three values: firstPostDate lastPostDate lastViewDate What I need to check is that if firstPostDate or lastPostDate are more recent than lastViewDate then to mark that thread as being new / having unread replies. I'm having problems executing this in PHP, due to the fact that my dates are all stored as timestamps in MySQL. At first I thought I could use UNIX_TIMESTAMP to return a Unix timestamp and then compare them, but I don't believe that I'm getting the correct results (because the timestamps are in Y-M-D H-M-S format (or similiar, I do not remember off the top of my head). I have other queries in the site that compare two dates, and that appears to work well. Is there a way I can compare the two or three dates in a mysql query, and return a "YES" if it's new, or "NO" if it is not? It would make my PHP markup much simpler. Or am I going about this the wrong way? A: You can use an expression as an additional field in your result set: SELECT ... (firstPostDate > lastViewDate OR lastPostDate > lastViewDate) AS unread FROM posts; The unread field should be 1 when the thread is new / having unread replies, and 0 otherwise. Test case: CREATE TABLE posts ( id int, firstPostDate timestamp, lastPostDate timestamp, lastViewDate timestamp ); INSERT INTO posts VALUES (1, '2010-01-01 12:00', '2010-01-02 12:00', '2010-01-03 12:00'); INSERT INTO posts VALUES (2, '2010-01-03 12:00', '2010-01-05 12:00', '2010-01-04 12:00'); INSERT INTO posts VALUES (3, '2010-01-06 12:00', '2010-01-06 12:00', '0000-00-00 00:00'); INSERT INTO posts VALUES (4, '2010-01-07 12:00', '2010-01-07 12:00', '2010-01-08 12:00'); Result: SELECT id, (firstPostDate > lastViewDate OR lastPostDate > lastViewDate) AS unread FROM posts; +------+--------+ | id | unread | +------+--------+ | 1 | 0 | | 2 | 1 | | 3 | 1 | | 4 | 0 | +------+--------+ 4 rows in set (0.01 sec)
{ "pile_set_name": "StackExchange" }
Q: CSS and creating border of svg figure I have file with star in SVG format. How to make border of that figure(not entire square with that star) using css? Also, how make fill that image on hover effect? I tried to add in html: <i class="favorite"></i> and in scss: .favorite { width: 17px; height: 16px; display: block; text-indent: -9999px; background-size: 17px 16px; background: url(../../../../../assets/images/icon-star. } But I dont see anything. When i change background-color to for example red I see white star on red square. How to make it work? A: You can't change the colours of an SVG that's included via <img> or background-image. You'll need to include it inline in your page. You can then change the colours using the fill and stroke properties. .square { fill: red; stroke: blue; stroke-width: 4; } <div> <p>Hello world</p> <svg> <rect class="square" x="5" y="5" width="100" height="100"/> </svg> </div>
{ "pile_set_name": "StackExchange" }
Q: C++ set stack pointer In my C++ / C project I want to set the stack pointer equal to the base pointer... Intuitively I would use something like this: asm volatile( "movl %%ebp %%esp" ); However, when I execute this, I get this error message: Error: bad register name `%%ebp %%esp' I use gcc / g++ version 4.9.1 compiler. I dont know whether I need to set specific g++ or gcc flag though... There should be a way to manipulate the esp and ebp registers but I just don't know the right way to do it. Doe anybody know how to manipulate these two registers in c++? Maybe I should do it with hexed OP codes? A: You're using GNU C Basic Asm syntax (no input/output/clobber constraints), so % is not special and therefore, it shouldn't be escaped. It's only in Extended Asm (with constraints) that % needs to be escaped to end up with a single % in front of hard-coded register names in the compiler's asm output (as required in AT&T syntax). You also have to separate the operands with a comma: asm volatile( "movl %ebp, %esp" ); asm statements with no output operands are implicitly volatile, but it doesn't hurt to write an explicit volatile. Note, however, that putting this statement inside a function will likely interfere with the way the compiler handles the stack frame.
{ "pile_set_name": "StackExchange" }
Q: Unable Response.Redirect(url); with many query arguments The '&' that separates query string arguments is getting encoded no mater what I do. // sitecore ASP.NET server side ascx code... string url = string.Format("http://other-domain.com/?a={0}&b={1}", "1", "2"); Response.Redirect(url); // ... gives my browser the address: http://other-domain.com/?a=1&amp;b=2 which is not what I want, I simply want: http://other-domain.com/?a=1&b=2 Is it Response.Redirect() that is HTMLencoding my '&'? And how do I get it to leave that separator alone? A: I am certain of one thing: this is not caused by Response.Redirect() or any of the other code that you posted. There is probably something else wrong in the actual code.
{ "pile_set_name": "StackExchange" }
Q: Business Japanese: what's the proper way to say "please visit [this URL]"? I'm writing a business e-mail to a Japanese speaking person, and I need to direct them to a certain URL. In English I would write "please visit http://www.example.com". I'm not sure the best way to say that in Japanese. My best guess is something like "http://www.example.comに訪ねてください", and if I was writing a friend I'd probably just try that figuring that they'd understand even if it wasn't quite right. But since this is formal business correspondence I want to make sure it's right. A: ...に訪ねる is ungrammatical. You have to use ...を訪ねる. In the first place, using the expression 'visit' is metaphoric. It may work in English, but it is a bit strange in Japanese to use 訪ねる. As cypher writes, ご覧ください 'please see' is more natural. A: On the off chance that the information on the referred page is related to the contents of your email, I'll add in ~をご参照【さんしょう】ください meaning "Please refer to..."
{ "pile_set_name": "StackExchange" }
Q: Open-loop gain of Op-amp - LT6015 I was recently reading a technical article from AllAboutCircuits by Robert Keim about Op-amp Stability, https://www.allaboutcircuits.com/technical-articles/negative-feedback-part-8-analyzing-transimpedance-amplifier-stability/ I am simulating the LTSpice circuit, as seen below, of the transimpedance amplifier using the LT6015 Op-Amp as depicted in the article. However when I run the simulation I am not able to get the same Open-loop frequency response as stated in the article. I obtain a max open-loop gain of ~145dB, whereas he has ~102dB. Furthermore I created some matlab code to check the open-loop gain using the approximation of the op-amp as a first-order low-pass filter. Taken from the datasheet of the LT6015 the open-loop gain is 3,000,000 and the open-loop bandwidth is therefore 1.1Hz (calculated from the gain bandwidth product, with a value of 3.2MHz). However this outputs a open-loop gain of ~129dB. Here is the code of my matlab program: Ao = 3000*10^3 %Open-loop gain Wb = 1.1 %Open-loop bandwidth of op-amp w = .1:.1:100000; h = 20*log10(Ao*(abs(1./(1+(j*w)/(Wb))))) figure semilogx(w,h) %% Plot on log scale hold on xlabel('\omega(rad/s)') ylabel('|H(j\omega)|dB') legend('1','2') I am unable to see what I am doing wrong to create the discrepancy between these three plots, with the primary focus being the former two, the last one acts as check. Perhaps the last one is incorrect because the LT6015 cannot be modelled as first-order low-pass filter? Any help would be greatly appreciated! A: ConfusedCheese, here is a simple method for simulating the loop gain for an operational amplifier with feedback. This simulation scheme provides DC feedback and a stable operational point (for double and symmetrical voltage supply only!). The dashed box contains the feedback factor, if any!. Without this box (direct connection to the inv. input) you simulate the open-loop gain Aol of the opamp only. The loop gain is simply T(s)=V(node2)/V(node1). Of course, the frequency must be swept over the desired range (ac analysis). simulate this circuit – Schematic created using CircuitLab
{ "pile_set_name": "StackExchange" }
Q: MusicPlayer issues in Android (Beginner) I have an issue with an app I'm creating. Basically, I am trying to have music playing in the background of my app, which I can do and it plays fine. However, when the user changes to another screen, the music restarts instead of just continuing as normal. Here is all the code I have currently: public class MainActivity extends Activity { MediaPlayer mp; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //setting the layout mp = MediaPlayer.create(this, R.raw.song); mp.setLooping(true); mp.getDuration(); mp.start(); I then have this method at the end of this class to stop the music when the app is closed: @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); mp.release(); finish(); } I am unsure of what to include in my other classes so the music continues playing. If anyone could show me I'd be very appreciative. Thank you. A: You have made your Mediaplayer instance dependent on the Activity. So when Activity gets restarted, onCreate() gets called again and the music restarts. If you want to continue playing music, take the mp out of any Activity instance and put it inside a Service. Then start the Service from your MainActivity and let it play the music unless you stop the Service. public class MainActivity extends ListActivity { /** Called when the activity is first created. */ Intent i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash); i=new Intent(this, MyMusicService.class); final ToggleButton togglebutton =(ToggleButton)findViewById(R.id.toggleButton1); togglebutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks if (togglebutton.isChecked()) { Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show(); startService(i); } else { stopService(i); Toast.makeText(MainActivity.this, "Not checked", Toast.LENGTH_SHORT).show(); } }}); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopService(i); } } The service is this : public class MyMusicService extends Service { MediaPlayer mp; @Override public int onStartCommand(Intent intent, int flags, int startId) { mp = MediaPlayer.create(this, R.raw.song); mp.start(); mp.setLooping(true); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(mp!=null) mp.release(); mp=null; } }
{ "pile_set_name": "StackExchange" }
Q: Cancel all tasks except from one in redux saga i'm reading some advanced concepts from redux saga documentation but i'm having a question here. In the documentation with use the following code to dispatch all action that are existing in our code: import { select, take } from 'redux-saga/effects' function* watchAndLog() { while (true) { const action = yield take('*') const state = yield select() console.log('action', action) console.log('state after', state) } } With the wildcard * we taking all the action in our application. Is there a way to take all action expect from one or two specific action? I want to dispatch all the action expect from "LOGIN" and "LOGOUT" actions? Any ideas? A: From the documentation on take: If it is a function, the action is matched if pattern(action) is true (e.g. take(action => action.entities) will match all actions having a (truthy) entitiesfield.) So you can do something like: function* watchAndLog() { while (true) { const action = take(action => ['LOGIN', 'LOGOUT'].indexOf(action.type) < 0); ... } }
{ "pile_set_name": "StackExchange" }
Q: windows store app 8.1 file system access Can windows store apps only access "library" files and not other locations on the hard drives of PCs? Like if I had a D drive that was full of video media that I wanted the app to have access to, is there no way to get to that? I've been searching for a while now and can't find anything but "knownfolder" examples and documentation. A: In order to access files outside of the libraries and other specific locations, you'd need to use the FileOpenPicker or FolderPicker. You can find more information on File Access and Permissions for Windows Store apps at http://msdn.microsoft.com/en-us/library/windows/apps/Hh967755.aspx.
{ "pile_set_name": "StackExchange" }
Q: Getting a 404 with htaccess I am hoping somebody can help me with this. I have a htaccess file in my public html folder for my website with the following: RewriteEngine on RewriteRule (.+)\.html$ /$1 [L,R=301] So when I visit my site to newsletter.html it redirects to domain.co.uk/newsletter instead of domain.co.uk/newsletter.html which is what I want.. but i also get a 404 saying the page cant be displayed. The webpage in question is named newletter.html in my file manager. Does anyone know why it cant be displayed? A: To hide .html extension use this code in root .htaccess: RewriteEngine on RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC] RewriteRule ^ /%1 [R=302,L,NE] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC] RewriteRule ^(.+?)/?$ /$1.html [L]
{ "pile_set_name": "StackExchange" }
Q: reposync exclude subdirs from mirror Is there a way to make the reposync command ignore a subdir of a public repo when mirroring it ? It seems to only want to sync on the url that has the /repodata/ & /repoview/ dirs, but i'm wanting to avoid that because the repo i'm trying to mirror has 17MB of stuff i want in one subdir under the dir that has repodata in it, and 9GB of stuff I don't in another dir. A: All appearances are that reposync won't do exactly what you are looking for. Assuming that you are wanting the latest version of a few packages from a specific repo, rather than reposync, you could use repoquery to find and download the package(s): grab the file for the machine and arch you are running on. wget repoquery --location flash-plugin grab a whole directory of packages: repoquery --location -a --repoid adobe-linux-x86_64 | xargs wget Not quite like reposync but may meet your needs. You don't get the whole repo, you only get the rpms themselves, but you could convert that into a local repo if that is what you need, or just serve up via http is that meets your needs.
{ "pile_set_name": "StackExchange" }
Q: Exporting a subset of a out-of-proc COM server by using an in-proc-server I implemented an out-of-proc COM server (implemented in a Service). I don't want other applications to access all the functionality in the COM server, so I developed an in-proc server (DLL) which would talk to the out-of-proc server. Because I don't want the interfaces in the out-of-proc COM server to be accessed directly, I don't embed the type library with the Service so I thought I could use #import and have access to the COM server through the TLB. However, when I try in my in-proc-server to create an instance of a class implemented in the service, I get an E_NOINTERFACE back. I guess this is due to marshalling, but I couldn't figure out how to overcome this. Any idea on how to communicate from the in-proc-server with my out-of-proc server without exposing the interface details of the out-of-proc server? A: I'm not sure about how this will help to conseal the interfaces, but there're three ways to make marshalling working and typelib is one of them. The other quite easy way is a proxy/stub - a bunch of code in a separate in-proc COM server that will automagically do the marshalling once it has been registered in Windows registry. Again, I'm not sure how this will help conseal the interface, but it looks more covert then a type library that just exposes teh interface to anyone with OLEView.
{ "pile_set_name": "StackExchange" }
Q: How to get random image from directory using PHP I have one directory called images/tips. Now in that directory I have many images which can change. I want the PHP script to read the directory, to find the images, and out of those images found to pick a random image. Any idea on how to do this? A: $imagesDir = 'images/tips/'; $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $randomImage = $images[array_rand($images)]; // See comments You can send a 2nd argument to array_rand() to get more than 1. A: $images = glob('images/tips/*'); return $images[rand(0, count($images) - 1)]; However, this doesn't ensure that the same image isn't picked twice consecutively.
{ "pile_set_name": "StackExchange" }
Q: Adding mouselistener to canvas with lwjgl display on it I'm using java and LWJGL. I created a mouse listener for a canvas, but when I set the Displays parent to the canvas it doesn't work. The mousehandlerClass: private static class handlerClass implements MouseListener { public handlerClass() { } @Override public void mouseClicked(MouseEvent e) { System.out.println("Canvas clicked"); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } Here is where I set the canvas as parent in my DisplayManager class: public void createDisplayJFrame(Canvas canvas) { ContextAttribs attribs = new ContextAttribs(3, 2).withForwardCompatible(true).withProfileCore(true); try { Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT)); Display.setParent(canvas); Display.create(new PixelFormat(), attribs); } catch (LWJGLException ex) { //System.out.println(ex); } GL11.glViewport(0, 0, WIDTH, HEIGHT); lastFrameTime = getCurrentTime(); } Here is where I add the MouseListener: public class UIMain extends javax.swing.JFrame { /** * Creates new form UIMain */ private static Canvas canvas; public static DisplayThread dt; HandlerClass handler = new HandlerClass(); public UIMain() { initComponents(); canvas = new Canvas(); canvas.addMouseListener(handler); canvas.setSize(500, 500); canvas.setBackground(Color.WHITE); canvas.isDisplayable(); canvas.setVisible(true); jPanel2.add(canvas, BorderLayout.CENTER); } My DisplayThreadClass: public class DisplayThread extends Thread { private Canvas canvas; ArrayList<Entity> entities = new ArrayList(); public DisplayThread(Canvas canvas) { this.canvas = canvas; } public void run() { new DisplayManager().createDisplayJFrame(canvas); //Created entities and added to entities ...... MasterRenderer renderer = new MasterRenderer(); while (!Display.isCloseRequested()) { DisplayManager.updateDisplay(); //Here is the solution if(org.lwjgl.input.Mouse.isButtonDown(org.lwjgl.input.Mouse.getEventButton())){ System.out.println("Mouse was clicked"); } } renderer.cleanUp(); DisplayManager.closeDisplay(); } When the canvas is not set as the parent (Nothing on the canvas) then the mouseListener works. But when the displays parent is set to the canvas. It does nothing. How can I determine when the mouse is clicked on the canvas when the canvas is set as parent? A: Although the actual issue may be resolved: This is probably related to some "magic" that is done in LWJGL, and may be related to LWJGL Display mounted on Canvas fails to generate Mouse Events - so if you used a Frame instead of a JFrame, it should already work. However, if you want to use swing, and add a real MouseListener to the canvas, you can consider using an LWJGL AWTGLCanvas: import static org.lwjgl.opengl.GL11.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.AWTGLCanvas; import org.lwjgl.util.glu.GLU; public class LwjglCanvasMouseEvents { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); LwjglCanvas canvas = null; try { canvas = new LwjglCanvas(); } catch (LWJGLException e) { e.printStackTrace(); } canvas.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.out.println(e); } }); f.getContentPane().add(canvas); f.setSize(400, 400); f.setLocationRelativeTo(null); f.setVisible(true); } } class LwjglCanvas extends AWTGLCanvas { private int currentWidth; private int currentHeight; public LwjglCanvas() throws LWJGLException { super(); } @Override public void paintGL() { if (getWidth() != currentWidth || getHeight() != currentHeight) { currentWidth = getWidth(); currentHeight = getHeight(); glViewport(0, 0, currentWidth, currentHeight); } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLU.gluOrtho2D(0.0f, currentWidth, 0.0f, currentHeight); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0, 0, 0); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(200, 0, 0); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(100, 200, 0); glEnd(); glPopMatrix(); try { swapBuffers(); } catch (LWJGLException e) { e.printStackTrace(); } repaint(); } }
{ "pile_set_name": "StackExchange" }
Q: Getting starting with Android - which direction to go? I'm a Java developer at heart. Just got Android based phone and curious if I can write some app for it. I know its late in the game, but why not. I guess a question to all those who write for Android. What is the approach? After some quick googling I found out that applications can be written in: - Java using android SDK - Flex from adobe offers - JavaFX seems they do that too - Or other commercial tools that promise my app will run on any mobile device There seems to be a cesspool out there with all the marketing and quick money making schemes attached to mobile development. In the end, whats the best way to start for seasoned Java developer? Thanks. A: Personally I use Eclipse IDE with the Android SDK. If you're used to Java - then stay with it. A good starting point is to read about the Activity Lifecycle as it is a very big part of how your app will function. The second approach is to hit the Tutorials. I'm a hands-on person so learning by doing is prefered.
{ "pile_set_name": "StackExchange" }
Q: How to parse JSON from URL and download CSV files? I'm given a URL which contains some JSON text. In the text there are URL's for csv files. I'm trying to parse the JSON from the URL and download the CSV files. I am able to print out the JSON from the URL but do not know how to grab the CSV files from within. import urllib, json import urllib.request with urllib.request.urlopen("http://staging.test.com/api/reports/68.json?auth_token=test") as url: s = url.read() print(s) The above will print the JSON from the URL ( see below printout), there are URL's for csv files that I then need to download using python. {"id":68,"name":"Carrier Rates","state":"complete","user_id":166,"data_set_id":7,"bounding_date":{"id":101,"start_date":"2019-01-01T00:00:00.000-05:00","end_date":"2999-12-31T00:00:00.000-05:00","bounding_field_id":322,"related_id":68,"related_type":"Reports::Report"},"results":[{"id":68,"created_at":"2019-07-26T15:29:40.872-04:00","version_name":"07/26/2019 03:29PM","content":"https://test-staging.s3.amazonaws.com/reports/manufacturer/carrier-test.1dec2e6d-0c36-44b7-ab26-fd43fe710daf.csv"},{"id":67,"created_at":"2019-07-26T15:29:07.112-04:00","version_name":"07/26/2019 03:29PM","content":"https://test-staging.s3.amazonaws.com/reports/manufacturer/carrier-test.3b02195e-c0a2-4abe-88f7-27d20ac76e07.csv"},{"id":35,"created_at":"2019-06-26T11:01:26.900-04:00","version_name":"06/26/2019 11:01AM","content":"https://test-staging.s3.amazonaws.com/reports/manufacturer/carrier-test.a488c58d-5e04-4c28-a429-7167e9e8edaa.csv"},{"id":34,"created_at":"2019-06-26T10:57:51.396-04:00","version_name":"06/26/2019 10:57AM","content":"https://cloudtestlogistics-staging.s3.amazonaws.com/reports/manufacturer/carrier-test.bf73db19-5604-4a1d-bc31-da6cf25742cc.csv"}]} A: The following code can help you. import json import urllib.request with urllib.request.urlopen("http://staging.test.com/api/reports/68.json?auth_token=test") as url: s = url.read() loadJson = json.load(s) results = loadJson["results"] csvLinks = [] for object in results: csvlinks.append(object["content"]) Now you have a list of links to CSV files. Download them using urllib.
{ "pile_set_name": "StackExchange" }
Q: Why would content served by Traefik be truncated? I have a Traefik reverse proxy in front of several docker containers in my dev environment. I noticed recently that large files are being cut off when served over port 80 (Traefik). However, if I download the file using the local HTTP port on the Docker container, the file is fine. This seems to only affect files that exceed a certain size. I generated a large file on one of my Docker containers like so. for ((i=1;i<=200000;i++)); do echo "$i some new line that has a reasonably long length and content" >> public/large-file.txt; done If I curl the file and bypass Traefik (port 4200 on this container), the file is intact and the same exact size every time. If I curl the file over port 80 via Traefik, the file is cut off at a seemingly random point. $ curl -O http://localhost/large-file.txt; cat large-file.txt ... 114633 some new line that has a reasonably long length and content 114634 some new line that has a reasonably long length and content 114635 some new line that has a rea $ curl -O http://localhost/large-file.txt; cat large-file.txt ... 199732 some new line that has a reasonably long length and content 199733 some new line that has a reasonably long length and content 199734 some new line that has a re Based on this behavior, it seems to me that this is not a Docker issue, and not an issue with my web-server. Rather, it seems like Traefik is at fault. Is this a bug in Traefik, or a potential misconfiguration? A: The official image is https://hub.docker.com/r/_/traefik The https://hub.docker.com/r/containous/traefik is made by the traefik team but contains experimental tags etc... About your problem, it may be linked to an issue in 1.5.0-rc as you can see on this issue (https://github.com/containous/traefik/issues/2637), but this will be fixed in the next 1.5 release
{ "pile_set_name": "StackExchange" }
Q: how to make multiuser? firstly I get this coding from http://www.webestools.com/scripts_tutorials-code-source-15-personal-message-system-in-php-mysql-pm-system-private-message-discussion.html before this I create user page and admin page using same coding. I edit same coding to see different user and admin page. I run at same browser at same time.. It run properly. But for this coding I make user and admin using same coding, same browser and run same time. I log in for admin first then log in for user. after I log in for user, I refresh admin page. session that I use in admin change to become like user page. connexion.php <?php include('config.php'); ?> <div class="header"> <a href="<?php echo $url_home; ?>"><img src="<?php echo $design; ?>/images/logo.png" alt="Members Area" /></a> </div> <?php //If the user is logged, we log him out if(isset($_SESSION['username'])) { //We log him out by deleting the username and userid sessions unset($_SESSION['username'], $_SESSION['userid']); ?> <div class="message">You have successfuly been loged out.<br /> <a href="<?php echo $url_home; ?>">Home</a></div> <?php } else { $ousername = ''; //We check if the form has been sent if(isset($_POST['username'], $_POST['password'])) { //We remove slashes depending on the configuration if(get_magic_quotes_gpc()) { $ousername = stripslashes($_POST['username']); $username = mysql_real_escape_string(stripslashes($_POST['username'])); $password = stripslashes($_POST['password']); } else { $username = mysql_real_escape_string($_POST['username']); $password = $_POST['password']; } //We get the password of the user $req = mysql_query('select password,id from users where username="'.$username.'"'); $dn = mysql_fetch_array($req); //We compare the submited password and the real one, and we check if the user exists if($dn['password']==$password and mysql_num_rows($req)>0) { //If the password is good, we dont show the form $form = false; //We save the user name in the session username and the user Id in the session userid $_SESSION['username'] = $_POST['username']; $_SESSION['userid'] = $dn['id']; ?> <div class="message">You have successfuly been logged. You can access to your member area.<br /> <a href="<?php echo $url_home; ?>">Home</a></div> <?php } else { //Otherwise, we say the password is incorrect. $form = true; $message = 'The username or password is incorrect.'; } } else { $form = true; } if($form) { //We display a message if necessary if(isset($message)) { echo '<div class="message">'.$message.'</div>'; } //We display the form ?> <div class="content"> <form action="connexion.php" method="post"> Please type your IDs to log in:<br /> <div class="center"> <label for="username">Username</label><input type="text" name="username" id="username"value="<? php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br /> <label for="password">Password</label><input type="password" name="password" id="password" />br /> <input type="submit" value="Log in" /> </div> </form> </div> <?php } } ?> index.php <?php include('config.php') ?> <?php //We display a welcome message, if the user is logged, we display it username ?> Hello<?php if(isset($_SESSION['username'])){echo ' '.htmlentities($_SESSION['username'],ENT_QUOTES, 'UTF-8');} ?>,<br /> Welcome on our website.<br /> You can <a href="users.php">see the list of users</a>.<br /><br /> <?php //If the user is logged, we display links to edit his infos, to see his pms and to log out if(isset($_SESSION['username'])) { //We count the number of new messages the user has $nb_new_pm = mysql_fetch_array(mysql_query('select count(*) as nb_new_pm from pm where ((user1="'.$_SESSION['userid'].'" and user1read="no") or (user2="'.$_SESSION['userid'].'" and user2read="no")) and id2="1"')); //The number of new messages is in the variable $nb_new_pm $nb_new_pm = $nb_new_pm['nb_new_pm']; //We display the links ?> <a href="edit_infos.php">Edit my personnal informations</a><br /> <a href="list_pm.php">My personnal messages(<?php echo $nb_new_pm; ?> unread)</a><br /> <a href="connexion.php">Logout</a> <?php } else { //Otherwise, we display a link to log in and to Sign up ?> <a href="sign_up.php">Sign up</a><br /> <a href="connexion.php">Log in</a> <?php } ?> A: You have to Add to your session some new indexes for admin, it will be like the following if a normal user logs in after checking if he's admin or not you store the normal user session indexes like these that you're using.. $_SESSION['username'] etc.. and if it's an admin logging in you store something like for example $_SESSION['isAdmin']; $_SESSION['adminName']; etc.. and then you check for the Admin session in the admin panel.. and Then depending on the Session variables you decide what to show and what to not show, ask for login if there's no 'isAdmin' set..
{ "pile_set_name": "StackExchange" }
Q: Using tanh as a way to keep values between -1.0 and 1.0? I am working my way through a homework involving implementing a few heuristics for a game called Lines of Action. The teacher has given us some structural code that that we can use to test our heuristic and search implementations. An interface is provided for heuristics and notes that the return value should be between $-1.0$ and $1.0$. There is then a note that "an easy way to scale is to perform a $tanh$". From what I can tell the values of $tanh$ are $1.0$ given $inf$ and $-1.0$ given $-inf$. But my question is... I have multiple features that make up my heuristic value that all have a different scale. Say one feature might output a value from 0-10 and another 0-100. Initially I was adding them and then returning the overall heuristic value as $tanh$ of the sum. But now I have realized this obviously gives features more weight than others. So I thought if I $tanh$ the features value before addition along with after addition I can keep them at the same weight and output a value from $-1.0$ to $1.0$. Is there a considerable weighting difference between features with different scales if I combine them in the manner above? I know this depends on the actual value of $tanh$ and the scales of my features. Is there some scale values that will keep a more even weighting? A: It is true that $\tanh$ takes $(-\infty, \infty)$ to $(-1,1)$ but that may not be the most important point for the question you are asking. If you have one feature that ranges over $0-10$ and another that ranges over $0-100$ the second will control the sum unless the common values are tightly clustered. If both features go over the whole range you could just divide the second by $10$ before adding. You might find this reasonable. Maybe one feature should be more important than the other, so its range should be wider. Maybe the one that ranges from $0$ to $100$ is almost always $55\pm 1$ with values outside that range very rare. Then the sum of the two will be dominated by the $0-10$ one except for the cases where the $0-100$ one is an outlier. The sum is mostly controlled by the variable with the highest variance. All this is a way to show that math can help with figuring out what your rule set will deliver, but not do so much for figuring out what you want the rule set to deliver.
{ "pile_set_name": "StackExchange" }
Q: upgrading libc6 2.19 to 2.21 on debian I want to install connect to an sql server using my debian server so I need to install msodbcsql for that to work, problem is its says msodbcsql : Depends: libc6 (>= 2.21) but 2.19-18+deb8u7 is to be installed apparently I need to upgrade libc6 to 2.21 or above but I don't know how. A: I solved that by using Ubuntu instead of Debian. Good version directly installed on Ubuntu 14.04.1 LTS 64-bit.
{ "pile_set_name": "StackExchange" }
Q: Show new portion of an image based on scrolling First time poster. I should start off by saying that I'm a graphic designer in the process of designing a website that I will have to code. I have minimal javascript/jquery experience. I'm having troubles trying to figure out how a new part of an image is revealed based on the location on a web page. I'm designing a scuba diving site and I'm trying to replicate the depth locator used in the website below, on the left hand side. Instead of having just a number I'll have information pertaining to certification levels at each depth. Any suggestions on how to go about doing this with either text or an image that will change based on the location on the web page. http://lostworldsfairs.com/atlantis/ Thanks! A: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script> <script> var depths = [1500,4000,7000]; var words = ['shallow','medium','deep','darkness']; $(document).ready(function() { $(window).scroll(function() { var depth = Math.floor($(window).scrollTop()); for(i in depths){ if(depth<depths[i]){ $("#depth-o-meter").html(words[i]); break; } } }); }); </script> <div style = 'position:fixed' ><span id = 'depth-o-meter' >aaa </span></div> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> this is the script with some testing data and html for testing :) it works
{ "pile_set_name": "StackExchange" }
Q: Using git bundle create to backup repos to a specific directory? I am working on backing some git repos as part of a new back up plan. It seems git bundle is the way to go, but I am wondering, and in my, in all honesty, short google searches, I cannot seem to find out if I can do a bundle directly into a specific directory. For my SVN I mounted a cifs share, and pointed the dump directly to that share without having to script a basic thing to create and then move. Let me know, thank you. A: Back-uping a git repository is as simple as either: git clone --bare it to a new place. It allows to git push/pull for incremental backup. tar -czf backup.tar.gz myrepo/.git/ file and copy it somewhere. So you can manage it in a simple file, easily. It's easy.
{ "pile_set_name": "StackExchange" }
Q: User defined function not working with Pandas I was learning Python Pandas, so wrote a little code to experiment with user defined functions used with agg, as follows. import pandas as pd def combine_cities(series): return reduce(lambda x, y: x + ', ' + y, series) data = pd.DataFrame({'Country': ['Russia','USA','China','USA','China'], 'City':['Moscow','Boston','Wuhan','New York','Beijing']}) a = data.groupby('Country').agg(combine_cities) print(a) However, I get the following error. Any idea what I am doing wrong here? NameError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\core\groupby\ops.py in agg_series(self, obj, func) 662 try: --> 663 return self._aggregate_series_fast(obj, func) 664 except Exception: ~\Anaconda3\lib\site-packages\pandas\core\groupby\ops.py in _aggregate_series_fast(self, obj, func) 680 grouper = reduction.SeriesGrouper(obj, func, group_index, ngroups, dummy) --> 681 result, counts = grouper.get_result() 682 return result, counts pandas\_libs\reduction.pyx in pandas._libs.reduction.SeriesGrouper.get_result() pandas\_libs\reduction.pyx in pandas._libs.reduction.SeriesGrouper.get_result() .... A: The reason why the error was occuring was that Python3 has removed the reduce function. Therefore, I had to add the following to make it work. from functools import reduce
{ "pile_set_name": "StackExchange" }
Q: exec from php is causing an "Premature end of script headers: php-cgi.exe" error I have a php script written which calls an external command using exec which compiles a spacial database query result into a shape file. In tables with lots of records (say 15,000), this command can take as long as 7 minutes to execute. The script works fine on scripts which do not take too long (maybe <2min) but on longer scripts (like the 7 minute one) the page will display "500 internal server error". Upon reviewing the Apache server log, the error states: "Premature end of script headers: php-cgi.exe". I have already adjusted the php maximum execution time to allow more than enough time, so I know it is not this. Is there an Apache maximum that's being hit, or something else? A: Premature end of script headers means that webserver's timeout for CGI scripts was exceeded by your script. This is a webserver timeout and it has nothing to do with php.ini configuration. You need to look at your CGI handler configuration to increase time allowed for CGI scripts to run. E.g. if you are using mod_fastcgi you may want to specify the following option in your Apache config: FastCgiServer -idle-timeout 600 which will give you timeout of 10 minutes. By default fastcgi provides 30 seconds. You could find some other fastcgi options here http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
{ "pile_set_name": "StackExchange" }
Q: How can I see the exact value for inputs and outputs for a convolutional layer in MobileNet I am trying to visualize the inputs and outputs for a convolutional layer in MobileNet. Is there any function or tools in TensorFlow that allow us to see the exact value for inputs, outputs for each layer? So let's say if I have an image, I am doing object detection. The model run through a bunch of layers, how do I see the data flow? A: I would take a look at the TensorFlow debugger, tfdbg. You can inspect intermediate activations, including gradients. Enabling eager execution is another option, where TensorFlow will behave more like numpy than a domain-specific language. You can print intermediate activations using regular print statements, or use Python's pdb. A third option is to add tf.Print nodes to the graph. Similarly you could add summaries and send them to TensorBoard.
{ "pile_set_name": "StackExchange" }
Q: Server side closed as soon as the client side is opened Till now, my server-client application was working perfectly. Then suddenly when I decided to run it(first the server then the client), the server window closed after a second of opening the client window. Now, only the client window was left open. However, the javaw.exe processes (there are 2 of them, server and client) are not stopped. They are hooked to the port number I used in the game. Therefore, I get the JVM_Bind exception when run again. I terminated both process and ran the application(s) again, but the same problem arises. I even changed the port numbers (on both the projects of course) but it gave me the same result. The server and the client keep sending and receiving things automatically like in any multiplayer game. Client side : private void tick() { String info = handler.getPlayer(0).getX() + " " + handler.getPlayer(0).getY() + " " + handler.hb2.width + " " + handler.getPlayer(0).h1.x + " " + handler.getPlayer(0).h1.y + " " + handler.getPlayer(0).h2.x + " " + handler.getPlayer(0).h2.y + handler.getPlayer(0).h1.punch + " " + handler.getPlayer(0).h2.punch; sendMessage(info); String infoR = ""; try { infoR = br.readLine(); } catch (IOException e) { e.printStackTrace(); } Scanner s = new Scanner(infoR); int a = 0; while(s.hasNext()) { String poop = s.next(); a++; try { switch(a) { case 1: handler.getPlayer(1).x = Integer.parseInt(poop); break; case 2: handler.getPlayer(1).y = Integer.parseInt(poop); break; case 3: handler.hb1.width = Integer.parseInt(poop); break; case 4: handler.getPlayer(1).h1.x = Integer.parseInt(poop); break; case 5: handler.getPlayer(1).h1.y = Integer.parseInt(poop); break; case 6: handler.getPlayer(1).h2.x = Integer.parseInt(poop); break; case 7: handler.getPlayer(1).h2.y = Integer.parseInt(poop); break; case 8: handler.getPlayer(1).h1.punch = Boolean.getBoolean(poop); break; case 9: handler.getPlayer(1).h2.punch = Boolean.getBoolean(poop); break; } } catch(NumberFormatException e) { frame.setVisible(false); poop += " " + s.next(); if(poop.equals("you lose")) new ResultDisplay("red"); handler.hb1.resultDisplayed = true; stop(); } } handler.tick(); } public void sendMessage(String message) { pw.println(message); pw.flush(); } private void init() { try { sock = new Socket("127.0.127.1", 1111); ostream = sock.getOutputStream(); pw = new PrintWriter(ostream); istream = sock.getInputStream();; br = new BufferedReader(new InputStreamReader(istream)); } catch (IOException e) { e.printStackTrace(); } // more game initialization code follows init() is called first and then the tick()method is called 60 times a second(ideally). Server side: private void tick() { String info = handler.getPlayer(1).getX() + " " + handler.getPlayer(1).getY() + " " + handler.hb1.width + " " + handler.getPlayer(1).h1.x + " " + handler.getPlayer(1).h1.y + " " + handler.getPlayer(1).h2.x + " " + handler.getPlayer(1).h2.y + " " + handler.getPlayer(1).h1.punch + " " + handler.getPlayer(1).h2.punch; String infoR = ""; try { infoR = br.readLine(); } catch (IOException e) { e.printStackTrace(); } Scanner s = new Scanner(infoR); int a = 0; while(s.hasNext()) { a++; String poop = s.next(); try { switch(a) { case 1: handler.getPlayer(0).x = Integer.parseInt(poop); break; case 2: handler.getPlayer(0).y = Integer.parseInt(poop); break; case 3: handler.hb2.width = Integer.parseInt(poop); break; case 4: handler.getPlayer(0).h1.x = Integer.parseInt(poop); break; case 5: handler.getPlayer(0).h1.y = Integer.parseInt(poop); break; case 6: handler.getPlayer(0).h2.x = Integer.parseInt(poop); break; case 7: handler.getPlayer(0).h2.y = Integer.parseInt(poop); break; case 8: handler.getPlayer(0).h1.punch = Boolean.getBoolean(poop); break; case 9: handler.getPlayer(0).h2.punch = Boolean.getBoolean(poop); break; } }catch(NumberFormatException e) { frame.setVisible(false); poop += " " + s.next(); if(poop.equals("you lose")) new ResultDisplay("green"); handler.hb2.resultDisplayed = true; stop(); } } sendMessage(info); handler.tick(); } public void sendMessage(String message) { pw.println(message); pw.flush(); } private void init() { try { sersock = new ServerSocket(1111); sock = sersock.accept(); br = new BufferedReader(new InputStreamReader(sock.getInputStream())); pw = new PrintWriter(sock.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } // more game initialization code follows The main game thread calls both the init() and tick() are called by the main game threads in both the projects A: In your try and catch around the switch on your server you handle the exception by actually setting the visibility of your frame to false and you don't print out the exception, thus explains why you don't get an exception. }catch(NumberFormatException e) { frame.setVisible(false); //<-- This bit poop += " " + s.next(); if(poop.equals("you lose")) new ResultDisplay("green"); handler.hb2.resultDisplayed = true; stop(); } Of course you catch it for a reason, but maybe you should print out the exception it throws and not hide the frame? It could be throwing something you don't want it to throw.
{ "pile_set_name": "StackExchange" }
Q: How to hide div when click on anywhere on the display Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide $(document).ready(function () { $('#PopupDiv').hide(); $('#Btn1').click(function () { alert() $('#PopupDiv').show(); }) $(document).click(function () { alert('o') if ($('#PopupDiv').is(':visible')) { alert('vis'); } }) }) <div> <input type="button" id="Btn1" value="BtnClick" /> </div> <div id="PopupDiv"> <p>Hello Popup Grid</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> A: Hope this helps: $(document).ready(function () { $('#PopupDiv').hide(); $('#Btn1').click(function () { alert(); $('#PopupDiv').show(); }) $(document).click(function (e) { alert('o') if (e.target.id != "Btn1") { $('#PopupDiv').hide(); } }) }) <div> <input type="button" id="Btn1" value="BtnClick" /> </div> <div id="PopupDiv"> <p>Hello Popup Grid</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: Wildfly swarm in docker - exception in starting http server I'm running in Docker a jar file (host computer macosx), and during boot I get this stacktrace: 10:42:28,101 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-2) MSC000001: Failed to start service jboss.undertow.listener.default: org.jboss.msc.service.StartException in service jboss.undertow.listener.default: Could not start http listener rating_1 | 10:42:28,401 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([ rating_1 | ("subsystem" => "undertow"), rating_1 | ("server" => "default-server"), rating_1 | ("http-listener" => "default") rating_1 | ]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.undertow.listener.default" => "org.jboss.msc.service.StartException in service jboss.undertow.listener.default: Could not start http listener rating_1 | Caused by: java.net.SocketException: Protocol family unavailable"}} rating_1 | 10:42:28,405 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("add") failed - address: ([("subsystem" => "ejb3")]) - failure description: {"WFLYCTL0288: One or more ser vices were unable to start due to one or more indirect dependencies not being available." => { "Services that were unable to start:" => [ "jboss.ejb.default-local-ejb-receiver-service", "jboss.ejb3.ejbClientContext.default", "jboss.ejb3.localEjbReceiver.value" ], "Services that may be the cause:" => ["jboss.remoting.remotingConnectorInfoService.http-remoting-connector"] }} It seems, that it cant start the http server, that some service arent installed? Am I using the correct docker image? Dockerfile: FROM java:8 RUN mkdir -p /var/rating ADD *.jar /var/rating #ADD tomcat-users.xml /usr/local/tomcat/conf/ EXPOSE 8095 EXPOSE 8096 CMD ["java", "-jar", "/var/rating/ratingFacade-swarm.jar", "-server", "-d 64"] I'm probably doing something wrong but I don't know what! Is it maybe an interface or a socket issue? Edit: These are the environment variables that I'm passing it in docker-compose.yml: JAVA_TOOL_OPTIONS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8096,server=y,suspend=n -Dfile.encoding=UTF-8 -Xms128M -Xmx384M -XX:TargetSurvivorRatio=90 -XX:MaxTenuringThreshold=8 -XX:+CMSParallelRemarkEnabled -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+ScavengeBeforeFullGC -XX:+UseBiasedLocking -Dswarm.project.stage=stage -Dswarm.http.port=8095" A: The java.net.SocketException: Protocol family unavailable part seems most important. I'd try adding the usual -Djava.net.preferIPv4Stack=true to see if that helps.
{ "pile_set_name": "StackExchange" }
Q: User management system similar to wordpress one? I am in very big need of a user management system just like the one that wordpress uses but without being blog related. I need to be able to manage users and apply certain privileges depending on user level. I tried to take apart the WP engine and take out the users part but I think it's so tied to the whole engine, I wasn't able to... Does anyone know of any scripts that offer the same register, login etc functions? Also, could it be open source? I already bought my first user management system but it sucks really bad... :( Thanks in advance to anyone willing to help me. Andy A: you can still use WordPress and disable the front end functionality, or like @OneTrickPony suggested you can try BackPress which is a PHP library of core functionality for web applications that grew out of WordPress.
{ "pile_set_name": "StackExchange" }
Q: Making a string that contains an escaped quote I need to make a string that will output exactly "\"" to the terminal if fed into std::cout I am having trouble wrapping my head around how to do this (c++) A: Simply precede each character that needs to be escaped (in your case, all four of them) with a backslash. For instance, this worked for me: std::cout << "Testing: \"\\\"\"" << std::endl; Output: Testing: "\"" Apparently (I just learned this), C++11 provides other (perhaps better) tools for using string literals. The above method of preceding individual characters with a backslash describes the more old-fashioned way of doing things.
{ "pile_set_name": "StackExchange" }
Q: Stop praat from removing zeros I am relatively new to praat, and I have written a praat script that segments a larger file into smaller files based on a procedure: @instance: "sbc001", 756.00, 758.70 procedure instance: .sound$, .start, .end However, praat is removing final zeros. For example, if my start time is 756.00 and my end time is 758.70 it will name the file sbc001_756_758_7 instead of naming it sbc001_756_00_758_70. Is there some way to force praat to include these zeros? I might be able to modify my perl code to return 758 and 70 so that I could put them together as a decimal in praat, but I'm not sure how to do that while getting praat to read it as a number. A: I’m not currently working with Praat, but I assume you’re calling something like string$() for the filename at some point. (Or, it’s being called implicitly to coerce your numerics into strings.) Can you use this function instead? fixed$ (number, precision) From Praat Manual: "formats a number as a string with precision digits after the decimal point. Thus, fixed$ (72.65687, 3) becomes the string 72.657, and fixed$ (72.65001, 3) becomes the string 72.650. In these examples, we see that the result can be rounded up and that trailing zeroes are kept. At least one digit of precision is always given, e.g. fixed$ (0.0000157, 3) becomes the string 0.00002. The number 0 always becomes the string 0."
{ "pile_set_name": "StackExchange" }
Q: Change EditText inputType after enter first character by user I have an EditText like this in my xml file: <EditText android:id="@+id/InputPass" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_marginBottom="20dp" android:layout_marginLeft="40dp" android:layout_marginRight="40dp" android:drawableLeft="@drawable/ic_lock" android:gravity="right" android:hint="رمز عبور" android:singleLine="true" android:textSize="18sp" /> For some reason I want to change its inputType after user entered first Character. I try this way: Pass.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int count, int after) { } @Override public void beforeTextChanged(CharSequence s, int start, int before, int count) { if(start == 0){ Pass.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } } @Override public void afterTextChanged(Editable s) { } }); But it does not work! Is anybody there that know any solution for that? A: I achieved to the best result by this one: Pass.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ Pass.setTransformationMethod(PasswordTransformationMethod.getInstance()); } } });
{ "pile_set_name": "StackExchange" }
Q: How does single coax wire transmit a lot of information? I have a coax cable entering my house. The cable (from the Cable company), splits into a Cable modem (for computer network) and into a DVR (a.k.a. cable box). How can a single coax wire contain digital programming information for over 100 channels and transmit data to the internet at fast speeds? For example, my DVR box can record multiple channels while my PC is transmitting to and from the internet (via the cable). I'm familiar with interfaces that use one bit per wire (such as Centronics Parallel) or send bit pulses using more than one wire (I2C, RS232C, USB, Ethernet). These transmission forms are not as fast as the coax. A: You are searching for a "30,000 foot view" answer, right? That is, a general answer w/o any particulars? The new game is "how much digital data can I send through a cable?". Once digital data transmission is achieved, then anything can be DIGITIZED, COMPRESSED and MULTIPLEXED into the data stream. To send digital data over coax, any number and combination of analog techniques can be used. For instance, an amplitude change of an analog sine wave can indicate the difference between 0s and 1s. The same can be said for a change in phase of the same sine wave. If combined these two modulation techniques are called QAM encoding. If not enough, we can take another step and transmit many such signals over the same coax cable by using sine waves of different frequencies. There are more analog techniques that may or may not be suitable for transmission over coax. Most if not all forms of communications you use in a day is actually DIGITIZED at some point. Phone calls, cable TV and iPods are examples where the media is likely digitized at some point. Most data people use is highly redundant. Music, speech and motion pictures are three examples where COMPRESSION can reduce the amount of data to transmit by an order of magnitude or more. MULTIPLEXING data in the digital domain can be done any number of ways. But in general, digital data is broken up into small groups of numbers which can be transmitted each in turn. This is usually referred to as time division multiplexing. These and more clever techniques are likely employed to deliver the broad range of media to your home over that coax wire entering your house.
{ "pile_set_name": "StackExchange" }
Q: SSDT2012 copy csv file to deploy server I am using SSDT2012 to deploy a database project. I have static data that I want to populate but it is in a .csv file. I added it to the project but can't see a way to copy over to the server temp folder or something similar. I tried adding Thanks for the help! EDIT: I have been looking at Deployment Contributors but it is still not a solution. The need to actually have everyone copy the Contributor onto their machines and having to maintain that and bug fix it; it is not a desirable approach. A: The recommended approach to dealing with static data is to use merge statements in the pre or post deploy scripts: http://blogs.msdn.com/b/ssdt/archive/2012/02/02/including-data-in-an-sql-server-database-project.aspx 2000 lines is quite a lot but sql can easily handle it. Getting your 2000 line csv into a merge statement by hand will obviously be a royal pain so you can use the Sql import wizard to get it into a table (basically just deploy it somewhere) and then you can deploy sp_generate_merge to create the merge statement which you can then put into your post-deploy script: https://github.com/readyroll/generate-sql-merge If you are going to use merge statements then regardless of whether you automatically generate the script or not, I would really recommend using this blog from Alex Whittles to help understand how they work as they can be quite confusing to start with: http://www.purplefrogsystems.com/blog/2011/12/introduction-to-t-sql-merge-basics/ Finally you should be careful when you remove items from your static data, if you have other tables with foreign keys into the data and you remove an item that the child tables depend on the merge statement would fail so you should make sure you go ahead and deal with any possible issues in the pre/post deployment script before running the merge. These should be re-runnable. Ed
{ "pile_set_name": "StackExchange" }
Q: Incrementing date in a loop with php I am new to coding in php and I have a query about getting a date to increment in a loop which is produced by a call to a weather API (http://openweathermap.org), I am using PHP curl which returns XML and I then am looping through 3 sets of data for 3 days, the first day is the current day and then the following two are the next 2 consecutive dates. I thought the simplest way would be to save the current date and then increment this date everytime the code loops, like this: if($numOfItems>0){ // yes, some items were retrieved foreach($items as $current){ //open loop ?> <div style="width:33%;float:left;position:relative;padding:2%" class="WeatherSection"> <?php $myDate = date('d/m/Y'); echo $myDate; var $day = date('d++'); $day = 'd'; $summary = $current->symbol['name']; echo "<p>$summary</p>"; ?> </div> <?php } //close loop } //close code ?> Sadly this doesn't seem to work,I'm sure for someone with more PHP experience this is a simple fix but I just can't figure out why this won't work... much appreciate any guidance! EDITED: thank you for your help, I tried adding this code: $time = time(); echo date( 'd/m/Y', $time); $time = strtotime('+1 day', $time); echo date( 'd/m/Y', $time); $time = strtotime('+1 day', $time); echo date( 'd/m/Y', $time); But it displays all these dates 3 times as it loops, see the screenshot... I just want the date to display once, increment for the next loop and display again with the new date and then once again. Is there a simple way to do this? Screenshot of application EDITED: After looking into options, it seems that trying to gather the date from the XML might be the best option, the way the PHP curl gathers the data though, it seems I can't get to the data in 'time'. Here's my new code: <?php $request = //this is where my API key is added, have removed for putting on StackOverflow $crl = curl_init(); // creating a curl object $timeout = 10; curl_setopt ($crl, CURLOPT_URL,$request); curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout); $xml_to_parse = curl_exec($crl); curl_close($crl); // closing the curl object $parsed_xml = simplexml_load_string($xml_to_parse); // traversing the xml nodes to count how many days were retrieved // ignore the first one (weatherdata) $items = $parsed_xml->forecast->time; $numOfItems = count($items); if($numOfItems>0){ // yes, some items were retrieved foreach($items as $current){ //open loop ?> <div style="width:30%;float:left;position:relative;padding:1.5%;margin-top:10px;text-align:center;" class="WeatherSection"> <?php $dateofweather = strval($current->time['day']); //my attempt to retrieve data from the XML echo "<p>$dateofweather</p>"; $summary = $current->symbol['name']; echo "<p>$summary</p>"; $icon = $current->symbol['var']; echo "<p><img src='http://localhost:8888/images/weathericons/$icon.png'/></p>"; $rain = intval($current->precipitation['value']); if($rain > 5) { echo "<div class='orange_background'><h5 style='padding:10px'>Very Rainy! Remember to regularly get your roof checked!</h5></div>"; } ?> </div> <div style="width:1px;height:300px;float:left;position:relative;padding:0;margin:5px;margin-top:10px;background:#fff;"></div> <?php } //close loop } //close code ?> A: It's safe to use date('d') + 1 in function mktime, but it's better to use strtotime instead.. $time = time(); echo date( 'd/m/Y', $time); $time = strtotime('+1 day', $time); echo date( 'd/m/Y', $time); update $time = time(); for ($i = 0; $i < 3; $i++) { echo date( 'd/m/Y', $time); $time = strtotime('+1 day', $time); }
{ "pile_set_name": "StackExchange" }
Q: First Time Call with BenchmarkDotNet I have tried out BenchmarkDotNet with a simple test class public class BenchTest { bool First = false; [Benchmark] public void FirstTimeInitEffect() { if (First == false) { Console.WriteLine("First called"); First = true; Thread.Sleep(1000); } else { Thread.Sleep(10); } } } And let it run with static void Main(string[] args) { var cfg = ManualConfig.Create(DefaultConfig.Instance); var job = new Job(); job.Accuracy.RemoveOutliers = false; cfg.Add(new Job[] { job } ); BenchmarkRunner.Run<BenchTest>(cfg); } This prints a nice summary but what I am missing from the results is that the first call to the method FirstTimeInitEffect takes 1s. I would expect from a benchmark tool to show me the first call effects as well. I have tried a custom config to prevent the removal of outliers but that did not the trick. Am I using the tool wrong or is this outside the scope of the tool? // * Detailed results * BenchTest.FirstTimeInitEffect: Job-LQPFTL(RemoveOutliers=False) Runtime = Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1586.0; GC = Concurrent Workstation Mean = 10.8548 ms, StdErr = 0.0169 ms (0.16%); N = 15, StdDev = 0.0654 ms Min = 10.7158 ms, Q1 = 10.8058 ms, Median = 10.8963 ms, Q3 = 10.9011 ms, Max = 10.9029 ms IQR = 0.0953 ms, LowerFence = 10.6628 ms, UpperFence = 11.0440 ms ConfidenceInterval = [10.8217 ms; 10.8879 ms] (CI 95%) Skewness = -1.01049139924314, Kurtosis = 2.40561202562778 Total time: 00:00:21 (21.92 sec) // * Summary * BenchmarkDotNet=v0.10.1, OS=Microsoft Windows NT 6.2.9200.0 Processor=Intel(R) Core(TM) i7-4770K CPU 3.50GHz, ProcessorCount=8 Frequency=3417979 Hz, Resolution=292.5706 ns, Timer=TSC [Host] : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1586.0 Job-LQPFTL : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1586.0 RemoveOutliers=False Allocated=0 B Method | Mean | StdDev | -------------------- |----------- |---------- | FirstTimeInitEffect | 10.8548 ms | 0.0654 ms | A: BenchmarkDotNet does a lot of warmup iterations; it allows to achieve a steady state before we start to collect actual measurements. Also, it does some additional stuff which also invokes your method (jitting, pilot iterations, and so on). So, the first call was omitted and wasn't included in the summary. If you want to get statistics based on all measurements (without jitting, pilot and warmup iterations), you should use RunStrategy.ColdStart (instead of RunStrategy.Throughput which is default). It works fine since BenchmarkDotNet v0.10.2. Source code: [SimpleJob(RunStrategy.ColdStart, targetCount: 5)] [MinColumn, MaxColumn, MeanColumn, MedianColumn] public class BenchTest { private bool firstCall; [Benchmark] public void FirstTimeInitEffect() { if (firstCall == false) { firstCall = true; Console.WriteLine("// First call"); Thread.Sleep(1000); } else Thread.Sleep(10); } } Measurements: Result 1: 1 op, 1000582715.59 ns, 1.0006 s/op Result 2: 1 op, 10190609.23 ns, 10.1906 ms/op Result 3: 1 op, 10164930.24 ns, 10.1649 ms/op Result 4: 1 op, 10604238.53 ns, 10.6042 ms/op Result 5: 1 op, 10420930.04 ns, 10.4209 ms/op Detailed results: Mean = 208.4175 ms, StdErr = 198.1331 ms (95.07%); N = 5, StdDev = 443.0390 ms Min = 10.1163 ms, Q1 = 10.1203 ms, Median = 10.4233 ms, Q3 = 505.7118 ms, Max = 1,000.9497 ms IQR = 495.5915 ms, LowerFence = -733.2670 ms, UpperFence = 1,249.0991 ms ConfidenceInterval = [-179.9233 ms; 596.7583 ms] (CI 95%) Skewness = 1.07, Kurtosis = 2.08 Summary: BenchmarkDotNet=v0.10.1, OS=Microsoft Windows NT 6.2.9200.0 Processor=Intel(R) Core(TM) i7-6700HQ CPU 2.60GHz, ProcessorCount=8 Frequency=2531252 Hz, Resolution=395.0614 ns, Timer=TSC [Host] : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1586.0 Job-IQRRGS : Clr 4.0.30319.42000, 32bit LegacyJIT-v4.6.1586.0 RunStrategy=ColdStart TargetCount=5 Allocated=1.64 kB Method | Mean | StdErr | StdDev | Min | Max | Median | -------------------- |------------ |------------ |------------ |----------- |-------------- |----------- | FirstTimeInitEffect | 208.4175 ms | 198.1331 ms | 443.0390 ms | 10.1163 ms | 1,000.9497 ms | 10.4233 ms |
{ "pile_set_name": "StackExchange" }
Q: Importing data into R, which fileformat is the easiest? I have a few datasets in the following formats: .asc, .wf1, .xls. I am indifferent about which one I use, as they are exactly the same. Could anyone please tell me which one of the fileformats is easiest to import into R, and how this is done? A: Definitely not .xls. If .asc is some sort of fixed-width format, than that can be read in easily with read.csv or read.table. Other formats that are easy to read include CSV (comma- or tab-separated text files) and DTA (Stata files, via read.dta in the foreign package). Edit: @KarlOveHufthammer pointed out that .asc is most likely a fixed-width format. In which case read.fwf is the tool to use to read it in to R. Note that FWF is a pain in the heiny to deal with, though, in that you have to have the column widths and names of every column stored somewhere else, then convert that to a format that read.fwf can use--and that's before problems like overlapping ranges. A: save xls to txt or csv, they are easiest for R to read: but be sure that only one header line or no header line is recommended try read.table('*.txt', header=T) read.table('*.txt', header=F) read.delim(*, header=F) read.csv("*.csv") etc.
{ "pile_set_name": "StackExchange" }
Q: Gitlab and Code-Climate - what does it really cover? nothing? I setup code quality step, following this gitlab doc (very poor doc): https://docs.gitlab.com/ee/user/project/merge_requests/code_quality.html Now the code quality step runs and I get the report (perfect). But, it seems that it doesn"t check much, here is an example: :["Complexity"],"check_name":"method_count","content":{"body":""},"description":"`Admis` has 78 methods (exceeds 20 allowed). Consider refactoring.","fingerprint":"3a31032b9aff6d8b119f276d03a3c391","location":{"path":"src/main/java/nc/unc/importparcoursup/dao/admisDAO/Admis.java","lines":{"begin":14,"end":457}},"other_locations":[],"remediation_points":7000000,"severity":"major","type":"issue","engine_name":"structure"},{ :["Complexity"],"check_name":"file_lines","content":{"body":""},"description":"File `Candidat.java` has 945 lines of code (exceeds 250 allowed). Consider refactoring.","fingerprint":"4f570943e9f89fac8caa554c7e78f993","location":{"path":"src/main/java/nc/unc/importparcoursup/dao/candidatDAO/Candidat.java","lines":{"begin":1,"end":1184}},"other_locations":[],"remediation_points":11208000,"severity":"major","type":"issue","engine_name":"structure"},{ :["Complexity"],"check_name":"method_count","content":{"body":""},"description":"`Candidat` has 232 methods (exceeds 20 allowed). Consider refactoring.","fingerprint":"4dbebf004d9f5f3a1fabf03c43699c01","location":{"path":"src/main/java/nc/unc/importparcoursup/dao/candidatDAO/Candidat.java","lines":{"begin":14,"end":1184}},"other_locations":[],"remediation_points":22400000,"severity":"major","type":"issue","engine_name":"structure"},{ :["Bug Risk"],"check_name":"TODO","description":"TODO found","location":{"lines":{"begin":28,"end":28},"path":"src/main/java/nc/unc/importparcoursup/view/components/CheckComponentAdmis.java"},"type":"issue","engine_name":"fixme","fingerprint":"d8d52d96fc27f9b0a1f9879e7d133345","severity":"minor"}] "method_count and file_lines": are for my entities class, so they are not real erros (no point in splitting an entity class) "TODO found": real problem ok (bravo code quality check!) I know there are many other problems. If I put the code into sonarcube, I find many more problems than that) Where are all the errors (the real ones) ? Did something is badly setup ? My project source: https://gitlab.com/tyvain/parcoursup A: your repository does not contain configuration for the code-quality check, so it runs with default options. You should probably add a .codeclimate.yml-file. (You can also run sonar as an engine there...) See https://docs.codeclimate.com/docs/advanced-configuration and https://docs.codeclimate.com/docs/list-of-engines gitlab by default (i.e. without configutation) seems to be more suited for web-projects, see the default config at https://gitlab.com/gitlab-org/security-products/codequality/tree/master/codeclimate_defaults Also, you should probably add the report (maybe additionally) in the reports-subentry below artifacts, like: artifacts: paths: - gl-code-quality-report.json reports: codequality: gl-code-quality-report.json This way, gitlab shows the new/fixed issues in merge requests (at payed levels), see Regards, Tim
{ "pile_set_name": "StackExchange" }
Q: Windows Simple Batch "Multithread" Processing Hi I am pushed by deadlines, so I will post my question here as I go along with my search..here is my script, all it does is look at every file of a folder, and create different "list.txt" depending of the value of "tree_size.txt" formated as CSV.txt (filename,size): FOR %%I in (%inputDir%\*.*) DO ( FOR /F "tokens=1,2" %%A IN (%tree_size%) DO ( IF %%~nxI==%%A IF %%B LEQ 10.000 ( echo %%~dpnxI >> %inputDir%\0_10.txt) IF %%~nxI==%%A IF %%B GTR 10.000 IF %%B LEQ 25.000 ( echo %%~dpnxI >> %inputDir%\11_25.txt) IF %%~nxI==%%A IF %%B GTR 25.000 IF %%B LEQ 40.000 ( echo %%~dpnxI >> %inputDir%\26_40.txt) IF %%~nxI==%%A IF %%B GTR 40.000 IF %%B LEQ 55.000 ( echo %%~dpnxI >> %inputDir%\41_55.txt) IF %%~nxI==%%A IF %%B GTR 55.000 ( echo %%~dpnxI >> %inputDir%\56_plus.txt) ) ) My aim is to modify this code in order to use multithread processing, which seams to be an option using batch scripting on Windows 7. A: Your problem is one of approach. As you have 50,000 files and assuming you have 50,000 lines in your tree_size file (of which you've not given us a sample) then you are reading tree_size 50,000 times and executing the if tree 50,000 * 50,000 = 2,500,000,000 times. Each of your comparison blocks makes 5 tests each time = 12,500,000,000 tests. Try this: FOR /F "tokens=1,2" %%A IN (%tree_size%) DO if exist "%inputDir%\%%A" ( IF %%B LEQ 10.000 ( echo %inputDir%\%%A >> %inputDir%\0_10.txt ) else ( IF %%B LEQ 25.000 ( echo %inputDir%\%%A >> %inputDir%\11_25.txt ) else ( IF %%B LEQ 40.000 ( echo %inputDir%\%%A >> %inputDir%\26_40.txt ) else ( IF %%B LEQ 55.000 ( echo %inputDir%\%%A >> %inputDir%\41_55.txt ) else ( echo %inputDir%\%%A >> %inputDir%\56_plus.txt ))))) ) which should accomplish the same thing using only 50,000 cycles of the inner loop.
{ "pile_set_name": "StackExchange" }
Q: 2 meanings of 'power in Admin Law – 'authority to restrict or take away the rights of others' v 'the capacity to act in a certain way' See emboldening pls. What are the other differences between the two meanings of 'power'? I don't reckon I spotted any! Isn't (b) just a type of (a)? 'authority to restrict or take away the rights of others' is just one way of "the capacity to act in a certain way". Bradley, Ewing. Constitutional and Administrative Law (2018 17 ed). p 589 Powers, duties and discretion A recurring feature in administrative law is the interplay between powers, duties and discretion. If someone satisfies the legal rules that govern who may vote in parliamentary elections, then he or she has a right to be entered on the electoral register and a right to vote in the area where he or she is registered. The relevant officials are under a correlative duty to give effect to these rights. Many situations that arise in the course of public administration are less clear-cut. Thus a minister may be under a duty to achieve certain broad policy objectives without in law being required to take action of any particular kind. p 590 Clearly, steps taken in the performance of such a duty involve the exercise of discretion. As Lord Diplock said: The very concept of administrative discretion involves a right to choose more than one possible course of action on which there is room for reasonable people to hold differing opinions as to which is to be preferred.42 Where an Act confers authority to administer a branch of government, it may confer a broad duty on the minister and other public authorities to fulfil certain policy objectives. It may impose specific duties on the minister to act when certain conditions exist and it will probably confer powers on the authorities concerned. In administrative law, ‘power’ has two meanings, which are not always distinguished: (a) the capacity to act in a certain way (for example, power to provide a library service or to purchase land by agreement for a sports field); and (b) authority to restrict or take away the rights of others (for example, power to regulate the mini-cab trade in a city or to buy land compulsorily that is needed for a public purpose). Since it is inherent in the nature of a power that it may be exercised in various ways, use of a power invariably requires the exercise of discretion; and power and discretion are often used interchangeably. Often there is a duty to exercise a discretion. When an official decides to perform a duty or to exercise a power or discretion in a certain way, the decision may delight some persons and disappoint others. Within a democracy, important choices of this kind should be made by those who have political responsibility for them, not by judges.43 Those whose rights or interests are adversely affected by an administrative decision may wish to challenge it, whether by taking any political action to get it changed if that is still possible, by using any rights of appeal that exist, or by seeking judicial review. 42Secretary of State for Education v Tameside MBC [1977] AC 1014, 1064. And see Davis, Discretionary Justice, and Galligan, Discretionary Powers. A: The first type is the power of agency, the second is the power to coerce The first type of power is available to anyone, not just governments, and is simply the power to do (or not do) whatever the law allows. Anyone can set up a library or buy land from a willing seller as in the examples. The second type is only available to government and is the power to (legally) force others to do what they don’t want to do. Comply with mini-cab regulations or be forced to sell their property as in the examples. Or, require the payment of tax as the quintessential example of this type of power.
{ "pile_set_name": "StackExchange" }
Q: Using d3.selectAll with nested json Here i want to create bars for each album with the numbers of 'a_tracks' but i can't get into the node "album". [ { "blazz" : "HisName", "firstname" : "HisFirstname", "album" : [ { "a_name" : "titlehere", "a_sells" : 90, "a_years" : 2000, "a_tracks" : 12 } , { "a_name" : "othertitlehere", "a_sells" : 200, "a_years" : 2000, "a_tracks" : 8 } ] } ] I try this but it's not working : d3.json('data.json', function(data){ var albums = data.map(function(d) { return d.album }); var canvas = d3.select("body").append('svg') .attr("width", 500) .attr("height",500) canvas.selectAll("rect") .data(albums) .enter() .append("rect") .attr('width', function(d){ return d.a_tracks*10;}) .attr('height',50) .attr('y',function(d,i){ return i * 52;}) .attr('fill','blue') I'm on the wrong way to do this ? (Json is given a my backbone collection) A: To expand on what @LarsKotthoff said in the comments... The problem you are having here is that the "album" property of each item in your original data contains an Array of albums rather than an Object representing a single album. So when you map your data into the variable called albums, that variable becomes an array of arrays rather than an array of objects. Because of this, when you try to set an element's width based on d.a_tracks an error will be thrown because d is an array, and therefore doesn't have a property called a_tracks. In fact it is an array that contains multiple objects which each have an a_tracks property. To work around this, you can use a nested selection as was suggested: canvas.selectAll("g") .data(albums) .enter().append("g") .selectAll("rect") .data(f‌​unction(d) { return d; }) .enter().append("rect") First, the data albums is bound to the incoming g (group) elements, which reflects the fact that each item in this data represents a group of albums rather than a single album. Then within the group selection, a new selection is created, binding each album in each group to an individual rect element.
{ "pile_set_name": "StackExchange" }
Q: Disappear Standard Error in OxEdit/G@rch6 package Hellow everyone, I'm new here. Please instruct me to do something. My problem is when I run FIGARCH(0,d,1), OxEdit still show me a matrix with variable names, coefficient, s.e, t-stat... like this But when I try FIGARCH(1,d,2) it show nothing but coefficient parameters, like this So please instruct me how to show the other stats. Furthermore, please instruct me how to run G@rch6 package in R via function GarchOxFit, because this function is no longer supported but Mr. Brian in this topic show that R can run G@rch6. I much appreciate your help. Thank you. A: Regarding your first question, as it is written in your example, the FIGARCH(1,d,2) estimation fails due to "no convergence" : ie the quasi Maximum Likelihood Estimation Method fails to obtain stable parameters via the maximization of the likelihood and so you can't get parameters for this specification (neither other stats). The QMLE method does not always get result.
{ "pile_set_name": "StackExchange" }
Q: Anim Zemiros is highly anthropomorphic; how come we sing it in public? Shir HaKovod - Anim Zemiros. This is amazingly anthropomorphic and all that without even once the word כביכול (= as if such a thing could be true). Admittedly the references come from texts such as Shir HaShirim but to make a poem from it, how come it’s allowed? A: The poet makes it very clear, before launching into these descriptions, that they are not literal: אֲסַפְּרָה כְבודְךָ וְלא רְאִיתִיךָ. אֲדַמְּךָ אֲכַנְּךָ וְלא יְדַעְתִּיךָ:‏ בְּיַד נְבִיאֶיךָ בְּסוד עֲבָדֶיךָ. דִּמִּיתָ הֲדַר כְּבוד הודֶךָ:‏ גְּדֻלָּתְךָ וּגְבוּרָתֶךָ. כִּנּוּ לְתוקֶף פְּעֻלָּתֶךָ:‏ דִּמּוּ אותְךָ וְלא כְּפִי יֶשְׁךָ. וַיַּשְׁווּךָ לְפִי מַעֲשיךָ:‏ הִמְשִׁילוּךָ בְּרוב חֶזְיונות. הִנְּךָ אֶחָד בְּכָל דִּמְיונות:‏ I shall relate Your glory, though I see You not; I shall allegorize You, I shall describe You, though I know You not. Through the hand of Your prophets, through the counsel of Your servants; You allegorized the splendrous glory of Your power. Your greatness and Your strength, they described the might of Your works. They allegorized You, but not according to Your reality, and they portrayed You according to your deeds. They symbolized You in many varied visions; yet You are a Unity containing all the allegories. (Hebrew text of lines 5 - 9 copy/pasted from Sefaria. English Translation from the Artscroll Siddur.) That sounds to me like five lines of "כביכול ."
{ "pile_set_name": "StackExchange" }
Q: How to access items in a model with ReferenceProperty? This is a follow up on my previous question. I set up the models with ReferenceProperty: class User(db.Model): userEmail = db.StringProperty() class Comment(db.Model): user = db.ReferenceProperty(User, collection_name="comments") comment = db.StringProperty(multiline=True) class Venue(db.Model): user = db.ReferenceProperty(User, collection_name="venues") venue = db.StringProperty() In datastore I have this entry under User: Entity Kind: User Entity Key: ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM ID: 21 userEmail: [email protected] And under Venue: Entity Kind: Venue Entity Key: ag1oZWxsby0xLXdvcmxkcgsLEgVWZW51ZRhVDA ID: 85 venue (string): 5 star venue user (Key): ag1oZWxsby0xLXdvcmxkcgoLEgRVc2VyGBUM User: id=21 I am trying to display the item in hw.py like this query = User.all() results = query.fetch(10) self.response.out.write("<html><body><ol>") for result in results: self.response.out.write("<li>") self.response.out.write(result.userEmail) self.response.out.write(result.venues) self.response.out.write("</li>") self.response.out.write("</ol></body></html>") This line works: self.response.out.write(result.userEmail) But this line does not work: self.response.out.write(result.venues) But as per vonPetrushev's answer result.venues should grab the venue associated with this userEmail. Sorry if this is confusing: I am just trying to access the tables linked to the userEmail with ReferenceProperty. The linked tables are Venue and Comment. How do I access an item in Venue or in Comment? Thanks. A: venues is actually a query object. So you'll need to fetch or iterate over it. Try replacing the self.response.out.write(result.venues) line with a loop: query = User.all() users = query.fetch(10) self.response.out.write("<html><body><ol>") for user in users: self.response.out.write("<li>") self.response.out.write(user.userEmail) self.response.out.write("<ul>") # Iterate over the venues for venue in user.venues: self.response.out.write("<li>%s</li>" % venue.venue) self.response.out.write("</ul></li>") self.response.out.write("</ol></body></html>") However, this will not scale very well. If there are 10 users, it will run 11 queries! Make sure you are using Appstats to look for performance issues like these. Try to minimize the number of RPC calls you make. A better solution might be to denormalize and store the user's email on the Venue kind. That way you will only need one query to print the venue information and users email.
{ "pile_set_name": "StackExchange" }
Q: Chef and Nagios intervals Can't seem to find a solution. I know it's probably easy, I'm a ruby noob..roob, but would appreciate the help. How do i set the interval check to say 5/5. So, alert me on the 5th failed attempt. This is what I have in my chef data bag for the chef-client service: { "command_line": "$USER1$/check_nrpe -H $HOSTADDRESS$ -t 45 -c wt_check_procs -a '-t 60 -c 1: -C 'chef-client''", "hostgroup_name": "chef_managed_systems", "id": "chef-client", "contact_groups": "email_and_page", "event_handler": "restart_chef" } How would I define something like the following but within my databag: define service{ host_name A Host service_description A Service normal_check_interval 5 retry_check_interval 1 max_check_attempts 5 } A: Looking at https://github.com/opscode-cookbooks/nagios/blob/master/templates/default/services.cfg.erb#L14 I would guess that by simply defining those attributes like the existing ones will work - just recognize the json formatting.
{ "pile_set_name": "StackExchange" }
Q: No metro project templates in Visual Studio Express 2012 for Desktop? Both of the download pages for for Desktop and for Windows 8 provide the same web installer called: "Visual Studio Express 2012 for Windows Desktop". I installed it and here is its "New Project" window: In this tutorial page, it says I should have templates like this: (source: microsoft.com) How can I get these templates? I'm using Windows 8 x64 RTM. A: You have most likely downloaded wrong Visual Studio Express version, maybe there is broken link on that page. If you want to develop Metro style apps for Windows 8, download the proper Visual Studio Express here: http://msdn.microsoft.com/en-us/windows/apps/hh852659
{ "pile_set_name": "StackExchange" }
Q: SVG/CSS: Masked Header Logo So I'm trying to make a masked Logo where the piece with the shadow is actually a transparent window to the content behind it. The design is like this: I'm thinking I have to tackle this with SVG and Masking, but my attempts didn't really go that well as seen here: @charset "utf-8"; *{margin:0;padding:0} body{ width:100%; min-height:100%; background-color:#eee; color:#eee; } /*Header -------------*/ header{ position:fixed; top:0; width:100%; height:20%; height:auto; z-index:999; } #logo:before{ width:10%; height:15vw; display:block; content:""; background:#fff; float:left; } #logo:after{ width:80%; height:15vw; display:inline-block; content:""; background:#fff; } #logo img{ float:left; width:10%; } /*Content -------------*/ main{ position:relative; margin:auto; width:100%; height:200%; background:#2d917f } /*Links -------------*/ a,a:visited{ color:#eee; text-decoration:none; -webkit-transition:all .2s ease; -moz-transition:all .2s ease; -o-transition:all .2s ease; transition:all .2s ease; } a:active, a:hover{ color:#fff; border-bottom:1px solid #fff } /*Scrollbar -------------*/ ::-webkit-scrollbar{width:12px;height:12px;background-color:#1A1A1A} ::-webkit-scrollbar-corner{background-color:#0e0e0e} ::-webkit-scrollbar-track{background-color:#121212} ::-webkit-scrollbar-thumb{background:#2d917f} ::-webkit-scrollbar:horizontal{height:12px} /*Selection -------------*/ ::selection{color:#fff;background-color:#2d917f} ::-moz-selection{color:#fff;background-color:#2d917f} <header> <div id="logo"> <img src="https://ap-images.ga/up/2017/05/11151821-Logo2.svg" title="11145933-Logo.svg" alt="11145933-Logo.svg"/> </div> </header> <main> </main> On Codepen: https://codepen.io/RafaelDeJongh/pen/PmROPW Does anyone have any idea how I'd best tackle this, and in general how to mask a certain part out of an element (in this case the header)? Thanks in advance! A: The simplest solution would just be to make an SVG that: A rectangle forming your white banner background A mask applied to that forming the whole Finally a drop shadow filter applied to the result Then either embed that SVG into your page and overlay your banner text, or save the SVG as a separate file and use it as a background-imaage for the <header> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1860 256"> <defs> <mask id="hole"> <rect width="100%" height="100%" fill="white"/> <g transform="translate(200,35)"> <rect x="1" y="1" width="118" height="178" fill="#000"/> <path fill="white" d="M0.1,0h119.8v180H0.1V0 M3.2,33.2c0,13.8,0,27.7,0,41.5C18.6,75.1,33.9,80.4,46,90c-0.1-5.1,0-10.2-0.1-15.3 c16.3-0.2,32.7,5,45.6,15c12.2,9.5,22,22.9,25.4,38.1c-0.4-31.5,0-63-0.2-94.5C78.9,33.2,41.1,33.2,3.2,33.2 M3.6,77.9 c0,23,0,45.9,0,68.9c14.1,0,28.3,0,42.4,0c0-17.6,0-35.1,0-52.7C34.2,84,18.9,78.4,3.6,77.9 M49,78c0.1,4.8,0,9.5,0,14.2 c15.5,13.6,25.1,33.8,25,54.5c14.1,0,28.3,0,42.4,0c0.5-17.7-7.1-35.2-19.3-47.8C84.7,86.1,67,78.2,49,78 M49.1,96.6 c0.1,16.7,0,33.4,0,50.2c7.3,0,14.6,0,21.8,0C70.9,128,62.6,109.6,49.1,96.6z"/> </g> </mask> <filter id="shadow"> <feOffset in="SourceAlpha" dx="10" dy="10" result="offset" /> <feColorMatrix in="offset" type="matrix" values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 1 0" result="greyoff" /> <feGaussianBlur in="greyoff" stdDeviation="7" result="blur" /> <feBlend in="SourceGraphic" in2="blur" mode="normal" /> </filter> </defs> <g filter="url(#shadow)"> <rect x="15" y="15" width="1800" height="220" fill="white" mask="url(#hole)"/> </g> </svg>
{ "pile_set_name": "StackExchange" }
Q: Like button Django3 - KeyError at /nutriscore/exemple-1/ 'pk' I hope you're well. I'm beginner with Python and I'm trying to implement a like button in blog post like this. In admin part I can see who is clicking on the like. But I encounter two issues: first one: when I click on the like button, the "return" redirect me with this kind of url nutriscore/4/ or my article uses a slug (like that /nutriscore/exemple-1/. Do you have any idea? seconde one: when I want to display the number of like {{ total_likes }} I have this issue: KeyError at /nutriscore/exemple-1/ 'pk' Models.py: class Post(models.Model): ... likes = models.ManyToManyField(User, related_name='nutriscore_posts') def total_likes(self): return self.likes.count() Views.py: class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) post.likes.add(request.user) return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) class PostDetail(generic.DetailView): model = Post context_object_name = 'post' template_name = 'post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes context['total_likes'] = total_likes return context urls.py path('like/<int:pk>', LikeView, name="like_post"), post_detail.html <form action="{% url 'like_post' post.pk %}" method="POST">{% csrf_token %}<button type="submit" name="post_id" value="{{ post.id }}" class="cherry-likes"><img src="static/img/like.png" width="30px" height="30px" class="" title=""></button></form> Thanks a lot :) A: Your pk should be int.You are also specifying as an int in your url but not in views. post = get_object_or_404(Post, id=pk ) if request.method == "POST": post.likes.add(request.user) return redirect('post_detail', post.pk) To display the total likes of the post you need to add a property decorator like this @property def total_likes(self): return self.likes.count() Now in the detail template {{post.total_likes}} would display the result. There is no need to write get_context_data method to display the total_likes.
{ "pile_set_name": "StackExchange" }
Q: How to Stop SSMS 2012 from scripting SPs using sp_executesql I realise this is a very similar question to Stop SSMS from scripting SPs using sp_executesql? However, they seem to have changed the behaviour with SSMS 2012. If you have the 'Check for existence' option selected, as in: ... it now generates an IF NOT EXISTS for the proc about to be created, as well as an IF EXISTS for the previous drop proc, if, as I usually do, I select the DROP and CREATE option: This forces it to script the CREATE using sp_executesql. It's pointless, since you don't need the IF NOT EXISTS check on the CREATE, if the DROP has just dropped it. It doesn't seem possible to have the one without the other. Any ideas? A: You can't do this without the dynamic SQL because a stored procedure has to be in its own batch. Therefore you can't say: IF <some condition> <start a new batch> The only way to keep that in the same batch is to use sp_executesql. If you're going to script the DROP and CREATE simultaneously, just do it without the check for object existence. This will give you: DROP PROCEDURE ...; GO CREATE PROCEDURE ...; GO Who cares if the DROP fails? (It shouldn't, because you just scripted from it!) If you're scripting this for another system that might have the object, you'll get an error message for the DROP when it doesn't, but the CREATE will still happen, so you can ignore the DROP errors. If you really want you can manually wrap the DROP statements in TRY/CATCH but I don't think it's necessary. If you need to do this for a lot of procedures, or if you really need the process to not generate benign errors, I suggest you abandon Management Studio's primitive scripting options and use a 3rd party tool for this. They'll have already dealt with many of the issues you haven't yet come across, but will. I blogged about this: http://bertrandaaron.wordpress.com/2012/04/20/re-blog-the-cost-of-reinventing-the-wheel/ A: The closest you can get to this functionality is to go under tools, options, SQL Server Object Explorer, Scripting, then set the Check for Object Existing to false. The drawback is that if you do this then drops and creates will always try to drop even if the object does not exist. The ideal solution would be a setting that allowed your script to look like the example below for creating Views, Procedures, and User-Defined Functions. /****** Object: View [dbo].[vEmployees] Script Date: 9/14/2012 9:18:57 AM ******/ IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vEmployees]')) DROP VIEW [dbo].[vEmployees] GO CREATE VIEW [dbo].[vEmployees] AS SELECT DISTINCT Employees.EmployeeID, FirstName, LastName from Employees JOIN Sales on Employees.EmployeeID=Sales.EmployeeID GO In short if the scripting engine thinks of the drop and create together in checking for object existance it does not need to put the condition on the create.
{ "pile_set_name": "StackExchange" }
Q: Can you define the src attribute in css? Can you define an iframe's src attribute in css as opposed to in the html tag? Is there a fundamental reason why this wouldn't work? I wanted to clean up my HTML a little bit by moving a long source link out of the main page but couldn't find an answer to this anywhere. A: This doesn't work because src has nothing to do with rendering style.
{ "pile_set_name": "StackExchange" }
Q: Trying to alloc more than 2GB on a windows 7 I'm usining Windows 7, 64bits, 8GB ram I'm needing to make alloc more than 2GB but I'm getting runtime error look at my piece of code #define MAX_PESSOAS 30000000 int i; double ** totalPessoas = new double *[MAX_PESSOAS]; for(i = 0; i < MAX_PESSOAS; i++) totalPessoas[i] = new double [5]; MAX_PESSOAS is set to 30milion, but I'll need at least 1billion (ok, I know I'll need more than 8GB but nvm, I can get it, I only need to know how to do that ) I'm using visual studio 2012 A: If your application is building to a 64-bit binary, it can address more than 8 GB without any special steps. If your application is building to a 32-bit binary, you can address up to 3 GB (or 4 GB if you're running 64-bit Windows) by enabling 4-gigabyte tuning, as long as the system supports it. Your best bet is probably to compile your application as a 64-bit binary, if you know that the operating system it will be running on is 64-bit.
{ "pile_set_name": "StackExchange" }
Q: Python - Как записать CSV таблицу с разным количеством строк в столбцах? У меня есть база (json) вида: article = {'выдача': [ { {'организация': {'Название': 'Фирма1', 'Телефон': '79111111111', 'Сайт': 'site1.con'}}, {'организация': {'Название': 'Фирма2', 'Телефон': ['79111111121', '79111111122', '79111111123'], 'Сайт': ['site21.con', 'site22.con']}}, {'организация': {'Название': 'Фирма3', 'Телефон': ['79111111131', '79111111132'], 'Сайт': ['site31.con', 'site32.con', 'site33.con']}}}]} У некоторых фирм есть по несколько телефонов или сайтов. Мне нужно, чтобы в out.csv база записалась следующим образом: Вопрос: Как записать CSV таблицу с разным количеством строк в столбцах? A: Подобный output можно получить из этих данных разными способами, давай попробуем через всеми любимую pandas - pretty sure @MaxU is gonna "destroy" this solution :) import pandas as pd def expand_column(df, column_name): """Expands inner lists in columns.""" series = df.apply(lambda x: pd.Series(x[column_name]), axis=1).stack().reset_index(level=1, drop=True) series.name = column_name return df.drop(column_name, axis=1).join(series) data = {'выдача': [ {'организация': {'Название': 'Фирма1', 'Телефон': '79111111111', 'Сайт': 'site1.con'}}, {'организация': {'Название': 'Фирма2', 'Телефон': ['79111111121', '79111111122', '79111111123'], 'Сайт': ['site21.con', 'site22.con']}}, {'организация': {'Название': 'Фирма3', 'Телефон': ['79111111131', '79111111132'], 'Сайт': ['site31.con', 'site32.con', 'site33.con']}} ] } df = pd.DataFrame([item['организация'] for item in data['выдача']]) df = expand_column(df, 'Сайт') df = expand_column(df, 'Телефон') df.to_csv('output.csv') Здесь мы использовали вот этот способ раскрытия значений внутри ячеек: When cell contents are lists, create a row for each element in the list. В output.csv в итоге получилось вот что:
{ "pile_set_name": "StackExchange" }
Q: Insert arrows using graphdrawing library I would like to link numbers 6 -> 5 and 5 -> 4 but I have no clue on how to do it. My code is as follows \documentclass[tikz,border=10pt]{standalone} \usetikzlibrary{graphdrawing} \usetikzlibrary{graphs} \usegdlibrary{trees} \begin{document} \begin{tikzpicture}[>=stealth, every node/.style={rectangle, rounded corners, draw, minimum size=0.75cm}] \graph [tree layout, grow=down, fresh nodes, level distance=0.5in, sibling distance=0.5in] { Flight 0 -> { Flight 1 -> { 4 -> , 5}, Flight 2 -> { 6 }, Flight 3 -> { 7,8 } } }; \end{tikzpicture} \end{document} This is the output: A: The nodes can be accessed by their name so you can simply draw arrows between them: % !TeX TS-program = lualatex \documentclass[tikz,border=10pt]{standalone} \usetikzlibrary{graphdrawing} \usetikzlibrary{graphs} \usegdlibrary{trees} \begin{document} \begin{tikzpicture}[>=stealth, every node/.style={rectangle, rounded corners, draw, minimum size=0.75cm}] \graph [tree layout, grow=down, fresh nodes, level distance=0.5in, sibling distance=0.5in] { Flight 0 -> { Flight 1 -> { 4 , 5}, Flight 2 -> { 6 }, Flight 3 -> { 7,8 } } }; \draw[->] (6) -- (5); \draw[->] (5) -- (4); \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: How to access a Field in a Dynpro i Added via the Dict in the PAI? I have the following question: I have a dypro and added via the layout builder a dict delement: mara-matnr Now I see it in my element list: Now I wanted to know, how to access the value of the matnr in my PAI which looks like this: MODULE user_command_1000 INPUT. " HOW TO ACCESS THE VALUE OF MATNR HERE? ENDMODULE. A: I have to guess what you did to get that far, and I’d strongly recommend not to continue along that road. What I’d rather do is create a new dictionary structure (not a transparent table!) that contains the screen fields you need use the TABLES statement with the structure to declare a global variable in your program or function pool top include place the fields of the structure on the screen, just like you did with the MARA fields in your example use the fields of your global variable in your coding The way you prepared the screen, you would have to add a global variable named MARA with the structure of the transparent table MARA, probably using the statement TABLES mara. While this is perfectly possible, it’s also really dangerous - you could end up changing the database contents inadvertedly, especially since you seem to be rather new to the system.
{ "pile_set_name": "StackExchange" }
Q: C# BufferedGraphics Memory Leak My code has the following form: while (Globals.Running) { if ((Form.Visible == false) || (Form.ContainsFocus == false) || (Form.Enabled == false)) { Threading.Thread.Sleep(100); } else { Update(); Draw(); } Application.DoEvents(); } When I look at the process in the Task Manager, I see the memory consumed increases by 8K each second. If I comment out the Draw() call, memory is stable. Therefore, memory is leaking inside Draw. Here is how that method looks like: private static void Draw() { BufferedGraphics.Graphics.Clear(Color.CornflowerBlue); //Engine.Draw(BufferedGraphics.Graphics); BufferedGraphics.Render(); ++FPS; } So, even without me drawing anything, memory is lost. If I comment out .Clear line, it still leaks. If I comment out .Render line, it still leaks. If I comment out both of those, it stops leaking. BufferedGraphics is initialized in the constructor like this: BufferedGraphics = BufferedGraphicsContext.Allocate(Graphics.FromHwnd(Form.Handle), Form.ClientRectangle); So, my question is, why is rendering nothing/clearing the graphics context leaking memory? Or is there something else at play here? A: Don't use application.doEvents! Use a dispatcher to update the UI whilst operating on a different thread, it wil prevent blocking of the UI and changes won't leak memory Example: Dispatcher.Invoke to update UI Control
{ "pile_set_name": "StackExchange" }
Q: Converting date back to JSON time using jquery so i have a JSON time for example 786668400 which i'm converting to day, month, year to display on a page. i have a form with select boxes for users to insert their birthdate and i need to submit the form with the result of those 3 select boxes in JSON time (or whatever it's called) using jquery/javascript. how do i do that? edit: adding some code as was asked by users... i'm converting it to a normal date using jquery like so: var dateFormat = new Date(786668400*1000).getDate() + "." + (new Date(786668400*1000).getMonth() + 1) + "." + new Date(786668400*1000).getFullYear(); these are the select boxes for the birthdate <select name="day"><option>Day</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7" selected="">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option></select><select name="month"><option>Month</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10" selected="">10</option><option value="11">11</option><option value="12">12</option></select><select name="year"><option>Year</option><option value="1941">1941</option><option value="1942">1942</option><option value="1943">1943</option><option value="1944">1944</option><option value="1945">1945</option><option value="1946">1946</option><option value="1947">1947</option><option value="1948">1948</option><option value="1949">1949</option><option value="1950">1950</option><option value="1951">1951</option><option value="1952">1952</option><option value="1953">1953</option><option value="1954">1954</option><option value="1955">1955</option><option value="1956">1956</option><option value="1957">1957</option><option value="1958">1958</option><option value="1959">1959</option><option value="1960">1960</option><option value="1961" selected="">1961</option><option value="1962">1962</option><option value="1963">1963</option><option value="1964">1964</option><option value="1965">1965</option><option value="1966">1966</option><option value="1967">1967</option><option value="1968">1968</option><option value="1969">1969</option><option value="1970">1970</option><option value="1971">1971</option><option value="1972">1972</option><option value="1973">1973</option><option value="1974">1974</option><option value="1975">1975</option><option value="1976">1976</option><option value="1977">1977</option><option value="1978">1978</option><option value="1979">1979</option><option value="1980">1980</option><option value="1981">1981</option><option value="1982">1982</option><option value="1983">1983</option><option value="1984">1984</option><option value="1985">1985</option><option value="1986">1986</option><option value="1987">1987</option><option value="1988">1988</option><option value="1989">1989</option><option value="1990">1990</option><option value="1991">1991</option><option value="1992">1992</option><option value="1993">1993</option><option value="1994">1994</option><option value="1995">1995</option><option value="1996">1996</option><option value="1997">1997</option><option value="1998">1998</option><option value="1999">1999</option><option value="2000">2000</option><option value="2001">2001</option><option value="2002">2002</option><option value="2003">2003</option><option value="2004">2004</option><option value="2005">2005</option><option value="2006">2006</option><option value="2007">2007</option><option value="2008">2008</option><option value="2009">2009</option><option value="2010">2010</option><option value="2011">2011</option><option value="2012">2012</option><option value="2013">2013</option><option value="2014">2014</option><option value="2015">2015</option><option value="2016">2016</option></select> and i need to get the values of these select boxes and convert them back to the JSON time format. .toJSON() doesn't seem to do it... i have no code for this yet because i haven't found anything that does that. all that comes up is converting from JSON to date... A: You can convert date to timestamp by creating date object and calling getTime method. Full example: <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <form> <input type="text" id="year" value="2016"> <input type="text" id="month" value="10"> <input type="text" id="day" value="11"> <div id="result"></div> </form> <script> jQuery(function() { var calculateTimestamp = function() { //Ge values from inputs var year = jQuery('#year').val(); var month = jQuery('#month').val(); var day = jQuery('#day').val(); //Create date object. Month is 0 based var date = new Date(year, month - 1, day, 12); //Get timestamp and convert to seconds jQuery('#result').html(date.getTime() / 1000) }; calculateTimestamp(); jQuery('input').on('chagne, keyup', calculateTimestamp); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Disabling/bypassing Rich Text Editor validation I've implemented a custom ribbon button/dialog to insert a link to a document contained in a third party DMS. The DMS client installs a protocol handler that allows the use of links such as the following - iwl:dms=DEV85SERVER&lib=LIVE&num=25210&ver=1 Unfortunately, upon saving the page, the above URL is stripped out and I'm left with an empty A tag. Is it possible to either disable the SP2010 RTE validation, or escape the above URL somehow to prevent the A tag being sanitized? A: I ended up going with an alternative approach. I added an .aspx page to my package, and had the RTE inserted link pass the relevant parameters over to the new page. Then, the .aspx page regenerated the original URL and handled it accordingly.
{ "pile_set_name": "StackExchange" }
Q: "Dynamic route" with expressjs I want to create a route which can change while the program is running. Example : app.get('/',function(req,res){/*Something here*/}; This is a normal route. I want to replace the '/' with a variable which can be replaced with a random number. After that I'll create a qrcode with a nodejs module and the user who scans this qrcode will confirm a kind of transaction. If you understand my idea and you have a solution, I'll take it. A: As @Louy said, use parameters: var getQRCode = require('./yourQRCodeModule'); app.param('qrcode', function(req, res, next, qrcode) { // qrcode will be "1234" if your request path was "/1234" console.log('checking qrcode: %s', qrcode); // get the qrcode from some asynchronous function getQRCode(qrcode, function callback(err, qrcode) { // if this number was not a valid dynamic path, return an error from your module console.log('qrcode was %s', (!err && qrcode) ? 'valid' : 'invalid'); if (err) { next(err); } else if (qrcode) { req.qrcode = qrcode; // object from your module next(); } else { next(new Error('failed to load QR code')); } }); }); app.get('/:qrcode', function (req, res) { // req.qrcode will be the object from your module // if the number was invalid, this will never be called }); What I'm trying to point out is that you're thinking of this scenario differently than how express approaches the problem. You want a one-time route with a specific qrcode, but these kind of routes don't exist in express. So here's what I understand your ideal solution to look like: server creates "azjzso1291084JKioaio1" for a qrcode you register something like app.getOnce("azjzso1291084JKioaio1", function(req, res){...}) first time the request gets called, it's removed from your express router Here's what I'm suggesting: server creates "azjzso1291084JKioaio1" for a qrcode your module stores this qrcode either in a database or in memory, within your module, e.g. var qrcodes = {}; qrcodes["azjzso1291084JKioaio1"] = {some: 'object'}; your app.param asynchronous function based on the example given in step 2 could look like this:   // yourQRCodeModule.js var qrcodes = {}; qrcodes["azjzso1291084JKioaio1"] = {some: 'object'}; module.exports = function getQRCode(qrcode, callback) { if (qrcodes[qrcode]) { var obj = qrcodes[qrcode]; // copy object delete qrcodes[qrcode]; // remove from memory here callback(null, obj); } else { // invalid path callback(new Error('invalid QR code'), null); } }; Now notice if you request /azjzso1291084JKioaio1 twice, the second time fails. This is how you intend it to work, if I am not mistaken.
{ "pile_set_name": "StackExchange" }
Q: Share the eclipse search result/ query I just want to know if the search result in eclipse search view can be shared with fellow team mate as it is. I perform a search and delete few unwanted entries and then send it to him/ her The other person shall be able to view it exactly same manner in the search view. Is there a way to do this? The will be very helpful for me A: You should be looking at the Mylyn project (http://eclipse.org/mylyn). This project allows you to create tasks and send them to co-workers through a task repository (such as bugzilla, jira, or most major issue trackers). Attached to these tasks are "contexts", which associate code elements (methods, fields, classes, etc) with the task. Here is what you would need to do: Install mylyn (you and all co-workers) Install the proper connector for your issue tracker (most major issue trackers have one). If you are not using an issue tracker, then you can still import and export tasks as files, but it is less easy to do, and I'd recommend using an issue tracker anyway. Now add the task repository to your Eclipse. This is the way that mylyn speaks to your issue tracker. It allows you to create issues, bug reports, tasks, etc, from within Eclipse. With this set up, you can now create a task associated with a task repository and activate it. You can add the desired program elements to your task by right clicking -> Mark as Landmark. Once you have your task context complete, you can then attach the context to the remote repository (essentially attaching a zip file to the issue in your issue tracker). Other users can then retrieve the context and immediately start working with the context that you created. It is really a great way to work when you need to share information about specific features in the code to other people on the project.
{ "pile_set_name": "StackExchange" }
Q: Why before ALL functions (except for main()) there is a 'static' keyword? I was reading some source code files in C and C++ (mainly C)... I know the meaning of 'static' keyword is that static functions are functions that are only visible to other functions in the same file. In another context I read up it's nice to use static functions in cases where we don't want them to be used outside from the file they are written... I was reading one source code file as I mentioned before, and I saw that ALL the functions (except the main) were static...Because there are not other additional files linked with the main source code .c file (not even headers), logically why should I put static before all functions? From WHAT should they be protected when there's only 1 source file?! EDIT: IMHO I think those keywords are put just to make the code look bigger and heavier.. A: If a function is extern (default), the compiler must ensure that it is always callable through its externally visible symbol. If a function is static, then that gives the compiler more flexibility. For example, the optimizer may decide to inline a function; with static, the compiler does not need to generate an additional out-of-line copy. Also, the symbol table will smaller, possibly speeding up the linking process too. Also, it's just a good habit to get into. A: It is hard to guess in isolation, but my assumption would be that it was written by someone who assumes that more files might be added at some point (or this file included in another project), so gives the least necessary access for the code to function. Essentially limiting the public API to the minimum. A: But there are other files linked with your main module. In fact, there are hundreds or even thousands, in the libraries. Most of these won't be selected for a small program but all the symbols are scanned by the linker. A collision between a symbol in main and an exported symbol from a library won't by itself cause any harm, but think of the trouble accidently naming something strcpy() could cause. Also, it probably doesn't hurt to get used to the best-practice styles.
{ "pile_set_name": "StackExchange" }
Q: SyntaxError Exception @Override public void start(Stage primaryStage) throws Exception{ try{ String fxmlName; Connection con = DriverManager.getConnection("url","root","password"); Statement st = con.createStatement(); String qry = "select UpdateT from schema.update"; ResultSet rs = st.executeQuery(qry); fxmlName = rs.getString("UpdateT"); // System.out.println(fxmlName); st.close(); Parent root = FXMLLoader.load(getClass().getResource(fxmlName)); primaryStage.setScene(new Scene(root)); primaryStage.initStyle(StageStyle.UNDECORATED); primaryStage.show(); } catch (Exception e){ System.out.println(e); } } Hey guys this is my code and its my first time on stack overflow and why I am getting this exception? java.sql.SQLException: Before start of result set A: UPDATE is a reserved word, so your DB objects should not use it. You can: change the table name (i 'd prefer this) use quotes every time to refer to that table
{ "pile_set_name": "StackExchange" }
Q: CakePHP 1.3 URLs not working I'm having a problem with CakePHP 1.3 while transferring it from Nginx to Apache, as I said in the title the URLs don't work apart from the home page. Also, I've made some changes to CakePHP so the directory structure is slightly different. It looks like this: files app lib plugins vendor webroot This is my .htaccess file which resides inside 'webroot': <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] </IfModule> Any suggestions? A: Enable mod rewrite from the command line, like this: a2enmod rewrite
{ "pile_set_name": "StackExchange" }
Q: How to convert a struct to a different struct with fewer fields I am trying to copy a struct of type Big to type Small without explicitly creating a new struct of type Small with the same fields. I have tried searching for other similar problems such as this and this yet all the conversions between different struct types happen only if the structs have the same fields. Here is an example of what I tried to do: // Big has all the fields that Small has including some new ones. type Big struct { A int B string C float D byte } type Small struct { A int B string } // This is the current solution which I hope to not use. func ConvertFromBigToSmall(big Big) Small { return Small{ A: big.A, B: big.B, } } I expected to be able to do something like this, yet it does not work: big := Big{} small := Small(big) Is there a way of converting between Big to Small (and maybe even vice-versa) without using a Convert function? A: There is no built-in support for this. If you really need this, you could write a general function which uses reflection to copy the fields. Or you could redesign. If Big is a Small plus some other, additional fields, why not reuse Small in Big? type Small struct { A int B string } type Big struct { S Small C float D byte } Then if you have a Big struct, you also have a Small: Big.S. If you have a Small and you need a Big: Big{S: small}. If you worry about losing the convenience of shorter field names, or different marshalled results, then use embedding instead of a named field: type Big struct { Small // Embedding C float D byte } Then these are also valid: Big.A, Big.B. But if you need a Small value, you can refer to the embedded field using the unqualified type name as the field name, e.g. Big.Small (see Golang embedded struct type). Similarly, to create a Big from a Small: Big{Small: small}.
{ "pile_set_name": "StackExchange" }
Q: How to share resources between unit test and instrumentation test in android? I'm following this post, http://blog.danlew.net/2015/11/02/sharing-code-between-unit-tests-and-instrumentation-tests-on-android/, to share code, but how to share an asset?, like a fixture file?, I want to mock an api response, so I have a JSON file to do it, but I try this: https://gist.github.com/nebiros/91a68aaf6995fa635507 In Unit Test, this works: ClassLoader.getSystemResourceAsStream("some_response.json"); but in Android Intrumentation Tests, it doesn't, where can I put those fixture files?. A: I found this way, to share fixture files from test to androidTest: Add your fixture files to the resources folder of your test one, here: src/test/resources. Add test resources folder to androidTest, resources.srcDirs += ['src/test/resources'], here's an example: android { sourceSets { String sharedTestJavaDir = 'src/sharedTest/java' test { java.srcDirs += [sharedTestJavaDir] } androidTest { java.srcDirs += [sharedTestJavaDir] resources.srcDirs += ['src/test/resources'] } } } Access fixture files from your androidTest env this way: this.getClass().getClassLoader().getResourceAsStream(filename);
{ "pile_set_name": "StackExchange" }
Q: "He was so desperate that he would have given anything" vs. "that he did give anything" A: I heard he promised to buy her anything she wants. B: Right. He was so desperate that he would have given anything to win her over. In sentence B, instead of "would have given," is "did give" correct as well? Why is "would have given" more appropriate? A: Would have given is not just ‘more appropriate’. It’s the only possible construction in this context. One of the uses of the modal verb would is to express what is called ‘unreal meaning’. It is not the case that he actually did give anything. The speaker is imagining a situation in which ‘giving anything’ might be possible.
{ "pile_set_name": "StackExchange" }
Q: Favorite - unfavorite buttons and animations I'm designing a web app that allows registered users to favorite / unfavorite quotes. I'm not sure if I have a comprehensive approach for a user. You can view or download a short movie clip that shows how the UI reacts when favoriting and suppressing a quote from favorites. For your information, I'm removing a quote from my favorites first and then I add a quote to my favorites. I want to have your thoughts on my approach and how I can improve the user experience. A: Your animation is weird. I think it will confuse the user. The classic star/heart filled when you favorite the associated quote is the best way. For instance, if you see this icon: "♡", and then this icon "❤", you will understand that the second is favorites. The best way is always the most understandable way. If you want to add an animation, you can change the border on mouseover, and fill the heart/star on the click.
{ "pile_set_name": "StackExchange" }
Q: How do i use the % placeholder to write something in python? I have been asked to use the % placeholder to write something in python. I don't know how to do it can you help. A: The formatting you're looking to use is as follows: Say you want to place two variables, name = 'Randy' age = 55 into a string. You would use the following syntax "Howdy, %s. You are %s years old." % (name, age) This will place your two variables within the string and return this: "Howdy, Randy. You are 55 years old." However, this formatting method has become outdated. Once strings require several parameters, it will quickly become less readable. Python now prefers that you use the following format: "Howdy, {}. You are {} years old.".format(name, age)" Which will also return "Howdy, Randy. You are 55 years old." There are also some neat tricks, like using dictionaries to store your variables and format the string from there, like such. person = {'name': 'Randy', 'age':55} "Howdy, {name}. You are {age} years old.".format(**person) Which will return the same sentence as above, and is easily readable. It also tells the code user what variables are supposed to be placed where which helps in making sense of your code. Hope this helped, good luck and happy coding!
{ "pile_set_name": "StackExchange" }
Q: CSS id don't work I can't see what is wrong with this. I have 2 HTML sheets and a CSS sheet. The first HTML sheet (index.html) is like this: <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <link href='http://fonts.googleapis.com/css?family=Cedarville+Cursive' rel='stylesheet' type='text/css'> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Olive</h1> <a href="page1.html">Enter</a> </body> </html> The second HTML sheet (page1.html) is this: <!DOCTYPE> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <link href='http://fonts.googleapis.com/css?family=Cedarville+Cursive' rel='stylesheet' type='text/css'> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <div> <p id="prenav">Olive</p> </div> </body> </html> And the CSS external sheet: body { background-color: olive; } h1 { font-family: 'Cedarville Cursive', cursive; font-size: 230px; text-align: center; padding: 0px; } a { display: block; text-align: center; font-family: 'Cedarville Cursive', cursive; color: white; font-size: 100px; padding: 0px; text-decoration: none; } #prenav { font-family: 'Cedarville Cursive', cursive; font-size: 50px; color: white; } The issue is that the id from the second HTML sheet (page1.html) doesn't work. I don't know why. I don't know if it's the syntaxis or what. The body attributes are working in page1.html, but the id attributes don't. The <p> element only appears with any style. Could someone tell me what's wrong with this? A: Not sure if this is the issue, but your first line should be: <!DOCTYPE html> If you don't declare it properly, your browser could render in quirks mode which can result in all sorts of odd behavior. A: Few tips for debugging... try to make cache refresh few times when you have modified your css styles (with chrome and windows: ctrl+shift+r) then if it doesnt work try to use code below and cache refresh again: #prenav { font-family: 'Cedarville Cursive', cursive !important; font-size: 50px !important; color: white !important; } The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. Code: <!DOCTYPE html> <html> <head> <link href='http://fonts.googleapis.com/css?family=Cedarville+Cursive' rel='stylesheet' type='text/css'> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <style type="text/css"> body { background-color: olive; } h1 { font-family: 'Cedarville Cursive', cursive; font-size: 230px; text-align: center; padding: 0px; } a { display: block; text-align: center; font-family: 'Cedarville Cursive', cursive; color: white; font-size: 100px; padding: 0px; text-decoration: none; } #prenav { font-family: 'Cedarville Cursive', cursive; font-size: 50px; color: white; } </style> </head> <body> <div> <p id="prenav">Olive</p> </div> </body> </html> Edit: Solution was to put .css stylesheet to correct folder. Cheers.
{ "pile_set_name": "StackExchange" }
Q: Neurotransmitters appearance in the evolutionary process Recently I disagreed with the assumption, that lots of neurotransmitters came within recent 10,000 years of Homo Sapiens evolution. Judging from the available information sources, there is possibility of minor changes of brain reaction on neurotransmitters, but first assumption seems like nonsense for me. So, are there any neurotransmitters, appeared only in human evolution history? Then, are there reliable sources which will connect the appearance and development of biological species with appearance of neurotransmitters? At last, are there significant acceleration of human brain evolution within last 10,000 years, connected with social processes or brain evolution for Humans occurring more gradually? A: Neurobiology and Evolution are not exactly my field of expertise, but I'll try to answer anyway. Are there any neurotransmitters that appeared only in human evolution history? Probably not. The common human neurotransmitters we know of, are also found in other animals. More surprisingly, most of them are also found in organisms with no nervous-system, such as microorganisms and plants. This has even led some to advocate the change of the name neurotransmitters to biomediaters (Roshchina, 2010). It is believed that most of the changes in the nervous system occur at the circuitry level, and are not the introduction of new types of neurotransmitters. For example, Venter et al (1988) write: The presence of hormones, neurotransmitters, their receptors and biosynthetic and degradative enzymes is clearly not only associated with the present and the recent past but with the past several hundred million years. Evidence is mounting which indicates substantial conservation of protein structure and function of these receptors and enzymes over these tremendous periods of time. These findings indicate that the evolution and development of the nervous system was not dependent upon the formation of new or better transmitter substances, receptor proteins, transducers and effector proteins but involved better utilization of these highly developed elements in creating advanced and refined circuitry. And Winer and Larue (1996) write: Many features in the mammalian sensory thalamus, such as the types of neurons, their connections, or their neurotransmitters, are conserved in evolution. However, it is important to remember that there are changes related to the neurotransmitters and how they are used in the brain. For example, Burki and Kaessmann (2004) showed that one gene encoding the enzyme glutamate dehydrogenase, which is important in the neurotransmitter glutamate recycling process has appeared less than 23 million years ago in our evolution. Grailhe et al (2001) show that one type of Serotonin recceptor has disappeared somewhere in the evolution between rodents and humans. References Roshchina, V. V. (2010). Evolutionary considerations of neurotransmitters in microbial, plant, and animal cells. In Microbial Endocrinology (pp. 17-52). Springer New York. Venter, J. C., Di Porzio, U., Robinson, D. A., Shreeve, S. M., Lai, J., Kerlavage, A. R., ... & Fraser, C. M. (1988). Evolution of neurotransmitter receptor systems. Progress in neurobiology, 30(2-3), 105. Winer, J. A., & Larue, D. T. (1996). Evolution of GABAergic circuitry in the mammalian medial geniculate body. Proceedings of the National Academy of Sciences, 93(7), 3083-3087. Burki, F., & Kaessmann, H. (2004). Birth and adaptive evolution of a hominoid gene that supports high neurotransmitter flux. Nature genetics, 36(10), 1061-1063. Grailhe, R., Grabtree, G. W., & Hen, R. (2001). Human 5-HT5 receptors: the 5-HT5A receptor is functional but the 5-HT 5B receptor was lost during mammalian evolution. European journal of pharmacology, 418(3), 157-167.
{ "pile_set_name": "StackExchange" }
Q: How to translate .PDF files using google APIs? How to translate .PDF files using google APIs? (translate from language the pdf's are to for example russian (new pdf file orplain text or html).) (code example needed) A: You could link the PDFs to http://translate.google.com/translate?hl=fr&sl=auto&tl=en&u=http://www.example.com/PDF.pdf The query paramaters: hl: original language tl: language to translate to u: URL for PDF If you would like to use the AJAX API I guess you first need to extract the text content from the PDF with some PHP and then translate it with Googles AJAX API for translation.
{ "pile_set_name": "StackExchange" }
Q: Android: Not able to get location name from Google Geocoding API I'm trying to get location name from Latitude and Longitude using google reverse Geocoding API. and I'm getting error. Here is Code I'm using : Geocoder geocoder= new Geocoder(MainActivity.this, Locale.ENGLISH); try { //Place your latitude and longitude List<Address> addresses = geocoder.getFromLocation(37.423247,-122.085469, 1); TextView myAddress=(TextView)findViewById(R.id.textView1); if(addresses != null) { Address fetchedAddress = addresses.get(0); StringBuilder strAddress = new StringBuilder(); for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) { strAddress.append(fetchedAddress.getAddressLine(i)).append("\n"); } myAddress.setText("I am at: " +strAddress.toString()); } else myAddress.setText("No location found..!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this,"Could not get address..!", Toast.LENGTH_LONG).show(); } Log file FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.get_mobiile_location/com.example.get_mobiile_location.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5103) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.example.get_mobiile_location.MainActivity.getMyLocation(MainActivity.java:79) at com.example.get_mobiile_location.MainActivity.onCreate(MainActivity.java:53) at android.app.Activity.performCreate(Activity.java:5133) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) ... 11 more Please check what I'm doing wrong. A: Based on the log java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 In the below line you are getting 0 addresses for the given lat,long values List<Address> addresses = geocoder.getFromLocation(37.423247,-122.085469, 1); So to avoid the crash check the condition before accessing data from it as follows if(addresses != null&&addresses.size()>0) { //fetch data from addresses }else{ //display Toast message } UPDATE : And add following permissions if you forgot anyone <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="android.permission.INTERNET" /> Refer following tutorial http://karanbalkar.com/2013/11/tutorial-63-implement-reverse-geocoding-in-android/ Hope this will helps you.
{ "pile_set_name": "StackExchange" }
Q: Momentjs , How to skip sunday? I have a condition where i have to send start and end date to a child component from parent component. In simple, i will send a start date and end date to the child component. The end date will be added to the start date (can be 3, 5, 7). i.e if start date is 2016-01-01 (and variable to add is 3) the end date is 2016-01-03. However, i need to take in account another condition where i have to skip Sunday. Lets say if 2016-01-02 is a sunday then the end date should be 2016-01-04. The start date is initalized in getInitialState() getInitialState(){ variable_to_add:5, start_date: moment().format("YYYY-MM-DD"), } componentDidMount(){ this.setState({end_date:moment().add(Number(variable_to_add),'day').format("YYYY-MM-DD") } render(){ return <CallChild start_date={this.state.start_date} end_date={this.end_date} }, Any suggesetions to accomplish or improve the code above will be highly appreciated. A: I ended up using Pure Javascript with hints found in another page of Stack overflow Link. formatDate:function(date) { var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), year = d.getFullYear(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; return [year, month, day].join('-'); }, addWeekdays:function(date, days) { var days = days-2; date.setDate(date.getDate()+2); var counter = 0; if(days > 0 ){ while (counter < days) { date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow var check = date.getDay(); // turns the date into a number (0 to 6) if (check == 0) { // Do nothing it's the weekend (0=Sun & 6=Sat) } else{ counter++; // It's a weekday so increase the counter } } } return this.formatDate(date); }, My getInitailState looks like this: getInitialState: function() { return { date_from: moment().isoWeekday(1).format("YYYY-MM-DD"), no_of_items : 7, start_date: moment().add(2,'day').format("YYYY-MM-DD"), value:0, }; }, And my Render function looks like: render(){ return <DayMenu weekday={(item.weekday).toString()} color={this.getRandomColor()} dataItem={dataItem} start_date={this.state.start_date} end_date={this.addWeekdays(new Date(this.state.start_date),this.state.no_of_items)}/>
{ "pile_set_name": "StackExchange" }
Q: flask + angularjs: ng-include is 404'ing I've been trying like mad to get angularjs' ng-include to work properly with a Flask application, and it seems like no matter what I try, the GET keeps returning 404'd. The main page (angular_test.html) loads up fine, but nothing from angular_entry.html. Flask: basedir = c.get('basedir') app = Blueprint('angulartest', __name__, static_folder=basedir+'/display/static', template_folder=basedir+'/display/angulartemplates') def before_blueprint_request(): g.user = current_user app.before_request(before_blueprint_request) @app.route('/angular_test.html', methods=['GET']) def ang_test(): print 'testing angular' return make_response(open(basedir+'/display/templates/angular_test.html').read()) # # return app.send_static_file('angular_test.html') (I've tried both) HTML: <div id='content' ng-app='FeedEaterApp' ng-controller='MainController'> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <div ng-include src="'angular_entry.html'"></div> <div ng-include src="template.url"></div> <div ng-include="'angular_entry.html'"></div> <div ng-include="template.url"></div> </div> JS: app.controller("MainController", function($scope){ $scope.message = 'this is a message from scope!~' $scope.templates = [ { name: 'template1.html', url: 'angular_entry.html'}, { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; }); I've also tried every single relative/absolute path I can think of, and still nothing but 404s. I've also tried changing around the static and template folders in Flask. No dice. Is Flask interfering with the GET on angular_entry.html? Is my application root path not set correctly or something? help! A: It's not possible to tell fully without knowing what c is or what it's get method does, but the most likely possibility is that you are mis-using the templates argument to flask.Blueprint. If you want to expose the templates to Angular they need to be accessible over HTTP. Flask's templates are fed through the Jinja templating engine on the server side via render_template and are not exposed to the end user over HTTP directly. If that is the issue you will want to move angulartemplates under static and change your include paths to properly reference /static/angularetemplates/{your_template_name} (you can also remove the keyword argument templates in your Blueprint initializer).
{ "pile_set_name": "StackExchange" }
Q: Cropping or centering image in Swift I have an image in an UIImageView. There are grey portions above and below the image because the image size doesn't have the same size as UIImageView. How can I crop or zoom the image in such a way that it just fits to cover the grey area above and below, or left and right? A: you should set imageview's contentmode to UIViewContentMode.ScaleAspectFill and you should set propert clipsToBounds of imageview to true. by this you will not get that gray space and image will fit in entire imageview.!!
{ "pile_set_name": "StackExchange" }