INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What is the issue with double free()? I've been seeing quite a bit of erroneous code around the web and in my Advanced C class (such as the code below). While I understand that it's obviously bad coding practice, I'm having a difficult time as to what it does that's so bad other than waste CPU cycles. From my understanding so far, if a pointer allocation is not located in the "malloc table" (for lack of a better word), it is usually ignored. I'd appreciate if someone here could provide me with a better understanding as to why this is bad and (other than the fact that it's a silly thing to do) and the consequences of it are. char* ptr = malloc(1); ... free(ptr); ... free(ptr);
A good advise: nullify pointer after free. In your case you have undefined behaviour, because computer can allocate memory, which is pointed by ptr, or may not allocate this piece of memory, or this chunk of memory could be added to other chunk of memory during defragmentation, etc. On the other hand, free(NULL) is defined and will do nothing. char* ptr = malloc(1); ... free(ptr); ptr = NULL; ... free(ptr);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "c, memory, memory management, free, undefined behavior" }
Separate apache sites with security in mind I have one machine running apache with php. It serves multiple domains from the folder /home/web/ Like /home/web/domainA and /home/web/domainB Now, how do I securely separate them? Domain A must not be able to read, write or execute files in domain B's folder. A virtual server is not a (well liked) option, since the server is low on RAM, and avoiding multiple boxes is preferable..
< \- could work for you. Assign different users to VirtualHosts and chown/chmod accordingly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, apache, security, webserver" }
Python lambda output This is probably something trivial but I can't seem to find a decent solution and/or I'm searching for the wrong thing. When I call this: `validation_data = validation.map(tuple)` I get the following output: [(61.0, 3864.0), (61.0, 3889.0)] I actually want the result to be Integers, so I changed the code to this instead: validation_data = validation.map(lambda xs: [int(x) for x in xs]) But now the format of the output changes (notice it's now square brackets like an array instead of smooth brackets) [[61, 3864], [61, 3889]] I'm not sure what happens here. Why does the output format change? And how do I keep the original `[()]` format instead of `[[]]`?
validation_data = validation.map(lambda xs: tuple(int(x) for x in xs)) This is essentially just combining the first statement in your question with the second. Either the only reason you had round brackets the first time was precisely because you used `tuple`, or the first statement was redundant. Note that `tuple(int(x) for x in xs)` is a special feature of Python syntax. It's short for `tuple((int(x) for x in xs))`. That argument is a generator comprehension, and when a function has a single argument which is a generator comprehension you can remove the extra round brackets. `tuple([int(x) for x in xs])` would also work and would be closer to your code. You could also do: validation_data = validation.map(lambda xs: tuple(map(int, xs)))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python" }
Gradle not excluding specified file I have added `exclude` statement but still my exclude `abc/object/MyTestConfig*.class` are getting added in jar, any reason why ? jar { zip64 true from((configurations.compile - configurations.jarDepends).collect { it.isDirectory() ? it : zipTree(it) }) { exclude "META-INF/*.SF" exclude "META-INF/*.DSA" exclude "META-INF/*.RSA" } from ("$projectDir/src/main/java/") { include "**/*.hbm.xml", "abc/tools/xml/XMLClasses.MF" exclude "abc/object/MyTestConfig*.class" } } task filterVersionConstants(type: Copy) { from "src/main/java/abc/" into "src/main/java/abc/" include "VersionConstants.tmpl" exclude "**/MyTestConfig*.class" rename { String fileName -> fileName.replace('.tmpl', '.java') }
After couple of trial and error, finally I'm able to exclude this file from my jar as below. Basically I need to pull exclude statement in `jar` task at first. jar { zip64 true exclude "abc/object/MyTestConfig*.class" from((configurations.compile - configurations.jarDepends).collect { it.isDirectory() ? it : zipTree(it) }) { exclude "META-INF/*.SF" exclude "META-INF/*.DSA" exclude "META-INF/*.RSA" } from ("$projectDir/src/main/java/") { include "**/*.hbm.xml", "abc/tools/xml/XMLClasses.MF" } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "gradle, build.gradle, gradlew, gradle eclipse" }
What is the grammar behind these repeated words (e.g. 一曲一曲, 一発一発)? > > I interpret this as "hit after hit" and "song after song". Does this work with any repeated? Does it make the construction an adverb? There's a song I like that says . Is it the same grammar?
> Does this work with any **** repeated It works with most _counters_. The meaning depends on contexts, but generally it is _one by one, one after another, each_ etc. > Does it make the construction an adverb? I would say no. The NN phrases behave just like numerical expressions, which are noun phrases that can work adverbially. You can see the following questions. * Grammatically speaking, what is ? * Placing a quantifier between a noun and particle? * Counters with and without For example, can be **** , where behaves a noun phrase. > **.** Is it the same grammar? I would say it is the same usage, practically meaning _every second_. ( is more idiomatic than or .) Note that there are a number of common following the pattern NN: , , etc. could be considered just as an instance of the pattern as well.
stackexchange-japanese
{ "answer_score": 3, "question_score": 1, "tags": "grammar" }
How could I implement a streaming Web Application in apache/php/sf1.4/jquery/flash/html 5? I want to implement a one-to-one webcam conversation (like a skype call) between two users of my web application. For the client side I found this very nice jQuery plugin with Flash libraries, but I don't know how the rest of the process should work.. upload the video to the server (optionally save it) stream the video. and the other user to receive it. Could you suggest any script or any workflow on how this system should be implemented.
you cannot rely on upload/download video approach. You need a realtime communication. You could rely on Flash technology (client) using an AMF Server on server side. You could check this OpenMeeting open source project
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, flash, html, stream, webcam" }
Any way a native application can access the DOM inside a browser? (Mac/Win/Linux) Think of a dictionary application that grabs words upon user's click from any other application (including browsers) and pops up it's meaning. Is it possible to twist this behavior based on the word's HTML attributes? Edit: I noticed something cool. OSX's built-in dictionary app has a shortcut (cmd+control+d) that actually pops up a word's meaning (the word you're hovering your mouse above). It also highlights the word. The highlight area grows as you increase the font size. check out this fiddle and try various font sizes.
Yes/no If your dictionary application embeds a browser instance (like a webkit browser) then it should be possible to access the DOM. If you want your application to manipulate an already running browser instance it has no control over then it could probably done if * that browser has a browser plugin that interacts with your application * you intercept low level commands to mess directly with the kernel or the memory of the browser. Neither of those are easy to do for all browsers.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows, macos, dom" }
Webpack externals configuration - root key What does it mean and what is `root` for in Webpack externals configuration? module.exports = { output: { libraryTarget: "umd" }, externals: [ "add", { "subtract": { root: "subtract", commonjs2: "./subtract", commonjs: ["./math", "subtract"], amd: "subtract" } } ] }
Check the answer here: webpack umd lib and external files Basically it applies to UMD modules and it is used to solve global dependencies when your module is loaded using the `<script>` tag or well a CDN repo.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, webpack, webpack externals" }
How can I make the `cal` tool in OSX highlight the current day? In Ubuntu and Fedora, when I type `cal` on the command line I get an ASCII calendar with the current day highlighted. In OSX, when I type `cal`, I get an ASCII calendar but no day is highlighted. How can I get the highlighting of the current date in OSX?
The following prints the current date with a reversed field which is replaced in cal by sed. ptd=$(date -j +%d) ctd=$(printf "\033[0;7m"$ptd"\033[0m") cal | sed 's/'"$ptd"'/'"$ctd"'/'
stackexchange-unix
{ "answer_score": 2, "question_score": 5, "tags": "osx, cal" }
Limit displayed text length (from DB) in PHP? I am able to load data off my database into my webpage. However, there are a couple of instances where I would like to limit the number of characters that are placed on a row. For example, "DESCRIPTION" is a varchar(200), and I only want to show the first 30 characters on this particular page. <td><?php print $row->DESCRIPTION; ?></td> What is the best way to go about doing this? Thanks. Ended up using this, <td><?php print substr($row->DESCRIPTION,0,20); ?></td>
I would do it on the php side with `substr`. <?php echo substr($row->DESCRIPTION, 30); ?> Of course that doesnt take into account words and what not so you might need to get more complex with that by writing a custom function if thats important.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "php, html, sql" }
@font-face defined in __layout.svelte not accessible from form elements in components? I have a SvelteKit project where I add a custom `@font-face`, which is applied to `*` as shown below, inside a `<style>` tag in `__layout.svelte` @font-face { font-family: 'Inter'; src: url('/inter.woff2') format('woff2-variations'); } * { font-family: 'Inter', 'Fira Sans', 'Helvetica Neue', 'Helvetica', sans-serif; } Most content is displayed as expected in Inter, including `<label>`s inside components. However, form elements in components (`<input>`, `<button>`) fall back to Fira Sans (which I have installed locally). Other than `font-size`, no additional font styling is applied inside the components. How would I apply the custom font to these elements?
You have to add the globally access css in `app.css`. @font-face { font-family: 'Inter'; src: url('/inter.woff2') format('woff2-variations'); } * { font-family: 'Inter', 'Fira Sans', 'Helvetica Neue', 'Helvetica', sans-serif; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, font face, svelte, svelte component, sveltekit" }
Textview show partial text in android I have a textview in which I must load a message. I want to set number of variable is display in textview and after that left message replace with add three dots (...). How can I detect set number of variable is display and after that display three dots(..) My code for textview is <TextView a:id="@+id/tv_message" a:layout_width="wrap_content" a:layout_height="wrap_content" a:textColor="@android:color/black" />
In text view you should work with ellipsize property in xml.... Though you need some workaround in Java to make it variable......
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android layout, android widget" }
Fill width on Windows Phone 8.1 I'm developing an application using the Windows Phone 8.1 SDK, I write UI descriptions using `XAML` markup. **I can't get a text box to fill width.** I see similar questions already posted but they involve ListView. I'm really confused. There seems to be no proportional sizing options. Tutorials show the use of explicit pixel counts in design. > Is that really the preferred method on Windows? How am I supposed to deal with unpredictable screen sizes in Windows?
The items which I had, which were failing to fill their parent, were inside a `ContentControl`. The `ContentControl` correctly filled its width, but its child, which was a `Grid`, would not. I found the solution here – < – and I will echo that solution here in case this post is found by someone else searching about the same problem. The `ContentControl` requires two special properties in order for its child element to fill the parent. They are `HorizontalContentAlignment` and `VerticalContentAlignment`. Like so": <ContentControl Name="MyContent" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"> … </ContentControl> Fill now occurs correctly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "xaml, windows runtime, windows phone 8.1, windows phone" }
Should I keep giving cards when I'm King 13? In Clash Royal, it's mostly clear that when you're in a clan and you are not yet King 13 you should give cards to other teammates. You'll get XP points plus gold. But what if you're King 13 and you only get gold and star points? Those are used to get clothes for your troops. If you totally don't mind about having such clothes, is it still worth giving cards only for gold?
New cards come out time-to-time and require gold to upgrade, so donating cards for gold could be worth it for upgrading new cards quicker as they are released (meaning, you'd just have to wait for getting enough cards instead of cards AND gold, since higher upgrades could get costly). If you are already sitting on a huge pile of gold (from either stockpiling or maybe you spend enough real money on the game to accumulate) then the only other thing would be to show support for clan mates (and maybe they could be more willing to trade those future new cards to you if you request them, if they care enough to remember). But if you have plenty of gold for future card releases, don't care about star points for cosmetic upgrades, and don't mind potentially being seen as a free loader from your clan mates (no judgement here)... then there is no real advantage to donating cards once you reach King level 13.
stackexchange-gaming
{ "answer_score": 2, "question_score": 1, "tags": "clash royale" }
Is it okay to slow cook sausage casserole without pan frying the sausages? We haven't got an oven/hob at the moment due to kitchen refurbishments and I'm currently slow cooking sausage casserole in a 2.5L slow cooker. There's about 6-8 thick sausages in there all cut up into quarters and mixed into the casserole. It's been on high for around 5 hours now and I was wondering if the sausages would be edible? They're 97% pork Debbie & Andrews sausages (more info HERE)
There's no health issue here, the sausages will be cooked enough to be safe. The reason you fry off the sausages first is that you make the casings more edible, get flavor from maillard reactions and browning, and maybe get rid of some of the fat (if you discard the fat that comes out of the sausages that is). I'm thinking that the sausage casings could end up being a bit soggy, however that depends on several factors and you'll probably get a good result. Worst case is you don't eat the sausage casings.
stackexchange-cooking
{ "answer_score": 7, "question_score": 6, "tags": "slow cooking, sausages" }
Avoid null values while filtering javascript array How can I filter for "mna" ===1 and ignore null values const words = [null, null, {"mna":1}, {"mna":2}, {"mna":1}]; const result = words.filter(word => word.mna === 1);
Just add it to the condition so you don't try to access `mna` unless it's truthy (null values are falsy so they will cause the condition to short circuit early) const words = [null, null, {"mna":1}, {"mna":2}, {"mna":1}]; const result = words.filter(word => word && word.mna === 1); console.log(result);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript" }
Having the "Hamburger Menu" to the right, shouldn't menu items be right-aligned as well? It's clear that the Hamburger Menu should be to the right of a native app and web application. At least our community concluded (through voting) on the question Hamburger menu icons - should they be on the left or right? that this should be the case. > That's because aprox. 67% of users use the right thumb (so that means the right hand) and in several studies have proved that the screen area is more difficult to reach with this hand posture is the top-left one. For the same reasons, **wouldn't menu items also be right-aligned** to make it easier to navigate the menu? The full menu item area may be selectable, but It's not always obvious (and not always implemented). Or do I miss something here? # Example !enter image description here !enter image description here
I would strongly advise against right text alignment from the readability point of view, at least for countries where the text is read from left to right. It is the same case as reading a book, if it would be right aligned, your eye would get quickly tired by searching the start of every line. See the image: !menu example Also when user knows what he is searching for, he can just scan through the first letters until he finds a match. That is much harder on the right example. The case of left handed users, covering parts of the menu while scrolling, can be solved by placing icons on the very left. You increase the legibility and make some space for the finger. See the example: !menu with icons example
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "navigation, mobile, mobile web, mobile application, alignment" }
Custom Post Type & Meta Box - Displaying meta box information on front end? I've created a custom post type "projects" that has a meta box for additional information (client name, type of project, budget, etc). I'd like to be able to display this information on the front-end. The custom post type is available to be added to custom menus if desired ('show_in_nav_menus' => true), but when you view each project, all you see is the title and the description. Ideally, I'd like the meta data to show with the title and description in whatever theme that is being used for the site, but I don't know if that's possible. Is there a way to display the meta box information on the front-end without having to either (a) touch the theme files (since themes can change so I don't want to do that) or (b) calling my own function that returns my own page template for the projects (because then it won't use the theme that is active)? Thanks! ETA - This is all done within my plugin.
Solution: Inside a function, retrieve meta box field values using get_post_custom_values() and added it to $content passed to the function. Use 'the_content' in the add_filter.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, metabox, front end" }
How can I get Carrot2 to save Basic Query? In the Search widget of Carrot2 (3.12.0.0), you can select the disk icon and do a "Save As...". This saves all the attributes of the Search widget (in our case we are using Solr, so it's all the Solr fields), but it doesn't save the Basic Query field (the only required field in the widget). In the image below, all the yellow highlighted fields are saved, but not the "Query (required)" field that is circled. I've downloaded the source from Git (< but I don't see how I can update the code to save this value or to even understand why it isn't saved by default. Any help would be greatly appreciated. ![enter image description here](
Seems to be a bug in the code. Or rather some special condition (why it's there, I can't tell). See this bug for the follow-up. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "carrot2" }
Inserting Column By Grouping Values in different column with Commas I have a dataframe as follows: COL1 COL2 Dest1 SMALL Dest1 MED Dest2 SMALL Dest3 LARGE I want convert it to this: COL1 COL2 COL3 Dest1 SMALL SMALL, MED Dest1 MED SMALL, MED Dest2 SMALL SMALL Dest3 LARGE LARGE I tried something like this but I don't know how to get the comma in there. library(dplyr) df2 <- df %>% group_by(COL1) %>% mutate(COL3 = paste(COL2))
Nevermind I figured it out: df2<-df %>% group_by(COL1) %>% mutate(COL3=paste(COL2, sep="", collapse=","))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, dplyr, paste" }
error: a function-definition is not allowed here before ‘{’ token I've been trying to solve the error. How do I solve it? I've tried putting the functions outside the main function but its still not working. int mutexlock = 1, full = 0, emp = 20, x = 0, buffer[100]; void producer(); void consumer(); int randomgenerator(); int main() { void producer() { int d = randomgenerator(); buffer[x] = d; cout << "\n" << d; x++; } void consumer() { x--; cout << "\n" << buffer[x] << endl cout << "sum" << buffer[x] << (buffer[x] + buffer[x]); } int randomgenerator() { int num = rand() % 6 + 1; return (num); } } Error: error: a function-definition is not allowed here before ‘{’ token {
You should put all functions out of the main function. Besides, please put the code you want to run after program starts in the main function. Example: int main() { producer(); consumer(); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "c++" }
Function for splitting by substring I have text Hi, my name is <b>Dan</b> and i need/n to separate string What I need is to find specific tags and separate text by predefined tags like /n or (b), the result need to be: Str[0] = Hi, my name is Str[1] = Dan Str[2] = and i need Str[3] = to separate string Can you please help me?
Try this : string[] separators = {"<b>", "</b>", "\\n"}; string value = "Hi, my name is <b>Dan</b> and i need \\n to separate string"; string[] words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -5, "tags": "c#" }
Embed MS Word as editor (like in Outlook) In Outlook you can use Word as your editor for emails (not sure what the situation is in Office 2007, but you can in 2003) Is it possible for me to replicate this in my own app? I've seen an article mentioning using the Web Browser component, opening a .doc file and turning on the right toolbars but I'm not sure if this is the right way?
You will need an ActiveX control to host Word in your application. [This article [msdn]]( can help you start, even though it is written for classic C++ and not C#. [This page [msdn]]( has some details on ActiveX/Windows Forms interoperability.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c#, ms word" }
Count sub directories that starts a specific character and specify length in windows I have a directory structure in Windows which looks like this: \Root \SUB-DIR1 \A1 \B1 \AA1 \SUB-DIR2 \A2 \C2 \AA2 \SUB-DIR3 \A3 \B3 \AA3 I would like to count _directories_ (not files) using a query such as _"starts with 'AA' and the the length of the subdirectory name is 3"_. I've tried: $f = get-childitem -Path C:\ROOT -recurse Write-Host $f.Count ...but I am not sure how to filter specific child items and get count of that. Powershell or Cmd would be of great help.
Match the directory names with a regex. Pattern `^AA.$` will match strings that begin (`^`), got (`AA`), have one more a character (`.`) and the string ends (`$`). As the dot will match just about anything, dirs like AAA, AAB, AA! etc are included too. Like so, # In addition, include only directories by checking PsIsContainer gci Root -Recurse | ? { $_.PsIsContainer -and $_.name -match "^AA.$" } As how to get the count, either output the gci into an array and check its count member or pass the results to `Measure-Object` and select the count member.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "windows, powershell, cmd" }
eigenvector equivalence for subspace of matrix? There is an eigenvalue $\lambda_1$ in matrix A, which is $3x3$, with corresponding eigenvector $x_a = 1/\sqrt{2}(1,0,1)$. The same eigenvalue $\lambda_1$ can be found in the subspace of matrix A, which is $2x2$, with corresponding eigenvector $x_b = 1/\sqrt{2}(1,1)$. Question: Could a zero be added to eigenvector $x_b$ such that it equals $x_a$? Matrix A = \begin{pmatrix} 1 & 0 & \lambda \\\ 0 & 0 & 0 \\\ \lambda & 0 & 1 \\\ \end{pmatrix} and the subspace of Matrix A = \begin{pmatrix} 1 & \lambda \\\ \lambda & 1 \ \\\ \end{pmatrix}
Depends on how you define equal, obvious $x_a \ne x_b$ in the exact sense since they DEFINITELY aren't the same thing (one has 3 dimensions the other has 2)! But... That doesn't mean they are not exhibiting some similar behavior. If you restate "equal" as "equal under a particular model" then the question becomes interesting again. It might be the case that there is a function $g$ out there such that $g(x_b) = g(x_a)$ where $g$ encodes some information about the matrix you are working with and the matching eigenvalues.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "linear algebra, eigenvalues eigenvectors" }
Which delimiter should be used for lists of values inside a CSV file? I have a CSV file that has lists of values for some fields. They're stored in the database as HTML "ul" elements, but I want to convert them into something more spreadsheet-friendly. What should I use as my delimiter? I could use escaped commas, pipes, semicolons, or pretty much anything else. Is there some kind of de facto standard people use for this?
Quotes around the item is for this 123, hello, "a, b, c, d", 29
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "csv" }
Remove Jetpack’s Open Graph meta tags for specific page I want to remove Jetpack’s Open Graph meta tags for certain page by page/post ID. I have tried to add this code to the theme function.php add_filter( 'jetpack_enable_open_graph', '__return_false' ); It works but for the entire post/page. So, how to make it only applied for a certain post/page ID?
You could try this: add_filter( 'jetpack_enable_open_graph', 'custom000_jetpack_enable_open_graph', 100, 2 ); function custom000_jetpack_enable_open_graph( $return_false, $int ){ if ( is_page() || is_single() ) { global $post; // Array of post IDs where you want it disabled $ids = array(1, 2, 3, 4, 5, 6); if( in_array($post->ID, $ids) ){ return false; } } return $return_false; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wordpress, jetpack" }
Dual Power Source for single output? In the world of USB, there's a type of cable with dual male head for 1 single female head, like this in below picture, while 1 head is for data+power and the other for power only. I have tested it could bring power to device with any 1 of the head (and without power loss when I unplug anyone of them) However, I do not find anything similar in 110/220v AC supply and all it suggested is by using Automatic Transfer Switch. Is it technically possible to have something similar in the AC world, making single-powered device having redundancy without ATS / UPS? Thanks everyone! ![enter image description here](
No, such a thing does not exist. No one would ever want to make or use such a cable because it will be dangerous for many reasons. First of all plugging only one plug to wall would leave the live parts of the second plug exposed for touching. If plugged to two different circuits, it will also be dangerous as it will connect the circuits together, which is something that should not be done. Some countries have unpolarized plugs so there is a 50% chanse you will plug it the wrog way and blow up fuses. If connected to outlets that are on a different mains phase (two phase or three phase household electricity) it will short out the two phases and blow the fuse. If redundancy is required, a device such as a redundant power supply will have two separate mains inlets.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "redundancy" }
Python: Rotate mxn array to an arbitrary angle I have matrix filled with zeros and a rectangle filled by ones on a region of this matrix, like this ![enter image description here]( and I want to rotate the rectangle to an arbitrary angle (30° in this case) like this ![enter image description here]( import numpy as np import matplotlib.pyplot as plt n_x = 200 n_y = 200 data = np.zeros((n_x, n_y)) data[20:50, 20:40] = 1 plt.imshow(data) plt.show()
How about using scipy? import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import rotate n_x = 200 n_y = 200 data = np.zeros((n_x, n_y)) data[20:50, 20:40] = 1 angle = 30 data = rotate(data, angle) plt.imshow(data) plt.show() Of course this is around the middle of the image. If you want to rotate around the center of the rectangle, I would suggest translating it to the middle of the image, rotate it and then translate it back.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, python 3.x, linear algebra" }
How to give customise name in SSL layer in website name? I am wondering if there is any way to give Company name in SSL layer. Check below example: If we refer facebook website then it shows its URL as < But if we refer below website then it shows company name: < (shows **oDesk Corporation [US]** in green color followed by < ) Visit these website and check website URL to understand difference. how it comes ? What is the process of this?
That's an Extended Validation -- or EV -- certificate. The process to obtain one is generally more long and complex than the process to get a standard SSL cert, and they cost a lot more. For comparison, take a look at Namecheap's selection of domain validated certificates vs their EV certificates. The descriptions (and prices) given there should help give a better idea of the difference.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ssl, https, ssl certificate" }
Error Placement of a Form I'm trying to use the following plugin wiht the second form where it places all the error messages inside of its separate div. Only difference is they place it above it and I'm placing mind below. However its still not displaying the messages inside the div for me. Not sure why. < Demo: < **Edit** : I updated my code want to show what I have now to how it's not placing the error messages inside of the div I have made for errors when there are errors for the form submission. Updated Demo: <
You need to use `errorPlacement` to put the error messages where you want them, otherwise it will use the default method of appending them to the input: // container is the element which should hold errors, // You have already definied it in your demo errorPlacement: function(error, element) { error.appendTo(container); }, Updated demo: < Check the docs for more info: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, jquery validate" }
How to prove Integral result I am trying to solve a integral through `Mathematica`, `Mathematica` gives me the following answer !enter image description here My question is how to solve this integral manually to get the `Mathematica` result or can we prove two integrals are equal?
Substitute $$z = \frac{w}{1-w} \iff w = \frac{z}{1+z}.$$ Then you have $dz = \frac{dw}{(1-w)^2}$, $1+z = (1-w)^{-1}$ and you obtain $$\begin{align}\int_0^\infty z^{-\frac{r}{\beta}}[1+z]^{-\frac{\alpha}{\gamma}-1}\,dz &= \int_0^1 \left(\frac{w}{1-w}\right)^{-\frac{r}{\beta}}[1-w]^{\frac{\alpha}{\gamma}+1}\,\frac{dw}{(1-w)^2}\\\ &= \int_0^1 w^{-\frac{r}{\beta}}(1-w)^{\frac{r}{\beta}+\frac{\alpha}{\gamma}+1-2}\,dw. \end{align}$$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "integration" }
Apache Redirect Help 'Pretty Links' I have < I want to be able to go to < but only have to type < would this work:? RewriteRule (.*) [L] What ever Cpanel uses
For static files, enabling `Options +MultiViews` is sufficient. No rewrites needed.
stackexchange-serverfault
{ "answer_score": 0, "question_score": -1, "tags": "apache 2.4, https" }
Use \pgfmathresult in siunitx I try to do some calculation and then want to use the result in a `siunitx` `qty`. However, this fails and I don't know why. \documentclass{article} \usepackage{pgfplots, siunitx} \newcommand{\scale}[1]{\pgfmathparse{#1/3.13-0.3}\pgfmathresult} \begin{document} Without siunitx: \(\scale{5}\) With siunitx: \(\qty{\scale{5}}{\celsius}\) \end{document}
You can't use a non-expandable command inside the number part of `siunitx`.* The entire reason `\pgfmathparse` sets `\pgfmathresult` is because `\pgfmathparse` is not expandable. You could use a wrapper around `\qty` that does the assignment then only passes the result, but with `siunitx` v3 you can use an expression directly \documentclass{article} %\usepackage{xfp} % pre-2022-06-01 LaTeX \usepackage{siunitx} \newcommand{\scale}[1]{\fpeval{#1/3.13-0.3}} \begin{document} Without siunitx: \(\scale{5}\) With siunitx: \(\qty[evaluate-expression]{\scale{5}}{\celsius}\) \end{document} (You don't _need_ `\fpeval` for this to work with `siunitx`, but you do for it work outside of `\qty`.) * * * * In LuaTeX one can use `\immediateassignment`, but I will ignore that here!
stackexchange-tex
{ "answer_score": 11, "question_score": 6, "tags": "tikz pgf, pgfmath" }
Do all primes occur in some sequence associated with the Collatz conjecture? Let $f(n) = \begin{cases} n/2, & \text{if $n$ is even} \\\ 3n+1, & \text{if $n$ is odd} \end{cases}$ For an arbitrary prime $p$ are there some start value $x_0$ such that $p = x_k$ for some $k > 0$ in the sequence defined by $x_{n+1} = f(x_n)$? I was confused. What I really wondered, turns out to be if all primes $> 3$ could be written as $3n + 1$ with $n$ odd, which is also trivially true. Or? No! I'll try again without Collatz. * * * Define $f(p_1^{n_1} \cdots p_k^{n_k}) = p_2^{n_2}\cdots p_k^{n_k}$, where $p_k$ is the $k$th prime. Is any prime $> 3$ in the image of the function $g:\mathbb N\to\mathbb N$, defined by $g(n) = f(3f(n) + 1)$. I see now that all odd numbers not divisible by $3$ are in the image.
Yes, just take $x_0=2p$ and then $x_1=p$.
stackexchange-math
{ "answer_score": 8, "question_score": 2, "tags": "prime numbers, conjectures, collatz conjecture" }
How does computer really request data in a computer? I was wondering how exactly does a CPU request data in a computer. In a 32 Bits architecture, I thought that a computer would put a destination on the address bus and would receive 4 Bytes on the data bus. I recently read on the memory alignment in computer and it confused me. I read that the CPU has to read two times the memory to access a not multiple 4 address. Why is so? The address bus lets it access not multiple 4 address.
The address bus itself, even in a 32-bit architecture, is usually not 32 bits in size. E.g. the Pentium's address bus was 29 bits. Given that it has a full 32-bit range, in the Pentium's case that means each slot in memory is eight bytes wide. So reading a value that straddles two of those slots means two reads rather than one, and alignment prevents that from happening. Other processors (including other implementations of the 32-bit Intel architecture) have different memory access word sizes but the point is generic.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "memory management, cpu, cpu architecture, memory alignment" }
How do I hide certain fields in the ShowingPopupEditForm programmatically in Devexpress I'm editing cells in a Devexpress gridview in a Form. I chose to have a pop-up edit form open when I'm editing. Now I don't want all the fields to show in the pop-up form. How do I go about hiding certain fields in the ShowingPopupEditForm. I would like to accomplish this in code. See pic. ![enter image description here](
use this : gridView.Columns["columnName"].OptionsEditForm.Visible = DefaultBoolean.False;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "gridview, devexpress" }
Protect SFTP Passwords A number of non-technical users currently manage secure data with FileZilla on Windows. The SFTP credentials are broadly shared in the organization as a result. I would like to centrally manage credentials so that users cannot directly view them. With FileZilla, the credentials are stored in a non-encrypted file, Settings.xml. Is there an approach using any user-friendly, Windows SFTP client to centrally manage SFTP credentials and prevent users from directly having access to the credentials?
Don't use passwords. Use SSH Keys. With SSH Keys, each user has his own private key(s) which are shared with no one. On each server+account for which you want to grant that user access, you add the key signature to the `authorized_keys` file. If you ever want to revoke access, you remove that user from the file. You can also specify restrictions on what each user (i.e. each key) can do, so if you log in with a given key certain limitations apply.
stackexchange-serverfault
{ "answer_score": 19, "question_score": 4, "tags": "sftp, credentials" }
sscanf and multiple %ms When `sscanf()` gets two "%ms" in the format string. Is it safe to call free() for both target pointers, when the `sscanf()` returns 0 or 1? Like in the next function: void foo(const char* text) { char* key = NULL; char* value = NULL; int count = sscanf(text, "%ms %ms", &key, &value); if (count == 2) { ... } free(key); free(value); } Or can the later target pointer (`value`) have some garbage value? And the following cleanup is needed: void bar(const char* text) { char* key = NULL; char* value = NULL; int count = sscanf(text, "%ms %ms", &key, &value); if (count == 2) { ... free(key); free(value); } else if (count == 1) { free(key); } }
First, you should be aware that `m` in a conversion specification is **non-standard** , so you should think about using it twice: Your code will be non-portable. But then, if your implementation supports `m`, this usage is **safe** as long as you initialize your pointers to `0`/`NULL`. `scanf()` never touches anything when there's no conversion possible and `free(0)` is specified to be a _no op_ (it's always safe).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c, scanf" }
Access element by ID in javascript I accidentally discovered that you can access element just typing it's id e.g: <input id="test" value="testValue"/> <script> console.log(test.value); //testValue </script> Can anyone point me please where that feature coming from? (it is really hard to google things like that)
From the spec: > **window[name]** > > Returns the indicated element or collection of elements. > > As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, html" }
Does HttpClient spin a new thread even if I immediately get the Result of the returned task? In my application I like to try and be consistant and use HttpClient whenever I can. However, sometimes I dont need the asynchronous properties of HttpClient and so I simply get the Result of the Task as soon as it is returned as demonstrated in the code below. public HttpResponseMessage httpPostWrapperMethod(string postBody, string url) { HttpContent content = new StringContent(postBody, Encoding.UTF8, "application/json"); HttpClient client = new HttpClient(); return client.PostAsync(url, content).Result; } My two part question is this: Does this code cause a new thread to be spun in the background when making the call? and If my calls to this other service are taking around 500ms, is this going to cause me to eat up too many threads when the service is under a production load of around 100 requests/second?
`PostAsync` doesn't result in a thread being created, no. In fact, were the code to be used asynchronously no thread would ever need to be doing anything for this work to be done. In your case here you're having the current thread sit around doing nothing while you wait for the operation to finish, so that is the only thread who's time is being consumed/wasted when performing this operation.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c#, asp.net, async await, dotnet httpclient" }
What is LFI vulnerability LFI: Local file inclusion. After going through many tutorials I have two things I can/t figure out: 1. checking the vulnerability: I don't understand what makes a website vulnerable or not. For example, in the stackexchange network itself we can make changes in the url: < <\-- for asking a question. < <\-- tags so I can go to any location in the site which means it is vulnerable to LFI, right? 2. Is this vulnerability specific to sites run on linux/unix? what if the site doesn't contain /etc/psswd directory would it be vulnerable.(What if there is no such directoryin the site)
The idea of a Local File Inclusion issue is that you can use the web application to load up files on the filesystem that either shouldn't be available (e.g. things outside the web root) or files within the webroot that shouldn't be loaded up inside a page. So for example > < in this application the file parameter is used to specify the page that the application should load up, in this case main_page.php. If the attacker can change it to > < he can get access to that file from the system, which could be useful for him in attacking the system. Alternatively he might be able to load a config file which contains application/database passwords. In terms of vulnerability, any web application language/framework could suffer from this, but PHP does seem to be particularly prone to this and Remote File Inclusion issues.
stackexchange-security
{ "answer_score": 10, "question_score": 2, "tags": "webserver, known vulnerabilities" }
typewatch jquery callabck not updating html I am using the typeWatch plugin to monitor a text field and I want to send a callback to a controller to then replace a divin the view. The event is hitting the controller but I cannot seem to get the div to update the contents: $(function() { $("#start_date").typeWatch( { highlight: true, callback: finished } ); function finished(date) { $.post('/matches/watch', { 'date': date, complete: function(request){ $('#watch').effect('highlight', {color: "#C3FF29"}, 2000); }, }); } }); #match_controller def watch @preview_start_date = params[:date] respond_to do |format| format.js end end #watch.html.js $("#watch").html(<%= @preview_start_date %>); Any help?
Try this: $("#watch").html('<%= @preview_start_date %>'); And also indicate to jQuery that you will be returning javascript from your controller: $.post( '/matches/watch', { 'date': date }, function(request) { $('#watch').effect('highlight', {color: "#C3FF29"}, 2000); }, 'script' );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, ruby on rails" }
A subgroup of full measure is dense given a haar measure I want to know why if $\mu$ is a haar measure on a compact $G$ and $\mu(A)=\mu(G)$ then $A$ is dense in $G$. This fact is mentioned in the wikipedia page, but I couldn't find a proof for it.
In fact, every subset of full Haar measure must be dense. This follows from the following statement, that you can also find on the wikipedia page: **Claim** If $U$ is a nonempty open set in the locally compact group $G$, then the left Haar measure satisfies $\mu(U)>0$. **Proof:** We will use the fact that Haar measure is inner regular, so there must be some compact set $K \subset G$ with $\mu(K)>0$. Given a nonempty open set $U \subset G$, fix some $u\in U$, and note that the sets $\\{gu^{-1}U: g \in K\\}$ form an open cover of $K$. There is a finite subcover $\\{g_ju^{-1}U: 1 \le j \le m\\}$. If $\mu(U)=0$ then this finite subcover, and the left-invariance of Haar measure, would yield $\mu(K)=0$, a contradiction.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "measure theory, lie groups, topological groups, haar measure" }
Is there an official name for visual puzzles based on observation skill? Is there a common/official name for visual puzzles that are based strictly on the observation skill - like the common "Where is Waldo" pictures, "find all faces", "count all X in the picture (or find a given number of them), "Spot a thief" and the likes - where the visual mess or tricky composition of the image obscures the location of the puzzle target?
In the online realm, these are known as "hidden object/picture" games, and the definition also matches those which appear in books. From Wikipedia (emph. not mine): > A **hidden object game** (sometimes called **hidden picture** ) is a genre of puzzle video game in which the player must find items from a list that are hidden within a picture. In essence, "Where's Waldo" is just a simpler version of this game, in which the list of items you are looking for has a length of one (though if I recall, there are sometimes more objects to find in Waldo). Physical copies of these games also, I believe, can go by the same name.
stackexchange-puzzling
{ "answer_score": 11, "question_score": 11, "tags": "puzzle identification" }
Replacing sublists with their last element (defun rep(list) (format t"~a~%" list) (cond ((null list) nil) ((atom (car list)) (cons (car list) (rep (cdr list)))) ((listp (car list)) (cons (car (reverse (car list))) (cdr list))) (t (rep list)) ) ) Write a function to replace each sublist of a list with its last element. A sublist is an element from the first level, which is a list. Example: (a (b c) (d (e (f)))) ==> (a c (e (f))) ==> (a c (f)) ==> (a c f) (a (b c) (d ((e) f))) ==> (a c ((e) f)) ==> (a c f) I have the above problem to solve. Got it till one point but I'm stuck. Apparently it doesn't go to the next elements in the list and I don't know why. Any ideas?
Did it without using map functions (defun rep(list) (cond ((null list) nil) ((listp (car list)) (rep (cons (car (reverse (car list))) (rep (cdr list))))) (t (cons (car list) (rep (cdr list)))) ) )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "lisp, common lisp" }
Suppose $B$ is an invertible integer matrix and $\det B = \pm 1$. Why must $B^{-1}$ be an integer matrix by Cramers rule? Suppose $B$ is an $n \times n$ invertible matrix with integer entries. Suppose I know $\det B = \pm 1$. How is it then "obvious" by use of Cramers rule that $B^{-1}$ also has integer entries ? I know Cramers rule reads: $$Bx = b \Rightarrow x_{i} = \frac {\det B_i} {\det B} = \frac {\det B_i} {\pm 1}$$ I see that this give me information regarding $x$, but it should provide information regarding $B^{-1}$ ?
Let's take the standard basis of $V_n$, $\\{e_1,e_2,\ldots,e_n\\}$. $$B\text{ invertible} \implies Bx=b\text{ has unique solution for all }b\in V_n,\text{ namely }x=B^{-1}b$$ Columns of $B^{-1}$ are $B^{-1}e_1,\;B^{-1}e_2,\;\ldots,B^{-1}e_n$ where $B^{-1}e_k$ has components of the form $\frac{\det B_i}{\pm 1}$, which are clearly integer numbers, $i=1,2,\ldots,n$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "linear algebra" }
Immutable attribute or Immutable wrapper object - which one? Quick question for those that might know! It appears there are two ways to mark a message as immutable in Orleans.. new Immutable(...) or with an attribute [Immutable] on the message class Which is preferred and more importantly why - or is it just a matter of personal taste?
[Immutable] applies to all instances of that class (everywhere you use it, the instances of this class will be considered as Immutable), while new Immutable(...) applies to every instance usage (at one place you can pass your class as mutable and at other place as Immutable). If all instances of this class will be always Immutable, [Immutable] is a more terse and elegant approach.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "orleans" }
Sri Lanka: visa requirements and possibility of visa on arrival at airport? I'm am European (French) and plan a holiday in Sri Lanka. Do I need to apply for a visa to stay there for 3 weeks? If yes, do I have to get the visa before going there (ie. through ambassy) or can I simply get it when I arrive (at the airport)? I found this ETA website for the electronic visa but it kinda looks old so I'm unsure if I should take this seriously.
You can purchase a visa on arrival by paying USD or Sri Lankan rupees. The ETA website does work, despite not looking very slick. I've tried out both methods as I typed in my passport number incorrectly to the ETA website. Immigration did not accept by online ETA receipt as it didn't match my passport. I was then forced to purchase the ETA on the spot.
stackexchange-travel
{ "answer_score": 2, "question_score": 2, "tags": "visas, visas on arrival, sri lanka" }
What does "compiz --replace" do? Sorry for the stupid question but I am new with Linux (I am using Gnome classic with Ubuntu 12.04) and I cannot set compiz in order to obtain the rotating cube. I have already installed compizconfig-setting-manager and also the extra (and fusion) plugins but: * even if I disable the desktop wall and enable cube and rotating cube, nothing happens; * even if I change into general settings the number of vertical and horizontal virtual size nothing happens. What I need is (possibly) a step by step answer. Thank you * * * Ok...I solved my problem by using the command. compiz --replace which I have found looking around. Can someone explain me what I have precisely performed with this command? Thanks in advance
With `compiz --replace`, you have replaced any existing window manager with Compiz; if you were already using Compiz, you have "reset" (or re-initialized) it -- which probably explains why this command solved your problem by finally applying your custom settings.
stackexchange-askubuntu
{ "answer_score": 7, "question_score": 5, "tags": "compiz" }
Convert quaternion from right-handed to left-handed coordinate system I my 3d program, the rotation of object is represented by the quaternion like `[0.130526, 0.0, 0.0, 0.991445]`. The program works with right-handed coordinate system with the Z axis pointing up (like in 3ds max): !enter image description here On the other hand, my application use **left-handed** coordinate system **and the Y axis is up** : !enter image description here How can I transform my quaternion from one coordinate system to another, with the respect for which axis is up?
A rotation of angle x around axis (u,v,w) can be represented by quaternion with real part cos(x/2) and unreal part sin(x/2)*(u,v,w). If axis coordinates are (u,v,w) in original trihedron, they will be (u,w,v) in your trihedron. Thus if original quaternion was (a,b,c,d) - a+ib+jc+kd - the quaternion must be transformed to (a,b,d,c) in your trihedron. **EDIT** But because your trihedron is left handed, the angle also has to be reversed, so the same rotation can finally be expressed by the quaternion (a,-b,-d,-c) in your trihedron.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 13, "tags": "math, graphics, 3d" }
Getting results of Google Scholar search with selenium and PhantomJS The following code is supposed to print the contents of this page. from selenium import webdriver driver = webdriver.PhantomJS() link = u' driver.get(link) print driver.page_source However, all it prints is: <html><head></head><body></body></html> If I use `webdriver.Firefox()` instead of `webdriver.PhantomJS()`, it works. I know that `PhantomJS` is properly installed, since the above code used to work just fine. What could this mean?
Which version of Selenium/PhantomJs are you using? I tried with: * Selenium 3.6.0 * PhantomJs 2.1.1 this: from selenium import webdriver driver = webdriver.PhantomJS(executable_path=r'PathTo/phantomjs-2.1.1-macosx/bin/phantomjs') link = ' driver.get(link) print (driver.page_source) and it works.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "selenium, web, phantomjs" }
Reaching Start Menu Directory on Windows Vista and 7 I'm creating a new shorcut within and update of my program on the Start Menu I worked getting the Special Environment variable ALLUSERSPROFILE and it worked for me under XP, it returns the right path, when using it under vista ir returns c:\ProgramData which is useless. Reading the Environment variable StartMenu is also pointless it returns empty string. ( On vista it lies under Windows\Start Menu, in english ,and if the install folder Windows has the default name) Does anyone has an Idea how to get the startmenu directory for the 'All Users". and would it be a generic solution that works under XP and Vista?
You want `CSIDL_COMMON_STARTMENU`. This doesn't appear to be defined in the `Environment.SpecialFolders` enumeration, but you can use the Win32 API via P/Invoke: [DllImport("shell32.dll")] static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, bool fCreate); int CSIDL_COMMON_STARTMENU = 0x16; StringBuilder path = new StringBuilder(260); SHGetSpecialFolderPath(IntPtr.Zero, path, CSIDL_COMMON_STARTMENU, false); > CSIDL_COMMON_STARTMENU (FOLDERID_CommonStartMenu) The file system directory that contains the programs and folders that appear on the Start menu for all users. A typical path is C:\Documents and Settings\All Users\Start Menu. Valid only for Windows NT systems.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, winforms" }
CSS / Page Loading Speed Just wanted to get a few opinions really, I'm trying to increase the loading speed of my site, and one way that Google pagespeed has suggested is to remove the unused CSS from my CSS file for each page. At the moment I am using one master CSS file for every page on the site. My question is would having individual CSS files for each page make overall loading times quicker ? I guess the first page would load quicker, but then each page would have a different CSS file which could potentially end up taking longer over a whole site visit ? Also pagespeed seems to warn against including multiple CSS files so I guess I can't really 'layer' them up...
There are two optimisation directives that contradict each other in this case. Of course you should reduce the size of the files if possible, but you should also have as few requests as possible. Using a global style sheet reduces the number of requests, but it means a larger file. You just have to look into where your needs are. If you need to reduce the initial load time, you should move styles out of the global style sheet. If you need to reduce the number of requests, you should use a global style sheet rather than individual page style sheets.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "css, seo, performance" }
Explain find command with options I am fairly new to more complex linux commands and this one has a bunch of options and flags that I have never seen and piecing these together just won't click in my brain. `find /external-disk/postgresql_wals_backup -type f -mtime -2 -exec cp {} /work-disk/postgresql-scripts/wal_backup_script_dir/ \;`
* `find` : command * `/external-disk/postgresql_wals_backup` : the path we are searching in * `-type f`: only look for files (No directories, links, etc) * `-mtime -2`: only look for files that have been modified 48 hours ago (-2: 2*24) * `-exec cp {} /work-disk/postgresql-scripts/wal_backup_script_dir/ \;`: * execute `cp` command on each file you have found * `{}` is just a placeholder for files that we found * Which copies all files that have been found to `/work-disk/postgresql-scripts/wal_backup_script_dir/`.
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 1, "tags": "command line, find" }
What rights do you need for Ola's integrity check? I'm configuring a new server and Ola's integrity check is working for user databases (I have restored a database of around 50 GB for tests) and is failing for system databases. If I look in the logs it works for `model` and fails for `master` and `msdb` with `The database could not be checked as a database snapshot could not be created...` The SQL Agent account is sysadmin. It works if I add the SQL Server and SQL Agent account as administrators of the Windows Server, so it's some rights missing somewhere. It's a VM running Windows Server 2016 version 1607, I don't have access to the Hyper-V host but it's probably the same version. Same result with SQL Server 2017 and SQL Server 2014. Seems to be caused by Windows Server 2016, maybe some group policies settings.
This sounds like more of an issue with `DBCC CHECKDB` being run than anything specific to Ola's. Since you're probably creating snapshots, the service account will need to have access to the database directory folders in order to create snapshots there. You could work around this temporarily by peforming a physical only `CHECKDB` as well.
stackexchange-dba
{ "answer_score": 2, "question_score": 0, "tags": "sql server, ola hallengren, windows server" }
$X,Y$ are homotopy equivalent, so the number of connected component in $X$ and $Y$ is equal $(X,\mathcal{T}),(Y,\mathcal{O})$ are homotopy equivalent, denote the homotopy equivalent functions by $f$ and $g$ ($f\circ g\simeq Id_Y, g\circ f\simeq Id_X$). from $f,g$ continuity , taking a connected component $[x]$ (A maximal connected subset of $X$) we get $f([x])$ is connected in $Y$, $g(f([x]))$ is connected in $X$. I was trying to show that $f([x])$ must be c connected component in Y, an another approach was assuming $[x_1],[x_2]$ are mapped by $f$ to $[y]$, means $f([x_1]\uplus [x_2])\subset[y]$ and then I tried to work with the Homotopy $F:X\times I\rightarrow X$ between $f\circ g$ to $Id_X$ , yet I didn't succeed in getting a contradiction.
Suppose that $gf\overset{H}{\simeq}\mathrm{id}_X$, where $H\colon X\times I\to X$ is continuous satisfying $H(\cdot,0)=gf$ and $H(\cdot,1)=\mathrm{id}_X$. Note that if $Z$ is a connected component of $X$, then $Z\times I$ is connected, from which it follows that $H(Z\times I)$ is contained in some component of $X$. However $H(Z\times\\{1\\})=\mathrm{id}_X(Z)=Z$ and this shows that $gf(Z)=H(Z\times\\{0\\})\subset Z$. Analogous argument also applies to $fg$. Then it can be seen that $f$ induces a bijection between the sets of connected components of $X$ and of $Y$.
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "algebraic topology" }
How can I calculate NSString max length which UILabel can contain without truncate the text? I have two UILabels, one above the other. The top one has fixed size (2 Lines), and the bottom one can expand (0 lines). The text which I using for the labels can be short and sometimes it can be very long. How can I calculate the first UILabel max string length without cut a word in the middle? //Here is the code which create the 2 labels. titleView = [[UILabel alloc] initWithFrame:CGRectMake(70, 0, 200, 50)]; titleView.numberOfLines = 2; titleView2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 250, 100)]; titleView2.numberOfLines = 0;
I've solved the problem with this method: + (int)getSplitIndexWithString:(NSString *)str frame:(CGRect)frame andFont:(UIFont *)font { int length = 1; int lastSpace = 1; NSString *cutText = [str substringToIndex:length]; CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)]; while (textSize.height <= frame.size.height) { NSRange range = NSMakeRange (length, 1); if ([[str substringWithRange:range] isEqualToString:@" "]) { lastSpace = length; } length++; cutText = [str substringToIndex:length]; textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)]; } return lastSpace; }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "iphone, ios, xcode, nsstring, uilabel" }
What is the status of a Stripe subscription AFTER a trial is over? When a user registers, I'm creating a subscription with: const stripeSubscription = await stripe.subscriptions.create({ customer: req.body.stripeCustomerId, items: [{ price: process.env['STRIPE_PRICE_ID'] }], trial_period_days: 7 }) This goes ahead and creates a subscription with a status of `trialing`. What happens when the trial expires? Assuming the person does not have a payment method attached, I don't think it'll be `active`, will it? So then what status will the subscription have?
Yes, it will become `active`. You can confirm this yourself in test mode using `trial_end={A_FEW_MINUTES_FROM_NOW}`. Assuming the associated Price is for a non-zero amount, a draft invoice will be create as happens with normal billing cycle renewals, but that invoice will remain open unless you set up a Payment Method to use or explicitly `/pay` it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "stripe payments" }
htaccess modrewrite regex duplication So I have RewriteEngine On RewriteBase /blog/ RewriteRule ^/blog/(.*)$ /$1 and I'm trying to redirect all: /blog/blog/xxxxxxx to /blog/xxxx For some reason it doesn't seem to work... Any thoughts?
NVM... solved by doing the following: RewriteRule ^blog/(.*)$ $1 [R=301,L]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "regex, .htaccess, mod rewrite" }
не работают стили при input[type=radio]:checked label{ width: 300px; position: relative; background-color: orange; } label::after{ content: ""; width: 30px; height: 30px; background-color: red; position: absolute; } input[type=radio]:checked label::after{ background-color: blue; } <label for="test"> <input type="radio" id="test"> </label>
Увы, но CSS не умеет смотреть "назад", точнее обращаться к родительскому элементу.. А ваш `label` как раз является родителем `input`. По этому придётся выкручиваться как-то так: label{ width: 300px; position: relative; background-color: orange; } label::after { content: ""; width: 30px; height: 30px; background-color: red; position: absolute; } input[type=checkbox]:checked ~ label::after { background-color: blue; } <input type="checkbox" id="test"> <label for="test"></label> * * * А ещё у вас ошибка, в HTML вы пишите `<input type="radio">`, а в CSS обращаетесь к `checkbox`.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, css" }
Finding Probability of P(S|W) at Bayesian Network of Rain Problem I am studying Bayesian Networks. Given that variables: $W$: Wet grass $R$: Rain $S$: Sprinkler I know the probabilities of: $P(C)$ $P(S | C)$ $P(S | !C)$ $P(R | C)$ $P(R | !C)$ $P(W | R,S)$ $P(W | R,!S)$ $P(W | !R,S)$ $P(W | !R,!S)$ with them how can I calculate: $P(R|W) = ?$ and $P(R|S, W) = ?$ Here is my Bayesian Network: !enter image description here **PS:** I could calculate P(S) and P(R). If anybody can just show me how to find **P(R|S)** I may solve this question.
The key thing to remember here is the defining characteristic of a Bayesian network, which is that each node only depends on its predecessors and only affects its successors. This can be expressed through the _local Markov property_ : each variable is conditionally independent of its non-descendants given the values of its parent variables. In this case, that means that $S$ and $R$ are conditionally independent given $C$: $$P(R=r\wedge S=s \;\vert\; C=c)=P(R=r \;\vert\; C=c)\cdot P(S=s \;\vert\; C=c),$$ for any truth values $r,s,c$. With this in hand, you can calculate any conditional probability you want. For example, $$ P(R|S)=\frac{P(RS)}{P(S)}=\frac{P(RS | C)P(C) + P(RS| !C)P(!C)}{P(S|C)P(C)+P(S|!C)P(!C)}=\frac{P(R|C)P(S|C)P(C)+P(R|!C)P(S|!C)P(!C)}{P(S|C)P(C)+P(S|!C)P(!C)}.$$
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "probability, bayesian network" }
Show $\phi(n)$ = $n \Pi_{p \vert n} (1 - \frac{1}{p})$ (Here $\phi$ is the Euler Totient Function, $p$ all the primes dividing $n$) So I wanted to know is the best way to prove this using induction on $n$? or to suppose cases where $n$ is prime or composite? which would be the best approach? I am lost on how to approach this..
**Hint** : > Let $p$ be a prime such that $p \not\mid n$, then $$\phi(pn)=(p-1)·\phi(n)$$ Let $p$ be a prime such that $p\mid n$, then $$\phi(pn)=p·\phi(n)$$ Prove and apply these properties to all prime factors of $n$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "number theory, elementary number theory, proof verification, alternative proof" }
Client Server C++ Windows Application Suppose I have 3 computers each collecting data and storing that data in files on the hard drive. I would like those computers to send those files to a 4th computer. What is the simplest way to accomplish this?
The simplest way I can think of would be to have the 4th computer advertise a shared network drive, and then have the 3 computers mount that drive as a pseudo-local drive (N:\ or whatever). Then all the 3 computers have to do is write or copy the files onto n:\whatever_folder. No network programming required.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c++, windows, client" }
What are the limitations of Toad for SQL Server freeware? I just downloaded the freeware version of Toad for SQL Server. Toad's download site says: "the Freeware edition has certain limitations, and is not intended to be used as a TRIAL for the Commercial edition of Toad for SQL Server." It also says that no more than 5 people from my organization can use the freeware version, and that I'm not entitled to hard-copy documentation, phone assistance, tech support or upgrades. Is the product fully functional besides that?
The Toad site has documentation on the limitations of Toad Data Modeler but not for Toad for SQL Server or Toad for Oracle. I found a blog post "I love the new Toad freeware!" on their site as well claiming that the new freeware is no longer **_"crippleware"_** the way it used to be. I've used the tool for a few days now, and there are lots of menu options disabled, so no, the product is nowhere close to fully functional.
stackexchange-dba
{ "answer_score": 3, "question_score": 3, "tags": "sql server, database design" }
Exibir elementos um por um com .each jquery Olá, pessoal. Eu estou tendo problemas com o .each do jQuery. Eu tenho um xml assim: <dados> <usuarios> <usuario id="1"> <login>usuario12</login> <senha>21</senha> </usuario> <usuario id="2"> <login>usuario23</login> <senha>23</senha> </usuario> </usuarios> e estou tentando ler ele assim com jQuery: $(xml).find("usuarios").each(function() { console.log($(this).find("usuario").text()); }); porém o console me mostra assim: > usuario1212usuario2323 Podem me ajudar?
Você deu .find por `usuarios`, mas você só tem 1 `usuarios`. Experimente colocar apenas `usuario`, desse jeito: var xml = '<dados><usuarios><usuario id="1"><login>usuario12</login><senha>21</senha></usuario><usuario id="2"><login>usuario23</login> <senha>23</senha></usuario></usuarios>'; $(xml).find('usuario').each(function () { console.log("id:" + $(this).attr('id')); console.log("login:" + $(this).find('login').text()); console.log("senha:" + $(this).find('senha').text()); }); <script src="
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
Angular Material - Hierarchical table Does anyone have a sample for a heirarchical mat-table ? The code in Angular tables Examples does have a detailed row. But I am looking for something with a parent child relation and lazy loading the details table on click of an expand button in the main table. Any help is much appreciated.
I think you are looking for this. < MatTable Expand Collapse Icon issue on pagination and sort
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "angular, angular material 6" }
javascript event for attachment downloaded? i have a page that generates a report, the report is sent to the browser as an attachment. what i would like to do is .. disable the generate report button , or show a spinny please wait, and when the attachment has finished being generated and has been sent to the browser i'd like to remove the spinny logo/re-enable the button.. is there a js event like, on attachmentcomplete or some such? thanks nat
> is there a js event like, on attachmentcomplete or some such? No. The downloading of files is entirely outside of JavaScript's control. The only way that comes to mind is having the script that generates the report update some sort of flag (e.g. a temporary file) that you can frequently poll from your page using Ajax. When the script is done generating the data, you would delete the flag. You'll need to decide if it's worth the effort just for a small UI effect, though.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "javascript, events, attachment" }
on cassandra Cluster getting error : *schema does not yet agree *, when creating keyspace I am getting error _schema does not yet agree_ while creating new key-space on cluster of three nodes. have tried restarting cluster but still getting the same error m using cassandra 0.7.4
Covered by < Short version: you need to upgrade to 0.7.8, then you need to follow the instructions at the above link to force the node with the inconsistent schema to rebuild it from one of the others.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "schema, cassandra, cluster computing" }
Using python 'requests' to send JSON boolean I've got a really simple question, but I can't figure it out how to do it. The problem I have is that I want to send the following payload using Python and Requests: { 'on': true } Doing it like this: payload = { 'on':true } r = requests.put(" data = payload) Doesn't work, because I get the following error: NameError: name 'true' is not defined Sending the _true_ as _'true'_ is not accepted by my server, so that's not an option. Anyone a suggestion? Thanks!
You need to json encode it to get it to a string. import json payload = json.dumps({"on":True})
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 27, "tags": "python, rest, python requests" }
Combining columns in table doesn't divide my columns equally I made a table, but when I tried to combine two columns, it didn't divide my table exactly in two, rather one part is larger than the other (as is shown in the image I added). What am I doing wrong? Thanks! \begin{table}[h!] \begin{center} \begin{tabular}{|l|c|c|} \hhline{|===|} \textbf{Trigger} & \multicolumn{2}{c|}{\textbf{99.9\% Efficiency Point [GeV]}}\\ & |y*| < 0.3 & |y*| < 0.6\\ \hline L1\_J20 & 132 & 141 \\ L1\_J40 & 205 & 215 \\ L1\_J50 & 235 & 247 \\ L1\_J75 & 318 & - \\ L1\_J100 & - & 414 \\ \hhline{|===|} \end{tabular} \caption{Caption} \label{tab:mjj} \end{center} \end{table} ![enter image description here](
I suggest using the `\thead` command from `makecell to have the`multicolumn`argument on two lines. \documentclass{article} \usepackage[T1]{fontenc} \usepackage{makecell, hhline, multirow} \renewcommand{\theadfont}{\normalsize\bfseries} \begin{document} \begin{table}[h!] \centering \begin{tabular}{|l|c|c|} \hhline{|===|} \multirowthead{2}{Trigger} & \multicolumn{2}{c|}{\thead{99.9\% Efficiency \\ Point [GeV] }}\\ & |y*| < 0.3 & |y*| < 0.6\\ \hline L1\_J20 & 132 & 141 \\ L1\_J40 & 205 & 215 \\ L1\_J50 & 235 & 247 \\ L1\_J75 & 318 & -- \\ L1\_J100 & -- & 414 \\ \hhline{|===|} \end{tabular} \caption{Caption} \label{tab:mjj} \end{table} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 0, "question_score": 0, "tags": "tables" }
Polygons in CSV, WKT coordinate order I have a text file with the data: 98923|Place1|31.144562;33.741344:31.171932;33.873543:31.103771;33.884808:31.073994;33.786865 342342|Place2|36.995064;7.632923:36.995880;7.849720:36.832218;7.848527:36.832191;7.633185 So I managed to create the coordinate string into a WKT format POLYGON ((31.144562 33.741344,31.171932 33.873543,31.103771 33.884808,31.073994 33.786865)) POLYGON ((36.995064 7.632923,36.995880 7.849720,36.832218 7.848527,36.832191 7.633185)) I imported them into QGIS but they are in the wrong location as coordinates are in the wrong order? Any ideas how I could fix this as my file have thousands of records
There's a `swapxy` plugin which claims to do exactly this. Its in the plugin repository, and is trusted. Here is a brown set of features, which when `swapxy` runs on them, produce the blue features, which are reflected in the Y=X line, which is the diagonal that runs between them. ![enter image description here](
stackexchange-gis
{ "answer_score": 2, "question_score": 0, "tags": "qgis, well known text" }
Is it possible to discover if picture was taken? I would like to discover that picture was taken by default camera app. Just like Google plus discovers it and upload it to server. I failed in finding it in documentation. Does anybody have a hint where to find this kind of information?
You can have 2 things as far as I know 1. An intent when media is added, which is the below I believe. I'm not really sure how much use it is in all cases, you should have to try it out :) Intent.ACTION_MEDIA_SCANNER_SCAN_FILE 2. You can keep an eye on the special kind of content you wish to know about when it changes. See for an exmple here: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, image, android camera" }
accessing arrays within NSMutabale array I have a NSMutableArray which stores multiple arrays, so my array looks like this: array: deals 1. [0] * [0] ID * [1] NAME * [2] DESCRIPTION * [3] PRICE 2. [1] * [0] ID * [1] NAME * [2] DESCRIPTION * [3] PRICE 3. [2] * [0] ID * [1] NAME * [2] DESCRIPTION * [3] PRICE How can I drill down into the array to access in information such as [1][NAME]? I have tried nesting objectAtIndex but it doesn't seem to work. Thanks
You have been able to access elements in an`NSMutableArray` using the shorthand accessors `[]` in objective-c for a while now (so shouldn't need `objectAtIndex`). NSString *name = myArray[1][1]; This is equivalent to: NSArray *entry = myArray[1]; NSString *name = entry[1]; Should be enough to access the **NAME** entry you are looking for. If this isn't working, verify that the elements are actually `NSArray` objects and not `NSDictionaries` \- if they are, you would use something more like: NSDictionary *entry = myArray[1]; NSString *name = entry[@"NAME"];
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "ios, iphone, arrays, xcode, parse platform" }
Компилятор, который не будет оптимизировать код Подскажите, а то хочу проверить кое-что, но не могу из-за оптимизации кода компилятором, а самих компиляторов пробовал уже штуки 4.
Практический каждый компилятор разрешает отключить оптимизацию. Например, для gcc используйте ключ `-O0`. (Вот ссылка на полную документацию.) Для MSVC используйте ключ `/Od` или свойства проекта Configuration properties -> C/C++ -> Optimizations. (Вот ссылка на полную документацию.) Для остальных компиляторов обратитесь к их документации. * * * Кстати, не все упрощения кода являются оптимизацией. Например, предвычисление константных выражений проводится независимо от ключей оптимизации. Пример: char buffer[sizeof(somestruct) + 1]; откомпилируется, выражение `sizeof(somestruct) + 1` будет вычислено во время компиляции, и такое вычисление не считается оптимизацией.
stackexchange-ru_stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "c++" }
How to connect vapor to mongodb atlas So I have a `vapor` \ `fluent` app that works fine with local mongo instance, here's current `mongo.json`: { "database" : "vapor", "port" : "27017", "host" : "127.0.0.1", "user" : "", "password" : "" } I've deployed a free `MongoDB Atlas` 3 replica set and I wonder how do I connect the app to it?
Fluent's MongoDB integration is using an outdated version of MongoKitten. Currently we're at MongoKitten 4. MongoKitten 1, which is being used in Fluent currently supports just a fraction of the features with a much worse performance.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "swift, mongodb, vapor, mongodb replica set, mongodb atlas" }
HybridUrlCodingStrategy not compatible with google? We use `MixedParamHybridUrlCodingStrategy` in our Wicket application in order to have pretty url parsed by google. Url pattern : The page has some ajax stateful components. When someone opens one of theses pages he is automatically redirected on : This is a problem for google which indicates crawling error due to the redirect. Have you any ideas of how to resolve this problem? Not redirecting when the user-agent is a robot?
Finally I solved the problem by making my page stateless. I used the framework jolira < to replace my links and a statelessForm in place of a classical form.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "seo, wicket, friendly url" }
Is there any way to detect an RTL language in Java? I need to be able to detect whether the current language my user is viewing is an RTL (Right To Left) language like Arabic. At the moment I'm just detecting this based on the language code from the system property user.language, but there must be a better way.
ComponentOrientation.getOrientation(new Locale(System.getProperty("user.language"))).isLeftToRight(); * Resource
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 16, "tags": "java, internationalization, right to left" }
How to move window using custom titleBar in Qt I'm beginner in Qt and I want to drag and move Window using my own custom titleBar(QLabel). The Qt code: void MainWindow::mousePressEvent(QMouseEvent *event) { mpos = event->pos(); } void MainWindow::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { QPoint diff = event->pos() - mpos; QPoint newpos = this->pos() + diff; this->move(newpos); } } This code allow me to move window by mouse pressed on any QWidget but I want to move window by mouse pressed on QLabel.
I suggest you to use `eventFilter` to get event `MousePress` and `MouseRelease`: void MainApp::mousePressEvent(QMouseEvent *event) { current = event->pos(); } void MainApp::mouseMoveEvent(QMouseEvent *event) { if(pressed) this->move(mapToParent(event->pos() - current)); } bool MainApp::eventFilter(QObject *object, QEvent *event) { if (object == ui->label && event->type() == QEvent::MouseButtonPress) { pressed = true; return true; } if (object == ui->label && event->type() == QEvent::MouseButtonRelease) { pressed = false; return true; } else return false; } This is a sample project for your question on github download here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c++, qt, window, mouseevent, move" }
ASP.NET MVC DropDownLists and foreign keys I am using a drop down list in my MVC app to select from a set of areas for editing or creating an entry the code looks like this: <%= Html.DropDownList("LocationID", ViewData["Areas"] as SelectList) %> ViewData["Areas"] = new SelectList(AreaHelper.Areas, tablet.LocationID); I am having issues with saving and updating the current `locationID` to the new selected value of the DDL, also when choosing the selected item on load when editing a current entry any pointers?
This is how i do it. public class ViewModel { public long Location { get;set;} } public ActionResult() { ViewData["Location"] = new List<SelectListItem> { new SelectListItem{ Name = "US", Value = "1" }, } return View(new ViewModel() { Location = GetOldValue() }) } \-- <%= Html.DropDOwnList("Location") %> This workes when using model binding and typed views.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "asp.net mvc" }
POST data with HEAD Request Is it possible to send POST data with a HEAD Request?
No, a HEAD request is different from a POST request. A HEAD request does not accept post data. From the HTTP specification section 9.4: > The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. Since a GET request does not contain post data, a HEAD request also does not.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "http headers, head" }
gke default-pools from clusters shows no number of nodes I've been having this issue that gcp says that there are "unscheduled pods" in my cluster. It then asks for increasing the node number, but even if I increased at the maximum permitted, the default-pool shows no nodes in this cluster. After the number of nodes was set to 0, it was set to 5 nodes but the gke cluster won't increase `kubectl get nodes` are returning "No resources found" and the `kubectl get pods` are also returning pods with "Pending" status
Were the nodes scaled up by the same user as who created the cluster? We found that the nodes were created but couldn't be assigned to cluster. This was logged: All cluster resources were brought up, but the cluster API is reporting that: only 0 nodes out of 5 have registered; cluster may be unhealthy. In the VM Instance Logs, the following error was logged: Supplied fingerprint does not match current metadata fingerprint.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "kubernetes, google kubernetes engine" }
Tag Badge rewording I was looking into the Tag Badge page, the text for the Silver says, "You'll have to earn 400 upvotes in non-community wiki questions to achieve this badge." I was wondering whether that meant questions or answers or both (knowing it at least meant answers), since they have columns for askers as well as answers. A little research showed that it meant answers only. How about we reword it to, "You'll have to earn 400 upvotes in _answers to_ non-community wiki questions to achieve this badge." The same for gold also.
Ya. This is confusing... probably it should be fixed. (Though it should be kind of obvious - why would you get a badge for asking questions?)
stackexchange-meta
{ "answer_score": 2, "question_score": 4, "tags": "feature request, tags, wording" }
Is there a way to automate azure shell scripts? I'm looking at the following documentation which Azure has provided for creating an API Management user and "subscription key":< so it would seem that there would be some way of triggering user creation via http request or something like that. Like you know how Google Cloud Functions lets you trigger a python script whenever it gets a pub/sub message? I need that except for this API Management Azure shell script, and I also need the output subscription key to be returned somehow. Is there support in Azure for shell script batch jobs that can access Azure CLI and also return the generated subscription key?
I think you are looking for PowerShell Azure Functions. Using Azure CLI in Azure Functions (if this is what you _really_ need) requires some additional work, but Azure PS modules are immediately available and in most cases sufficient. The script you are referring to uses Azure PS, not Azure CLI. Running it in Azure Functions should be easy.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "azure, powershell, azure functions, azure api management, azure cli" }
Counting item number in Python 'for'? > **Possible Duplicate:** > for x in y, type iteration in python. Can I find out what iteration I'm currently on? > Iteration count in python? Kind of hard to explain, but when I run something like this: fruits = ['apple', 'orange', 'banana', 'strawberry', 'kiwi'] for fruit in fruits: print fruit.capitalize() It gives me this, as expected: Apple Orange Banana Strawberry Kiwi How would I edit that code so that it would "count" the amount of times it's performing the `for`, and print this? 1 Apple 2 Orange 3 Banana 4 Strawberry 5 Kiwi
for i,fruit in enumerate(fruits, 1): print i, fruit.capitalize() will do what you want and print: 1 Apple 2 Orange 3 Banana 4 Strawberry 5 Kiwi By default enumerate() will start generating an index with 0 if not specified, but you can specify the starting value as shown.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "python" }
How to give alias to results returned after inner join in mySQL I need to do a correlated SQL Query and for that purpose i need to provide an alias to outer query which in which I perform an inner join. I am not able to do the alias SELECT DISTINCT(name) FROM PERSON INNER JOIN M_DIRECTOR AS dira ON (dira.PID = M_DIRECTOR.PID) as dira WHERE 9 > ( SELECT COUNT(MID) FROM M_DIRECTOR WHERE name = dira.name ) ;
I didn't really understand what you want to do, but I guess select distinct p.name, count(d.MID) cnt from hindi2_PERSON p inner join hindi2_M_DIRECTOR d on p.PID = d.PID group by p.name having count(d.MID) > 9 ; would do what you want
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, sql" }
GWT for cross device game development How does Google Web Toolkit do in deploying to browsers as well as mobile devices, tablets, televisions, etc.? Would a game targeting specific devices be optimized significantly for the device even when using GWT? **Edit** More specifically, I'm asking **how would a game written in GWT perform on a limited system (phone, tablet, tv, etc.)?** Are the general optimizations it does for different browsers good enough for other devices?
The GWT compiler tries to create browser-specific code, not device specific code. I haven't worked with it much lately, so I'm not sure what all the browsers it supports these days. Maybe it produces code especially for [desktop] chrome as well as [mobile] chrome. Since mobile is such a big focus these days, I'm sure the GWT compiler is also keeping those mobile browsers in mind.
stackexchange-gamedev
{ "answer_score": 3, "question_score": -1, "tags": "mobile, cross platform" }
ConfigParser.MissingSectionHeaderError when parsing rsyncd config file with global options A configuration file generally needs section headers for each section. In rsyncd config files a global section need not explicitly have a section header. Example of an rsyncd.conf file: [rsyncd.conf] # GLOBAL OPTIONS path = /data/ftp pid file = /var/run/rsyncdpid.pid syslog facility = local3 uid = rsync gid = rsync read only = true use chroot = true # MODULE OPTIONS [mod1] ... How to parse such config files using python `ConfigParser`? Doing the following gives an erorr: >>> import ConfigParser >>> cp = ConfigParser.ConfigParser() >>> cp.read("rsyncd.conf") # Error: ConfigParser.MissingSectionHeaderError: File contains no section headers.
Alex Martelli provided a solution for using ConfigParser to parse similar files (which are section less files). His solution is a file-like wrapper that will automatically insert a dummy section. You can apply the above solution to parsing rsyncd config files. >>> class FakeGlobalSectionHead(object): ... def __init__(self, fp): ... self.fp = fp ... self.sechead = '[global]\n' ... def readline(self): ... if self.sechead: ... try: return self.sechead ... finally: self.sechead = None ... else: return self.fp.readline() ... >>> cp = ConfigParser() >>> cp.readfp(FakeGlobalSectionHead(open('rsyncd.conf'))) >>> print(cp.items('global')) [('path', '/data/ftp'), ('pid file', '/var/run/rsyncdpid.pid'), ...]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 10, "tags": "python, rsync, configparser" }
Is it bad to use the built-in python on mac? I started learning python on a PC, by installing Python 3, and so when I switched to mac I thought "Look at that, you can just type idle in the terminal and there's Python 2, let me just use that," not wanting to have to deal with two versions on the same machine. However, I read that it's recommended to install a newer version of Python and not to mess up with the built-in install. Is it a bad practice to use the built-in version? For the matter, I'm not a heavy programmer, just like to play with Python every now and then. The only extra module I've installed was Pillow.
You can use the built-in Python, there's nothing "bad" about it. If someday you run into some limitation (unlikely), you can always switch then.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, macos, python 2.7, python 3.x, python imaging library" }
Convert document ready to on jQuery I'm trying to convert this document to `on()` but I don't know how. This is my code: $(document).ready(function() { var $sub = $("#removImg").hide(), $chnckbox = $('input[name="chkboxplat[]"]').click(function() { $#sub.toggle( $chnckbox.is(":checked") ); }); }); I tried `$(document).on(function(){`. Hope you can help me, thanks!
From the description of the issue in your comment you need to use a delegated event handler on the checkbox as it's dynamically appended to the DOM. To do this you do need to use `on()`, however the syntax you had was incorrect. You need to add a new event handler, not replace the document.ready handler. Try this: $(document).ready(function() { var $sub = $("#removImg").hide(); $(document).on('change', 'input[name="chkboxplat[]"]', function() { $sub.toggle(this.checked); }); }); Note the use of the `change` event, not `click`, so that the code works for users who navigate via the keyboard
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "jquery" }
Remote client can't connect to redisai docker container running in an Azure VM I am running two VM's in Azure. One contains the docker container running RedisAI. Accessing that one via the local VM (by ssh-ing into it) works just fine. The redisai container is run on this VM via the command: `sudo docker run -p 6379:6379 --gpus all -it --rm redisai/redisai:latest-gpu` The other VM runs a remote client trying to access the other VM `redis-cli -h <IP-ADDR>` which results in `Could not connect to Redis at <IP-ADDR>:6379: Connection timed out`
While typing up the question, I figured out the answer. I had to allow inbound port 6379 from all sources on both of the VM's in order to a connection to occur over the NSG. ![inbound port rule](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "azure, docker, networking, redis" }
Facebook App: Make the landing page redirect to a URL? Is it possible to make the landing page (what I understand by landing page: the page the user first sees when they view the FB app or the page they get redirected to after they accepted an invitation to the app, right?) redirect to some URL of my choosing? Like `mysite.com/User/Register`... would that work or does Facebook not allow that?
You should be able to configure the landing page to be whatever you want it to be. But if that's not an option (maybe you want to track it as a hit to that page or something) you can always redirect whenever you want using `top.location.href` in an iFrame app, or `<fb:redirect url="" />` in FBML.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "facebook, api, facebook c# sdk" }
¿Cómo puedo añadir un slider como este a mi sitio web? Quiero añadir un slider lo más parecido a este a mi sitio web. La cosa es que se mueva a esa velocidad y que se detenga cuando pases el cursor sobre el. La parte de que las imágenes estén linkeadas sí la sé hacer. No estoy muy familiarizado con js. Si me pueden mencionar alguno, les agradezco de antemano. <
Buen día. Es muy fácil, el js que usan es este: < En la misma pagina viene la documentación, espero te sea útil. Si requieres mas ayuda me dices, para echarlo a andar en tu web. <
stackexchange-es_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html, css, web, slider" }
Understanding the capacitors in an op amp circuit I am a computer programmer forced to make some circuits for a Langmuir probe our lab is making (the main task is programming the analytic software on the computer, but I have to make a basic amplifier circuit as well). Below is a circuit made by a colleague of mine for a similar problem that I'm basing my work on. I understand everything except for the capacitors. Are they for decoupling, or filtering, or what? Any help would be appreciated. !enter image description here
The 1uF capacitor forms a simple low-pass filter with th 4.7K to filter the PWM square wave from the microcontroller. The 100nF cap in parallel with 4.7K does not do much- it prevents erosion of the op-amp phase margin due to input and stray capacitance on the inverting input.
stackexchange-electronics
{ "answer_score": 4, "question_score": 1, "tags": "capacitor, operational amplifier, amplifier, decoupling capacitor, probe" }
Reducing a Postgres table to JSON I have a following table in Postgres +----+-----------+----------------------+---------+ | id | user_fk| language_fk | details | +----+-----------+----------------------+---------+ | 1 | 2 | en-us | 123 | | 2 | 3 | en-us | 456 | | 3 | 4 | en-us | 789 | | 4 | 4 | es-la | 012 | +----+-----------+----------------------+---------+ And I want to reduce this to the following SQL statement: UPDATE users SET details = '{"en-us": "789", "es-la": "012"}' WHERE id = 4; UPDATE users SET details = '{"en-us": "123"}' WHERE id = 2; UPDATE users SET details = '{"en-us": "456"}' WHERE id = 3; So I want to reduce languages per user and put it in a different table. Is there a way to do this in Postgres?
Use the function `jsonb_object_agg()` to get the expected output: select min(id) as id, user_fk, jsonb_object_agg(language_fk, details) as details from users group by user_fk id | user_fk | details ----+---------+---------------------------------- 1 | 2 | {"en-us": "123"} 2 | 3 | {"en-us": "456"} 3 | 4 | {"en-us": "789", "es-la": "012"} (3 rows) You cannot update the table in this way because of different types of old and new `details` column. Create a new table with reduced columns using `create table` from `select:` create table new_users as select min(id) as id, user_fk, jsonb_object_agg(language_fk, details) as details from users group by user_fk;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, json, postgresql" }
Path of particle under gravity If a particle is subjected to gravity then $$\frac{∂^2 u}{∂\theta^2} +u = \frac{GM}{h^2} $$ where $$ u = \frac{1}{r}$$ and $$h = r^2\dot{\theta}.$$ If you solve this you get $$u = A\sin\theta+B\cos\theta + \frac{GM}{h^2}.$$ But the general solution for this is just in terms of $\cos\theta$ because then you have the eqn for a conic. So why is $A = 0$?
You can also write the general solution to this differential equation (under a fixed set of polar coordinates) as $$u = C_1 \cos(\theta+C_2) + \frac{GM}{h^2}$$ by defining $C_1=\sqrt{A^2+B^2}$ and $C_2=\tan^{-1}\left(\dfrac{A}B\right)$. However, by redefining $\theta=0$ appropriately, we can have the same solution with $C_2=0$, leaving us with only a cosine term.
stackexchange-math
{ "answer_score": 1, "question_score": 3, "tags": "ordinary differential equations, dynamical systems" }
Hard Integral with Numerical Approximation I'm rather new to Mathematica so there might be an easy solution but I couldn't find it in another forum. I have an integral that will probably require numerical approximation as Mathematica can't solve it directly. My Code is xFunction[x_] = (.01 + .3x)/(2*(2 + 3.2*x - 2.39*(x^2))) $Assumptions = x <= 0.7 $Assumptions = x >= 0.3 MyIntegral = Integrate[(Tanh[Y]^2)*(xFunction[x] - Y)^(1/6), {Y, .3, x}] Do I need to define x as a real number? The end goal is to take the values of x on 0.3<x<.7 and graph it which x as the independent variable on the x-axis and MyIntegral as the dependent variable on the y-axis. Y is just a dummy variable so it shouldn't matter. I'm sure it's just a few lines of code but I can't seem to figure it out. Any help would be appreciated!
By this point, you have done most of the work already. Use `NIntegrate` instead of `Integrate` for numerical integration. I also changed `=` to `:=` in the definition of `xFunction`, and lastly, defined `MyIntegral` to be another function: xFunction[x_] := (.01 + .3 x)/(2*(2 + 3.2*x - 2.39*(x^2))) MyIntegral[x_] := NIntegrate[(Tanh[Y]^2)*(xFunction[x] - Y)^(1/6), {Y, .3, x}] Now, this produces complex numbers for $x\in [0.3,0.7]$. So, instead of `Plot`, I use `ReImPlot`: ReImPlot[MyIntegral[x], {x, 0.3, 0.7}] and obtain![enter image description here](
stackexchange-mathematica
{ "answer_score": 0, "question_score": 0, "tags": "numerical integration" }
Does time pass at all for a system at equilibrium Time by definition expresses itself through the passage of events. But for a system at perfect equilibrium wherein no change occurs does the rate of passage of time decrease to zero because nothing happens.
A system in perfect equilibrium is not perfectly stationary in space or time. But, any change in the system is offset by another change such that there is no _net_ change. Let's look at a simple example. Take a perfectly insulated box isolated from the environment and fill it with a gas. The gas molecules are all bouncing around, hitting each other and the walls, and in general are very dynamic. However, if there are no temperature gradients, no chemical changes, etc then the system is in equilibrium. It doesn't mean things aren't moving and events aren't happening: **it means the events that do happen do not alter the state of the system** , however you choose to define the "state." Usually a statistical description is taken to define a "state", although in some cases it is much simpler to take a macroscopic description like a motionless ball sitting in a hole.
stackexchange-physics
{ "answer_score": 10, "question_score": 6, "tags": "time, equilibrium" }
Is it possible to convert index type from async to sync for existing secondary index in YDB? I've created a table in YDB with async index using following YQL statement: (sql) create table messages ( chat_id uint64, user_id uint64, posted_at uint64, modifed_at Datetime, message_text Utf8, message_media Json, views_cnt Uint64, index idx_user_chat_posted global sync on (user_id, chat_id, posted_at), primary key(chat_id, posted_at, user_id) ) Is it possible to convert index type from sync to async?
Currently YDB doesn't support index type change. Though it is possible to create async index on the same set of columns with `ALTER TABLE` statement. New async index will have another name and all the queries using sync index should be rewritten.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "ydb" }
How to update value in array of objects when onchange text is called (in flat list) There is a state value savedData: [ { key: 'First Name', value: '' }, { key: 'Last Name', value: '' }, { key: 'Mobile', value: '' }, { key: 'Email', value: '' }, { key: 'Password', value: '' }, { key: 'Forgot Password', value: '' }, { key: 'CheckBox1', value: '' }, ] Text inputs are in a flat list, each text input is rendered in each cell. How can I update a value in the array by index when `onChange` of text input is called, _without_ using state variables or global variables?
You could pass the `key` as parameter for `onChange` method onChange={() => this.handleChange("First Name")} and then just update the value. let field = savedDate.find(({key}) => key == key_param); field.value = ... I'd recommend to use the field's id as key for the `savedData` _state_ and just pass the `event.target.id` as parameter. savedData:[ {key:'firstName',value:''}, {key:'lastName',value:''}, {key:'mobile',value:''}, {key:'email',value:''}, {key:'password',value:''}, {key:'forgot Password',value:''}, {key:'checkBox1',value:''}, ] ............... onChange={(e) => this.handleChange(e.target.id)}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, arrays, react native" }