_id
stringlengths
2
6
text
stringlengths
4
46k
title
stringclasses
1 value
d6601
You can just try using string.find. But it seems like your problem is that link.get("href") returned None. Your link probably has no "href". A: I had to guess a little bit what exactly your context was. But this might help you. You can check if something is None by "if var is None:" and continuing the loop. But my recommendation is to start with basic tutorials instead of jumping right into some concrete tasks... this might be easier for you :) from bs4 import BeautifulSoup import re website = """#INSERT_HTML_CODE""" soup = BeautifulSoup(website, 'html.parser') p = re.compile("https://") soup = BeautifulSoup(website, 'html.parser') soup_links = soup.find_all("a") print(len(soup_links)) counter = 0 for link in soup_links: if link is None: # <---- Handle None value with continuing the loop continue if p.match(link.get("href", "")) is not None: # <--- Handle link element, if https is in href String. # If href is not existing. .get() returns "" and nothing is broken print("HTTPS found") print("<a href='%s'>%s</a>" % (link.get("href"), link.string) ) print("") counter = counter + 1 print(counter)
d6602
You are visiting the URL /products// so there is no value for the parameter productslug in the URL. That means your Product query fails: product = Product.objects.get(slug=productslug) because it has no (correct) value for productslug. To fix it, change your URL pattern to: (r'^products/(?P<productslug>.+)/$', 'zakai.views.SpecificProduct'), which requires at least one character for the productslug parameter. To improve it furhter you can use the following regex which only accepts - and characters (which is what a slug consists of): (r'^products/(?P<productslug>[-\w]+)/$', 'zakai.views.SpecificProduct'),
d6603
You can do what you describe in the examples with the match specification instead of host. It's another way to specify a host, or a set of hosts. For example: Match user u* host t* Hostname %hest.dev User %r This will match against a user pattern and a target host pattern. The command line will then be something like ssh u@t, resulting in this substitution: u@test.dev. Here's a snippet from the ssh debug output: debug2: checking match for 'user u* host t*' host t originally t debug3: /Users/_/.ssh/config line 2: matched 'user "u"' debug3: /Users/_/.ssh/config line 2: matched 'host "t"' debug2: match found ... debug1: Connecting to test.dev port 22. debug1: Connection established. ... u@test.dev's password: match can match against a couple of other things (and there's an option to execute a shell command) but otherwise it's just like host. The ssh client options that go in there are the same ones (e.g. you can specify and IdentityFile that will be used with the matching spec) You can read more in the man page: ssh_config A: I think you will have to create separate HostName/User entries for each possible abbreviation match. You could then use %r to access separate identity files for each user. This would allow you to skip using user@host for login at the expense of creating a more complex configuration file. You might have better luck writing a script or shell alias that unmunges your abbreviations and hands them to ssh ready to go.
d6604
"-p" in this context is part of the regexp. The regexp is looking for a match to any of the following patterns: -p 123 -p123 -p -123 -p-123 The " " and the second "-" are optional. A: BASH will treat everything after =~ operator as regex so BASH will try to match against this regex: -p' '+-?[0-9]+
d6605
I found this old helper class of mine. Maybe you can make use of it. public static class GlyphRunText { public static GlyphRun Create( string text, Typeface typeface, double emSize, Point baselineOrigin) { GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { throw new ArgumentException(string.Format( "{0}: no GlyphTypeface found", typeface.FontFamily)); } var glyphIndices = new ushort[text.Length]; var advanceWidths = new double[text.Length]; for (int i = 0; i < text.Length; i++) { var glyphIndex = glyphTypeface.CharacterToGlyphMap[text[i]]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphTypeface.AdvanceWidths[glyphIndex] * emSize; } return new GlyphRun( glyphTypeface, 0, false, emSize, glyphIndices, baselineOrigin, advanceWidths, null, null, null, null, null, null); } }
d6606
it (likely) means that your app has executed different from usual, and exposed a bug in your ref counting of the object. this type of issue can also be related to improper multithreading. executing your app to trigger the problem with zombies enabled should help you locate it. A: If you don't initialize a normal local variable to anything, its value is undefined — it could be anything. In practice, it will interpret the bit pattern that happens to lie on the stack where the variable is allocated as a value of the variable's type. In this case, the "anything" that the variable contains happens to be the address of that string.
d6607
The C-style escape for the backspace character is \b which is also the Regex escape for a word boundary. Fortunately you can put it in a character class to change the meaning: e.Handled = Regex.IsMatch(e.Text, "[0-9\b]+");
d6608
Your double-loop algorithm is somewhat slow, of order O(n**2) where n is the number of dimensions of the vector. Here is a quick way to find the closeness of the vector elements, which can be done in order O(n), just one pass through the elements. Find the maximum and the minimum of the vector elements. Just use two variables to store the maximum and minimum so far and run once through all the elements. The difference between the maximum and the minimum is called the range of the values, a commonly accepted measure of dispersion of the values. If the values are exactly equal, the range is zero which shows perfect quality. If the range is below 1e-4 then the vector is of acceptable quality. The bigger the range, the worse the equality. The code is obvious for just about any given language, so I'll leave that to you. If the fact that the range only really considers the two extreme values of the vector bothers you, you could use other measures of variation such as the interquartile range, variance, or standard deviation. But the range seems to best fit what you request.
d6609
If you use sqflite or shared_preferences simply remove all data in the main() function with clear all keys or clear the database. Then you need to write a function that will execute this part of the code once. So basically that's all. import 'package:shared_preferences/shared_preferences.dart'; void main(List<String> arguments) async { bool isDataCleared = false; if (isDataCleared == false) { final prefs = await SharedPreferences.getInstance(); prefs.clear(); isDataCleared = true; prefs.setBool('isDataCleared', isDataCleared); } else { // Do something or continue } } I hope it will help! A: You must have made the changes in your code previously for it to trigger an update whenever there is a new release automatically. There is a workaround I can think of though: You can embed some data in this new release which should be passed to the backend. If this new data is not passed, you should log them out with an error message to update the application. This approach is because the backend is the only common link between the old and new applications.
d6610
Because you have defined button by id not by class <button id="general">General</button> So change let general = document.querySelector(".general"); to let general = document.querySelector("#general"); document.addEventListener('DOMContentLoaded', function(){ let general = document.querySelector("#general"); general.addEventListener('click', function(){ window.location = "https://www.facebook.com"; return false; }); }); <!DOCTYPE html> <html lang="en"> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"> <script src="script.js" type="text/javascript"></script> </script> <link href="styles.css" rel="stylesheet"> <title>About me</title> </head> <body> <div class="title"> <h1 style="size: 22;">HOMEPAGE</h1> </div> <div class="btn-group blue"> <button id="general">General</button> <button>2</button> <button>3</button> <button>4</button> </div> <div class="float-container"> <div class="float-child" style="border: white;"> <img src="https://api.time.com/wp-content/uploads/2014/03/improving-life-health-hiking-nature.jpg" alt="Picture of Hiker" style="width: 100%; padding: 5px;"/> </div> <div class="float-child"> <p> Hello, welcome to my website. </p> </div> </div> </body> </html>
d6611
With your current setup you actually have two binaries compiled from the same source file: cli and raytracing. raytracing doesn't declare any [dependencies] so of course you're getting an error when trying to compile that. You haven't explained what you're trying to achieve, so I can't tell you the correct way to fix this problem. Generally, there's two things you can do: * *Make the root package virtual by deleting everything from ./Cargo.toml except the [workspace] section. (normal) *Ditch the ./cli/Cargo.toml and move its [dependencies] section to ./Cargo.toml. (bit weird)
d6612
A couple of problems with your code: * *You do not have a width and height specified on your html and body, without which any of descendent elements wouldn't have a reference to set their positions and/or dimensions in percent units. *You do not have dimensions (width/height) specified on your #div_parent, without which you cannot position its absolutely positioned child (which is relative to it) to the vertical center. Moreover, as you want to position your .div_child to the center of the page, why do you have a parent wrapped around it anyway. Apart from fixing the above, a trick which is usually used to align elements both horizontally and vertically is to use transform: translate to shift it back by 50%. Like this: .div_child { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); ... } Fiddle: http://jsfiddle.net/abhitalks/Lnqvqnkn/ Snippet: * { box-sizing: border-box; paddin:0; margin: 0; } html, body { height: 100%; width: 100%; } #div_parent{ height: 100%; width: 100%; background: #ccc; position: relative;} .div_child { background-color: #338BC7; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: auto; height: auto; padding: 20px; color: white; text-align: center; border: 1px solid #ccc; } <div id="div_parent"> <div class="div_child"> <p>Centered In The Middle Of The Page.</p> </div> </div> A: When I need fluid width, I prefer using this method: CSS .background { display: table; width: 100%; height: 100%; position: absolute; left: 0; top: 0; } .background > div { display: table-cell; vertical-align: middle; text-align: center; } HTML <div> <div> <p>Centered In The Middle Of The Page.</p> </div> </div> Demo on jsfiddle. Hope it works for you.
d6613
This is due to the use floating point numbers. Floating point numbers involve a binary representation, in which some numbers that can be exactly represented in decimal notation easily are not stored exactly. For example, 0.6 in decimal is (approximately) 0.111111000110011001100110011010 in binary. When converted back to decimal this number is (approximately) 0.6000000238418579. Due to this, when you store 0.6 in a float column, the value returned to you will be (slightly) different. The exact value you receive depends on the specific handling that the value has gone through, which may differ depending on a variety of factors. In order to avoid this, you would be better off using a BigDecimal, and setting the storage type on that column to :decimal.
d6614
As an example, let's start with 32-bit float array: orig = np.arange(5, dtype=np.float32) We'll convert this to a buffer of bytes: data = orig.tobytes() This is shown as: b'\x00\x00\x00\x00\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' Note the initial "b", which indicates this is a bytes object, not a string. If your data is actually a string, see at the bottom of this answer. Now that we've got our buffer of bytes containing the data in the array, we can convert this back to an array of 32-bit floating-point values with: out = np.frombuffer(data, dtype=np.float32) (out is now identical to orig). If data is a string, you need to first cast it to a bytes buffer, which you can do with data = bytes(data, 'latin1') The "latin1" part is the encoding. This encoding seems to not change any data when converting from string to bytes.
d6615
rack-ssl-enforcer gem will help you
d6616
It turned out that the delay was due to a combination of: * *poor container's file system behaviour because bind-mount'ed to the local machine's one (Linux container on Windows machine) *project consisting of a large number of (small, actually) source files (~10,000) *git information displayed on the prompt To solve the issue, I ended up disabling git's processing every time (as described at https://giters.com/ohmyzsh/ohmyzsh/issues/9848 ), by adding a postCreateCommand in devcontainer.json file. This is the content of my devcontainer.json: "postCreateCommand": "git config --global oh-my-zsh.hide-info 1 && git config --global oh-my-zsh.hide-status 1 && git config --global oh-my-zsh.hide-dirty 1" A: With recent vscode devcontainers, I found that I needed to do something like this instead, as bash appears to be the default shell, instead of zsh. "postCreateCommand": "git config --global codespaces-theme.hide-info 1 && git config --global codespaces-theme.hide-status 1 && git config --global codespaces-theme.hide-dirty 1" See: https://github.com/microsoft/vscode-dev-containers/issues/1196 There might be additional changes coming as well, based on https://github.com/devcontainers/features/pull/326
d6617
try this [otherNav.view insertSubview:shadowImageView belowSubview:animatedActionView]; because the first parameter must be an View or a subclass of uiview in your case you try to pass an UIImage who itsn't an UIView or subclass of UIview
d6618
You don't need slim. Just irb the code: name = (defined?(name) ? name : 'tags') p name #=> nil It does not work, because you implicitly define name on the left side of the statement name = .... So when Ruby interpreter evaluates defined?(name) it gives truly result. I think you already get the answer: unless defined?(name) name = 'tags' end or shorter: name ||= 'tags'
d6619
Without having the recaptcha code, you can style it with this CSS: #recaptcha_response_field { background: #fff !important; } OR you can use: input[type=text] { background-color: #fff !important; } A: https://developers.google.com/recaptcha/docs/display#render_param there is a light dark setting
d6620
@MathAng, It looks like the height of your A and LI aren't matching the same height, the default height of the LI tag is 26 pixels in height. But at your CSS you're saying that it must be 10 pixels for the A tag. What I prefer is or use: .scrollable-menu-brands li a { padding-top: 0px; } instead of: .scrollable-menu-brands li a { height: 10px; padding-top: 0px; } Or add height: 10px; to your LI tag, like so: .scrollable-menu-brands li { height: 10px; } Hopefully this does the trick for you!
d6621
You can use $(document).ready(); $(document).ready(function() { setTimeout(function() { your_func(); }, 1000); }); A: You may use $( document ).ready(); for that problem: $( document ).ready(function() { setTimeout(function() { console.log( "ready!" ); }, 1000); }); A: Your solution works well, don't need to change to document ready <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(window).bind("load", function() { setTimeout(function() { console.log('Hey'); }, 1000); }); </script> Notice the differences between the events: The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
d6622
Maybe this will help. You can use initialCommands key in sbt to do this So in build.sbt if you put initialCommands in console := """import my.project._ val myObj = MyObject("Hello", "World") """ after you type 'console', you can start using myObj or the classes in my.project http://www.scala-sbt.org/0.13.5/docs/Howto/scala.html#initial A: Yes you can, but you cannot use modified code without reloading the REPL. Just run: sbt "~ ; console" And then import your classes with import your.package._ and use them from there. If you make any changes to your library code, just hit CTRL+D or :quit and it will detect file changes, compile them and enter the REPL again. You can then use the history (navigating with the arrows up/down) to execute anything from the previous session again.
d6623
Problem You are missing how to pass the argument to mysqli_fetch_array(). Solution Therefore, this line: if(mysqli_query($cons, $result)) { should be if($res = mysqli_query($cons, $result)) { // assign the return value of mysqli_query to $res (FWIW, I'd go with $res = mysqli_query($cons, $result); then do if($res) {.) And then do while($row = mysqli_fetch_array($res)) // pass $res to mysqli_fetch_array instead of the query itself Why? You were giving to mysqli_fetch_array() - as an argument - the string that contains your query. That's not how it works. You should pass the return value of mysqli_query() instead. Therefore, you could also write: while($row = mysqli_fetch_array(mysqli_query($cons, $result))) {} (but it's not adviced, it is just to show you how it works). A: As mentioned in the comment, you need to set a $result from your query and use that in your loop instead. $qry ="SELECT * FROM report"; $result = mysqli_query($cons, $qry); if ($result){ while($row = mysqli_fetch_array($result)){ } } A: you can write like this:- $query = mysqli_query($cons,"SELECT * FROM items WHERE id = '$id'"); if (mysqli_num_rows($query) > 0) { while($row = mysqli_fetch_assoc($query)) { $result=$row; } }
d6624
decodeURIComponent is the key: decodeURIComponent('VehicleId%20eq%20%272415%27&'); // "VehicleId eq '2415'&" That's definitely not a proper ID (not to mention you're trying to do $filter=VehicleId=2135, of course that will break the query string, find a way to encode that value). You should probably make those IDs a bit more standard as then you'd get more accurate results. A: You could use regexp to parse the VehicleId, such as : var tab=unescape(location.search).match(/VehicleId eq '(\d+)'/); if (tab) { var id=tab[1]; }
d6625
I don't have the exact sql, but you will need to query the systables and syscolumns tables, which have all of the information you need to create the data dictionary. A: I would use the "information schema" views. Here are 2 of the most useful views: SELECT * FROM INFORMATION_SCHEMA.Tables SELECT * FROM INFORMATION_SCHEMA.Columns A: Instead of doing this yourself, you could take a look at some SQL Server documentation tools/scripts: http://www.mssqltips.com/tip.asp?tip=1250 http://www.red-gate.com/products/SQL_Doc/index.htm http://www.mssqltips.com/tip.asp?tip=1499 A: https://www.csvreader.com/posts/data_dictionary.php SELECT d.[primary key], d.[foreign key], CASE WHEN LEN(d.[column]) = 0 THEN d.[table] ELSE '' END AS [table], d.[column], CAST(d.[description] AS VARCHAR(MAX)) AS [description], d.[data type], d.nullable, d.[identity], d.[default] FROM ( SELECT '' AS [primary key], '' AS [foreign key], s.[name] AS [schema], CASE WHEN s.[name] = 'dbo' THEN t.[name] ELSE s.[name] + '.' + t.[name] END AS [table], '' AS [column], ISNULL(RTRIM(CAST(ep.[value] AS NVARCHAR(4000))), '') AS [description], '' AS [data type], '' AS nullable, '' AS [identity], '' AS [default], NULL AS column_id FROM sys.tables t INNER JOIN sys.schemas s ON s.[schema_id] = t.[schema_id] -- get description of table, if available LEFT OUTER JOIN sys.extended_properties ep ON ep.major_id = t.[object_id] AND ep.minor_id = 0 AND ep.name = 'MS_Description' AND ep.class = 1 WHERE t.is_ms_shipped = 0 AND NOT EXISTS ( SELECT * FROM sys.extended_properties ms WHERE ms.major_id = t.[object_id] AND ms.minor_id = 0 AND ms.class = 1 AND ms.[name] = 'microsoft_database_tools_support' ) UNION ALL SELECT CASE WHEN pk.column_id IS NOT NULL THEN 'PK' ELSE '' END AS [primary key], CASE WHEN fk.primary_table IS NOT NULL THEN fk.primary_table + '.' + fk.primary_column ELSE '' END AS [foreign key], s.[name] AS [schema], CASE WHEN s.[name] = 'dbo' THEN t.[name] ELSE s.[name] + '.' + t.[name] END AS [table], c.[name] AS [column], ISNULL(RTRIM(CAST(ep.[value] AS NVARCHAR(4000))), '') AS [description], CASE WHEN uty.[name] IS NOT NULL THEN uty.[name] ELSE '' END + CASE WHEN uty.[name] IS NOT NULL AND sty.[name] IS NOT NULL THEN '(' ELSE '' END + CASE WHEN sty.[name] IS NOT NULL THEN sty.[name] ELSE '' END + CASE WHEN sty.[name] IN ('char', 'nchar', 'varchar', 'nvarchar', 'binary', 'varbinary') THEN '(' + CASE WHEN c.max_length = -1 THEN 'max' ELSE CASE WHEN sty.[name] IN ('nchar', 'nvarchar') THEN CAST(c.max_length / 2 AS VARCHAR(MAX)) ELSE CAST(c.max_length AS VARCHAR(MAX)) END END + ')' WHEN sty.[name] IN ('numeric', 'decimal') THEN '(' + CAST(c.precision AS VARCHAR(MAX)) + ', ' + CAST(c.scale AS VARCHAR(MAX)) + ')' ELSE '' END + CASE WHEN uty.[name] IS NOT NULL AND sty.[name] IS NOT NULL THEN ')' ELSE '' END AS [data type], CASE WHEN c.is_nullable = 1 THEN 'Y' ELSE '' END AS nullable, CASE WHEN c.is_identity = 1 THEN 'Y' ELSE '' END AS [identity], ISNULL(dc.[definition], '') AS [default], c.column_id FROM sys.columns c INNER JOIN sys.tables t ON t.[object_id] = c.[object_id] INNER JOIN sys.schemas s ON s.[schema_id] = t.[schema_id] -- get name of user data type LEFT OUTER JOIN sys.types uty ON uty.system_type_id = c.system_type_id AND uty.user_type_id = c.user_type_id AND c.user_type_id <> c.system_type_id -- get name of system data type LEFT OUTER JOIN sys.types sty ON sty.system_type_id = c.system_type_id AND sty.user_type_id = c.system_type_id -- get description of column, if available LEFT OUTER JOIN sys.extended_properties ep ON ep.major_id = t.[object_id] AND ep.minor_id = c.column_id AND ep.[name] = 'MS_Description' AND ep.[class] = 1 -- get default's code text LEFT OUTER JOIN sys.default_constraints dc ON dc.parent_object_id = t.[object_id] AND dc.parent_column_id = c.column_id -- check for inclusion in primary key LEFT OUTER JOIN ( SELECT ic.column_id, i.[object_id] FROM sys.indexes i INNER JOIN sys.index_columns ic ON ic.index_id = i.index_id AND ic.[object_id] = i.[object_id] WHERE i.is_primary_key = 1 ) pk ON pk.column_id = c.column_id AND pk.[object_id] = t.[object_id] -- check for inclusion in foreign key LEFT OUTER JOIN ( SELECT CASE WHEN s.[name] = 'dbo' THEN pk.[name] ELSE s.[name] + '.' + pk.[name] END AS primary_table, pkc.[name] as primary_column, fkc.parent_object_id, fkc.parent_column_id FROM sys.foreign_keys fk INNER JOIN sys.tables pk ON fk.referenced_object_id = pk.[object_id] INNER JOIN sys.schemas s ON s.[schema_id] = pk.[schema_id] INNER JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.[object_id] AND fkc.referenced_object_id = pk.[object_id] INNER JOIN sys.columns pkc ON pkc.[object_id] = pk.[object_id] AND pkc.column_id = fkc.referenced_column_id ) fk ON fk.parent_object_id = t.[object_id] AND fk.parent_column_id = c.column_id WHERE t.is_ms_shipped = 0 AND NOT EXISTS ( SELECT * FROM sys.extended_properties ms WHERE ms.major_id = t.[object_id] AND ms.minor_id = 0 AND ms.class = 1 AND ms.[name] = 'microsoft_database_tools_support' ) ) d ORDER BY d.[schema], d.[table], d.column_id;
d6626
Let's remember however that having ssh support in a container is typically an anti-pattern (unless it's your container only 'concern' but then what would be the point of being able to ssh in. Refer to http://techblog.constantcontact.com/devops/a-tale-of-three-docker-anti-patterns/ for information about that anti-pattern A: nsenter could work for you. First ssh to the host and then nsenter to the container. PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)` nsenter --target $PID --mount --uts --ipc --net --pid source http://jpetazzo.github.io/2014/06/23/docker-ssh-considered-evil/ A: Judging by the comments, you might be looking for a solution like dockersh. dockersh is used as a login shell, and lets you place every user that logins to your instance into an isolated container. This probably won't let you use sftp though. Note that dockersh includes security warnings in their README, which you'll certainly want to review: WARNING: Whilst this project tries to make users inside containers have lowered privileges and drops capabilities to limit users ability to escalate their privilege level, it is not certain to be completely secure. Notably when Docker adds user namespace support, this can be used to further lock down privileges. A: Some months ago, I helped my like this. It's not nice, but works. But pub-key auth needs to be used. Script which gets called via command in .ssh/authorized_keys #!/usr/bin/python import os import sys import subprocess cmd=['ssh', 'user@localhost:2222'] if not 'SSH_ORIGINAL_COMMAND' in os.environ: cmd.extend(sys.argv[1:]) else: cmd.append(os.environ['SSH_ORIGINAL_COMMAND']) sys.exit(subprocess.call(cmd)) file system_foo@server: .ssh/authorized_keys command="/home/modwork/bin/ssh-wrapper.py" ssh-rsa AAAAB3NzaC1yc2EAAAAB... If the remote system does ssh system_foo@server the SSH-Daemon at server executes the comand given in .ssh/authorized_keys. This command does a ssh to a different ssh-daemon. In the docker container, there needs to run ssh-daemon which listens on port 2222.
d6627
Your Controller catches and redirects to the same url: @RequestMapping(value="/login", method=RequestMethod.GET) public String loadForm(Model model) { model.addAttribute("user", new User()); return "redirect:/login"; } Also, your SecurityConfig defines this: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { ... .loginPage("/login") } .loginPage()'s javadoc says this: login page to redirect to if authentication is required So, any secured request made or direct access to /login will: * *redirect to /login because of .loginPage("/login") in your SecurityConfig *which you then catch with @RequestMapping(value="/login" *then redirect to /login with "redirect:/login" *then re-catch and redirect at will.
d6628
EnumPrinters to get the list of printers, EnumJobs to get a list of jobs for that printer. GetJob to get info on a specific job and SetJob to change the settings for that job (pause or cancel it). See more in the Printing and Print Spooler References. .NET has the PrintQueue and PrintServer classes. A: Following URLs may be of interest to you, http://www.codeproject.com/KB/printing/printwatchvbnet.aspx and http://www.codeproject.com/KB/printing/EMFSpoolViewer.aspx
d6629
Filter the data in list before passing to Adapter ArrayList<Dbbean> list = yourlist; Create a filtered list ArrayList<Dbbean> filteredList = new ArrayList<>(); for(Dbbean dbean : list){ if(dbean.blename.startsWith("Dev") filteredList.add(dbean); } Pass filtered list to Adapter EvelistAdapter adapter = new EvelistAdaptr(this,filteredList); yourRecyclerView.setAdapter(adapter); A: Do not call removeItem inside onBindViewHolder directly. If you want to remove item then just do it before setting adapter. Provide the filtered ArrayList<Dbbean> list to adpater in first place .Later you can remove item from adapter on any specified action. Do not use notifyDataSetChanged() until you are not sure which dataset is changed. Use : notifyItemRemoved() for a particular item removed for position . A: this is causing the problem you are just forcefully making changes to the onBindViewHolder which is drawing something right now again to redraw. @Override public void onBindViewHolder(ViewHolder holder, final int position) { if(adapterlist.get(position).blename.startsWith("Dev")) { holder.tv_country.setText(adapterlist.get(position).blename); }else{ removeAt(position); } } public void removeAt(int position) { adapterlist.remove(position); notifyDataSetChanged(); } suggestion better check this condition and remove the items when you are about to notify the adapter from fragment or activity.
d6630
You fetch the exact date, it seems like you want to fetch the week: SELECT COUNT(distinct ip ) AS uni, ( date_added ) AS wday, WEEK( FROM_UNIXTIME( date_added ) ) AS cusotms A: Here is the solution: SELECT COUNT( DISTINCT ip ) AS uni, ( date_added ) AS wday, FROM_UNIXTIME( date_added ) AS cusotms FROM `site_stats` WHERE FROM_UNIXTIME( date_added ) >= CURDATE( ) - INTERVAL DAYOFWEEK( CURDATE( ) ) -3WEEK GROUP BY WEEK( FROM_UNIXTIME( date_added ) ) LIMIT 0 , 30 hope it helps :)
d6631
You can put this code in separate method (https://refactoring.com/catalog/extractFunction.html) and write it like this: public void DoSomeStuff() { if((example_A >= 0) && (condition_A)) return; if((example_B >= )) && (condition_B)) { doSomething(); return; } doAnything(); } A: If I understand you right, the line removeThisClass(); should be removed, and you don't want to be left with an empty block like this: if((example_A >= 0) && (condition_A)) { } else if((example_B >= )) && (condition_B)) { doSomething(); } else { doAnything(); } In order to not do the "A" tests twice, you need to negate the condition, e.g. like this: if ((example_A < 0) || ! (condition_A)) { if ((example_B >= )) && (condition_B)) { doSomething(); } else { doAnything(); } } Your refactored code is wrong, because if the "A" condition is true, the original code would execute removeThisClass();, which means it should now do nothing, but your code will call doAnything(); when "A" is true. A: You can put in a comment. Sonar should accept that and it could also help the reader. void doSomething() { for (int i = 0; i < 42; i++) // Non-Compliant { } for (int i = 0; i < 42; i++); // Compliant if (myVar == 4) // Compliant - contains a comment { // Do nothing because of X and Y } else // Compliant { doSomething(); } try // Non-Compliant { } catch (Exception e) // Compliant { // Ignore } }
d6632
There is an issue discussed in the repository, which hints at a possible problem cause. A broken connection error may be fixed with hard-refreshing the page. Modifying the templates and the content pages reloads after that. Check the browser console to see what the actual issue is. Some actions require manual restart. For example, renaming the template files or adding components will cause an error. Changing the config file also does not trigger the reload. A: Add the following to config.js module.exports = { host: 'localhost', ... A: just delete the those folders and run again. .vuepress/.cache .vuepress/.temp
d6633
There are two ways you could do this really. One is through code and the other is through the administrators panel. I'm assuming based on the question you are interested in the back end solution. This involves creating two unique menu items with the same name (alias' would need to be different). One which is only visible to logged in users, which points to the component view desired. The second menu is only visible to guests, and will point to the user log in component view with a redirect url set to component view you wish them to be redirected to. I attached a link below to an article explaining how to only show menu items to guests and have them hide when users are logged in. http://docs.joomla.org/How_do_you_hide_something_from_logged_in_users%3F
d6634
I am not sure about the EventBridge filter for the purpose but found a very easy technique from the link below: https://aws.amazon.com/premiumsupport/knowledge-center/eventbridge-create-custom-event-pattern/ So basically you have to let the event you are targeting to be in your cloudtrail or get teh email notifications and then copy and paste the only wanted part. So for my problem I did this and it is workng exactly as I wanted. { "source": ["aws.iam"], "detail-type": ["AWS API Call via CloudTrail"], "detail": { "eventSource": ["iam.amazonaws.com"], "eventName": ["AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy", "DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy", "PutGroupPolicy", "PutRolePolicy", "PutUserPolicy"], "requestParameters": { "roleName": ["testone"] } } } A: You would use an EventBridge filter for you rule so that it only matches the specific role.
d6635
You can use crosstab to get the dummies, then matrix product to see cooccurrences: s = pd.crosstab(df['ID'],df['VALUE']) pair_intersection = s.T @ s all_three = s.ne(0).all(1) Then, pair_intersection looks like: VALUE Today Tomorrow Yesterday VALUE Today 3 2 2 Tomorrow 2 4 1 Yesterday 2 1 2 Then counts of two overlapping groups can be extracted using pair_intersection.at['Today', 'Tomorrow']. all_three is ID A False B False C False D False E True dtype: bool And thus the number of instances that fall in all three groups is sum(all_three)
d6636
I was able to solve a similar problem. I installed pdftotext with a brew cask. The installation was done with the following command $ brew cask install pdftotext $ pdftotext -v pdftotext version 3.03 Copyright 1996-2011 Glyph & Cog, LLC and place the xpdfrc/language support packages in the following directory I did. ls /usr/local/etc/xpdfrc /usr/local/etc/xpdfrc I downloaded the Japanese Language Pack from here. https://www.xpdfreader.com/download.html $ tree /usr/local/share/xpdf /usr/local/share/xpdf └── japanese ├── Adobe-Japan1.cidToUnicode ├── CMap │ ├── 78-EUC-H │ ├── 78-EUC-V │ ├── 78-H │ ├── 78-RKSJ-H │ ├── 78-RKSJ-V │ ├── 78-V │ ├── 78ms-RKSJ-H │ ├── 78ms-RKSJ-V │ ├── 83pv-RKSJ-H │ ├── 90ms-RKSJ-H │ ├── 90ms-RKSJ-UCS2 │ ├── 90ms-RKSJ-V │ ├── 90msp-RKSJ-H │ ├── 90msp-RKSJ-V │ ├── 90pv-RKSJ-H │ ├── 90pv-RKSJ-UCS2 │ ├── 90pv-RKSJ-UCS2C │ ├── 90pv-RKSJ-V │ ├── Add-H │ ├── Add-RKSJ-H │ ├── Add-RKSJ-V │ ├── Add-V │ ├── Adobe-Japan1-0 │ ├── Adobe-Japan1-1 │ ├── Adobe-Japan1-2 │ ├── Adobe-Japan1-3 │ ├── Adobe-Japan1-4 │ ├── Adobe-Japan1-5 │ ├── Adobe-Japan1-6 │ ├── Adobe-Japan1-UCS2 │ ├── EUC-H │ ├── EUC-V │ ├── Ext-H │ ├── Ext-RKSJ-H │ ├── Ext-RKSJ-V │ ├── Ext-V │ ├── H │ ├── Hankaku │ ├── Hiragana │ ├── Katakana │ ├── NWP-H │ ├── NWP-V │ ├── RKSJ-H │ ├── RKSJ-V │ ├── Roman │ ├── UniJIS-UCS2-H │ ├── UniJIS-UCS2-HW-H │ ├── UniJIS-UCS2-HW-V │ ├── UniJIS-UCS2-V │ ├── UniJIS-UTF16-H │ ├── UniJIS-UTF16-V │ ├── UniJIS-UTF32-H │ ├── UniJIS-UTF32-V │ ├── UniJIS-UTF8-H │ ├── UniJIS-UTF8-V │ ├── UniJIS2004-UTF16-H │ ├── UniJIS2004-UTF16-V │ ├── UniJIS2004-UTF32-H │ ├── UniJIS2004-UTF32-V │ ├── UniJIS2004-UTF8-H │ ├── UniJIS2004-UTF8-V │ ├── UniJISPro-UCS2-HW-V │ ├── UniJISPro-UCS2-V │ ├── UniJISPro-UTF8-V │ ├── UniJISX0213-UTF32-H │ ├── UniJISX0213-UTF32-V │ ├── UniJISX02132004-UTF32-H │ ├── UniJISX02132004-UTF32-V │ ├── V │ └── WP-Symbol ├── EUC-JP.unicodeMap ├── ISO-2022-JP.unicodeMap ├── README ├── Shift-JIS.unicodeMap └── add-to-xpdfrc 2 directories, 76 files The contents of xpdfrc are as follows $ cat /usr/local/etc/xpdfrc cidToUnicode Adobe-Japan1 /usr/local/share/xpdf/japanese/Adobe-Japan1.cidToUnicode unicodeMap ISO-2022-JP /usr/local/share/xpdf/japanese/ISO-2022-JP.unicodeMap unicodeMap EUC-JP /usr/local/share/xpdf/japanese/EUC-JP.unicodeMap unicodeMap Shift-JIS /usr/local/share/xpdf/japanese/Shift-JIS.unicodeMap cMapDir Adobe-Japan1 /usr/local/share/xpdf/japanese/CMap toUnicodeDir /usr/local/share/xpdf/japanese/CMap
d6637
I don't see anyway to avoid the use of node but you can improve the information returned by it by * *compiling the OCaml with the debug info (add -g option to ocamlc) *add the options --debuginfo --sourcemap --pretty to the invocation of js_of_ocaml In your example, you'd have to do ocamlfind ocamlc -g -package js_of_ocaml.ppx -linkpkg cubes.ml -o T js_of_ocaml --debuginfo --sourcemap --pretty T -o cubes.js
d6638
Heroku's Logplex contains all logging statements from your application - there is no filtering of any kind. By default, Rails does not log SQL statements in production so you'll need to bump your log level in production.rb to a level that is more suitable. http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels
d6639
You can pass argument --runner SparkRunner to the pipeline launcher to use spark as the underlying runner. Also, Please share what language of Beam SDK you are using. Python and java have some what different ways to run on Spark via Beam.
d6640
Join the tables SELECT b.*, s.services FROM service_booking AS b JOIN services AS s ON s.service_id = b.service_id
d6641
Select 'Plugins'->'Language Server'->'Settings' and uncheck the box that says 'Display Diagnostics' at the bottom of the page then click OK.
d6642
FYI, here's what Microsoft had to say about it: "It’s not really a bug. Script blocks are valid attribute arguments – e.g. ValidateScriptBlock wouldn’t work very well otherwise. Attribute arguments are always converted to the parameter type. In the case of Mandatory – it takes a bool, and any time you convert a ScriptBlock to bool, you’ll get the value $true. You never invoke a script block to do a conversion." A: For the second question, you can always validate the value within the script. Just set the value to the environment variable as the default value. When I tried the validation with ($foo -eq $null) it didn't work, so I switched it to ($foo -eq ""). Here is a sample I tested to get what you were asking for: function Test-Mandatory { [CmdletBinding()] param( [string] $foo = $Env:TEST_PARAM ) begin { if ($foo -eq "") { $foo = Read-Host "Please enter foo: " } } #end begin process { Write-Host $foo } #end process } #end function As for the mandatory question, I believe if you assign a default value (even if it is empty), it will satisfy the mandatory assignment. When it goes to check if the value is present, since it was assigned a value, the mandatory checks true, allowing it to move on. A: Of note, this doesn't work as you would expect... I would expect $foo to be marked as mandatory only if $Env:TEST_PARAM does not exist. However, even when $Env:TEST_PARAM exists, the shell prompts :( function Test-Mandatory { [CmdletBinding()] param( [Parameter(Mandatory = { [string]::IsNullOrEmpty($Env:TEST_PARAM) })] [string] $foo ) if (!$PsBoundParameters.foo) { $foo = $Env:TEST_PARAM } Write-Host $foo }
d6643
I assume you are using the Workbooks.OpenText method to open the file, i.e. something like: Workbooks.OpenText Filename:="C:\Temp\myFile.txt", _ Origin:=xlWindows, _ StartRow:=1, _ DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(6, 1), Array(11, 1), Array(46, 1), Array(51, 1), Array(57, 1), Array(71, 1), Array(79, 1), Array(86, 1), Array(96, 1), Array(100, 1), Array(107, 1), Array(114, 1), Array(123, 1), Array(132, 1), Array(141, 1)), _ TrailingMinusNumbers:=True If so, you can just drop off the FieldInfo parameter and force Excel to make its own guess: Workbooks.OpenText Filename:="C:\Temp\myFile.txt", _ Origin:=xlWindows, _ StartRow:=1, _ DataType:=xlFixedWidth, _ TrailingMinusNumbers:=True
d6644
You need to register Data observer to listen to data changes from sync adapter. mRecyclerViewAdapter.registerAdapterDataObserver(myObserver); RecyclerView.AdapterDataObserver are a result of which notify methods you call. So for instance if you call notifyItemInserted() after you add an item to your adapter then onItemRangeInserted() will get called A more detailed example protected void setupRecyclerView() { mAdapter = new MyAdapter(mItemList); mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { super.onChanged(); checkAdapterIsEmpty(); } }); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setHasFixedSize(true); mRecyclerView.setAdapter(mAdapter); checkAdapterIsEmpty(); }` The adapter may publish a variety of events describing specific changes. Not all adapters may support all change types and some may fall back to a generic "something changed" event if more specific data is not available.
d6645
I tried your code, and it worked well without 'a+' option when open the text file. Your code shows nothing because you opened file as a 'wrting' mode. You should give the option as 'r' or 'r+' or just leave it as default. 'r' : open for reading (default) 'a' : open for writing, appending to the end of the file if it exists. '+' : open a disk file for updating (reading and writing) Try: stats = open('stats.txt') # select #stats = open('stats.txt','r') # one of #stats = open('stats.txt','r+') # these statheadings = stats.readlines() print(statheadings) It will work as well, and the result: ['404: Not Found\n'] If you want to check only a value, you can add index also. Print only the last line: print(satheadings[-1]) Result: 404: Not Found A: Rather than attempting to save the file to the disk first, you can just open it directly: import requests response = requests.get('https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv') print(response.text) However, the URL that you're trying to access is giving me a 404. Is this because it's in a private repository? If so, you'll want to store it somewhere where it's publicly accessible so your program can reach it (or otherwise set up a more complicated authentication scheme).
d6646
It seems you're using python 2 so I'm using this old python 2 super() syntax where you have to specify the class and the instance, although it would work in python 3 as well. In python 3 you could also use the shorter super() form without parameters. For multiple inheritance to work is important that the grandparent class __init__ signature matches the signature of all siblings for that method. To do that, define a common parent class (MyParent in this example) whose __init__ has the same parameter list as all the childs. It will take care of calling the object's __init__ that doesn't take any parameter, for us. from __future__ import print_function class MyParent(object): def __init__(self, s): super(MyParent, self).__init__() class A(MyParent): def __init__(self, s): self.a = "a" super(A, self).__init__(s) def testA(self, x): print(x) class B(MyParent): def __init__(self, s): self.b = "b" super(B, self).__init__(s) def testA(self,x): print(x) C = type('C', (A, B), {}) x = C("test") print(x.b) You can define as many children to MyParent as you want, and then all __init__ methods will be called, provided you used super() correctly.
d6647
It is fine to access $scope in that function. .controller("myCtryl", function($scope, $http) { $scope.functionA = function(){ $scope.data = "some data"; } $scope.functionB = function(){ $scope.data //this id valid } } A: You can just access $scope.data in functionB the same way you access it in functionA. It will work. The $scope variable is in the same lexical scope for both functions.
d6648
Prior to PHP 5.5, empty() function can only support strings. Any other input provided to it like: a function call e.g. if (empty(myfunction()) { // ... } would result parse error. As per documentation: Note: Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false. Better way, get your $content variable first and then check if it is not empty. Rather than initialising it and checking its emptiness simultaneously. You can separate the if statement in two parts like this: if ($content = Cache::get($md5) && !empty($content)) { return unserialize($content); } A: Try this, if (!empty($content) && $content = Cache::get($md5)) { return unserialize($content); } OR : To get easy readability if (!empty($content){ if($content = Cache::get($md5)){ return unserialize($content); } }
d6649
By Jquery you can do this way $.ajax({ url: 'http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet', type: 'GET', success: function (responce) { // code to append into your table }, error: function (jqXHR, textStatus, errorThrown) { } }); A: I can't show you the whole code snippet. Anyway, hope this help for you. <table id="my_table" border='1'> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </table> <script> var response = [{ "column_1":"90", "column_2":"Abc", "column_3":"50" }, { "column_1":"68", "column_2":"Cde", "column_3":"90" }]; $(function() { $.each(response, function(i, item) { $('<tr>').append( $('<td>').text(item.column_1), $('<td>').text(item.column_2), $('<td>').text(item.column_3) ).appendTo('#my_table'); }); }); </script> A: As mentioned I believe you are using codeigniter as your php framework. To accomplish your task you need follow below steps : 1.) In view file for eg. myview.php add this <div id="mydata"></div> <script> $.ajax({ type: "GET", url: "http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet", beforeSend: function(){ $("#mydata").html('<span style="color:green;tex-align:center;">Connecting....</span>'); }, success: function(data){ if(data!="") { $("#mydata").html(data); }else{ $("#mydata").html('<span style="color:red;tex-align:center;">No data found !</span>'); } } }); </script> 2.)To save the data in the database either create event handler such as button clicks or you can try using setInterval function. <button id="mybt" onclick="save_to_db()">Save to DB</button> <script> function save_to_db(){ //code to format data to insert into the table $.ajax({ type:"POST", url:"/mycontroller/insert_function" // data:"data_to_insert", success:function(data){ if(data=="ok"){ console.log("inserted successfully"); } } }) } </script> A: In your HTML tag <table id="data"> </table> In your script tag var url="http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet"; $.ajax({ type: "GET", url: url, cache: false, // data: obj_data, success: function(res){ console.log("data",res); //if you want to remove some feild then delete from below array var feilds =["sanggar_id","kode_pengelolaan","nama","alamat_jalan","desa_kelurahan","kecamatan","kabupaten_kota","propinsi","lintang","bujur","tahun_berdiri","luas_tanah"]; var html=''; html+=`<thead> <tr>`; $.each(feilds,function(key,val){ html+=`<th class="${val}">${val}</th>`; }) html+=`</tr> </thead> <tbody>`; $.each(res.data,function(key,val){ html+=`<tr>`; $.each(feilds,function(aaa,feild){ html+=`<th class="${val[feild]}">${val[feild]}</th>`; }) html+=`</tr>`; }) html+=`</tr> </tbody>`; $("#data").html(html); }, });
d6650
You need to cancel the setTimeout() if the arrows are clicked before it fires so you don't get multiple timers going at once (which will certainly exhibit weirdness). I don't follow exactly what you're trying to do on the arrows, but this code should manage the timers: var intervalId = setInterval(switchLeft, 4000); var timeoutId; $("#leftarrow, #rightarrow").click(function() { // clear any relevant timers that might be going // so we never get multiple timers going clearInterval(intervalId); clearTimeout(timeoutId); // restart the interval in 8 seconds timeoutId = setTimeout(function() { intervalId = window.setInterval(switchLeft, 4000) }, 8000); });
d6651
This exception is the result of class identity crisis . You cannot cast between class loaders. As mentioned this site: Other types of confusion are also possible when using multiple class loaders. Figure 2 shows an example of a class identity crisis that results when an interface and associated implementation are each loaded by two separate class loaders. Even though the names and binary implementations of the interfaces and classes are the same, an instance of the class from one loader cannot be recognized as implementing the interface from the other loader. EDIT Although the solution is found out by the OP but I would like to give my two cents. The confusion which is leading to the nonrecognition of instance of the class from other ClassLoader could easily be resolved if that class is moved into the System class loader's space. And making System Class Loader to be the parent of newly created ClassLoaders. This would cause the different ClassLoaders to share the same class. This could be achieved by URLClassLoader(URL[] urls,ClassLoader parent) in following way: URL[] urls = { new URL("jar:file:" + pathToJar +"!/") }; ClassLoader cl = new URLClassLoader(urls,ClassLoader.getSystemClassLoader());
d6652
I'm using the JsonSlurper it looks quite simple and OS independent: import groovy.json.JsonSlurper String url = "http://<SONAR_URL>/api/qualitygates/project_status?projectKey=first" def json = new JsonSlurper().parseText(url.toURL().text) print json['projectStatus']['status'] A: Can't you just do new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text A: Java has had a proper HTTP Client in the standard library since Java 9. Here's how you can use that from a Gradle script (Groovy): import groovy.json.JsonSlurper import java.net.http.* import static java.nio.charset.StandardCharsets.UTF_8 tasks.register('hello') { def url = new URL("http://myserver.com:8983/solr/select?q=*&wt=json") def req = HttpRequest.newBuilder(url.toURI()).GET().build() def res = HttpClient.newHttpClient() .send(req, HttpResponse.BodyHandlers.ofString(UTF_8)) def parsedJson = new JsonSlurper().parseText(res.body()) println parsedJson } A: this is working guys import java.io.* import groovyx.net.http.HTTPBuilder import groovyx.net.http.EncoderRegistry import static groovyx.net.http.Method.* import static groovyx.net.http.ContentType.* buildscript { repositories { mavenCentral() } dependencies { classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2' } } task hello { def http = new groovyx.net.http.HTTPBuilder("http://local.com:8983/solr/update/json") http.request(POST, JSON ) { req -> req.body{ } response.success = { resp, reader -> println "$resp.statusLine Respond rec" } } } A: This question is ranking so well on search engines that I keep stumbling on it. However, as others commented, I don't really like the accepted answer because it relies on curl. So here is a complete example w/o any prerequisite (no plugin, no curl, ...): import groovy.json.JsonSlurper import groovy.json.JsonOutput task getExample { doLast { def req = new URL('https://jsonplaceholder.typicode.com/posts/1').openConnection() logger.quiet "Status code: ${req.getResponseCode()}" def resp = new JsonSlurper().parseText(req.getInputStream().getText()) logger.quiet "Response: ${resp}" } } task postExample { doLast { def body = [title: "foo", body: "bar", userId: 1] def req = new URL('https://jsonplaceholder.typicode.com/posts').openConnection() req.setRequestMethod("POST") req.setRequestProperty("Content-Type", "application/json; charset=UTF-8") req.setDoOutput(true) req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8")) logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done on first read def resp = new JsonSlurper().parseText(req.getInputStream().getText()) logger.quiet "Response: ${resp}" } } You can run this on your box as they use a public development API. A: The easiest way to call REST from groovy without external libraries is executing CURL. Here's an example of calling Artifactory, getting JSON back and parsing it: import groovy.json.JsonSlurper task hello { def p = ['curl', '-u', '"admin:password"', "\"http://localhost:8081/api/storage/libs-release-local?list&deep=1\""].execute() def json = new JsonSlurper().parseText(p.text) } A: The solution using Kotlin DSL and Fuel HTTP Client: import com.github.kittinunf.fuel.httpPost import com.github.kittinunf.result.Result buildscript { dependencies { "classpath"("com.github.kittinunf.fuel:fuel:2.3.1") } } tasks { register("post") { val (request, response, result) = "https://httpbin.org/post".httpPost().responseString() if (result is Result.Success) { println(result.get()) } } }
d6653
use find() $(this).find('.delete-status-update-link').show(); A: You have issues with your code, (function extra ( before function and after ): $('.cycle-status-update') .on('mouseenter', (function(){ $(this).closest('.delete-status-update-link').show(); }))//<----here .on('mouseleave', (function(){ //<--before function $(this).closest('.delete-status-update-link').hide(); })) //^----here try this: $('.cycle-status-update').on('mouseenter', function(){ $('.delete-status-update-link').show(); }).on('mouseleave', function(){ $('.delete-status-update-link').hide(); });
d6654
As mention above in the comment html code: <form> <select name="s1"> <option value="1"> <option selected value="2"> </select> <select name="s2"> <option selected value="1"> <option value="2"> </select> <select name="s3"> <option value="1"> <option selected value="2"> </select> <input type="hidden" name="result" id="hiddenVal" value="#212#" /> </form> javaScript or jquery code: var str = "#"; $('form select').each(function(){ str = str + $(this).val(); }); str +="#"; alert(str); if($("#hiddenVal").val() == str){ alert("yes value from select and value from hidden field is equal"); } jsFiddle A: var concate_string = ""; $('form select').each(function(){ concate_string = concate_string +"#"+$(this).val(); }); concate_string = concate_string +"#"; if($('[name="result"]:eq(0)')==concate_string){ //your action ? }
d6655
In HTML5, there is the Window.sessionStorage attribute that is able to store content against a specific session within a tab/window (other windows will have their own storage, even when running against the same session). There is also localStorage, and database Storage options available in the spec as well. A: HTML5 is still a bit far away from being implemented, but you might be able to use Google Gears for your local storage needs. Also, I've no idea how many simultaneous clients and tasks we're talking about, how big the tasks are and what strain such a request might put on the database, but I'd think you should be able to run smooth without any caching, 10+ requests doesn't seem that much. If traffic is not the bottleneck, I would put caching on the server and keep the client 'dumb'.
d6656
The QProcess is allocated on the stack and will deleted as soon as it goes out of scope. This is likely to happen before the the "xterm" child process quits (hence the output). Try allocating the QProcess in the heap instead: QProcess * process = new QProcess(container); ... process->start(executable, arguments); You can delete the QProcess in three ways: * *Do nothing. Let the QX11EmbedContainer delete it. It is a child of the QX11EmbedContainer and will be deleted when the QX11EmbedContainer is deleted. *Hook up the finished() signal to its own deleteLater() slot. connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), process, SLOT(deleteLater()) ); *Delete it yourself by retaining a pointer to it and delete that pointer later. As an extra note, I'm suspicious of the first parameter to QProcess::start(). It should be the path to your executable and further arguments should be added to the QStringlist. QProcess * process = new QProcess(container); QString executable("xterm"); // perhaps try "/usr/X11/bin/xterm" QStringList arguments; arguments << "-into"; arguments << QString::number(container->winId()); proces->start(executable, arguments);
d6657
This technique for feature selection is rather trivial so I don't believe it has a particular name beyond something intuitive like "low-frequency feature filtering", "k-occurrence feature filtering" "top k-occurrence feature selection" in the machine learning sense; and "term-frequency filtering" and "rare word removal" in the Natural Language Processing (NLP) sense. If you'd like to use more sophisticated means of feature selection, I'd recommend looking into the various supervised and unsupervised methods available. Cai et al. [1] provide a comprehensive survey, if you can't access the article, then this page by JavaTPoint covers some of the supervised methods. A quick web search for supervised/unsupervised feature selection also yields many good blogs, most of which make use of the sciPy and sklean Python libraries. References [1] Cai, J., Luo, J., Wang, S. and Yang, S., 2018. Feature selection in machine learning: A new perspective. Neurocomputing, 300, pp.70-79.
d6658
No - its a new request every time - any attributes set in one request, will not be there when the next request comes in. If you want to set attributes that are persistent across requests, you can use: request.getServletContext().setAttribute("att","value");
d6659
I have used the Image Charts API in the past and implemented the builder pattern to generate my chart URL. Transparent backgrounds and coloured axis were used in our app with the method call providing transparency shown below; /** * Remove any background fill colours. The #chco parameter is used for {@link ChartType#BAR} * fills. * * @return this. * @see https://developers.google.com/chart/image/docs/chart_params#gcharts_solid_fills */ public GoogleImageChartBuilder withTransparentBackgroundFill() { stringBuilder.append("&chf=bg,s,00000000"); return this; } So on re-reading the documentation linked to above I have said with the chf parameter; "give me a solid background fill that is transparent"... perhaps a more sensible way of putting it would have been "give me a transparent background fill"! i.e. stringBuilder.append("&chf=bg,t,00000000"); The axis colouring is defined by the chxs parameter. Take a look at the last optional argument documented here named <opt_axis_color>. Hope that helps you out. Remember the image charts API is now deprecated. The JavaScript version isn't so terrifying :)
d6660
What you're seeing is the Visual Studio "IntelliSense" feature. You can find settings for it under the "Tools / Options" menu, but there are very few. You can choose what displays in the list, which key(s) selects the highlighted item, and how the first highlighted item is selected, but there's nothing available that would allow you to reorder the items.
d6661
Yes, you can use the EditingControlShowing event to get a handle to the combobox. Then hook up an event handler for the SelectedIndexChanged or whatever event you want and code it..! DataGridViewComboBoxEditingControl cbec = null; private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is DataGridViewComboBoxEditingControl) { cbec = e.Control as DataGridViewComboBoxEditingControl; cbec.SelectedIndexChanged -=Cbec_SelectedIndexChanged; cbec.SelectedIndexChanged +=Cbec_SelectedIndexChanged; } } private void Cbec_SelectedIndexChanged(object sender, EventArgs e) { if (cbec != null) Console.WriteLine(cbec.SelectedItem.ToString()); }
d6662
If the models are in your application, just don't register them in the first place. If the model is in a third party app like the django.contrib.auth then use AdminSite unregister method. You can put this in any admin.py or urls.py important is to be discovered by the admin.autodiscover. # admin.py from django.contrib.auth.models import User admin.site.unregister(User)
d6663
select top 1 with ties FullName,Status,[Current Position] from yourtable order by row_number() over(partition by FullName order by case Status when 'Active' then 1 else 0 end) A: You can select DISTINCT FullName, ordering the table by FullName, Status. SELECT DISTINCT FullName, Status, [Current Position] FROM employees ORDER BY FullName, Status; After reordering, 'Active' will always be in first position. (if exists) A: Try this: select top 1 with ties full_name "Full Name",Status,current_position "Current Position" from employee order by row_number() over(partition by full_name order by case Status when 'Active' then 0 else 1 end)
d6664
You can try the following command: copy /y /b boot_sect.bin+kernel.bin os-image > nul The /y switch is to automatically overwrite the destination file in case it already exists and /b is for binary copy.
d6665
When a form is posted to a CFML server, the posted file is saved in a temporary directory before any of your code runs. All <cffile action="upload"> does is to copy a file from that temporary directory to the location you want it to be. Your remote server ServerB has no idea about any file posted on ServerA, so <cffile action="upload"> will not help you. The action is misleading. It's not upload-ing anything. It's just copying from a predetermined temp directory. The web server handles the uploading before the CF server is even involved. You will likely need to <cffile action="upload"> on ServerA to a specific place, and then it needs to post that file to your web service on ServerB. Then ServerB should be able to use <cffile action="upload"> to transfer it from the upload temp directory to wherever you need it to be. That said I have never tried this when posting to a web service. Alternatively you could just post the file directly to ServerB in the first place, to save needing ServerA to be an intermediary. This might not be possible, of course.
d6666
Just a sanity check: do you have admin rights when running the installer? A: To answer my own specific questions (rather than solve my problem as thankfully @p4-randall did): * *the p4rubynotes.txt manual says "The P4Ruby Windows installer requires Ruby 1.8." *P4Ruby is seemingly not installed anywhere! To clarify this, it looks like the P4 client is updated with a version supporting P4Ruby, so the directory it needs to write to is the Perforce installation directory (e.g. C:\program Files\Perforce\).
d6667
You can just basically "transpose" them with zip: with open('wordlist.txt','r') as f: wordlist= list(zip(*[i.splitlines() for i in f.read().split('_')])) If there are no underlines: with open('wordlist.txt','r') as f: wordlist= list(zip(*[f.readlines()[i:i+3] for i in range(0,len(f.readlines()),3)])) And do new file: ... with open('wordlist2.txt','w') as f2: f2.write('_'.join(['\n'.join(i) for i in wordlist])) A: With underscores you could use the concept proposed by U9-Forward with open('wordlist.txt','r') as f: wordlist = list(zip(*[i.splitlines() for i in f.read().split('_\n')])) with open('newwordlist.txt','w') as f2: f2.write('\n_\n'.join(['\n'.join(i) for i in wordlist])) U9 was really close, just the newlines became issues If you have just have a list of words and no underscores, you could use random.shuffle. from random import shuffle with open('wordlist.txt', 'r') as f: words = f.read().splitlines() shuffle(words) # shuffles words randomly with open('newwordlist.txt', 'w') as f2: f2.write('\n'.join(words))
d6668
Via Reflection, you can get an equivalent behavior to that one described in Java 8. You can create an instance of a Delegate with a null target and dynamically binding its first argument to the this method parameter. For your example you can create the toStr delegate in the following way: MethodInfo methodToStr = typeof(object).GetMethod("ToString"); Func<Object, String> toStr = (Func<Object, String>) Delegate.CreateDelegate( typeof(Func<Object, String>), methodToStr);
d6669
Not quite. It's just a syntactic translation. For example, the compiler will translate this: var query = from item in source select item.Property; into var query = source.Select(item => item.Property); It does that without knowing anything about the Select method. It just does the translation, then tries to compile the translated code. All the translations are carefully documented in section 7.16 of the C# 4 spec (and the equivalent for earlier editions, of course). In the case of Rx, it calls the extensions on IObservable<T> and IQbservable<T>. In the case of Parallel Extensions, it calls the extension methods on ParallelQuery<T>. You can do some mad stuff with it - I have a blog post which gives a few examples. Here's another odd one: using System; using System.Linq; namespace CornerCases { class WeirdQueryExpression { static WeirdQueryExpression Where(Func<int, int> projection) { return new WeirdQueryExpression { Select = ignored => "result!" }; } Func<Func<string, bool>, string> Select { get; set; } static void Main() { string query = from x in WeirdQueryExpression where x * 3 select x.Length > 10; Console.WriteLine(query); } } } The query translates to: WeirdQueryExpression.Where(x => x * 3) .Select(x => x.Length > 10); ... which is a call to a static method, which returns a WeirdQueryExpression, followed by accessing the Where property which returns a Func<Func<string, bool>, string>. We then call that delegate (passing in another delegate) and assign the result to query. Funky, huh?
d6670
In My Case Working 100% Try This import CoreData func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell Identifier name ", for: indexPath) as! Cellname cell.YourButtonNamw.tag = indexPath.row cell.YourButtonNamw.addTarget(self, action: #selector(delete), for: .touchUpInside) return cell } @objc func delete(_ sender:UIButton){ let itemName1 = itemName[sender.tag] let context = APP_DELEGATE.persistentContainer.viewContext var albums = [YourTableName]() let request = NSFetchRequest<YourTableName>(entityName: YourTableName) request.predicate = NSPredicate(format: "itemName = %@" , itemName1) do { albums = try context.fetch(request) for entity in albums { context.delete(entity) do { try context.save() } catch let error as Error? { print(error!.localizedDescription) } } } catch _ { print("Could not delete") } }
d6671
as written in the exception, you need to add write permission for the web-server. First possible solution would be to set the owner or the group of the folder to www-data. Another solution would be to allow "others" to write in this folder. I would not recommend the second solution, because it could be less secure.
d6672
The problem was that ajaxContext doesn't have a get_response method. It must be an old version of the object whose example I was looking at. Since I wanted the status code, I just used the ajaxContext.status property.
d6673
UPDATE has no "implicit columns" syntax like INSERT does. You have to name all the columns that you want to change. One alternative you can use in MySQL is REPLACE: REPLACE INTO $dbtable VALUES (?, ?, ?, ?, ?, ...) That way you can pass the current value for your primary key, and change the values of other columns. Read more about REPLACE here: https://dev.mysql.com/doc/refman/5.6/en/replace.html Note that this is internally very similar to @Devon's suggestion of using two statements, a DELETE followed by an INSERT. For example, when you run REPLACE, if you have triggers, both the ON DELETE triggers are activated, and then the ON INSERT triggers. It also has side-effects on foreign keys. A: The solution I can think of doesn't involve an UPDATE at all. DELETE FROM $dbtable WHERE id = $id; INSERT INTO $dbtable VALUES ($id, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); Since you don't want to use the UPDATE syntax, this would delete the row and add a new row with the same id, essentially updating it. I would recommend wrapping it in a transaction so you don't lose your previous row if the insert fails for any reason.
d6674
The instances are actually providing that information themselves. You need to implement the description method, which is inherited from NSObject, for your custom classes in order for them to be able to print themselves as something other than a memory address (which is what NSObject's implementation does). I've no idea what properties your Hours class has, but this is as simple as something like: - (NSString *)description { return [NSString stringWithFormat:@"Open: %i Close: %i", self.openTime, self.closeTime]; } The method just needs to return an NSString containing whatever information you think is important to see when inspecting the object. This is also how classes represent themselves when you use the %@ format specifier in NSLog(). A: In your example, store.storeHours is an empty NSArray. So, naturally, you can't look inside it. For more clarity in the debugger, try adding a method (inherited from NSObject) - (NSString*) description to your objects like Hours that tells you more about their contents. See also debugDescription. A: implement -(NSString*)description{ //Return a string in whatever way you like to describe this instance. That is what xcode debugger reads. //This is implemented in the parent to return the address, that's why you see that way. }
d6675
Updated Try to add following codes below your link_to codes, so it looks like: <%= link_to "#", "assets/blindlogo.jpg", :class=>"single_image" %> See http://fancybox.net/howto. This page says you need href in your link element.
d6676
function index(){ $res = $this->Grade->find('first', array( 'conditions' => array('id' => 2) )); $this->set('res', $res); } I highly suggest you go through the CakePHP Book's Tutorials & Examples. There are so many things wrong or strange with your code that I'm not going to even try to explain it all, but above is how you could find a Grade based on an id. A: Your find-statement looks good, but you don't set it for the view $this->set ( 'res' ); Try: $res = $this->Grade->find(array( 'conditions' => array('id' => 2) )); $this->set('res', $res); With that you do your find, save the result in $res and give it to the view using the set(). A: it simply works, when I erase line $this->Grade->read(); and it solved my problem, no one knows.
d6677
I suppose you tried the test option (lower case) of the Maven Surefire Plugin to invoke a specific test, which Surefire couldn't find in the first module of the reactor build and hence fails. I also suppose integration tests are executed by the Maven Failsafe Plugin. If not, they should, as mentioned by official documentation: The Failsafe Plugin is designed to run integration tests while the Surefire Plugin is designed to run unit tests. ... If you use the Surefire Plugin for running tests, then when you have a test failure, the build will stop at the integration-test phase and your integration test environment will not have been torn down correctly. .. The Failsafe Plugin will not fail the build during the integration-test phase, thus enabling the post-integration-test phase to execute. To make it short: it's safer and much more robust to do so. Although the plugin configuration entry for the Maven Failsafe Plugin is also test, its corresponding command line option is it.test, so you should instead run: mvn clean install -Dit.test=SampleIT Where SampleIT is an integration Test (note the standard IT suffix, recognized by default by Failsafe. The official Running a Single Test documentation also provides further details on running single integration tests. Also note: the invocation above will work if you don't have other integration tests in other modules of the build, otherwise it will fail not finding it earlier (before hitting the concerned module). If you are using Surefire to run the concerned integration test (again, you shouldn't) or you have several modules running integration tests, you should then configure a profile in the concerned module which would take care of this specific invocation, something like as following: <profiles> <profile> <id>run-single-it-test</id> <activation> <property> <name>single.it.test</name> </property> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.19.1</version> <configuration> <test>${single.it.test}</test> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> And then invoke the build as following: mvn clean install -Dsingle.it.test=SampleIT As such, Maven will activate the profile based on the existence of a value for the single.it.test property and pass it to the test property of the Failsafe Plugin (or the Surefire, if it was the case), Failsafe will ignore any other integration test for that execution and other modules would not suffer any impact (ignoring that property). A: A_Di-Matteo's answer gets you most of the way there, but you need the following config for maven-surefire-plugin to suppress all the unit tests as well. <profiles> <profile> <id>run-single-it-test</id> <activation> <property> <name>single.it.test</name> </property> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skipTests>true</skipTests> <failIfNoTests>false</failIfNoTests> </configuration> <executions> <execution> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <configuration> <test>${single.it.test}</test> <failIfNoTests>false</failIfNoTests> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
d6678
Your function code performance will be slow. Because in your code update command will be executed on 2 times. It is possible to write this function very simply and with high performance. CREATE OR REPLACE PROCEDURE update_leaders_score(in_school_id integer, in_leader_score integer) LANGUAGE plpgsql AS $procedure$ begin update schools SET leaders_score = in_leader_score, leaders_icon = case when (in_leader_score > 0 and in_leader_score < 20) then 'Very_weak' when (in_leader_score >= 20 and in_leader_score < 40) then 'Weak' when (in_leader_score >= 40 and in_leader_score < 60) then 'Average' when (in_leader_score >= 60 and in_leader_score < 80) then 'Strong' when (in_leader_score >= 80 and in_leader_score < 100) then 'Very_strong' end WHERE school_id = in_school_id; END; $procedure$ ; A: Increase the length of the Leaders_Icon by using below code before calling stored procedure, It will work. ALTER TABLE SCHOOLS ALTER COLUMN Leaders_Icon SET DATA TYPE VARCHAR(20);
d6679
There will be no effective difference if you have Option Infer On. If you have Option Infer Off then the first snippet will always result in a variable of type Thing while the second snippet will fail to compile with Option Strict On and result in a variable of type Object with Option Strict Off. The first code snippet is explicit in its typing of the variable so it will be the type you specify regardless of what settings you have for Option Strict and Option Infer. The second code snippet is not explicit about the type so that type must be determined implicitly by the compiler. With Option Infer On, the type Thing can be inferred from the initialising statement. With Option Infer Off, the type will default to Object and late-binding must be used, which is not allowed with Option Strict On. It's worth noting that your original question isn't really valid because it's actually not a case of using As or =. This: Using aThing As New Thing() is actually just a shorthand for this: Using aThing As Thing = New Thing() so you're actually using = either way and the choice is just whether or not to provide an As clause. An As clause is required with Option Strict On unless you also have Option Infer On and the type can be inferred from the initialising statement. If there is no initialising statement or the type of that statement is different to the type you want the variable to be then an As clause is required to tell the compiler the type of the variable that it cannot infer for itself.
d6680
PhantomJS is single process, just like node.js, and will never spawn something to process requests. Basically, everything is shared in the same instance (web pages, html ressources, ...) You can spawn custom process, using execFile/spawn modules.
d6681
You need to outside of GetDubPrime catch the ArgumentException that you throw inside it. If nothing catches the exception the program exits. Something like: (...) try { x = GetDubPrime(...); } catch(ArgumentException ex) { // bad data, do something Console.WriteLine(ex.Message); x = 0; // or whatever is necessary } (...)
d6682
Here is the default css: /* optional disabled input styling */ table.tablesorter thead tr.tablesorter-filter-row input.disabled { opacity: 0.5; filter: alpha(opacity=50); } As seen, a disabled class is applied to those disabled filters, so you can use css to either apply display:none or visibility:hidden to it: tr.tablesorter-filter-row input.disabled { display: none; } A: I recommend simply sticking with: /* optional disabled input styling */ table.tablesorter thead tr.tablesorter-filter-row input.disabled { opacity: 0.0; filter: alpha(opacity=0); } As having that one hidden, removes also the table's inner border thus creating unpleasant visual effect.
d6683
How did you add your ojdbc driver ? A typical way is shown below: First you need to right click your project and go for "Build Path" and go for "Configure build Path" Then , in the "libraries" tab, click on the "Add External JARs" go to your ojdbc driver file to load it. This is the typical way to load your ojdbc driver. Try first see whether it will help A: If your IDE (Eclipse) gives error: The package java.sql is not accessible Or if compiling using javac gives error: test\Test.java:3: error: package java.sql is not visible import java.sql.*; ^ (package java.sql is declared in module java.sql, but module Test does not read it) 1 error Then it is because your Java 9+ project has a module-info.java file, i.e. your project is modular. You need to add the following line to the module-info.java file: requires java.sql;
d6684
$k2 = preg_replace('/[^[:alnum:]]/', '', $k); simple and quick ;)
d6685
Submitted as a bug. Solved by adding to input group and by removing QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); flag.
d6686
A problem can be that you are "blowing up" you're autoencoder. You have an input of 13 and than map that to 200, 150, 100 and 13 again. There is no bottleneck in the network where it has to learn a compressed representation of the input. Maybe try 13 -> 6 -> 4 -> 6 -> 13 or something like that. Than it lears a compressed representation and the task to reconstruct the input is not trivial anymore. Additionally play around with other hyperparameters like the activation function. Maybe change it to 'relu' in the intermediate models.
d6687
Ruby's include doesn't access the file system. The given module must have already been defined or a NameError will be raised: # foo.rb class Foo include Bar # NameError: uninitialized constant Foo::Bar end This works (everything in one file): # foo.rb module Bar end class Foo include Bar end If your module is defined in a separate file, you have to load this file using require or require_relative: # bar.rb module Bar end # foo.rb require_relative 'bar' class Foo include Bar end A: require is about files. include is about modules. Since a module and a file does not correspond one-to-one in Ruby, requiring a file and including a module are different tasks. They need to be controlled separately. The content of the module Stacklike is written on the file stacklike.rb, so you need to require that file to access the module. Then, you need to include Stack if you want to. A: We use Module#include method with module names as parameter to that method, to add those modules in the requiring class's ancestor chain. Now Kernel#require_relative will made available the classes,modules etc from the requiring file to the required file on top level. When you did require_relative "stacklike",it means module(s),class(s) etc whichever you have defined inside the file stacklike.rb are now available to the top level of the file stack.rb. Now to use the instance methods of the module Stacklike,using the instance of the class Stack,you need to include that module to the class Stack.
d6688
I have tested different parts in relation to the filesystem but it's easier for you to confirm on the actual files to confirm it works on your data. EDIT to allow for inclusion of pathnames import sys import os import os.path import re import itertools #generator function to merge sound and word files def takeuntil(iterable, stop): for x in iterable: yield x if x[1] == stop: break def process_words_and_sounds(word_file, sound_file): #open word and sound files total_words = 0 with open(word_file) as unsplit_words, open(sound_file) as unsplit_sounds: sounds = (line.split() for line in unsplit_sounds) words = (line.split() for line in unsplit_words) output = [ (word, " ".join(sound for _, _, sound in takeuntil(sounds, stop))) for start, stop, word in words ] for x in output: total_words += 1 return total_words, output for root, dir, files in os.walk(sys.argv[1]): words = [ os.path.join( root, f ) for f in files if f.endswith('.WRD')] phones = [ os.path.join( root, f ) for f in files if f.endswith('.PHN')] phones.sort() words.sort() files = zip(words, phones) # print files output = [] total_words = 0 for word_sounds in files: word_file, sound_file = word_sounds word_count, output_subset = process_words_and_sounds(word_file, sound_file) total_words += word_count output.extend( output_subset ) #open a dictionary file and create subset of words class_defintion = re.compile('([1-2] [lnr] t en|[1-2] t en)') with open('TIMITDIC.TXT') as w_list: entries = (line.split(' ', 1) for line in w_list) comp_set = [ x[0] for x in entries if class_defintion.search(x[1]) ] #extract words from above into list of words in dictionary set glottal_environments = [ x for x in output if x[0] in comp_set ]
d6689
As far as I know if you are running your application on Micromax device with version 4.2.1, you can face this java.lang.StringIndexOutOfBoundsException as it seems to be a manufacturer bug in that specific version for Micromax device. The same problem happened to me once when I had to play a video in splash screen and got the same error in that particular version of Micromax device. Below are the links for the same issue. java.lang.StringIndexOutOfBoundsException while playing video in videoView : Android v 4.2.1 https://groups.google.com/forum/#!topic/android-developers/-WP6uxDebm8 So try debugging your app other that Micromax version 4.2.1, hope that will work.
d6690
TL;DR: Is it possible to run out of threads when using coroutines? Well, the answer is no (deadlocks are another issue). But, is it possible to use coroutines in a way which means that your concurrency is bound by your number of threads? Yes. I think the first thing you must understand is the difference between a blocking and non-blocking/suspending/async function. A real suspending/non-blocking/async function which has some long running functionality, but properly yields control of execution until that long running task is complete is how you really leverage the concurrency that you get with coroutines. Let me demonstrate. Muliple coroutines with an internal long running suspending function on 1 thread val singleThread = Executors.newFixedThreadPool(1).asCoroutineDispatcher() fun main() = runBlocking { val start = System.currentTimeMillis() val jobs = List(10) { launch (singleThread){ delay(1000) print(".") } } jobs.forEach { it.join() } val end = System.currentTimeMillis() println() println(end-start) } Here we have 10 coroutines that have been launched in quick succession on 1 thread. They all use the suspending function delay to simulate a long running task that takes 1000 milliseconds. But... the whole thing finishes in 1018 milliseconds. This will be a bit strange for someone familiar with pure thread based concurrency. Explanation to come. But just to make it absolutely clear, here is the same code, but using Thread.sleep instead of delay. Multiple coroutines on 1 thread with internal long running blocking function fun main() = runBlocking { val start = System.currentTimeMillis() val jobs = List(10) { launch (singleThread){ Thread.sleep(1000) print(".") } } jobs.forEach { it.join() } val end = System.currentTimeMillis() println() println(end-start) } This same bit of code, but with a blocking Thread.sleep took 10027 milliseconds. Each coroutine blocked the thread it was on, and so, our 10 coroutines actually executed in series. Control was not given back to the dispatcher while the long running function was being executed. You can read a much more detail explanation of the difference between non-blocking suspension and blocking calls from Roman Elizarov here In your case, I suspect that you are doing your retrieval of data using a blocking IO library. That means that each of those calls is blocking the thread it is on, and not yielding control to the dispatcher while the IO task is completing. My recommendation would be: * *Carry on using Dispatchers.IO *Start using a non blocking library to retrieve your data. I recommend ktor http client with the CIO engine. But what about your data loss when you do things concurrently? There is not enough information here to be sure, but, I think that you have not built your logic in a way that accounts for concurrency. In a truly parallel execution, swipe number 3 might complete before swipe 2 or swipe 1 completes. If your updates are not idempotent or you are delivering some partial set of data with each update request, then you could be processing update 3 before the others and ignoring update 1 and 2 when they do eventually arrive.
d6691
Those methods can't be mocked because they they are final methods created by spring-retry using a CGLIB proxy.
d6692
Did you try this? myActivity.setTitle(userInput); //Where userInput is new title given by user Hope this helps. A: You can simply call the setTitle() function from within your Activity. It takes either an int (resource ID) or a CharSequence as a parameter. or this.setTitle("New Title Here"); or change in manifest file A: If you just want to change the string in the Title bar, you can use setTitle as @android_beginner or @Mystic Magic suggested. If you intend on changing the name of the app as it appears in the Android desktop, I'm afraid that's not possible.
d6693
if (!Regex.IsMatch(value, @"^[0-9]{5}$")) _errors.Add("PostalCode", "Invalid Zip Code"); break; case Countries.Canada: if (!Regex.IsMatch(value, @"^([a-z][0-9][a-z]) ?([0-9][a-z][0-9])$", RegexOptions.IgnoreCase)) _errors.Add("PostalCode", "Invalid postal Code"); break; default: throw new ArgumentException("Unknown Country"); } _PostalCode = value; } } So you can only validate the postal code after the country has been set, but there seems to be no way of controlling that order. I could use the Error string from IDataErrorInfo, but that doesn't show up in the Html.ValidationMessage next to the field. A: For more complex business rule validation, rather than type validation it is maybe better to implement design patterns such as a service layer. You can check the ModelState and add errors based on your logic. You can view Rob Conroys example of patterns here http://www.asp.net/learn/mvc/tutorial-29-cs.aspx This article on Data Annotations ay also be useful. http://www.asp.net/learn/mvc/tutorial-39-cs.aspx Hope this helps. A: Here's the best solution I've found for more complex validation beyond the simple data annotations model. I'm sure I'm not alone in trying to implement IDataErrorInfo and seeing that it has only created for me two methods to implement. I'm thinking wait a minute - do i have to go in there and write my own custom routines for everything now from scratch? And also - what if I have model level things to validate. It seems like you're on your own when you decide to use it unless you want to do something like this or this from within your IDataErrorInfo implementation. I happened to have the exact same problem as the questioner. I wanted to validate US Zip but only if country was selected as US. Obviously a model-level data annotation wouldn't be any good because that wouldn't cause zipcode to be highlighted in red as an error. [good example of a class level data annotation can be found in the MVC 2 sample project in the PropertiesMustMatchAttribute class]. The solution is quite simple : First you need to register a modelbinder in global.asax. You can do this as an class level [attribute] if you want but I find registering in global.asax to be more flexible. private void RegisterModelBinders() { ModelBinders.Binders[typeof(UI.Address)] = new AddressModelBinder(); } Then create the modelbinder class, and write your complex validation. You have full access to all properties on the object. This will run after any data annotations have run so you can always clear model state if you want to reverse the default behavior of any validation attributes. public class AddressModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { base.OnModelUpdated(controllerContext, bindingContext); // get the address to validate var address = (Address)bindingContext.Model; // validate US zipcode if (address.CountryCode == "US") { if (new Regex(@"^\d{5}([\-]\d{4})?$", RegexOptions.Compiled). Match(address.ZipOrPostal ?? "").Success == false) { // not a valid zipcode so highlight the zipcode field var ms = bindingContext.ModelState; ms.AddModelError(bindingContext.ModelName + ".ZipOrPostal", "The value " + address.ZipOrPostal + " is not a valid zipcode"); } } else { // we don't care about the rest of the world right now // so just rely on a [Required] attribute on ZipOrPostal } // all other modelbinding attributes such as [Required] // will be processed as normal } } The beauty of this is that all your existing validation attributes will still work - [Required], [EmailValidator], [MyCustomValidator] - whatever you have. You can just add in any extra code into the model binder and set field, or model level ModelState errors as you wish. Please note that for me an Address is a child of the main model - in this case CheckoutModel which looks like this : public class CheckoutModel { // uses AddressModelBinder public Address BillingAddress { get; set; } public Address ShippingAddress { get; set; } // etc. } That's why I have to do bindingContext.ModelName+ ".ZipOrPostal" so that the model error will be set for 'BillingAddress.ZipOrPostal' and 'ShippingAddress.ZipOrPostal'. PS. Any comments from 'unit testing types' appreciated. I'm not sure about the impact of this for unit testing. A: Regarding the comment on Error string, IDataErrorInfo and the Html.ValidationMessage, you can display object level vs. field level error messages using: Html.ValidationMessage("address", "Error") Html.ValidationMessage("address.PostalCode", "Error") In your controller decorate the post method handler parameter for the object with [Bind(Prefix = "address")]. In the HTML, name the input fields as such... <input id="address_PostalCode" name="address.PostalCode" ... /> I don't generally use the Html helpers. Note the naming convention between id and name.
d6694
Decorators can't change the structure of the class they are decorating. This is a design limitation. There is a proposal to change this but it does not seem to be a priority (maybe upvote the GitHub issue if it's important to you) We could use a mapped type if we want to transform all methods, but we can't apply a mapped type transformation to only decorated properties so this is not a viable solution in this case. A better option would be to actually have the corect return type directly in the class. We could do this with minimal changes to the code using async: class Class { @buffered(100) // i.e. 100ms delay // use async and return a promise instead of a number public async f1(t: Date): Promise<number> { return new Date().getTime() - t.getTime(); } @buffered // i.e. defaults to 200ms delay public async f2(t: Date) { // no need to specify the return type will be inferred correctly to Promise<number> return new Date().getTime() - t.getTime(); } } const p: Promise<number> = new Class().f1(new Date()); // works fine p.then((res: number) => { console.debug(res); });
d6695
Simply use following code snippet : try { File myFile = new File("/mnt/sdcard/images/2.png"); MimeTypeMap mime = MimeTypeMap.getSingleton(); String ext=myFile.getName().substring(myFile.getName().lastIndexOf(".")+1); String type = mime.getMimeTypeFromExtension(ext); Intent sharingIntent = new Intent("android.intent.action.SEND"); sharingIntent.setType(type); sharingIntent.putExtra("android.intent.extra.STREAM",Uri.fromFile(myFile)); startActivity(Intent.createChooser(sharingIntent,"Share using")); } catch(Exception e){ Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); }
d6696
For structured ordering in a database, you'll want a column to store the ordering. An int is fine, but a decimal can make updates a little easier. Don't use the name "order" for the column, as it's a keyword, consider "display_order". You can create a self-referencing table. A "canonical" term has a null parent id, an "alternative" does not. create table terms ( term_id int primary key, term text not null, parent_term_id int null references terms(term_id), display_order int not null, unique (parent_term_id, term), unique (parent_term_id, display_order) ); Add a canonical term: inset into terms (term_id, term, parent_id, display_order) values (1, 'United Kingdom', null, 0); Add alternative terms, associated w the above: inset into terms (term_id, term, parent_id, display_order) values (2, 'Great Britain', 1, 0), (3, 'England', 1, 1); You can use Recursive Common Table Expressions (except in MySQL) to efficiently query this structure. See Using a sort order column in a database table regarding updating your order column. A: Another form of structuring data in an RDBMS is nested sets. I've played around with them and if they meet your need, they can be vastly superior to self-referential designs. One important consideration is that the ratio of data "movement" (inserts, deletes, updates to change the position) to queries must be low. In other words, the data should be relatively stable. With a nested set design, just one self-join is all that is needed to traverse an entire tree to any arbitrary depth. No recursion! That alone makes it a big selling point for me. :) Unfortunately, while there is information available on the Internet, it is all fairly basic. But if you don't mind playing around to get familiar with it, you just might be glad you did.
d6697
Build a Question Text to ID hash table function hashtable() { const ss = SpreadsheetApp.getActive(); const sh = ss.getSheetByName('Sheet0'); let texttoid = {}; sh.getDataRange().getDisplayValues().forEach(r => texttoid[r[1]]=r[0]); Logger.log(JSON.stringify(texttoid)); } Execution log 11:58:17 AM Notice Execution started 11:58:18 AM Info {"text1":"id0","text2":"id1","text3":"id2","text4":"id3","text5":"id4","text6":"id5","text7":"id6","text8":"id7","text9":"id8","text10":"id9","text11":"id10"} 11:58:18 AM Notice Execution completed Sheet0: id0 text1 id1 text2 id2 text3 id3 text4 id4 text5 id5 text6 id6 text7 id7 text8 id8 text9 id9 text10 id10 text11 You can goto to Google Apps Script Reference and using the search box find any function that you don't understand. If it's a pure JavaScript function the go here You could store the hash table in cache if wish to use it repeatedly to save the time of building it each time from a spreadsheet.
d6698
call your function this way: function fooBar(item ){ // .... // return truthy condition }; var result = arr.filter(fooBar); - Passing argument to the filter function: const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; /** * Array filters items based on search criteria (query) */ const filterItems = (query) => { return fruits.filter((el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1 ); } console.log(filterItems('ap')); // ['apple', 'grapes'] console.log(filterItems('an')); // ['banana', 'mango', 'orange'] Source: Mozilla Docs - Filtering array based on nested values: var arr = [ {foo: 'item1', nested: {nestedFoo: 'returnThis'} }, {foo: 'item2', nested: {nestedFoo: 'notThis'} }, ]; var result = arr.filter(item => item.nested.nestedFoo == 'returnThis'); // result variable now contains an array with one object console.log(result) // array console.log(result[0]) // object console.log(result[0].foo) // 'item1' Refer to this question for explanation on how to access nested values - Making it more clear: var arr = [ { username: '', id: '', moreInfo: { infoDate: '' } }, { username: '', id: '', moreInfo: { infoDate: '' } }, ... ]; const filterItems = (fromDate, thruDate, fieldName) => { return arr.filter((item) => item.moreInfo.infoDate >= fromDate && item.moreInfo.infoDate < thruDate ); }
d6699
Richtextbox1.text = mid(Richtextbox1.text,1,len(richtextbox1.text)-x) & NewTotal Where x is the length of the previous total and NewTotal is the new total string. Edit (see comments): Use this code to solve your issue: dim numberofcolumns as integer = listview1.ColumnHeaders.Count dim str(numberofcolumns-1) as string str(numberofcolumns-2) = "TotalAmount" str(numberofcolumns-1) = totalammountvariable Dim itm As ListViewItem itm = New ListViewItem(str) ListView1.Items.add(itm) A: First Clear All Data and Rebind RichTextBox1.Clear() Using this Command clear all data in Richtextbox and rebind you data
d6700
This will print the lines in file2 that are not in file1: fgrep -F -x -v -f file1 file2 The -F means to treat the input as fixed strings rather than patterns, the -x means to match the whole line, the -v means to print lines that don't match rather than those that do match, and -f file1 uses file1 as a list of patterns. Your question is kind of unclear but I'm guessing that you want all of the lines that appear in one or the other file but not both. There's several ways to do that. One is to do two greps: fgrep -F -x -v -f file2 file1; fgrep -F -x -v -f file1 file2 Another, if the order of the lines in the output doesn't matter, is to sort them and use comm: sort file1 -o sortfile1 sort file2 -o sortfile2 comm -3 sortfile1 sortfile2 A: grep -f file1 file2 && grep -o -f file1 file2 | sed s'/^\(.*\)$/-e "\1"/g' | tr '\n' ' ' | xargs grep -v file1 What this does is print all matches from file2 by patterns in file1, and after that print all lines from file1 that do not match files in file2. The second part is done as follows: * *grep -o -f file1 file2 returns matches between file and file2, but only the matching parts of the lines; *sed s'/^\(.*\)$/-e "\1"/g' | "\1"/g' | tr '\n' ' ' prefixes those matching parts with -e, encases them in double quotes, and replaces newlines printed by the grep -f command with spaces. This builds a string of the form -e "[pattern1]" -e "[pattern2]" ..., which is what grep uses for multiple patterns matching. The quotes (hopefully) ensure that spaces in patterns will not be a problem; *xargs grep -v file1 builds and executes the command grep -v file1 [whatever was piped to xargs]. The result is all lines from file1 that have not match in the output of the first command (and, thus, in file2). I'm not completely sure this solves your problem since non-matching lines from file1 are printed at the end (by far the easiest option), and you do not say where you want them. It probably could be done more elegantly, too. Here's a sample output: sh-4.3$ cat file1 hello my name is bernardo sh-4.3$ cat file2 hello 1 my 2 name 3 is 4 sh-4.3$ grep -f file1 file2 && grep -o -f file1 file2 | sed s'/^\(.*\)$/-e "\1"/g' | tr '\n' ' ' | xargs grep -v file1 hello 1 my 2 name 3 is 4 bernardo