date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/17
1,429
3,603
<issue_start>username_0: I am new to python and I have search a lot about this issue. I know there is a way of converting tuples to a list, but somehow it doesn't work for me. Here is my issue. Say I have: ``` l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] ``` Then say I have another list of: ``` l_all = ['l_1','l_2','l_3'] ``` How can I convert it(l\_all) to a list of ``` [['a','b','c'],['e','f','g'],['g','h','i']] ``` I tried ast package using ast.literal\_eval, but I received this error: > > ValueError: malformed node or string: <\_ast.Name object at > 0x00000172CA3C5278> > > > I also tried to use json package, still no luck. I tried just output `ast.literal_eval('l_1')`, not working either. I'd really appreciate if anyone can help on this. Thanks a lot!<issue_comment>username_1: You can use a dictionary to store the list names and each associated list: ``` d = {'l_2': ['e', 'f', 'g'], 'l_3': ['g', 'h', 'i'], 'l_1': ['a', 'b', 'c']} l_all = ['l_1','l_2','l_3'] final_results = [d[i] for i in l_all] ``` Output: ``` [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] ``` However, to actually access the lists via variable name, you would have to use `globals`: ``` l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] l_all = ['l_1','l_2','l_3'] new_l = [globals()[i] for i in l_all] ``` Output: ``` [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] ``` Upvotes: 2 <issue_comment>username_2: You can use [`locals()`](https://docs.python.org/3/library/functions.html#locals) ``` l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] l_all = ['l_1', 'l_2', 'l_3'] all_local_variables = locals() l_all_values = [all_local_variables[i] for i in l_all] ``` And you should be aware that you can get `KeyError` if no such variable present in current scope, for that you can `all_local_variables.get(i)`, that will return `None` if not present or set default as `all_local_variables.get(i, 'default')` Upvotes: 0 <issue_comment>username_3: That sounds like a problem that should be fixed upstream `ast.literal_eval` evaluates *literals*. `eval` is just 1) cheating and 2) so dangerous I wouldn't recommend it at all. Anyway, you could scan global then local variables using global & local dicts in a list comprehension: ``` l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] l_all = ['l_1','l_2','l_3'] l_all = [globals().get(x,locals().get(x)) for x in l_all] ``` result: ``` [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] ``` `globals().get(x,locals().get(x))` is a quick & dirty code to first look in global vars & fallback to local vars if not found. It could be overcomplicated for your needs. Upvotes: 2 <issue_comment>username_4: The simplest way to do this is to evaluate your strings in l\_all. Something like this ``` >>> l_1 = ['a','b','c'] >>> l_2 = ['e','f','g'] >>> l_3 = ['g','h','i'] >>> l_all = ['l_1','l_2','l_3'] >>> [ eval(x) for x in l_all ] ``` The output is ``` [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] ``` Upvotes: 0 <issue_comment>username_5: > > Then say I have another list of: > > > `l_all = ['l_1','l_2','l_3']` > > > Let's say you don't create this using strings, and use the list variables directly You can then get the wanted output ``` l_all = [l_1,l_2, l_3] ``` Upvotes: 1 <issue_comment>username_6: You can simply do: ``` l_1 = ['a','b','c'] l_2 = ['e','f','g'] l_3 = ['g','h','i'] l_all = ['l_1','l_2','l_3'] print(list(map(lambda x:globals()[x],l_all))) ``` output: ``` [['a', 'b', 'c'], ['e', 'f', 'g'], ['g', 'h', 'i']] ``` Upvotes: 1
2018/03/17
635
2,463
<issue_start>username_0: i have a sqlalchemy query which renders a template with a couple of settings. below you can find very simplified code to give an idea of what is going on. This code puts a checkbox field for a setting on every page, and there is no fixed nr of settings at the moment, it depends on the size of the table. As far as the pagination goes, this works fine. I can go to next and previous page. The submit button on the page only posts the checkbox value of the last page. Is it possible to also remember and/or save the input from all pages, not just the last page? ``` @app.route('/settings') def settings(): page = request.args.get('page', 1, type=int) settings = Settings.query.paginate(page, 1, False) next_url = url_for('settings', page=settings.next_num) \ if settings.has_next else None prev_url = url_for('settings', page=settings.prev_num) \ if settings.has_prev else None inputtype = 'checkbox' return render_template("settings.html", settings = settings, inputtype = inputtype, next_url = next_url, prev_url = prev_url ) ``` template would be something like this. ``` {% for setting in settings %} {% if prev\_url %} [Previous]( {{ prev_url }} ) (% endif %} {% if next\_url %} [Next]( {{ next_url }} ) {% endif %} ```<issue_comment>username_1: I get the feeling that if you submit you only submit the settings on the current page. Only the current settings are on the page and it would not make much sense to add all of them to the page. I think that what you want is not possible on multiple pages if you use links to got to the previous and next settings. If you make a change on page 1 and then click next the changes made on page 1 are not saved anywhere so they are lost. Maybe it is possible to make previous and next also post to settings. This way you get the settings from that page and can make a temporary settings object that you can process when you click commit. Upvotes: 2 [selected_answer]<issue_comment>username_2: I fixed this without using javascript. I came across this answer and seems to do the trick. It simply does a post request and jumps to the next page. @hugo, thanks for your answers, it certainly helped me looking in the right direction. [Cannot Generate a POST Request on Flask using url\_for](https://stackoverflow.com/questions/30464304/cannot-generate-a-post-request-on-flask-using-url-for) Upvotes: 0
2018/03/17
458
1,800
<issue_start>username_0: I downloaded the source of bootstrap into my application using yarn ``` yarn install boostrap ``` I tried just importing the bootstrap-grid.css in my application, and when I copied the starter example the look had no grid layout style applied to it. > > <https://getbootstrap.com/docs/4.0/examples/pricing/> > > > When I added the entire boostrap.css it worked fine. So what else other than bootstrap-grid should I be importing to get the layout/grid components?<issue_comment>username_1: The pricing example uses card-deck and cards, not the grid. If you want cards, you need to use `bootstrap.css`. `bootstrap-grid.css` works specifically for the [grid system](https://getbootstrap.com/docs/4.0/layout/grid/). Upvotes: 2 [selected_answer]<issue_comment>username_2: The below files worked for me. I am not sure if this is documented anywhere. ``` functions.scss variables.scss mixins.scss reboot.scss _grid.scss ``` Upvotes: 0 <issue_comment>username_3: To complete the answer from username_2, you should also import the `$grid-gutter-width` variable so that you will be able to set a gutter on your project's grid if needed. There are other variables that you may want to set up that the grid system is using, for them please refer to the official documentation and you should be able to add them like the following example: ``` /*------------------------------------*\ Grid gutter \*------------------------------------*/ $grid-gutter-width: 0 !default; /*------------------------------------*\ Bootstrap file imports \*------------------------------------*/ @import "~bootstrap/scss/functions"; @import "~bootstrap/scss/variables"; @import "~bootstrap/scss/mixins"; @import "~bootstrap/scss/reboot"; @import "~bootstrap/scss/grid"; ``` Upvotes: 0
2018/03/17
998
3,429
<issue_start>username_0: Let's say I have some records as below: ``` { id: 1, age: 22, name: 'A', class: 'Y' }, { id: 2, age: 25, name: 'B', class: 'D' }, { id: 3, age: 30, name: 'C', class: 'Y' }, { id: 4, age: 40, name: 'D', class: 'B' } ``` Now I need to get the last (closest) record which has an age less than 28. For this, I can use the following code: ``` const firstUsersYoungerThan28 = await Users.find({ class: 'C', age: { $lt: 28 } }) .sort({ age: -1 }) .limit(1) .lean(); const firstUserYoungerThan28 = firstUsersYoungerThan28[0]; ``` Let's say the collection have millions of records. My question is, is this the most efficient way? Is there a better way to do this? My biggest concern is, does my app load the records to the memory in order to sort them in the first place?<issue_comment>username_1: See the documentation about [`cursor.sort()`](https://docs.mongodb.com/manual/reference/method/cursor.sort/): > > ### Limit Results > > > You can use sort() in conjunction with limit() to return the first (in > terms of the sort order) k documents, where k is the specified limit. > > > If MongoDB cannot obtain the sort order via an index scan, then > MongoDB uses a top-k sort algorithm. This algorithm **buffers the first > k results** (or last, depending on the sort order) seen so far by the > underlying index or collection access. If at any point the memory > footprint of these k results exceeds 32 megabytes, the query will > fail. > > > Make sure that you have an index on `age`. Then when MongoDB does the sorting, it will only keep the first `k` (in your case, 1) results in memory. MongoDB can handle millions of documents for such basic queries, don't worry. Just make sure that you do have the proper indexes specified. Upvotes: 3 [selected_answer]<issue_comment>username_2: You should create an index with the following properties: 1. The index filters everyone with an age below 28 2. The index sorts by currentMeterReading. This type of index is a partial index. Refer to the [documentation about partial indexes](https://docs.mongodb.com/manual/core/index-partial/) and [using indexes for sorting](https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/) for more information. The following index should do the trick: `db.users.createIndex( { age: -1, currentMeterReading: -1}, { partialFilterExpression: { age: {$lt: 28} } )` Without the index, a full scan would probably be in order which is very bad for performance. With the index, only the columns you specified will be stored in memory (when possible) and searching them would be much faster. Note that MongoDB may load the values of the index lazily instead of on index creation in some or all cases. This is an implementation choice. As far as I know, there's no way to create an index with only the last record in it. If you want to understand how databases work you have to understand how [indexes](https://en.wikipedia.org/wiki/Database_index) work, specifically [B-Trees](https://en.wikipedia.org/wiki/B-tree). B-Trees are very common constructs of all databases. [Indexes do have their disadvantages](https://stackoverflow.com/questions/41410482/what-are-the-disadvantages-to-indexes-in-database-tables) so don't create one for each query. Always measure before creating an index since it might not be necessary. Upvotes: 0
2018/03/17
556
1,719
<issue_start>username_0: I have the following element that is transitioning from left to right, how do I get it to transition from right to left without any gaps between the element and the right of the page. ```css @keyframes slideInFromLeft { 0% { transform: translateX(-100%); } 100% { transform: translateX(0); } } header { /* This section calls the slideInFromLeft animation we defined above */ animation: 5s ease-out 0s 1 slideInFromLeft; z-index: 1; background: #333; padding: 30px; position: fixed; top: 10%; color: #fff; } ``` ```html Test ``` Fiddle here: <https://jsfiddle.net/yy3qtbef/1/>.<issue_comment>username_1: If I correctly understand your question, Add ``` right: 20px ``` to the .header class and change - ``` translateX(-100%) ``` to ``` translateX(100%) ``` Here is the demo - <https://jsfiddle.net/r0jf2a1y/> Upvotes: 2 <issue_comment>username_2: To remove the undesired gap, you need to get rid of the *default margin* with the `margin: 0` (or you can give it to the *body element*), to slide it from the *right*, position it there with the `right: 0`, and change the value of the `transform` property to `translateX(100%)`, which will make sure that the element is off the screen before it slides to the left: ```css header { animation: 5s ease-out 0s 1 slideInFromRight; z-index: 1; background: #333; margin: 0; /* added */ padding: 30px; position: fixed; top: 10%; right: 0; /* added */ color: #fff; } @keyframes slideInFromRight { 0% { transform: translateX(100%); /* modified */ } 100% { transform: translateX(0); } } ``` ```html Test ``` Upvotes: 2 [selected_answer]
2018/03/17
549
1,801
<issue_start>username_0: I have some texture - a square picture with the painted bricks. And I want to create the element I will use as an obstacles - usual platformer's walls - in my game. So, I can't understand, how can I create this game object? For example, in 3D I can jus to create an object - for example, cube - and drag'n'drop my texture to this object. But in 2D I can't do the same steps. In 2D, as I understand, I need to create a new game object - sprite - and... what next? Drag'n'drop in this case doesn't work, sprite renderer has some fields I think I need to use - 'Sprite' and 'Matherial", but I can't understand, what exactly I need to do with my texture to have the ability use it here and how exectly I need to use it.<issue_comment>username_1: If I correctly understand your question, Add ``` right: 20px ``` to the .header class and change - ``` translateX(-100%) ``` to ``` translateX(100%) ``` Here is the demo - <https://jsfiddle.net/r0jf2a1y/> Upvotes: 2 <issue_comment>username_2: To remove the undesired gap, you need to get rid of the *default margin* with the `margin: 0` (or you can give it to the *body element*), to slide it from the *right*, position it there with the `right: 0`, and change the value of the `transform` property to `translateX(100%)`, which will make sure that the element is off the screen before it slides to the left: ```css header { animation: 5s ease-out 0s 1 slideInFromRight; z-index: 1; background: #333; margin: 0; /* added */ padding: 30px; position: fixed; top: 10%; right: 0; /* added */ color: #fff; } @keyframes slideInFromRight { 0% { transform: translateX(100%); /* modified */ } 100% { transform: translateX(0); } } ``` ```html Test ``` Upvotes: 2 [selected_answer]
2018/03/17
464
1,699
<issue_start>username_0: I have an `ArrayList` which I want to transform into a JSON array of objects. How can I transform it? Array is of type `Kunde`: ``` public class Kunde { private String knr; private String name1; private String name2; private String anrede; private String strasse; private String plz; private String ort; private String erfdat; private String telefon; private String fax; private String handy; private String lastbes; private String email; private String land; ``` for each member variable there is a getter and a setter. I store it like this: ``` List Kunden = new ArrayList(); ``` My JSON should look like this: ``` { "kunden": [ {"name1": "hans", "name2": "peter"}, {...} ] } ```<issue_comment>username_1: Try to do something like this ``` ArrayList list = new ArrayList(); list.add("yo"); list.add("yo"); JSONArray jsArray = new JSONArray(list); ``` Upvotes: -1 <issue_comment>username_2: Play comes with `play-json` module which can do it. You might have to create a wrapping class to output the `kunden` root node: ``` public class Kunden { private List kunden; // getter and setter } Kunden root = new Kunden(); kunden.setKunden(...); JsonNode rootNode = Json.toJson(root); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node); ``` Note that `ObjectMapper` is used to pretty print. See the official Play Framework 2.6.X docs: [Mapping Java objects to JSON](https://www.playframework.com/documentation/2.6.x/JavaJsonActions#Mapping-Java-objects-to-JSON). Upvotes: 2 [selected_answer]
2018/03/17
586
2,429
<issue_start>username_0: I'm using FOS UserBundle in my Symfony 3.3 Project and I have two firewalls , because Admins and Users connect from different login forms (with different URLs). I would like to restrict access to admin dashboard only if the account used for logging is granted to ADMIN\_ROLE. That is, if I try to authenticate with a simple user account, I get the message "Bad credentials". Is there a way to tell a firewall to only allow users of a certain role to connect ? my security.yml firewalls section : ``` firewalls: admin: pattern: ^/admin form_login: provider: fos_userbundle csrf_token_generator: security.csrf.token_manager login_path: /admin check_path: /admin/login_check default_target_path: /admin success_handler: app.security.adminauthentication_handler failure_handler: app.security.adminauthentication_handler logout: path: /admin/logout target: /admin anonymous: true context: application main: pattern: ^/ form_login: provider: fos_userbundle csrf_token_generator: security.csrf.token_manager success_handler: app.security.authentication_handler failure_handler: app.security.authentication_handler logout: true anonymous: true ``` Please note that I'm using AJAX for both login forms. Thanks<issue_comment>username_1: Try to do something like this ``` ArrayList list = new ArrayList(); list.add("yo"); list.add("yo"); JSONArray jsArray = new JSONArray(list); ``` Upvotes: -1 <issue_comment>username_2: Play comes with `play-json` module which can do it. You might have to create a wrapping class to output the `kunden` root node: ``` public class Kunden { private List kunden; // getter and setter } Kunden root = new Kunden(); kunden.setKunden(...); JsonNode rootNode = Json.toJson(root); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node); ``` Note that `ObjectMapper` is used to pretty print. See the official Play Framework 2.6.X docs: [Mapping Java objects to JSON](https://www.playframework.com/documentation/2.6.x/JavaJsonActions#Mapping-Java-objects-to-JSON). Upvotes: 2 [selected_answer]
2018/03/17
2,864
6,065
<issue_start>username_0: I'm building a cube with Python. I am going to use vbo and shader. but, Normal does not work. Where is the problem? and How should I coding it? ``` import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from ctypes import * from math import * pygame.init () screen = pygame.display.set_mode (( 800, 800), pygame.OPENGL|pygame.DOUBLEBUF, 24) glViewport (0, 0, 800, 800) glClearColor (0.0, 0.5, 0.5, 1.0) ##### shader def createAndCompileShader(type,source): shader=glCreateShader(type) glShaderSource(shader,[source]) glCompileShader(shader) return shader vertex_shader=createAndCompileShader(GL_VERTEX_SHADER,""" out vec4 result; vec3 light; vec4 color; void main(void) { light = vec3(1.5,1.5,1.5); color = vec4(0.5,0.5,0.5,0.1); vec4 V = gl_ModelViewMatrix * gl_Vertex; vec3 N = gl_NormalMatrix * gl_Normal ; //vec3 V = vec3(gl_ModelViewMatrix * gl_Vertex ); //vec3 N = vec3(gl_ModelViewMatrix * vec4(gl_Normal,0.0)); vec3 L = normalize( light - V.xyz ); float distance = length( light - V.xyz); //vec3 L = normalize( light - V); //float distance = length( light - V); float diffuse = max(dot(N, L),0.1); diffuse = diffuse * (1.0 /(1.0+(0.5*distance*distance))); result = color * (0.6+diffuse); gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } """) fragment_shader=createAndCompileShader(GL_FRAGMENT_SHADER,""" in vec4 result; void main(void) { gl_FragColor = result; } """) program=glCreateProgram() glAttachShader(program,vertex_shader) glAttachShader(program,fragment_shader) glLinkProgram(program) glUseProgram(program) ##### ''' vertices = [ 0.0,0.0,0.0,0.1,0.0,0.0,0.0,0.0,0.1, 0.1,0.0,0.0,0.1,0.0,0.1,0.0,0.0,0.1, 0.1,0.0,0.0,0.1,0.1,0.0,0.1,0.1,0.1, 0.1,0.1,0.1,0.1,0.0,0.1,0.1,0.0,0.0, 0.1,0.1,0.0,0.0,0.1,0.0,0.0,0.1,0.1, 0.0,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.0, 0.0,0.1,0.1,0.0,0.0,0.1,0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.1,0.0,0.0,0.1,0.1, 0.0,0.0,0.1,0.1,0.0,0.1,0.1,0.1,0.1, 0.1,0.1,0.1,0.0,0.1,0.1,0.0,0.0,0.1, 0.0,0.0,0.0,0.1,0.0,0.0,0.1,0.1,0.0, 0.0,0.0,0.0,0.0,0.1,0.0,0.1,0.1,0.0 ] normals = [ 0.0,-1.0,0.0, 0.0,-1.0,0.0, 1.0,0.0,0.0, 1.0,0.0,0.0, 0.0,1.0,0.0, 0.0,1.0,0.0, -1.0,0.0,0.0, -1.0,0.0,0.0, 0.0,0.0,1.0, 0.0,0.0,1.0, 0.0,0.0,-1.0, 0.0,0.0,-1.0 ] ''' vertices = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, # Left Side -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, # Left Side 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, # Back Side 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, # Bottom Side 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, # Back Side 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, # Bottom Side -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, # Front Side 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, # Right Side 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, # Right Side 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, # Top Side 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, # Top Side 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0 # Front Side ] normals= [ -1.0, 0.0, 0.0, # Left Side -1.0, 0.0, 0.0, # Left Side 0.0, 0.0, -1.0, # Back Side 0.0, -1.0, 0.0, # Bottom Side 0.0, 0.0, -1.0, # Back Side 0.0, -1.0, 0.0, # Bottom Side 0.0, 0.0, 1.0, # front Side 1.0, 0.0, 0.0, # right Side 1.0, 0.0, 0.0, # right Side 0.0, 1.0, 0.0, # top Side 0.0, 1.0, 0.0, # top Side 0.0, 0.0, 1.0, # front Side ] vbo1 = glGenBuffers(1) glBindBuffer (GL_ARRAY_BUFFER, vbo1) glBufferData (GL_ARRAY_BUFFER, len(vertices)*4, (c_float*len(vertices))(*vertices), GL_STATIC_DRAW) #glBindBuffer (GL_ARRAY_BUFFER, 0) vbo2 = glGenBuffers(1) glBindBuffer (GL_ARRAY_BUFFER, vbo2) glBufferData (GL_ARRAY_BUFFER, len(normals)*4, (c_float*len(normals))(*normals), GL_STATIC_DRAW) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90,1,0.01,1000) gluLookAt(1.5,1.5,1.5,0,0,0,0,1,0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == KEYDOWN: if event.key == K_RIGHT: glRotatef(3,0,1,0) elif event.key == K_LEFT: glRotatef(3,0,-1,0) elif event.key == K_UP: glRotatef(3,1,0,0) elif event.key == K_DOWN: glRotatef(3,-1,0,0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glShadeModel(GL_SMOOTH) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glMatrixMode(GL_MODELVIEW) glEnableClientState (GL_VERTEX_ARRAY) glBindBuffer (GL_ARRAY_BUFFER,vbo1) glVertexPointer (3, GL_FLOAT,0, None) glEnableClientState(GL_NORMAL_ARRAY) glBindBuffer (GL_ARRAY_BUFFER,vbo2) glNormalPointer (GL_FLOAT, 0 , 0) n = len(vertices)//3 glDrawArrays (GL_TRIANGLES, 0, n) glDisableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_VERTEX_ARRAY) pygame.display.flip () ``` [![enter image description here](https://i.stack.imgur.com/M8BAI.png)](https://i.stack.imgur.com/M8BAI.png) [![enter image description here](https://i.stack.imgur.com/BZFnH.png)](https://i.stack.imgur.com/BZFnH.png) [![enter image description here](https://i.stack.imgur.com/4ibZo.png)](https://i.stack.imgur.com/4ibZo.png)<issue_comment>username_1: Normals in OpenGL have to be defined for each vertex, not for each face. If you have a cube with 36 vertices, you also have to supply 36 normals. ``` vertices = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, # Left Side ... normals= [ -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, # Left Side ... ``` Upvotes: 1 <issue_comment>username_2: seems like you didn't enable the depth test ``` glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); ``` which can lead to strange results Upvotes: 1 [selected_answer]
2018/03/17
737
1,738
<issue_start>username_0: I have two tables ``` table: a --------------------- id amount status --------------------- 4031 3000 1 4032 4000 1 4033 5000 1 4034 6000 1 4035 7000 1 4036 8000 0 ``` ``` table: s -------------- id a_id b_id -------------- 1 4031 20 2 4031 21 3 4032 23 4 4032 24 5 4033 25 6 4033 26 7 4034 21 8 4034 20 9 4035 25 10 4035 29 11 4036 21 12 4036 20 ``` How do we get the sum of the a.amount where have ( b\_id = 20 AND b\_id = 21) AND a.status = 1? The answer should be 9000.<issue_comment>username_1: You can get the answer using a subquery: ``` SELECT SUM(a.amount) FROM a WHERE a.status=1 AND EXISTS (SELECT 1 FROM s WHERE s.a_id=a.id AND s.b_id in (20,21)); ``` There is no need to group the data as we want the global sum of the amounts selected. Upvotes: 0 <issue_comment>username_2: ``` SELECT SUM(amount) FROM ( JOIN s ON a.id = s.id WHERE STATUS =1 AND (b_id = 20 OR b_id = 21) GROUP BY a.id ) AS amounts ``` total : 9000 In the case you can add several times the same amount, I guess this should work without join: ``` SELECT SUM(amount) AS total FROM `a`, `s` WHERE a_id = a.id AND (b_id = 20 OR b_id = 21) AND status = 1 ``` total : 18000 Upvotes: 2 <issue_comment>username_3: Try this: ``` select sum(a.amount) from a join b on a.id = b.a_id where b.b_id IN ( 20, 21 ) and a.status = 1 ``` Upvotes: 0 <issue_comment>username_4: ``` SELECT SUM(a.amount) FROM a WHERE a.status=1 AND EXISTS (SELECT 1 FROM s WHERE s.a_id=a.id AND s.b_id=20) AND EXISTS (SELECT 1 FROM s WHERE s.a_id=a.id AND s.b_id=21) ; ``` Upvotes: 0
2018/03/17
444
1,658
<issue_start>username_0: I am getting: ``` org.testng.TestNGException: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:325) at org.testng.remote.AbstractRemoteTestNG.initialize(AbstractRemoteTestNG.java:136) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:97) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) ``` I am working on writing automation scripts using maven, testNG and selenium. when I execute my TestCases individually through RunAs-> TestNG, they execute fine . But when I try to run all the Test Cases as a suite by doing: right Click on Testng.xml-> RunAs TestNG suite. I get the above exception. I have tried various options so far, like upgrading the TestNG version(now using 6.10.0), importing the project again, changing the POM and TestNG files. Nothing has worked so far. I tried to Google this but could not find the answer for this issue. whatever solution is given online corresponds to SSL connection and I am not sure that that's my issue. Can anyone please help me with this issue? Thanks in advance!<issue_comment>username_1: The issue seems to be with the testng.xml. Make sure the first line of .xml file should be exactly as: the only issue here is "http" to be used instead of "https" Upvotes: 4 <issue_comment>username_2: Even i have faced similar issue but for me I have missed adding testNg library in my project build path, check and see if it helps. Upvotes: 0
2018/03/17
515
1,799
<issue_start>username_0: If I enter something into t1, t2 is changed. But if t2 already has manual input, it is not changed any more (and vice versa). How can I change an input field that has already an manual input with javascript (without reloading the page!)? ``` inputfields are not changed, if they have/had an input already! ```<issue_comment>username_1: The simple answer is use this: ```js function upd1() { t2.value = 'changed'; return true; } function upd2() { t1.value = 'changed'; return true; } ``` ```html t1: t2: ``` --- Value changes after you type in one of the inputs and press Enter. Because as said here: <https://www.w3schools.com/jsref/met_element_setattribute.asp> . --- *"The setAttribute() method adds the specified attribute to an element, and gives it the specified value. **If the specified attribute already exists, only the value is set/changed**."* Upvotes: -1 <issue_comment>username_2: You can also save an old value of each field to continue editing. Also it will show editing status on another field each time. It will be more comfortable for users. ```html inputfields are not changed, if they have/had an input already! let firstElValue = ''; let secondElValue = ''; function upd1() { let el = document.querySelector('#t2'); el.value = 'changed'; return true; } function upd2() { let el = document.querySelector('#t1'); el.value = 'changed'; return true; } function renderFirstEl() { let el = document.querySelector('#t1'); secondElValue = document.querySelector('#t2').value; el.value = firstElValue; } function renderSecondEl() { let el = document.querySelector('#t2'); firstElValue = document.querySelector('#t1').value; el.value = secondElValue; } ``` Upvotes: 0
2018/03/17
650
2,466
<issue_start>username_0: I used [php-telegram-bot/core](https://github.com/php-telegram-bot/core) to create a shopping bot in telegram. What I want to do is when a User make an order, bot send a notification that a new Order is come to admin of Channel. Suppose admin channel username is like `@admin_username` and stored in a global variable(means that may be change in a period of time). for that I wrote this : ``` static public function showOrderToConfirm ($order) { if ($order) { Request::sendMessage([ 'chat_id' => '@admin_username', 'text' => 'New Order registered', 'parse_mode' => 'HTML' ]); } } ``` But this does not work and does not anything.<issue_comment>username_1: Telegram bot API does not support sending messages using username because it's not a stable item and can be changed by the user. On the other hand, bots can only send messages to user that have sent at least one message to the bot before. You know that when a user sends a message to a bot (for example the users taps on the start button) the bot can get his/her username and ChatID (As you know ChatID is different from username; ChatID is a long number) so I think the best way that you can fix this issue is storing the chat IDs and related usernames in a database and send the message to that chatID of your favorite username. By the way, try searching online to see whether there is an API which supports sending messages to usernames or not. But as I know it's not possible. Upvotes: 2 <issue_comment>username_2: This example works very well: ``` php $token = 'YOUR_TOCKEN_HERE'; $website = 'https://api.telegram.org/bot' . $token; $input = file_get_contents('php://input'); $update = json_decode($input, true); $chatId = $update['message']['chat']['id']; $message = $update['message']['text']; switch ($message) { case '/start': $response = 'now bot is started'; sendMessage($chatId, $response); break; case '/info': $response = 'Hi, i am @trecno_bot'; sendMessage($chatId, $response); break; default: $response = 'Sorry, i can not understand you'; sendMessage($chatId, $response); break; } function sendMessage($chatId, $response){ $url = $GLOBALS['website'] . '/sendMessage?chat_id=' . $chatId . '&parse_mode=HTML&text=' . urlencode($response); file_get_contents($url); } ? ``` Upvotes: 0
2018/03/17
1,206
4,107
<issue_start>username_0: I try to install my app on Heroku. This app is a PHP/Laravel app with the "Passport" for the authentication. All is running fine in my local machine (MacOS). When I try to do a simple 'post' with Postman, I have this error : > > 2018-03-17T17:05:22.059708+00:00 app[web.1]: [17-Mar-2018 17:05:22 UTC] [2018-03-17 17:05:22] production.ERROR: Key path "file:///app/storage/oauth-private.key" does not exist or is not readable {"exception":"[object] (LogicException(code: 0): Key path "file:///app/storage/oauth-private.key" does not exist or is not readable at /app/vendor/league/oauth2-server/src/CryptKey.php:45)"} [] > > > To setup passport, I generated the keys with : > > php artisan passport:install > > > And I see the keys in my database in Heroku. So the command worked properly. So what is this error ? I tried also to regenerate the keys, to stop and restart the application. Without successes. Edit ---- In fact, the key files are not generated in the folder app/storage, that's why there is this error. But why these files are not generated?<issue_comment>username_1: The solution is here: <https://github.com/laravel/passport/issues/267> Add these few lines into your `composer.json` under the "scripts" property, then commit and deploy into Heroku: ``` "post-install-cmd": [ "php artisan clear-compiled", "chmod -R 777 storage", "php artisan passport:keys" ] ``` But, after that you have to delete the keys from the table "oauth-clients", then regenerate these keys with : ``` php artisan passport:install ``` Upvotes: 5 <issue_comment>username_2: About the @username_1 answer, It will log out your users with every deployment, so if you're really using Heroku and not Dokku (as in my case), I recommend you to generate the keys by using that command: php artisan passport:keys and then via Nano copy the keys generated in storage/oauth-public.key and storage/oauth-private.key into multiline env variables, then you can use this post install script in composer.json: > > "post-install-cmd": [ > "php artisan clear-compiled", > "chmod -R 777 storage", > "echo -n $OAUTH\_PRIVATE\_KEY > storage/oauth-private.key", > "echo -n $OAUTH\_PUBLIC\_KEY > storage/oauth-public.key" ] > > > That will regenerate the keys from ENV with every deployment and keep your users logged in. If that solution doesn't work, you could still [remove '/storage/\*.key' line from .gitignore](https://github.com/laravel/passport/issues/267#issuecomment-431686878) Upvotes: 2 <issue_comment>username_3: Laravel Passport has a configuration that allows to set public and private keys as environment variables. You can run `php artisan vendor:publish --tag=passport-config` on your local machine and commit the change. Then set `PASSPORT_PRIVATE_KEY` and `PASSPORT_PUBLIC_KEY` on Heroku config. Found from this [blog](https://blog.marco-marassi.com/posts/laravel-passport-heroku-oauth-private-key-does-not-exist-or-is-not-readable) Upvotes: 2 <issue_comment>username_4: My solution was quite straight forward: 1. go to your .gitignore file 2. comment out /storage/\*.key 3. re-deploy to heroku It appears that the oauth-keys are ignored by default in Laravel (v.7) Upvotes: 0 <issue_comment>username_5: **Loading Keys From The Environment** Alternatively, you may publish Passport's configuration file using the vendor:publish Artisan command: ``` php artisan vendor:publish --tag=passport-config ``` After the configuration file has been published, you may load your application's encryption keys by defining them as environment variables: ``` PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----" PASSPORT\_PUBLIC\_KEY="-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY-----" ``` [Passport documentation](https://laravel.com/docs/8.x/passport) Upvotes: 0 <issue_comment>username_6: I have a better solution to the problem that does not require making your keys public 1. connect to your heroku account via you terminal 2. Run heroku ps:exec 3. Run php artisan passport:keys Upvotes: 0
2018/03/17
1,031
3,864
<issue_start>username_0: In fluter, I have 2 tab pages that show different view. I wanted to have the floatingactionbutton to show only in one of the view and hidden in other tabs. But the floatingactionbutton stays floating even when the view is switched. Can anyone help me on this? If there is any code or tutorial, it would be appreciated.<issue_comment>username_1: You can create a list of FloatingActionButtons for each page. Call index method on the TabController variable to know the index of the tab that is active and use that to select a fab from the list. Don't forget to call addListener on the TabController variable. here is snippet code of how I did it: // in the main statefulwidget class ``` TabController tabController; var fabIndex; @override void initState() { super.initState(); tabController = new TabController(length: 3, vsync: this,initialIndex: 0); tabController.addListener(_getFab); fabIndex=0; } void dispose() { tabController.dispose(); super.dispose(); } final List fabs=[ new FloatingActionButton(child: new Icon(Icons.access\_time),onPressed: (){},), new FloatingActionButton(child: new Icon(Icons.account\_balance),onPressed: (){},), new FloatingActionButton(child: new Icon(Icons.add\_alert),onPressed: (){},) ]; void \_getFab(){ setState((){`enter code here` fabIndex=tabController.index; }); } ``` Use the fabIndex in the scaffold's floatingActionButton property as follows: ``` floatingActionButton: fabs[fabIndex], ``` Upvotes: 3 <issue_comment>username_2: demo pic: [tab1 show fab](https://i.stack.imgur.com/nGMjh.png) [tab2 hide fab](https://i.stack.imgur.com/czxUh.png) You can set floatingActionButton to null when `_selectedIndex == 0`, then FAB is gone with animation, so cool. And remember to change `_selectedIndex` in BottomNavigationBar onTap method. Here is the example code with some comments: ``` final _tabTitle = [ 'Title 1', 'Title 2' ]; // BottomNavigationBarItem title final _tabIcon = [ Icon(Icons.timer_off), Icon(Icons.timeline), ]; // BottomNavigationBarItem icon class _MyHomePageState extends State { int \_selectedIndex = 0; String title = \_tabTitle[0]; // tap BottomNavigationBar will invoke this method \_onItemTapped(int index) { setState(() { // change \_selectedIndex, fab will show or hide \_selectedIndex = index; // change app bar title title = \_tabTitle[index]; }); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title), ), body: Center( child: Text(\_tabTitle[\_selectedIndex]), ), // two tabs bottomNavigationBar: BottomNavigationBar( items: [ BottomNavigationBarItem(title: Text(\_tabTitle[0]), icon: \_tabIcon[0]), BottomNavigationBarItem(title: Text(\_tabTitle[1]), icon: \_tabIcon[1]) ], currentIndex: \_selectedIndex, onTap: \_onItemTapped, ), // key point, fab will show in Tab 0, and will hide in others. floatingActionButton: \_selectedIndex == 0 ? FloatingActionButton( onPressed: () {}, child: Icon(Icons.add), ) : null, ); } } ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: I would wrap the tab you want with a scaffold and give it a fab. ``` TabBarView( children:[ Text("tab1"), Scaffold(body:Text("tab2"), floatingActionButton: FloatingActionButton(...) ) ) ``` Upvotes: 0 <issue_comment>username_4: The easiest way is to just give your each tab it's own Scaffold as the top widget, and provide it's own FAB there (Instead of the Scaffold where each tabs are kept, the main Scaffold, place it individually inside every tab's Scaffold, and remove from the top Scaffold). If you already have one, you can wrap it inside another. But if you want to keep the FAB the same in every other screen except some, you then can follow other solutions written here. Upvotes: 1
2018/03/17
1,719
5,978
<issue_start>username_0: I want to use a SCNTechnique with Metal shaders in Swift Playgrounds on a SCNView. Therefore I tried compiling my shaders with the following code: ``` guard let metalDevice = sceneView.device else { return } if let path = Bundle.main.path(forResource: "distortTechnique", ofType: "metal") { do { let contents = try String(contentsOf: URL(fileURLWithPath: path)) do { try metalDevice.makeLibrary(source: contents, options: nil) } catch { error print(error) } } catch { // contents could not be loaded } } ``` The file is loaded but I get the following compiler error: ``` Error Domain=MTLLibraryErrorDomain Code=3 "Compilation failed: program_source:11:10: fatal error: 'SceneKit/scn_metal' file not found #include ^ " UserInfo={NSLocalizedDescription=Compilation failed: program\_source:11:10: fatal error: 'SceneKit/scn\_metal' file not found #include ^ } ``` So it seems like the »scn\_metal« library can't be found. Any idea how I can solve this? The same setup is running perfectly fine in an iOS App project. Here is the shader code: ``` #include using namespace metal; #include struct custom\_vertex\_t { float4 position [[attribute(SCNVertexSemanticPosition)]]; }; constexpr sampler s = sampler(coord::normalized, address::repeat, filter::linear); struct out\_vertex\_t { float4 position [[position]]; float2 uv; float time; float random; }; vertex out\_vertex\_t pass\_through\_vertex(custom\_vertex\_t in [[stage\_in]], constant SCNSceneBuffer& scn\_frame [[buffer(0)]]) { out\_vertex\_t out; out.position = in.position; out.uv = float2((in.position.x + 1.0) \* 0.5 , (in.position.y + 1.0) \* -0.5); out.time = scn\_frame.time; return out; }; fragment half4 pass\_through\_fragment(out\_vertex\_t vert [[stage\_in]], texture2d colorSampler [[texture(0)]]) { float4 fragment\_color = colorSampler.sample( s, vert.uv); return half4(fragment\_color); }; fragment half4 distort\_fragment(out\_vertex\_t vert [[stage\_in]], texture2d colorSampler [[texture(0)]]) { float multiplier = sin(vert.time \* 0.5); float effectRadius = 0.75; float effectAmount = 360. \* 2.; float effectAngle = multiplier \* effectAmount; effectAngle = effectAngle \* M\_PI\_F / 180; float2 resolution = float2(colorSampler.get\_width(), colorSampler.get\_height()); float2 center = float2(0.5, 0.5);//iMouse.xy / iResolution.xy; float2 uv = vert.position.xy / resolution - center; float len = length(uv \* float2(resolution.x / resolution.y, 1.)); float angle = atan2(uv.y, uv.x) + effectAngle \* smoothstep(effectRadius, 0., len); float radius = length(uv); float4 fragment\_color = colorSampler.sample(s, float2(radius \* cos(angle), radius \* sin(angle)) + center); return half4(fragment\_color); }; ``` Attached is an image of the playground. Thanks! [![enter image description here](https://i.stack.imgur.com/6p5Jy.jpg)](https://i.stack.imgur.com/6p5Jy.jpg)<issue_comment>username_1: I was able to get a metal shader working as an SCNProgram in a playground by including the contents of SCNMetalDefines at the top of the metal file. I'm not sure whether `scn_metal` has more to it than these defines. This had everything I needed for a vertex/fragment pipeline though. Could you post the code of your shaders? Or at least, could you tell us what the shader references in `scn_metal`? ``` #include using namespace metal; #ifndef \_\_SCNMetalDefines\_\_ #define \_\_SCNMetalDefines\_\_ enum { SCNVertexSemanticPosition, SCNVertexSemanticNormal, SCNVertexSemanticTangent, SCNVertexSemanticColor, SCNVertexSemanticBoneIndices, SCNVertexSemanticBoneWeights, SCNVertexSemanticTexcoord0, SCNVertexSemanticTexcoord1, SCNVertexSemanticTexcoord2, SCNVertexSemanticTexcoord3 }; // This structure hold all the informations that are constant through a render pass // In a shader modifier, it is given both in vertex and fragment stage through an argument named "scn\_frame". struct SCNSceneBuffer { float4x4 viewTransform; float4x4 inverseViewTransform; // transform from view space to world space float4x4 projectionTransform; float4x4 viewProjectionTransform; float4x4 viewToCubeTransform; // transform from view space to cube texture space (canonical Y Up space) float4 ambientLightingColor; float4 fogColor; float3 fogParameters; // x:-1/(end-start) y:1-start\*x z:exp float2 inverseResolution; float time; float sinTime; float cosTime; float random01; }; // In custom shaders or in shader modifiers, you also have access to node relative information. // This is done using an argument named "scn\_node", which must be a struct with only the necessary fields // among the following list: // // float4x4 modelTransform; // float4x4 inverseModelTransform; // float4x4 modelViewTransform; // float4x4 inverseModelViewTransform; // float4x4 normalTransform; // This is the inverseTransposeModelViewTransform, need for normal transformation // float4x4 modelViewProjectionTransform; // float4x4 inverseModelViewProjectionTransform; // float2x3 boundingBox; // float2x3 worldBoundingBox; #endif /\* defined(\_\_SCNMetalDefines\_\_) \*/ ``` Upvotes: 3 <issue_comment>username_2: I finally got it working by precompiling the metal library of an actual app project and then use the result default.metallib with the included shader functions in the playground. This seems necessary as the SCNTechnique documentation for the vertex and frag,ent »These functions must exist in the app’s default Metal library.« A bit hacky but works for my purpose. Concrete steps: - create a new app project for the selected platform - setup SCNTechnique plist with all definitions - add .metal file with shader code - archieve the project - open the archieved bundle and copy the default.metallib file into your playground Resources folder - now just set your technique on the SCNView – profit. Thanks again to Oliver for your help! Upvotes: 2
2018/03/17
1,290
4,930
<issue_start>username_0: On reactjs how does one print one element per second from an array? I have tried to replicate and simplify my work. The array comes from redux. But the final situation doesn't change. Thanks. ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { renderWord(word,index) { return {word} ; } renderWords() { const words = arrWords.map((word, index) => { return this.renderWord(word, index); }); return words; } render(){ return ( {this.renderWords()} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ```<issue_comment>username_1: One possible solution is to keep an `index` that keeps incrementing every second and render that many words ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { count: 0 }; componentDidMount() { this.timerID = setInterval(()=> { console.log(this.state); this.setState(prevState => ({ count: (prevState.count + 1)%arrWords.length })) }, 1000); } componentWillUnmount() { clearInterval(this.timerID); } renderWord(word,index) { return {word} ; } renderWords() { const words = arrWords.map((word, index) => { if(index <= this.state.count) return this.renderWord(word, index); }); return words; } render(){ return ( {this.renderWords()} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Upvotes: 2 <issue_comment>username_2: I think this should work for you. Use the React lifecycle methods to start and end an interval before the component mounts and unmount. Simply increment the index and let React handle the rest. ``` const arrWords = ["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { constructor() { super(); this.state = { arr: arrWords, index: 0 } } componentDidMount() { this.timer = setInterval(() => { const { index, arr } = this.state; // increment index if appropriate or reset to 0 this.setState({ index: index + 1 >= arr.length ? 0 : index + 1}); }, 1000); } // Clean up before unmounting componentWillUnmount() { clearInterval(this.timer); } render() { const { arr, index} = this.state; return {arr[index]} ; } } ReactDOM.render(, document.getElementById("app")); ``` Upvotes: 1 <issue_comment>username_3: The answers above aren't incorrect but they aren't very fun either. Use `Promise.resolve()` to solve this. *not too sure if you mean render one word per second by replacing the previous each time, or one word per second by appending to the end* Replacing previous word ----------------------- ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { word: '', index: 0 }; renderWord(word,index) { return new Promise(( resolve, reject ) => { if ( this.wordTimeout ) clearTimeout(this.wordTimeout); this.wordTimeout = setTimeout(() => this.setState({ word, index }, resolve), 1000 ) }); } componentDidMount () { arrWords.reduce(( promise, word, index ) => promise.then(() => this.renderWord(word, index)), Promise.resolve() ); } render(){ return ( {this.state.word} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Appending to create sentence ---------------------------- ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { index: 0 }; renderSentence (index) { return new Promise(( resolve, reject ) => { if ( this.wordTimeout ) clearTimeout(this.wordTimeout); this.wordTimeout = setTimeout(() => this.setState({ index }, resolve), 1000 ) }); } componentDidMount () { arrWords.reduce(( promise, word, index ) => promise.then(() => this.renderSentence(index)), Promise.resolve() ); } render(){ // Plenty of better ways to do this but this will do what you need const words = arrWords.slice(0, this.state.index + 1); const renderedWords = words.map(word => {word} ); return ( {renderedWords} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Upvotes: 1
2018/03/17
4,811
17,682
<issue_start>username_0: I am working on an application that will randomly generate a menu based on a user's calorie needs. For my first activity I ask for input from the user and gather information needed to calculate the daily calorie needs. The calorie needs is the double value that I need to transfer to my second activity in order to accurately generate a menu. I have been scouring any source I can find but I have not found any viable solutions. I have attempted using getIntent() as you will see and I have tried using a method to call in my second activity but the value does not update after running, the method always returns 0.0 even if the calories have been calculated correctly. I feel as though this may be an easy fix but I cannot grasp what I am doing wrong. Code Below: **Activity 1:** ``` package com.jfreitas2.freitas_project1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Intent good = new Intent(MainActivity.this, Main2Activity.class); public double weight1, calNeeds; RadioButton mrad, frad; EditText weight, age; CheckBox kg, lb, sed, mod, act; String gender; int age1; TextView test; double cals = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //find all Id's related to the check boxes and radio buttons mrad = (RadioButton) findViewById(R.id.malerad); frad = (RadioButton) findViewById(R.id.femalerad); lb = (CheckBox) findViewById(R.id.lbCheck); kg = (CheckBox) findViewById(R.id.kgCheck); sed = (CheckBox) findViewById(R.id.checkSed); mod = (CheckBox) findViewById(R.id.checkMod); act = (CheckBox) findViewById(R.id.checkAct); addListenerToCheckBoxes(); //adds listeners to all check boxes and radio buttons checkBoxOnlyOne(); //ensures only one checkbox/radio button can be checked within each pair addListenerOnButton(); //runs program to determine ideal body weight } public void addListenerOnButton()//runs program to determine ideal body weight { //finds calculate button's ID Button btn = (Button) findViewById(R.id.etbutton); //run everything below this when button is clicked (calculate ideal body weight) btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { calNeeds = getUserCalNeeds(); good.putExtra("cals", calNeeds); startActivity(good); } }); } public void addListenerToCheckBoxes()//adds listeners to all check boxes and radio buttons to set them checked when clicked { lb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { lb.setChecked(true);//set to checked } }); kg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { kg.setChecked(true);//set to checked } }); mrad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mrad.setChecked(true);//set to checked } }); frad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { frad.setChecked(true);//set to checked } }); sed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sed.setChecked(true);//set to checked } }); mod.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mod.setChecked(true); } }); act.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { act.setChecked(true); } }); } public void checkBoxOnlyOne()//ensures only one checkbox/radio button can be checked within each pair { lb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { kg.setChecked(false);//change accompanying button to false } }); kg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { lb.setChecked(false);//change accompanying button to false } }); mrad.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { frad.setChecked(false);//change accompanying button to false } }); frad.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mrad.setChecked(false);//change accompanying button to false } }); sed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mod.setChecked(false); act.setChecked(false); } }); mod.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { sed.setChecked(false); act.setChecked(false); } }); act.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { sed.setChecked(false); mod.setChecked(false); } }); } public double getUserCalNeeds() { //retrieve ID's weight =(EditText) findViewById(R.id.editWeight); age = (EditText) findViewById(R.id.editAge); //turn Strings into doubles in order to run equations weight1 = Double.parseDouble(weight.getText().toString()); age1 = Integer.parseInt(age.getText().toString()); //check what gender was chosen for choosing an equation if(mrad.isChecked()) gender = "male"; else if(frad.isChecked()) gender = "female"; //check if weight is kg or lb.. if it is lbs then we convert to kg if(lb.isChecked()) weight1 = weight1*0.45359237; if(gender == "female") { if (age1 >= 3 && age1 <= 9) calNeeds = (22.5 * weight1) + 499; else if (age1 >= 10 && age1 <= 17) calNeeds = (12.2 * weight1) + 746; else if (age1 >= 18 && age1 <= 29) calNeeds = (10.7 * weight1) + 496; else if (age1 >= 30 && age1 <= 60) calNeeds = (8.7 * weight1) + 829; else if (age1 >= 61) calNeeds = (10.5 * weight1) + 596; } else if(gender == "male") { if (age1 >= 3 && age1 <= 9) calNeeds = (22.7 * weight1) + 495; else if (age1 >= 10 && age1 <= 17) calNeeds = (17.5 * weight1) + 651; else if (age1 >= 18 && age1 <= 29) calNeeds = (15.3 * weight1) + 679; else if (age1 >= 30 && age1 <= 60) calNeeds = (11.6 * weight1) + 879; else if (age1 >= 61) calNeeds = (13.5 * weight1) + 487; } if(sed.isChecked()) calNeeds *= 1.2; else if(mod.isChecked()) calNeeds *= 1.3; else if(act.isChecked()) calNeeds *= 1.4; return calNeeds; } public double getCals() { return calNeeds; } } ``` **Activity 2** ``` package com.jfreitas2.freitas_project1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class Main2Activity extends AppCompatActivity { //MainActivity main = new MainActivity(); double calNeeds = getIntent().getDoubleExtra("cals", 0.0); public HashMap breakie = new HashMap(), lunchie = new HashMap(), dindin = new HashMap(); //create hashmaps for food and calories public ArrayList breakArr = new ArrayList(), lunchArr = new ArrayList(), dinArr = new ArrayList(); //arrays to fill with food to compare to hashmaps. public ArrayList bMenu = new ArrayList(), lMenu = new ArrayList(), dMenu = new ArrayList(); public ListView bList, lList, dList; TextView totalCal; int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity\_main2); bList = (ListView) findViewById(R.id.breakList); lList = (ListView) findViewById(R.id.lunchList); dList = (ListView) findViewById(R.id.dinnerList); totalCal = (TextView) findViewById(R.id.totalCal); //fillMaps(); //fillArrayLists(); //fillMenus(); //totalCal.setText(""+calNeeds); } public void fillMaps() { //Fill Breakfast Map breakie.put("2 Eggs", 156); breakie.put("3 Strips Bacon", 129); breakie.put("2 Sausage Links", 340); breakie.put("1 Cup Cereal", 307); breakie.put("1 Large Banana", 121); breakie.put("2 Slices Wheat Bread with Peanut Butter", 326); breakie.put("1 Cup Strawberries", 50); breakie.put("2 Pieces French Toast", 300); breakie.put("2 Medium Pancakes with Syrup", 232); breakie.put("1 Chewie Granola Bar", 100); // //Fill Lunch Map lunchie.put("1 Chicken Breast", 231); lunchie.put("4 Slices Turkey Breast", 88); lunchie.put("2 Slices Wheat Bread", 138); lunchie.put("5 Piece Chicken Tenders", 230); lunchie.put("1 Small Caesar Salad", 94); lunchie.put("1 Chicken Salad Sandwich", 200); lunchie.put("1 Small Bag of Chips", 153); lunchie.put("1 Quesadilla", 528); lunchie.put("1 Cup Chicken Alfredo", 415); lunchie.put("1 Ham Sandwich", 292); // //Fill Dinner Map dindin.put("1 5oz Steak", 429); dindin.put("6oz Spinach", 40); dindin.put("6oz Cooked Pasta", 225); dindin.put("4oz French Fries", 365); dindin.put("1 Hamburger", 254); dindin.put("1 Slice Pizza", 185); dindin.put("1 Garden Salad", 100); dindin.put("1 Chicken Parm Dish", 400); dindin.put("3 Chicken Wings", 300); dindin.put("1 Potato Roasted", 161); // } public void fillArrayLists() { //filling arraylist with food for breakfast breakArr.add("2 Eggs"); breakArr.add("3 Strips Bacon"); breakArr.add("2 Sausage Links"); breakArr.add("2 Cups Cereal"); breakArr.add("1 Large Banana"); breakArr.add("2 Slices Wheat Toast with Peanut Butter"); breakArr.add("1 Cup Strawberries"); breakArr.add("2 Pieces French Toast"); breakArr.add("2 Medium Pancakes with Syrup"); breakArr.add("1 Chewie Granola Bar"); // //filling arraylist with food for lunch lunchArr.add("1 Chicken Breast"); lunchArr.add("4 Slices Turkey Breast"); lunchArr.add("2 Slices Wheat Bread"); lunchArr.add("5 Piece Chicken Tenders"); lunchArr.add("1 Small Caesar Salad"); lunchArr.add("1 Chicken Salad Sandwich"); lunchArr.add("1 Small Bag of Chips"); lunchArr.add("1 Quesadilla"); lunchArr.add("1 Cup Chicken Alfredo"); lunchArr.add("1 Ham Sandwich"); // //filling arraylist with food for dinner dinArr.add("1 5oz Steak"); dinArr.add("6oz Spinach"); dinArr.add("6oz Cooked Pasta"); dinArr.add("4oz French Fries"); dinArr.add("1 Hamburger"); dinArr.add("1 Slice Pizza"); dinArr.add("1 Garden Salad"); dinArr.add("1 Chicken Parm Dish"); dinArr.add("3 Chicken Wings"); dinArr.add("1 Potato Roasted"); } public void fillMenus() { Random rand = new Random(10); int x; double currentCal = 0; while(currentCal < calNeeds) { //add to breakfast menu x = rand.nextInt(); currentCal += breakie.get(breakArr.get(x)); bMenu.add(breakArr.get(x)); //add to lunch menu x = rand.nextInt(); currentCal += lunchie.get(lunchArr.get(x)); lMenu.add(lunchArr.get(x)); //add to dinner menu x = rand.nextInt(); currentCal += dindin.get(dinArr.get(x)); dMenu.add(dinArr.get(x)); count++; } } /\*public void displayMenus() { bList = (ListView) findViewById(R.id.breakList); lList = (ListView) findViewById(R.id.lunchList); dList = (ListView) findViewById(R.id.dinnerList); test = (TextView) findViewById(R.id.textView); test.setText(bMenu.get(0)); ArrayAdapter breakAdapter = new ArrayAdapter(Main2Activity.this, android.R.layout.simple\_list\_item\_1, bMenu); bList.setAdapter(breakAdapter); }\*/ } ```<issue_comment>username_1: One possible solution is to keep an `index` that keeps incrementing every second and render that many words ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { count: 0 }; componentDidMount() { this.timerID = setInterval(()=> { console.log(this.state); this.setState(prevState => ({ count: (prevState.count + 1)%arrWords.length })) }, 1000); } componentWillUnmount() { clearInterval(this.timerID); } renderWord(word,index) { return {word} ; } renderWords() { const words = arrWords.map((word, index) => { if(index <= this.state.count) return this.renderWord(word, index); }); return words; } render(){ return ( {this.renderWords()} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Upvotes: 2 <issue_comment>username_2: I think this should work for you. Use the React lifecycle methods to start and end an interval before the component mounts and unmount. Simply increment the index and let React handle the rest. ``` const arrWords = ["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { constructor() { super(); this.state = { arr: arrWords, index: 0 } } componentDidMount() { this.timer = setInterval(() => { const { index, arr } = this.state; // increment index if appropriate or reset to 0 this.setState({ index: index + 1 >= arr.length ? 0 : index + 1}); }, 1000); } // Clean up before unmounting componentWillUnmount() { clearInterval(this.timer); } render() { const { arr, index} = this.state; return {arr[index]} ; } } ReactDOM.render(, document.getElementById("app")); ``` Upvotes: 1 <issue_comment>username_3: The answers above aren't incorrect but they aren't very fun either. Use `Promise.resolve()` to solve this. *not too sure if you mean render one word per second by replacing the previous each time, or one word per second by appending to the end* Replacing previous word ----------------------- ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { word: '', index: 0 }; renderWord(word,index) { return new Promise(( resolve, reject ) => { if ( this.wordTimeout ) clearTimeout(this.wordTimeout); this.wordTimeout = setTimeout(() => this.setState({ word, index }, resolve), 1000 ) }); } componentDidMount () { arrWords.reduce(( promise, word, index ) => promise.then(() => this.renderWord(word, index)), Promise.resolve() ); } render(){ return ( {this.state.word} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Appending to create sentence ---------------------------- ```js const arrWords=["I", "would", "like", "to", "print", "one", "word", "per", "second"]; class Message extends React.Component { state = { index: 0 }; renderSentence (index) { return new Promise(( resolve, reject ) => { if ( this.wordTimeout ) clearTimeout(this.wordTimeout); this.wordTimeout = setTimeout(() => this.setState({ index }, resolve), 1000 ) }); } componentDidMount () { arrWords.reduce(( promise, word, index ) => promise.then(() => this.renderSentence(index)), Promise.resolve() ); } render(){ // Plenty of better ways to do this but this will do what you need const words = arrWords.slice(0, this.state.index + 1); const renderedWords = words.map(word => {word} ); return ( {renderedWords} ); } }; ReactDOM.render(, document.getElementById('app')); ``` ```html ``` Upvotes: 1
2018/03/17
553
2,109
<issue_start>username_0: ``` class Program : Application { [STAThread] public static void Main() { Program app = new Program(); app.StartupUri = new Uri("../../LoginWindow.xaml", UriKind.Relative); //app.MainWindow is null app.Run(); } virtual protected void OnStartUp(StartupEventArgs e) { MessageBox.Show("Start up"); } } ``` //the MainWindow of app is null, so how can I set the DataContext to the LoginWindow(is an UserControl) in void Main() //for some reason, there should not be a window class, I want to directly start the UserControl<issue_comment>username_1: Well this is not the proper way which a [WPF application starts](https://learn.microsoft.com/en-us/dotnet/framework/wpf/getting-started/walkthrough-my-first-wpf-desktop-application) in. I do not know why you need to create a `Main` method as your application were a Windows.Form one. Anyway you can do what you need looking at [this blog](https://ludovic.chabant.com/devblog/2010/04/20/writing-a-custom-main-method-for-wpf-applications/). Basically you > > need to change the application's build action from "*Application Definition*" to "*Page*", create a constructor that calls "*InitializeComponent*", and write your Main() by eventually calling one of the application’s "*Run*" method overloads > > > Then your code will become ``` class Program : Application { public Program() { InitializeComponent(); } [STAThread] public static void Main() { LoginWindow loginWindow = new LoginWindow(); /* Here you can set loginWindow's DataContext */ Program app = new Program(); app.Run(window); } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: A much easier way to do this is to subscribe to the Startup event of your application: App.xaml: ``` ``` App.xaml.cs: ``` public partial class App { private void App_Startup(object sender, StartupEventArgs e) { var view = new MainView { DataContext = new MainVM() }; view.Show(); } } ``` Upvotes: 1
2018/03/17
815
1,861
<issue_start>username_0: How can I draw a SVG using qml in simple words? According to QtDocs it is possible to draw a SVG using this code: ``` Path { startX: 50; startY: 50 PathSvg { path: "L 150 50 L 100 150 z" } } ``` But actually it doesn't. So, how can I draw SVG?<issue_comment>username_1: Nothing in the documentation says anything about drawing. It says "defines a path" by using SVG path syntax. Drawing it is a different step: ``` Canvas { width: 400; height: 200 contextType: "2d" onPaint: { context.strokeStyle = Qt.rgba(.4,.6,.8) context.path = yourPath context.stroke() } } ``` Note that as long as Qt is compiled with SVG support you can directly use .svg files as image sources. Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want to show a path, you must use it within a `Shape`: ``` Shape { ShapePath { fillColor: "red" strokeWidth: 2 strokeColor: "blue" startX: 50; startY: 50 PathSvg { path: "L 150 50 L 100 150 z" } } } ``` Upvotes: 3 <issue_comment>username_3: I have been having great success using inline SVG in data-uri as follows: ``` Image { source: `data:image/svg+xml;utf8, ` } ``` [![triangle-svg](https://i.stack.imgur.com/2f82a.png)](https://i.stack.imgur.com/2f82a.png) You can [Try it Online!](https://stephenquan.github.io/qmlonline/?code=import%20QtQuick%202.15%0Aimport%20QtQuick.Controls%202.15%0A%0APage%20%7B%0A%20%20%20%20Image%20%7B%0A%20%20%20%20%20%20%20%20source%3A%0A%60data%3Aimage%2Fsvg%2Bxml%3Butf8%2C%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20150%20150%22%3E%0A%3Cpath%20fill%3D%22orange%22%20stroke%3D%22royalblue%22%20d%3D%22L%20150%2050%20L%20100%20150%20z%22%20%2F%3E%0A%3C%2Fsvg%3E%60%0A%20%20%20%20%7D%0A%7D) Upvotes: 1
2018/03/17
564
1,628
<issue_start>username_0: What value does the $xyz get assigned? Does it get a null value or is there any error? There is also an error\_reporting(0) function. ``` error_reporting(0); $xyz =// removed; ```<issue_comment>username_1: You can't assign a comment to a variable because when the script is executed, all comments are ignored so you'll end up with a syntax error. As you can see in the syntax highlighting in your question, the semicolon at the end is greyed out because everything after the `//` is ignored. Upvotes: 2 <issue_comment>username_2: You'd get a syntax error, like so: ``` PHP Parse error: syntax error, unexpected end of file ``` So, `$xyz` wouldn't have a value, PHP would just exit because of the syntax error, and you'd never even get to see what the value was. ([See for yourself](https://tio.run/##K8go@P/fxr4go4Artagovyi@KLUgv6gkMy9dw0DTWoFLpaKySsFWX1@hKDU3vyw1xfr/fwA)) --- ~~Since you've set `error_reporting(0)` you won't get any errors, so `$xyz` has a value of `NULL`. [Try it online!](https://tio.run/##K8go@P/fxr4go4Artagovyi@KLUgv6gkMy9dw0DTWoFLpaKySsFWX1@hKDU3vyw1xZqrLLEoPqU0t0ADJKVp/f8/AA) If you don't even set the `$xyz`, it's still `NULL`: [Try it online!](https://tio.run/##K8go@P/fxr4go4Artagovyi@KLUgv6gkMy9dw0DTmqsssSg@pTS3QEOlorJK0/r/fwA) Effectively, PHP just ignores that line, it's like `$xyz` was never set, so `var_dump`ing it returns `NULL`.~~ (Turns out that `$xyz` was being set to the output of `var_dump`, so there was no syntax error. Thanks to [@Bytewave](https://stackoverflow.com/users/3397227/bytewave) for figuring that out) Upvotes: 1 [selected_answer]
2018/03/17
704
2,968
<issue_start>username_0: I have checked recent blogs about onsubmit event not triggering the method. Those suggestions were not helpful for this problem.And i've tried this method and form in an another html page which didn't work either.So i am not able to find out where main problem is ? My code : ``` function validateLogin() { var nameCheck=document.Log.username.value; var passwordCheck=document.Log.password.value; var status=false; if(nameCheck.length<4) { document.Log.getElementById("nameLoc").innerHTML= 'Put your Email Address for this Community\'s Sake'; status=false; } else { document.Log.getElementById("nameLoc").innerHTML= 'Naming Convention Allright'; status=true; } if(passwordCheck.length<8) { document.Log.getElementById("passwordLoc").innerHTML= 'Password Does not Meet with Standard'; status=false; } else { document.Log.getElementById("passwordLoc").innerHTML= 'Pass<PASSWORD>'; status=true; } return status; } ![Avatar](login.png) **Username** **Password** Login Remember me ```<issue_comment>username_1: Just add value in your button like below :- ``` <button type="submit" value="submit>Login ``` Upvotes: 1 <issue_comment>username_2: You are trying to use `getElementById` on the `form` - but it is a function of the `document`. Change to this: ``` if (nameCheck.length < 4) { document.getElementById("nameLoc").innerHTML = 'Put your Email Address for this Community\'s Sake'; status = false; } else { document.getElementById("nameLoc").innerHTML = 'Naming Convention Allright'; status = true; } if (passwordCheck.length < 8) { document.getElementById("passwordLoc").innerHTML = 'Password Does not Meet with Standard'; status = false; } else { document.getElementById("passwordLoc").innerHTML = 'Pass<PASSWORD> Convention Allright'; status = true; } ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: You can add an event listener to your form in the script tag and it will work: `document.Log.addEventListener("submit", validateLogin);` PS: For this, you will need to move your script tag to below your form, because Log isn't defined as far as the code is concerned until the form loads before the code is run. Upvotes: 0 <issue_comment>username_4: How do you know if your function is called? Put an alert in there to make sure! Your validate function will allow the submission to continue if either condition is met. You should change it to initialise status to true then set it to false in both negative results but don't set it back to true for positive. If it still doesn't work you could put your call in the onclick event of the submit button instead. Upvotes: 0
2018/03/17
1,278
4,782
<issue_start>username_0: From Spring boot 1.5.x, I receive the following WARN messages: ``` :: Spring Boot :: (v2.0.0.RELEASE) 2018-03-17 18:58:18.546 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.web.context.support.WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext)] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:18.551 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:18.937 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.web.context.support.WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext)] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:18.938 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:19.034 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.web.context.support.WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext)] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:19.035 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:19.136 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.web.context.support.WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext)] because it is marked as final: Consider using interface-based JDK proxies instead! 2018-03-17 18:58:19.136 WARN 27877 --- [ restartedMain] o.s.a.f.CglibAopProxy : Unable to proxy interface-implementing method [public final void org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext) throws org.springframework.beans.BeansException] because it is marked as final: Consider using interface-based JDK proxies instead! ``` I don't have CGLIB in the dependency hierarchy. I'm using only interfaces for DI and I've tried to disable `@EnableGlobalMethodSecurity(securedEnabled = true)` and everything related to it, but still no change. (I've read that MethodSecurity and `@Secured` annotations in the Controller Classes can cause this WARNing, but it seems that I get them from another place. How to know from where I receive these warnings?<issue_comment>username_1: The problem was with some @Transactional annotations on a Class level. After I put them on the interfaces (Repositories - I'm using spring data) Everything is OK :) Upvotes: 1 <issue_comment>username_2: Based on the reported issue, I have faced same issue like having interface-implementing method with final. From the concrete class (Bean) if we remove final from method , also solved the same issue. Ref: <https://github.com/spring-projects/spring-boot/issues/8974> Upvotes: 0 <issue_comment>username_3: After checking `@Transactional` annotation, make sure u put your `@Repository` annotation directly to **repository interface**. In my case I did the following: 1. Removed `@Transactional` and `@Repository` from my **DAO class** 2. Put `@Repository` to my repo interface 3. Put `@Component` to my **DAO class** See [Spring Boot + Annotations](https://stackoverflow.com/questions/49339820/spring-boot-unable-to-proxy-interface-implementing-method-warn-message) for more info about annotations Upvotes: 1
2018/03/17
861
3,237
<issue_start>username_0: I have a scenario where I create a worker pool which has 4 workers. These workers picks up job from a channel and stores the result to the memory. So the worker execute the job and may update the result in parallel. I would like to know which data type is best to save the result as it would be accessed by multiple workers at a time. I would need to use the lock mechanism to achieve this. The result will be key-value format. So can maps be considered in this scenario.<issue_comment>username_1: Yes, you could use a map for that and you would have to protect it by a mutex. I would however suggest that each job contains a result channel where you can input the result of the job. Here a rough sketch of what that would look like: [playground](https://play.golang.org/p/FavfF5FRhCx): note that playground only has one core so the numbers will appear in sequence. ``` package main import ( "fmt" "time" ) type job struct { a int b int chRes chan int } func main() { var chIn = make(chan job, 20) for i := 0; i < 10; i++ { go worker(chIn) } for i := 0; i < 100; i++ { go func(i int) { chRes := make(chan int) chIn <- job{ a: i, b: i, chRes: chRes, } fmt.Println(<-chRes) }(i) } // I'm lazy, so here just a sleep so we can see something time.Sleep(1 * time.Second) } func worker(ch chan job) { for job := range ch { job.chRes <- job.a + job.b } } ``` -- edit -- If you device to go with a store instead (which kind of goes against the go mantra `share memory by communicating` instead of `communicate by sharing memory`): there is also a `sync.Map` that is already concurrency safe. No mutex needed. Upvotes: 1 <issue_comment>username_2: I'd use a second channel the workers send results to. One goroutine will receive results from this channel and store them. Shared memory and protected code sections are not needed if you use this approach. **Edit: Example** The following program uses four workers and one result collector. Tasks are passed to the workers from the main gorouting. The worker send results and errors to the collector who builds a summary. ``` package main import ( "fmt" "sync" ) func main() { tasks := make(chan int) results := make(chan string) var wg sync.WaitGroup for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done() for task := range tasks { rem := int(task) % 2 switch rem { case 0: results <- fmt.Sprintf("done with task %d", task) case 1: results <- fmt.Sprintf("error: only even tasks accepted: %d", task) } } }() } summary := "" go func() { for result := range results { summary += result + "\n" } }() for i := 0; i < 10; i++ { tasks <- i } close(tasks) wg.Wait() close(results) fmt.Println(summary) } ``` see <https://play.golang.org/p/puZONnJHme-> Upvotes: 2
2018/03/17
430
1,456
<issue_start>username_0: I have written the following query from various tables : ``` SELECT DISTINCT 0 AS IID, pd.IID AS PurchaseOrerDetailsId, i.[Description] AS ITEM, '' AS BatchNo, s.[Description] AS Unit, '' AS MfgDt, 0 AS QtyReceived, '' AS ExpiryDate, '' AS PackSize, 0 AS QtyOrdered, 0 AS MRP, 0 AS PTR, 0 AS PTS, 0 AS PurchaseRate, 0 AS CGST, 0 AS SGST, 0 AS IGST, 0 AS DiscPer, 0 AS DiscVal, 0 AS PurchaseValue, 0 AS CGSTAmt, 0 AS SGSTAmt, i.IID AS ItemId FROM PurchaseOrderDetails pd LEFT JOIN StockDetails sd ON pd.ItemId = sd.ItemId INNER JOIN Items i ON i.IID = pd.ItemId INNER JOIN Strings s ON s.IID = i.Unit WHERE pd.PurchaseOrderId = 1 ``` I am getting the following result: [![enter image description here](https://i.stack.imgur.com/ch0FF.png)](https://i.stack.imgur.com/ch0FF.png) Now I want to eliminate first two records (PurchaseOrerDetailsId is 1 and 2). Any clue. Thanks Partha<issue_comment>username_1: You can use row\_number() as [rn] inside a CTE, after that you can select [rn] > 2. Upvotes: 0 <issue_comment>username_2: I suspect there is more to it. But based on what you supplied: ``` and pd.IID > 2 ``` You don't use `StockDetails sd`. That left join is a waste. All those hard coded values are not needed for the question. Upvotes: 1
2018/03/17
462
1,442
<issue_start>username_0: I have a teams table called `list`, and a games table called `games`. A `Team_ID` could be in either the `games_home` or the `games_away` column. How do I get this to work in SQL? ``` SELECT list.*, games.* FROM list INNER JOIN games ON (list.Team_ID = games.games_away) AND (list.Team_ID = games.games_home); ``` This does not show any results. Image of relationship: [![enter image description here](https://i.stack.imgur.com/TzhCS.png)](https://i.stack.imgur.com/TzhCS.png) [example of output](https://i.stack.imgur.com/sMNbP.png) id 13 = man u id 9 = liverpool etc [my problem](https://i.stack.imgur.com/VdPWg.png)<issue_comment>username_1: You could make a UNION ALL with two queries: one selects home matches, the other selects away matches ``` SELECT l.*, g.* FROM list l INNER JOIN games g ON g.games_away = l.team_ID UNION ALL SELECT l.*, g.* FROM list l INNER JOIN games g ON g.games_home = l.team_ID ``` Upvotes: 0 <issue_comment>username_2: If you want the data for both teams in a single row you'll need two joins: ``` SELECT g.*, l1.Team as home_team, l2.Team as away_team, l1.*, l2.* FROM games g INNER JOIN list l1 ON l1.Team_ID = g.games_home INNER JOIN list l2 ON l2.Team_ID = g.games_away ``` Select only the columns you actually need to return and alias them as I did above so you can distinguish home vs. away. Upvotes: 2 [selected_answer]
2018/03/17
455
1,649
<issue_start>username_0: I'm doing those Stanford course, and on that part about gestures I couldn't replicated the pinchGesture, it simply doesn't works and even don't call the breakpoint inside the method that are supposed to be called. I'm copying my code below inside FaceViewController ```swift @IBOutlet weak var faceView: FaceView! { didSet { faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: #selector(FaceView.changeScale(_:)))) updateUI() } } ``` inside FaceView ```swift @objc func changeScale(_ recognizer: UIPinchGestureRecognizer) { switch recognizer.state { case .changed, .ended: scale *= recognizer.scale recognizer.scale = 1.0 default: break } } ``` I'm on Xcode 9 and swift is version 4. Many thanks.<issue_comment>username_1: You could make a UNION ALL with two queries: one selects home matches, the other selects away matches ``` SELECT l.*, g.* FROM list l INNER JOIN games g ON g.games_away = l.team_ID UNION ALL SELECT l.*, g.* FROM list l INNER JOIN games g ON g.games_home = l.team_ID ``` Upvotes: 0 <issue_comment>username_2: If you want the data for both teams in a single row you'll need two joins: ``` SELECT g.*, l1.Team as home_team, l2.Team as away_team, l1.*, l2.* FROM games g INNER JOIN list l1 ON l1.Team_ID = g.games_home INNER JOIN list l2 ON l2.Team_ID = g.games_away ``` Select only the columns you actually need to return and alias them as I did above so you can distinguish home vs. away. Upvotes: 2 [selected_answer]
2018/03/17
436
1,442
<issue_start>username_0: I want to manually add new data to firebase. I found [this](http://mariechatfield.com/tutorials/firebase/step2.html) tutorial but this is only for depth 1. How can I add something like this ? ``` roles: { "ajda4a684fawefae" : ["role1", "role2"], "as87awda74w8wa86" : ["role1", "role3"] } ``` Main problem is to put part in `{}` to value. --- **UPDATE** --- I have found solution. It should look like this: [![enter image description here](https://i.stack.imgur.com/zGV4C.png)](https://i.stack.imgur.com/zGV4C.png)<issue_comment>username_1: Here's how I just added a structure like that in the [Firebase Database console](https://console.firebase.google.com/project/_/database/data/) of one of my projects [![edit mode of Firebase database](https://i.stack.imgur.com/DflDF.png)](https://i.stack.imgur.com/DflDF.png) I didn't know that you can enter arrays as literals. When I needed them before, I added them by entering explicit numeric child keys (which is how the database ends up storing them). Upvotes: 2 <issue_comment>username_2: I realize this answer is likely a few years too late, but in case it helps anyone else, you just need to use valid json. Keys need to be in quotes, string values need to be in quotes, while numbers and booleans should not be. See my example! [![enter image description here](https://i.stack.imgur.com/jJRnR.png)](https://i.stack.imgur.com/jJRnR.png) Upvotes: 1
2018/03/17
1,076
3,687
<issue_start>username_0: I use one among many options to store my API keys in the **computer/keychain** rather than directly in the cloud-backed-up project code (namely [gradle-credentials-plugin](https://github.com/etiennestuder/gradle-credentials-plugin) ). What I'd like is to be able to manage Google Maps keys in a similar way, but they're used in a different file ([Manage Google Maps API Key with Gradle in Android Studio](https://stackoverflow.com/questions/26124309/manage-google-maps-api-key-with-gradle-in-android-studio)). If anyone has a simple (or intricate, but reliable) option for me to dig into, I'd be grateful!<issue_comment>username_1: You can use a **not versioned** file called as you want, let's say `api.keys` with this content: ``` debugMapsApiKey=<KEY> releaseMapsApiKey=<KEY> ``` Put it in your root project folder. You read this file in your `build.gradle` file in a way like that: ``` def apiKeysFile = rootProject.file("api.keys") def apiKeysFile = new Properties() apiKeysFile.load(new FileInputStream(apiKeysFile)) [...] debug { buildConfigField "String", MAPS_KEY, apiKeysFile['debugMapsApiKey'] } release { buildConfigField "String", MAPS_KEY, apiKeysFile['releaaseMapsApiKey'] } ``` And you can access it in code through `BuildConfig.MAPS_KEY` that if you build in debug you will have `"xxxxXXxxxx"` value, instead in release you will have `"xxxxYYxxxx"`. And if you want to access on XML you could use `resValue` that create a string resource. ``` debug { resValue "string", MAPS_KEY, apiKeysFile['debugMapsApiKey'] } release { resValue "string", MAPS_KEY, apiKeysFile['releaseMapsApiKey'] } ``` In this way you could also get it in code with ``` getString(R.string.MAPS_KEY) ``` Upvotes: 2 <issue_comment>username_2: Shadowsheep's solution works, but it's not really what I want to do. What I've ended up doing. * First, I was under the mistaken impression it was absolutely necessary to populate *google-maps-api.xml* with the key, when it apparently is sufficient to set the key in the Manifest. * Second, I've added a line into the Manifest * Third, I've set mapsKey via my chosen tool (gradle-credentials-plugin by etiennestuder) * Finally, I've added into the app's module *build.gradle* `buildTypes` section these two lines: > > def mapsKey = credentials.GOOGLE\_MAPS\_API\_KEY ?: "Key Missing" > > > it.resValue "string", "GoogleMapsApiKey", mapsKey > > > Upvotes: 1 [selected_answer]<issue_comment>username_3: You can use [manifestPlaceholders](https://developer.android.com/studio/build/manifest-build-variables) to inject the string from your `build.gradle`. 1. Inset your API key into a file like `local.properties` ``` google.maps_api_key=SECRET_KEY ``` 2. Make sure this file is ignored using `.gitignore`: ``` local.properties ``` 3. Make the API key available to your `AndroidManifest.xml`. Using `withInputStream()` ensures the `InputStream` [is closed automatically](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html). ``` android{ defaultConfig { // Load credentials. def properties = new Properties() file("../local.properties").withInputStream { properties.load(it) } // Share the key with your `AndroidManifest.xml` manifestPlaceholders = [ googleMapsApiKey:"${properties.getProperty('google.maps_api_key')}"] ``` 4. Load the API key in your `AndroidManifest.xml`: ``` ``` Upvotes: 3 <issue_comment>username_4: google\_maps\_api.xml ``` GoogleMapsApiKey ``` manifest ``` ``` gradle ``` resValue "string", "GoogleMapsApiKey", mapskey ``` gradle.properties ``` mapskey="AIza...8w" // key here ``` Upvotes: 1
2018/03/17
674
2,117
<issue_start>username_0: I have been facing a major issue while using selenium: On the Trivago website "<https://www.trivago.com/site_map>", I have been trying to get the script to click on each continent but it seems to not work: ``` element = driver.find_element_by_class_name('link') element.click() ``` I also attempted by xpath using the following: ``` //*[@id="js_sitemap"]/div/div/ul/li[1]/a ``` Can anyone give me a hand?<issue_comment>username_1: You're trying to click on `li` node while you need to handle child link: ``` driver.find_element_by_css_selector('li.link>a').click() ``` But if you want to open page of each continent you'd better to get list of references and get each of them: ``` links = [link.get_attribute('href') for link in driver.find_elements_by_css_selector('li.link>a')] for link in links: driver.get(link) # do something with continent ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As @DyZ pointed out, you can simply scrape the listings by using the urls provided on the page, such as `'https://www.trivago.com/north-america-34225/hotel'`. However, you can iterate over `find_elements_by_tag_name` and call the `click` method for each object reference: ``` from selenium import webdriver d = webdriver.Chrome('/Users/jamespetullo/Downloads/chromedriver') d.get('https://www.trivago.com/site_map') for continent in d.find_elements_by_tag_name('a'): if continent.text in [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America']: continent.click() #do something with page source or current page object d.back() ``` Alternatively, to find the links, you can use `bs4` and `urllib`: ``` from bs4 import BeautifulSoup as soup import urllib import re data = str(urllib.urlopen('https://www.trivago.com/site_map').read()) links = [i.text for i in soup(data, 'lxml').find_all('a', href=True) if re.findall('[a-zA-Z\-]+\-\d+/hotel', i['href'])] ``` Output: ``` [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America'] ``` Upvotes: 1
2018/03/17
749
2,170
<issue_start>username_0: I am trying to remove some entries in a big xml file (8 million lines) with the following structure: ``` "coords": ["0" , "4"] 452;2| 460;4| 1001;6| 385;1| 463;1| "coords": ["0" , "8"] 629;2| 460;3| 75;3| 1010;3| 458;2| 450;1| ``` I want to remove all entries below 1000. Example: 452;2| So I want a regex to capture numbers below 1000 plus the semicolon and the numbers after that in that line. It's that possible? I am doing this in notepad ++ btw Thanks<issue_comment>username_1: You're trying to click on `li` node while you need to handle child link: ``` driver.find_element_by_css_selector('li.link>a').click() ``` But if you want to open page of each continent you'd better to get list of references and get each of them: ``` links = [link.get_attribute('href') for link in driver.find_elements_by_css_selector('li.link>a')] for link in links: driver.get(link) # do something with continent ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As @DyZ pointed out, you can simply scrape the listings by using the urls provided on the page, such as `'https://www.trivago.com/north-america-34225/hotel'`. However, you can iterate over `find_elements_by_tag_name` and call the `click` method for each object reference: ``` from selenium import webdriver d = webdriver.Chrome('/Users/jamespetullo/Downloads/chromedriver') d.get('https://www.trivago.com/site_map') for continent in d.find_elements_by_tag_name('a'): if continent.text in [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America']: continent.click() #do something with page source or current page object d.back() ``` Alternatively, to find the links, you can use `bs4` and `urllib`: ``` from bs4 import BeautifulSoup as soup import urllib import re data = str(urllib.urlopen('https://www.trivago.com/site_map').read()) links = [i.text for i in soup(data, 'lxml').find_all('a', href=True) if re.findall('[a-zA-Z\-]+\-\d+/hotel', i['href'])] ``` Output: ``` [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America'] ``` Upvotes: 1
2018/03/17
704
2,196
<issue_start>username_0: Just try to use the DATEDIFF native function in SQL with my following query: ``` SELECT KDX_Id, ( SELECT DATEDIFF('DAY', ___Bookings.BOO_DateCI, ___Bookings.BOO_DateCO) FROM ___Bookings WHERE KDX_Id = ___Bookings.BOO_ClientId ) AS nb_nights FROM ___Kardex ``` Error message is: `#1582 - Incorrect parameter count in the call to native function 'DATEDIFF'`. Table structure is: <http://sqlfiddle.com/#!9/25399/2> What I am missing ? Thanks.<issue_comment>username_1: You're trying to click on `li` node while you need to handle child link: ``` driver.find_element_by_css_selector('li.link>a').click() ``` But if you want to open page of each continent you'd better to get list of references and get each of them: ``` links = [link.get_attribute('href') for link in driver.find_elements_by_css_selector('li.link>a')] for link in links: driver.get(link) # do something with continent ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As @DyZ pointed out, you can simply scrape the listings by using the urls provided on the page, such as `'https://www.trivago.com/north-america-34225/hotel'`. However, you can iterate over `find_elements_by_tag_name` and call the `click` method for each object reference: ``` from selenium import webdriver d = webdriver.Chrome('/Users/jamespetullo/Downloads/chromedriver') d.get('https://www.trivago.com/site_map') for continent in d.find_elements_by_tag_name('a'): if continent.text in [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America']: continent.click() #do something with page source or current page object d.back() ``` Alternatively, to find the links, you can use `bs4` and `urllib`: ``` from bs4 import BeautifulSoup as soup import urllib import re data = str(urllib.urlopen('https://www.trivago.com/site_map').read()) links = [i.text for i in soup(data, 'lxml').find_all('a', href=True) if re.findall('[a-zA-Z\-]+\-\d+/hotel', i['href'])] ``` Output: ``` [u'Africa', u'Asia', u'Australia & Oceania', u'Central and South America', u'Europe', u'North America'] ``` Upvotes: 1
2018/03/17
508
1,820
<issue_start>username_0: So I'm building a project using Angular 4, I have a bunch of images in my assets folder and I have an array of objects in my app.component.ts file that is trying to reference them. The directory is set out like this ``` src | app | app.component.ts | app.component.html | ... | assets | robbie.jpg | ... ``` The ts file includes the image references like this, ``` export class AppComponent { // array of contact objects contacts = [ { name: "<NAME>", image: "../assets/robbie.jpg", email: "XXXXXXXX", phone: "XXXXXXX", role: "Software Developer", address: "XXXXXXX", notes: "XXXXXXX", selected: false }, ... ] } ``` And in app.component.html, I'm trying to reference this image through an img tag like this ``` ![]({{contacts[0].image}}) ``` It isn't however working- the console says that this path can't be found and won't display the robbie.jpg image within the assets folder on the page. How do I do this? How do I normally reference images within components in Angular 4?<issue_comment>username_1: Assuming you are using the `ng serve` command to run your application, the assets folder will be on the same level as the generated javascript and html output. Simply: `image: "assets/robbie.jpg"` should work. Upvotes: 0 <issue_comment>username_2: Try this syntax: `img src="assets/robbie.jpg"` Angular know assets folder path, we don't require to tell explicitly. Upvotes: 1 <issue_comment>username_3: try this ``` export class AppComponent { public contacts = [ { name: "<NAME>", image: "../assets/robbie.jpg", email: "XXXXXXXX", phone: "XXXXXXX", role: "Software Developer", address: "XXXXXXX", notes: "XXXXXXX", selected: false }, ... ] } ``` Upvotes: 0
2018/03/17
604
2,071
<issue_start>username_0: I am getting mad I had those variables ``` $wwa_section_title = get_field('wwa_section_title'); $wwa_section_description = get_field('wwa_section_description'); $wwa_section_body = get_field('wwa_section_body'); $wwa_section_image_1 = get_field('wwa_section_image_1'); $wwa_section_image_2 = get_field('wwa_section_image_2') ``` And this is the HTML section ``` php echo $wwa\_section\_title; ? ------------------------------------- php echo $wwa\_section\_body; ? ![](<?php echo $wwa_section_image_2['url'];?>) ![](<?php echo $wwa_section_image_1['url'];?>) php echo $wwa\_section\_description; ? * Ipsum is simply text of the stry simply * Dummy text of the print * Ipsum is simply text of the stry simply * Dummy text of the print * Ipsum is simply text of the stry simply * Ipsum is simply text of the stry simply * Dummy text of the print * Ipsum is simply text of the stry simply * Dummy text of the print * Ipsum is simply text of the stry simply ``` When I transfer this code into a template part and try to render it, the variables become empty. Once I role back and return the whole code into the page template it wotks fine I tried to use `$post->ID` and did not work I tried to use `the_field()` instead and did not work<issue_comment>username_1: Assuming you are using the `ng serve` command to run your application, the assets folder will be on the same level as the generated javascript and html output. Simply: `image: "assets/robbie.jpg"` should work. Upvotes: 0 <issue_comment>username_2: Try this syntax: `img src="assets/robbie.jpg"` Angular know assets folder path, we don't require to tell explicitly. Upvotes: 1 <issue_comment>username_3: try this ``` export class AppComponent { public contacts = [ { name: "<NAME>", image: "../assets/robbie.jpg", email: "XXXXXXXX", phone: "XXXXXXX", role: "Software Developer", address: "XXXXXXX", notes: "XXXXXXX", selected: false }, ... ] } ``` Upvotes: 0
2018/03/17
442
1,555
<issue_start>username_0: I wanted to create a program where there is a pixel which selects a random point in the surface and then walks to it by straight line. When he is finished, then he selects another random point. And it's like that forever. The problem is, how do i convert that to `x += 1` or `y += 1` or `x -= 1` or `y-= 1` sort of instructions? So far what i've got: ``` class pixel: def __init__(self, x, y): self.x = x self.y = y self.walking = False def update(self): if self.walking == False: self.walking = True self.destx = random.randint(0, width) self.desty = random.randint(0, height) #Some form of script to walk to that position if self.x == self.destx and self.y == self.desty: self.walking = False ```<issue_comment>username_1: Assuming you are using the `ng serve` command to run your application, the assets folder will be on the same level as the generated javascript and html output. Simply: `image: "assets/robbie.jpg"` should work. Upvotes: 0 <issue_comment>username_2: Try this syntax: `img src="assets/robbie.jpg"` Angular know assets folder path, we don't require to tell explicitly. Upvotes: 1 <issue_comment>username_3: try this ``` export class AppComponent { public contacts = [ { name: "<NAME>", image: "../assets/robbie.jpg", email: "XXXXXXXX", phone: "XXXXXXX", role: "Software Developer", address: "XXXXXXX", notes: "XXXXXXX", selected: false }, ... ] } ``` Upvotes: 0
2018/03/17
468
1,580
<issue_start>username_0: I am writing a c++ program for the following problem: Suppose we flew an airplane from Europe to North America and while measuring our height above the sea level (> 0) every x kilometers. we measured zero where there was sea and greater than 0 where there was land. How can we define the two sea sides of the ocean and count the number of islands between europe and north america. so far i am able to write the following code but i am unable to find the count of the islands. ``` #include using namespace std; int main() { cout << "How many measurements?" << endl; int N; cin >> N; int heights[N]; for (int i=0; i> heights[i]; } int E, A; E=1; while (heights[E]>0) { E++; } A=N-2; while (heights[A]>0) { A--; } cout << E+1 << " " << A+1 << endl; return 0; } ```<issue_comment>username_1: Assuming you are using the `ng serve` command to run your application, the assets folder will be on the same level as the generated javascript and html output. Simply: `image: "assets/robbie.jpg"` should work. Upvotes: 0 <issue_comment>username_2: Try this syntax: `img src="assets/robbie.jpg"` Angular know assets folder path, we don't require to tell explicitly. Upvotes: 1 <issue_comment>username_3: try this ``` export class AppComponent { public contacts = [ { name: "<NAME>", image: "../assets/robbie.jpg", email: "XXXXXXXX", phone: "XXXXXXX", role: "Software Developer", address: "XXXXXXX", notes: "XXXXXXX", selected: false }, ... ] } ``` Upvotes: 0
2018/03/17
1,399
4,684
<issue_start>username_0: I'm trying the solve the first question in [Advent of Code 2017](http://adventofcode.com/2017/day/1), and come up with the following solution to calculate the needed value: ``` checkRepetition :: [Int] -> Bool checkRepetition [] = False checkRepetition (x:xs) | x == ( head xs ) = True | otherwise = False test :: [Int] -> Int test [] = 0 test [x] = 0 test xs | checkRepetition xs == True = ((head xs)*a) + (test (drop a xs)) | otherwise = test (tail xs) where a = (go (tail xs)) + 1 go :: [Int] -> Int go [] = 0 go xs | checkRepetition xs == True = 1 + ( go (tail xs) ) | otherwise = 0 ``` However, when I give an input that contains repetitive numbers such as `[1,3,3]`, it gives the error > > \*\*\* Exception: Prelude.head: empty list > > > However, for 1.5 hours, I couldn't figure out exactly where this error is generated. I mean any function that is used in `test` function have a definition for `[]`, but still it throws this error, so what is the problem ? Note that, I have checked out [this](https://stackoverflow.com/questions/15285439/haskell-prelude-head-error-empty-list) question, and in the given answer, it is advised not to use `head` and `tail` functions, but I have tested those function for various inputs, and they do not throw any error, so what exactly is the problem ? I would appreciate any help or hint.<issue_comment>username_1: As was pointed out in the comments, the issue is here: ``` checkRepetition (x:xs) | x == ( head xs ) = True ``` `xs` is not guaranteed to be a non-empty list (a one-element list is written as `x:[]`, so that `(x:xs)` pattern matches that `xs = []`) and calling `head` on an empty list is a runtime error. You can deal with this by changing your pattern to only match on a 2+ element list. ``` checkRepetition [] = False checkRepetition [_] = False checkRepetition (x1:x2:_) = x1 == x2 -- No need for the alternations on this function, by the way. ``` --- That said, your algorithm seems needlessly complex. All you have to do is check if the *next* value is equal, and if so then add the current value to the total. Assuming you can get your `String -> [Int]` on your own, consider something like: ``` filteredSum :: [Int] -> Int filteredSum [] = 0 -- by definition, zero- and one-element lists filteredSum [_] = 0 -- cannot produce a sum, so special case them here filteredSum xss@(first:_) = go xss where -- handle all recursive cases go (x1:xs@(x2:_)) | x1 == x2 = x1 + go xs | otherwise = go xs -- base case go [x] | x == first = x -- handles last character wrapping | otherwise = 0 -- and if it doesn't wrap -- this should be unreachable go [] = 0 ``` For what it's worth, I think it's better to work in the Maybe monad and operate over `Maybe [Int] -> Maybe Int`, but luckily that's easy since Maybe is a functor. ``` digitToMaybeInt :: Char -> Maybe Int digitToMaybeInt '0' = Just 0 digitToMaybeInt '1' = Just 1 digitToMaybeInt '2' = Just 2 digitToMaybeInt '3' = Just 3 digitToMaybeInt '4' = Just 4 digitToMaybeInt '5' = Just 5 digitToMaybeInt '6' = Just 6 digitToMaybeInt '7' = Just 7 digitToMaybeInt '8' = Just 8 digitToMaybeInt '9' = Just 9 digitToMaybeInt _ = Nothing maybeResult :: Maybe Int maybeResult = fmap filteredSum . traverse digitToMaybeInt $ input result :: Int result = case maybeResult of Just x -> x Nothing -> 0 -- this is equivalent to `maybe 0 id maybeResult` ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Thank you for the link. I went there first to glean the purpose. I assume the input will be a string. The helper function below constructs a numeric list to be used to sum if predicate is True, that is, the zipped values are equal, that is, each number compared to each successive number (the pair). The helper function 'nl' invokes the primary function 'invcap' Inverse Captcha with a list of numbers. The nl function is a list comprehension. The invcap function is a list comprehension. Perhaps the logic in this question is at fault. Overly complicated logic is more likely to introduce errors. Proofs are very much easier when logic is not cumbersome. The primary function "invcap" ``` invcap l = sum [ x | (x,y) <- zip l $ (tail l) ++ [head l], x == y] ``` The helper function that converts a string to a list of digits and invokes invcap with a list of numeric digits. ``` nl cs = invcap [ read [t] :: Int | t <- cs] ``` Invocation examples Prelude> nl "91212129" ...... 9 ' ' ' ' ' ' ' ' ' ' ' ' ' Prelude> nl "1122" ...... 3 Upvotes: 0
2018/03/17
622
1,558
<issue_start>username_0: ``` new Date(null) // Date 1970-01-01T00:00:00.000Z ``` How come when I type `new Date(null)` in JavaScript console I'm getting `Date 1970-01-01T00:00:00.000Z`?<issue_comment>username_1: Apparently because that (Unix timestamp 0) is what a Date object is initialized to by default, eh? Upvotes: 2 <issue_comment>username_2: Because the ECMAScript 2017 standard says so? The end of ECMA section [20.3.1.1](http://ecma-international.org/ecma-262/8.0/#sec-time-values-and-time-range) claims: > > The exact moment of midnight at the beginning of 01 January, 1970 UTC **is represented by the value +0**. > > > ...which might make you say, "...but!, but!, I did not say +0, I said": ``` new Date(null) ``` Ok, so let's follow the standard on that one... That Date constructor example goes to section [20.3.2.2](http://ecma-international.org/ecma-262/8.0/#sec-date-value), where item **3.b.iii** there says: > > 3.b.iii: Else, let V be ToNumber(v). > > > ToNumber is a hyperlink, so follow that to section [7.1.3](http://ecma-international.org/ecma-262/8.0/#sec-tonumber) where there is a number conversion table that shows: > > **Argument Type  | Result** > > Null                       | +0 > > > Therefore: ``` new Date(null) ``` Effectively becomes: ``` new Date(+0) ``` Which is why you ultimately get: > > Date 1970-01-01T00:00:00.000Z > > > Upvotes: 5 <issue_comment>username_3: On doing new Date(null), it returns Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time) for me. Upvotes: 0
2018/03/17
397
1,341
<issue_start>username_0: I am trying to "parameterize" a drake script by assign a character to an object but I get this warning: ``` plan <- drake_plan(commencement = "dec2017") make(plan) Warning messages: ``` > > 1: missing input files: dec2017 > > 2: File 'dec2017' was built or processed, but the file itself does not exist > > > Everything works fine if I `loadd('commencement')` but I am not what's the non-existant file that is being created. That creates issues later on in the script because `commencement` is embedded in files path.<issue_comment>username_1: As far as I understand drake, you mostly deal with functions. One workaround would be this ``` foo <- function() "dec2017" plan <- drake_plan(commencement = foo()) make(plan) #> target commencement ``` Upvotes: 1 <issue_comment>username_2: This is a known issue which is going to be fixed in newer versions of drake. All you need to do to get your code to work is to run: ``` pkgconfig::set_config("drake::strings_in_dots" = "literals") ``` before `drake_plan`. This tells drake to treat strings as strings, instead of filenames. Alternatively you can pass the argument `strings_as_dots = "literals"` directly to `drake_plan`. File inputs and outputs need to be specified manually in this mode with `file_in` and `file_out`. Upvotes: 1 [selected_answer]
2018/03/17
401
1,422
<issue_start>username_0: I'm appending strings in to one index. I'm unable to check if that index contains the value that will be appended next. Value of the string changes depending on the user input How can I check if the elements array already contains "value1"? Assuming that I have something like this: ``` var km: String = "1" var meters: String = "1000" var array: [String] = [] array.append(km + "Kilometers" + "=" + meters + "meters") if array.contains(km) { //do something } ``` I would like to check if the next value of km that user inputs is the same if it is inform the user that this has been already entered.<issue_comment>username_1: As far as I understand drake, you mostly deal with functions. One workaround would be this ``` foo <- function() "dec2017" plan <- drake_plan(commencement = foo()) make(plan) #> target commencement ``` Upvotes: 1 <issue_comment>username_2: This is a known issue which is going to be fixed in newer versions of drake. All you need to do to get your code to work is to run: ``` pkgconfig::set_config("drake::strings_in_dots" = "literals") ``` before `drake_plan`. This tells drake to treat strings as strings, instead of filenames. Alternatively you can pass the argument `strings_as_dots = "literals"` directly to `drake_plan`. File inputs and outputs need to be specified manually in this mode with `file_in` and `file_out`. Upvotes: 1 [selected_answer]
2018/03/17
2,078
8,487
<issue_start>username_0: I'm using the fullpage.js and on the second section scrolloverflow.js is active. for the second section I'd like a footer that sticks to the bottom of the viewport. instead of doing so, the footer stays in place while scrolling within the content of the second section as you can see in the jsfiddle. Is there a way to keep the footer locked to the bottom of the viewport of the second section only? Thanks in advance. snippet is not displaying accordingly, so jsfiddle which works: <https://jsfiddle.net/L1fhbj36/20/> Snippet: ```js $(document).ready(function() { $('#fullpage').fullpage({ sectionsColor: ['#FFF', '#FFF'], scrollOverflow: true, }); }); ``` ```css body { background: #FFF; } html, body { height: 100%; margin: 0 auto; } html { overflow-y: auto; } #splash { position: absolute; left: 0; bottom: 0; top: 0; right: 0; width: 100%; height: 100%; background-size: 100% 100%; background-color: #FFF; background-image: url("https://thenypost.files.wordpress.com/2017/06/duck.jpg?quality=90&strip=all"); background-size: cover; } #section0 .layer { position: absolute; z-index: 4; width: 100%; left: 0; top: 43%; -webkit-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } #section0 { overflow: hidden; } .footer { width: 100%; height: 3em; left: 0; bottom: 0; position: fixed; background-color: grey; } ``` ```html Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ```<issue_comment>username_1: you gave your footer position attribute fixed.. try absolute instead ```css .footer { width: 100%; height: 3em; left: 0; bottom: 0; position: absolute; background-color: grey; } ``` Upvotes: -1 <issue_comment>username_2: According to the [docs](https://github.com/alvarotrigo/fullPage.js/#fullpagejs) you were missing the `fixedElements` option. I added that and created a working snippet. Also, here's the updated fiddle as well <https://jsfiddle.net/L1fhbj36/63/> ```js $(document).ready(function() { $('#fullpage').fullpage({ sectionsColor: ['#FFF', '#FFF'], scrollOverflow: true, fixedElements: '.footer' }); }); ``` ```css body { background: #FFF; } html, body { height: 100%; margin: 0 auto; } html { overflow-y: auto; } #splash { position: absolute; left: 0; bottom: 0; top: 0; right: 0; width: 100%; height: 100%; background-size: 100% 100%; background-color: #FFF; background-image: url("https://thenypost.files.wordpress.com/2017/06/duck.jpg?quality=90&strip=all"); background-size: cover; } #section0 .layer { position: absolute; z-index: 4; width: 100%; left: 0; top: 43%; -webkit-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } #section0 { overflow: hidden; } .footer { width: 100%; height: 3em; left: 0; bottom: 0; position: fixed; background-color: grey; } ``` ```html Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ``` Upvotes: 0 <issue_comment>username_3: Just place the fixed element outside the `fp-scrollable` one by using javacript on the `afterRender` callback. Then use `position:absolute` for it instead of fixed and use `position:relative` for `.fp-section` or `.section`. Upvotes: 0
2018/03/17
3,083
11,043
<issue_start>username_0: I've created this two extensions in Kotlin to Encrypt/Decrypt strings: ``` fun String.encrypt(seed : String): String { val keyGenerator = KeyGenerator.getInstance("AES") val secureRandom = SecureRandom.getInstance("SHA1PRNG") secureRandom.setSeed(seed.toByteArray()) keyGenerator.init(128, secureRandom) val skey = keyGenerator.generateKey() val rawKey : ByteArray = skey.encoded val skeySpec = SecretKeySpec(rawKey, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, skeySpec) val byteArray = cipher.doFinal(this.toByteArray()) return byteArray.toString() } fun String.decrypt(seed : String): String { val keyGenerator = KeyGenerator.getInstance("AES") val secureRandom = SecureRandom.getInstance("SHA1PRNG") secureRandom.setSeed(seed.toByteArray()) keyGenerator.init(128, secureRandom) val skey = keyGenerator.generateKey() val rawKey : ByteArray = skey.encoded val skeySpec = SecretKeySpec(rawKey, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, skeySpec) val byteArray = cipher.doFinal(this.toByteArray()) return byteArray.toString() } ``` for some reason I'm getting the following exception: ``` javax.crypto.IllegalBlockSizeException: last block incomplete in decryption ``` What I'm doing wrong?<issue_comment>username_1: To encode your ciphertext use base 64 or hexadecimals. The Java API contains a Base64 class, so you're probably best off using that. `byte[]#toString` doesn't do what you expect it to do; it simply returns a representation of the *byte array reference*, not the contents of the byte array. --- Besides that: * don't use SecureRandom to derive a key, try and lookup PBKDF2; * explicitly use a mode of operation such as `"AES/GCM/NoPadding"`; * use a unique IV, and a random IV if you decide to use CBC (usually insecure); * don't use `toByteArray` without explicitly selecting a character encoding for the message. Upvotes: 4 [selected_answer]<issue_comment>username_2: Following Maarten Bodews guides I fix the issues as: ``` fun String.encrypt(password: String): String { val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES") val iv = ByteArray(16) val charArray = password.toCharArray() for (i in 0 until charArray.size){ iv[i] = charArray[i].toByte() } val ivParameterSpec = IvParameterSpec(iv) val cipher = Cipher.getInstance("AES/GCM/NoPadding") cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec) val encryptedValue = cipher.doFinal(this.toByteArray()) return Base64.encodeToString(encryptedValue, Base64.DEFAULT) } fun String.decrypt(password: String): String { val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES") val iv = ByteArray(16) val charArray = password.toCharArray() for (i in 0 until charArray.size){ iv[i] = charArray[i].toByte() } val ivParameterSpec = IvParameterSpec(iv) val cipher = Cipher.getInstance("AES/GCM/NoPadding") cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec) val decryptedByteValue = cipher.doFinal(Base64.decode(this, Base64.DEFAULT)) return String(decryptedByteValue) } ``` Upvotes: 3 <issue_comment>username_3: AES Encryption / Decryption using base64 key, salt and iv (Initialization Vector). ``` object AESEncyption { const val secretKey = "<KEY> const val salt = "QWlGNHNhMTJTQWZ2bGhpV3U=" // base64 decode => AiF4sa12SAfvlhiWu const val iv = "bVQzNFNhRkQ1Njc4UUFaWA==" // base64 decode => mT34SaFD5678QAZX fun encrypt(strToEncrypt: String) : String? { try { val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT)) val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256) val tmp = factory.generateSecret(spec) val secretKey = SecretKeySpec(tmp.encoded, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding") cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec) return Base64.encodeToString(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)), Base64.DEFAULT) } catch (e: Exception) { println("Error while encrypting: $e") } return null } fun decrypt(strToDecrypt : String) : String? { try { val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT)) val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val spec = PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256) val tmp = factory.generateSecret(spec); val secretKey = SecretKeySpec(tmp.encoded, "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); return String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT))) } catch (e : Exception) { println("Error while decrypting: $e"); } return null } } ``` iOS [swift](https://stackoverflow.com/a/60752764/8956604) Upvotes: 4 <issue_comment>username_4: Following username_2 guide I reduce it like this this: ``` const val encryptionKey = "ENCRYPTION_KEY" fun String.cipherEncrypt(encryptionKey: String): String? { try { val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES") val iv = encryptionKey.toByteArray() val ivParameterSpec = IvParameterSpec(iv) val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec) val encryptedValue = cipher.doFinal(this.toByteArray()) return Base64.encodeToString(encryptedValue, Base64.DEFAULT) } catch (e: Exception) { e.message?.let{ Log.e("encryptor", it) } } return null } fun String.cipherDecrypt(encryptionKey: String): String? { try { val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES") val iv = encryptionKey.toByteArray() val ivParameterSpec = IvParameterSpec(iv) val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec) val decodedValue = Base64.decode(this, Base64.DEFAULT) val decryptedValue = cipher.doFinal(decodedValue) return String(decryptedValue) } catch (e: Exception) { e.message?.let{ Log.e("decryptor", it) } } return null } ``` Upvotes: 0 <issue_comment>username_5: The easiest way of implementing AES Encryption and Decryption in Android is to copy this class in your projects. **Encrypt Strings** Please copy the AESUtils class in your project first and then you can use it like this. ``` String encrypted = ""; String sourceStr = "This is any source string"; try { encrypted = AESUtils.encrypt(sourceStr); Log.d("TEST", "encrypted:" + encrypted); } catch (Exception e) { e.printStackTrace(); } ``` **Decrypt Strings** ``` String encrypted = "ANY_ENCRYPTED_STRING_HERE"; String decrypted = ""; try { decrypted = AESUtils.decrypt(encrypted); Log.d("TEST", "decrypted:" + decrypted); } catch (Exception e) { e.printStackTrace(); } ``` **AESUtils Class** ``` import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESUtils { private static final byte[] keyValue = new byte[]{'c', 'o', 'd', 'i', 'n', 'g', 'a', 'f', 'f', 'a', 'i', 'r', 's', 'c', 'o', 'm'}; public static String encrypt(String cleartext) throws Exception { byte[] rawKey = getRawKey(); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String encrypted) throws Exception { byte[] enc = toByte(encrypted); byte[] result = decrypt(enc); return new String(result); } private static byte[] getRawKey() throws Exception { SecretKey key = new SecretKeySpec(keyValue, "AES"); byte[] raw = key.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKey skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] encrypted) throws Exception { SecretKey skeySpec = new SecretKeySpec(keyValue, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } } ``` Upvotes: 2 <issue_comment>username_6: You can Encrypt and Decrypt in Kotlin like this first you need: ``` val SECRET_KEY = "secretKey" val SECRET_IV = "secretIV" ``` after that Encrypt: ``` private fun String.encryptCBC(): String { val iv = IvParameterSpec(SECRET_IV.toByteArray()) val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv) val crypted = cipher.doFinal(this.toByteArray()) val encodedByte = Base64.encode(crypted, Base64.DEFAULT) return String(encodedByte) } ``` and Decrypt: ``` private fun String.decryptCBC(): String { val decodedByte: ByteArray = Base64.decode(this, Base64.DEFAULT) val iv = IvParameterSpec(SECRET_IV.toByteArray()) val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES") val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING") cipher.init(Cipher.DECRYPT_MODE, keySpec, iv) val output = cipher.doFinal(decodedByte) return String(output) } ``` after that you can use it like this: ``` val strEncrypt = edt.text.toString().encryptCBC() val strDecrypted = strEncrypt?.decryptCBC() ``` Upvotes: 2
2018/03/17
558
1,699
<issue_start>username_0: How do I make this work? `[Jack's Birthday](javascript:func("Jack)`<issue_comment>username_1: If possible, do it this way ``` function func(x) { alert(x); } [Birthday](javascript:func('Norman\'S Birthday')) ``` Upvotes: 0 <issue_comment>username_2: Convert to NCR. This should work. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Or. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Upvotes: 0 <issue_comment>username_3: > > Do as follows: > > > ```js // How about using variables instead? var emily = "Emily'S Birthday" var birthdays = { john: "John'S Birthday" } function func(val) { console.log(val); } ``` ```html [Jack's Birthday](javascript:func("Jack'S Birthday")) [Norman's Birthday](javascript:func('Norman\'S Birthday')) [Emily's Birthday](javascript:func(emily)) [John's Birthday](javascript:func(birthdays.john)) ``` > > Explanation: > > > 1. Keep single quotes within double quotes when you escape using backslash `\` 2. Use double quotes within single quotes when you use `$apos;` 3. Best of all, use variables, they ease a lot of pain - a. You don't have to go into html to modify values, b. these can be declared at one place, or a single file, c. They can be fetched from back-end d. Best yet, no need to deal with quotes! Upvotes: 2 [selected_answer]<issue_comment>username_4: Apparently you can't escape characters within HTML attributes. The proper way to go would be to use HTML entities like `'` : ```html [click me](javascript:console.log("'")) ``` See [How to properly escape quotes inside html attributes?](https://stackoverflow.com/q/4015345/1636522). Upvotes: 1
2018/03/17
653
2,042
<issue_start>username_0: My bootstrap navbar toggle button stopped working after I restarted my PC. Ive tried to troubleshoot it but I could not find the problem. Here is my code: ```html Ebere Orisi [Ebere Orisi](https://blurpshell.github.io) [IT SECURITY (current)](#itSec) [SOFTWARE & WEB](#webDev) [CONTACT](#getInTouch) ``` Please what could the problem be. Here is the actual site: <https://ebereorisi.github.io><issue_comment>username_1: If possible, do it this way ``` function func(x) { alert(x); } [Birthday](javascript:func('Norman\'S Birthday')) ``` Upvotes: 0 <issue_comment>username_2: Convert to NCR. This should work. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Or. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Upvotes: 0 <issue_comment>username_3: > > Do as follows: > > > ```js // How about using variables instead? var emily = "Emily'S Birthday" var birthdays = { john: "John'S Birthday" } function func(val) { console.log(val); } ``` ```html [Jack's Birthday](javascript:func("Jack'S Birthday")) [Norman's Birthday](javascript:func('Norman\'S Birthday')) [Emily's Birthday](javascript:func(emily)) [John's Birthday](javascript:func(birthdays.john)) ``` > > Explanation: > > > 1. Keep single quotes within double quotes when you escape using backslash `\` 2. Use double quotes within single quotes when you use `$apos;` 3. Best of all, use variables, they ease a lot of pain - a. You don't have to go into html to modify values, b. these can be declared at one place, or a single file, c. They can be fetched from back-end d. Best yet, no need to deal with quotes! Upvotes: 2 [selected_answer]<issue_comment>username_4: Apparently you can't escape characters within HTML attributes. The proper way to go would be to use HTML entities like `'` : ```html [click me](javascript:console.log("'")) ``` See [How to properly escape quotes inside html attributes?](https://stackoverflow.com/q/4015345/1636522). Upvotes: 1
2018/03/17
713
2,218
<issue_start>username_0: It's works: ```js var onChange = function (isVisible) { console.log('Element is now %s', isVisible ? 'visible' : 'hidden'); if(isVisible = 'visible'){ //here I need add class } }; ``` And the VisibilitySensor is in inside component **Needs** in div className =**Need**. ```xml ``` The code is working well, I can see console.log after rendering. So. what is my problem. I wan't add class **animated fadeInUp**. **if isVisible = 'visible'** How can I add this class to **Needs** className React? If it help, here is all code: <https://pastebin.com/bnTKbXC4><issue_comment>username_1: If possible, do it this way ``` function func(x) { alert(x); } [Birthday](javascript:func('Norman\'S Birthday')) ``` Upvotes: 0 <issue_comment>username_2: Convert to NCR. This should work. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Or. ``` [Birthday](javascript:func("Norman'S Birthday")) ``` Upvotes: 0 <issue_comment>username_3: > > Do as follows: > > > ```js // How about using variables instead? var emily = "Emily'S Birthday" var birthdays = { john: "John'S Birthday" } function func(val) { console.log(val); } ``` ```html [Jack's Birthday](javascript:func("Jack'S Birthday")) [Norman's Birthday](javascript:func('Norman\'S Birthday')) [Emily's Birthday](javascript:func(emily)) [John's Birthday](javascript:func(birthdays.john)) ``` > > Explanation: > > > 1. Keep single quotes within double quotes when you escape using backslash `\` 2. Use double quotes within single quotes when you use `$apos;` 3. Best of all, use variables, they ease a lot of pain - a. You don't have to go into html to modify values, b. these can be declared at one place, or a single file, c. They can be fetched from back-end d. Best yet, no need to deal with quotes! Upvotes: 2 [selected_answer]<issue_comment>username_4: Apparently you can't escape characters within HTML attributes. The proper way to go would be to use HTML entities like `'` : ```html [click me](javascript:console.log("'")) ``` See [How to properly escape quotes inside html attributes?](https://stackoverflow.com/q/4015345/1636522). Upvotes: 1
2018/03/17
265
963
<issue_start>username_0: Getting error while loading css on angular5 with ngx-bootstrap `Refused to apply style from 'http://localhost:3000/node_modules/ngx-bootstrap/datepicker/bs-datepicker.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.` i have include css only in index.html<issue_comment>username_1: try adding the following inside of your link tag : ``` type="text/css" ``` Best regards Upvotes: 0 <issue_comment>username_2: You can also add the style in your `.angular-cli.json`, if you're using ng-cli. Then Angular CLI will take care of adding the file to index.html for you: ``` { ... "styles" : [ "../../../node_modules/bootstrap/dist/css/bootstrap.min.css", "../../../node_modules/ngx-bootstrap/datepicker/bs-datepicker.css", "styles.scss", ... ], ... } ``` Alternatively, if not angular-cli, then webpack can take care of this for you. Upvotes: 1
2018/03/17
826
2,801
<issue_start>username_0: thanks in advance your your help; I rather a newbie with RN and Android (i used create-native init to create project). Issue 1: when i first `ctrl`+`M` and choose "Debug JS Remotely" it attempts [<http://10.0.2.2:8081/debugger-ui]> but hangs indefinitely. Issue 2. and when I finally give up and instead manually visit [<http://localhost:8081/debugger-ui/]>, I have no way to revert AVD from "white screen of death"..ive tried "Stop Remote JS Bebugging", "Reload" etc....but end of having to use "react-native run-android" to refresh Issue 3: Once I finally have [<http://localhost:8081/debugger-ui/]> displaying the desired "Debugger session #0 active" and I go into dev tools --> Sources --> Network --> debuggerWorker.js.....I don't see my folders/files listed. See screenshot. RN is hard enough without being able to debug! [![enter image description here](https://i.stack.imgur.com/0Q5UL.png)](https://i.stack.imgur.com/0Q5UL.png)<issue_comment>username_1: This is an issue with the of latest version of react-native (0.54). After some investigation, I found there are two ways to workaround this issue. ### Option 1. Downgrade react versions, modify the package.json of your AwesomeProject as below ```js "dependencies": { "react": "16.2.0", "react-native": "0.52.2" }, ``` Then run these commands: ```sh cd AwesomeProject rm -rf node_modules android npm install # this will bring folder node_modules back, with react/react-native of previous version react-native eject # this will bring folder android back react-native run-android ``` ### Option 2. Turning off `Use JS Deltas` as mentioned in [this issue](https://github.com/facebook/react-native/issues/18416) But the author did not provide full steps, which led me working out option 1. 1. `Cmd`+`m` in your emulator, and turn off "Use JS Deltas". 2. Find the termnial window for "Metro Bundler", press `Ctrl`+`c` to terminate it, then press the Up arrow to re-run the command for "Metro Bundler", such as `/works/StackOverflow/node_modules/react-native/scripts/launchPackager.command ; exit;`. (**This is an important step**). Now back to Chrome, you can find your source files listed under `debuggerWorker.js` > `localhost:8081`. [![enter image description here](https://i.stack.imgur.com/Vei3e.png)](https://i.stack.imgur.com/Vei3e.png) Upvotes: 3 <issue_comment>username_2: This solution worked for me: 1. `ctrl+m` on your emulator. 2. click on `Dev Settings`. 3. Disable `User JS Delta` 4. restart the react native server. (ctrl+c in the terminal and then `npm run android`) Upvotes: 4 <issue_comment>username_3: I was having the same issue , manage to fix it by going setting inside inspect element and enable the javascript ![Screenshot](https://i.stack.imgur.com/tMASO.png) Upvotes: 0
2018/03/17
1,021
3,612
<issue_start>username_0: I am using Node.js to modify a html file which contains a lot: ``` ![](img/scene1.jpg) ``` how every I want to replace this part to : ``` ![](img/scene1.jpg) ``` The id attribute should be from 1 to 141 like: id="scene\_1, id="scene\_2"... I wrote a program as blow: ``` var fs = require('fs') fs.readFile("my_story.html", 'utf8', function (err,data) { if (err) { return console.log(err); } var source = data.toString(); var regexp = /![](img/g; var nodeCount = (source.match(regexp) || []).length; var count = 0; while (count < nodeCount) { var result = data.replace(regexp, '<img src=) ``` However, it gives me this result: ``` ![](img/scene1.jpg) ``` and all the id="scene\_141". Anyone know how to fix it? Thank you so much in advanced!<issue_comment>username_1: Modify complete `img` tag.You just need to modify the regex slightly to ``` var regexp = /![](\"img\/scene1.jpg\")/g; ``` Also, check that double quotes close in `result` Upvotes: 0 <issue_comment>username_2: Try this: ``` var fs = require('fs') fs.readFile("my_story.html", 'utf8', function (err,data) { if (err) { return console.log(err); } var source = data.toString(); var regexp = `![](img/scene1.jpg)`; var nodeCount = (source.match(new RegExp(regexp, 'g')) || []).length; var count = 0; while (count < nodeCount) { data = data.replace(new RegExp(regexp), '![](img/scene1.jpg) ``` to count them you need the global flag then replacing them you would need to replace only the first match. and you should write the new data to the file only once after you finish your editing to the file. Upvotes: 1 <issue_comment>username_3: Firstly, as with many questions like this, the real answer is: "Don't do this by hand, there are parsing libraries out there which you can use.". For example, there's an npm module called `cheerio` which does jQuery-style manipulation of HTML structures. I don't know how good it is, it's the only one I've heard of so it's worth trying out if you're familiar with jQuery, but there are undoubtedly others. However, if you still want to do it your way... username_2's answer looks right to me, but it doesn't explain what's wrong with your code so I'll write another answer. The problem is the `/g` flag on the regex. This is needed on the first appearance of the regex. However, the second time round, it causes the `.replace` method to replace *all* substrings which match the regex. But it still goes through the loop `nodeCount` times. Each time, it overwrites the copy of the file that was saved in the previous iteration. The last iteration of the loop is likely to be the one that wins out, hence the id is `scene_141`. (However, depending on the filesystem, the file size and blind luck, it may sometimes show a slightly lower scene number, or even a corrupted file. But I don't know if this is likely/possible.) username_2 chose to solve this by deactivating the `/g` flag on the replace. But you could also use `/g`, like this: ``` var regexp = /![](img\/scene1\.jpg)/g; var count = 0; var result = data.replace(regexp, function() { var currentCount = count; count++; return '<img src="img/scene1.jpg" class="img-responsive" id="scene_' + currentCount +'>'; }); ``` Each time the function is called, it returns a string which will replace the substring which matches the regex. It returns an HTML string where the id increases by 1 each time. username_2 has also sensibly moved the `fs.writeFile` outside the loop, so it doesn't keep overwriting the file. Upvotes: 3 [selected_answer]
2018/03/17
776
2,300
<issue_start>username_0: Based on the following information, [![enter image description here](https://i.stack.imgur.com/VGFyD.png)](https://i.stack.imgur.com/VGFyD.png) [![enter image description here](https://i.stack.imgur.com/LiX32.png)](https://i.stack.imgur.com/LiX32.png) we know that Java's `short` spans from `-32768 (=0x8000)` to `32767 (=0x7FFF)` and casting is optional. What I don't understand is that why do we have to cast `0x8000` to `short` *explicitly*? ``` public static void main(String[] args) { short x; x = (short) 0x8000; // x = 0x8000; // have to cast 0x8000 to short System.out.println(x); } ``` I am using NetBeans on Windows.<issue_comment>username_1: You forgot to add the sign: the positive value `0x8000` is too large for a `short`, `-0x8000` should work. Upvotes: 2 <issue_comment>username_2: `0x8000` is firstly interpreted as an integer with the value `32768`, and then Java attempts to convert that to a short, which it is then unable to do, because `32768` doesn't fit into a short. Note that just using `32768` instead also gives the same result: ``` short x = (short)32768; System.out.println(x); // -32768 ``` As another example, consider this line of code: ``` short x = 0xffff8000; System.out.println(x); // -32768 ``` No cast is necessary here because `0xffff8000` is the integer `-32768`, and that fits into a short. But don't ask me why they made the decision to make things work this way (it might've been just to keep things simple for the compiler). --- The only applicable extract I could find in the JLS comes from [5.2. Assignment Contexts](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2): ([3.10.1. Integer Literals](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.1) is also relevant) (but I could certainly have missed a relevant part) > > In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: > > > * A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable > > > Although this does, in my opinion, leave some ambiguity about the intended behaviour here. Upvotes: 3 [selected_answer]
2018/03/17
1,361
5,115
<issue_start>username_0: When I click the raised button, the timepicker is showing up. Now, if I wait 5 seconds, for example, and then confirm the time, this error will occur: **setState() called after dispose()** I literally see in the console how flutter is updating the parent widgets, but why? I don't do anything - I just wait 5 seconds?! The example below will work in a normal project, however in my project which is quite more complex it won't work because Flutter is updating the states while I am waiting... What am I doing wrong? Does anyone have a guess at what it could be that Flutter is updating randomly in my more complex project and not in a simple project? **[UPDATE]** I took a second look at it and found out it is updating from the level on where my `TabBar` and `TabBarView` are. Could it have to do something with the "**with TickerProviderStateMixin**" which I need for the `TabBarView`? Could it be that it causes the app to refresh regularly and randomly? ``` class DateTimeButton extends State { DateTime selectedDate = new DateTime.now(); Future initTimePicker() async { final TimeOfDay picked = await showTimePicker( context: context, initialTime: new TimeOfDay(hour: selectedDate.hour, minute: selectedDate.minute), ); if (picked != null) { setState(() { selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute); }); } } @override Widget build(BuildContext context) { return new RaisedButton( child: new Text("${selectedDate.hour} ${selectedDate.minute}"), onPressed: () { initTimePicker(); } ); } } ```<issue_comment>username_1: If it is an expected behavior that the `Future` completes when the widget already got disposed you can use ``` if (mounted) { setState(() { selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute); }); } ``` Upvotes: 6 <issue_comment>username_2: Try this ``` Widget build(BuildContext context) { return new RaisedButton( child: new Text("${selectedDate.hour} ${selectedDate.minute}"), onPressed: () async { await initTimePicker(); } ); } ``` Upvotes: 2 <issue_comment>username_3: Just check boolean property `mounted` of the state class of your widget before calling `setState()`. ``` if (this.mounted) { setState(() { // Your state change code goes here }); } ``` Or even more clean approach Override `setState` method in your `StatelfulWidget` class. ``` class DateTimeButton extends StatefulWidget { @override void setState(fn) { if(mounted) { super.setState(fn); } } } ``` Upvotes: 10 [selected_answer]<issue_comment>username_4: Just write one line before `setState()` ``` if (!mounted) return; ``` and then ``` setState(() { //Your code }); ``` Upvotes: 5 <issue_comment>username_5: I had the same problem and i solved changing the super constructor call order on `initState()`: Wrong code: ``` @override void initState() { foo_bar(); // call setState(); super.initState(); // then foo_bar() } ``` Right code: ``` @override void initState() { super.initState(); foo_bar(); // first call super constructor then foo_bar that contains setState() call } ``` Upvotes: 4 <issue_comment>username_6: To prevent the error from occurring, one can make use of the `mounted` property of the `State` class to ensure that a widget is mounted before settings its state: ``` // First Update data if (!mounted) { return; } setState(() { } ``` Upvotes: 3 <issue_comment>username_7: ``` class MountedState extends State { @override Widget build(BuildContext context) { return null; } @override void setState(VoidCallback fn) { if (mounted) { super.setState(fn); } } } ``` **Example** To prevent the error,Instead of using State use **MountedState** ``` class ExampleStatefulWidget extends StatefulWidget { const ExampleStatefulWidget({Key key}) : super(key: key); @override _ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState(); } class _ExampleStatefulWidgetState extends MountedState { .... } ``` Upvotes: 3 <issue_comment>username_8: I had this error when I mistakenly called super.initState before the variable. Check this: ``` @override void initState() { super.initState(); bloc = MainBloc(); } ``` Should be fixed as ``` @override void initState() { bloc = MainBloc(); super.initState(); } ``` Upvotes: 0 <issue_comment>username_9: The problem could occur when you have long asynchronous operation in stateful widget that could be closed/disposed before the operation finished. Futures in Dart are not preemptive, so the only way is to check if a widget mounted before calling setState. If you have a lot of widgets with asynchrony, adding ton of `if (mounted)` checks is tedious and an extension method might be useful ``` extension FlutterStateExt on State { void setStateIfMounted(VoidCallback fn) { if (mounted) { // ignore: invalid\_use\_of\_protected\_member setState(fn); } } } ``` Upvotes: 2
2018/03/17
1,506
5,207
<issue_start>username_0: I am new to React-Native and struggling to return objects from a nested array (Hopefully I am using the correct terminology). I am grabbing my data from the tfl tube status api JSON is below: ``` [ { "$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities", "id": "bakerloo", "name": "Bakerloo", "modeName": "tube", "disruptions": [], "created": "2018-03-13T13:40:58.76Z", "modified": "2018-03-13T13:40:58.76Z", "lineStatuses": [ { "$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities", "id": 0, "statusSeverity": 10, "statusSeverityDescription": "Good Service", "created": "0001-01-01T00:00:00", "validityPeriods": [] } ], "routeSections": [], "serviceTypes": [], "crowding": {} }, ``` I am fetching the data using Axios. ``` state = { lineDetails: [] }; componentDidMount() { axios.get('https://api.tfl.gov.uk/line/mode/tube/status') .then(response => this.setState({ lineDetails: response.data })); }; ``` I am returning the data like this. ``` renderLineDetails() { return this.state.lineDetails.map((details) => )}; render() { return ( {this.renderLineDetails()} ); } My TubeList component looks like: const TubeList = ({ details }) => { const { name, statusSeverityDescription } = details; const { nameStyle, statusStyle } = styles; return ( {name} {statusSeverityDescription} ); ``` }; Is someone able to explain why statusSeverityDescription is not displaying in my list below. [Iphone Simulator image](https://i.stack.imgur.com/pd8wa.png) Thank you.<issue_comment>username_1: If it is an expected behavior that the `Future` completes when the widget already got disposed you can use ``` if (mounted) { setState(() { selectedDate = new DateTime(selectedDate.year, selectedDate.month, selectedDate.day, picked.hour, picked.minute); }); } ``` Upvotes: 6 <issue_comment>username_2: Try this ``` Widget build(BuildContext context) { return new RaisedButton( child: new Text("${selectedDate.hour} ${selectedDate.minute}"), onPressed: () async { await initTimePicker(); } ); } ``` Upvotes: 2 <issue_comment>username_3: Just check boolean property `mounted` of the state class of your widget before calling `setState()`. ``` if (this.mounted) { setState(() { // Your state change code goes here }); } ``` Or even more clean approach Override `setState` method in your `StatelfulWidget` class. ``` class DateTimeButton extends StatefulWidget { @override void setState(fn) { if(mounted) { super.setState(fn); } } } ``` Upvotes: 10 [selected_answer]<issue_comment>username_4: Just write one line before `setState()` ``` if (!mounted) return; ``` and then ``` setState(() { //Your code }); ``` Upvotes: 5 <issue_comment>username_5: I had the same problem and i solved changing the super constructor call order on `initState()`: Wrong code: ``` @override void initState() { foo_bar(); // call setState(); super.initState(); // then foo_bar() } ``` Right code: ``` @override void initState() { super.initState(); foo_bar(); // first call super constructor then foo_bar that contains setState() call } ``` Upvotes: 4 <issue_comment>username_6: To prevent the error from occurring, one can make use of the `mounted` property of the `State` class to ensure that a widget is mounted before settings its state: ``` // First Update data if (!mounted) { return; } setState(() { } ``` Upvotes: 3 <issue_comment>username_7: ``` class MountedState extends State { @override Widget build(BuildContext context) { return null; } @override void setState(VoidCallback fn) { if (mounted) { super.setState(fn); } } } ``` **Example** To prevent the error,Instead of using State use **MountedState** ``` class ExampleStatefulWidget extends StatefulWidget { const ExampleStatefulWidget({Key key}) : super(key: key); @override _ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState(); } class _ExampleStatefulWidgetState extends MountedState { .... } ``` Upvotes: 3 <issue_comment>username_8: I had this error when I mistakenly called super.initState before the variable. Check this: ``` @override void initState() { super.initState(); bloc = MainBloc(); } ``` Should be fixed as ``` @override void initState() { bloc = MainBloc(); super.initState(); } ``` Upvotes: 0 <issue_comment>username_9: The problem could occur when you have long asynchronous operation in stateful widget that could be closed/disposed before the operation finished. Futures in Dart are not preemptive, so the only way is to check if a widget mounted before calling setState. If you have a lot of widgets with asynchrony, adding ton of `if (mounted)` checks is tedious and an extension method might be useful ``` extension FlutterStateExt on State { void setStateIfMounted(VoidCallback fn) { if (mounted) { // ignore: invalid\_use\_of\_protected\_member setState(fn); } } } ``` Upvotes: 2
2018/03/17
578
2,291
<issue_start>username_0: I have a div with text, which I wanna truncate, after one remains only text which can fit. Code below. In internet I only found a plugins, that depends on JQuery, but I know, it possible to do with [Range](https://developer.mozilla.org/en-US/docs/Web/API/Range), if someone had experience, please show me, how do this. ```css .container { height: 60px; border: 1px solid black; } ``` ```html Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem ```<issue_comment>username_1: > > Take a look > > > ```css .container { height: 100px; border: 1px solid black; overflow: auto; /* Try using hidden, scroll, auto or overlay */ } ``` ```html Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem ``` > > Explanation: You can either make the container > > > 1. Scrollable: By using overflow: auto; 2. Non Scrollable: Just plain hides the rest of the content by using overflow: hidden Upvotes: 0 <issue_comment>username_2: You can use something like this: ```js const container = document.querySelector('.container'); let lines = container.querySelectorAll('.text'); const bottomLine = container.getBoundingClientRect().bottom; for (let line of lines) { if (line.getBoundingClientRect().bottom > bottomLine) { container.removeChild(line); } } ``` ```css .container { height: 60px; border: 1px solid black; } ``` ```html Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem ``` Upvotes: 3 [selected_answer]
2018/03/17
768
2,828
<issue_start>username_0: This table is displaying details about my workload table per row. And when I click my "pre-View\_attend" submit button I want to get the "WorkloadID" and "subjectID" of that workload row where the submit button was clicked. Currently I have a hidden field containing the subject ID which is "subjectID\_hidden", and when I try to get the "WorkloadID" and "subjectID" by using isset. It seems that I can't accurately get the exact subject ID of the row where I've clicked the "pre-View\_attend" submit button. ```html | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | php echo $row["subjectName"]; ? | php echo $row["className"]; ? | php echo $row["RoomNumber"]; ? | php echo $Sched\_Days.'<br'.$FST.' To '.$FET;?> | " class="btn btn-primary view\_StudentList">View Student List | " class="btn btn-primary">Take Attendance | " class="btn btn-primary">View Attendance |"> php } mysqli\_close($connect);? /* I'm getting the workload ID accurately, but the subject ID is incorrect. I believe I'm getting the last subject ID that my query produced */ php if(isset($_POST['pre-View_attend'])) { $FWID=$_POST['pre-View_attend']; $FSJID=$_POST['subjectID_hidden']; echo"Workload ID: $FWID SubjectID: $FSJID"; } ? ```<issue_comment>username_1: > > Take a look > > > ```css .container { height: 100px; border: 1px solid black; overflow: auto; /* Try using hidden, scroll, auto or overlay */ } ``` ```html Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem ``` > > Explanation: You can either make the container > > > 1. Scrollable: By using overflow: auto; 2. Non Scrollable: Just plain hides the rest of the content by using overflow: hidden Upvotes: 0 <issue_comment>username_2: You can use something like this: ```js const container = document.querySelector('.container'); let lines = container.querySelectorAll('.text'); const bottomLine = container.getBoundingClientRect().bottom; for (let line of lines) { if (line.getBoundingClientRect().bottom > bottomLine) { container.removeChild(line); } } ``` ```css .container { height: 60px; border: 1px solid black; } ``` ```html Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem Lorem lorem lorem lorem lorem ``` Upvotes: 3 [selected_answer]
2018/03/17
685
1,875
<issue_start>username_0: I have a subquery that returns ``` one_id | two_id -------------------- 1654838 | 1526634 1657136 | 1526634 1659179 | 1526634 1659527 | 1526634 2040608 | 1510944 2040608 | 1516727 ``` I have a table\_x like ``` one_id | two_id | other_column ----------------------------------- 1654838 | 1526634 | ... ... | ... | ... ``` How can I DELETE records FROM table\_x having `one_id` and `two_id` listed in subquery result? If the subquery would return only `one_id` I could use something like ``` DELETE FROM table_x WHERE `one_id` IN (SELECT ... ``` Is there a similar solution with the given subquery result?<issue_comment>username_1: **Update** Yes, the below answer was not correct. I had the chance to test it. But this should work: ``` DELETE FROM mytable2 AS t1 WHERE EXISTS ( SELECT one_id, two_id FROM mytable1 t2 WHERE t1.one_id=t2.one_id AND t1.two_id=t2.two_id ) ``` Update 2: Add an additional WHERE AND clause which will give you the wanted one\_id and two\_id values. Example: ``` WHERE (t2.someothercol > 0 AND t2.someothercol < 10) AND t1.one_id=t2.one_id AND t1.two_id=t2.two_id ``` **Original answer** ~~Maybe something like this (I couldn't test it though):~~ ``` WITH my_subquery AS ( SELECT one_id, two_id FROM some_table ) DELETE FROM table_X AS t1 WHERE t1.one_id=my_subquery.one_id AND t1.two_id=my_subquery.two_id ``` Reference to PostgreSQL documentation: <https://www.postgresql.org/docs/9.1/static/queries-with.html> Upvotes: 2 <issue_comment>username_2: I don't know what's the impact on performance but you can try something like: ``` DELETE FROM table_x WHERE CONCAT(one_id, two_id) IN (SELECT CONCAT(one_id, two_id) ... ``` Probably also casting and/or aliasing is needed. Upvotes: 0
2018/03/17
538
1,635
<issue_start>username_0: how to do rounded tapers like this on sketchup 2018? What I did was, drawing the shape on both surfaces and tried deleting the surfaces. But it didn't create a new surface on taper. As you can see it has a hole, that you can see inside of that column, I want to fill it with a surface, so it can't be see through. <http://i68.tinypic.com/kbsu1s.jpg> [-- the sample pic](http://i68.tinypic.com/kbsu1s.jpg)<issue_comment>username_1: **Update** Yes, the below answer was not correct. I had the chance to test it. But this should work: ``` DELETE FROM mytable2 AS t1 WHERE EXISTS ( SELECT one_id, two_id FROM mytable1 t2 WHERE t1.one_id=t2.one_id AND t1.two_id=t2.two_id ) ``` Update 2: Add an additional WHERE AND clause which will give you the wanted one\_id and two\_id values. Example: ``` WHERE (t2.someothercol > 0 AND t2.someothercol < 10) AND t1.one_id=t2.one_id AND t1.two_id=t2.two_id ``` **Original answer** ~~Maybe something like this (I couldn't test it though):~~ ``` WITH my_subquery AS ( SELECT one_id, two_id FROM some_table ) DELETE FROM table_X AS t1 WHERE t1.one_id=my_subquery.one_id AND t1.two_id=my_subquery.two_id ``` Reference to PostgreSQL documentation: <https://www.postgresql.org/docs/9.1/static/queries-with.html> Upvotes: 2 <issue_comment>username_2: I don't know what's the impact on performance but you can try something like: ``` DELETE FROM table_x WHERE CONCAT(one_id, two_id) IN (SELECT CONCAT(one_id, two_id) ... ``` Probably also casting and/or aliasing is needed. Upvotes: 0
2018/03/17
645
2,255
<issue_start>username_0: I have created a thread with three steps to: 1. Access token request: it generates a token to be used in step three. This token is stored in a property ${\_\_setProperty(accessToken,${accessToken})} 2. Logon Get request to hit a url 3. Logon Post request, pass some data to the url and I have set the Authorisation header using the Bearer + accessToken (the one generated in first step. Running a single thread it works, perfect; but when I increase the number of threads, the 3 steps are not running in sequence, maybe I have some Access token before the first Logon Post and I see the token this one is using is not the token generated in the first step, it is the last one generated. If I set a rump time longer of the total execution time it works, but then I cannot run several threads on parallel. How can I configure the script to run the threads using the correspondent token generated in step 1 in each Post? How can I different properties or variables to store the token of every thread and use them? Thanks.<issue_comment>username_1: **Update** Yes, the below answer was not correct. I had the chance to test it. But this should work: ``` DELETE FROM mytable2 AS t1 WHERE EXISTS ( SELECT one_id, two_id FROM mytable1 t2 WHERE t1.one_id=t2.one_id AND t1.two_id=t2.two_id ) ``` Update 2: Add an additional WHERE AND clause which will give you the wanted one\_id and two\_id values. Example: ``` WHERE (t2.someothercol > 0 AND t2.someothercol < 10) AND t1.one_id=t2.one_id AND t1.two_id=t2.two_id ``` **Original answer** ~~Maybe something like this (I couldn't test it though):~~ ``` WITH my_subquery AS ( SELECT one_id, two_id FROM some_table ) DELETE FROM table_X AS t1 WHERE t1.one_id=my_subquery.one_id AND t1.two_id=my_subquery.two_id ``` Reference to PostgreSQL documentation: <https://www.postgresql.org/docs/9.1/static/queries-with.html> Upvotes: 2 <issue_comment>username_2: I don't know what's the impact on performance but you can try something like: ``` DELETE FROM table_x WHERE CONCAT(one_id, two_id) IN (SELECT CONCAT(one_id, two_id) ... ``` Probably also casting and/or aliasing is needed. Upvotes: 0
2018/03/17
732
3,244
<issue_start>username_0: I have an Azure function triggered by queue messages. This function makes a request to third-party API. Unfortunately this API has limit - 10 transactions per second, but I might have more than 10 messages per second in service bus queue. How can I limit the number of calls of Azure function to satisfy third-party API limitations?<issue_comment>username_1: You can try writing some custom logic i.e. implement your own in-memory queue in Azure function to queue up requests and limit the calls to third party API. Anyway until the call to third party API succeeds, you dont need to acknowledge the messages in the queue. In this way reliability is also maintained. Upvotes: 0 <issue_comment>username_2: Unfortunately there is no built-in option for this. The only reliable way to limit concurrent executions would be to run on a fixed App Service Plan (not Consumption Plan) with just 1 instance running all the time. You will have to pay for this instance. Then set the option in `host.json` file: ``` "serviceBus": { // The maximum number of concurrent calls to the callback the message // pump should initiate. The default is 16. "maxConcurrentCalls": 10 } ``` Finally, make sure your function takes a second to execute (or other minimal duration, and adjust concurrent calls accordingly). As @SeanFeldman suggested, see some other ideas in [this answer](https://stackoverflow.com/a/40096267/1171619). It's about Storage Queues, but applies to Service Bus too. Upvotes: 4 [selected_answer]<issue_comment>username_3: The best way to maintain integrity of the system is to throttle the consumption of the Service Bus messages. You can control how your QueueClient processes the messages, see: <https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues#4-receive-messages-from-the-queue> Check out the "Max Concurrent calls" ``` static void RegisterOnMessageHandlerAndReceiveMessages() { // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc. var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = 1, // Indicates whether the message pump should automatically complete the messages after returning from user callback. // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync(). AutoComplete = false }; // Register the function that processes messages. queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); } ``` Upvotes: 0 <issue_comment>username_4: Do you want to get rid of N-10 messages you receive in a second interval or do you want to treat every message in respect to the API throttling limit? For the latter, you can add the messages processed by your function to another queue from which you can read a batch of 10 messages via another function (timer trigger) every second Upvotes: 1
2018/03/17
864
3,833
<issue_start>username_0: Suppose I have a worker thread that populates a large vector declared in the main thread. While the worker thread is still running (in response to user interaction) I want the main thread to check if the vector has been populated up to a certain size. If it has I want it to extract some values from the vector. If it hasn't i want it to wait till the worker thread populates up to the required size. As the worker thread could still be adding items to the vector (possibly resulting in a resize/move) I'm thinking I can only do this while the worker thread is suspended but TThread.Suspend() is deprecated. I've spent days looking at TMutex, TSemaphore etc. but the documentation is dire. Could anyone point me in the right direction? One possible solution is to populate a separate smaller vector in the worker thread and then use synchronize to append that to the large vector (and so on) but I'd like to avoid that.<issue_comment>username_1: You can try writing some custom logic i.e. implement your own in-memory queue in Azure function to queue up requests and limit the calls to third party API. Anyway until the call to third party API succeeds, you dont need to acknowledge the messages in the queue. In this way reliability is also maintained. Upvotes: 0 <issue_comment>username_2: Unfortunately there is no built-in option for this. The only reliable way to limit concurrent executions would be to run on a fixed App Service Plan (not Consumption Plan) with just 1 instance running all the time. You will have to pay for this instance. Then set the option in `host.json` file: ``` "serviceBus": { // The maximum number of concurrent calls to the callback the message // pump should initiate. The default is 16. "maxConcurrentCalls": 10 } ``` Finally, make sure your function takes a second to execute (or other minimal duration, and adjust concurrent calls accordingly). As @SeanFeldman suggested, see some other ideas in [this answer](https://stackoverflow.com/a/40096267/1171619). It's about Storage Queues, but applies to Service Bus too. Upvotes: 4 [selected_answer]<issue_comment>username_3: The best way to maintain integrity of the system is to throttle the consumption of the Service Bus messages. You can control how your QueueClient processes the messages, see: <https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues#4-receive-messages-from-the-queue> Check out the "Max Concurrent calls" ``` static void RegisterOnMessageHandlerAndReceiveMessages() { // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc. var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = 1, // Indicates whether the message pump should automatically complete the messages after returning from user callback. // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync(). AutoComplete = false }; // Register the function that processes messages. queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); } ``` Upvotes: 0 <issue_comment>username_4: Do you want to get rid of N-10 messages you receive in a second interval or do you want to treat every message in respect to the API throttling limit? For the latter, you can add the messages processed by your function to another queue from which you can read a batch of 10 messages via another function (timer trigger) every second Upvotes: 1
2018/03/17
865
3,632
<issue_start>username_0: I have this raw query but I'm struggling to convert it to eloquent. Below is my raw sql. I cannot use DB:select because i'm using paginate at the end. ``` select * from orders join users on orders.user_id = users.id where orders.id = $search or orders.reference_no like '%$search%' or users.name like '%$search%' public function customer() { return $this->belongsTo('App\User', 'user_id', 'id'); } $orders = Order::where('reference_no', 'LIKE', "%$search%") ->orWhere('reference_no',$search) ->orWhere('id',$search) ->whereHas('customer', function ($query) use ($search) { $query->where('name', 'like', '%$search%'); }) ->paginate(10); ```<issue_comment>username_1: You can try writing some custom logic i.e. implement your own in-memory queue in Azure function to queue up requests and limit the calls to third party API. Anyway until the call to third party API succeeds, you dont need to acknowledge the messages in the queue. In this way reliability is also maintained. Upvotes: 0 <issue_comment>username_2: Unfortunately there is no built-in option for this. The only reliable way to limit concurrent executions would be to run on a fixed App Service Plan (not Consumption Plan) with just 1 instance running all the time. You will have to pay for this instance. Then set the option in `host.json` file: ``` "serviceBus": { // The maximum number of concurrent calls to the callback the message // pump should initiate. The default is 16. "maxConcurrentCalls": 10 } ``` Finally, make sure your function takes a second to execute (or other minimal duration, and adjust concurrent calls accordingly). As @SeanFeldman suggested, see some other ideas in [this answer](https://stackoverflow.com/a/40096267/1171619). It's about Storage Queues, but applies to Service Bus too. Upvotes: 4 [selected_answer]<issue_comment>username_3: The best way to maintain integrity of the system is to throttle the consumption of the Service Bus messages. You can control how your QueueClient processes the messages, see: <https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues#4-receive-messages-from-the-queue> Check out the "Max Concurrent calls" ``` static void RegisterOnMessageHandlerAndReceiveMessages() { // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc. var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler) { // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity. // Set it according to how many messages the application wants to process in parallel. MaxConcurrentCalls = 1, // Indicates whether the message pump should automatically complete the messages after returning from user callback. // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync(). AutoComplete = false }; // Register the function that processes messages. queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); } ``` Upvotes: 0 <issue_comment>username_4: Do you want to get rid of N-10 messages you receive in a second interval or do you want to treat every message in respect to the API throttling limit? For the latter, you can add the messages processed by your function to another queue from which you can read a batch of 10 messages via another function (timer trigger) every second Upvotes: 1
2018/03/17
430
1,311
<issue_start>username_0: When I ran `flutter run` command this error appeared. I am trying to use a `map_view`. My Xcode version is 9.2 In file included from > > /Users/rsaivenkatesh/.pub-cache/hosted/pub.dartlang.org/map\_view-0.0.10/ios/Classes/MapViewPlugin.m:1: > /Users/rsaivenkatesh/.pub-cache/hosted/pub.dartlang.org/map\_view-0.0.10/ios/Classes/MapViewPlugin.h:1:9: fatal error: 'Flutter/Flutter.h' file not found > #import > > > 1 error generated. > Could not build the application for the simulator. > Error launching application on iPhone X. > > ><issue_comment>username_1: Perhaps you need to `flutter pub upgrade` to make sure you have the latest dependencies. Upvotes: 0 <issue_comment>username_2: I had a similar problem trying to include the audioplayer package > > audioplayer-0.4.0/ios/Classes/AudioplayerPlugin.h:1:9: fatal error: 'Flutter/Flutter.h' file not found > > > I thought I was up-to-date, but after I did a Flutter upgrade and then deleted Podfile, Podfile.lock and the Pods folder from my ios directory under my project (and ran flutter clean), I was finally able to build and launch to iOS. See <https://github.com/flutter/flutter/pull/16273> I'm using Xcode 9.3 and Cocoapods 1.5.0 Flutter shows version 0.3.1 after upgrading. Upvotes: 3 [selected_answer]
2018/03/17
323
1,310
<issue_start>username_0: I have to run my logic for several times, based on test data. Here, in some iterations few fields are optional so I get No element found exception but thats ok for me to pass the TC, so I want to continue my script. And in next iteration my script should again look for that field, if its present it should follow path 1 or else path 2. **How can I achieve this ?** Please help...<issue_comment>username_1: You have to use a try catch construction catching the noSuchElement exception and in the catch block no code or code which have to be excecuted when the element is not present. Another option is to use findElements instead of findElement, this will give you a list. You can check now if the list is empty which means that the element is not found, there is one element in the list when the element is found. No exception is thrown when using findElements. Upvotes: 1 <issue_comment>username_2: Use a try/catch block ``` try { data = getElement(1); found = true; } catch (NoSuchElementException e) { found = false; } ``` Upvotes: 1 <issue_comment>username_3: You can handle that by using the if() {} else {} conditions. Or you can put some default values in that missing fields. Or you can use Exception Handling concept try {} catch() {} blocks.. Upvotes: 0
2018/03/17
1,141
3,736
<issue_start>username_0: I'm currently trying to implement **shortcuts feature** on the menu of my web based project. I had already implemented single or double shortcut key combination (like **`F1`, `CTRL` + `Q`** etc..,). ``` $("#MyField").keydown(function (eventData) { if (eventData.keyCode == 112) { eventData.preventDefault(); myFunction_ToCall(); } }); ``` But now I'm moving towards the combination of 3-keys, to access a `sub-subMenu`, because my menu is look like this: 1. Menu1 1. SubMenu1 1. **Sub-SubMenu1** 2. **Sub-Sub-Menu2** 2. SubMenu2 3. SubMenue3 2. Menu2 3. Menu3 4. Menu4 So, to access the **`1. Sub-SubMenu1`** the path will be like `1. Menu1 > 1. SubMenu1 > 1. Sub-SubMenu1`, the **key combination will be like `CTRL` + `1` + `1` + `1``**. I searched a lot, but couldn't find any better solution. And now I'm confused how to achieve it. Anyone can help me!!<issue_comment>username_1: How about this example from [Keyboard events with Ctrl, Alt, Shift keys](http://www.javascripter.net/faq/keyboard_ctrl_alt_shift.htm) **Take a look at how it captures combinations..** ``` function handleKeyDown(e) { var ctrlPressed=0; var altPressed=0; var shiftPressed=0; var evt = (e==null ? event:e); shiftPressed=evt.shiftKey; altPressed =evt.altKey; ctrlPressed =evt.ctrlKey; self.status="" + "shiftKey="+shiftPressed +", altKey=" +altPressed +", ctrlKey=" +ctrlPressed if ((shiftPressed || altPressed || ctrlPressed) && (evt.keyCode<16 || evt.keyCode>18)) alert ("You pressed the "+fromKeyCode(evt.keyCode) +" key (keyCode "+evt.keyCode+")\n" +"together with the following keys:\n" + (shiftPressed ? "Shift ":"") + (altPressed ? "Alt " :"") + (ctrlPressed ? "Ctrl " :"") ) return true; } document.onkeydown = handleKeyDown; ``` Upvotes: 0 <issue_comment>username_2: I would use `KeyboardEvent.key`, `KeyboardEvent.ctrlKey` and a tree where each sequence of keystrokes forms a branch : ```js step = shortcuts = { "1": { "1": sayHello, "2": sayGoodbye } }; document.addEventListener("keydown", function (ev) { if (ev.key === "Control") { step = shortcuts; // go back to the root ev.preventDefault(); } }); document.addEventListener("keyup", function (ev) { if (ev.ctrlKey && step[ev.key]) { step = step[ev.key]; // a node was reached if (typeof step === "function") { step(); // a leaf was reached } } }); function sayHello () { console.log("Hello :-)"); } function sayGoodbye () { console.log("Goodbye :-("); } ``` ```html Click here before trying shortcuts. ``` Here is an improved version of the previous snippet : ```js step = shortcuts = { "1": { "1": "sayHello", "2": "sayGoodbye" } }; commands = { "sayHello": function () { console.log("Hello :-)"); }, "sayGoodbye": function () { console.log("Goodbye :-("); } }; printShortcuts(shortcuts, "CTRL"); document.addEventListener("keydown", function (ev) { if (ev.key === "Control") { step = shortcuts; // go back to the root ev.preventDefault(); } }); document.addEventListener("keyup", function (ev) { if (ev.ctrlKey && step[ev.key]) { step = step[ev.key]; // a node was reached if (commands[step]) { commands[step](); // a leaf was reached } } }); function printShortcuts (node, prefix) { if (typeof node === "string") { document.body.innerHTML += prefix + " : " + node + "() "; } else { for (var child in node) { printShortcuts(node[child], prefix + "-" + child); } } } ``` ```html Click here before trying shortcuts. ``` Upvotes: 2
2018/03/17
625
2,286
<issue_start>username_0: Pardon all the italic shouting. Just trying to emphasize key points. Please note that the existing post [iOS app submission and beta review process](https://stackoverflow.com/questions/38004875/ios-app-submission-and-beta-review-process) does not answer this question. The following sequence of events does happen and it's what I expect: * Create a new *version* (number) of app in iTC * Archive and upload app to iTC * *Internal* testers get notified to download with TestFlight * Submit for Beta Approval (critical for next step) * Now *all* testers (inside & out) get notified to download But next: * Create a new *build* (number) in Xcode * Archive and upload to iTC * Only *internal* testers are notified. ⬅︎ **unexpected** Do I need Beta Approval *every* time I want the external testers notified? I could swear this has not been the case. But of course things may have changed. Or it's just my bad memory.<issue_comment>username_1: You need to approve first build of every new version.As Apple mentioned" A review is only required for the first build of a version. Subsequent builds may not need a full review.."<https://help.apple.com/itunes-connect/developer/#/dev3bfa33892> Upvotes: -1 <issue_comment>username_2: Beta review is only required for the first build and the first build send in after a 90 day period. Upvotes: -1 <issue_comment>username_3: > > Do I need Beta Approval every time I want the external testers notified? > > > NO == > > I could swear this has not been the case. But of course things may have changed. Or it's just my bad memory. > > > It's just that: 1) there's a short delay (5-20 minutes) before you can send to external testers 2) from time to time Apple's servers are screwed, and the 5-20 minute delay becomes "many hours". Change the version number - you have to wait for a (presumably human) approval: takes 1-2 days Change the build number - only a short delay for a (presumably) automatic check. And don't forget you have to manually release to the external testers each time! ================================================================================ [![enter image description here](https://i.stack.imgur.com/zQMse.png)](https://i.stack.imgur.com/zQMse.png) Upvotes: 3 [selected_answer]
2018/03/17
813
3,126
<issue_start>username_0: Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error. ``` var user = $('.username').value(); var pass = $('.password').value(); $.ajax({ type : 'POST', url : 'login_check.php', data : { 'username': user, 'password': <PASSWORD> }, beforeSend: function() { $("#Loading").show(); }, success : function(response) { if(response=="success" && response!=="fail") { $('.status').html("Success! Now logging in ......"); setTimeout(' window.location.href = "index.php"; ',4000); } else { $('#Loading i').hide(); $('.status').html("Login fail! Please use correct credentials...."); setTimeout(' window.location.href = "login.php"; ',4000); } } }); ``` Can anyone points me out?<issue_comment>username_1: I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting ``` var user = $('.username').val(); var pass = $('.<PASSWORD>').val(); $.ajax({ type : 'POST', url : 'login_check.php', data : { 'username':user, 'password':<PASSWORD>, }, beforeSend: function() { $("#Loading").show(); }, success : function(response) { $('.status').html("Success! Now logging in ......"); setTimeout(()=>{ window.location.href = "index.php"; },4000); }, error: function(xhr, status, error) { $('#Loading i').hide(); $('.status').html("Login fail! Please use correct credentials...."); setTimeout(()=>{ window.location.href = "login.php"},4000); } }); ``` Upvotes: 0 <issue_comment>username_2: The reason you are getting error is because your javascript is getting break(giving error) at `$('.username').value();` as there is no `value()` function. If you open console you get this error. So because of this rest of script is not working. So change `$('.username').value();` to this `$('.username').val();` and same for the `var pass = $('.password').value();` change to `var pass = $('.password').val();` and also you don't need if condition as mention in comment. Your final code will be something like this. ``` var user = $('.username').val(); var pass = $('.password').val(); $.ajax({ type: 'POST', url: //some url data: { 'username': user, 'password': <PASSWORD>, }, beforeSend: function() { //some code }, success: function(response) { // some code which you want to excute on success of api }, error: function(xhr, status, error) { // some code which you want to excute on failure of api } }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Your `response` needs to be a PHP `echo` that returns a string with a value of either `”success”` or `”fail”`. Your PHP response after successful login: `echo(‘success’);` Your PHP response after failed login: `echo(‘fail’);` Upvotes: 0
2018/03/17
649
2,568
<issue_start>username_0: How much time does it take to train a classifier in Watson? I uploaded around 500 images and it has been 48 hours and the module is still in training. I am trying to differentiate plant leaves and thus gave images of plant leaves. Total file size is around 50MB.<issue_comment>username_1: I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting ``` var user = $('.username').val(); var pass = $('.password').val(); $.ajax({ type : 'POST', url : 'login_check.php', data : { 'username':user, 'password':<PASSWORD>, }, beforeSend: function() { $("#Loading").show(); }, success : function(response) { $('.status').html("Success! Now logging in ......"); setTimeout(()=>{ window.location.href = "index.php"; },4000); }, error: function(xhr, status, error) { $('#Loading i').hide(); $('.status').html("Login fail! Please use correct credentials...."); setTimeout(()=>{ window.location.href = "login.php"},4000); } }); ``` Upvotes: 0 <issue_comment>username_2: The reason you are getting error is because your javascript is getting break(giving error) at `$('.username').value();` as there is no `value()` function. If you open console you get this error. So because of this rest of script is not working. So change `$('.username').value();` to this `$('.username').val();` and same for the `var pass = $('.password').value();` change to `var pass = $('.password').val();` and also you don't need if condition as mention in comment. Your final code will be something like this. ``` var user = $('.username').val(); var pass = $('.password').val(); $.ajax({ type: 'POST', url: //some url data: { 'username': user, 'password': <PASSWORD>, }, beforeSend: function() { //some code }, success: function(response) { // some code which you want to excute on success of api }, error: function(xhr, status, error) { // some code which you want to excute on failure of api } }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Your `response` needs to be a PHP `echo` that returns a string with a value of either `”success”` or `”fail”`. Your PHP response after successful login: `echo(‘success’);` Your PHP response after failed login: `echo(‘fail’);` Upvotes: 0
2018/03/17
718
2,571
<issue_start>username_0: Is it possible to start emulator in such a way `flutter doctor` detects it and `flutter run` should able to deploy to flutter code ? I tried `emulator -avd *image name*` but `flutter doctor` fails to detect running emulator and flutter run does not deploys code on emulator.<issue_comment>username_1: It looks like an adb issue, not of the Flutter doctor issue. Because if adb is running perfectly then it would show you a list of devices from android studio or from flutter devices or by running a `adb devices` command. You can try restarting adb using commands: * `adb kill-server` and * then `adb start-server` Upvotes: 1 <issue_comment>username_2: first you must change directory of your command line to `${android_SDK_DIR}\emulator` most of the time its in `c:\users\${yourUserName}\AppData\Local\Android\SDK\` and run `emulator -list-avds` and it show you your emulator that you create before in android studio then just run `emulator @${your emulator name that shows on the list}` for example `emulator @Nexus6_API_27` remember that maybe your android sdk folder directory was change on install SDK and if you don't create emulator in android studio before , the list will be empty so before you run command you must create AVD in your android studio Upvotes: 2 <issue_comment>username_3: I think the easiest method I found is you just go to cmd ``` flutter emulator -- launch ``` it will run and will be detected by your intelli j Upvotes: 0 <issue_comment>username_4: I have to get an answer in here somehow, even if it's to offer that the command may also be plural. Yes, indeed, you can run "flutter emulators" from your flutter\bin directory (if you haven't added to system PATH yet) and voila... > > PS C:> flutter emulators 1 available emulator: > > > Pixel\_2\_API\_28 • pixel\_2 • Google • Pixel 2 API 28 > > > To run an emulator, run 'flutter emulators --launch '. To > create a new emulator, run 'flutter emulators --create [--name xyz]'. > > > You can find more information on managing emulators at the links > below: <https://developer.android.com/studio/run/managing-avds> > > <https://developer.android.com/studio/command-line/avdmanager> > > > Upvotes: 0 <issue_comment>username_5: In notepad type the following and save it as "file\_name.bat" and run it: ``` SET builddir=%~dp0 SET EX="C:\Users\user_name\AppData\Local\Android\Sdk\emulator\emulator.exe" CALL %EX% -avd emu_name -partition-size 512 -feature WindowsHypervisorPlatform pause ``` emu\_name is the name of your emulator. Upvotes: 3
2018/03/17
1,546
4,250
<issue_start>username_0: I recently came across the website [StuffAndNonsense.co.uk](https://stuffandnonsense.co.uk/), which is a personal site for the digital designer <NAME>. I was astonished by it, using webpage technologies I didn't even know existed. I looked into the styles and found this bit: ``` :root { --font-family: tondo_rg,sans-serif; --font-family-light: tondo_lt,sans-serif; --font-family-bold: tondo_bd,sans-serif; --font-weight: 400; --font-size-xxx-display: 8vmin; --font-size-xx-display: 4.11rem; --font-size-x-display: 3.653rem; --font-size-display: 3.247rem; --font-size-xxxx-large: 2.887rem; --font-size-xxx-large: 2.027rem; --font-size-xx-large: 1.802rem; --font-size-x-large: 1.602rem; --font-size-large: 1.424rem; --font-size-medium: 1.266rem; --font-size: 1.125rem; --font-size-small: 1rem; --font-size-x-small: .889rem; --font-size-xx-small: .79rem; --lineheight-text: 1.5; --lineheight-heading: 1.3; --color-background: #fff; --color-background-selection: #f0f2f3; --color-border: #cacfd5; --color-text-default: #0b1016; --color-text-alt: #95a0ac; --color-base: #f4f5f6; --color-accent: #ba0d37; --color-logo-enamel: #ba0d37; --color-logo-highlight: #fdfdfd; --color-logo-metal: #cacfd5; --color-logo-lettering: #fff; --color-logo-type: #0b1016; --color-text-link: #2c4159; --color-text-link-active: var(--color-text-link); --color-text-link-focus: var(--color-text-link); --color-text-link-hover: var(--color-accent); --color-text-link-visited: var(--color-text-link); --color-button-default: #2c4159; --color-button-alt: #243449; --color-button-border: #8586a4; --color-button-shadow: #ecedee; --border-radius-x-small: .25rem; --border-radius-small: .5rem; --border-radius-medium: .75rem; --border-radius-large: 1rem; --border-radius-circle: 50%; --border-width-hairline: .5px; --border-width-thin: 1px; --border-width-thick: 2px; --grid-gap: 4vw; --max-width: 92rem; --spacing-xx-small: .125rem; --spacing-x-small: .25rem; --spacing-small: .5rem; --spacing: .75rem; --spacing-medium: 1rem; --spacing-large: 1.5rem; --spacing-x-large: 2rem; --spacing-xx-large: 3rem; --duration-instantly: 0; --duration-immediately: .1s; --duration-quickly: .2s; --duration-promptly: .5s; --duration-slowly: 1s; } ``` I was... confused to say the least. Not only had I never seen CSS properties prefixed by `--`, but I'd never seen stuff like `font-size-xx-large: 1.802rem;`. What is this doing? I tried [Googling](https://www.google.com/search?q=css+%22--font-size-xx-display%22) (and even [Binging](https://www.bing.com/search?q=css+%22--font-size-xx-display%22)) it to no avail.<issue_comment>username_1: These properties are CSS Variables. You can see more on CSS variables here: <https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables> Here's an example of how to access CSS variables: ``` element { background-color: var(--main-bg-color); } ``` The reason they are in something called `root`: The :root selector allows you to target the highest-level "parent" element in the DOM, or document tree. Upvotes: 4 [selected_answer]<issue_comment>username_2: Variables in CSS starts with "--" which are case sensitive :root is used to define global scope which is similar to defining for body selector ``` :root { --font-size-xx-large: 16px; --font-size-xx-small: 12px; } ``` For referencing that variable, we need to use var() function ``` p { font-size: var(--font-size-xx-large); } div{ font-size: var(--font-size-xx-small); } ``` Note: Currently it is not supported by all browsers Check compatibility details here - <https://caniuse.com/#feat=css-variables> code sample for reference - <https://codepen.io/nagasai/pen/aYmPYv> ```css :root { --font-size-xx-large: 16px; --font-size-xx-small: 12px; } p { font-size: var(--font-size-xx-large); } div{ font-size: var(--font-size-xx-small); } ``` ```html Paragraph font size large 16px Div font size small 12px ``` Upvotes: 2
2018/03/17
750
2,377
<issue_start>username_0: I am giving a homework exercise that the student can submit in singles or pairs. The solutions are submitted in a Google form with three fields: submitter1, submitter2 (optional), solution. The submissions automatically go into a Google spreadsheet with four columns: submitter1, submitter2, solution, and grade (filled in by the TA). For example: ``` submitter1 submitter2 solution grade 111 222 x 100 333 y 90 444 555 z 80 ``` I would like to create a second sheet that automatically lists the grades of each submitter alone, e.g: ``` submitter grade 111 100 222 100 333 90 444 80 555 80 ``` The order in the second table is not important. Is there a way to do this in Google spreadsheet? Alternatively, is there a way to do this in another spreadsheet software, such as LibreOffice Calc or Excel? (in that case I could copy the spreadsheet to that program and do the calculations there, though it is less convenient than doing it directly in Google spreadsheet). EDIT: The main problem is to collect all submitter IDs into a single column. I do not know in advance how many submissions there will be, and how many of them will be single/pair. I tried to put in the "submitter" column: ``` =IF(ISBLANK(Sheet1!A2),Sheet1!$B$2,Sheet1!A2) ``` and copy it downwards. This gives me all the first-submitters, and then the first second-submitter. But then how to automatically take the next second-submitters?<issue_comment>username_1: List the submitters with this in A2, ``` =ArrayFormula(UNIQUE(TRANSPOSE(SPLIT(CONCATENATE(Sheet1!A2:B&CHAR(9)),CHAR(9))))) ``` Retrieve their grades with this formula, ``` =index(Sheet1!D:D, iferror(match(A2, Sheet1!A:A, 0), match(A2, Sheet1!B:B, 0))) ``` Linked google-sheet [here](https://docs.google.com/spreadsheets/d/1WWN96AdYSx6ddArbBuGrDU_jCrO7WGTFA2Te1kaW-dw/edit?usp=sharing) (updated) Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` =UNIQUE({{Sheet1!A:A,Sheet1!D:D};{Sheet1!B:B,Sheet1!D:D}}) ``` [Arrange arrays](https://support.google.com/docs/answer/6208276) and do the formulas. QUERY to remove blanks, if needed: ``` =QUERY(UNIQUE({{Sheet1!A:A,Sheet1!D:D};{Sheet1!B:B,Sheet1!D:D}}),"Select Col1,Col2 Where Col1 is not null") ``` Upvotes: 1
2018/03/17
729
3,038
<issue_start>username_0: I have an issue in asp.net Master page, I have 4 buttons as a menu bar and I need to change the color when a button is clicked , I have done this in java script , but when I am redirecting to the child page it is changing the color again to it's initial color. ASP.NET CODE (button class and focus class have different color): ``` ``` Java script code: ``` function setColor(pos) { //var property = document.getElementById(btn); var buttons = Array.prototype.slice.call(document.querySelectorAll(".button")); // Loop through the buttons buttons.forEach(function (btn) { // Set up a click event handler for the button btn.addEventListener("click", function () { if (this.value == "button 1") { window.location.href = "Default.aspx"; } else if (this.value == "button 2") { window.location.href = "Default2.aspx"; } else if (this.value == "button 3") { window.location.href = "Default3.aspx"; } // Loop though all the buttons and reset the colors back to default buttons.forEach(function (btn) { btn.classList.remove("focus"); }); // Now, add the class to the one button that got clicked this.classList.add("focus"); }); }); } ```<issue_comment>username_1: this is because you're redirecting the page and therefore reloading the `html` and the `css` so everything goes back to it's initial state and you lose the color you changed, but you can do what you want by checking the filename when the page loads and setting the the button's color accordingly, like : ``` document.onload = function() { var pathName = window.location.pathname.split('/'); var fileName = pathName[pathName.length - 1]; switch(fileName) { case 'Default.aspx': document.getElementById('t1').classList.add("focus"); break; case 'Default2.aspx': document.getElementById('t2').classList.add("focus"); break; case 'Default3.aspx': document.getElementById('t3').classList.add("focus"); break; } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Please try with below code. you have to put this code in Master page ``` $( document ).ready(function() { var path = window.location.pathname; var page = path.split("/").pop(); var t1 = document.getElementById("t1"); var t2 = document.getElementById("t2"); var t3 = document.getElementById("t3"); t1.classList.remove("focus"); t2.classList.remove("focus"); t3.classList.remove("focus"); switch(page) { case 'Default.aspx': t1.classList.add("focus"); break; case 'Default2.aspx': t2.classList.add("focus"); break; case 'Default3.aspx': t3.classList.add("focus"); break; } }); ``` Upvotes: 1
2018/03/17
1,523
5,032
<issue_start>username_0: When no other of these questions are helping me, then this means I need to remove and reinstall Android Studio. Here's the error: > > Error initializing ADB: Unable to create Debug Bridge: > > Unable to start ADB server: adb server version (36) doesn't match this client; > > killing... could not read OK from ADB server > > > * failed to start daemon error: cannot connect to daemon 'C:\Android\Sdk\platform-tools\adb.exe start-server' failed -- run manually if necessary.<issue_comment>username_1: There are a couple of solutions depending on what exactly is causing the problem. So, just follow the following steps. ***Step 1:-*** Close Android-Studio. ***Step 2:-*** Open Command prompt *or `win` + `r`, type `cmd` and press `Enter`*. ***Step 3:-*** Navigate to your `platform-tools`, in most of the cases the location is: ``` C:\Users\[user]\AppData\Local\Android\android-sdk\platform-tools ``` but in your case, the location is: ``` C:\Android\Sdk\ ``` For Mac users the path is ``` /Users/[user]/Library/Android/sdk/platform-tools ``` ***Step 4:-*** Type `adb.exe start-server`, Press `Enter` ***Step 5:-*** Open Android Studio again. For Mac the command is just `adb start-server` The problem should be solved! --- If the problem persists, then follow these steps- ***Step 1:-*** Close Android Studio. ***Step 2:-*** Press `Alt` + `Ctrl` + `Del`, then choose `Start Task Manager`. *Windows Task Manager opens.* ***Step 3:-*** Go to the `processes` tab. ***Step 4:-*** Look for `adb.exe` and select that. ***Step 5:-*** Press `End Process`. ***Step 6:-*** Open Android Studio again. That's it. Now your problem must be solved! --- But if the problem is still there (which I don't think will happen), then there is something wrong (or might be missing) in your `platform-tools`. To fix that, delete `platform-tools` from your computer, then download them again from [Official Android Developer website.](https://developer.android.com/studio/releases/platform-tools.html#tos-header) Extract the downloaded file. Now place the extracted file, where `platform-tools` were located before deleting. Default Location of `platform-tools` is ``` C:\Users\[user]\AppData\Local\Android\android-sdk\ ``` But in your case, the location is ``` C:\Android\Sdk\ ``` Upvotes: 8 [selected_answer]<issue_comment>username_2: I spent around a complete day to look for the solution but couldn't find the exact one. **Finally what I did was that I uninstalled my antivirus and after that it worked like a charm.** So, here I shortlist the steps to check whether you are solving for the correct problem or not:- 1. Run command prompt and set path to where adb.exe file is present. (In most of the cases it's found at C:\Users\YOUR\_USERNAME\AppData\Local\Android\Sdk\platform-tools) 2. Type `adb start-server` and press enter. 3. If there is an error displayed saying something like "Cannot connect to daemon" , then you must look in your antivirus for firewall settings and add the path to its exceptions or you can simply uninstall your antivirus. Upvotes: 4 <issue_comment>username_3: Steps to follow for Immediate recovery. No need to close Android Studio. 1. Goto Task Manager By Clicking **(Ctrl + Shift + Esc)**. 2. Open **Processes Tab**. 3. Click Image Name in the Processes Tab for Ascending Order(A-Z). 4. Now choose **adb.exe** (or) **adb.exe\*32** (or) **adb.exe\*64**. 5. Now Click **End Process** Button at Right End Bottom corner. 6. That's All , Now your adb will auto re-started When Launching Application. Upvotes: 4 <issue_comment>username_4: Download, extract and replace the platform-tools folder with this one [here](https://androidstudio.io/downloads/tools/download-the-latest-version-of-adb.exe.html) because the adb.exe file could be corrupted or empty with a file size of 0KB File path on **windows** ``` C:\Users[user]\AppData\Local\Android\Sdk\platform-tools ``` File path on **mac** ``` /Users/[user]/Library/Android/sdk/platform-tools ``` Upvotes: 3 <issue_comment>username_5: On my Macbook, I had to kill an already running server from the terminal to fix the problem: ``` josh@JoshsMBP ~ % ps aux | grep adb josh 19134 2.5 0.0 4421320 5216 ?? Ss 31Aug21 229:41.25 adb -L tcp:5037 fork-server server --reply-fd 4 josh 93496 0.8 0.0 4279728 816 s000 S+ 1:47pm 0:00.00 grep adb josh@JoshsMBP ~ % pkill adb ``` Upvotes: 2 <issue_comment>username_6: on MacOS, I kill all adb process in Activity Monitor. Its working... Upvotes: 2 <issue_comment>username_7: This issue comes due to antivirus treating adb as malware sometimes **Solution 1** * Close the android studio * End task background process adb.exe()/ adb.exe(32)/ adb.exe(64) from Task Manager. * Relaunch android studio. **Solution 2** * open cmd (administrator mode) ...\Android\sdk\platform-tools on this path and run the following commands: * adb.exe kill-server * adb.exe start-server Upvotes: 0
2018/03/17
1,850
6,170
<issue_start>username_0: ``` deadcheck<-function(a,t){ #function to check if dead for specific age at a time age sending to function roe<-which( birthmort$age[i]==fertmortc$min & fertmortc$max) #checks row in fertmortc(hart) to pick an age that meets min and max age requirements I think this could be wrong... prob<-1-(((1-fertmortc$mortality[roe])^(1/365))^t) #finds the prob for the row that meets the above requirements if(runif(1,0,1)<=prob) {d<-TRUE} else {d<-FALSE} #I have a row that has the probability of death every 7 days. return(d) #outputs if dead ``` Background: I am creating an agent based model that is a population in a dataframe that is simulating how Tuberculosis spreads in a population. ( I know that there are probably 10000 better ways of having done this). I have thus far created a loop that populates my dataframe with people ages etc. I am now trying to create a function that will go to a chart that lists the probability of death per year, based on a age bracket. 0-5,5-10,10-15 etc. (I have math in there b/c I want it to check who lives, dies, makes babies every 7 days). I have a function similar to this that check who is pregnant and it works. However I for the life of me can't figure out why this function is not working. I keep getting the following error. Error in if (runif(1, 0, 1) <= prob) { : argument is of length zero I am unsure how to fix this. I apologize in advanced it this is a dumb question, I have been trying to teach myself to code over the last 4-5 months. If I asked this question in the wrong format or incorrectly then please let me know how to do so correctly.<issue_comment>username_1: There are a couple of solutions depending on what exactly is causing the problem. So, just follow the following steps. ***Step 1:-*** Close Android-Studio. ***Step 2:-*** Open Command prompt *or `win` + `r`, type `cmd` and press `Enter`*. ***Step 3:-*** Navigate to your `platform-tools`, in most of the cases the location is: ``` C:\Users\[user]\AppData\Local\Android\android-sdk\platform-tools ``` but in your case, the location is: ``` C:\Android\Sdk\ ``` For Mac users the path is ``` /Users/[user]/Library/Android/sdk/platform-tools ``` ***Step 4:-*** Type `adb.exe start-server`, Press `Enter` ***Step 5:-*** Open Android Studio again. For Mac the command is just `adb start-server` The problem should be solved! --- If the problem persists, then follow these steps- ***Step 1:-*** Close Android Studio. ***Step 2:-*** Press `Alt` + `Ctrl` + `Del`, then choose `Start Task Manager`. *Windows Task Manager opens.* ***Step 3:-*** Go to the `processes` tab. ***Step 4:-*** Look for `adb.exe` and select that. ***Step 5:-*** Press `End Process`. ***Step 6:-*** Open Android Studio again. That's it. Now your problem must be solved! --- But if the problem is still there (which I don't think will happen), then there is something wrong (or might be missing) in your `platform-tools`. To fix that, delete `platform-tools` from your computer, then download them again from [Official Android Developer website.](https://developer.android.com/studio/releases/platform-tools.html#tos-header) Extract the downloaded file. Now place the extracted file, where `platform-tools` were located before deleting. Default Location of `platform-tools` is ``` C:\Users\[user]\AppData\Local\Android\android-sdk\ ``` But in your case, the location is ``` C:\Android\Sdk\ ``` Upvotes: 8 [selected_answer]<issue_comment>username_2: I spent around a complete day to look for the solution but couldn't find the exact one. **Finally what I did was that I uninstalled my antivirus and after that it worked like a charm.** So, here I shortlist the steps to check whether you are solving for the correct problem or not:- 1. Run command prompt and set path to where adb.exe file is present. (In most of the cases it's found at C:\Users\YOUR\_USERNAME\AppData\Local\Android\Sdk\platform-tools) 2. Type `adb start-server` and press enter. 3. If there is an error displayed saying something like "Cannot connect to daemon" , then you must look in your antivirus for firewall settings and add the path to its exceptions or you can simply uninstall your antivirus. Upvotes: 4 <issue_comment>username_3: Steps to follow for Immediate recovery. No need to close Android Studio. 1. Goto Task Manager By Clicking **(Ctrl + Shift + Esc)**. 2. Open **Processes Tab**. 3. Click Image Name in the Processes Tab for Ascending Order(A-Z). 4. Now choose **adb.exe** (or) **adb.exe\*32** (or) **adb.exe\*64**. 5. Now Click **End Process** Button at Right End Bottom corner. 6. That's All , Now your adb will auto re-started When Launching Application. Upvotes: 4 <issue_comment>username_4: Download, extract and replace the platform-tools folder with this one [here](https://androidstudio.io/downloads/tools/download-the-latest-version-of-adb.exe.html) because the adb.exe file could be corrupted or empty with a file size of 0KB File path on **windows** ``` C:\Users[user]\AppData\Local\Android\Sdk\platform-tools ``` File path on **mac** ``` /Users/[user]/Library/Android/sdk/platform-tools ``` Upvotes: 3 <issue_comment>username_5: On my Macbook, I had to kill an already running server from the terminal to fix the problem: ``` josh@JoshsMBP ~ % ps aux | grep adb josh 19134 2.5 0.0 4421320 5216 ?? Ss 31Aug21 229:41.25 adb -L tcp:5037 fork-server server --reply-fd 4 josh 93496 0.8 0.0 4279728 816 s000 S+ 1:47pm 0:00.00 grep adb josh@JoshsMBP ~ % pkill adb ``` Upvotes: 2 <issue_comment>username_6: on MacOS, I kill all adb process in Activity Monitor. Its working... Upvotes: 2 <issue_comment>username_7: This issue comes due to antivirus treating adb as malware sometimes **Solution 1** * Close the android studio * End task background process adb.exe()/ adb.exe(32)/ adb.exe(64) from Task Manager. * Relaunch android studio. **Solution 2** * open cmd (administrator mode) ...\Android\sdk\platform-tools on this path and run the following commands: * adb.exe kill-server * adb.exe start-server Upvotes: 0
2018/03/17
1,699
5,689
<issue_start>username_0: I have an integer array of size 4. I am adding elements to it via the add method. This is as an unsorted array. I am sorting it via the sort method shown in the code below. The sort method places the smallest number in the position a[0]. When I try to add elements after I call the sort method I always get a return value of 0. Is there a way around this? ``` import java.util.Arrays; public class Scrap { private static int[] array = new int[4]; private static int i = 0; public static void main(String[] args) { Scrap pq = new Scrap(); pq.add(4); pq.insert(3); pq.add(5); pq.sort();// smallest to largest sort method. // System.out.println(array[0]); pq.insert(1); pq.sort(); int test = pq.Minimum(); System.out.println("The smallest element of the array is " + test); pq.sort(); } // public void add(int input) { insert(input); } // Method to insert number into the array. public void insert(int input) { array[i] = input; i++; } // Finding smallest number of the array. public int Minimum() { int a = array[0]; return a; } // Sorts the array from smallest to largest integer public void sort() { int first, temp; for (int i = array.length - 1; i > 0; i--) { first = 0; for (int j = 1; j <= 1; j++) { if (array[j] > array[first]) first = j; } temp = array[first]; array[first] = array[i]; array[i] = temp; } } public int remove() { return delete(); } public int delete() { return remove(); } // Method to convert the array into a string for output } ```<issue_comment>username_1: I am assuming that you will be using a correct `sort` method (because, this is not correct, you can use Arrays.sort). But still with a correct sort, there is a logical problem in your code. At the beginning, the array contains all 0s. After adding the first 3 int, when you call the sort method, the array contains the values in following order: ``` 0,3,4,5 ``` Note that, the value of `i` is not changed. At this state the value of i is 3. So when you insert 1, the new values become ``` 0,3,4,1 ``` So after sorting again, the values of arrays become ``` 0,1,3,4 ``` So obviously the minimum will retrun 0 Upvotes: 1 <issue_comment>username_2: The problem in a nutshell: * You start with an array of length 4. + At this point the array contains 4 zeros, that is: `[0, 0, 0, 0]` * You add 4, 3, and 5. These operations update the content of the array to `[4, 3, 5, 0]`. * You sort the array. This should change the content of the array to `[0, 3, 4, 5]`. In fact it changes to `[0, 5, 3, 4]`, which means your implementation of `sort` is clearly broken. + You probably didn't expect the 0 value to move. **You can fix this by sorting only the first 3 values.** (And, of course, you should also fix your implementation of `sort`.) * Then when you insert 1, the program updates the value at index 3, so the content changes to `[0, 5, 3, 1]`. If you implement the fix I suggested above, and sort only the first `size` elements, then the content after the first call to `sort` should become `[3, 4, 5, 0]`, and the content after the insert 1 should become `[3, 4, 5, 1]`. And when you sort that again, the content should become `[1, 3, 4, 5]` and the smallest value will be 1 as expected, instead of 0. More concretely: * First of all, change `private static int i = 0;` to `private int size = 0;`. The name `i` is extremely inappropriate here, and will surely confuse you. `size` is appropriate. It also doesn't make sense to make it `static`, so I suggest to drop that keyword. * Fix the implementation of `sort`. There are many basic sorting algorithms that are easy to implement. In the implementation, instead of going until `array.size`, go until `size`. Do you see the difference? `size` is the field in `Scrap`, essentially it's the number of elements you added using the `add` or `insert` methods. Some cleaning up would be good too: * Delete the `add` method and rename `insert` to `add`. * Delete the `remove` and `delete` methods. They are not used, and you will get a stack overflow if you try to use them as they are now (the methods call each other, forever) --- Look at the content of the array after each step in the program. After `Scrap pq` is created, this is the content of its array: ``` [0, 0, 0, 0] ``` Then a couple of modifications: > > > ``` > pq.add(4); > pq.insert(3); > pq.add(5); > > ``` > > The content at this point: ``` [4, 3, 5, 0] ``` So far so good. Then you sort it: > > > ``` > pq.sort(); > > ``` > > The content at this point: ``` [0, 5, 3, 4] ``` Ouch. The sort implementation doesn't work very well, does it. But let's ignore that for now. Next step: > > > ``` > pq.insert(1); > > ``` > > The content at this point: ``` [0, 5, 3, 1] ``` None of this behavior makes sense, probably this is not how you intended the program to work. Review the program, verify the content after each step. Do not proceed to the next step until the current step is working correctly. Upvotes: 3 [selected_answer]<issue_comment>username_3: I don't think that is the most effective way to sort an array. It is possible to do this with just 1 for loop. Try this to sort your array from smallest to largest. ``` int temp; for(int i=0;iarray[i+1]){ temp=array[i]; array[i]=array[i+1]; array[i+1]=temp; i=-1; } } ``` Upvotes: 1
2018/03/17
323
1,140
<issue_start>username_0: I want to replace all instances of substrings that match a regular expression with another string in C#. For example, the function call could look something like this: ``` inputString.Replace("foo*bar", "baz"); ``` If the input string was (example only): ``` "foo2bar and foo2bax and fooTheQuickFax" ``` The output would be (example only): ``` "baz and foo2bax and fooTheQuickFax" ``` Does anyone know how to achieve this outcome? Note: This question is NOT a duplicate. This is asking about Regex specifically, featuring an example. It is not asking about how to find the string between two strings - the person who marked this as duplicate did not read the question.<issue_comment>username_1: ``` Regex.Replace("foo2bar and foo2bax and fooTheQuickFax", "foo.*bar", "baz"); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Use [`Regex.Replace()`](https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx) method like ``` string pattern = "\\foo?bar"; string replacement = "baz"; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); ``` Upvotes: 0
2018/03/17
823
3,269
<issue_start>username_0: I'm trying to understand how to use axios (<https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js>) within a function to talk to my own backend to get some data. The code below works. I need to define a global variable outside of the function to catch the result. If I move the variable *myresponse* into the function, I can no longer catch the reply. How can I avoid the global variable? ``` var myresponse = "xxx" function getTimeData() { axios.get('/time') .then(function (response) { console.log(response.data); myresponse = response.data; }) .catch(function (error) { myresponse = "error"; }); return myresponse; } console.log(getTimeData()) ``` For this example I run a local server at "/time" that returns a timestring.<issue_comment>username_1: If you need to collect the data from axios you could always just wrap the return. ``` var result; function getTimeData() { return axios.get('/time') } getTimeData() .then(function(res) { result = res.data; console.log(result); }) .catch(function(err) { console.error(err) }); ``` Upvotes: 0 <issue_comment>username_2: Global variables can be used inside axios. As axios uses AJAX you should not return outside axios. ``` var myresponse = "xxx" function getTimeData() { axios.get('/time') .then(function (response) { myresponse = response.data; return myresponse; }) .catch(function (error) { myresponse = "error"; return myresponse; }); } console.log(getTimeData()) ``` This will work. Even in your code while logging myresponse will not be set but after receiving response it will be set to response.data. --- A part of my vue code which works fine. Note that after created this.users does not immediately get the value in res.data but it will contain res.data once axios sends the req and receives it. ``` var HTTP = axios.create({ baseURL: URL, }) methods:{ getUsers(){ return HTTP.get('/users/admin') }, deleteUsers(user){ HTTP.post('/users/admin',{ id : user._id }) .then(()=>{ this.getUsers() }) } }, created(){ this.getUsers().then(res=>{ this.users = res.data; }) } ``` Upvotes: 1 <issue_comment>username_3: If your final desire is log the value why do you need a separate variable? Just do it in your function. With async/await: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); console.log( response.data ); } catch ( error ) { console.log( error ); } }; getTimeData(); ``` If you want to use the returned value somewhere else, use it again directly in your function: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); return somethingElse( response.data ); } catch ( error ) { return errorHanlder( error ); } }; getTimeData(); ``` Upvotes: 1
2018/03/17
809
3,226
<issue_start>username_0: I have a table `ABC` that has many columns, two of which are: `ID - VARCHAR(10)` and `ROLE VARCHAR(10)`. Now I have been trying to update the column `ROLE` using the `ID` and this is the query: ``` UPDATE TABLE ABC SET ROLE='READ_ONLY' WHERE ID='AB234PQR' ``` Now for some unknown reason, i have been getting the error - `truncated incorrect integer value`. I have no idea where I am going wrong.I have been banging my head over this for a while now. I have visited other questions with the similar title.All use `convert` or some other function in `where` clause, But I have not used any such thing, still it gives me the same error. I checked the table description and it seems fine. Where can I be going wrong? Any help is appreciated.<issue_comment>username_1: If you need to collect the data from axios you could always just wrap the return. ``` var result; function getTimeData() { return axios.get('/time') } getTimeData() .then(function(res) { result = res.data; console.log(result); }) .catch(function(err) { console.error(err) }); ``` Upvotes: 0 <issue_comment>username_2: Global variables can be used inside axios. As axios uses AJAX you should not return outside axios. ``` var myresponse = "xxx" function getTimeData() { axios.get('/time') .then(function (response) { myresponse = response.data; return myresponse; }) .catch(function (error) { myresponse = "error"; return myresponse; }); } console.log(getTimeData()) ``` This will work. Even in your code while logging myresponse will not be set but after receiving response it will be set to response.data. --- A part of my vue code which works fine. Note that after created this.users does not immediately get the value in res.data but it will contain res.data once axios sends the req and receives it. ``` var HTTP = axios.create({ baseURL: URL, }) methods:{ getUsers(){ return HTTP.get('/users/admin') }, deleteUsers(user){ HTTP.post('/users/admin',{ id : user._id }) .then(()=>{ this.getUsers() }) } }, created(){ this.getUsers().then(res=>{ this.users = res.data; }) } ``` Upvotes: 1 <issue_comment>username_3: If your final desire is log the value why do you need a separate variable? Just do it in your function. With async/await: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); console.log( response.data ); } catch ( error ) { console.log( error ); } }; getTimeData(); ``` If you want to use the returned value somewhere else, use it again directly in your function: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); return somethingElse( response.data ); } catch ( error ) { return errorHanlder( error ); } }; getTimeData(); ``` Upvotes: 1
2018/03/17
791
3,155
<issue_start>username_0: Take a look at this piece of code: ``` #include using namespace std; using ld = long double; template struct A { static\_assert(false,""); constexpr static int value = 3; }; template struct B { constexpr static int value = i\*i\*i; }; template struct CheckVal { constexpr static int value = conditional*<3>::value; };* ``` This is supposed to terminate the compilation if a `1` is passed to `CheckVal`, but I'm getting the following error on compilation, no matter what is passed to `CheckVal`: ``` error: use of class template 'A' requires template arguments constexpr static ld value = conditional*<3>::value;* ``` What is the problem here? How can I fix it?<issue_comment>username_1: If you need to collect the data from axios you could always just wrap the return. ``` var result; function getTimeData() { return axios.get('/time') } getTimeData() .then(function(res) { result = res.data; console.log(result); }) .catch(function(err) { console.error(err) }); ``` Upvotes: 0 <issue_comment>username_2: Global variables can be used inside axios. As axios uses AJAX you should not return outside axios. ``` var myresponse = "xxx" function getTimeData() { axios.get('/time') .then(function (response) { myresponse = response.data; return myresponse; }) .catch(function (error) { myresponse = "error"; return myresponse; }); } console.log(getTimeData()) ``` This will work. Even in your code while logging myresponse will not be set but after receiving response it will be set to response.data. --- A part of my vue code which works fine. Note that after created this.users does not immediately get the value in res.data but it will contain res.data once axios sends the req and receives it. ``` var HTTP = axios.create({ baseURL: URL, }) methods:{ getUsers(){ return HTTP.get('/users/admin') }, deleteUsers(user){ HTTP.post('/users/admin',{ id : user._id }) .then(()=>{ this.getUsers() }) } }, created(){ this.getUsers().then(res=>{ this.users = res.data; }) } ``` Upvotes: 1 <issue_comment>username_3: If your final desire is log the value why do you need a separate variable? Just do it in your function. With async/await: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); console.log( response.data ); } catch ( error ) { console.log( error ); } }; getTimeData(); ``` If you want to use the returned value somewhere else, use it again directly in your function: ``` const getTimeData = async () => { try { const response = await axios.get( "/timer" ); return somethingElse( response.data ); } catch ( error ) { return errorHanlder( error ); } }; getTimeData(); ``` Upvotes: 1
2018/03/17
826
2,749
<issue_start>username_0: I am trying to filter out `Guest` users in my Graph query. Since the `ne` comparison operator is not supported I was trying `$filter=userType eq 'Member' or userType eq null` instead. That fails too though. Any known workarounds to list users with `null` as `userType`? Without that I need to download about a million rows each time and throw 4 out of 5 away on the client side, which is pretty slow and wasteful. ``` { "error": { "code": "Request_UnsupportedQuery", "message": "Unsupported or invalid query filter clause specified for property 'userType' of resource 'User'.", "innerError": { "request-id": "411f7927-c3af-4042-a619-eee1c88971a0", "date": "2018-03-17T18:28:35" } } ```<issue_comment>username_1: As a general rule of thumb, `userType` should be either `Member` or `Guest`. The exception to this is when you're syncing an on-prem Active Directory. Since `userType` is an Azure AD property, the value for a synced user will be `null`. If you can safely assume that your on-prem users are *not* guests, you can filter Azure AD user's based on if they're synced or cloud-native. You do this by looking at the `onPremisesSyncEnabled` property. For synced users, this will be `true`, for cloud-native users it will be `null`. If you combine this with the `userType` property, you can effectively retrieve only non-guest users using the following `$filter`: ``` $filter=onPremisesSyncEnabled eq true OR userType eq 'Member' ``` You can also avoid this entirely if you [Enable synchronization of UserType](https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-change-the-configuration#enable-synchronization-of-usertype) in [Azure AD Connect](https://learn.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnect). Upvotes: 3 <issue_comment>username_2: **Update as of June 2021** the `ne` comparison operator is now supported on userType on graph! So you can now get users that are not guest users with this query: `https://graph.microsoft.com/v1.0/users/?$filter=userType ne 'guest'&$count=true` edit: Important to note that this is an [advanced query](https://learn.microsoft.com/en-us/graph/aad-advanced-queries?tabs=http) as so it requires the header `ConsistencyLevel` to be set to `eventual` and include the $count=true query parameter here is a link to [graph explorer](https://developer.microsoft.com/en-us/graph/graph-explorer?request=users%3F%24filter%3DuserType%2Bne%2B%27guest%27%26%24count%3Dtrue&method=GET&version=v1.0&GraphUrl=https://graph.microsoft.com&headers=W3sibmFtZSI6IkNvbnNpc3RlbmN5TGV2ZWwiLCJ2YWx1ZSI6ImV2ZW50dWFsIn1d) with the query that you can run Upvotes: 3 [selected_answer]
2018/03/17
948
3,376
<issue_start>username_0: I'm currently using a terminal and vim on OSX as a development environment for Flutter. Things are going pretty well except that the app does not reload when I save any dart files. Is there a way to trigger that behavior?Currently I have to go to the terminal and hit "r" to see my changes.<issue_comment>username_1: You don't say what platform, but all platforms have a "watcher" app that can run a command when any file in a tree changes. You'll need to run one of those. Upvotes: -1 <issue_comment>username_2: vscode has this feature. If you don't mind moving to vscode you can get it out of the box. You could also reach out to the author and see if they have any suggestions on how you could do it in vim or check the source directly. Most likely vim will have a mechanism to do so. Upvotes: -1 <issue_comment>username_3: Sorry for the plug, but I wrote a very simple [plugin](https://github.com/reisub0/hot-reload.vim "hot-reload.vim") to handle this. It makes use of Flutter's `--pid-file` command line flag to send it a `SIGUSR1` signal. You can achieve the same result as my two-line plugin by adding this to an `autocmd` ``` silent execute '!kill -SIGUSR1 "$(cat /tmp/flutter.pid)"' ``` And launching Flutter with the `--pid-file` flag. Upvotes: 3 <issue_comment>username_4: I did it with the excellent little tool called `entr`. On OS/X you can install it from `brew`: `brew install entr`. The home page of the tool is at <http://eradman.com/entrproject/> Then you start `flutter run` with the pidfile as [@nobody\_nowhere](https://stackoverflow.com/users/4398309/nobody-nowhere) suggests. How do you run `entr` depends on the level of service. In the simplest case you just do `find lib/ -name '*.dart' | entr -p kill -USR1 $(cat /tmp/flutter.pid)` But such invocation will not detect new files in the source tree (because `find` builds a list of files to watch only once, at the start). You can get away with slightly more complex one-liner: ``` while true do find lib/ -name '*.dart' | \ entr -d -p kill -USR1 $(cat /tmp/flutter.pid) done ``` The `-d` option makes `entr` exit when it does detect a new file in one of the directories and the loop runs again. I personally use even more complex approach. I use Redux and change to middleware or other state files does not work with hot reload, it doesn't pick up these changes. So you need to resort to hot restart. I have a script `hotrestarter.sh`: ``` #!/bin/bash set -euo pipefail PIDFILE="/tmp/flutter.pid" if [[ "${1-}" != "" && -e $PIDFILE ]]; then if [[ "$1" =~ \/state\/ ]]; then kill -USR2 $(cat $PIDFILE) else kill -USR1 $(cat $PIDFILE) fi fi ``` It checks if the modified file lives in `/state` subdirectory and if true does hot restart or else hot reload. I call the script like that: ``` while true do find lib/ -name '*.dart' | entr -d -p ./hotreloader.sh /_ done ``` The `/_` parameter makes `entr` to pass the name of the file to the program being invoked. Upvotes: 1 <issue_comment>username_5: I made a vim plugin [username_5/flutter-reload.vim](https://github.com/username_5/flutter-reload.vim) based on killing with `SIGUSR1`. You don't have to use `--pid-file` flag with this plugin. (Thanks to the `pgrep` :)) Simply execute `flutter run`, modify your \*.dart file and see the reloading. Upvotes: 2
2018/03/17
962
3,402
<issue_start>username_0: Is there any way how make normal Map View in flutter. I need to have map ready when user opens the app. Only thing I saw, is that apptree plugin, but I could only make the map appear after user taps the button (and fullscreen, I need to put it into container). Basicaly what I need is some Map Widget, is there any ?<issue_comment>username_1: You don't say what platform, but all platforms have a "watcher" app that can run a command when any file in a tree changes. You'll need to run one of those. Upvotes: -1 <issue_comment>username_2: vscode has this feature. If you don't mind moving to vscode you can get it out of the box. You could also reach out to the author and see if they have any suggestions on how you could do it in vim or check the source directly. Most likely vim will have a mechanism to do so. Upvotes: -1 <issue_comment>username_3: Sorry for the plug, but I wrote a very simple [plugin](https://github.com/reisub0/hot-reload.vim "hot-reload.vim") to handle this. It makes use of Flutter's `--pid-file` command line flag to send it a `SIGUSR1` signal. You can achieve the same result as my two-line plugin by adding this to an `autocmd` ``` silent execute '!kill -SIGUSR1 "$(cat /tmp/flutter.pid)"' ``` And launching Flutter with the `--pid-file` flag. Upvotes: 3 <issue_comment>username_4: I did it with the excellent little tool called `entr`. On OS/X you can install it from `brew`: `brew install entr`. The home page of the tool is at <http://eradman.com/entrproject/> Then you start `flutter run` with the pidfile as [@nobody\_nowhere](https://stackoverflow.com/users/4398309/nobody-nowhere) suggests. How do you run `entr` depends on the level of service. In the simplest case you just do `find lib/ -name '*.dart' | entr -p kill -USR1 $(cat /tmp/flutter.pid)` But such invocation will not detect new files in the source tree (because `find` builds a list of files to watch only once, at the start). You can get away with slightly more complex one-liner: ``` while true do find lib/ -name '*.dart' | \ entr -d -p kill -USR1 $(cat /tmp/flutter.pid) done ``` The `-d` option makes `entr` exit when it does detect a new file in one of the directories and the loop runs again. I personally use even more complex approach. I use Redux and change to middleware or other state files does not work with hot reload, it doesn't pick up these changes. So you need to resort to hot restart. I have a script `hotrestarter.sh`: ``` #!/bin/bash set -euo pipefail PIDFILE="/tmp/flutter.pid" if [[ "${1-}" != "" && -e $PIDFILE ]]; then if [[ "$1" =~ \/state\/ ]]; then kill -USR2 $(cat $PIDFILE) else kill -USR1 $(cat $PIDFILE) fi fi ``` It checks if the modified file lives in `/state` subdirectory and if true does hot restart or else hot reload. I call the script like that: ``` while true do find lib/ -name '*.dart' | entr -d -p ./hotreloader.sh /_ done ``` The `/_` parameter makes `entr` to pass the name of the file to the program being invoked. Upvotes: 1 <issue_comment>username_5: I made a vim plugin [username_5/flutter-reload.vim](https://github.com/username_5/flutter-reload.vim) based on killing with `SIGUSR1`. You don't have to use `--pid-file` flag with this plugin. (Thanks to the `pgrep` :)) Simply execute `flutter run`, modify your \*.dart file and see the reloading. Upvotes: 2
2018/03/17
1,082
3,581
<issue_start>username_0: I am trying to match the following type of string: Match - 4738 - 3333 No match - 0447 7474 9495 - 8485 /2848 / 9949 - 584888 so i made this regex: `/^(- )?(?=\d{4})$/` but this doesnt match my target string: `- 8549` this is data i need to analyse: [![enter image description here](https://i.stack.imgur.com/artlsm.png)](https://i.stack.imgur.com/artlsm.png) I am quite new to regex so all tips and suggestions are welcome on how to fix this. Thanks in advance<issue_comment>username_1: You don't say what platform, but all platforms have a "watcher" app that can run a command when any file in a tree changes. You'll need to run one of those. Upvotes: -1 <issue_comment>username_2: vscode has this feature. If you don't mind moving to vscode you can get it out of the box. You could also reach out to the author and see if they have any suggestions on how you could do it in vim or check the source directly. Most likely vim will have a mechanism to do so. Upvotes: -1 <issue_comment>username_3: Sorry for the plug, but I wrote a very simple [plugin](https://github.com/reisub0/hot-reload.vim "hot-reload.vim") to handle this. It makes use of Flutter's `--pid-file` command line flag to send it a `SIGUSR1` signal. You can achieve the same result as my two-line plugin by adding this to an `autocmd` ``` silent execute '!kill -SIGUSR1 "$(cat /tmp/flutter.pid)"' ``` And launching Flutter with the `--pid-file` flag. Upvotes: 3 <issue_comment>username_4: I did it with the excellent little tool called `entr`. On OS/X you can install it from `brew`: `brew install entr`. The home page of the tool is at <http://eradman.com/entrproject/> Then you start `flutter run` with the pidfile as [@nobody\_nowhere](https://stackoverflow.com/users/4398309/nobody-nowhere) suggests. How do you run `entr` depends on the level of service. In the simplest case you just do `find lib/ -name '*.dart' | entr -p kill -USR1 $(cat /tmp/flutter.pid)` But such invocation will not detect new files in the source tree (because `find` builds a list of files to watch only once, at the start). You can get away with slightly more complex one-liner: ``` while true do find lib/ -name '*.dart' | \ entr -d -p kill -USR1 $(cat /tmp/flutter.pid) done ``` The `-d` option makes `entr` exit when it does detect a new file in one of the directories and the loop runs again. I personally use even more complex approach. I use Redux and change to middleware or other state files does not work with hot reload, it doesn't pick up these changes. So you need to resort to hot restart. I have a script `hotrestarter.sh`: ``` #!/bin/bash set -euo pipefail PIDFILE="/tmp/flutter.pid" if [[ "${1-}" != "" && -e $PIDFILE ]]; then if [[ "$1" =~ \/state\/ ]]; then kill -USR2 $(cat $PIDFILE) else kill -USR1 $(cat $PIDFILE) fi fi ``` It checks if the modified file lives in `/state` subdirectory and if true does hot restart or else hot reload. I call the script like that: ``` while true do find lib/ -name '*.dart' | entr -d -p ./hotreloader.sh /_ done ``` The `/_` parameter makes `entr` to pass the name of the file to the program being invoked. Upvotes: 1 <issue_comment>username_5: I made a vim plugin [username_5/flutter-reload.vim](https://github.com/username_5/flutter-reload.vim) based on killing with `SIGUSR1`. You don't have to use `--pid-file` flag with this plugin. (Thanks to the `pgrep` :)) Simply execute `flutter run`, modify your \*.dart file and see the reloading. Upvotes: 2
2018/03/17
153
614
<issue_start>username_0: I am testing my Django API endpoints but I need to enable WSGIPassAuthorization to let Authorization header be received. Where should I enable it? PS: I am on macOS, but any answer might be useful!<issue_comment>username_1: If you are using `mod_wsgi`, just install apache and use it inside your VirtualHost. And then: `WSGIPassAuthorization On` Upvotes: 3 <issue_comment>username_2: You have to go to /etc/apache2/sites-enabled where your configuration file sits either the one with SSL certificates or the one without and add `WSGIPassAuthorization On` where the file ends. Upvotes: 2
2018/03/17
1,210
3,799
<issue_start>username_0: ``` #include #include using namespace std; using namespace std::chrono; class rmq { public: rmq() = default; rmq(size\_t size) :m\_pData(new unsigned int[size]), m\_size(size) {} ~rmq(){ if (m\_pData)delete[]m\_pData;} void populateValue() { if (m\_pData) { for (size\_t i = 0; i < m\_size; i++) m\_pData[i] = i; } else { std::cout << "NUll reference" << std::endl; } } unsigned int minQuery(size\_t firstIdx, size\_t lastIdx) { unsigned int minValue = 0; if (firstIdx < lastIdx && lastIdx <= m\_size) { minValue = m\_pData[firstIdx]; while (++firstIdx < lastIdx) { if (minValue > m\_pData[firstIdx]) minValue = m\_pData[firstIdx]; } } return minValue; } private: unsigned int \*m\_pData; size\_t m\_size; }; int main() { rmq r(UINT32\_MAX); r.populateValue(); high\_resolution\_clock::time\_point t1 = high\_resolution\_clock::now(); int minvalue = r.minQuery(0, UINT32\_MAX); high\_resolution\_clock::time\_point t2 = high\_resolution\_clock::now(); auto duration = duration\_cast(t2 - t1).count(); std::cout << "RMQ:" << minvalue <<" "<<"Duration\_i`enter code here`n\_ns:"< ``` When the size is specified as UINT32\_MAX I am getting the following exception Unhandled exception at 0x763BC54F in RMQ.exe: Microsoft C++ exception: std::bad\_array\_new\_length at memory location 0x004CFAC0. But the same thing works with UINT16\_MAX. Could not comprehend the logic behind the same. Compiler version is Visual C++ 2015 (also known as Visual C++ 14.0). Target architecture: x86<issue_comment>username_1: You are trying to allocate an array of integers with 2^32 elements. This requires 16 GiB of memory. In a 32-bit address space the maximum total amount of memory available is 4GiB. In windows the most you can allocate to a 32-bit process is 3GiB in 32-bit windows or 4GiB in 64-bit windows. This rises to 8TiB+ for 64-bit processes. see <https://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx> Note that allocation may still fail even if you are under these limits if your total available RAM and swap space aren't big enough. Upvotes: 2 <issue_comment>username_2: A [std::bad\_array\_new\_length](http://en.cppreference.com/w/cpp/memory/new/bad_array_new_length) exception is thrown under one of the following conditions: > > 1. array length is negative > 2. total size of the new array would exceed implementation-defined maximum value > 3. the number of initializer-clauses exceeds the number of elements to initialize > > > Your code has hit the second bullet point, when trying to execute the expression `new unsigned int[UINT32_MAX]`. This tries to allocate an array of `unsigned int`s with 2^32 - 1 elements. The size of an `unsigned int` in Visual Studio is 4, so the total size of the array, in bytes, is 4 \* (2^32 - 1). That size cannot be represented using a [std::size\_t](http://en.cppreference.com/w/cpp/types/size_t), and consequently cannot be passed to [std::malloc](http://en.cppreference.com/w/cpp/memory/c/malloc) (which `operator new` eventually calls, in Visual Studio's implementation), so the implementation bails out with an exception. If you need to allocate an array with 2^32 - 1 `unsigned int`s, you will have to compile for a 64-bit target. The largest array of `unsigned int`s you can request for a 32-bit target without getting a `std::bad_array_new_length` would be `unsigned int[UINT32_MAX >> 2]`. Mind you, that will still give you a [std::bad\_alloc](http://en.cppreference.com/w/cpp/memory/new/bad_alloc) exception. Allocating an array of `unsigned int`s with `UINT16_MAX` elements amounts to 4 \* (2^16 - 1) bytes, roughly 256kB. Not entirely a spectacular amount of memory to allocate, so the request is (usually) serviced without an exception. Upvotes: 2
2018/03/17
576
1,804
<issue_start>username_0: I have a data frame that looks like this: ``` a b c 0 Alabama[edit] NaN NaN 1 Auburn (Auburn University)[1] 2 Florence (University of 3 Jacksonville (Jacksonville State 4 Livingston (University of ``` I'd like to add a column to the dataframe called 'State' that copies the value of column 'a' when column 'b' has a NaN value, otherwise it will just place a NaN value in the state column. I have tried: ``` df['State'] = np.where(df['b'] == np.NaN, df['a'], np.NaN) df['State'] = df.loc[df['b'] == np.NaN, 'a'] ``` However for some reason both of these do not seem to evaluate the np.NaN. If i modify the criteria to == '(Auburn' then it finds the row and correctly copies the value of column 'a' into 'State' If i use this function: `df1 = df[df['b'].isnull()]` then i get all the relevant rows but in a new dataframe which i was trying to avoid. Any help much appreciated. Thanks JP<issue_comment>username_1: Your mistake is in your belief that `df['b'] == np.NaN` selects NaNs... it does not, as this example shows: ``` In [1]: np.nan == np.nan Out[1]: False ``` This is the mathematical definition of NaN. Since NaN != NaN, doing an equality comparison on NaN just won't cut it. Use `isna` or `isnull` or `np.isnan`, these functions are meant for this very purpose. For example, ``` df['State'] = np.where(df['b'].isnull(), df['a'], np.NaN) ``` Or, ``` df['State'] = df.loc[df['b'].isnull(), 'a'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can using `isnull` with `where`,Since NaN has the property that it doesn't equal itself ``` df.a.where(df['b'].isnull()) Out[112]: 0 Alabama[edit] 1 NaN 2 NaN 3 NaN 4 NaN Name: a, dtype: object ``` Upvotes: 1
2018/03/17
1,548
4,712
<issue_start>username_0: I have made a map with `d3.js`and now I would like to color several countries one after another: * at 1 seconde, I would like Spain to be in lets say red color, * at 1.5 sec, France should be red (Spain should remain red) * at 2 sec, Germany should be red (Spain and France should remain red) * and so on So far I could change the color of all the countries at once. I try to do what I want with a try `.transition().delay(500)` but it didn't work. This is my code so far: ```html var w = 1000; var h = 550; var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h); var path = d3.geoPath() .projection(d3.geoMercator() //.scale(0) //.translate([200, 2100]) ); var countries\_visited= ['Spain','France','Germany','Poland', 'Finland'] d3.json( "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json", function (error, json) { //draw svg lines of the boundries svg.append("g") .attr("class", "black") .selectAll("path") .data(json.features) .enter() .append("path") .attr("d", path) .attr('fill', '#e7d8ad');; d3.timeout(function() { d3.selectAll('path') //.transition().delay(500) //should color countries, one after the other .attr('fill', colorCountry); }, 500); } ); function colorCountry(country){ if (countries\_visited.includes(country.properties.name)) { return '#c8b98d'; } else { // why do I need a else (otherwise set to black return '#e7d8ad'; }; }; ``` As a side question: why do I need a else statement in `colorCountry`? Why the country `fill` changes if I don't add the `else`?<issue_comment>username_1: Here is a slightly modified version of your code which displays visited countries one after the other: ```html var w = 1000; var h = 550; var svg = d3.select("body").append("svg").attr("width", w).attr("height", h); var path = d3.geoPath().projection(d3.geoMercator()); var countries\_visited = ['Spain','France','Germany','Poland', 'Finland']; d3.json( "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json", function (error, json) { svg.append("g") .attr("class", "black") .selectAll("path") .data(json.features) .enter() .append("path") .attr("id", function(d) { return d.properties.name; }) .attr("d", path) .attr('fill', '#e7d8ad'); var delay = 1000; countries\_visited.forEach( country => { d3.selectAll('#' + country) .transition().delay(delay) .attr('fill', '#c8b98d'); delay += 500; }); } ); ``` It consists in creating several independent transitions. One for each visited country: ``` var delay = 1000; countries_visited.forEach( country => { d3.selectAll('#' + country) .transition().delay(delay) .attr('fill', '#c8b98d'); delay += 500; }); ``` Each transition is given a delay, which retards the moment the country is colored. And it's the creation of transitions itself that increments the delay to apply for the next country. I included an `id` for each path (country) in order to easily select it during the transition and apply the new color. This is a way to answer your side question, by only selecting the element to modify, we can just modify the `fill` attribute of the modified country. Upvotes: 2 <issue_comment>username_2: Not to diminish from Xavier's [answer](https://stackoverflow.com/a/49343085/7106086), you can also avoid a loop with a more d3 idiomatic method by setting the delay with a function (rather than with an increment): ``` d3.selectAll("path") .filter(function(d) { return countries_visited.indexOf(d.properties.name) > -1 }) .transition() .delay(function(d) { return countries_visited.indexOf(d.properties.name) * 500 + 1000; }) .attr("fill","#c8b98d"); ``` This looks like: ```html var w = 1000; var h = 550; var svg = d3.select("body").append("svg").attr("width", w).attr("height", h); var path = d3.geoPath().projection(d3.geoMercator()); var countries\_visited = ['Spain','France','Germany','Poland', 'Finland']; d3.json( "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json", function (error, json) { svg.append("g") .attr("class", "black") .selectAll("path") .data(json.features) .enter() .append("path") .attr("id", function(d) { return d.properties.name; }) .attr("d", path) .attr('fill', '#e7d8ad'); d3.selectAll("path") .filter(function(d) { return countries\_visited.indexOf(d.properties.name) > -1 }) .transition() .delay(function(d) { return countries\_visited.indexOf(d.properties.name) \* 500 + 1000; }) .attr("fill","#c8b98d"); }); ``` Upvotes: 4 [selected_answer]
2018/03/17
804
3,397
<issue_start>username_0: I have a `Form` in `Laravel` that submits with Ajax.every thing works well but the problem is that I can't render the validation's errors in HTML. **(I want to display the errors in `*` in my HTML)** > > Here is my Ajax request: > > > ``` $(document).ready(function () { $("#submit").click(function (xhr) { xhr.preventDefault(), $.ajax({ type: "POST", contentType: "charset=utf-8", dataType: 'json', url: "{{route('messages.store')}}", headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content") }, data: { name: $("#name").val(), email: $("#email").val(), phone: $("#company").val(), subject: $("#subject").val(), message: $("#message").val() }, success: function () { alert('True'); }, error: function (xhr) { console.log((xhr.responseJSON.errors)); } }, "json") }) }); ``` > > Console logs: > > > [![screenshot](https://i.stack.imgur.com/GlieF.png)](https://i.stack.imgur.com/GlieF.png) Thanks for any help.<issue_comment>username_1: Validation return JSON response for an AJAX request not as what you have mentioned in your question. You can check in the [lara doc](https://laravel.com/docs/5.6/validation#form-request-validation) And the response you seeing in the console is a JSON array not HTML errors. So what you can do is, you can catch any error in AJAX and check there itself if there is any error for email,message and so on. Based on that you can display error on the page. Upvotes: 0 <issue_comment>username_2: Try like this ``` error: function (xhr) { $('#validation-errors').html(''); $.each(xhr.responseJSON.errors, function(key,value) { $('#validation-errors').append(''+value+' ``` Here **validation-errors** is the div id. You can use your own div id. Upvotes: 5 [selected_answer]<issue_comment>username_3: ``` ``` Put this where you want your error to be displayed and then in your error function ``` $('#error_email').html(''+ xhr.responseJSON.errors.email[0] + ' ') ``` Upvotes: 0 <issue_comment>username_4: You need to remove `contentType: "charset=utf-8"` from `Ajax` options to make it work correctly. Upvotes: 0 <issue_comment>username_5: try this hope it will help you with rendering errors after the relevant fields. ``` $("#booking_form").submit(function(e){ e.preventDefault(); let form_data = $("#booking_form").serialize() $(document).find("span.text-danger").remove(); $.ajax({ url : "your-url", type : "POST", data : form_data, success : function(response){ }, error:function (response){ $.each(response.responseJSON.errors,function(field_name,error){ $(document).find('[name='+field_name+']').after('' +error+ '') }) } }) }) ``` Upvotes: 0
2018/03/17
527
1,932
<issue_start>username_0: My Professor kept telling us that she wants us to use the `System.lineSeparator();` to create an empty new line, she didn't specify any reasons, but basically said it was cleaner. What's the difference and should I use it in the described manner over. ``` System.out.println("[your message]\n") ``` in contrast to ``` System.out.println("[your message]"); System.lineSeparator(); ```<issue_comment>username_1: The `\n` character is a single character which is called "new line", usually. Sometimes it may be called "linefeed" to be more accurate. The line separator varies from computer to computer, from Operating System to Operating System. You will get different line separators on Windows and Unix. If you run this: `System.getProperty("line.separator")` it will return the line separator that is specific to your OS. On windows it will return `\r\n` and on Unix it will return `\n`. I hope that it will be clear enough for you. Upvotes: 5 [selected_answer]<issue_comment>username_2: Here's what the API documentation has to say about [`System.lineSeparator`](https://docs.oracle.com/javase/9/docs/api/java/lang/System.html#lineSeparator--): > > Returns the system-dependent line separator string. It always returns the same value - the initial value of the [system property](https://docs.oracle.com/javase/9/docs/api/java/lang/System.html#getProperty-java.lang.String-) `line.separator`. > > > On UNIX systems, it returns `"\n"`; on Microsoft Windows systems it returns `"\r\n"`. > > > Upvotes: 2 <issue_comment>username_3: > > My Professor kept telling us she want us to use the `System.lineSeparator();` to create an emphty new line > > > Are you actually sure she said that? Because invoking `System.lineSeparator();` does nothing: it returns a string, which is simply discarded. If you want to insert a new line (in `System.out`), use: ``` System.out.println(); ``` Upvotes: 3
2018/03/17
761
2,583
<issue_start>username_0: I am new to Rust and I'm working on a game with the Piston engine to wet my feet. I want to render a bunch of entities using sprite sheets, but a lot of entities might share a sprite sheet so I would like to only load and store one copy of each file. In pseudo code, my approach is basically like this: ``` fn get_spritesheet(hashmap_cache, file): if file not in hashmap_cache: hashmap_cache[file] = load_image_file(file) return hashmap_cache[file] ``` Then maybe something like: ``` //These 'sprite' fileds point to the same image in memory let player1 = Entity { sprite: get_spritesheet(cache, "player.png") }; let player2 = Entity { sprite: get_spritesheet(cache, "player.png") }; ``` However, I am running in to a lot of barriers with Rust's ownership system (probably because I just don't understand it). As far as I can tell, I want the cahe/hashmap to "own" the image resources. Specifically, then, returning references (as in the `get_spritesheet` function) seems to be weird. Also, is it possible for a struct to not own all its members? I think it is but I was confused about how to do that.<issue_comment>username_1: I figured out that returning a borrow was only giving me an error because I passed in two borrowed references to the function and it didn't know which one the return was borrowing from. Adding lifetime parameters made it work. My function now looks like this: ``` pub fn load_spritesheet<'a>( spritesheets: &'a mut HashMap, file: &String, ) -> Option<&'a Texture> { if !spritesheets.contains\_key(file) { if let Some(texture) = load\_texture( &vec!["dynamic\_entities", "spritesheets"], file.as\_str(), &TextureSettings::new(), ) { spritesheets.insert(file.clone(), texture); } } spritesheets.get(file) } ``` As for the reference in the struct, I just implemented a getter method that calls `load_spritesheet` every frame. Not ideal, but works for now. Upvotes: 0 <issue_comment>username_2: This is what [`std::collections::hash_map::Entry`](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html) is for: > > A view into a single entry in a map, which may either be vacant or occupied. > > > ``` match hashmap_cache.entry(key) { Entry::Vacant(entry) => *entry.insert(value), Entry::Occupied(entry) => *entry.get(), } ``` If the entry is vacant, the value is inserted into the cache, otherwise the value is received from the cache. [Playground](https://play.rust-lang.org/?gist=8c751400f6a815287b48b1efcbe77b68&version=stable) Upvotes: 4 [selected_answer]
2018/03/17
765
2,701
<issue_start>username_0: I like to have no warnings in my code, however this jaxb class , which works well, does give class cast warnings common due to lack of jdk method variant. Is there any way to support all jaxb conversions without getting this warning. I use JAXBIntrospector rather than just Unmarshaller since some jaxb classes only using unmarshaller throws an error on. here is sample code: ``` public static T unmarshall( final String xml , final Class clazz ) throws Exception { T rtn = null; JAXBContext jaxbContext; jaxbContext = jaxbContextCache.get( clazz ); if ( jaxbContext == null ) { jaxbContext = JAXBContext.newInstance( Class.forName( clazz.getName() ) ); jaxbContextCache.put( clazz , jaxbContext ); } final Reader reader = new StringReader(xml); final XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS\_SUPPORTING\_EXTERNAL\_ENTITIES, Boolean.FALSE); xif.setProperty(XMLInputFactory.SUPPORT\_DTD, Boolean.FALSE); final XMLStreamReader xmlReader = xif.createXMLStreamReader(reader); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); rtn = (T) JAXBIntrospector.getValue( unmarshaller.unmarshal( xmlReader ) ); // warning cast conversion return rtn; } ```<issue_comment>username_1: I figured out that returning a borrow was only giving me an error because I passed in two borrowed references to the function and it didn't know which one the return was borrowing from. Adding lifetime parameters made it work. My function now looks like this: ``` pub fn load_spritesheet<'a>( spritesheets: &'a mut HashMap, file: &String, ) -> Option<&'a Texture> { if !spritesheets.contains\_key(file) { if let Some(texture) = load\_texture( &vec!["dynamic\_entities", "spritesheets"], file.as\_str(), &TextureSettings::new(), ) { spritesheets.insert(file.clone(), texture); } } spritesheets.get(file) } ``` As for the reference in the struct, I just implemented a getter method that calls `load_spritesheet` every frame. Not ideal, but works for now. Upvotes: 0 <issue_comment>username_2: This is what [`std::collections::hash_map::Entry`](https://doc.rust-lang.org/std/collections/hash_map/enum.Entry.html) is for: > > A view into a single entry in a map, which may either be vacant or occupied. > > > ``` match hashmap_cache.entry(key) { Entry::Vacant(entry) => *entry.insert(value), Entry::Occupied(entry) => *entry.get(), } ``` If the entry is vacant, the value is inserted into the cache, otherwise the value is received from the cache. [Playground](https://play.rust-lang.org/?gist=8c751400f6a815287b48b1efcbe77b68&version=stable) Upvotes: 4 [selected_answer]
2018/03/17
1,264
4,363
<issue_start>username_0: I'm modifying several functions of some "core" JS software using "hijacking": ``` var orig_func = func; // initially function(a,b,c,d) func = function(a,b,c,d) { // modify arguments d = someCustomization(c,d); // do additional stuff doSomethingCustom(a); // apply the original "core" function return orig_func.apply(this,arguments); } ``` which works nicely *unless* the modified params are optional: calling ``` func(a,b); ``` works in a way that `d` is `undefined` even though `someCustomization` returns something else when both its arguments are `undefined`. Here's an MVCE for using in cosole: ``` var f = function(optionalParam){ if(optionalParam) console.log(optionalParam); }; var orig_f = f; f = function(optionalParam){ optionalParam = optionalParam ? 'custom: '+optionalParam : 'default'; orig_f.apply(this, arguments); }; f(); // shows undefined f('test'); // shows 'custom: test' ``` "Expected" behaviour is to see `"default"` in console in the first case, but I get `undefined` instead. After some experiments and using [this thread](https://stackoverflow.com/q/13610987/3995261) where I've summarized adding a positioned param in a [corresponding answer](https://stackoverflow.com/a/49340230/3995261) I've come with the following solution in terms of MCVE: ``` var f = function(some,optionalParam){ console.log('some:',some); console.log('optionalParam:',optionalParam); }; var orig_f = f; f = function(some,optionalParam){ if(optionalParam) optionalParam = 'custom: '+optionalParam; else { var argPosition = 2; while(arguments.length < argPosition) [].push.call(arguments,undefined); arguments[argPosition-1] = 'default'; } orig_f.apply(this, arguments); }; f(); // shows 'some: undefined' and 'optionalParam: default' ``` or in terms of the initial task: ``` var orig_func = func; // initially function(a,b,c,d) func = function(a,b,c,d) { // modify arguments while(arguments.length < 4) [].push.call(arguments,undefined); arguments[3] = someCustomization(c,d); // do additional stuff doSomethingCustom(a); // apply the original "core" function return orig_func.apply(this,arguments); } ``` But I'm not really able to explain what's the problem with the initial approach: why it worked for required (used) params and failed for an optional (unused) one? Does it have anything to do with closures? Why `d` is "not connected" with `arguments` in the second case?<issue_comment>username_1: `arguments` "magic bindings" are created by iterating actual arguments, so if an arg is not there, no binding will be created: ```js function a(x, y) { y = 42; console.log(arguments) } a(10, 20) a(10) ``` That said, using magic bindings is a bad idea, and they won't work in the strict mode anyways. If the number of arguments is known beforehand, simply do ``` orig_func.call(this, a, b, c, d); ``` otherwise use a splat `...args` and manipulate that. Upvotes: 2 <issue_comment>username_2: Right, with the help of username_1 ("magic bindings" keyword) and some more research I've come to an almost sufficient explanation: * in the *old* standart (haven't found which one, though) argument variables (`a,b,c,d`) and `arguments[i]` point to the same values (*not sure how this is done in JS*, though) + in the *new* standart this is not so (like Bergi has said, it is deprecated): changing `arguments[0]` won't affect `a` and vise versa; like username_1 said, it is so in the strict mode: ``` function f(x) { "use strict"; arguments[0] = 5; console.log( x ); } f(1); // logs 1 ``` * now when all variables are present, both `a,b,c,d` (as variables scoped to the function) and `arguments[1-4]` are defined and connected pairwise pointing to the same values. When params `c` and `d` are omitted, `arguments[3]` and `arguments[4]` are not defined and even if we define them, there's no "connection" between them and the variables (again, I'm *not sure if such connection can be created manually*) * basic recomendation is if we need to modify arguments, we should either use only `arguments` (and `.apply` them) or only local variables (and use `.call`) or mix them but don't rely on the connection between them Upvotes: 1 [selected_answer]
2018/03/17
635
2,239
<issue_start>username_0: If I hit tab multiple times to indent something, then I always get an anoying window showing up: [![enter image description here](https://i.stack.imgur.com/vAtLi.jpg)](https://i.stack.imgur.com/vAtLi.jpg) This is extremly annoying, how can I stop this? UPDATE: I use Netbeans 8.2. It seems to happen in `.html` files and also in blade templates but not in pure .php files. [![enter image description here](https://i.stack.imgur.com/bM9O4.png)](https://i.stack.imgur.com/bM9O4.png) I have to write something, if I then press tab a dropdown will appear sometimes if I then press tab again, then the `Insert Button` window shows.<issue_comment>username_1: I can't replicate your problem with NetBeans 8.2, but I can make that **Insert Button** window appear by doing the following: * Edit an HTML file. * Press *control/space* to open the autocomplete menu as shown in the OP. * Hit *enter*, which selects the first entry on the dropdown menu, which happens to be **Button**. * The **Insert Button** window opens. A second way of making that happen is: * Edit an HTML file. * Type **`<`** to open the drop down menu of all HTML tags. * Press *backspace* to switch to the menu in the OP screenshot. * Hit *enter*, which selects the first entry on the dropdown menu, which happens to be **Button**. * The **Insert Button** window opens. In the second scenario the initial display of that drop down menu can be prevented: * **Tools > Options > Editor > Code Completion** * Select **HTML** as the **Language**. * Uncheck **Auto Popup Completion Window**. * Click **Apply** then click **OK**. [![autoCompleteOff](https://i.stack.imgur.com/irgoi.png)](https://i.stack.imgur.com/irgoi.png) The change is immediately effective, so typing **`<`** no longer triggers the display of the drop down menu. Since I can't replicate your problem it may not fix your issue, but it's worth trying. You can still request the drop down menu by pressing *control/space*. Upvotes: 3 [selected_answer]<issue_comment>username_2: [Here](https://stackoverflow.com/a/45148920/1441712) is the right answer: > > Simply go to Tools/Palette/Code Clips and remove everything from > Palette (all folders and items). > > > Upvotes: 0
2018/03/17
729
2,964
<issue_start>username_0: I am trying to create a `table` class that extends `ArrayList`. In it, I would like to be able to create a `map` method that takes a lambda expression and returns a new `table` with the mapped values. I would also like to do this with `filter`. I use the map and filter a lot and I don't like typing out the whole thing over and over. ``` public abstract class Table extends ArrayList { // a lot of other stuff. public Table map(/\*WHAT DO I PUT HERE?\*/ mapper) { return this.stream().map(mapper).collect(/\*WHAT DO I PUT HERE?\*/); } public Table filter(/\*WHAT DO I PUT HERE?\*/ predicate) { return this.stream().filter(predicate).collect(/\*WHAT DO I PUT HERE?\*/); } } ``` I am still trying to figure out generics. Maybe there is a better way. I don't know. I have tried duplicating what is in the original code for the `ArrayList`, but everything I try seems to create new problems.<issue_comment>username_1: On one hand, it's entirely possible: ``` public abstract class Table extends ArrayList { // implement in concrete subclasses public abstract Collector> collector(); // Collector> collector() is enough if map doesn't have E1 type parameter public Table map(Function mapper) { return this.stream().map(mapper).collect(collector()); } public Table filter(Predicate predicate) { return this.stream().filter(predicate).collect(collector()); } } public class ChildTable extends Table { @Override public Collector> collector() { return Collectors.toCollection(() -> new ChildTable()); // or simpler Collectors.toCollection(ChildTable::new); } } ``` `collector()` could be implemented, but it would have to return a specific subtype of `Table`. On the other, it may be better to have the list as a *field* of `Table` instead of extending it: prefer composition over inheritance. Do you really want all `ArrayList` methods available? Upvotes: 4 [selected_answer]<issue_comment>username_2: Simply use `Function` for mapper as your return type is same object and `Predicate` for predicate as `E` is to be predicated. For Table whatever implementation class you have that you be used inside collect. See the way collect works. It basically takes an initializer (`first argument`), BiFunction to specify how to add the element to the collection (`second argument`) and finally BiFunction to specify how it works in case of the parallel stream (`third argument`). See the code below:- ``` public abstract class Table extends ArrayList { public Table map(Function mapper) { return this.stream().map(mapper).collect(TableImpl::new, TableImpl::add, TableImpl::addAll); } public Table filter(Predicate predicate) { return this.stream().filter(predicate).collect(TableImpl::new, TableImpl::add, TableImpl::addAll); } } class TableImpl extends Table { //whatever you impl is } ``` Please feel free to extract the collect implementation to a `Collector` to avoid duplication of code. Upvotes: 2
2018/03/17
730
2,829
<issue_start>username_0: I am learning angular 5 ,I have copied this example from angular's official site. ``` import {Component} from '@angular/core' @Component({ selector : "parent-onchange", template :` from parent componenet Minor Major ` }) export class ParentCompOnChange{ sendMaj : 1; sendMin : 23; updateMin(){ console.log("before"+this.sendMin); this.sendMin++; console.log(this.sendMin); } updateMaj(){ this.sendMaj++; console.log(this.sendMaj); } } ``` So this line `console.log("before"+this.sendMin);` gives undefined value of sendMin and other console.logs give NAN (adding one to undefined). Could anyone tell me what is wrong as per the official document [Angular 5](https://angular.io/guide/component-interaction#parent-listens-for-child-event) it should work fine.<issue_comment>username_1: On one hand, it's entirely possible: ``` public abstract class Table extends ArrayList { // implement in concrete subclasses public abstract Collector> collector(); // Collector> collector() is enough if map doesn't have E1 type parameter public Table map(Function mapper) { return this.stream().map(mapper).collect(collector()); } public Table filter(Predicate predicate) { return this.stream().filter(predicate).collect(collector()); } } public class ChildTable extends Table { @Override public Collector> collector() { return Collectors.toCollection(() -> new ChildTable()); // or simpler Collectors.toCollection(ChildTable::new); } } ``` `collector()` could be implemented, but it would have to return a specific subtype of `Table`. On the other, it may be better to have the list as a *field* of `Table` instead of extending it: prefer composition over inheritance. Do you really want all `ArrayList` methods available? Upvotes: 4 [selected_answer]<issue_comment>username_2: Simply use `Function` for mapper as your return type is same object and `Predicate` for predicate as `E` is to be predicated. For Table whatever implementation class you have that you be used inside collect. See the way collect works. It basically takes an initializer (`first argument`), BiFunction to specify how to add the element to the collection (`second argument`) and finally BiFunction to specify how it works in case of the parallel stream (`third argument`). See the code below:- ``` public abstract class Table extends ArrayList { public Table map(Function mapper) { return this.stream().map(mapper).collect(TableImpl::new, TableImpl::add, TableImpl::addAll); } public Table filter(Predicate predicate) { return this.stream().filter(predicate).collect(TableImpl::new, TableImpl::add, TableImpl::addAll); } } class TableImpl extends Table { //whatever you impl is } ``` Please feel free to extract the collect implementation to a `Collector` to avoid duplication of code. Upvotes: 2
2018/03/17
992
2,860
<issue_start>username_0: Have two Dictionaries in Python and would like to make a join using a key. The first dictionary "d" is OrderedDict like this: ``` [OrderedDict([ ('id', '1'), ('date', '20170101'), OrderedDict([ ('id', '2'), ('date', '20170102'), OrderedDict([ ('id', '3'), ('date', '20170102')] ``` The second one "dd" is defaultdict and it's like this: ``` defaultdict(int, {'1': 14, '2': 5, '3': 7}) ``` I want to make a join using possibilities of "operator" library and using keys but the approach is not working for me because I dont know exactly how should I treat the keys in defaultdict: ``` sort_key = operator.itemgetter("id") ks=[ k for k in dd.keys()] for i, j in zip(sorted(d, key=sort_key), sorted(dd,key=ks)): i.update(j) ``` How should I correctly perform the joining? Desirable output will be OrderedDict with additional values from the second dictionary: ``` [OrderedDict([ ('id', '1'), ('date', '20170101'), ('quantity', '14'), OrderedDict([ ('id', '2'), ('date', '20170102'), ('quantity', '5'), OrderedDict([ ('id', '3'), ('date', '20170102'), ('quantity', '7')] ``` Thanks!<issue_comment>username_1: ``` from collections import OrderedDict, defaultdict d = [OrderedDict([ ('id', '1'), ('date', '20170101')]), OrderedDict([ ('id', '2'), ('date', '20170102')]), OrderedDict([ ('id', '3'), ('date', '20170102')]) ] dd = defaultdict(int, {'1': 14, '2': 5, '3': 7}) id1 = set([ di['id'] for di in d]) id2 = set( dd.keys() ) final_keys = id1 & id2 to_be_del = [] for di in d: id = di['id'] if id not in final_keys: to_be_del.append(di) continue q = dd[id] di['quantity'] = q for di in to_be_del: d.remove(di) print(d) ``` 1. Get list of ids from OrderedDict list 2. Get list of keys from dd 3. Get intersection of these keys 4. Set the quantity from dd and delete OrderedDict if it's id is missing in the defaultdict. <https://ideone.com/ZXVcQu> Upvotes: 1 <issue_comment>username_2: You can try this: ``` from collections import OrderedDict, defaultdict d = [OrderedDict([ ('id', '1'), ('date', '20170101')]), OrderedDict([ ('id', '2'), ('date', '20170102')]), OrderedDict([ ('id', '3'), ('date', '20170102')])] marker = defaultdict(int, {'1': 14, '2': 5, '3': 7}) new_d = [OrderedDict([(a, b) for a, b in i.items()]+[('quantity', marker[i['id']])]) for i in d] ``` Output: ``` [OrderedDict([('id', '1'), ('date', '20170101'), ('quantity', 14)]), OrderedDict([('id', '2'), ('date', '20170102'), ('quantity', 5)]), OrderedDict([('id', '3'), ('date', '20170102'), ('quantity', 7)])] ``` Upvotes: 1 [selected_answer]
2018/03/17
1,019
3,049
<issue_start>username_0: ``` new = ['|<', '@', '1', '3', '7', '0', '8', '\/'] old = ['K', 'A', 'L', 'E', 'T', 'O', 'B', 'V'] ask_user = input("Type a sentence: ") def ask_replace_letters(): ask_user = input("Do you want to replace letters? ").upper() if ask_user == "YES": ask_user1 = input("What letters do you want to replace? ").upper() for letter in ask_user1: if letter not in old: print("This program cannot replace the letter(s): ", letter) print(replace_letters()) elif ask_user == "NO": print(replace_phrases()) else: print("Please enter yes or no.") def replace_letters(): result = ask_user for i in range(len(old)): result = result.replace(old[i], new[i]) return result ask_replace_letters() ``` When I run the code I get: ``` Type a sentence: BYE Do you want to replace letters? yes What letters do you want to replace? BYW This program cannot replace the letter(s): Y 8Y3 This program cannot replace the letter(s): W 8Y3 ``` What I want: ``` Type a sentence: BYE Do you want to replace letters? YES What letters do you want to replace? BYW This program cannot replace the letter(s): YW 8YE ``` Is there a way to go around this? Basically I want the function to take the character the user input, check if it's in the list, change it, and state the ones that couldn't be changed. Sorry I'm still somewhat new to Python.<issue_comment>username_1: ``` from collections import OrderedDict, defaultdict d = [OrderedDict([ ('id', '1'), ('date', '20170101')]), OrderedDict([ ('id', '2'), ('date', '20170102')]), OrderedDict([ ('id', '3'), ('date', '20170102')]) ] dd = defaultdict(int, {'1': 14, '2': 5, '3': 7}) id1 = set([ di['id'] for di in d]) id2 = set( dd.keys() ) final_keys = id1 & id2 to_be_del = [] for di in d: id = di['id'] if id not in final_keys: to_be_del.append(di) continue q = dd[id] di['quantity'] = q for di in to_be_del: d.remove(di) print(d) ``` 1. Get list of ids from OrderedDict list 2. Get list of keys from dd 3. Get intersection of these keys 4. Set the quantity from dd and delete OrderedDict if it's id is missing in the defaultdict. <https://ideone.com/ZXVcQu> Upvotes: 1 <issue_comment>username_2: You can try this: ``` from collections import OrderedDict, defaultdict d = [OrderedDict([ ('id', '1'), ('date', '20170101')]), OrderedDict([ ('id', '2'), ('date', '20170102')]), OrderedDict([ ('id', '3'), ('date', '20170102')])] marker = defaultdict(int, {'1': 14, '2': 5, '3': 7}) new_d = [OrderedDict([(a, b) for a, b in i.items()]+[('quantity', marker[i['id']])]) for i in d] ``` Output: ``` [OrderedDict([('id', '1'), ('date', '20170101'), ('quantity', 14)]), OrderedDict([('id', '2'), ('date', '20170102'), ('quantity', 5)]), OrderedDict([('id', '3'), ('date', '20170102'), ('quantity', 7)])] ``` Upvotes: 1 [selected_answer]
2018/03/17
493
1,674
<issue_start>username_0: ```js console.log(/\.js$/.toString() === '/\.js$/') // false // or console.log(/\.js$/.toString() == '/\.js$/') // false // but console.log(/\.js$/.toString()) // /\.js$/ console.log(/\.js$/.toString() === /\.js$/.toString()) // true ```<issue_comment>username_1: `\` is a special char in string literals to escape the next char. Use 2 of them. ```js console.log(/\.js$/.toString() === '/\\.js$/') // true ``` Upvotes: 1 <issue_comment>username_2: Because when converted to a string, the meaning of `\` changes. In a string, it is used to escape characters, such as `\n` and `\t`. In a regex, it means to take the next character literally, such as `.` in your case. Thus, when converted to a string `\` must be escaped, so `/\.js$/` becomes `"/\\.js$/"`. Note that if you then feed this into the `RegExp` constructor, `"\\.js$"` would be valid, whereas `"\.js$"` would have a different meaning, and be interpreted as `/.js$/` Upvotes: 3 [selected_answer]<issue_comment>username_3: Because the string **'`/\.js$/`**'becomes **`/.js$/`** this happens because **'.'** in js is actualy the scaped character **.** So basically you are comparing **'`/\.js$/`**' with **`/.js$/`** that are different strings. to achieve get the same strings you need to escape the / by changing your string literal to `'/\\.js$/'` Upvotes: 1 <issue_comment>username_4: See the difference your self, `console.log(/\.js$/.toString());` prints `/\.js$/` while `console.log('/\.js$/');` prints `\.js$/` which is obviously different.(so you are getting false as both string are different) ```js console.log(/\.js$/.toString()); console.log('/\.js$/'); ``` Upvotes: 1
2018/03/17
522
1,713
<issue_start>username_0: I have a file containing some data and I want to use only the first column as a stdin for my script, but I'm having trouble extracting it. I tried using this ``` awk -F"\t" '{print $1}' inputs.tsv ``` but it only shows the first letter of the first column. I tried some other things but it either shows the entire file or just the first letter of the first column. My file looks something like this: ``` Harry_Potter 1 Lord_of_the_rings 10 Shameless 23 .... ```<issue_comment>username_1: Try this (better rely on a real [csv](/questions/tagged/csv "show questions tagged 'csv'") parser...): ``` csvcut -c 1 -f $'\t' file ``` Check [csvkit](https://csvkit.readthedocs.io/en/1.0.3/#) Output : -------- ``` Harry_Potter Lord_of_the_rings Shameless ``` Note : ------ As @RomanPerekhrest said, you should fix your broken sample input (we saw spaces where tabs are expected...) Upvotes: 2 <issue_comment>username_2: You can use `cut` which is available on all Unix and Linux systems: ``` cut -f1 inputs.tsv ``` You don't need to specify the `-d` option because tab is the default delimiter. From `man cut`: > > > ``` > -d delim > Use delim as the field delimiter character instead of the tab character. > > ``` > > As Benjamin has rightly stated, your `awk` command is indeed correct. Shell passes literal \t as the argument and awk does interpret it as a tab, while other commands like `cut` may not. Not sure why you are getting just the first character as the output. --- You may want to take a look at this post: * [Difference between single and double quotes in Bash](https://stackoverflow.com/a/42082956/6862601) Upvotes: 5 [selected_answer]
2018/03/17
1,461
4,813
<issue_start>username_0: ``` #include #include #include #include "linkedStack.h" #include #include #include "ArgumentManager.h" using namespace std; int getPrecedence(char ch) //this function will decide and return precedence for the operators and operand { switch (ch) { case '/':return 2; break; case '\*': return 2; break; case '+': return 1; break; case '-': return 1; break; default: return 0; } } string infixToPostfix(const string& expression) // this function will convert the infix expression to postfix by passing the infix expression string { int size = expression.size(); //size of infix string char infix[expression.size()]; //converting string into array of chars strncpy(infix, expression.c\_str(), sizeof(infix)); infix[sizeof(infix)] = '\0'; //adding 0 for array ending char postfix[strlen(infix)]; // create a char array with the size of the infix string length linkedStack s; int precedence; int i = 0; int k = 0; char ch; //iterate the infix expression while (i < size) { ch = infix[i]; //push opening parenthesis to stack if (ch == '(') { s.push(ch); i++; continue; } if (ch == ')') { while (!s.empty() && s.top() != '(') // if closing parenthesis is found pop of all the elements and append it to the postfix expression till we encounter an opening parenthesis { postfix[k++] = s.top(); s.pop(); } if (!s.empty()) { s.pop(); // pop the opening parenthesis } i++; continue; } precedence = getPrecedence(ch); if (precedence == 0) { postfix[k++] = ch; // if an operand is found add it to the postfix expression } else { if (s.empty()) { s.push(ch); //push operator onto stack if the stack is empty } else { while (!s.empty() && s.top() != '(' && precedence <= getPrecedence(s.top())) // pop of all the operators from the stack to the postfix expression till we see an operator with a lower precedence than the current operator { postfix[k++] = s.top(); s.pop(); } s.push(ch); // push the current operator to stack } } i++; } while (!s.empty()) // pop all of the the remaining operators in the stack and add it to postfix { postfix[k++] = s.top(); s.pop(); } postfix[k] = '\0'; // add null character to end of character array for c string string postfixStr = postfix; //covert the final postfix char array to a string return postfixStr; // returns the final postfix expression as a string } int main(int argc, char\* argv[]) { ArgumentManager am(argc, argv); string infilename = am.get("A"); string outfilename = am.get("C"); string expression1; ifstream infile; infile.open(infilename); if (infile.good()) { getline(infile, expression1); //gets the infix string from file } infile.close(); //close the infile stream string expression2 = "12 + 3 / 4"; string postfix1 = infixToPostfix(expression1); string postfix2 = infixToPostfix(expression2); cout << expression1 << endl; cout << postfix1 << endl; cout << expression2 << endl; cout << postfix2 << endl; return 0; } ``` Hi, I'm having trouble with my output with my infix to post fix converter using stack. For instance in the case of "12 + 3 / 4" the output should be "12 3 4 / +" with the characters evenly spaced by one white space. However, it is adding unnecessary white spaces or none at all. For the test case above you can see the problem I'm running into in the attached pic or below. The first line is the infix the second is the post fix output. There are two cases here.[Output Example](https://i.stack.imgur.com/DvtEa.png) ``` 25 + ( 4 * 5 ) - 12 25 4 5 * + 12- 12 + 3 / 4 12 3 4/+ ```<issue_comment>username_1: Try this (better rely on a real [csv](/questions/tagged/csv "show questions tagged 'csv'") parser...): ``` csvcut -c 1 -f $'\t' file ``` Check [csvkit](https://csvkit.readthedocs.io/en/1.0.3/#) Output : -------- ``` Harry_Potter Lord_of_the_rings Shameless ``` Note : ------ As @RomanPerekhrest said, you should fix your broken sample input (we saw spaces where tabs are expected...) Upvotes: 2 <issue_comment>username_2: You can use `cut` which is available on all Unix and Linux systems: ``` cut -f1 inputs.tsv ``` You don't need to specify the `-d` option because tab is the default delimiter. From `man cut`: > > > ``` > -d delim > Use delim as the field delimiter character instead of the tab character. > > ``` > > As Benjamin has rightly stated, your `awk` command is indeed correct. Shell passes literal \t as the argument and awk does interpret it as a tab, while other commands like `cut` may not. Not sure why you are getting just the first character as the output. --- You may want to take a look at this post: * [Difference between single and double quotes in Bash](https://stackoverflow.com/a/42082956/6862601) Upvotes: 5 [selected_answer]
2018/03/17
1,076
3,836
<issue_start>username_0: I'm trying to figure out how I can access flask db query all data passed to template from jquery function. I have a db table containing customer\_name and customer\_phone\_number. I pass this to template via flask view db query all. I iterate this and load customer\_name into dropdown, no problems here! I'm using jquery to monitor dropdown selection and want to load customer\_phone\_number into text input field when customer\_name is selected. Something like this: flask view: ``` @auth.route('/order/add', methods=['GET', 'POST']) @login_required def order_add(): form = OrderForm() custs = Customer.query.filter_by(type_is_retail=False).all() return render_template('auth/orders/order_add_test2.html', custs=custs, form=form, title='New Order') ``` html template: ``` Company Name Add New Company ---------------------------- Select Company {% if custs %} {% for cust in custs %} {{ cust.lname }} {% endfor %} {% endif %} Phone Number ``` jquery: ``` $('#comp_name').on('change', function() { var cust_pn; for cust in custs { <--------------------------------- if ($(this).val() == cust.customer_name) { <------- Here is issue! $('#pn').val() = cust.customer_phone_number; <- } } }); ``` Looking for proper syntax to iterate over db query in Jquery. It doesn't seem necessary to implement AJAX to go back to flask to get another db query, just for Jquery. Is there a way to pass the orignal db query to Jquery initally? Or access the original query via Jquery also? using answer below, if I: ``` var custs = {{ custs }}; ``` this line prevents my other (unrelated to this question) jquery functions from working! but if I: ``` var custs; $('#comp_name').on('change', function() { custs = "{{ custs }}"; alert(custs); }); ``` then alert shows: ``` [<Customer1>,<Customer3>] ``` which is the correct customer numbers that I need access to, but doesn't show \_name or \_phone\_number that I can access or reference. This seems to be getting me closer to my objective, however! How can I use this properly to access custs.company\_name and custs.phone\_number? I'm not opposed to using AJAX if that is only way, I just don't think that is the most efficient way seeing how the data I need hass already been passed to the template. Should I also pass the same data a different way for jquery to access it also at the same time I pass it to the template? Instead of passing data to template then firing jquery to go back to flask view to get the same data (maybe wrapped in a different coat!) and bring it back to jquery!<issue_comment>username_1: Try this (better rely on a real [csv](/questions/tagged/csv "show questions tagged 'csv'") parser...): ``` csvcut -c 1 -f $'\t' file ``` Check [csvkit](https://csvkit.readthedocs.io/en/1.0.3/#) Output : -------- ``` Harry_Potter Lord_of_the_rings Shameless ``` Note : ------ As @RomanPerekhrest said, you should fix your broken sample input (we saw spaces where tabs are expected...) Upvotes: 2 <issue_comment>username_2: You can use `cut` which is available on all Unix and Linux systems: ``` cut -f1 inputs.tsv ``` You don't need to specify the `-d` option because tab is the default delimiter. From `man cut`: > > > ``` > -d delim > Use delim as the field delimiter character instead of the tab character. > > ``` > > As Benjamin has rightly stated, your `awk` command is indeed correct. Shell passes literal \t as the argument and awk does interpret it as a tab, while other commands like `cut` may not. Not sure why you are getting just the first character as the output. --- You may want to take a look at this post: * [Difference between single and double quotes in Bash](https://stackoverflow.com/a/42082956/6862601) Upvotes: 5 [selected_answer]
2018/03/17
1,863
6,589
<issue_start>username_0: While compiling the following (reduced) code: ``` #include #include template struct tying; template<> struct tying<1> {static auto function(auto& o) -> decltype(auto) {auto& [p1] = o;return std::tie(p1);}}; template<> struct tying<2> {static auto function(auto& o) -> decltype(auto) {auto& [p1,p2] = o;return std::tie(p1,p2);}}; template concept bool n\_components = requires(T& object) { { tying::function(object) }; }; typedef struct { int a; float b; } test\_t; int main(int argc, char\* argv[]) { constexpr size\_t n = 1; constexpr bool t = n\_components; printf("n\_components: %s\n", n, t ? "yes" : "nope"); return 0; } ``` with gcc specific options `-std=c++1z -fconcepts` the gcc (version 7.3.0, and x86-64 gcc-trunk at godbolt also) fails with an error: > > error: only 1 name provided for structured binding > note: while 'test\_t' decomposes into 2 elements > > > I was very surprised by this, as the error "raises" inside the `requires-expression`, and to my understanding, this should result in `n_components` constraint to get evaluated to false, as the requirement is not satisfied. Note: replacing `constexpr size_t n = 1;` with other values "fixes" the error, so I presume the `n_components` constraint is not to blame: * replacing with `n = 2` the `n_components` constraint evaluates to "true" as expected. * replacing with `n = 3` the `n_components` constraint evaluates to "false" as expected - due to referring to unspecialized `tying<3>` struct. It seems there are no other compilers supporting the c++ concepts and structured bindings available yet to compare with. PS. I was playing around with "poor man's reflection" a.k.a. `magic_get` and hoped to replace the unreliable `is_braces_constructible` trait with something more robust...<issue_comment>username_1: The immediate situation ======================= > > I was very surprised by this, as the error "raises" inside the requires-expression > > > To be precise, the error happens in the body of the `function`s you wrote. We can boil down your code to: ``` void function(auto& arg); void function_with_body(auto& arg) { arg.inexistent_member; } template concept bool test = requires(Arg arg) { function(arg); }; // never fires static\_assert( test ); template concept bool test\_with\_body = requires(Arg arg) { function\_with\_body(arg); }; // never fires static\_assert( test\_with\_body ); ``` ([on `Coliru`](http://coliru.stacked-crooked.com/a/c8ba89e25b97d293)) As far as the `requires` expression are concerned, the function calls are valid C++ expressions: there's nothing tricky about their return and parameter types, and the supplied argument can be passed just fine. No check is performed for the function bodies, and with good reason: the function or function template may have been declared but not defined yet (i.e. as is the case for `function`). Instead, it's normally up to the function template writer to make sure that the function body will be error-free for all (sensible) specializations. Your code uses return type deduction, but that won't make too much of a difference: you can declare a function with a placeholder type (e.g. `decltype(auto)`) without defining it, too. (Although a call to such a function *is* in fact an invalid expression since the type cannot be deduced and that's visible to a `requires` expression, but that's not what you're doing.) In pre-concepts parlance, return type deduction is not SFINAE-friendly. Structured bindings =================== As to your wider problem of writing a constraints around structured bindings, you are out of luck. As best as I know these are all the obstacles: * There is no interface for querying the decomposition size of a type, even though the implementation blatantly has access to the information in order to type-check structured binding declarations. (`std::tuple_size` is for tuple-like types only.). This could be worked around by blindingly trying sizes in increasing order though. * You can only ever write constraints around types and expressions, but structured bindings can only appear in normal variable declarations. (If function parameters could be structured bindings we could work around that.) No trickery with lambda expressions allowed because these can't appear in an unevaluated operand, such as in the body of a `requires` expression. The closest you can go is emulate what the language is doing during an actual structured binding. That can get you support for tuple-like types (including arrays), but not 'dumb' aggregates. ([range-for](https://stackoverflow.com/questions/40676743/how-to-write-a-simple-range-concept) is another case of a statement-level constraint that you can't fit into an expression constraint, and where emulating the language can only get you so far.) Upvotes: 2 <issue_comment>username_2: Here's a partial solution for clang since 5.0. It is distilled from a recent reddit post [Find the number of structured bindings for any struct](https://www.reddit.com/r/cpp/comments/dz1sgk/find_the_number_of_structured_bindings_for_any/?utm_source=share&utm_medium=web2x) The method is non-standard, using gnu extension *statement expressions* to effectively SFINAE on structured binding declarations. It is also non-portable as gcc fails to parse structured binding in statement expression in a lambda trailing return type. ```cpp template struct overloads : Ts... { using Ts::operator()...; }; template overloads(Ts...) -> overloads; template auto num\_bindings\_impl() noexcept { return overloads{ [](auto&& u, int) -> decltype(({auto&& [x0] = u; char{};}))(\*)[1] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1] = u; char{};}))(\*)[2] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1,x2] = u; char{};}))(\*)[3] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1,x2,x3] = u; char{};}))(\*)[4] {return {};}, [](auto&& u, unsigned) -> void {} }(declval(), int{}); }; ``` This implementation to be used only in unevaluated context and expanding out for as many bindings as you wish, up to compiler implementation limits. Then, you can define traits that work up to that limit: ```cpp template inline constexpr bool has\_bindings = [] { if constexpr ( ! is\_empty\_v ) return ! is\_void\_v< decltype(num\_bindings\_impl()) >; else return false; }(); template inline constexpr unsigned num\_members = [] { if constexpr ( ! is\_empty\_v ) return sizeof \*num\_bindings\_impl(); else return 0; }(); ``` <https://godbolt.org/z/EVnbqj> Upvotes: 2
2018/03/17
1,394
5,200
<issue_start>username_0: Is there any way to make this code compile or some other alternative. This implementation is only a example. ``` namespace ConsoleApp3 { using System; public static class Temp where T : struct { public static T DoSomething() => throw new NotImplementedException(); // common implementation public static int DoSomething() => 10; // custom implementation for specified type } } ```<issue_comment>username_1: The immediate situation ======================= > > I was very surprised by this, as the error "raises" inside the requires-expression > > > To be precise, the error happens in the body of the `function`s you wrote. We can boil down your code to: ``` void function(auto& arg); void function_with_body(auto& arg) { arg.inexistent_member; } template concept bool test = requires(Arg arg) { function(arg); }; // never fires static\_assert( test ); template concept bool test\_with\_body = requires(Arg arg) { function\_with\_body(arg); }; // never fires static\_assert( test\_with\_body ); ``` ([on `Coliru`](http://coliru.stacked-crooked.com/a/c8ba89e25b97d293)) As far as the `requires` expression are concerned, the function calls are valid C++ expressions: there's nothing tricky about their return and parameter types, and the supplied argument can be passed just fine. No check is performed for the function bodies, and with good reason: the function or function template may have been declared but not defined yet (i.e. as is the case for `function`). Instead, it's normally up to the function template writer to make sure that the function body will be error-free for all (sensible) specializations. Your code uses return type deduction, but that won't make too much of a difference: you can declare a function with a placeholder type (e.g. `decltype(auto)`) without defining it, too. (Although a call to such a function *is* in fact an invalid expression since the type cannot be deduced and that's visible to a `requires` expression, but that's not what you're doing.) In pre-concepts parlance, return type deduction is not SFINAE-friendly. Structured bindings =================== As to your wider problem of writing a constraints around structured bindings, you are out of luck. As best as I know these are all the obstacles: * There is no interface for querying the decomposition size of a type, even though the implementation blatantly has access to the information in order to type-check structured binding declarations. (`std::tuple_size` is for tuple-like types only.). This could be worked around by blindingly trying sizes in increasing order though. * You can only ever write constraints around types and expressions, but structured bindings can only appear in normal variable declarations. (If function parameters could be structured bindings we could work around that.) No trickery with lambda expressions allowed because these can't appear in an unevaluated operand, such as in the body of a `requires` expression. The closest you can go is emulate what the language is doing during an actual structured binding. That can get you support for tuple-like types (including arrays), but not 'dumb' aggregates. ([range-for](https://stackoverflow.com/questions/40676743/how-to-write-a-simple-range-concept) is another case of a statement-level constraint that you can't fit into an expression constraint, and where emulating the language can only get you so far.) Upvotes: 2 <issue_comment>username_2: Here's a partial solution for clang since 5.0. It is distilled from a recent reddit post [Find the number of structured bindings for any struct](https://www.reddit.com/r/cpp/comments/dz1sgk/find_the_number_of_structured_bindings_for_any/?utm_source=share&utm_medium=web2x) The method is non-standard, using gnu extension *statement expressions* to effectively SFINAE on structured binding declarations. It is also non-portable as gcc fails to parse structured binding in statement expression in a lambda trailing return type. ```cpp template struct overloads : Ts... { using Ts::operator()...; }; template overloads(Ts...) -> overloads; template auto num\_bindings\_impl() noexcept { return overloads{ [](auto&& u, int) -> decltype(({auto&& [x0] = u; char{};}))(\*)[1] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1] = u; char{};}))(\*)[2] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1,x2] = u; char{};}))(\*)[3] {return {};}, [](auto&& u, int) -> decltype(({auto&& [x0,x1,x2,x3] = u; char{};}))(\*)[4] {return {};}, [](auto&& u, unsigned) -> void {} }(declval(), int{}); }; ``` This implementation to be used only in unevaluated context and expanding out for as many bindings as you wish, up to compiler implementation limits. Then, you can define traits that work up to that limit: ```cpp template inline constexpr bool has\_bindings = [] { if constexpr ( ! is\_empty\_v ) return ! is\_void\_v< decltype(num\_bindings\_impl()) >; else return false; }(); template inline constexpr unsigned num\_members = [] { if constexpr ( ! is\_empty\_v ) return sizeof \*num\_bindings\_impl(); else return 0; }(); ``` <https://godbolt.org/z/EVnbqj> Upvotes: 2