_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d18501
test
It was a case sensitivity issue in the file names : two different files, with only difference in casing in their names, were stored in git. When checking the differences, git would receive the "wrong" content for one of the two names.
unknown
d18502
test
At log out button_click , perform session.Abondon(); and Check the session in each page_Load like if(session["userName"]!=null) { //Perform the action } else { //Redirect to login page } A: Use the following code on logout click Session.RemoveAll(); Session.Abandon(); A: add this logout button Session.Abandon(); A: You can use this... <script type = "text/javascript" > function preventBack() { window.history.forward(); } setTimeout("preventBack()", 0); window.onunload = function () { null }; </script>
unknown
d18503
test
You can mock loops in LESS using a recursive mixin with a guard expression. Here's an example applied to your case: #q1 { background-color: #ccc; } /* recursive mixin with guard expression - condition */ .darker-qs(@color, @index) when (@index < 10) { @darker-color: darken(@color, 10%); /* the statement */ #q@{index} { background-color: @darker-color; } /* end of the statement */ /* the next iteration's call - final expression */ .darker-qs(@darker-color, @index + 1); } /* the primary call - initialization */ .darker-qs(#ccc, 2);
unknown
d18504
test
I think it'll work if you do the following: * *Remove the configuration you showed in the code snippet above *Add a mapping table and configure its table name to match the original table name. // name this whatever you want class UserUserGroupMapping { public UserUserGroupMappingId { get; set; } public int UserId { get; set; } public virtual User User { get; set; } public int UserGroupId { get; set; } public virtual UserGroup UserGroup { get; set; } // other properties } modelBuilder.Entity<UserUserGroupMapping>() .HasKey(um => um.UserUserGroupMappingId) .ToTable("UserUserGroupMapping"); *Replace the many-to-many collection properties from User and UserGroup and replace it with one-to-many associations class User { // other properties // remove this: // public virtual ICollection<UserGroup> UserGroup { get; set; } public virtual ICollection<UserUserGroupMapping> UserGroupMappings { get; set; } } class UserGroup { // other properties // remove this: // public virtual ICollection<User> Users { get; set; } public virtual ICollection<UserUserGroupMapping> UserMappings { get; set; } } modelBuilder.Entity<UserUserGroupMapping>() .HasRequired(um => um.UserGroup).WithMany(g => g.UserMappings) .HasForeignKey(um => um.UserGroupId); modelBuilder.Entity<UserUserGroupMapping>() .HasRequired(um => um.User).WithMany(g => g.UserGroupMappings) .HasForeignKey(um => um.UserId); *Use the package manager to Add-Migration and remove anything from the scaffolded migration that might attempt to drop the old table and create a new table. The migration will need to at least (I might be missing some here): * *DropPrimaryKey for the original key columns *AddColumn for the new columns (with Int(identity:true, nullable: false) for the new primary key column) *AddPrimaryKey for the new key column Then you can use the methods outlined in this answer to retrieve entities.
unknown
d18505
test
inside docker container run following commands : yum update -y glibc-common yum install -y sudo passwd openssh-server openssh-clients tar screen crontabs strace telnet perl libpcap bc patch ntp dnsmasq unzip pax which rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm yum install -y hiera lsyncd sshpass rng-tools service sshd start; sed -i 's/UsePAM yes/#UsePAM yes/g' /etc/ssh/sshd_config; sed -i 's/#UsePAM no/UsePAM no/g' /etc/ssh/sshd_config; sed -i 's/#PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config; sed -i 's/enabled=0/enabled=1/' /etc/yum.repos.d/CentOS-Base.repo mkdir -p /root/.ssh/; rm -f /var/lib/rpm/.rpm.lock; echo "StrictHostKeyChecking=no" > /root/.ssh/config; echo "UserKnownHostsFile=/dev/null" >> /root/.ssh/config echo "root:password" | chpasswd ( or ) Simply you can pull docker image of centos with ssh in docker hub https://hub.docker.com/search/?isAutomated=0&isOfficial=0&page=1&pullCount=0&q=centos+ssh&starCount=0 https://hub.docker.com/r/kinogmt/centos-ssh/ https://hub.docker.com/r/jdeathe/centos-ssh/ A: You can avoid the "Failed to get D-Bus connection: Operation not permitted" / aka installing systemd inside a docker by using the https://github.com/gdraheim/docker-systemctl-replacement ... after that the docker-exec stuff should be all fine to do things inside a container. A: If you really do need an ssh or sftp container, then you can use my Docker Image as a source image for your own or run it directly: If using the official CentOS-7 Image and you require systemd, there are instructions on how to enable it under the section "Systemd integration". However, based on the following: I need to ssh in to the docker container(CentOS 7) from my host. You can use docker exec to run commands in a running, (backgrounded), container so, for images that have bash available, you can access an interactive tty and run bash as follows from your host - where container can be either the name or id: docker exec --tty --interactive <container> bash OR docker exec -ti <container> bash Finally, it's unlikely to be necessary to install the firewall package in your image as the operator will decide what ports to publish from those which are exposed and you can make use of Docker Networking to only expose the necessary public facing services. A: If you are using the Docker CLI, then you can get into the Docker container using the following command docker exec -it containerId bash I am not sure how to ssh into the docker container, but if you want to do basic operation inside the Docker container, you can make use of the above docker command.
unknown
d18506
test
You don't give much detail as to why. This happens in the Dispose override method of the form (in form.designer.cs). It looks like this: protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } A: Both the Panel and the Form class have a Controls collection property, which has a Clear() method... MyPanel.Controls.Clear(); or MyForm.Controls.Clear(); But Clear() doesn't call dispose() (All it does is remove he control from the collection), so what you need to do is List<Control> ctrls = new List<Control>(MyPanel.Controls); MyPanel.Controls.Clear(); foreach(Control c in ctrls ) c.Dispose(); You need to create a separate list of the references because Dispose also will remove the control from the collection, changing the index and messing up the foreach... A: I don't believe there is a way to do this all at once. You can just iterate through the child controls and call each of their dispose methods one at a time: foreach(var control in this.Controls) { control.Dispose(); } A: You didn't share if this were ASP.Net or Winforms. If the latter, you can do well enough by first calling SuspendLayout() on the panel. Then, when finished, call ResumeLayout().
unknown
d18507
test
ResultSet was used globally. ResultSet used in getGenreName method override the resultSet in the main searchCharacter method. Solution: set ResultSet variable individually in each method.
unknown
d18508
test
Yes, it's bad practice to put any personal information in the URL. A URL can be cached and viewed in so many ways. Even if you use SSL, URLs are still saved in your browser's history, so it just makes me cringe to pass non-public data in the URL. Usually it's not any more work to pass information in the body of a POST request, so that's what I would do. A: Not if you do it over https, as the URL path and querystring will be encrypted along with the body. It's not a problem for the URL to be stored in the browser history, as that is private to the user.
unknown
d18509
test
It turns out this is an IE bug (no real surprise there) - when the browser spawns a new tab in a new worker process the new process doesn't have access to the session cookie. A few other people have found this and stopping the spawning of new processes, though not a great solution, seems to fix the issue. Note that this issue also occurs on the Yahoo website, and all other sites that use session cookies. Really not sure which combination of events and situations trigger this (on our system is only hits non-admin users - we've looked through our GPO rules but haven't found anything obvious), but I reckon MS really need to fix it because if it starts to trigger more often it could completely cripple IE. Here's the link to temporarily bypass the issue, if you get hit by it, yourself. http://blogs.msdn.com/b/askie/archive/2009/03/09/opening-a-new-tab-may-launch-a-new-process-with-internet-explorer-8-0.aspx
unknown
d18510
test
You can check the interfaceOrientation in viewDidLoad. You can get the interfaceOrientation with self.userInterFaceOrientation. Maybe it would be better to check the interfaceOrientation in viewWillAppear. The difference is, that viewDidLoad will only called one and viewWillAppear every time you enter that view. A: Its so Simple you just click on your Project -> Summary -> Supported Interface Orientations. You can click the Interface Orientations as your requirements.
unknown
d18511
test
Try to use {0,number,#} instead of {0}. Edit: More info: https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html
unknown
d18512
test
You most likely need to add the email column to your fillable array: protected $fillable = ['user_id','instruction', 'description', 'fk_eleve', 'email']; Did you further create a proper migration for this, like does the table have the column email?
unknown
d18513
test
You've got 2 choices: * *Put the library jar on the classpath. *Assemble\Build the library jar with the regular jar. For option 1, you most likely need the jar located "near" the main jar on the file system; though, this is not necessarily a requirement. When you run the jar you then include the library jar on the classpath. For option 2, you use some type of tool like maven's assembly plugin or the fatjar plugin in Eclipse (sorry, I don't know what the analog is in NB). I hope this helps.
unknown
d18514
test
You are simply: writing as string, but reading back expecting a binary serialized object! You know, that is like: you put an egg in a box, and then you expect you can open that box and pour milk from it into a glass! That wont work. Here: bw.write(m.toString()); You write the map into that file as raw string. This means that your file now contains human readable strings! But then you do: Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject(); Which expects that the file contains serialized objects. Long story short, these are your options: * *keep writing these strings, but then you need to implement your own parser that reads such text files, and turns them back into objects within maps *instead of writing raw text strings, use a library such as gson or jackson and serialize your map as JSON string (which requires that all keys/values can be serialized as JSON) *instead of writing raw text or JSON, use the default Java serialization mechanism and serialize to binary content which requires that all keys/values implement the Serializable interface. See here for a nice tutorial how to do that in detail. My recommendation: go for option 2, or 3. 2 adds a dependency to a 3rd party library, but I think it is the more "common" practice these days. A: You need to serialize/deserialize the object, not just reading/writing its toString representation to file. See: https://javahungry.blogspot.com/2017/11/how-to-serialize-hashmap-in-java-with-example.html
unknown
d18515
test
Let's think of your problem this way: You have a set of balls in 64-dimension space each with radius d, representing the space around each of your input vectors. (Note, I'm assuming that by "distance" you mean Euclidean distance). Now, you want to find the smallest subset of balls that will cover each of your original points, meaning that you need each point to be inside at least one ball in the subset, with the additional restriction that the balls in the cover must have centers also distance d apart. Without this additional restriction, you have an instance of a hard but well-studied one called Geometric set cover, which in turn is a special case of the more famous Set cover problem. It seems intuitively that the additional restriction makes the problem harder, but I don't have a proof for that. The bad news is, the (geometric) set cover problem is NP-hard, meaning that you won't be able to quickly find the exact minimum if there may be many points in the original set. The good news is, there are good algorithms that find approximate solutions, which will give you a set which isn't necessarily as small as possible, but which is close to the smallest possible. Here is Python code for a simple greedy algorithm which will not always find a minimum-size cover, but will always return a valid one: def greedy(V, d): cover = set() uncovered = set(V) # invariant: all(distance(x,y) > d for x in cover for y in uncovered) while uncovered: x = uncovered.pop() cover.add(x) uncovered = {y for y in uncovered if distance(x,y) > d} Note, you could make this greedy solution a little better by replacing the uncovered.pop() call with a smarter choice, for example choosing a vector which would "cover" the most number of remaining points. A: First, we can derive an undirected graph where vertices are the vectors of v and edges are the pairs of points that are no farther apart than r. This doesn't require the distances to be a proper metric: it doesn't have to satisfy the triangle inequality, only that it is symmetrical (dist(a,b) == dist(b,a)) and that it is 0 iff two points are equal. After that step, we can forget about the distances altogether and focus entirely on partitioning the graph. As others have noted, that partition is a Vertex Cover problem. However, it has a twist: we require all the vertices in the cover to be disjoint (i.e.: no vectors in v1 can be within distance r of each other). To obtain the graph, we can use the efficient KDTree to compute just once the nearest-neighbor structure. In particular, we'll use kd.sparse_distance_matrix(kd, r) to obtain all pairs of points separated by r or less: from scipy.spatial import KDTree def get_graph(v, r): kd = KDTree(v) sm = kd.sparse_distance_matrix(kd, r) graph = {i: {i} for i, _ in sm.keys()} for i, j in sm.keys(): graph[i] |= {j} return graph (note: .sparse_distance_matrix() has a parameter p if we want other distances than Euclidean). The partitioning of the graph can be done in various ways. @DanR shows a greedy approach that is very fast, but often suboptimal in the size of v1 that it finds. The following shows instead a brute-force approach that is guaranteed to find a minimal solution if there is one. It is adequate for relatively small number of vectors and can provide a ground-truth for the optimal solution, when researching other heuristics. To speed up the combinatorial search, we first observe that often some points are not within distance r of any other (i.e. the graph found above doesn't represent all the points of v). We can leave those other points aside, since they will necessarily be part of v1 but don't interfere with the rest of the search (below, we call them "singletons"). Second, we cut unpromising "leads" (prefixes in the combinatorial expansion) if they are not fully disjoint. This speeds up considerably the full search, by cutting down entire swathes of search space. If no prefix is cut, the full search is time-exponential. What is the speed of this? It depends on the distribution of the v vectors and (strongly) on the distance r. In fact, it depends on the number of clusters found. To give an idea, with v 20 vectors picked in uniform in 2D, I observe roughly 30ms. For 40 vectors, typically around 100ms, but it can jump to over 2 seconds for certain values of r. We implement a variation of combinations that has a check function to cut down unpromising prefixes: from itertools import combinations def _okall(tup, *args, **kwargs): return True def combinations_all(iterable, n0=1, n1=None, check=None, *args, **kwargs): pool = tuple(iterable) n = len(pool) if n0 > n: return n1 = n if n1 is None else n1 check = _okall if check is None else check if n0 < 1: yield () n0 = 1 seed = list(combinations(range(n), n0-1)) for r in range(n0, n1+1): prev_seed = seed seed = [] for prefix in prev_seed: for j in range(max(prefix, default=-1)+1, n): indices = prefix + (j,) tup = tuple(pool[i] for i in indices) if check(tup, *args, **kwargs): seed.append(indices) yield tup Example: # list all combinations of [0,1,2,3] (of all sizes), excluding those starting # by (0,1) >>> list(combinations_all(range(4), check=lambda tup: tup[:2] != (0,1))) [(0,), (1,), (2,), (3,), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 2, 3), (1, 2, 3)] Now, we use that to find the minimal disjoint cover and return the indices of v1: def check(tup, graph): # refuses tup if any one is within reach of another # optimization: tup[:-1] has already passed this test, so just check the last one if len(tup) < 2: return True reach_of_last = graph[tup[-1]] prefix = set(tup[:-1]) return prefix.isdisjoint(reach_of_last) def brute_vq(v, r): n = v.shape[0] graph = get_graph(v, r) to_part = set(graph) singletons = set(range(n)).difference(to_part) if not to_part: return sorted(singletons) for tup in combinations_all(to_part, check=check, graph=graph): # here tup are indices that are far apart enough (guaranteed disjoint in reach) # check if they fully cover to_part cover = {j for i in tup for j in graph[i]} if cover == to_part: v1_idx = sorted(singletons.union(tup)) return v1_idx Examples: v = np.random.uniform(size=(20, 2)) r_s = [[0.2, 0.3], [0.4, 0.5]] fig, axes = plt.subplots(nrows=len(r_s), ncols=len(r_s[0]), figsize=(12,12), sharex=True, sharey=True) for r, ax in zip(np.ravel(r_s), np.ravel(axes)): idx = brute_vq(v, r) ax.set_aspect('equal') ax.scatter(v[:, 0], v[:, 1]) for i, p in enumerate(v): ax.text(*p, str(i)) for i in idx: circ = plt.Circle(v[i], radius=r, color='g', fill=False) ax.add_patch(circ) plt.show(); A: My 5c: Create a distance matrix (this is an O*O operation, obviously): A B C D | min,max A 0 3 2 1 | 1,3 B 3 0 5 4 | 3,5 C 2 5 0 6 | 2,6 D 1 4 6 0 | 1,6 # note: D-C violates the triangle inequality Distance matrix, relabelled: A D B C | min,max A 0 1 3 2 | 1,3 D 1 0 4 6 | 1,6 B 3 4 0 5 | 3,5 C 2 6 5 0 | 2,6 Now, per row (or column) take tha max() of the min() (or the min() of the max()...) With a distance of 3, the NW-part is fully connected and the rest is still partially connected (with d=4, B would enter the subset, too) A D | B C | min,max A 0 1 | 3 2 | 1,3 D 1 0 | 4 6 | 1,6 ----+ ---------- B 3 4 | 0 5 | 3,5 C 2 6 | 5 0 | 2,6
unknown
d18516
test
this is probably because you haven't enabled SSL bumping, i.e. your http_port directive is set to the default http_port 3128. I've written about both Squid's SSL setup and blocking websites * *configure squid with ICAP & SSL *block and allow websites with squid A: When the site is encrypted squid can validate only the Domain but not the entire URL path or keywords in the URL. To block https sites using urlpath_regex we need to setup Squid proxy using SSLbump. It is tricky and a long process , need to carefully configure the SSL bump settings by generating certificates.. but it is possible . I have succeeded in blocking the websites using urlpathregex over https sites... For more detailed explanation: Squid.conf file should have the below to achieve block websites using Keywords or Path ie..urlpath_regex http_port 3128 ssl-bump cert=/usr/local/squid/certificate.pem generate-host-certificates=on dynamic_cert_mem_cache_size=4MB acl BlockedKeywords url_regex -i "/etc/squid/.." acl BlockedURLpath urlpath_regex -i "/etc/squid/..." acl BlockedFIles urlpath_regex -i "/etc/squid3/...." http_access deny BlockedKeywords http_access deny BlockedFIles http_access deny BlockedURLpath
unknown
d18517
test
Dennis_E and Panagiotis Kanavos provided the answer. Thanks both of you. I just add it here, in case someone thinks he has the same problem. System.Collections.Generic.Dictionary.Item property (TKey) Describes it as follows: Property Value Type: TValue The value associated with the specified key. * *get If the specified key is not found, a get operation throws a KeyNotFoundException, *set a set operation creates a new element with the specified key.
unknown
d18518
test
Use slicing on any sequence to reverse it : print(list[::-1]) A: If your looking for a method from scratch without using any built-in function this one would do arr = [1,2,3,5,6,8] for i in range(len(arr)-1): arr.append(arr[-2-i]) del(arr[-3-i]) print(arr) # [8, 6, 5, 3, 2, 1] A: Do you want to reverse your list? a = ['car1', 'car2', 'car3'] a.reverse() print(a) ['car3', 'car2', 'car1'] A: you should use slicing. for example, a = ['1','2','3'] print(a[::-1]) will print ['3','2','1']. I hope this will work for you. Happy Learning! A: Your code is giving me the correct output except that len() is used to calculate the length of a list and not length(). x=int(input('how many cars do you have')) a=[] for i in range(x): car=(input('enter your car name')) a.append(car) print(a) y=[] for i in range(len(a)-1,-1,-1): y.append(a[i]) print(y) A: Simple Custom way (without using built-in functions) to reverse a list: def rev_list(mylist): max_index = len(mylist) - 1 return [ mylist[max_index - index] for index in range(len(mylist)) ] rev_list([1,2,3,4,5]) #Outputs: [5,4,3,2,1]
unknown
d18519
test
You need to escape the HTML and specifically in this example, & and the character used to quote the attribute value (either " or '): <button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <b>own</b> review"}'></button> or: <button type='button' data-data='{"type": "voting", "message": "Can&#39;t vote on <span style=&#39;text-decoration:underline&#39;>own</span> review"}'></button>
unknown
d18520
test
I would put all of your functions and variables into a single object for your library. var MyLibrary = { myFunc: function() { //do stuff }, myVar: "Foo" } There are a few different ways of defining 'classes' in JavaScript. Here is a nice page with 3 of them. A: You should take one variable name in the global namespace that there are low odds of being used, and put everything else underneath it (in its own namespace). For example, if I wanted to call my library AzureLib: AzureLib = { SortSomething: function(arr) { // do some sorting }, DoSomethingCool: function(item) { // do something cool } }; // usage (in another JavaScript file or in an HTML <script> tag): AzureLib.SortSomething(myArray); A: You could put all of your library's functions inside of a single object. That way, as long as that object's name doesn't conflict, you will be good. Something like: var yourLib = {}; yourLib.usefulFunction1 = function(){ .. }; yourLib.usefulFunction2 = function(){ .. }; A: Yes, you can create an object as a namespace. There are several ways to do this, syntax-wise, but the end result is approximately the same. Your object name should be the thing that no one else will have used. var MyLibrary = { myFunc: function() { /* stuff */ } }; Just remember, it's object literal syntax, so you use label : value to put things inside it, and not var label = value;. If you need to declare things first, use a wrapping function to enclose the environment and protect you from the global scope: var MyLibrary = (function() { var foo = 'bar'; return { myFunc: function() { /* stuff */ } }; })(); // execute this function right away to return your library object
unknown
d18521
test
Try this : let newDiv = document.createElement("DIV"); newDiv.setAttribute("id", "hide"); document.body.appendChild(newDiv); document.getElementById("hide").style.zIndex = "9"; document.getElementById("hide").style.width = "100%"; document.getElementById("hide").style.height = "100%"; document.getElementById("hide").style.backgroundImage = "url('https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/p5020056.jpg')"; document.getElementById("hide").style.backgroundRepeat = "no-repeat"; document.getElementById("hide").style.backgroundSize = "cover"; document.getElementById("hide").style.top = "0"; document.getElementById("hide").style.position = "fixed"; document.body.style.margin = "0"; document.body.style.padding = "0"; <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p> <p>This is a text under the image and will not show up because the image is covering the whole area of the body !</p> <p> I can even copy and paste this hundreds of times, but the image will still be on top of everything !</p>
unknown
d18522
test
Use read_excel df = pd.read_excel(Location2) A: It seems as if you'd need to set up the correct delimiter that separates the two fields. Try adding delimiter=";" to the parameters A: I think you need parameter sep in read_csv, because default separator is ,: df = pd.read_csv(Location2, sep=';') Sample: import pandas as pd from pandas.compat import StringIO temp=u"""time;Watt 0;00:00:00;50 1;01:00:00;45 2;02:00:00;40 3;00:03:00;35""" #after testing replace 'StringIO(temp)' to 'filename.csv' df = pd.read_csv(StringIO(temp), sep=";") print (df) time Watt 0 00:00:00 50 1 01:00:00 45 2 02:00:00 40 3 00:03:00 35 Then is possible convert time column to_timedelta: df['time'] = pd.to_timedelta(df['time']) print (df) time Watt 0 00:00:00 50 1 01:00:00 45 2 02:00:00 40 3 00:03:00 35 print (df.dtypes) time timedelta64[ns] Watt int64 dtype: object
unknown
d18523
test
The API call windows.remove() is specifically for closing a window. You will need the windowId, which is available as the id property within the windows.Window Object which is passed to the callback/resolve function for windows.create(). You do not need to call windows.remove() from the same script which opened the window. Any script with access to that API can close the window. A: You can remove a window created by an extension in Firefox from a "dismiss" button this way: GetEl('dismiss').addEventListener('click',function(e) { browser.windows.getCurrent().then(F2); }); function F2(info) { return browser.windows.remove(info.id); } // F2 (GetEl returns the element node for a given id string.)
unknown
d18524
test
The problem is that rendering (transformation to an OutgoingContent) of a request body happens during the execution of the HttpRequestPipeline, which takes place only once after making an initial request. The HTTP request retrying happens after in the HttpSendPipeline. Since you pass a String as a request body it needs to be transformed before the actual sending. To solve this problem, you can manually wrap your String into the TextContent instance and pass it to the setBody method: retry { retryOnServerErrors(maxRetries = Int.MAX_VALUE) exponentialDelay(maxDelayMs = 128.seconds.inWholeMilliseconds) modifyRequest { it.setBody(TextContent("With Different body ...", ContentType.Text.Plain)) } }
unknown
d18525
test
lFirst does not have any aggregate function (MAX, MIN, SUM, COUNT...) so there is no need to have a GROUP BY clause. Do not confuse between DISTINCT row operator and GROUP BY clause. Second, "BY EMP_PERSONAL.NEW_EMPNO DESC" Does not mean anything ! Is it a compement to GROUP BY or a part of ORDER BY ? To solve the first part, rewrite your query as : SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE FROM EMP_OFFICIAL,EMP_PERSONAL WHERE EMP_PERSONAL.STATUS='Active' AND EMP_OFFICIAL.WORK_ENT='Worker' AND EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO Also a JOIN must be write with the JOIN operator not as a cartesian product followed by a restriction. So rewrite your query as : SELECT FIRST_NAME, MIDDLE_NAME,LAST_NAME , EMP_MOBILE_NO,NEW_EMPNO , SECTION_NAME, EMP_TYPE, JOINING_DATE FROM EMP_OFFICIAL JOIN EMP_PERSONAL ON EMP_OFFICIAL.EMPNO=EMP_PERSONAL.EMPNO WHERE EMP_PERSONAL.STATUS='Active' AND EMP_OFFICIAL.WORK_ENT='Worker' This will be most optimized by the optimizer because it not spread time and operations to do the translation between false JOIN and real joins...
unknown
d18526
test
You need to actually create the table first, then run your code to populate the table. I would take a look at the data set you're working with to get an idea of the field names and data types and then run something like this: CREATE TABLE devices( id serial PRIMARY KEY, name TEXT NOT NULL, otherfield TEXT NOT NULL ); I'm not sure if you're trying to build a full automated cycle of creating a table and populating it, but you could just hop on over to postgres and run the create table code in the terminal or whatever database management tool you're using. After the table is created, you should be table to run the below code to verify it's been created correctly: SELECT * FROM devices It should come back with an empty table with all the columns you specified. If all that is good to go, run your code that populates the table. Should work fine.
unknown
d18527
test
This seems to be a case when we need to apply a logic on column values before a record is inserted. I would suggest creating a BEFORE INSERT trigger on this table, which will be automatically executed by MySql before each record is inserted. We can write the logic to determine the value of last column depending upon values supplied for the other columns. Have a look at this link for trigger example. If the requirement here is to do a one time bulk insert then, we can drop this trigger once insertion is complete. A: I would advise you to do it either with BEFORE INSERT trigger as Darshan Mehta recommends, or do your logic in the programming side, or with a stored procedure. Still it is doable at query time, so to answer your question specifically, try something like this: INSERT INTO medicos (num_colegiado, apellidos, especialidad, fecha_nac, universidad, sueldo, tipo_medico) SELECT 'A021', 'Apellidos :D', 'Loquesealogia', '1970-03-14', 'Valencia', '3500', IF('Loquesealogia' like '%a','Excellent',IF(DATE_ADD('1970-03-14', interval 40 YEAR)>NOW(),'Expert','indiferente'))
unknown
d18528
test
Under TFS2008, you do need to do it this way. Under 2010, there might be an "exclude", but I'm not able to check that at the moment. To keep from having a whole lot of maintenance, instead of listing each user individually, what we did was just pared down the list from "Valid Users" to the "Moderators" and "Contributors". We know that we can control those groups without affecting service permissions: <FIELD name="Assigned To" refname="System.AssignedTo" type="String" reportable="dimension"> <ALLOWEDVALUES expanditems="true"> <LISTITEM value="[Project]\Contributors"/> <LISTITEM value="[Project]\Moderators"/> </ALLOWEDVALUES> </FIELD>
unknown
d18529
test
One way to make code available across different script scopes is to use a WinJS namespace. For example, in page1.js, you would have: (function(){ function setText(){ var mytext = ""; WinJS.Namespace.define("page1", { text: mytext }); } })(); in page2.js, you'd put the text in that namespace: (function(){ page1.text = "page 2 text!"; })(); Back in page 1, you can retrieve that value later on: (function(){ function setText(){ var mytext = ""; WinJS.Namespace.define("page1", { text: mytext }); } function getText() { document.querySelector("#myTextField").value = page1.text; } })(); I'd suggest being a bit more formal about what you put in namespaces, but that's one way to do it.
unknown
d18530
test
you can try it via defining the body as structured representation and then transform it to JSON: $recipient['dst'] = "+000000"; $message['recipients'] = array($recipient); $message['text'] = "this is a test message"; $job['messages'] = array($message); $json = json_encode($job); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'url here', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $json, CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Idempotency-Key: HMCENRO202001140009T', 'Authorization: Basic Og==' ), )); $response = curl_exec($curl); curl_close($curl); echo $response;
unknown
d18531
test
As Evert said, the commit() was missing. An alternative to always specifying it in your code is using the autocommit feature. http://initd.org/psycopg/docs/connection.html#connection.autocommit For example like this: with psycopg2.connect("...") as dbconn: dbconn.autocommit=True A: You forgot to do connection.commit(). Any alteration in the database has to be followed by a commit on the connection. For example, the sqlite3 documentation states it clearly in the first example: # Save (commit) the changes. conn.commit() And the first example in the psycopg2 documentation does the same: # Make the changes to the database persistent >>> conn.commit()
unknown
d18532
test
You can pass the setOpen function as a prop to the SidebarButton component and then simply call the setOpen function to change the value. <SidebarButton setOpen={setOpen} /> If you would like to also call it from the menu component then you may need to move the declaration of open to a higher component that is common between Sidebar and Menu since props can only be passed downwards.
unknown
d18533
test
Make sure that MySQL.Data.dll actually got copied to the output folder. And that you are using right platform (x32 vs x64 bit) and right version of .NET (2,3,3.5 vs 4). If everyhing seems fine, enable Fusion Logging and take a look at this article: For FileNotFoundException: At the bottom of the log will be the paths that Fusion tried probing for this assembly. If this was a load by path (as in Assembly.LoadFrom()), there will be just one path, and your assembly will need to be there to be found. Otherwise, your assembly will need to be on one of the probing paths listed or in the GAC if it's to be found. You may also get this exception if an unmanaged dependency or internal module of the assembly failed to load. Try running depends.exe on the file to verify that unmanaged dependencies can be loaded. Note that if you re using ASP.NET, the PATH environment variable it's using may differ from the one the command line uses. If all of them could be loaded, try ildasm.exe on the file, double-click on "MANIFEST" and look for ".file" entries. Each of those files will need to be in the same directory as the manifest-containing file.
unknown
d18534
test
Note that Ajax request are usually sent through the client's browser, while usually a server would call file_get_contents() or a similar tool, to fetch your page. So in the case of a server, you can check the REMOTE_ADDR HTTP header (which contains the caller's IP) against a blacklist. In the case of an Ajax request, probably from a user agent you can't really say from which website the originated from. Though I am not sure, but the HTTP_REFERER header might contain exactly that, but again I have not checked it. UPDATE (Ajax Requests): After looking up a little bit, I turn out that browsers don't send referrer data with XHR requests, so you can only blacklist the IPs of the servers you don't want to be accessed from. A: If the server request it directly then you can use $_SERVER 'REMOTE_ADDR' and 'REMOTE_HOST'. If they use javascript then you will only get the clients ip. You can use strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') to disallow jquery requests. A: Isn't what you're looking for a $_SERVER['REMOTE_ADDR']? AJAX calls probably won't have a Referer header and that's why you are getting that error. A: The HTTP Referrer gets sent by a browser, probably not by file_get_contents()! You can use $_SERVER['REMOTE_ADDR']. This will give you the raw IP address from the TCP stack. In the case of a server-side API call, you get the server's IP (assuming the client does not use any proxies). However if the client is an AJAX request, you'll get the IP address of the user viewing that page. A: HTTP_REFERER is not going to be reliable. You might try $_SERVER['REMOTE_ADDR'] to inspect IP address of remote client. I would however think that you would have a better time whitelisting approved clients rather then blacklisting, as an attacker could easily proxy a request to get around an IP/host-based blacklist. There are a number of approaches for whiltelisting: * *whitelist known IP's *HTTP Authentication *Your own custom API keys *Third party authentication (i.e. OAuth) and so forth.
unknown
d18535
test
If I see... you can use ScrollTo method. yourLongListMultiSelector.ScrollTo(yourNewInsertedItem); A: To get you going, I tried something but could not get it a 100% Here is a working basic page template which in fact does what you require with messages <phone:PhoneApplicationPage > <ScrollViewer x:Name="Scroll" VerticalAlignment="Bottom" Height="500" ScrollViewer.VerticalScrollBarVisibility="Disabled"> <StackPanel VerticalAlignment="Bottom" > <toolkit:LongListMultiSelector x:Name="DataList" ItemsSource="{Binding}" ScrollViewer.VerticalScrollBarVisibility="Disabled" VerticalAlignment="Bottom" VirtualizingStackPanel.VirtualizationMode="Recycling"></toolkit:LongListMultiSelector> </StackPanel> </ScrollViewer> </phone:PhoneApplicationPage> This keeps new messages down, pulling the list up. The scrolling is now disabled. You can easily enclose ScrollViewer in grid and add the button above (like in your picture) Now the code that would go into the button click Scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; Scroll.ScrollToVerticalOffset(DataList.ActualHeight); Unfortunately this scrolls the list up BUT if you trigger the second line of code again for example via button click, ScrollToVerticalOffset works. So for some reason ScrollToVerticalOffset is not working right away-after changing VerticalScrollBarVisibility. If you can get this last part figured out, I believe your question would be solved A: The thing that prevents your desired effect is the ListHeader control is at top when you insert item at top. You can do some tricky code to bypass it: var temp = MyLongListMultiSelector.ListHeader; //also works with ListHeaderTemplate MyLongListMultiSelector.ListHeader = null; MyObservableCollection.Insert(0, item); MyLongListMultiSelector.ListHeader = temp; Or you can make a fake header item and handle the add top event like: MyLongListMultiSelector.Remove(fakeHeaderItem); MyObservableCollection.Insert(0, item); MyObservableCollection.Insert(0, fakeHeaderItem); A: you can easily achieve this via adding new items to top of the observable collection obsData.Insert(0,newItem) Reference
unknown
d18536
test
Use beautifulsoup (http://www.crummy.com/software/BeautifulSoup/bs4/doc/) to extract the table then convert it. Try Convert a HTML Table to JSON; it shows how to use beautifulsoup to grab the table and convert it into JSON.
unknown
d18537
test
all_objects only shows you objects you have permissions on, not all objects in the database. You'd need to query dba_objects to see everything, if you have permissions to do that. public_dependency appears to include object IDs for objects you don't have permissions on. The objecct IDs on their own don't tell you much, so it isn't revealing anything about objects you can't see (other than that there are some objects you can't see). So it isn't odd that there is an apparent discrepancy between what the two views reference. Querying all_dependencies might give you a more comsistent picture.
unknown
d18538
test
This only work in resize browser because this code resizeEditiorImg you need run this command resizeEditiorImg in your load page. example <body onload="resizeEditiorImg()">
unknown
d18539
test
If you do this: Object **c = new Object*[n]; for (size_t i=0; i!=n; ++i) { c[i] = new Object[m]; } then it will typically take more memory than doing this: Object *c = new Object[n*m]; for just the reasons you stated. Every memory allocation has a certain amount of overhead. In addition to needing to keep the number of elements, there is overhead for the memory allocator itself. It also takes more memory for all the extra pointers for each row. Note that it is possible to have a situation where breaking it up would use less memory. If your heap was fragmented, then finding one large chunk of memory may require allocating more memory from the operating system, whereas if your array was broken into smaller pieces, those pieces may be able to fit in the holes of your fragmented heap.
unknown
d18540
test
stroke() sets the color used to draw lines and borders. fill() sets the color used to fill shapes. rect() draws a rectangle. The stroke and the fill color has to be set before the rectangle is drawn: fill(h,s,l); stroke(0,0,100); rect(0, i * boxh, boxw, boxh); function setup() { colorMode(HSB,360,100,100); createCanvas(400, 400); var boxh = height / 10; var boxw = width; for(var i = 0; i < 10; i++) { var h = lerp(64, 22, i / 9); var s = lerp(86, 90, i / 9); var l = lerp(96, 56, i / 9); fill(h,s,l); stroke(0,0,100); rect(0, i * boxh, boxw, boxh); } } <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>
unknown
d18541
test
I try it at Win8 and it is working. At win 8.1 and win7 it is not working. I dont known why, but if I after that copy "R Folder" from program files (from Win8) to Win 8.1. It is working.
unknown
d18542
test
Something like this: $('#ShowRow').find('.value:first a:first').html() A: You can do: $('#ShowRow').find('.value:first a:first').html()
unknown
d18543
test
EDIT with what OP actually wanted. Here is the image that takes up the full width and height without stretching. You can use object-fit: cover Information on object-fit: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit img { display: none; width: 100%; height: 100%; object-fit: cover; } .effect:hover .text { display: none; } .effect:hover img { display: block; } h1.text { font-size: 14px; } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="row"> <div class="col-sm-3 alternate_2 effect"> <h1 class="display-6 text">Studio Griot</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 effect"> <h1 class="display-6 text">Web Development</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 alternate_2 effect"> <h1 class="display-6 text">Data Visualisation</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 effect"> <h1 class="display-6 text">Incrediminds</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> </div> Add width: 100% to the img. That will keep it 100% width of its parent. I changed your bootstrap markup to col-sm so you could see it when you run the snippet. Added information for future visitors: An img will always display as large as its own default/native size, unless you specify the width: 100% and make sure it is display: block, since img are inline by default. img { display: none; width: 100%; } .effect:hover .text { display: none; } .effect:hover img { display: block; } h1.text { font-size: 14px; } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="row"> <div class="col-sm-3 alternate_2 effect"> <h1 class="display-6 text">Studio Griot</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 effect"> <h1 class="display-6 text">Web Development</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 alternate_2 effect"> <h1 class="display-6 text">Data Visualisation</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> <div class="col-sm-3 effect"> <h1 class="display-6 text">Incrediminds</h1> <p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pretium dui ultrices, ornare mauris in, ultricies sapien. Proin dictum urna quis mauris pharetra, sit amet aliquam diam suscipit. In congue.</p> <a href="#"> <img src="http://via.placeholder.com/500/500" /> </a> </div> </div>
unknown
d18544
test
Question: have you verified that the UIImage returned from initWithContentsOfFile is not nil? You might need the full path instead of just the filename As far as the wackiness with the UIViews not getting removed goes, everything you've posted looks fine as far as I can see. The only thing I can think of is that maybe you don't have retain specified as an attribute for your viewPane property...
unknown
d18545
test
This took me quite a long time to answer since I had to create my own format currency function. A live demo can be found here: http://jsfiddle.net/dm6LL/ The basic updating each second is very easy and will be done through JavaScript's setInterval command. setInterval(function(){ current += .158; update(); },1000); The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page. function update() { amount.innerText = formatMoney(current); } Amount and current that you see in the update() function are predefined: var amount = document.getElementById('amount'); var current = 138276343; Then all that's left is my formatMoney() function which takes a number and converts it into a currency string. function formatMoney(amount) { var dollars = Math.floor(amount).toString().split(''); var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1]; if(typeof cents == 'undefined'){ cents = '00'; }else if(cents.length == 1){ cents = cents + '0'; } var str = ''; for(i=dollars.length-1; i>=0; i--){ str += dollars.splice(0,1); if(i%3 == 0 && i != 0) str += ','; } return '$' + str + '.' + cents; }​
unknown
d18546
test
* *Run "divshot login" from your command line on you local machine and follow the instructions to login. *Run "divshot auth:token" to get your auth token from the command line. *When running commands that interact with the Divshot API, use the flag "--token " to give it authorization (on the vagrant box) A: Another solution: * *Run divshot login on your local computer *Inspect $HOME/.divshot/config/user.json, check it has a key token *Copy that file to the corresponding path on the other computer
unknown
d18547
test
You don't need to store the playerID to check identities. Local playerID can be accessed always with: [GKLocalPlayer localPlayer].playerID As to how to use playerID now that it's deprecated, that property was only moved from GKTurnBasedParticipant to GKPlayer. That doesn't affect the code that I pasted before, but it does affect the way you access to match.participants. So, for any given player, the way to access it in iOS8 would be: GKTurnBasedParticipant *p1 = (GKTurnBasedParticipant *)self.match.participants[index]; p1.player.playerID As you can see, you only have to add a .player to your current code.
unknown
d18548
test
Managed to retrieve the value of the checkbox with this structure for the radio-buttons: <%= q.radio_button answer_option.question_id, answer_option.answer %> <%= q.label "#{answer_option.question_id}_#{answer_option.answer.parameterize.underscore}", answer_option.answer %> And the controller: user_choices = params[:contest][:questions] user_contest.questions.each do |question| question[:user_answer] = "#{user_choices[:'#{question.id}']}" question.save end
unknown
d18549
test
Use DataFrame.assign: df = df.assign(result_multiplied = df['result']*2) Or if column result is processing in code before is necessary lambda function for processing counted values in column result: df = df.assign(result_multiplied = lambda x: x['result']*2) Sample for see difference column result_multiplied is count by multiple original df['result'], for result_multiplied1 is used multiplied column after mul(2): df = df.mul(2).assign(result_multiplied = df['result']*2, result_multiplied1 = lambda x: x['result']*2) print (df) index result result_multiplied result_multiplied1 0 AA 2 2 4 1 BB 4 4 8 2 CC 6 6 12
unknown
d18550
test
function trim_array($Array) { foreach ($Array as $value) { if(trim($value) === '') { $index = array_search($value, $Array); unset($Array[$index]); } } return $Array; } A: $out_array = array_filter($input_array, function($item) { return !empty($item['key_of_array_to_check_whether_it_is_empty']); } ); A: Just want to contribute an alternative to loops...also addressing gaps in keys... In my case, I wanted to keep sequential array keys when the operation was complete (not just odd numbers, which is what I was staring at. Setting up code to look just for odd keys seemed fragile to me and not future-friendly.) I was looking for something more like this: http://gotofritz.net/blog/howto/removing-empty-array-elements-php/ The combination of array_filter and array_slice does the trick. $example = array_filter($example); $example = array_slice($example,0); No idea about efficiencies or benchmarks but it works. A: I use the following script to remove empty elements from an array for ($i=0; $i<$count($Array); $i++) { if (empty($Array[$i])) unset($Array[$i]); } A: $my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" "); foreach ($my as $key => $value) { if (is_null($value)) unset($my[$key]); } foreach ($my as $key => $value) { echo $key . ':' . $value . '<br>'; } output 1:5 2:6 A: $myarray = array_filter($myarray, 'strlen'); //removes null values but leaves "0" $myarray = array_filter($myarray); //removes all null values A: foreach($arr as $key => $val){ if (empty($val)) unset($arr[$key]; } A: Just one line : Update (thanks to @suther): $array_without_empty_values = array_filter($array); A: You can just do array_filter($array) array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too. The other option is doing array_diff($array, array('')) which will remove elements with values NULL, '' and FALSE. Hope this helps :) UPDATE Here is an example. $a = array(0, '0', NULL, FALSE, '', array()); var_dump(array_filter($a)); // array() var_dump(array_diff($a, array(0))) // 0 / '0' // array(NULL, FALSE, '', array()); var_dump(array_diff($a, array(NULL))) // NULL / FALSE / '' // array(0, '0', array()) To sum up: * *0 or '0' will remove 0 and '0' *NULL, FALSE or '' will remove NULL, FALSE and '' A: foreach($linksArray as $key => $link) { if($link === '') { unset($linksArray[$key]); } } print_r($linksArray); A: In short: This is my suggested code: $myarray = array_values(array_filter(array_map('trim', $myarray), 'strlen')); Explanation: I thinks use array_filter is good, but not enough, because values be like space and \n,... keep in the array and this is usually bad. So I suggest you use mixture ‍‍array_filter and array_map. array_map is for trimming, array_filter is for remove empty values, strlen is for keep 0 value, and array_values is for re indexing if you needed. Samples: $myarray = array("\r", "\n", "\r\n", "", " ", "0", "a"); // "\r", "\n", "\r\n", " ", "a" $new1 = array_filter($myarray); // "a" $new2 = array_filter(array_map('trim', $myarray)); // "0", "a" $new3 = array_filter(array_map('trim', $myarray), 'strlen'); // "0", "a" (reindex) $new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen')); var_dump($new1, $new2, $new3, $new4); Results: array(5) { [0]=> " string(1) " [1]=> string(1) " " [2]=> string(2) " " [4]=> string(1) " " [6]=> string(1) "a" } array(1) { [6]=> string(1) "a" } array(2) { [5]=> string(1) "0" [6]=> string(1) "a" } array(2) { [0]=> string(1) "0" [1]=> string(1) "a" } Online Test: http://sandbox.onlinephpfunctions.com/code/e02f5d8795938be9f0fa6f4c17245a9bf8777404 A: Another one liner to remove empty ("" empty string) elements from your array. $array = array_filter($array, function($a) {return $a !== "";}); Note: This code deliberately keeps null, 0 and false elements. Or maybe you want to trim your array elements first: $array = array_filter($array, function($a) { return trim($a) !== ""; }); Note: This code also removes null and false elements. A: use array_filter function to remove empty values: $linksArray = array_filter($linksArray); print_r($linksArray); A: Remove empty array elements function removeEmptyElements(&$element) { if (is_array($element)) { if ($key = key($element)) { $element[$key] = array_filter($element); } if (count($element) != count($element, COUNT_RECURSIVE)) { $element = array_filter(current($element), __FUNCTION__); } return $element; } else { return empty($element) ? false : $element; } } $data = array( 'horarios' => array(), 'grupos' => array( '1A' => array( 'Juan' => array( 'calificaciones' => array( 'Matematicas' => 8, 'Español' => 5, 'Ingles' => 9, ), 'asistencias' => array( 'enero' => 20, 'febrero' => 10, 'marzo' => '', ) ), 'Damian' => array( 'calificaciones' => array( 'Matematicas' => 10, 'Español' => '', 'Ingles' => 9, ), 'asistencias' => array( 'enero' => 20, 'febrero' => '', 'marzo' => 5, ) ), ), '1B' => array( 'Mariana' => array( 'calificaciones' => array( 'Matematicas' => null, 'Español' => 7, 'Ingles' => 9, ), 'asistencias' => array( 'enero' => null, 'febrero' => 5, 'marzo' => 5, ) ), ), ) ); $data = array_filter($data, 'removeEmptyElements'); var_dump($data); ¡it works! A: As per your method, you can just catch those elements in an another array and use that one like follows, foreach($linksArray as $link){ if(!empty($link)){ $new_arr[] = $link } } print_r($new_arr); A: I think array_walk is much more suitable here $linksArray = array('name', ' ', ' 342', '0', 0.0, null, '', false); array_walk($linksArray, function(&$v, $k) use (&$linksArray){ $v = trim($v); if ($v == '') unset($linksArray[$k]); }); print_r($linksArray); Output: Array ( [0] => name [2] => 342 [3] => 0 [4] => 0 ) * *We made sure that empty values are removed even if the user adds more than one space *We also trimmed empty spaces from the valid values *Finally, only (null), (Boolean False) and ('') will be considered empty strings As for False it's ok to remove it, because AFAIK the user can't submit boolean values. A: As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you: print_r(array_filter($linksArray)); Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0', you will need a custom callback: // PHP 7.4 and later print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== '')); // PHP 5.3 and later print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; })); // PHP < 5.3 print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";'))); Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray)); A: You can use array_filter to remove empty elements: $emptyRemoved = array_filter($linksArray); If you have (int) 0 in your array, you may use the following: $emptyRemoved = remove_empty($linksArray); function remove_empty($array) { return array_filter($array, '_remove_empty_internal'); } function _remove_empty_internal($value) { return !empty($value) || $value === 0; } EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using array_filter $trimmedArray = array_map('trim', $linksArray); A: The most popular answer on this topic is absolutely INCORRECT. Consider the following PHP script: <?php $arr = array('1', '', '2', '3', '0'); // Incorrect: print_r(array_filter($arr)); // Correct: print_r(array_filter($arr, 'strlen')); Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug. Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean. So, the absolute, definitive, correct answer is: $arr = array_filter($arr, 'strlen'); A: If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function: array_values(array_filter($array)); Also see: PHP reindex array? A: The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation: What does empty mean? First of all, we must agree on what empty means. Do you mean to filter out: * *the empty strings only ("")? *the strictly false values? ($element === false) *the falsey values? (i.e. 0, 0.0, "", "0", NULL, array()...) *the equivalent of PHP's empty() function? How do you filter out the values To filter out empty strings only: $filtered = array_diff($originalArray, array("")); To only filter out strictly false values, you must use a callback function: $filtered = array_diff($originalArray, 'myCallback'); function myCallback($var) { return $var === false; } The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every null and false, etc, leaving only 0): $filtered = array_filter($originalArray, 'myCallback'); function myCallback($var) { return ($var === 0 || $var === '0'); } Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default: $filtered = array_filter($originalArray); A: $a = array(1, '', '', '', 2, '', 3, 4); $b = array_values(array_filter($a)); print_r($b) A: For multidimensional array $data = array_map('array_filter', $data); $data = array_filter($data); A: $linksArray = array_filter($linksArray); "If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php A: I had to do this in order to keep an array value of (string) 0 $url = array_filter($data, function ($value) { return (!empty($value) || $value === 0 || $value==='0'); }); A: With these types of things, it's much better to be explicit about what you want and do not want. It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer. Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed. In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values. Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop. <?php $xs = [0, 1, 2, 3, "0", "", false, null]; $xs = array_filter($xs, function($x) { if ($x === null) { return false; } if ($x === false) { return false; } if ($x === "") { return false; } if ($x === "0") { return false; } return true; }); $xs = array_values($xs); // reindex array echo "<pre>"; var_export($xs); Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution. See this example and the inline comments for the output. <?php /** * @param string $valueToFilter * * @return \Closure A function that expects a 1d array and returns an array * filtered of values matching $valueToFilter. */ function filterValue($valueToFilter) { return function($xs) use ($valueToFilter) { return array_filter($xs, function($x) use ($valueToFilter) { return $x !== $valueToFilter; }); }; } // partially applied functions that each expect a 1d array of values $filterNull = filterValue(null); $filterFalse = filterValue(false); $filterZeroString = filterValue("0"); $filterEmptyString = filterValue(""); $xs = [0, 1, 2, 3, null, false, "0", ""]; $xs = $filterNull($xs); //=> [0, 1, 2, 3, false, "0", ""] $xs = $filterFalse($xs); //=> [0, 1, 2, 3, "0", ""] $xs = $filterZeroString($xs); //=> [0, 1, 2, 3, ""] $xs = $filterEmptyString($xs); //=> [0, 1, 2, 3] echo "<pre>"; var_export($xs); //=> [0, 1, 2, 3] Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you. <?php /** * Supply between 1..n functions each with an arity of 1 (that is, accepts * one and only one argument). Versions prior to php 5.6 do not have the * variadic operator `...` and as such require the use of `func_get_args()` to * obtain the comma-delimited list of expressions provided via the argument * list on function call. * * Example - Call the function `pipe()` like: * * pipe ($addOne, $multiplyByTwo); * * @return closure */ function pipe() { $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo] return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1 return array_reduce( // chain the supplied `$arg` value through each function in the list of functions $functions, // an array of functions to reduce over the supplied `$arg` value function ($accumulator, $currFn) { // the reducer (a reducing function) return $currFn($accumulator); }, $initialAccumulator ); }; } /** * @param string $valueToFilter * * @return \Closure A function that expects a 1d array and returns an array * filtered of values matching $valueToFilter. */ function filterValue($valueToFilter) { return function($xs) use ($valueToFilter) { return array_filter($xs, function($x) use ($valueToFilter) { return $x !== $valueToFilter; }); }; } $filterer = pipe( filterValue(null), filterValue(false), filterValue("0"), filterValue("") ); $xs = [0, 1, 2, 3, null, false, "0", ""]; $xs = $filterer($xs); echo "<pre>"; var_export($xs); //=> [0, 1, 2, 3] A: try this ** **Example $or = array( 'PersonalInformation.first_name' => $this->request->data['User']['first_name'], 'PersonalInformation.last_name' => $this->request->data['User']['last_name'], 'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'], 'PersonalInformation.dob' => $this->request->data['User']['dob'], 'User.email' => $this->request->data['User']['email'], ); $or = array_filter($or); $condition = array( 'User.role' => array('U', 'P'), 'User.user_status' => array('active', 'lead', 'inactive'), 'OR' => $or );
unknown
d18551
test
The reason you are getting an exception is that under the hood the SocketAsyncEventArgs only uses the buffers present in the list at the time of setting the BufferList property. Basically you are trying to send en empty buffer with the code : e.BufferList = new List<ArraySegment<byte>>(); e.BufferList.Add(new ArraySegment<byte>(lTxBytes)); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); e.BufferList.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); Instead try to do : var list = new List<ArraySegment<byte>>(); list.Add(new ArraySegment<byte>(lTxBytes)); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lTx.Identity))); list.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(lResponse))); e.BufferList = list; This behavior is not well documented at all and can only be understood by looking at the BufferList setter code in detail. Behind the scenes the SocketAsyncEventArgs has a WSABuffer array field(for interop with native code) where it copies and pins the byte arrays references when you set the BufferList. Since it is this WSABuffer[] that is sent to native code, that explains why your code throws an exception.
unknown
d18552
test
One thing you can try is to use the size-report of your flex compilation : flex compiler options This way you will have an idea of which classes are really used in your libraries and therefore wich ones aren't because the flex compiler only link to classes you really need in your compiled swf. This not ideal but it can avoid a lot of manual process pain. A: Add this param to your compiler: -link-report output.xml this information will help you. A: I'm not sure if it would work for flash-builder, but for Java there is the UCDetector.
unknown
d18553
test
Finally I got the solution, it was because the new S2 version. The shared files was renamed from parameters.ini to parameters.yml set :shared_files, ["app/config/parameters.yml"]
unknown
d18554
test
If it requires Authentication then the only way you'll be able to "get" it using GET is to authenticate the user. Otherwise you'll see an error code in the response. Recent changes were made in the applications permission model for Direct Messages. Lean More Here Your going to need some code besides a URL to send, receive and validate authentication tokens.
unknown
d18555
test
When you run $ sudo pip install... system pip will be used. So to install flask in current environment just run $ pip install ... or as: $ /path/to/venv/bin/pip install ... Or make your venv able to load global system packages by parameter --system-site-packages, while configure virtual environment. A: If you are having the same trouble even if you have your virtualenv running, just make sure you didn't accidentally delete the files and attempt to execute pip in that folder you created for your venv... Like I did. :D
unknown
d18556
test
You can use Flux.collectList() to get all results in a list: @Test public void reactiveGetTest() { long start = System.currentTimeMillis(); List<Mono<String>> monos = IntStream.range(0, 500) .boxed() .map(i -> reactiveGet("https://www.google.com/")) .collect(Collectors.toList()); List<String> results = Flux.mergeSequential(monos).collectList().block(); System.out.println("result: " + results.size()); System.out.println("total time: " + (System.currentTimeMillis() - start)); }
unknown
d18557
test
You are not really providing too much details of the issue. I can give some generic guidelines: * *Ensure that there is network connectivity. If you are testing Postman and Mule from the same computer it is probably not an issue. *Ensure host, port and certificates (if using TLS) are the same. Pointing an HTTPS request to port 80 could cause a timeout sometimes. *Enable HTTP Wire logging in Mule and compare with Postman code as HTTP to identify any significant difference between the requests. For example: headers, URI, body should be the same, except probably for a few headers. Depends on the API. This is usually the main cause for differences between Postman and Mule, when the request are different.
unknown
d18558
test
It seems like you want a tree whose branching factor is determined on the type level, and can be any natural number. This is fairly straightforward with GADTs: data Nat = Z | S Nat data Vec (n :: Nat) a where Nil :: Vec 'Z a (:>) :: a -> Vec n a -> Vec ('S n) a infixr 5 :> data Tree k a = Leaf | Node a (Vec k (Tree k a)) Vec is the standard way to encode a homogenous length-indexed vector with GADTs (found e.g. here). A node in a tree is then an element of type a and a vector of length k, where each element of the vector is a subtree. Binary trees are simply type BinaryTree = Tree ('S ('S 'Z)) and constructing is simply tree = Node 1 (Node 2 (Leaf :> Leaf :> Nil) :> Leaf :> Nil) the inferred type will be Num a => Tree ('S ('S 'Z)) a. But if you really need 10 nodes, writing out ten 'S is still too tedious, so you may want to use type literals: import qualified GHC.TypeLits as TL ... type family N (n :: TL.Nat) :: Nat where N 0 = 'Z N n = 'S (N (n TL.- 1)) type Tree10 = Tree (N 10) This not only gives you trees with any branching factor you like, but it allows you to write functions which are polymorphic in the branching factor, and even more, GHC give you all the following for free: -- With StandaloneDeriving, DeriveFunctor, DeriveFoldable, DeriveTraversable deriving instance Functor (Vec k) deriving instance Foldable (Vec k) deriving instance Traversable (Vec k) deriving instance Functor (Tree k) deriving instance Foldable (Tree k) deriving instance Traversable (Tree k)
unknown
d18559
test
Getting BitLocker information from WMI requires elevated permissions. Your code has to be running as an admin and you have to ask for elevated privileges. So, I don't use ManagementObjectSearcher to obtain BitLocker info. Instead, I do something similar to the following (modified to your scenario - but not tested as shown): ManagementObject GetBitLockerManager( string driveLetter ) { var path = new ManagementPath( ); path.Server = string.Empty; path.NamespacePath = @"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption"; path.ClassName = "Win32_EncryptableVolume"; var options = new ConnectionOptions( ); options.Impersonation = ImpersonationLevel.Impersonate; options.EnablePrivileges = true; options.Authentication = AuthenticationLevel.PacketPrivacy; var scope = new ManagementScope( path, options ); var mgmt = new ManagementClass( scope, path, new ObjectGetOptions( ) ); mgmt.Get( ); return mgmt .GetInstances( ) .Cast<ManagementObject>( ) .FirstOrDefault ( vol => string.Compare ( vol[ "DriveLetter" ] as string, driveLetter, true ) == 0 ); } A: OK so I figured it out, thank you for all of the assistance provided. Code is below. ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume"); foreach (ManagementObject QueryObj in Encryption.Get()) { string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString(); if (EncryptionStatus == "0") { EncryptionDialog.Text = "Unencrypted"; } else if (EncryptionStatus == "1") { EncryptionDialog.Text = "Encrypted - SysPrep will not complete"; } else if (EncryptionStatus == "2") { EncryptionDialog.Text = "Cannot Determine Encryption"; } }
unknown
d18560
test
A simple formula should do the job : assuming the data are found in A:C =IF(ISBLANK(A2),"",IF(ISBLANK(C2),B2, SUMIFS(B:B,A:A,A2,C:C,1))) The outer IF display nothing when column A is empty. The inner IF displaycolumn B when column C is empty. The SUMIFS will add upcolumn B where column A is the same(as current row) and when column C is 1.
unknown
d18561
test
Implement this in your appdelegate and show an alert : func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { }
unknown
d18562
test
Container( child: CachedNetworkImage( imageUrl: _imageUrl, imageBuilder: (context, imageProvider)=>PhotoView( minScale: 1.0, imageProvider: imageProvider, ), ), ), A: For the future searchers, there is an another solution which seems perfectly fits the desired behaviour. https://stackoverflow.com/a/58200356/5829191 A: This work for me. Since I have a Container with the same borderRadius as the Catched Image. Without the BoxDecoration it failed med too! Container( decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),),child:CachedNetworkImage(imageUrl: ("UrlToImage"),imageBuilder: (context, imageProvider) => Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),image: DecorationImage(image: imageProvider, fit: BoxFit.cover, )),),placeholder: (context, url) => CircularProgressIndicator(),errorWidget: (context, url, error) => Image.asset("PathToImage") ),
unknown
d18563
test
if(population[i]> max); max = population[i]; should be if(population[i]> max) max = population[i]; Try that and see. OK, I think I see what's up now. You are trying to print populations for the various years. Each column is essentially 6 characters wide ("\*\*" set in a setw(3), plus a " "). Trouble is, you only print that column if it's going to get the "**"; otherwise you print nothing. So all the columns with "\*\*" are jammed to the left. Solution is to always print the column, for each row, whether it gets a "**" or not: for (int year_counter = 0; year_counter <= count - 1; year_counter++) if (num <= population[year_counter]) cout << setw(3) << "**" << " "; else //NEW cout << setw(3) << " " << " "; //NEW
unknown
d18564
test
Mule is failing probably because an empty directory (lib/shared/default) is missing. Hg doesn't version empty directories. A: There is something weird that Mercurial (Debian's 1.8.3-1+b1 in Unstable) does: whenever I run hg clean, even if there is nothing to clean (hg status output is null), trying to run ./mule fails with the stated error. Solution: stay away from that clean command for now.
unknown
d18565
test
There are a few options, but the most popular is using SpringFox: https://github.com/springfox/springfox It's able to generate both Swagger and RAML compatible documentations.
unknown
d18566
test
You need some other data store to keep it across postback requests, so if it's global to the application, you can use application cache, but if it's specific to the user, then session is fine. If there isn't that much data involved and it's not that intensive as a read, you may want to consider whether there is a benefit to caching a chunk of data vs just re-querying it when needed. To get more advanced and present another alternative that is more involved, a CQRS implementation is a possibility (also see this); the idea there is one data container is for transaction data, and another for reads (whether that is a separate database or table, or even a document database as some possibilities).
unknown
d18567
test
Are you using apache server? Check if you have mod_rewrite enabled. A: Just in case, if you have created any folder on you live website for your code, than try using below line RewriteBase /yourFolderName/ keep above code just below RewriteEngine On A: This one worked for me: Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / ## don't touch /forum URIs RewriteRule ^forums/ - [L,NC] ## hide .php extension snippet # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L] # To internally forward /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*?)/?$ $1.php [L]
unknown
d18568
test
For that you will have to go into the checkboxes template and modify that. Specifically you should go in and remove the ContentPresenter which is what displays the text. Since you have no text, it is not a problem. The end result will look something like this. Just add that style to your checkbox. The default templates ContentPresenter is housed under the Bullet. Because of this, clicking on that content presenter (even if empty, I think it has a default size) will activate the controls click logic. <Style x:Key="CheckBoxStyle1" TargetType="{x:Type CheckBox}"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> <Setter Property="Background" Value="{StaticResource CheckRadioFillNormal}"/> <Setter Property="BorderBrush" Value="{StaticResource CheckRadioStrokeNormal}"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="FocusVisualStyle" Value="{StaticResource EmptyCheckBoxFocusVisual}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type CheckBox}"> <BulletDecorator Background="Transparent" SnapsToDevicePixels="true"> <BulletDecorator.Bullet> <Microsoft_Windows_Themes:BulletChrome BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" IsChecked="{TemplateBinding IsChecked}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/> </BulletDecorator.Bullet> </BulletDecorator> <ControlTemplate.Triggers> <Trigger Property="HasContent" Value="true"> <Setter Property="FocusVisualStyle" Value="{StaticResource CheckRadioFocusVisual}"/> <Setter Property="Padding" Value="2,0,0,0"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> A: It sounds like your CheckBox is stretching to the whole width of the grid cell (with all of that width clickable), and you don't want it to stretch. Set the CheckBox's HorizontalAlignment property to Left (or Center, or Right). Then it will be exactly the width it needs to be for the checkbox, rather than stretching to the entire width provided by its parent.
unknown
d18569
test
As a means of testing if supplied values are within permitted bounds you could try: $valid_username=in_array( strlen( $username ), range(2,16) ); $valid_password=$password===$repeatPassword && in_array( strlen( $password ), range(8,32) ); if( $valid_username && $valid_password ){/* all good */} example: if( $submit ) { if( $username && $password && $repeatPassword && $email ) { // hash the Passwords $password = md5( trim( $password ) ); $repeatPassword = md5( trim( $repeatPassword ) ); $unrange=range(3,16); $pwdrange=range(8,32); $valid = true; $valid_username = in_array( strlen( $username ), $unrange ); $valid_password = in_array( strlen( $password ), $pwdrange ); $password_match = $password===$repeatPassword; if( !$valid_password ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Password</b> should be between ".min( $pwdrange )." and ".max( $pwdrange )." characters! </h3> </span>"; } if( !$valid_username ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Username</b> must be between ".min( $unrange )." and ".max( $unrange )." characters! </h3> </span>"; } if( !$password_match ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-danger'> Your <b>Passwords</b> must match! </h3> </span>"; } if( $valid ) { echo 'Registration Completed!'; /* add to db? */ } } else echo "<h3 class='text-center'> <span class='alert alert-warning'> Please fill out <b>All</b> fields!</h3> </span>"; } A: You probably don't need to check the length of both $password and $repeatPassword since you will also be checking to see if they match each other. if (strlen($password < 8) { // error } elseif ($password != $repeatPassword) { // error } else { // ALL IS GOOD ! } A: I had actually solved my problem, I decided to take out the or to the password and it had solved the problem and everything is up and running. A: Try this: if (strlen($password) >= 8 && strlen($password) <= 32) { if (strlen($repeatpassword) >= 8 && strlen($repeatpassword) <= 32) { // code here } } I think it's a bit odd to check both passwords, however. So, my solution would be: if (strlen($password) >= 8 && strlen($password) <= 32) { // code here }
unknown
d18570
test
Your column names are mixed up. Instead of cmbKala.DisplayMember = "mName"; cmbKala.ValueMember = "mID"; Try this: cmbKala.DisplayMember = "kName"; cmbKala.ValueMember = "kID";
unknown
d18571
test
In the answer, my extendable component is an h1 as opposed to a p. As it made things easier to debug. I figured out that the flow works as stated by jelhan in the comments. * *There is a createElement (I'm a 100% positive as I saw in the debugger that my h1 custom tag was breaking on __openElement). *It then parses all the attributes one by one with setAttribute (100% positive, because debugger). Ultimately, the "is" attribute is set by setAttribute. I know that when setAttribute is used, then the web component will not be instantiated. *It ends with an insertBefore call, at either a flushElement or somewhere else (I saw this in my debugger, didn't bother to pinpoint it). There is a Stackoverflow question on how a web component should be added in vanillaJS. With that knowledge, I created a JS fiddle, in which you see the workflow of how Glimmer does it now (workflow-wise), and how Glimmer could be doing it. I also created a hacky workaround for statically defined elements in a .hbs file (warning: I don't create libraries, I merely poke around in them) You need to replace __setAttribute with something like this: __setAttribute(name, value, namespace) { if(name === "is"){ //hack, hack, hackerdeehack //I need the actual document, this.dom doesn't cut it. I suppose it's kind of like a shadow DOM, similar to what ReactJS does. let webComponent = window.document.createElement(this.constructing.tagName, { is: value }); //copy attributes that are already parsed [...this.constructing.attributes].forEach( attr => { this.dom.setAttribute(webComponent, attr.nodeName, attr.nodeValue, namespace) }); this.constructing = webComponent; } this.dom.setAttribute(this.constructing, name, value, namespace); } Ultimately, it's up to the EmberJS/Glimmer maintainers to propose a certain way forward. This particular hack was made, because I did not want to mess around with the VM and I also did not want to mess around with the parsing behavior of Glimmer. But I did want to see if I was right in my thinking, and I am (2 days ago, I didn't know that Glimmer existed, so I needed to be a bit thorough). Some extra info for the curious people Terminology that I saw: * *opcodes: VM thingy, I kind of forgot what it meant in a VM context, but I've seen it in my compiler construction and computer architecture courses. I always translate it as: the table of numbers to which CPUs understand what instruction they should execute. *System calls: DOM function calls are system calls, as they are what the rendering engine is about. A couple of handy breakpoints (+ console.log()s) in order to verify the workflow that I outlined: //element-builder.js __openElement(tag) { console.log('NewElementBuilder - __openElement', tag, [this.element], this.element.attributes, 'modules'); debugger; return this.dom.createElement(tag, this.element); } __setAttribute(name, value, namespace) { debugger; this.dom.setAttribute(this.constructing, name, value, namespace); //this is how the "is" attribute is set } //note: it could also be that __flushElement is called... I didn't check this thoroughly __appendText(text) { let { dom, element, nextSibling } = this; debugger; console.log('__appendText', dom, element, nextSibling, text); let node = dom.createTextNode(text); dom.insertBefore(element, node, nextSibling); return node; } // just to be sure __flushElement(parent, constructing) { debugger; this.dom.insertBefore(parent, constructing, this.nextSibling); }
unknown
d18572
test
You have to configure the jobLauncher that you're using to launch jobs to use your TaskExecutor (or a separate pool). The simplest way is to override the bean: @Bean JobLauncher jobLauncher(JobRepository jobRepository) { new SimpleJobLauncher( taskExecutor: taskExecutor(), jobRepository: jobRepository) } Don't be confused by the warning that will be logged saying that a synchronous task executor will be used. This is due to an extra instance that is created owing to the very awkward way Spring Batch uses to configure the beans it provides in SimpleBatchConfiguration (long story short, if you want to get rid of the warning you'll need to provide a BatchConfigurer bean and specify how 4 other beans are to be created, even if you want to change just one). Note that it being the same job is irrelevant here. The problem is that by default the job launcher will launch the job on the same thread.
unknown
d18573
test
I assume you have a table view with cells that can be swiped left, and that swiping shows a delete button entitled DELETE. Then you could do the following: let firstCell = XCUIApplication().cells.element(boundBy: 0) firstCell().swipeLeft() let deleteButton = firstCell.buttons[„DELETE“] deleteButton.tap() EDIT: Thanks for your edit! Your delete button does not have any title text. Thus, you cannot access the button with firstCell.buttons[„DELETE“]. From your screen shot it looks as if the delete button was the only button in the cell. If so, you could try firstCell.buttons.firstMatch. If you have more buttons, you could access the delete button using firstCell.buttons.element(boundBy: 0) where „0“ had to be replaced by the correct index.
unknown
d18574
test
You could create a custom view and draw the text on canvas. Here is a sample. Custom view: public class TextOverlay : View { protected TextOverlay(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public TextOverlay(Context context) : base(context) { } public TextOverlay(Context context, IAttributeSet attrs) : base(context, attrs) { } public TextOverlay(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public TextOverlay(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); // make the canvas Transparent canvas.DrawColor(Color.Transparent); canvas.Translate(100, 150); var paint = new Paint { Color = Color.Blue, TextSize = 18 }; paint.SetStyle(Paint.Style.Fill); canvas.Rotate(-45); canvas.DrawText("CANCELLED", 0, 0, paint); } } Add it to a relative layout on top of the image view: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main"> <ImageView android:src="@android:drawable/ic_menu_gallery" android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageView1" android:foregroundGravity="center" android:layout_alignParentStart="false" android:layout_alignParentTop="false" android:layout_alignParentRight="false" android:layout_alignParentLeft="false" android:layout_alignParentEnd="false" android:layout_alignParentBottom="false" android:layout_centerInParent="true" /> <viewoverlay.TextOverlay android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/textOverlay" android:foregroundGravity="center" android:layout_alignParentStart="false" android:layout_alignParentTop="false" android:layout_alignParentRight="false" android:layout_alignParentLeft="false" android:layout_alignParentEnd="false" android:layout_alignParentBottom="false" android:layout_centerInParent="true" /> </RelativeLayout>
unknown
d18575
test
The problem is that android-support-annotations.jar used to be a separate library containing the android annotations, but for some reason these annotations are already included in recent versions of the android-support-v4.jar file. Deleting the annotations jar solved the issue. A: Solved this exact issue in a Cordova project that used the facebook plugin. I was able to successfully build by commenting out this line from platforms\android\project.properties, as shown: # cordova.system.library.1=com.android.support:support-v4:+ And by commenting out this line from platforms\android\build.gradle, as shown: // compile "com.android.support:support-v4:+" Then doing the build. The problem started when I installed (katzer/cordova-plugin-local-notifications) which added these lines, but it created a conflict since the library it was adding to the build was already part of the facebook plugin build. A: Build->clean Project ,and it worked A: As other users said, the first elements to troubleshoot are dependencies. Although, sometimes you can struggle for hours and you don't find any problem so you can focus on the build process instead. Changing the way in which the .dex files are produced sometimes solves the problem. You can go through these steps: * *Open your Build.gradle (app) file *Search for the task dexOptions *Change it to: dexOptions { incremental false } If you don't find the task in your file then you can add it. A: I deleted the android-support-v4.jar and it worked. A: For me the reason was the new data-binding lib com.android.databinding:dataBinder:1.0-rc2 it somehow used a conflicting version of the annotations lib, which I could not force with configurations.all { resolutionStrategy { force group: 'com.android.support', name: 'support-v4', version: '23.1.0' force group: 'com.android.support', name: 'appcompat-v7', version: '23.1.0' force group: 'com.android.support', name: 'support-annotations', version: '23.1.0' } } but the new rc3 and rc4 versions seem to have fixed it, so just use those versions A: I had the same problem , but i deleted build files from the build folder projectname/app/build and it removed all the related error. "can't clean the project" and also "dex errow with $anim" A: If this is cordova / ionic project this worked for me add these line to build.gradle under platforms/android after line number 22 i.e after apply plugin: 'android' configurations { all*.exclude group: 'com.android.support', module: 'support-v4' } A: I managed to fix this issue. The reason was that I included the android support library 19.0.0 as a dependency, but 19.1.0 is required. See here for more information So it has to be dependencies { compile 'com.android.support:support-v4:19.1.0' compile 'com.crashlytics.android:crashlytics:1.+' compile 'com.android.support:support-annotations:20.0.0' } A: If you import AppCompat as a library project and you also have android-support-annotations.jar in libs elsewhere, make sure to import everywhere AppCompat library only (it already includes this annotations lib). Then delete all android-support-annotations.jar to avoid merging multiple versions of this library. A: Updating Android SDK Tools fixed it for me, now it just sees the copy in android-support-v4.jar. I had the same problem when using ant, and the annotations library was being included automatically by an outdated sdk.dir/tools/ant/build.xml. A: Clean project works as a temporary fix, but the issue will reappear on next compilation error. To fix more reliably, I had to update the dependency to android support-v4 to com.android.support:support-v4:22.2.0. A: Put in your build.gradle the dependency of support-annotations according with your compileSdkVersion. For instance: A project with the compileSdkVersion 25 you can put the following dependence: compile 'com.android.support:support-annotations:25.0.1' This will solve your problem. A: In my case I had a file called cache.xml under /build/intermediates/dex-cache/cache.xml in the root project folder. I deleted this file, rebuild the project and it worked for me. A: I deleted the android-support-v4.jar and it worked. Explain - android-support-v4.jar is conflicting with my other .jar files of project\libs files ** specially when you are running with java 8 on AS. A: Put android-support-v4.jar in your libs folder in eclipse. Clean and build the project. It will resolve the issue. A: Another reason that messages such as these can come up in Android Studio when building and launching can be the cause of application tags in your libraries. If you have several Android Library projects that you imported as modules. Go into those projects and remove the <application> ... </application> tags and everything between them. These can cause issues in the build process along with the support library issues already mentioned. A: From /platforms/android/libs/ delete android-support-v4.jar. It works for me.
unknown
d18576
test
brian d foy answer is essentially correct. You can pretty much translate this code into Perl6 my $frame = Buf.new; $frame.append(0xA2); $frame.append(0x01); say $frame; # OUTPUT: «Buf:0x<a2 01>␤» However, the declaration is not the same: bu = bytearray( 'þor', encoding='utf8',errors='replace') in Python would be equivalent to this in Perl 6 my $bú = Buf.new('þor'.encode('utf-8')); say $bú; # OUTPUT: «Buf:0x<c3 be 6f 72>␤» And to use something equivalent to the error transformation, the approach is different due to the way Perl 6 approaches Unicode normalization; you would probably have to use UTF8 Clean 8 encoding. For most uses, however, I guess Buf, as indicated by brian d foy, is correct. A: I think you're looking for Buf - a mutable sequence of (usually unsigned) integers. Opening a file with :bin returns a Buf.
unknown
d18577
test
So i solve my own issue. It turns out that my Widget is the actual root cause. I don't think SliverList is playing well with FirebaseAnimatedList (maybe because they are doing essentially the same thing?) So i refactor and remove everything related to SliverList. Widget build(BuildContext context) { final screenSize = MediaQuery.of(context); return Container( decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade600)), child: Column( //mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.all(5), child: Text( productcode, style: const TextStyle(fontSize: 20), ), ), Container( padding: EdgeInsets.all(5), width: screenSize.size.width, decoration: BoxDecoration( border: Border.all( color: Colors.grey.shade200, strokeAlign: StrokeAlign.inside)), child: Text( productname, style: const TextStyle(fontSize: 20), ), ), Container( padding: EdgeInsets.all(5), width: screenSize.size.width, decoration: BoxDecoration( border: Border.all( color: Colors.grey.shade200, strokeAlign: StrokeAlign.inside)), child: Text( serial, style: const TextStyle(fontSize: 20), ), ), Align( alignment: Alignment.topRight, child: Flexible( fit: FlexFit.loose, child: SizedBox( width: 90, child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade200), ), padding: EdgeInsets.all(5), child: Text( 'Quantity : \n\v${quantity}', style: TextStyle(fontSize: 18), textAlign: TextAlign.right, )), ), ), ) ], ), ); Then i reimplemented it into my pages. Now it works as expected. all is well again!
unknown
d18578
test
Here is the function that should install Pandoc correctly and that was submitted as a pull request. In case you run into this error before it is fixed. library(installr) FixedInstall.Pandoc <- function (URL = "https://github.com/jgm/pandoc/releases", use_regex = TRUE, to_restart, ...) { URL <- "https://github.com/jgm/pandoc/releases" page_with_download_url <- URL if (!use_regex) warning("use_regex is no longer supported, you can stop using it from now on...") page <- readLines(page_with_download_url, warn = FALSE) sysArch <- Sys.getenv("R_ARCH") sysArch <- gsub("/ |/x", "", sysArch) pat <- paste0("jgm/pandoc/releases/download/[0-9.]+/pandoc-[0-9.-]+-windows",".*", sysArch, ".*", ".msi") target_line <- grep("windows", page, value = TRUE) m <- regexpr(pat, target_line) URL <- regmatches(target_line, m) URL <- head(URL, 1) URL <- paste("https://github.com/", URL, sep = "") installed <- install.URL(URL, ...) if (!installed) return(invisible(FALSE)) if (missing(to_restart)) { if (is.windows()) { you_should_restart <- "You should restart your computer\n in order for pandoc to work properly" winDialog(type = "ok", message = you_should_restart) choices <- c("Yes", "No") question <- "Do you want to restart your computer now?" the_answer <- menu(choices, graphics = "TRUE", title = question) to_restart <- the_answer == 1L } else { to_restart <- FALSE } } if (to_restart) os.restart() }
unknown
d18579
test
No, you cannot do that without a loop or equivalent construct. (full stop) You can hide the loop inside some functions, such as std::transform(), but not avoid it. Moreover, compilers are well trained to optimize loops (because they are ubiquotous), so there is no good reason to avoid them. A: Without an explicit loop: std::transform( std::begin(mykeys), std::end(mykeys), std::inserter(myMap, myMap.end()), [] (char c) {return std::make_pair(c, 0);} ); Demo. A range-based for loop would be far more sexy though, so use that if possible: for (auto c : mykeys) myMap.emplace(c, 0); A: You can not do this without a loop. What you can do is to hide a loop under a standard algorithm because you need to convert an object of type char to an object of type std::map<char, int>::value_type that represents itself std::pair<const char, int> For example #include <iostream> #include <vector> #include <map> #include <iterator> #include <algorithm> int main() { std::vector<char> v { 'a', 'b', 'c' }; std::map<char, int> m; std::transform( v.begin(), v.end(), std::inserter( m, m.begin() ), []( char c ){ return std::pair<const char, int>( c, 0 ); } ); for ( const auto &p : m ) { std::cout << p.first << '\t' << p.second << std::endl; } return 0; } The output is a 0 b 0 c 0 A: Using boost: template<class Iterators, class Transform> boost::iterator_range< boost::transform_iterator< typename std::decay_t<Transform>::type, Iterator >> make_transform_range( Iterator begin, Iterator end, Transform&& t ) { return { boost::make_transform_iterator( begin, t ), boost::make_transform_iterator( end, t ) }; } A helper to map keys to pairs: template<class T> struct key_to_element_t { T val; template<class K> std::pair< typename std::decay<K>::type, T > operator()(K&& k) const { return std::make_pair( std::forward<K>(k), val ); } }; template<class T> key_to_element_t< typename std::decay<T>::type > key_to_element( T&& t ) { return { std::forward<T>(t) }; } template<class R> struct range_to_container_t { R r; template<class C> operator C()&& { using std::begin; using std::end; return { begin(std::forward<R>(r)), end(std::forward<R>(r)) }; } }; template<class R> range_to_container_t<R> range_to_container( R&& r ) { return std::forward<R>(r); } after all that mess we get: std::vector<char> mykeys { 'a', 'b', 'c' ]; std::map<char, int> myMap = range_to_container( make_transform_range( begin(mykeys), end(mykeys), key_to_element( 0 ) ) ); which constructs the std::map directly from a transformed sequence of elements in the mykeys vector. Pretty silly.
unknown
d18580
test
Okay, well first of all, here is a link to a working fiddle: jsfiddle What you need to do is, to give every element, you want to float a float: left; I would also give every #frame a position: relative; so that the #title's can position themselves according to their parent element. As @Antony also pointed out, you made a syntax error with margin-right; 45px;, the first semicolon should be a regular colon! A: I would first rethink your structure a bit. Here's how I would do it. You can use the link element itself for the thumbnail wrapper - and I would suggest you define the importance of the headings etc with heading tags. Search engines read sites like newspapers. If you don't declare importance, they wont know how to structure your site. I wouldn't use underline tag or italic tag because they are deprecated and I wouldn't use br linebreak because it's unnecessary and it's not really a line break. You can declare that in your .css file. jsfiddle HERE The magic is basically the float: left; but this will set you up with a more solid foundation. You see, for example - if you decided that you didn't want italics anymore - you would have to go remove all of those tags from the html. This way you only declare it in one place. Further more, styles that all of the blocks share need not be repeated. All blocks are the same I'm imagining. Mabybe they have different background-images.. but the rest is the same. Think modular. HTML <section class="content"> <a class="link-wrapper one" alt="song thumbnail" href="#"> <h2>Song Title</h2> <h3>Tag line etc I'm guessing</h3> </a> <a class="link-wrapper two" alt="song thumbnail" href="#"> <h2>Song Title</h2> <h3>Tag line etc I'm guessing</h3> </a> </section> CSS /* moves padding inside the box - start your project off right */ * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } html, body { margin: 0; padding: 0; } .content { padding: 1em; } .link-wrapper { position: relative; display: block; float: left; width:250px; height:217px; text-align: center; margin-right: 1em; text-decoration: none; } .link-wrapper h2 { /* heiarchy of text importance is how SEO works */ font-weight: normal; text-decoration: underline; padding-top: 1em; } .link-wrapper h3 { /* heiarchy of text importance is how SEO works */ font-weight: normal; font-style: italic; } /* to differentiate + unique classes for thumbnails */ .one { background-image:url(http://placehold.it/250x217/ff0066); } .two { background-image:url(http://placehold.it/250x217/99edee); } I hope this helps. -nouveau
unknown
d18581
test
You can not align directly on a surface. You have to wrap your content with Column, Row, Box, etc. You can change your code like the following @Composable fun MainScreen(message: String) { Surface { Column { Surface( modifier = Modifier .width(500.dp) .height(250.dp), color = Color.Green ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text(text = message) } } Surface( modifier = Modifier .width(500.dp) .height(250.dp), color = Color.Blue ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text( text = message ) } } } } }
unknown
d18582
test
In the case of getResultList(), the javadocs state that it returns an java.util.List (see here: http://docs.oracle.com/javaee/5/api/javax/persistence/Query.html#getResultList%28%29 ), that Vector implements. The result type, aka what's in the list, depends on the criteria projection or, in a JPQL Query, of the from statement. In your case, because you don't do projection, I think it should return a List<User>. For your information, and if you are using JPA 2.0, you can also use TypedQuery which could avoid that (ugly !) cast : http://www.javabeat.net/typedquery-jpa-2/
unknown
d18583
test
Have you added a Setup project to the solution? It seems to me that those take much longer to load than other types of projects.
unknown
d18584
test
form tags are not valid between table and tr tags. I suggest changing your view to not have the tr or td tags and do this outside: <table> @foreach (var item in Model) { <tr><td> @using (Html.BeginForm()) { @Html.Partial("_roomPartial", item) } </td></tr> } </table> If you need to have a form for every row but want your inputs spread across cells, your only option is to have nested tables like this: <table> <tr> <td> <form> <table> <tr> <td>cell1</td> <td>cell2</td> <td>cell3</td> </tr> </table> </form> </td> </tr> <tr> <td> <form> <table> <tr> <td>cell1</td> <td>cell2</td> <td>cell3</td> </tr> </table> </form> </td> </tr> </table>
unknown
d18585
test
Firstly page of top you put used db connection related code : $conn = mysql_connect('localhost', 'user', 'pass'); mysql_select_db('details_db'); and then bellow and removed mysql_select_db('details_db'); line after mysql_ $funds = $_POST['funds']; $withdraw_or_add = $_POST['list']; if($withdraw_or_add == "add") { $sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1"; } else { $info = mysql_query("SELECT * FROM users WHERE userId = '1'"); $info = mysql_fetch_assoc($info); $new_fund = $info['userFunds'] - $funds; $sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1"; } //mysql_select_db('details_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated data successfully\n"; mysql_close($conn); Note: Please stop using mysql_* functions. mysql_* extensions have been removed in PHP 7. Please used PDO and MySQLi.
unknown
d18586
test
See docs in header: Addling handlers while the server is running is not allowed. Attempting to do this will result in undefined behavior.
unknown
d18587
test
It appears the @angular/core is version ~7.2.0 but the @angular/material is ^9.2.3. You either need to upgrade the Angular or downgrade the Angular Material library. I'd rather downgrade the Material library. Try the following commands in order npm uninstall @angular/material npm uninstall @angular/cdk npm install @angular/[email protected] npm install @angular/[email protected] A: I'm not sure why this happened (normally the dependencies of material 9 are set to angular 9), but you can delete it and resintall the correct version again npm un -S @angular/material @angular/cdk npm add -S @angular/material@7 @angular/cdk@7
unknown
d18588
test
Although I do not get your question completely, I will try to give you some tools that might be useful: To get input value you can use (and put this inside of a 'for' loop depending on the number of rows you want to create) new_InvoiceNo= input("Enter InvoiceNo:\n") new_Customer= input("Enter Customer:\n") new_invoice = input("Enter invoice:\n") ... then you can either append these values as list into the main DF : to_append = [new_InvoiceNo, new_Customer, new_invoice, ...] new_values = pd.Series(to_append, index = df.columns) df = df.append(new_values , ignore_index=True) or , you can use '.loc' method: to_append = [new_InvoiceNo, new_Customer, new_invoice, ...] df_length = len(df) df.loc[df_length] = to_append Try to implement this in your code and report it back here.
unknown
d18589
test
I would use some kind of Java JSON Serializer, there a few of them out there. * *GSON *FlexJson Here is a simple example with FlexJson on how you could convert an object to JSON String. final JSONSerializer serializer = new JSONSerializer(); final String output = serializer.transform(new ProtocolCalculatorTransformer(),ProtocolCalculation.class).exclude("*.class").deepSerialize(this); return output;
unknown
d18590
test
So to have an annotationset associated to a dataset, you would need write permission to that dataset. If you created the dataset then you would have write permission, which would be associated with your account. If it is a public dataset, then you might need to ask for permission from the person who loaded that dataset to add you with write permissions to it, or you could reload it under you account. Now assuming you created a dataset, then you can create an AnnotationSet via curl directly - you will need to use your API key from the console (please don't post your API key publicly here). Below is the command and what you would fill in: curl -v -X POST -H "Content-Type: application/json" -d '{"datasetId":"YourActualDatasetID", "referenceSetId":"YourActualReferencesetID"}' https://genomics.googleapis.com/v1/annotationsets?fields=asdf&key=YOUR_API_KEY Let me know if this worked for you, and if there is anything else that I can help you with. Thanks, Paul A: to add to Paul's answer: annotationSetId must be the id to a real annotation set. We will work on improving the error message. We would like to require referenceId for all our APIs. We don't for our Variant API because the Reference API didn't exist when we created the Variant API. To give a user WRITE permission, add the user as a Project Editor. See https://cloud.google.com/iam/docs/quickstart-roles-members#add_a_project_member_and_grant_them_an_iam_role A: My previous comment didn't get formatted properly, so I'm writing it as an answer instead. For this specific test I would need to enable billing for my account, so my guide is the raw information in the Genomics REST API via the Discovery service: https://www.googleapis.com/discovery/v1/apis/genomics/v1/rest Based on the REST API, the scopes for creating a AnnotationSet are the following: "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/genomics" Since you are getting an authentication error, it would be good to first check on the console (https://console.cloud.google.com) for your project that is tied to your API (server) key that you used, if it is enabled for the Genomics and Cloud APIs? ~p A: Here is the public references: https://console.cloud.google.com/storage/browser/genomics-public-data/references/ And here we can get ReferenceIDs: https://developers.google.com/apis-explorer/#p/genomics/v1/genomics.referencesets.search A: Glad to hear you got everything to work Amir! It was a fun team effort by the three of us, and I'm always happy to help out as I've used and seen the evolution of the API over the past two years :) Regarding ReferenceIds I see you already found some of the same links I am posting here. These are basically the id that point to a reference which is a sequence such as a chromosome. A collection of reference IDs belong to a ReferenceSet which represents a reference assembly, and references.bases belong to a ReferenceID. I have not seen in the REST API a way to create load a new reference genome - those are probably populated and made available by Google manually via the backend. Maybe Melissa might have more information regarding that. Below are a collection of links that may be helpful regarding References - some of which you also discovered - and am listing them as a collection in case others might find them useful in the future: http://googlegenomics.readthedocs.io/en/latest/use_cases/discover_public_data/reference_genomes.html https://cloud.google.com/genomics/v1/users-guide#references https://cloud.google.com/genomics/v1/reference-sets#finding-references https://cloud.google.com/genomics/reference/rest/v1/referencesets https://cloud.google.com/genomics/reference/rest/v1/references https://cloud.google.com/genomics/reference/rest/v1/references.bases Each of the above of the REST APIs will have their own specific methods for searching and associating to data. Hope it helps, ~p A: To use the REST API for annotation: gcloud auth login TOKEN=$(gcloud auth print-access-token) curl -v -X POST -H "Authorization: Bearer $TOKEN" -d '{"datasetId": "YOUR_DATA_SET" , "referenceSetId": "EMWV_ZfLxrDY-wE" }' --header "Content-Type: application/json" https://genomics.googleapis.com/v1/annotationsets
unknown
d18591
test
from bs4 import BeautifulSoup import requests url = 'https://bitskins.com/' page_response = requests.get(url, timeout=5) page_content = BeautifulSoup(page_response.content, 'html.parser') skin_list = page_content.findAll('div', class_ = 'panel item-featured panel-default') for skin in skin_list: name = skin.find("div", class_ = "panel-heading item-title") price = skin.find("span", class_ = "item-price hidden") discount = skin.find("span", class_ = "badge badge-info") wear = skin.find("span", class_ = "hidden unwrappable-float-pointer") print("name:", name.text) print("Price", price.text) print("Discount:", discount.text) # Choose which one you want for w in wear.text.split(","): print("Wear:", w) You was trying to find the incorrect class. I added some other data which you can scrape for examples. Wear holds a few values which i outputted. A: In your line of code, you are searching for a tag with a class that has multiple values. wear_box = page_content.find_all('div', attrs={'class': 'text-muted text-center'}) On the page the only tag that fits is: <div class="container text-center text-muted" style="padding-top: 17px;"> In BS4, when you are searching for attributes with multiple values, you either search for a single value eg: wear_box = page_content.find_all('p', attrs={'class': 'text-muted'}) Or you have to search for the exact list of vales eg: wear_box = page_content.find_all('div', attrs={'class': 'container text-center text-muted'})
unknown
d18592
test
I found great tutorial on Android Image Processing here. public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) { int w = src.getWidth(); int h = src.getHeight(); Bitmap result = Bitmap.createBitmap(w, h, src.getConfig()); Canvas canvas = new Canvas(result); canvas.drawBitmap(src, 0, 0, null); Paint paint = new Paint(); paint.setColor(color); paint.setAlpha(alpha); paint.setTextSize(size); paint.setAntiAlias(true); paint.setUnderlineText(underline); canvas.drawText(watermark, location.x, location.y, paint); return result; } Thanks to Pete Houston who shares such useful tutorial on basic image processing. A: It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like. A: For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method: private Bitmap addWaterMark(Bitmap src) { int w = src.getWidth(); int h = src.getHeight(); Bitmap result = Bitmap.createBitmap(w, h, src.getConfig()); Canvas canvas = new Canvas(result); canvas.drawBitmap(src, 0, 0, null); Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo); canvas.drawBitmap(waterMark, 0, 0, null); return result; } A: If someone is still searching for this, I found a good solution here It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for. /** * Embeds an image watermark over a source image to produce * a watermarked one. * @param source The source image where watermark should be placed * @param watermark Watermark image to place * @param ratio A float value < 1 to give the ratio of watermark's height to image's height, * try changing this from 0.20 to 0.60 to obtain right results */ public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) { Canvas canvas; Paint paint; Bitmap bmp; Matrix matrix; RectF r; int width, height; float scale; width = source.getWidth(); height = source.getHeight(); // Create the new bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG); // Copy the original bitmap into the new one canvas = new Canvas(bmp); canvas.drawBitmap(source, 0, 0, paint); // Scale the watermark to be approximately to the ratio given of the source image height scale = (float) (((float) height * ratio) / (float) watermark.getHeight()); // Create the matrix matrix = new Matrix(); matrix.postScale(scale, scale); // Determine the post-scaled size of the watermark r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight()); matrix.mapRect(r); // Move the watermark to the bottom right corner matrix.postTranslate(width - r.width(), height - r.height()); // Draw the watermark canvas.drawBitmap(watermark, matrix, paint); return bmp; } And it is well commented which is what is a huge plus! A: In Kotlin: Note: Its just modified code of above answers private fun mark(src: Bitmap, watermark: String): Bitmap { val w = src.width val h = src.height val result = Bitmap.createBitmap(w, h, src.config) val canvas = Canvas(result) canvas.drawBitmap(src, 0f, 0f, null) val paint = Paint() paint.color = Color.RED paint.textSize = 10f paint.isAntiAlias = true paint.isUnderlineText = true canvas.drawText(watermark, 20f, 25f, paint) return result } val imageBitmap = mark(yourBitmap, "Your Text") binding.meetProofImageView.setImageBitmap(imageBitmap) A: You can use androidWM to add a watermark into your image, even with invisible watermarks: add dependence: dependencies { ... implementation 'com.huangyz0918:androidwm:0.2.3' ... } and java code: WatermarkText watermarkText = new WatermarkText(“Hello World”) .setPositionX(0.5) .setPositionY(0.5) .setTextAlpha(100) .setTextColor(Color.WHITE) .setTextFont(R.font.champagne) .setTextShadow(0.1f, 5, 5, Color.BLUE); WatermarkBuilder.create(this, backgroundBitmap) .loadWatermarkText(watermarkText) .getWatermark() .setToImageView(backgroundView); You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb. A: I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code. Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only. public static Bitmap waterMarkBitmap(Bitmap src, String watermark) { int w = src.getWidth(); int h = src.getHeight(); Bitmap mutableBitmap = Utils.getMutableBitmap(src); Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig()); Canvas canvas = new Canvas(result); canvas.drawBitmap(src, 0f, 0f, null); Paint paint = new Paint(); paint.setColor(Color.RED); paint.setTextSize(92f); paint.setAntiAlias(true); paint.setAlpha(70); // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque. paint.setUnderlineText(false); canvas.rotate(45, w / 10f, h / 4f); canvas.drawText(watermark, w / 10f, h / 4f, paint); canvas.rotate(-45, w / 10f, h / 4f); return result; } It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap. Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one. public static Bitmap getMutableBitmap(Bitmap immutableBitmap) { if (immutableBitmap.isMutable()) { return immutableBitmap; } Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap); return workingBitmap.copy(Bitmap.Config.ARGB_8888, true); } I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not. A: use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.
unknown
d18593
test
options.AcceptAnonymousClients() has no effect on the code flow as client_id is a mandatory parameter in this case (it only affects the token, introspection and revocation endpoints). options.SignInScheme cannot be set to a scheme belonging to OpenIddict. In most cases, it must correspond to a cookie handler (typically the one registered by Identity). You will also want to remove /signin-google from the endpoints managed by OpenIddict, as it will prevent the Google authentication handler from working properly.
unknown
d18594
test
You could use content negotiation for that, where your AJAX request sets the Accept header to tell your Express server to return JSON instead of HTML: router.get('/reports', function(req,res) { ... if (req.accepts('json')) { return res.send(theData); } else { return res.render('reports', ...); }; }); Alternatively, you can check if the request was made with an AJAX call using req.xhr (although that's not 100% failsafe). A: No you can't do both, but you could render the page and send the data at the same time: res.render('reports',{data:json}); and then access those data in the newly rendered page. alternatively you could send a flag when making the call , and then decide whether you want to render or send based on this flag. A: Ideally, it needs to be 2 separate route, one spitting json and other rendering a view. Else, you could pass a url param, depending on which you return json or render a view. router.get('/reports/json', function(req,res){ var data = JSON_OBJECT; res.send(data); }); router.get('/reports', function(req,res){ var data = JSON_OBJECT; res.render('path-to-view-file', data); }); A: No, you can't. You can only have a single response to a given request. The browser is either expecting an HTML document or it is expecting JSON, it doesn't make sense to give it both at once. render just renders a view and then calls send. You could write your view to output an HTML document with a <script> element containing your JSON in the form of a JavaScript literal.
unknown
d18595
test
You can use Stash by AppsCode which is a great solution to backup Kubernetes volumes. For supported versions check here Stash by AppsCode is a Kubernetes operator for restic. If you are running production workloads in Kubernetes, you might want to take backup of your disks. Traditional tools are too complex to setup and maintain in a dynamic compute environment like Kubernetes. restic is a backup program that is fast, efficient and secure with few moving parts. Stash is a CRD controller for Kubernetes built around restic to address these issues. Using Stash, you can backup Kubernetes volumes mounted in following types of workloads: Deployment, DaemonSet, ReplicaSet, ReplicationController, StatefulSet After installing stash using Script or HELM you would want to follow Instructions for Backup and Restore if you are not familiar I find it very useful
unknown
d18596
test
This emptied my bin without any confirmation. @ECHO OFF start /b /wait powershell.exe -command "$Shell = New-Object -ComObject Shell.Application;$RecycleBin = $Shell.Namespace(0xA);$RecycleBin.Items() | foreach{Remove-Item $_.Path -Recurse -Confirm:$false}" A: Above answers are ok for cmd batch files but for the new powershell there is a better way Simply use the cmdlet Clear-RecycleBin Optionally you can use the -Force or -Confirm:$false parameters so it won't ask for confirmation For more info open powershell and type Get-Help Clear-RecycleBin A: I have just found this. erase /s/q/f "C:\$RECYCLE.BIN\*">nul A: Guaranteed to delete all content in the Recycle Bin for the selected drive while leaving the folder itself intact: C:\$Recycle Bin\>rd . /q /s * *Change to the required drive *Change into the $Recycle Bin folder *Run the command rd . /q /s [remove-dir (currentdir) /quiet /subdir] You will get an error that the current directory is still in use (because that is your current location) and can't be deleted. This is expected behaviour because I want the $Recycle Bin folder to remain.
unknown
d18597
test
If Java had destructors, would I need to call the destructor of an iterator if I destroy the linked list? To delete an iterator because it corresponds to a deleted node (whatever the list is deleted or not, so all its nodes are deleted or not) is for me the worst possible choice, that means the iterator becomes silently unusable, a very practical way to introduce undefined behaviors at the execution. In case a node knows its iterators a good way is to mark them invalid when the node is deleted, and in that case to try access the corresponding element of the list or go to the previous/next element produces an exception. For me the list by itself do not need to know the iterators, and an iterator does not need to know the list by itself, so for question 1 no relation at all between GenericLinkedList<T> and GLLIterator<T>. For the question 2 no aggregation nor composition, because the iterator just references a node, the iterator has a node is false, an iterator is not composed of nodes nor owns them. In the reverse direction even a node knows the iterators pointing to it that node is not composed of iterator nor owns them, but also just reference them. If a node knows the iterators you have an association from node to iterator with the multiplicity *, else no relation at all. In iterator you have a simple association to node, the multiplicity can be 0..1 (0 means the iterator was invalidated) or 1 depending on the implementation. For the question 3 an interface having no implementation it cannot use something else, contrarily to the implementing class(es).
unknown
d18598
test
Things tend to get very tedious when you handle data attributes in individual arrays. Conceptually, it makes more sense in this scenario to treat a Player as a unique Object to hold their name, number and scores. public class Player { private String name; private int number; private int scores[]; private int currentGame = 0; public Player(String name, int number, int numGames) { this.name = name; this.number = number; this.scores = new int[numGames]; } // Getters and Setters public String getName() { return name; } // Required public void addScore(int score) { if (currentGame < scores.length) { scores[currentGame++] = score; } } public int getAverage() { int total = 0; for (int i = 0; i < currentGame; i++) { total += scores[i]; } return total / currentGame; } @Override public String toString() { return String.format("%s (%s) : avg %d", name, number, getAverage()); } } You then can instantiate a player with their name, number and how many games they played. You might, however, like to treat the Player class as a single game and have an Object that describes each Game itself; consisting of 10 Players. The Object is lacking getters/setters for the name and number attribute. Then you can create a single array to hold all data for a game. If you plan on having multiple games, you may want to have an array of scores instead of a single score per Player. public static final String[] playerName = {"Jim", "Joe", "Ken", "James", "John", "Bud", "Clark", "Barry", "Jose", "Paul"}; public static final int[] jerseyNumber = {34, 33, 24, 11, 3, 13, 6, 4, 28, 10}; public Player[] createGame(int numGames) { Player[] players = new Player[10]; for (int i = 0; i < 10; i++) { players[i] = new Player(playerName[i], jerseyNumber[i], numGames); } return players; } Then when you will need to get the score somehow. public void getScore(Player[] players, int numGames) { Scanner input = new Scanner(System.in); for (int i = 0; i < numGames; i++) { System.out.println("Game " + i); for (Player player : players) { System.out.print(player.getName() + " : "); player.addScore(input.nextInt()); } } } public void getAverage(Player[] players) { for (Player player : players) { System.out.println(player.toString()); } }
unknown
d18599
test
As a member operator overload it should only take one argument, the other being this. class Foo { int a; public: bool operator==(const Foo & foo); }; //... bool Foo::operator==(const Foo & foo) { return a == foo.a; } A: If operator== is a non static data member, is should take only one parameter, as the comparison will be to the implicit this parameter: class Foo { bool operator==(const Foo& rhs) const { return true;} }; If you want to use a free operator (i.e. not a member of a class), then you can specify two arguments: class Bar { }; bool operator==(const Bar& lhs, const Bar& rhs) { return true;} A: You should remove your operator== from a RationalNumber to somewhere else. As it is declared inside a class it is considered that 'this' is the first argument. From semantics it is seen that you offer 3 arguments to a compiler. A: friend bool operator==( Rationalnumber l, Rationalnumber r ); when you declare it as non-member function, it can take two arguments. when you declare it as member function, it can only take one argument.
unknown
d18600
test
First you must tag the image ID. The you must login to your private Docker registry. (The correct name is registry and not repository. A Docker registry holds repositories). Then you push the image. Substitute privateregistry with the hostname of the Registry. docker tag 2482781314c7 privateregistry/test11 docker login privateregistry docker push privateregistry/test11
unknown