qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
10,578,960
I am using ckeditor in order to edit the text seen in the screen. The information is taken from database and written to the screen in a div element and it is possible to edit the information by double clicking. However, after edited i couldn't get the edited information. Here is my code, i tried to add a form which includes the div element, but it did not work. ``` <form method="post"> <p> Double-click any of the following <code>&lt;div&gt;</code> elements to transform them into editor instances.</p> <?php $makeleSql = 'SELECT * FROM makale'; $makaleRs = $con->func_query($makeleSql); while ($makaleRow = mysql_fetch_array($makaleRs)) { ?> <div class = "editable" id = <?php echo "content".$makaleRow['id'];?> style="display:none"> <?php $contentSql = 'SELECT * FROM content WHERE makale_id ='.$makaleRow['id']; $contentRs = $con->func_query($contentSql); while ($contentRow = mysql_fetch_array($contentRs)) { echo $contentRow['icerik'].$makaleRow['id']; } ?> </div> <?php } ?> <button type="submit" value="Submit" onclick="getDiv();"/> </form> ``` What should i do in order to take the information in the div element? Moreover, i am using this example. <http://nightly.ckeditor.com/7484/_samples/divreplace.html> Thanks.
2012/05/14
[ "https://Stackoverflow.com/questions/10578960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343936/" ]
For save form's data you need store information in input/select/textarea. Div and other not form's element not will be stored. You have to store your data in hidden fields: ``` <form method="post"> <p> Double-click any of the following <code>&lt;div&gt;</code> elements to transform them into editor instances.</p> <?php $makeleSql = 'SELECT * FROM makale'; $makaleRs = $con->func_query($makeleSql); while ($makaleRow = mysql_fetch_array($makaleRs)) { ?> <div class="editable" id="<?php echo "content".$makaleRow['id'];?>"> <?php $contentSql = 'SELECT * FROM content WHERE makale_id ='.$makaleRow['id']; $contentRs = $con->func_query($contentSql); while ($contentRow = mysql_fetch_array($contentRs)) { echo $contentRow['icerik'].$makaleRow['id']; // store original text echo '<input type="hidden" name="'.$makaleRow['id'].'" value="'.htmlspecialchars($contentRow['icerik'].$makaleRow['id']).'">; } ?> </div> <?php } ?> <button type="submit" value="Submit" onclick="getDiv(this);"/> </form> <script> var getDiv = function(btn) { for(var el in btn.form.elements) { var d = document.getElementById(btn.form.elements[el].name); btn.form.elements[el].value = d.innerHTML; } return true; } </script> ```
13,880,230
I have multiple ~50MB Access 2000-2003 databases (MDB files) that only contain tables with data. The *data-databases* are located on a server in my enterprise that can take ~1-2 second to respond (and about 10 seconds to actually open the 50 MDB file manually while browsing in the file explorer). I have other databases that only contain forms. Most of those *forms-database* (still MDB files) are actually copied from the server to the client (after some testing, the execution looks smoother) before execution with a batch file. Most of those *forms-databases* use table-links to fetch the data from the *data-databases*. Now, my question is: is there any advantage/disadvantage to merge all *data-databases* from my ~50MB databases to make one big database (let's say 500MB)? Will it be slower? It would actually help to clean up my code if I wouln't have to connect to all those different databases and I don't think 500MB is a lot, but I don't pretend to be really used to Access by any mean and that's why I'm asking. If Access needs to read the whole MDB file to get the data from a specific table, then it would be slower. It wouldn't be really that surprising from Microsoft, but I've been pleased so far with MS Access database performances. There will never be more than ~50 people connected to the database at the same time (most likely, this number won't in fact be more than 10, but I prefer being a little bit conservative here just to be sure).
2012/12/14
[ "https://Stackoverflow.com/questions/13880230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1689179/" ]
Something like this? ``` var points = File.ReadLines("c:\filepath") .Skip(1) //Ignore the 1st line .Select(line => line.Split(' ')) //Chop the string into x & y .Select(split => new Point(double.Parse(split[0]), double.Parse(split[1])); //create a point from the array ```
73,439,041
Cheers, I have the bellow React code, where i need to send an HTTP Request to check if my actual user have permission or not to access my page. For that, im using useEffect hook to check his permission every page entry. But my actual code does not wait for `authorize()` conclusion. Leading for `/Unauthorized` page every request. What i am doing wrong? ``` import React, { useState, useCallback } from "react"; import { useNavigate } from "react-router-dom"; import { security } from "../../services/security"; export default function MypPage() { const navigate = useNavigate(); const [authorized, setAuthorized] = useState(false); const authorize = useCallback(async () => { // it will return true/false depending user authorization const response = await security.authorize("AAA", "BBB"); setAuthorized(response); }); useEffect(() => { authorize(); if (authorized) return; else return navigate("/Unauthorized"); }, [authorize]); return <div>MypPage</div>; } ``` Thanks.
2022/08/21
[ "https://Stackoverflow.com/questions/73439041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11573910/" ]
replace your container with this code: ``` Container( alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: (hisseResult?.result[index].rate ?? 0) > 0 ? Colors.green : Colors.red), width: 75, height: 25, child: Text(hisseResult?.result[index].rate.toString() ?? "", style: TextStyle(color: Colors.white))) ``` if rate > 0, the container is set to green, else container is set to red Greetings!
24,546,513
I had to write a csv sorting code for which I used the following code : ``` foreach(@files){ if(/\.csv$/i) { # if the filename has .csv at the end push(@csvfiles,$_); } } foreach(@csvfiles) { $csvfile=$_; open(hanr, "D:\\stock\\".$csvfile)or die"error $!\n"; # read handler open(hanw , ">D:\\stock\\sorted".$csvfile) or die"error $! \n"; # write handler for creating new sorted files @lines=(); @lines=<hanr>; foreach $line (@lines){ chomp $line; $count++; next unless $count; # skip header i.e the first line containing stock details my $row; @$row = split(/,/, $line ); push @$sheet2 , $row; } foreach my $row ( sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @$sheet2 ) # sorting based on date ,then stockcode { chomp $row; print hanw join (',', @$row ),"\n"; } @$sheet2 = (); $count = -1; close(hanw); close(hanr); } ``` However I do not understand what @$row is ..also I understand sorting a normal array @sheet2 comparing column 0 and 1 ..but if someone would explain the whole thing it would be wonderful: ``` @$row = split(/,/, $line ); push @$sheet2 , $row; } foreach my $row ( sort {$a->[0] cmp $b->[0] || $a->[1] cmp $b->[1]} @$sheet2 ) { *print hanw join (',', @$row ),"\n"; } ```
2014/07/03
[ "https://Stackoverflow.com/questions/24546513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3249348/" ]
You have `my $row;` which leaves `$row` undefined, and pushing into `@$row` (or `@{$row}`) automatically creates new array due [`autovivification`](http://en.wikipedia.org/wiki/Autovivification) perl feature. In case of ``` sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @$sheet2 ``` `@$sheet2` is array of array structure, and `@$sheet2` arrays are sorted by first and second element from sub-array (string sort due `cmp` operator; if `$a->[0]` and `$b->[0]` are equal then `$a->[1]` and `$b->[1]` are compared).
5,969
I am re-asking this question for Photoshop Elements 10 : [How can I resize an image without anti-aliasing?](https://graphicdesign.stackexchange.com/questions/5519/how-can-i-resize-an-image-without-anti-aliasing) I want the same result as the user got here- the ability to change a layer's angle and scale without having photoshop try to smooth the image for me (I'm working with pixel art). The only issue is that there is no "Interpolate Image" option in the general preferences tab like in other photoshops. The only area I can even access the "Nearest Neighbor" option is in the Image Resize tab, and that doesn't allow me to operate within a specific layer or to change the angle at all. Thanks for your help!
2012/02/14
[ "https://graphicdesign.stackexchange.com/questions/5969", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/3722/" ]
I guess you could copy the part of the image you want to resize into a new image; resize that image using "Nearest Neighbor" interpolation; then copy it back into your original image. But that doesn't help if you need to rotate. This might just be one of the features that Elements leaves out...
17,040,671
Goal: If finding the word "Total" in a cell, the current row with word "Total" as a start point (with letter D in the column) and all the way to the letter H shall have a light grey background color. If not having "Total", the background shall be default. Problem: How should I do it by using VBA? ![enter image description here](https://i.stack.imgur.com/BgwMm.gif)
2013/06/11
[ "https://Stackoverflow.com/questions/17040671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484390/" ]
You could try it with conditional formatting. Just select the cell and go to "Format" -> "Conditional formatting" (well that's the path in Excel 2003, don't know 2007 or later) But you can do it with a macro if you want to. Here is an example how to do it: ``` Sub RowsToGrey() Dim r As Long, i As Long r = Cells(Rows.Count, 4).End(xlUp).Row For i = 1 To r If InStr(Cells(i, 4), "Total") Then Range(Cells(i, 4), Cells(i, 8)).Interior.ColorIndex = 15 Else Range(Cells(i, 4), Cells(i, 8)).Interior.ColorIndex = 0 End If Next i End Sub ``` I hope that helps.
200,123
Is there any framework or method that will allow to use browser to run a 2D game made in python with pygame graphical library?
2022/03/31
[ "https://gamedev.stackexchange.com/questions/200123", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/145066/" ]
Since mid-2022, pygame has partial support for WebAssembly as upcoming python3.11 and allows for running the same pygame code on desktops and mobile/web. You can publish your game on itch.io or github pages as some people have already done. use pygbag from <https://pypi.org/project/pygbag> , some documentation is available from pygame-web.github.io read documentation to adjust your main loop for async, and then use `python3 -m pygbag game_folder_with_all_extra_modules_and_assets/main.py`
4,307,222
I am working on the Glen Bredon's ``topology and geometry''. In its proposition 6.10, the degree of a mapping $(x\_0, \dots, x\_n) \mapsto (-x\_0, \dots, x\_n)$ from $\mathbb{S}^n \to \mathbb{S}^n$ is introduced. The statement of that proposition is following. For $\mathbb{S}^n \subseteq \mathbb{R}^{n + 1}$ with coordinates $x\_0, \dots, x\_n$, let $f: \mathbb{S}^n \to \mathbb{S}^n$ be given by $f(x\_0,x\_1, \dots, x\_n) = (-x\_0, x\_1, \dots, x\_n)$, the reversal of the first coordinate only. Then $\deg(f) = -1$. Here, $H\_\*$ denotes any homology theory satisfying the Eilenberg-Steenrod axioms. As a reminder, the degree of a continuous function from $\mathbb{S}^n$ into $\mathbb{S}^n$ is defined by following. If $f : \mathbb{S}^n \to \mathbb{S}^n$ is a continuous map, $\deg(f)$ is defined to be the integer such that $f\_\*(a) = \deg(f) a$ for all $a \in \tilde{H}\_n(\mathbb{S}^n ; \mathbb{Z}) \cong \mathbb{Z}$, where $f\_\*$ denotes the homomorphism of abelian groups induced by $f$ and the functor $H\_n$. My question is following. The proof of the above proposition starts with the case of $n = 0$. Obiovusly, $\mathbb{S}^0 = \{x, y\}$ with $x = 1$, $y = -1$ in $\mathbb{R}^1$. By the additivity of a homology theory, the inclusions $\{x\} \hookrightarrow \mathbb{S}^0$ and $\{y\} \hookrightarrow \mathbb{S}^0$ induce an isomorphism \begin{equation} H\_0(\{x\}) \bigoplus H\_0(\{y\}) \overset{\cong}{\to} H\_0(\mathbb{S}^0) \end{equation} At this moment, the textbook says that the homomorphism $f\_\*$ becomes, on the direct sum, the interchange $(a,b) \mapsto (b,a)$, where we indentify the homology of all one-point space via the unique maps between them. How can I verify the statement about this $f\_\*$. It is obvious that the map $f$ assigns $y$ to $x$ and $x$ to $y$. However, since I am working with a general homology theory, not a singular homology theory, I cannot exploit the structure of singular complexes, so I have been in trouble with connecting the behaviour of $f$ and $f\_\*$. I hope anyone let me know how I proceed. Thank you.
2021/11/15
[ "https://math.stackexchange.com/questions/4307222", "https://math.stackexchange.com", "https://math.stackexchange.com/users/399707/" ]
You consider an arbitrary homology theory $H\_\*$ satsyfing all Eilenberg-Steenrod axioms including the dimension axiom. Thus you should not use the notation $\tilde{H}\_n(\mathbb{S}^n ; \mathbb{Z})$ because that suggests that the functors $H\_n$ have a second variable (the coefficient group). But such a concept is not contained in the Eilenberg-Steenrod axioms. What you mean is that the coefficient group of $H\_\*$ is $H\_0(\*) = \mathbb Z$, where $\*$ denotes a one-point space. We have $S^0 = \{-1,1\} \subset \mathbb R$. The reflection map $f$ simply exchanges the points $\pm 1$. Let $i\_\pm : \* \to S^0$ denote the map with image $\pm 1$. Note that $f \circ i\_\pm = i\_\mp$. We know that $$j : H\_0(\*) \oplus H\_0(\*) \to H\_0(S^0), j(a,b) = (i\_-)\_\*(a) + (i\_+)\_\*(b)$$ is an isomorphism. Let $\phi : H\_0(\*) \oplus H\_0(\*) \to H\_0(\*) \oplus H\_0(\*), \phi(a,b) = (b,a)$. We claim that the diagram $\require{AMScd}$ \begin{CD} H\_0(\*) \oplus H\_0(\*) @>{\phi}>> H\_0(\*) \oplus H\_0(\*) \\ @V{j}VV @V{j}VV \\ H\_0(S^0) @>{f\_\*}>> H\_0(S^0) \end{CD} commutes which answers your question. By the way, to prove this we do not have to know that $j$ is an isomorphism. Moreover, the proof works for any coefficient group. We have $$j(\phi(a,b)) = j(b,a) = (i\_-)\_\*(b) + (i\_+)\_\*(a) = (f \circ i\_+)\_\*(b) + (f \circ i\_-)\_\*(a) \\= f\_\*((i\_+)\_\*(b)) + f\_\*((i\_-)\_\*(a)) = f\_\*((i\_+)\_\*(b) + (i\_-)\_\*(a)) = f\_\*(j(a,b)) .$$
18,074,221
I'm facing an issue with chrome 28. I build an application that use the webcam to take picture. I had no problem with it, but since I upgrade to chrome 28, my application is not working anymore (I'm getting an error with the getUserMedia function). Here is the message : `{"constraintName":"","message":"","name":"PERMISSION_DENIED"}.` If I try to run the app code on a simple `html` and `httpserver`, I got no problem with it. And when using the APP I'm not asked anymore if I allow the usage of the webcam. I've tried to turn on some chrome flags for webrtc but nothing change. Does anybody has/had this issue ? Thanks !
2013/08/06
[ "https://Stackoverflow.com/questions/18074221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2655718/" ]
Try like this: ``` public class TempContext : DbContext { public DbSet<Shop> Shops { get; set; } public DbSet<Certificate> Certificates { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Shop>().HasRequired(x => x.Certificate); } } ```
72,904,850
I am struggling to create a new variable named "edu\_category" to indicate whether each person experiences Female Hypergamy (wive's education level < husband's), Female Homogamy (wive's education level == husband's), or Female Hypogamy (wive's education level > husband's). My data looks like this (Female == 1 indicates this person is female, 0 indicates male): | PersonID | Female | EducationLevel | SpouseID | SpouseEducation | | --- | --- | --- | --- | --- | | 101 | 1 | 3 | 102 | 4 | | 102 | 0 | 4 | 101 | 3 | | 103 | 1 | 2 | 104 | 2 | | 104 | 0 | 2 | 103 | 2 | | 105 | 0 | 5 | 106 | 6 | | 106 | 1 | 6 | 105 | 5 | I wish to create a new variable so that my data looks like this: | PersonID | Female | EducationLevel | SpouseID | SpouseEducation | edu\_category | | --- | --- | --- | --- | --- | --- | | 101 | 1 | 3 | 102 | 4 | FHypergamy | | 102 | 0 | 4 | 101 | 3 | FHypergamy | | 103 | 1 | 2 | 104 | 2 | FHomogamy | | 104 | 0 | 2 | 103 | 2 | FHomogamy | | 105 | 0 | 5 | 106 | 6 | FHypogamy | | 106 | 1 | 6 | 105 | 5 | FHypogamy | Here, let's look at person with ID "105", his (because female == 0) education level is 5, his spouse's (person 106's) education level is 6, so it's Female Hypogamy, wive's education > husband's (we assume by default everyone's spouse is of opposite sex). Now let's look at person with ID "106", since she is person 105's spouse, we also fill the variable "edu\_category" with the same "FHypogamy". So essentially, we are looking at every unit of couples. What I tried: ``` df2 <- df1 %>% mutate(edu_category = case_when((SpouseEducation > EducationLevel) | (Female == 1) ~ 'FemaleHypergamy', (SpouseEducation == EducationLevel) | (Female == 1) ~ 'FemaleHomogamy', (SpouseEducation < EducationLevel) | (Female == 1) ~ 'FemaleHypogamy', (SpouseEducation > EducationLevel) | (Female == 0) ~ 'FemaleHypogamy', (SpouseEducation == EducationLevel) | (Female == 0) ~ 'FemaleHomogamy', (SpouseEducation < EducationLevel) | (Female == 0) ~ 'FemaleHypergamy')) ``` However, it's not giving my accurate results - the variable "edu\_category" itself is successfully created, but the "FemaleHypergamy", "FemaleHomogamy", and "FemaleHypogamy" are not reflecting accurate situations. What should I do? Thank you for the help!
2022/07/07
[ "https://Stackoverflow.com/questions/72904850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19455550/" ]
You can do this in a report visualisation with a few measures, to calculate number of sales, percentage of sales, product rank by sales (then product name), and cumulative sales percentage: ##### # Sales: ``` # Sales = COUNT ( Sales[ID SALE] ) ``` ##### % Sales: ``` % Sales = DIVIDE ( [# Sales], CALCULATE ( [# Sales], REMOVEFILTERS ( Sales[PRODUCT] ) ) ) ``` ##### % Sales (Cumulative): ``` % Sales (Cumulative) = VAR CurrentRank = IF ( ISINSCOPE ( Sales[PRODUCT] ), [Rank by Sales then Product], DISTINCTCOUNT ( Sales[PRODUCT] ) ) RETURN SUMX ( ALL ( Sales[PRODUCT] ), IF ( [Rank by Sales then Product] <= CurrentRank, [% Sales], BLANK() ) ) ``` ##### Rank by Product: ``` Rank by Product = RANKX ( ALL ( Sales[PRODUCT] ), FIRSTNONBLANK ( Sales[PRODUCT], 1 ),, ASC, Dense ) ``` ##### Rank by Sales then Product: ``` Rank by Sales then Product = RANKX ( ALL ( Sales[PRODUCT] ), [# Sales] + ( 1 / [Rank by Product] ),, DESC, Dense ) ``` Sample output: [![Sample output](https://i.stack.imgur.com/sdGzn.png)](https://i.stack.imgur.com/sdGzn.png) *EDIT*: You could do the % Sales (Cumulative) measure in on, and remove the 'Rank' measures, but it's significantly less legible: ``` % Sales (Cumulative) = VAR CurrentRank = IF ( ISINSCOPE ( Sales[PRODUCT] ), RANKX ( ALL ( Sales[PRODUCT] ), [# Sales] + DIVIDE ( 1, CALCULATE ( RANKX ( ALL ( Sales[PRODUCT] ), FIRSTNONBLANK ( Sales[PRODUCT], 1 ),, ASC, Dense ) ) ),, DESC, Dense ), DISTINCTCOUNT ( Sales[PRODUCT] ) ) RETURN SUMX ( ALL ( Sales[PRODUCT] ), IF ( RANKX ( ALL ( Sales[PRODUCT] ), [# Sales] + DIVIDE ( 1, CALCULATE ( RANKX ( ALL ( Sales[PRODUCT] ), FIRSTNONBLANK ( Sales[PRODUCT], 1 ),, ASC, Dense ) ) ),, DESC, Dense ) <= CurrentRank, [% Sales], BLANK() ) ) ```
453,030
How can I create a product key for my C# Application? I need to create a product (or license) key that I update annually. Additionally I need to create one for trial versions. > > Related: > > > * [How do I best obfuscate my C# product license verification code?](https://stackoverflow.com/questions/501988) > * [How do you protect your software from illegal distribution?](https://stackoverflow.com/questions/109997) > > >
2009/01/17
[ "https://Stackoverflow.com/questions/453030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53605/" ]
You can do something like create a record which contains the data you want to authenticate to the application. This could include anything you want - e.g. program features to enable, expiry date, name of the user (if you want to bind it to a user). Then encrypt that using some crypto algorithm with a fixed key or hash it. Then you just verify it within your program. One way to distribute the license file (on windows) is to provide it as a file which updates the registry (saves the user having to type it). Beware of false sense of security though - sooner or later someone will simply patch your program to skip that check, and distribute the patched version. Or, they will work out a key that passes all checks and distribute that, or backdate the clock, etc. It doesn't matter how convoluted you make your scheme, anything you do for this will ultimately be security through obscurity and they will always be able to this. Even if they can't someone will, and will distribute the hacked version. Same applies even if you supply a dongle - if someone wants to, they can patch out the check for that too. Digitally signing your code won't help, they can remove that signature, or resign it. You can complicate matters a bit by using techniques to prevent the program running in a debugger etc, but even this is not bullet proof. So you should just make it difficult enough that an honest user will not forget to pay. Also be very careful that your scheme does not become obtrusive to paying users - it's better to have some ripped off copies than for your paying customers not to be able to use what they have paid for. Another option is to have an online check - just provide the user with a unique ID, and check online as to what capabilities that ID should have, and cache it for some period. All the same caveats apply though - people can get round anything like this. Consider also the support costs of having to deal with users who have forgotten their key, etc. *edit: I just want to add, don't invest too much time in this or think that somehow your convoluted scheme will be different and uncrackable. It won't, and cannot be as long as people control the hardware and OS your program runs on. Developers have been trying to come up with ever more complex schemes for this, thinking that if they develop their own system for it then it will be known only to them and therefore 'more secure'. But it really is the programming equivalent of trying to build a perpetual motion machine. :-)*
22,213,229
I have this set of number `a=[1 2 3]`. And I want to put this number randomly into matrix 7 x 1, and number 1 must have 2 times, number 2 must have 3 times and number 3 must have 2 times. The sequence is not necessary. The answer look like. `b=[1 2 2 2 1 3 3]'`
2014/03/06
[ "https://Stackoverflow.com/questions/22213229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3386135/" ]
Try [`randperm`](http://www.mathworks.com/help/matlab/ref/randperm.html): ``` a=[1 2 3]; samps = [1 1 2 2 2 3 3]; % specify your desired repeats samps = samps(randperm(numel(samps))); % shuffle them b = a(samps) ``` Or, instead of specifying `samps` explicitly, you can specify the number of repetitions for each element of `a` and use `arrayfun` to compute `samps`: ``` reps = [2 3 2]; sampC = arrayfun(@(x,y)x*ones(1,y),a,reps,'uni',0); samps = [sampC{:}]; samps = samps(randperm(numel(samps))); % shuffle them b = a(samps) ```
73,214,339
Put the entire code into a question, thank you to all that have replied but this issue is super annoying either way help is appreciated! Context: This code is meant to go onto the top reddit post of the day/week, then screenshot it and once that's done it goes to the comments and screenshots the top comments of said post, the former works but the latter does not. ``` import time,utils,string from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from utils import config def scrape(post_url): bot = utils.create_bot(headless=True) data = {} try: # Load cookies to prevent cookie overlay & other issues bot.get('https://www.reddit.com') for cookie in config['reddit_cookies'].split('; '): cookie_data = cookie.split('=') bot.add_cookie({'name':cookie_data[0],'value':cookie_data[1],'domain':'reddit.com'}) bot.get(post_url) # Fetching the post itself, text & screenshot post = WebDriverWait(bot, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.Post'))) post_text = post.find_element(By.CSS_SELECTOR, 'h1').text data['post'] = post_text post.screenshot('output/post.png') # Let comments load bot.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(3) # Fetching comments & top level comment determinator comments = WebDriverWait(bot, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'div[id^=t1_][tabindex]'))) allowed_style = comments[0].get_attribute("style") # Filter for top only comments NUMBER_OF_COMMENTS = 10 comments = [comment for comment in comments if comment.get_attribute("style") == allowed_style][:NUMBER_OF_COMMENTS] print(' Scraping comments...',end="",flush=True) # Save time & resources by only fetching X content for i in range(len(comments)): try: print('.',end="",flush=True) # Filter out locked comments (AutoMod) try: comments[i].find_elements(By.CSS_SELECTOR, '.icon.icon-lock_fill') continue except: pass # Scrolling to the comment ensures that the profile picture loads # Credits: https://stackoverflow.com/a/57630350 desired_y = (comments[i].size['height'] / 2) + comments[i].location['y'] window_h = bot.execute_script('return window.innerHeight') window_y = bot.execute_script('return window.pageYOffset') current_y = (window_h / 2) + window_y scroll_y_by = desired_y - current_y bot.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by) time.sleep(0.2) # Getting comment into string text = "\n".join([element.text for element in comments[i].find_elements_by_css_selector('.RichTextJSON-root')]) # Screenshot & save text comments[i].screenshot(f'output/{i}.png') data[str(i)] = ''.join(filter(lambda c: c in string.printable, text)) except Exception as e: if config['debug']: raise e pass if bot.session_id: bot.quit() return data except Exception as e: if bot.session_id: bot.quit() if config['debug']: raise e return False ```
2022/08/02
[ "https://Stackoverflow.com/questions/73214339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13668926/" ]
There is a potential conflict between the class you created `gui.FlowLayout` and `java.awt.FlowLayout`, the layout you have to give to your frame. The error is due to the fact the `JFrame.setLayout()` method expects a `java.awt.FlowLayout` and not a `gui.FlowLayout` which is the only FlowLayout available in your code. To fix that, I'd do the following 1. Remove the ambiguity by renaming the class you created (to `FlowLayoutExample` for example). 2. Import the `java.awt.FlowLayout` you actually need. The code should become: ``` package gui; import javax.swing.JButton; import javax.swing.JFrame; import java.awt.FlowLayout; public class FlowLayoutExample { public static void main(String[] args) { JFrame frame = new JFrame(); //cerates frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application frame.setSize(500, 500); //sets x-dimesion, and y-dimension of frame frame.setLayout(new FlowLayout()); frame.add(new JButton("1")); frame.setVisible(true); } } ``` **Note:** there is also another possibility: you can skip the import and directly mention the complete class name (with the package): ``` frame.setLayout(new java.awt.FlowLayout()); ``` I tend to prefer the first solution because: * The name `FlowLayout` doesn't reflect what your class does while `FlowLayoutExample` is IMHO more explicit. * Always using complete class names makes your code more verbose and thus less readable.
24,696
**The Challenge** Using only lands and Goblins, your goal is to build a Magic: the Gathering deck that can win the game as quickly as possible, against an opponent who does nothing. You may assume that your deck is stacked, so that you will always draw exactly the cards you want. **Scoring** The winning answer will be the one which can defeat the opponent in as few turns as possible. You may choose to play or draw, but winning on the play is considered faster than winning on the draw. In the event that two solutions are equally fast, the winner will be the solution that deals more damage. In the event that two solutions are equally fast and equally damaging, the winner will be the one that uses less cards. **Possibly Asked Questions** When you say Goblins... Any card with the subtype Goblin. So no [Goblin Game](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=8902) or [Dragon Fodder](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=398647). What's the opponent doing? The opponent's deck consists of sixty islands, and they begin the game by mulliganing to zero. They will take no game actions unless an effect requires them to. Loopholes? Your solution may not rely upon random chance such as winning coinflips, or the opponent doing something suicidal, like choosing 20 on [Choice of Damnations](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=88803)
2015/12/19
[ "https://puzzling.stackexchange.com/questions/24696", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/7459/" ]
Got it down to turn 1 on the draw if we allow Mons's Goblin Waiters! **Turn 1 - infinite damage on the draw (16 cards used)** > > Turn 0: > > > > Gemstone Caverns, exiling Mons's Goblin Raiders for irony (1 card "used") > > > > > > Turn 1: > > > > City of Traitors, tap both lands for 2R (2R, 2 cards) > > > > Play Mons's Goblin Waiters for R, sacrifice both lands for R (2R, 3 cards) > > > > Play Skirk Prospector for R, sacrifice Mons's Goblin Waiters for R (2R, 4 cards) > > > > Play Mogg War Marshal for 1R, sacrifice it and both tokens for RRR (1RRR, 5 cards) > > > > Play Mogg War Marshal for 1R, sacrifice it and both tokens for RRR (RRRRR, 6 cards) > > > > Play Goblin Ringleader for RRRR, revealing Mogg War Marshal, Goblin Lackey, Goblin Bushwhacker, and Grenzo, Dungeon Warden, then sacrifice it for R (RR, 7 cards) > > > > Play Mogg War Marshal for RR, sacrifice it and both tokens for RRR (RRR, 8 cards) > > > > Play Goblin Lackey for R (RR, 9 cards) > > > > Play Goblin Bushwhacker, Kicked, for RR (10 cards) > > > > Attack with Goblin Lackey for 2 damage, put Grenzo, Dungeon Warden into play (11 cards) > > > > Sacrifice Goblin Lackey and Goblin Bushwhacker for RR (RR, 11 cards) > > > > Pay RR to Grenzo, revealing Siege-Gang Commander, put it into play, sacrifice it and all three tokens for RRRR (RRRR, 12 cards) > > > > Pay RR to Grenzo, revealing Siege-Gang Commander, put it into play, sacrifice it and all three tokens for RRRR (RRRRRR, 13 cards) > > > > Pay RR to Grenzo, revealing Goblin Sledder, put it into play, sacrifice it to give Grenzo +1/+1 (RRRR, 14 cards) > > > > Pay RR to Grenzo, revealing Kiki-Jiki, Mirror Breaker, put it into play (RR, 15 cards) > > > > Pay RR to Grenzo, revealing Lightning Crafter, put it into play, *but hold the ETB trigger on the stack...* (16 cards) > > > > Tap Kiki-Jiki, targeting Lightning Crafter to create a token, champion Kiki-Jiki with the token, tap the token to deal your opponent 3 damage, then sacrifice the token for R, returning Kiki-Jiki to the battlefield untapped > > > > Repeat the step above infinite times, dealing your opponent infinite damage!  > > > Without Mons's, the best is turn two: **Turn 2 (*pre-combat!*) - infinite damage on the play (12 cards used)** > > Turn 1: > > > > [Geothermal Crevice](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=23238) tapped (1 card used) > > > > > Turn 2: > > > > Tap and sacrifice Geothermal Crevice, play [Frogtosser Banneret](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=152587) for BG (2 cards) > > > > Mountain, play [Akki Rockspeaker](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=77919) for R, gaining R (R, 4 cards) > > > > Play [Skirk Prospector](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393985) for R (5 cards) > > > > Sacrifice Akki Rockspeaker to gain R, play [Mogg War Marshal](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393973) for R (6 cards) > > > > Sacrifice Mogg War Marshal and both tokens for RRR (RRR, 6 cards) > > > > Play [Mogg War Marshal](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393973) for R (RR, 7 cards) > > > > Sacrifice Mogg War Marshal and both tokens for RRR (RRRRR, 7 cards) > > > > Play [Goblin Ringleader](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393963) for RRR, revealing Mogg War Marshal x2, Kiki-Jiki Mirror Breaker, Lightning Crafter (RR, 8 cards) > > > > Play [Mogg War Marshal](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393973), [Mogg War Marshal](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393973) for RR (10 cards) > > > > Sacrifice both Mogg War Marshals and all four tokens for RRRRRR (RRRRRR, 10 cards) > > > > Sacrifice Goblin Ringleader for R (RRRRRRR, 10 cards) > > > > Play [Kiki-Jiki, Mirror Breaker](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=397698) for RRRR (RRR, 11 cards) > > > > Play [Lightning Crafter](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=152893) for RRR, *but hold the ETB trigger on the stack* (12 cards) > > > > Tap Kiki-Jiki targeting Lightning Crafter to make a token, champion Kiki-Jiki with the token. Tap the token to deal 3 damage to your opponent, then sacrifice the token to Skirk Prospector for R, returning Kiki-Jiki to the battlefield (untapped) > > > > Repeat the above step infinite times, dealing infinite damage to your opponent! > > (With the original Lightning Crafter trigger still on the stack) > > > As well as the most efficient kill: **Turn 2 - infinite damage on the play (6 cards used)** > > Turn 1: > > > > Mountain, [Goblin Lackey](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=382959) (2 cards used) > > > > > > Turn 2: > > > > Tap Mountain for R, play [Skirk Prospector](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393985) (3 cards) > > > > Attack with Goblin Lackey for 1 damage, put [Kiki-Jiki, Mirror Breaker](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=397698) into play (4 cards) > > > > Play [Gaea's Cradle](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=10422), Tap for GGG (GGG floating, 5 cards) > > > > Sacrifice Goblin Lackey to Skirk Prospector for R (GGGR, 5 cards) > > > > Play [Lightning Crafter](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=152893) for GGGR, *but hold the ETB trigger on the stack* (6 cards) > > > > Tap Kiki-Jiki targeting Lightning Crafter to make a token, champion Kiki-Jiki with the token. Tap the token to deal 3 damage to your opponent, then sacrifice the token to Skirk Prospector for R, returning Kiki-Jiki to the battlefield (untapped) > > > > Repeat the above step infinite times, dealing infinite damage to your opponent! > > (With the original Lightning Crafter trigger still on the stack) > > > Optimizing for card efficiency another way: **Turn 2 - infinite damage on the play (5 cards from hand)** > > I'm proud to have broken [Goatnapper](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=142363), although the consequences may be tragic - after having proven that it facilitates a practically unbeatable turn two infinite combo deck, I am sure it will shortly be banned from Legacy, and we will all be poorer for the loss. > > > . > > Turn 1: > > > > Mountain, [Goblin Lackey](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=382959) (2 cards played) > > > > > > Turn 2: > > > > Attack with Goblin Lackey for 1 damage, put [Grenzo, Dungeon Warden](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=382276) into play (3 cards) > > > > Tap Mountain for R, play [Skirk Prospector](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393985) (4 cards) > > > > Play [Gaea's Cradle](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=10422), Tap for GGG (GGG floating, 5 cards) > > > > Pay GG to Grenzo, revealing [Siege-Gang Commander](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393982), put it into play, get three Goblin tokens > > > > Sacrifice Siege-Gang Commander and all three tokens to Skirk Prospector for RRRR (GRRRR, 5 cards) > > > > Sacrifice Goblin Lackey to Skirk Prospector for R (GRRRRR, 5 cards) > > > > Pay GR to Grenzo, revealing [Amoeboid Changeling](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=207921), put it into play > > > > Pay RR to Grenzo, revealing [Goatnapper](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=142363), put it into play targeting Amoeboid Changeling (a Goat, as well as a Goblin), untapping it, gaining control of it, and giving it haste > > > > Pay RR to Grenzo, revealing [Kiki-Jiki, Mirror Breaker](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=397698), put it into play > > > > Tap Amoeboid Changeling (haste from Goatnapper) to give Kiki-Jiki all creature types until end of turn > > > > Tap Kiki-Jiki, targeting Goatnapper, creating a token with haste. Target Kiki-Jiki with the Goatnapper token trigger (Kiki-Jiki is currently a Goat as well as a Goblin), untap and gain control of Kiki-Jiki (as well as giving it more haste) > > > > Repeat the above step infinite times for infinite Goatnapper tokens, leaving Kiki-Jiki untapped > > > > Sacrifice your infinite Goatnapper tokens for infinite R from Skirk Prospector (Infinite R, 5 cards) > > > > Pay RR to Grenzo, revealing [Goblin Sledder](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=393964), put it into play (Infinite R, 5 cards) > > > > Sacrifice Skirk Prospector and Goblin Sledder, giving Grenzo +2/+2 until end of turn > > > > Pay RR to Grenzo, revealing [Goblin Dynamo](http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=42274), put it into play (Infinite R, 5 cards) > > > > Tap Kiki-Jiki, targeting Goblin Dynamo, creating a token copy with haste > > > > Tap and sacrifice the Goblin Dynamo token with X = infinite, dealing infinite damage to your opponent! > > >
63,948,882
After calculation I would like to pop up a windows displaying a message and the results. In the following example I would like to display in the pop up windows the value of x. The function winDialog seems to not be able to perform it. ``` library(sp) library(svDialogs) library(rgdal) x <- runif(1, 1, 10) if(x <= 5){ winDialog("ok", "OK") } else{ winDialog("ok", "too big") } ```
2020/09/18
[ "https://Stackoverflow.com/questions/63948882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11501898/" ]
You can use `paste()` to combine the value of your variable `x` and the text you want to print. Note that the `winDialog()` function only works under windows and not under other OS. ``` x <- runif(1, 1, 10) winDialog("ok", paste(x, ifelse(x <= 5, "is OK", "is too big"))) ``` [![Dialog box](https://i.stack.imgur.com/59wJX.png)](https://i.stack.imgur.com/59wJX.png)
663,821
After choosing between "Express" or "Custom" update it keeps loading forever. ![windows update screen](https://i.stack.imgur.com/MkvQ8.jpg) ![windows update keepes loading forever](https://i.stack.imgur.com/CpMj8.jpg) That's how it looks like. I have been waiting for more than 24 hours, but no success. **SYSTEM & ADDITIONAL INFO** * Three computers were reformatted and are presenting the same problem. * Same CD have been used on all installations. * No problem occurred during instalation. * There is no problem with the network * Windows Version: XP SP3
2013/10/22
[ "https://superuser.com/questions/663821", "https://superuser.com", "https://superuser.com/users/229162/" ]
I did have exactly the same problem as stated by RaphaelVidal. In my case the solution was actually simple. Cause of the problem looks to be a cancelled download or install of an earlier update. I could see that in the update history (see left side in Microsoft Update) that an earlier update was cancelled. In that history a "KB-number" of that cancelled update is shown. The solution is to Google on that " + download + Microsoft". And than download and install that update manually. After that install, in my case Microsoft Update was working again. (Maybe you see more cancelled updates in the history and you should repeat the above).
47,797,157
I am currently doing a project with SQL Server. I am not too familiar with this programming language, and I am required to create relationships. The relationships I have created are * Pet/Owner (One-To-Many) * Pet/Appointment (One-to-One) * Appointment/Vet (One-to-One). I have looked on Google and YouTube, and I THINK my code is correct. Can someone double check my work before I start to add data? ``` CREATE TABLE Vet ( [VET_NUM] CHAR(5) PRIMARY KEY, [LAST_NAME] CHAR(20), [FIRST_NAME] CHAR(20), [STREET] CHAR(30), [CITY] CHAR(20), [STATE] CHAR(20), [POSTAL_CODE] CHAR(20), [SALARY] DECIMAL(8,2), [DEGREE] CHAR(20), [POSITION] CHAR(20) ); CREATE TABLE Owner ( [OWNER_NUM] CHAR(20) PRIMARY KEY, [OWNER_NAME] CHAR(30) NOT NULL, [STREET] CHAR(30), [CITY] CHAR(20), [STATE] CHAR(20), [POSTAL_CODE] CHAR(20), [PET_NUM] CHAR(5) ); CREATE TABLE Appointment ( [APPOINTMENT_NUM] CHAR(5) PRIMARY KEY, [APPOINTMENT_DATE] DATE, [VET_NUM] CHAR(3) [PET_NUM] CHAR(3) ); CREATE TABLE Pet ( [PET_NUM] CHAR(3) PRIMARY KEY, [PET_NAME] CHAR(35) NOT NULL, [STREET] CHAR(30), [CITY] CHAR(15), [STATE] CHAR(2), [POSTAL_CODE] CHAR(5), [BREED] CHAR(20), [OWNER_NUM] CHAR(3), [APPOINTMENT_NUM] CHAR(5) ); ```
2017/12/13
[ "https://Stackoverflow.com/questions/47797157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8612039/" ]
You need to add Foreign Keys to support the relationships, for example: ``` ALTER TABLE Owner ADD CONSTRAINT FK_Owner_Pet FOREIGN KEY (PET_NUM) REFERENCES Pet (PET_NUM) ON DELETE CASCADE ON UPDATE CASCADE ; GO ``` This implements a one-to-many relationship. I don't think you really want one-to-one relationships. Will a PET only ever have one APPOINTMENT? Will a VET only ever have one APPOINTMENT?
4,820,591
I would like to have the SQL Server PowerShell extensions available to me whenever I start PowerShell by loading the snap-ins in my profile.ps1 script. I found an article [here](http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx) with a script example that shows how to do this, and this works fine on my 32-bit Windows XP box. Unfortunately, on my 64-bit Windows 7 machine, this blows up. If I try to launch this script with the 64-bit PowerShell, I get: ``` Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2. At C:\Users\xxxx\Documents\WindowsPowerShell\profile.ps1:84 char:13 + Add-PSSnapin <<<< SqlServerCmdletSnapin100 + CategoryInfo : InvalidArgument: (SqlServerCmdletSnapin100:String [Add-PSSnapin], PSArgumentException + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand ``` If I run this instead in a 32-bit PowerShell, I get: ``` Get-ItemProperty : Cannot find path 'HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds \Microsoft.SqlServer.Management.PowerShell.sqlps' because it does not exist. At C:\Users\xxxx\Documents\WindowsPowerShell\profile.ps1:39 char:29 + $item = Get-ItemProperty <<<< $sqlpsreg + CategoryInfo : ObjectNotFound: (HKLM:\SOFTWARE\...owerShell.sqlps:String) [Get-ItemProperty], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand ``` I'd like to be able to run this in a 64-bit PowerShell if possible. To this end, I tracked down what I thought was the Powershell extension dlls and in a 64-bit Administrator elevated PowerShell I ran: ``` cd "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn" installutil Microsoft.SqlServer.Management.PSProvider.dll installutil Microsoft.SqlServer.Management.PSSnapins.dll ``` No dice. Although installutil seemed to indicate success, I still get the "No snap-ins have been registered for Windows PowerShell version 2" error message when I run the script. Anyone have any suggestions as to where I go from here?
2011/01/27
[ "https://Stackoverflow.com/questions/4820591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241023/" ]
I've used this script without issue on x64 machines. The problem with the x86 invocation is that the script looks for registry keys which on an x64 instance are only accessible from x64 PowerShell. For the x64 invocation you could try registering the snapins since that is the error message you're receiving. Run as administrator... Change this: ``` cd $sqlpsPath Add-PSSnapin SqlServerCmdletSnapin100 Add-PSSnapin SqlServerProviderSnapin100 ``` to this: ``` cd $sqlpsPath $framework=$([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) Set-Alias installutil "$($framework)installutil.exe" installutil Microsoft.SqlServer.Management.PSSnapins.dll installutil Microsoft.SqlServer.Management.PSProvider.dll Add-PSSnapin SqlServerCmdletSnapin100 Add-PSSnapin SqlServerProviderSnapin100 ``` An even better solution is not use add-pssnapin instead turn sqlps into a module. I have blog post here: <http://sev17.com/2010/07/10/making-a-sqlps-module> Update for SQL Server 2012 - now ships a sqlps module you can install instead of the above blog: <http://www.microsoft.com/en-us/download/details.aspx?id=35580>
5,637,650
Test.java ``` package a; import b.B; public class Test { public static void main(String[] v) { new A().test(); new B().test(); } } ``` A.java: ``` package a; public class A { protected void test() { } } ``` B.java: ``` package b; public class B extends a.A { protected void test() { } } ``` Why does `new B().test()` give an error? Doesn't that break visibility rules? `B.test()` is invisible in `Test` because they're in different packages, and yet it refuses to call the `test()` in `B`'s superclass which is visible. Links to the appropriate part of the JLS would be appreciated.
2011/04/12
[ "https://Stackoverflow.com/questions/5637650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/371623/" ]
Here you go JLS on `protected` keyword: [JLS protected description](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.2) and [JLS protected example](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.2). Basically a `protected` modifier means that you can access field / method / ... 1) in a subclass of given class *and* 2) from the classes in the same package. Because of 2) `new A().test()` works. But `new B().test()` doesn't work, because class `B` is in different package.
168,350
I'm setting up a site for internal use and it will be served over HTTPS with a self-signed server certificate. To increase security, I want to also secure the site with client certificates. Is there any reason to use a separate certificate authority to sign the client certificates instead of just using the server private key I already have to sign them?
2017/08/28
[ "https://security.stackexchange.com/questions/168350", "https://security.stackexchange.com", "https://security.stackexchange.com/users/157901/" ]
When you talk about security, all this self-signed SSL stuff has nothing common with security. In order to implement proper SSL configuration for internal network, you have to: * Create your own CA server (depending on a platform, different products may be used. For example, in Windows you can use Active Directory Certificate Services, in Linux you can use CA software like EJBCA). CA certificate will be self-signed * Provide best security for your CA server: strict physical and remote access to the server. * Distribute self-signed root CA certificate to trust store on all affected clients * Use this CA to issue certificates to clients and web servers * Maintain revocation information for these certificates (CA server will periodically publish CRLs) The reason is -- separation of concerns and security. Web servier is by default less secure. There are more chances that private key leaks from web server, because you can't guarantee adequate security for it because of web server specialization (be public). With dedicated CA you can provide better security, so less people can access it either, physically or programmatically. If you lose SSL certificate, you can revoke it and issue a new one. Minimum server reconfiguration is required. No client reconfiguration is required. If you use CA certificate on web server, you will have to recreate every server/client certificate and reconfigure all of them in the case of key compromise.
1,578,885
Let $\mathscr A$ be a unital C\*-algebra and let $a,b\in \mathscr A$ such that $0\leq a \leq b$ and $a$ is invertible. How to show that $b$ is invertible? ($0\leq a \leq b$ means that $a,b$ is positive and that $b-a$ is positive. Moreover, a positive element is a hermitian element with a spectrum which is a subset of $[0,\infty)$.) Since $a$ is invertible, we have that $0 \not \in \sigma(a)$. I guess my question is why this implies that $0 \not \in \sigma(b)$. Maybe one should use functional calculus in some way(?).
2015/12/16
[ "https://math.stackexchange.com/questions/1578885", "https://math.stackexchange.com", "https://math.stackexchange.com/users/82448/" ]
Let $x=-\cos(\theta)$ so that $$\mu(1-x^2)^2-x=0$$ This polynomial indeed has a single root in the range $[0,1]$ for all positive $\mu$. We can rewrite the above equation as $$\mu=\frac x{(1-x^2)^2}.$$ For small $x$, $x\approx\mu$. For $x$ close to $1$, let $1-\epsilon$, we have $$\mu=\frac{1-\epsilon}{(1-(1-\epsilon)^2)^2}\approx\frac1{4\epsilon^2}.$$ This gives us the approximation $$x=1-\frac1{2\sqrt\mu}.$$ You can refine the root numerically in the range $$[\mu,1-\frac1{2\sqrt\mu}].$$ For a "manual" method, you can plot the relation $\mu=f(x)$ as accurately as possible. Then for a given value of $\mu$, find the corresponding $x$ on the plot and use it for a starting value of Newton's iterations. --- **Update**: The $\mu$ curve has a vertical asymptote at $x=1$, which makes it more difficult to handle. We can discard it by considering the function $$\frac\mu{\mu+1}=\frac x{(1-x^2)^2\left(\frac x{(1-x^2)^2}+1\right)}=\frac x{(1-x^2)^2+x}.$$ [![enter image description here](https://i.stack.imgur.com/5cxPH.png)](https://i.stack.imgur.com/5cxPH.png) It turns out that the function is fairly well approximated by $x$ in the range of interest, so that a good initial approximation is simply $$x=\frac\mu{\mu+1} !$$
57,343
How to determine the order of nucleophilicity for given chemical species? Like I came across this question, to rearrange $\ce{RCOO-, OR-, OH-, H2O}$ (alkyl acetate, alkoxide, hydroxide, and water) in decreasing order of nucleophilicity and it ranked $\ce{OR-}$ first. Shouldn't it be $\ce{OH-}$ since $\ce{OR-}$ would be more sterically crowded?
2016/08/12
[ "https://chemistry.stackexchange.com/questions/57343", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/30466/" ]
Within a group of nucleophiles with the same atom, the nucleophilicity decrease with **decreasing basicity of nucleophile**. Decreasing basicity means the decreasing affinity of electron pair for a proton. The decreasing order of nucleophilicity is shown in the figure. [![enter image description here](https://i.stack.imgur.com/EwG8V.gif)](https://i.stack.imgur.com/EwG8V.gif) But the relationship between nucleophilicity and basicity can be reversed by steric effect. Less basic but steric unhindered nucleophile therefore have higher nucleophilicity than strong basic but strically hindered nucleophile.
34,496,574
No mather what I write in the input fields I only get NaN even from the page load I get NaN Any idea why? I need quantity to \* by price and give a result, here is the code. I will display the code now ``` <form action="?F=save-sale" method="post" name="venta"> <table class="table-global"> <tr> <td class="table-global-td-title">Cantidad </td> <td class="table-global-td-title">Precio venta</td> <td class="table-global-td-title">Vendedor</td> <td class="table-global-td-title">Documento</td> <td class="table-global-td-title">M&eacute;todo de pago</td> <td class="table-global-td-title">Suma total</td> <td class="table-global-td-title"></td> </tr> <tr> <td class="table-global-td-subtitle"><input type="number" class="input-global-100" name="cantidad" id="cantidad"> </td> <td class="table-global-td-subtitle"><input type="number" class="input-global-100" name="venta" id="venta" value="0"></td> <td class="table-global-td-subtitle"> <select style="text-transform:capitalize" class="select-global-120" name="vendedor" id="vendedor"> <option value="" selected>Seleccionar</option> <option value="001">001</option> </select> </td> <td class="table-global-td-subtitle"> <select class="select-global-132" name="comprobante" id="comprobante"> <option value="Boleta" selected>Boleta</option> <option value="Factura">Factura</option> </select> </td> <td class="table-global-td-subtitle"><select class="select-global-120" name="metodo" id="metodo" > <option value="Transferencia">Transferencia</option> <option value="Efectivo" selected>Efectivo</option> <option value="Cheque">Cheque</option> <option value="Transbank">Transbank</option> </select></td> <td class="table-global-td-subtitle"> <input type="text" class="input-global-total-100" name="ventatotal" id="ventatotal" readonly value="0" /> </td> <td class="table-global-td-subtitle"> <input class="submit-global-120" type="submit" value="Realizar la venta" /></td> </tr> </table> <script> var aacosto = document.getElementsByName('costo')[0]; var aacostototal = document.getElementsByName('costototal')[0]; var aaventa = document.getElementsByName('venta')[0]; var aaventatotal = document.getElementsByName('ventatotal')[0]; var aacantidad = document.getElementsByName('cantidad')[0]; var aaganancia = document.getElementsByName('ganancia')[0]; var aagananciatotal = document.getElementsByName('gananciatotal')[0]; function updateInput() { aaventatotal.value = parseFloat(aaventa.value) * parseFloat(aacantidad.value); } aaventa.addEventListener('keyup', updateInput); aaventatotal.addEventListener('change', updateInput); aacantidad.addEventListener('keyup', updateInput); updateInput(); </script> </form> ``` Here is a Fiddle so you guys can see it working <https://fiddle.jshell.net/v6spxoqv/10/>
2015/12/28
[ "https://Stackoverflow.com/questions/34496574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618056/" ]
Just have this condition `if (aaventa.value && aacantidad.value)` before calculating the product. It makes sure that the values are not *empty*. Everything else is fine. ```js var aaventa = document.getElementsByName('venta')[0]; var aaventatotal = document.getElementsByName('ventatotal')[0]; var aacantidad = document.getElementsByName('cantidad')[0]; function updateInput() { if (aaventa.value && aacantidad.value) aaventatotal.value = parseFloat(aaventa.value) * parseFloat(aacantidad.value); else aaventatotal.value = 0; } aaventa.addEventListener('keyup', updateInput); aaventatotal.addEventListener('change', updateInput); aacantidad.addEventListener('keyup', updateInput); updateInput(); ``` ```html <input name="venta"> <input name="cantidad"> <input name="ventatotal"> ```
52,141,775
I have a Typscript app and API. I wrote the below test per numerous Google searches and some examples found here on SO and other places. I see no issue in the test code. Googling `TypeError: chai.request is not a function`, so far is getting me now where. Do you see my error below? Thank you, thank you, thank you for any help :-) [![enter image description here](https://i.stack.imgur.com/A6rVF.png)](https://i.stack.imgur.com/A6rVF.png)
2018/09/02
[ "https://Stackoverflow.com/questions/52141775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2556640/" ]
I solved this by the following approach (Express.js with TypeScript) ``` import chai from 'chai'; import chaiHttp from 'chai-http'; chai.use(chaiHttp); ``` Hope it helps. *Remember to install* **@types/chai** *and other type definition packages for the block above to work*
68,301,835
I've got the following two methods: ```java public static <T, R> IGetter<T, R> createGetterViaMethodname( final Class<T> clazz, final String methodName, final Class<R> fieldType ) throws Throwable { final MethodHandles.Lookup caller = MethodHandles.lookup(); final MethodType methodType = MethodType.methodType( fieldType ); final MethodHandle target = caller.findVirtual( clazz, methodName, methodType ); final MethodType type = target.type(); final CallSite site = LambdaMetafactory.metafactory( caller, "get", MethodType.methodType( IGetter.class ), type.erase(), target, type ); final MethodHandle factory = site.getTarget(); return (IGetter<T, R>) factory.invoke(); } public static <T, I> ISetter<T, I> createSetterViaMethodname( final Class<T> clazz, final String methodName, final Class<I> fieldType ) throws Throwable { final MethodHandles.Lookup caller = MethodHandles.lookup(); final MethodType methodType = MethodType.methodType( void.class, fieldType ); final MethodHandle target = caller.findVirtual( clazz, methodName, methodType ); final MethodType type = target.type(); final CallSite site = LambdaMetafactory.metafactory( caller, "set", MethodType.methodType( ISetter.class ), type.erase(), target, type ); final MethodHandle factory = site.getTarget(); return (ISetter<T, I>) factory.invoke(); } ``` including the following two interfaces: ```java @FunctionalInterface public interface IGetter<T, R> { @Nullable R get( T object ); } @FunctionalInterface public interface ISetter<T, I> { void set( T object, @Nullable I value ); } ``` This works great for all Class-Types, including the Number-Wrappers for primitive types such as `Integer` for `int`. However, if I have a setter that takes an `int` or a getter that returns an `ìnt`, it tries passing / returning the Number-Wrapper, resulting in an exception. What's the correct way to box / unbox this without having to make another method. The reason here is to keep the API clean and simple to use. I am willing to take a small performance hit for the boxing / unboxing here.
2021/07/08
[ "https://Stackoverflow.com/questions/68301835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5841827/" ]
There is no built-in "pretty" way to convert a primitive class to a wrapper class, so you gotta use a map like this: ``` private final static Map<Class<?>, Class<?>> map = new HashMap<>(); static { map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); } ``` Or use one of the other ways [here](https://stackoverflow.com/questions/3473756/java-convert-primitive-class). Once you do that, you can just check if `fieldType` is a primitive. If it is, change the return type/parameter type of the method type by looking up the wrapper type in the map. For the getter: ``` MethodType type = target.type(); if (fieldType.isPrimitive()) { type = type.changeReturnType(map.get(fieldType)); } ``` For the setter: ``` MethodType type = target.type(); if (fieldType.isPrimitive()) { type = type.changeParameterType(1, map.get(fieldType)); } ``` Just in case it wasn't clear, the caller would pass the primitive class for primitive getters and setters: ``` createSetterViaMethodname(Main.class, "setFoo", int.class) // for a setter declared like this: public void setFoo(int i) { ... } ``` Full code: ``` public class Main { public static void main(String[] args) throws Throwable { // this prints 1234567 createSetterViaMethodname(Main.class, "setFoo", int.class).set(new Main(), 1234567); } public void setFoo(int i) { System.out.println(i); } public final static Map<Class<?>, Class<?>> map = new HashMap<>(); static { map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); } public static <T, R> IGetter<T, R> createGetterViaMethodname( final Class<T> clazz, final String methodName, final Class<R> fieldType ) throws Throwable { final MethodHandles.Lookup caller = MethodHandles.lookup(); final MethodType methodType = MethodType.methodType( fieldType ); final MethodHandle target = caller.findVirtual( clazz, methodName, methodType ); MethodType type = target.type(); if (fieldType.isPrimitive()) { type = type.changeReturnType(map.get(fieldType)); } final CallSite site = LambdaMetafactory.metafactory( caller, "get", MethodType.methodType( IGetter.class ), type.erase(), target, type); final MethodHandle factory = site.getTarget(); return (IGetter<T, R>) factory.invoke(); } public static <T, I> ISetter<T, I> createSetterViaMethodname( final Class<T> clazz, final String methodName, final Class<I> fieldType ) throws Throwable { final MethodHandles.Lookup caller = MethodHandles.lookup(); final MethodType methodType = MethodType.methodType( void.class, fieldType ); final MethodHandle target = caller.findVirtual( clazz, methodName, methodType ); MethodType type = target.type(); if (fieldType.isPrimitive()) { type = type.changeParameterType(1, map.get(fieldType)); } final CallSite site = LambdaMetafactory.metafactory( caller, "set", MethodType.methodType( ISetter.class ), type.erase(), target, type ); final MethodHandle factory = site.getTarget(); return (ISetter<T, I>) factory.invoke(); } } @FunctionalInterface interface IGetter<T, R> { @Nullable R get( T object ); } @FunctionalInterface interface ISetter<T, I> { void set( T object, @Nullable I value ); } ```
5,235,998
I wrote a small farad converter to learn GUI programming. It works great, looks fine-ish. The only problem is I can't seem to figure out how to control this strange highlighting that comes up on my `ttk.Combobox` selections. I did use a `ttk.Style()`, but it only changed the colors of the `ttk.Combobox` background, entries, etc. I also tried changing `openbox/gtk` themes. ![what the farad](https://i.stack.imgur.com/Vgx86.png) I'm talking about what's seen there on the text "microfarads (uF)". It'd be fine, if it highlighted the entire box; but I'd rather have it gone completely. How can I manipulate a `ttk.Combobox`'s selection highlight? ``` # what the farad? # thomas kirkpatrick (jtkiv) from tkinter import * from tkinter import ttk # ze la programma. def conversion(*args): # this is the numerical value inV = float(inValue.get()) # these two are the unit (farads, microfarads, etc.) values inU = inUnitsValue.current() outU = outUnitsValue.current() # "mltplr" is multiplied times inValue (inV) if inU == outU: mltplr = 1 else: mltplr = 10**((outU - inU)*3) outValue.set(inV*mltplr) # start of GUI code root = Tk() root.title("What the Farad?") # frame mainFrame = ttk.Frame(root, width="364", padding="4 4 8 8") mainFrame.grid(column=0, row=0) # input entry inValue = StringVar() inValueEntry = ttk.Entry(mainFrame, width="20", justify="right", textvariable=inValue) inValueEntry.grid(column=1, row=1, sticky="W") # input unit combobox inUnitsValue = ttk.Combobox(mainFrame) inUnitsValue['values'] = ('kilofarads (kF)', 'farads (F)', 'millifarads (mF)', 'microfarads (uF)', 'nanofarads (nF)', 'picofarads (pF)') inUnitsValue.grid(column=2, row=1, sticky="e") inUnitsValue.state(['readonly']) inUnitsValue.bind('<<ComboboxSelected>>', conversion) # result label outValue = StringVar() resultLabel = ttk.Label(mainFrame, textvariable=outValue) resultLabel.grid(column=1, row=2, sticky="e") # output unit combobox outUnitsValue = ttk.Combobox(mainFrame) outUnitsValue['values'] = ('kilofarads (kF)', 'farads (F)', 'millifarads (mF)', 'microfarads (uF)', 'nanofarads (nF)', 'picofarads (pF)') outUnitsValue.grid(column=2, row=2, sticky="e") outUnitsValue.state(['readonly']) outUnitsValue.bind('<<ComboboxSelected>>', conversion) # padding for widgets for child in mainFrame.winfo_children(): child.grid_configure(padx=4, pady=4) # focus inValueEntry.focus() # bind keys to convert (auto-update, no button) root.bind('<KeyRelease>', conversion) root.mainloop() ```
2011/03/08
[ "https://Stackoverflow.com/questions/5235998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623985/" ]
You can use the Combobox's [`selection_clear()`](http://effbot.org/tkinterbook/entry.htm#Tkinter.Entry.selection_clear-method) method to clear the selection whenever you want. e.g ``` inUnitsValue.selection_clear() ```
4,433,626
We have a growing mailing list which we want to send our newsletter to. At the moment we are sending around 1200 per day, but this will increase quite a bit. I've written a PHP script which runs every half hour to send email from a queue. The problem is that it is very slow (for example to send 106 emails took a total of 74.37 seconds). I had to increase the max execution time to 90 seconds to accomodate this as it was timing out constantly before. I've checked that the queries aren't at fault and it seems to be specifically the sending mail part which is taking so long. As you can see below I'm using Mail::factory('mail', $params) and the email server is ALT-N Mdaemon pro for Windows hosted on another server. Also, while doing tests I found that none were being delivered to hotmail or yahoo addresses, not even being picked up as junk. Does anyone have an idea why this might be happening? ``` foreach($leads as $k=>$lead){ $t1->start(); $job_data = $jobObj->get(array('id'=>$lead['job_id'])); $email = $emailObj->get($job_data['email_id']); $message = new Mail_mime(); //$html = file_get_contents("1032.html"); //$message->setTXTBody($text); $recipient_name = $lead['fname'] . ' ' . $lead['lname']; if ($debug){ $email_address = DEBUG_EXPORT_EMAIL; } else { $email_address = $lead['email']; } // Get from job $to = "$recipient_name <$email_address>"; //echo $to . " $email_address ".$lead['email']."<br>"; $message->setHTMLBody($email['content']); $options = array(); $options['head_encoding'] = 'quoted-printable'; $options['text_encoding'] = 'quoted-printable'; $options['html_encoding'] = 'base64'; $options['html_charset'] = 'utf-8'; $options['text_charset'] = 'utf-8'; $body = $message->get($options); // Get from email table $extraheaders = array( "From" => "Sender <sender@domain.com>", "Subject" => $email['subject'] ); $headers = $message->headers($extraheaders); $params = array(); $params["host"] = "mail.domain.com"; $params["port"] = 25; $params["auth"] = false; $params["timeout"] = null; $params["debug"] = true; $smtp = Mail::factory('mail', $params); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) { $logObj->insert(array( 'type' => 'process_email', 'message' => 'PEAR Error: '.$mail->getMessage() )); $failed++; } else { $successful++; if (DEBUG) echo("<!-- Message successfully sent! -->"); // Delete from queue $deleted = $queueObj->deleteById($lead['eq_id']); if ($deleted){ // Add to history $history_res = $ehObj->create(array( 'lead_id' => $lead['lead_id'], 'job_id' => $lead['job_id'] ) ); if (!$history_res){ $logObj->insert(array( 'type' => 'process_email', 'message' => 'Error: add to history failed' )); } } else { $logObj->insert(array( 'type' => 'process_email', 'message' => 'Delete from queue failed' )); } } $t1->stop(); } ```
2010/12/13
[ "https://Stackoverflow.com/questions/4433626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541095/" ]
There doesn't appear to be a method, but I am not surprised. Slugify removes characters from the string and unslugify would not know where to put it back in. For example, if you look at the URL for this question, it is ``` stackoverflow.com/questions/4433620/play-framework-how-do-i-lookup-an-item-from-a-slugify-url ``` It has removed the exclamation (!), parentheses and the quotes from the title of this question. How would an unslugify method know how and where to put those characters back in? The approach you want to take is to also include the ID, just as the stackoverflow URL has. If you wanted to take the same format as the stackoverflow URL, your route would be ``` GET /questions/{id}/{title} Question.show() ``` Then in your action, you would ignore the title, and simply do `Blog.findById(id);` You then have a SEO friendly URL, plus use a good REST approach to accessing the Blog post.
84,130
Is there any way to see all publicly shared Google Drive items/documents from a specific Google user?
2015/09/05
[ "https://webapps.stackexchange.com/questions/84130", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/95229/" ]
I wrote a Google Apps Script macro that you can attach to a new spreadsheet (or an old one, if it would make any sense) that accomplishes this task. To attach a script to a spreadsheet, go into that spreadsheet (or create a new one), click "Tools"->"Script editor...", copy and paste the code into the editor, click "Resources"->"Current project's triggers," select "onOpen" under Run, select "From spreadsheet" under Events, make sure the third drop-down menu reads "On open," then save the script under a name of your choice. The code below: 1. asks you to enter the email address of the user for whom you want to get a list of shared files 2. creates a new sheet within the active spreadsheet 3. populates it with two columns of data: one with the names of all of the *publicly shared* files owned by the user you specified AND live hyperlinks to those files, and a second column containing the names of the folders containing these files Here's the code: ``` function doGet() { var owner = SpreadsheetApp.getUi().prompt("Enter owner's email address:").getResponseText(); var ssheet = SpreadsheetApp.getActive(); var newSheet = ssheet.insertSheet(owner); newSheet.getRange('A1:B1').setValues([["File Name","Containing Folder"]]); newSheet.getRange('A1:B1').setFontWeight("bold"); var cells = newSheet.getRange('A1:B500'); var files = DriveApp.getFiles(); var ownerFiles = []; while (files.hasNext()){ var file = files.next(); if (file.getOwner().getEmail()==owner && file.getSharingAccess()==DriveApp.Access.ANYONE) { ownerFiles[ownerFiles.length]=file; } } for (i=0; i<ownerFiles.length; i++){ cells.getCell(i+2,1).setValue("=HYPERLINK(" + ownerFiles[i].getUrl() + "," + ownerFiles[i].getName() + ")"); var folders = ownerFiles[i].getParents(); var folder = folders.next(); cells.getCell(i+2,2).setValue(folder); } } function onOpen() { SpreadsheetApp.getUi().createMenu('List') .addItem('Public Files Owned by...', 'doGet') .addToUi(); } ``` To run the script, reopen the spreadsheet after first saving the script, then click "List"->"Public Files Owned by...". Something to bear in mind is that this is an inefficient script; if you have a lot of files stored in your Drive, this could take a *long* time to execute. In addition, it is currently written to accommodate up to 499 entries. (Increasing this maximum is simply a matter of raising the number for the 'B' column in the `cells` declaration.) It is also currently written to output only the first parent folder if a file is contained in multiple folders.
160,333
I'd like to measure a dozen potentiometers with an Arduino UNO. Unfortunately, the UNO only has 6 analog pins, but it does have about a dozen digital pins. Could I effectively measure an analog value with a digital pin by following this procedure? 1. Wire the potentiometer in parallel with a capacitor. 2. Connect one junction to an Arduino's digital pin. 3. Set this pin to write HIGH until the capacitor fully charges. 4. Set pin to read LOW and then use pulseIn() to measure the time it takes for the capacitor to discharge across the potentiometer, causing the voltage at the pin to go from 5V to 0. This time should be proportional to the resistance of the pot. e.g. a pot with a low resistance will cause the cap to discharge very fast, whereas a high resistance will cause the cap to discharge more slowly.
2015/03/17
[ "https://electronics.stackexchange.com/questions/160333", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/6852/" ]
I would not rely on it. While it may work there could also be some stray capacitance or other factors that also affect the reading of time and voltage value. Remember that there is a no mans land between high and low (where the analog signal would be), that theoretically could change with temperature, time or any variety of other reasons and invalidate your setup. It also relies on knowing the precise time of discharge. Keeping time like this is something that is very hard to do accurately on any microcontoller. Take for instance you get this to work and calibrate it so that you know that it reads `low` when the input gets to 1.7v. But come back in a day (or even minute) later and that 1.7v threshold is now 1.6v. The calibration you did would be invalid and you would be getting bogus results. What I would do instead is use the digital pins to read an external ADC over an SPI or other digital line. This has the benefit of being more reliable and (in most cases) more accurate as well. So to answer your question, it is theoretically possible. It would be a tough circuit to design, you would need to disconnect the line being monitored while you charge the capacitor, but it could be done. However it most likely would not be very reliable.
411,968
I am working with VLC from C# by creating a process that opens the command line. Is there any way of knowing when a movie ended in from the command line or something ?
2012/04/13
[ "https://superuser.com/questions/411968", "https://superuser.com", "https://superuser.com/users/128126/" ]
I have googled for solution finally - its not a thing that comes visible with a simple search though. Seems not many people interested. I am writing from a PC where I do not have Outlook installed, but hope I remember that well. 1. You need to enable Developer "ribbon" in Outlook 2. You need to create new form (using Appointment Form as a base) 3. On this new form - you need to put a VBA code for Open action 4. in this code - you need to modify Item. Start and Item. End (only if its set to full hour or half an hour, if you miss this piece your appointment will "shrink" each time you open it. Start should be +5 minutes, end should be -10 minutes (as the +5 for start actually pushes End 5 minutes forward as well). 5. While you are at editing new form you may want to add some standard footer in the invite (e. G. your conference call number). 6. Save this form ("Publish Form As... " if I remember this well) 7. Right click in the calendar view on your Calendar "folder" and change default form to be used from Appointment to the one you have saved in point 6. Hope you will be able to follow this with a little help of google. The solution is to 1. create new form 2. add small VBA at its beginning 3. select this form as your new default "Calendar form".
42,606,533
I was given an assignment to find the sum of the squares of the first n odd numbers whereby n is given by the user. The assignment was; ``` The script only takes one input, so do not # include any input command below. The print commands below are already given. # Do not alter the print commands. Do not add any other prints commands. r = range(1, n + 1) # prepare the range result = 0 # initialise the result for k in r: # iterate over the range result = result + k # update the result compute the sum of the squares of the first n odd numbers, and print it ``` This is what I have done so far; ``` r = range(1, n ** n, 2) result = 0 for k in r: result = result + k ``` I know the range is wrong because when I ran it, I used 5 as n and I expected the answer to be 165 because the squares of the first 5 odd numbers is 165 but instead I got 144. Please help
2017/03/05
[ "https://Stackoverflow.com/questions/42606533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7660992/" ]
We want to do iterate through odd numbers so if we want to do n odd numbers we need to go up to 2\*n. For example, 5 odd numbers would be 1,3,5,7,9 and 2\*5=10, but we only want every other number so we have the command `r = range(1, n * 2, 2)` We then start with zero and add to it, hence `result = 0` Now we iterate through our range (r) and add to our result the iterator squared, hence `result = result = (k * k)` Overall we have: ``` r = range(1, n * 2, 2) result = 0 for k in r: result = result + (k * k) print result ```
62,454,336
Env: Python 3.6, O/S: Windows 10 I have the following code that will search for filenames that contain a string either at the start (`.startswith`) of a filename or the end of a filename (`.endswith`), including sub directories and is case sensitive, i.e. `searchText = 'guess'` as opposed to `searchText = 'Guess'`. I would like to modify`if FILE.startswith(searchText):` that allows a search anywhere in the filename and is case insensitive. Is this possible? For example, a directory contains two files called `GuessMyNumber.py` and `guessTheNumber.py`. I would like to search for `'my'` and the code to return the filename `GuessMyNumber.py` ``` #!/usr/bin/env python3 import os # set text to search for searchText = 'Guess' # the root (top of tree hierarchy) to search, remember to change \ to / for Windows TOP = 'C:/works' found = 0 for root, dirs, files in os.walk(TOP, topdown=True, onerror=None, followlinks=True): for FILE in files: if FILE.startswith(searchText): print ("\nFile {} exists..... \t\t{}".format(FILE, os.path.join(root))) found += 1 else: pass print('\n File containing \'{}\' found {} times'.format(searchText, found)) ``` Thanks guys, Tommy.
2020/06/18
[ "https://Stackoverflow.com/questions/62454336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709475/" ]
A simple `glob`-based approach: ``` #!/usr/bin/env python3 import os import glob # set text to search for searchText = 'Guess' # the root (top of tree hierarchy) to search, remember to change \ to / for Windows TOP = 'C:/works' found = 0 for filename in glob.iglob(os.path.join(TOP, '**', f'*{searchText}*'), recursive=True): print ("\nFile {} exists..... \t\t{}".format(filename, os.path.dirname(filename))) found += 1 print('\n File containing \'{}\' found {} times'.format(searchText, found)) ``` --- A simple `fnmatch`-based approach: ``` #!/usr/bin/env python3 import os import fnmatch # set text to search for searchText = 'Guess' # the root (top of tree hierarchy) to search, remember to change \ to / for Windows TOP = 'C:/works' found = 0 for root, dirnames, filenames in os.walk(TOP, topdown=True, onerror=None, followlinks=True): for filename in filenames: if fnmatch.fnmatch(filename, f'*{searchText}*'): print ("\nFile {} exists..... \t\t{}".format(filename, os.path.join(root))) found += 1 print('\n File containing \'{}\' found {} times'.format(searchText, found)) ``` --- You could also use a PERL-compatible (more general) regular expression supported by `re` instead of the POSIX-compatible (less general) supported by `glob` and `fnmatch`. However, in this simple scenario, the POSIX-compatible is more than enough.
631,694
[![enter image description here](https://i.stack.imgur.com/UBFqR.png)](https://i.stack.imgur.com/UBFqR.png) The supply voltage is 15 V and RL is 100 kΩ. Find the voltage across each diode and RL. Is = 0.1 μA, η = 2, and VT = 25 mV. How can I calculate the net current through RL? I have three unknowns: the net current and the voltages across the diodes.
2022/08/18
[ "https://electronics.stackexchange.com/questions/631694", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/293958/" ]
You'd use the Shockley equation, $$ I(V\_D)=I\_S \left( e^\frac{V\_D}{\eta V\_T} - 1 \right), $$ to figure it out. You're given \$I\_S\$, \$V\_T\$ and \$\eta\$. We can invert this equation: given \$I\$, solve for \$V\_D\$. This will be more useful, since the current \$I\$ is the same for both diodes: $$ V\_D(I) = \ln \left( \frac{I}{I\_S}+1 \right) {\eta V\_T} $$ Now, the diode D2 is in reverse saturation, since the voltage across it is on par with \$-\frac{1}{\eta V\_T}\$. The reverse saturation current is then \$-I\_S\$, and that diode acts as a current limiter, and sets the current in the entire circuit. Then, the voltage drop on the resistor is \$I\_S \cdot R\_L\$, the voltage drop on D1 is, per Schockley equation, \$V\_{D1}=\ln(2)\eta V\_T\$, and the voltage drop across D2 is whatever voltage is left in the circuit. We can simulate it and see if it agrees with our figuring: ![schematic](https://i.stack.imgur.com/6a9uB.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f6a9uB.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) The diode models in the simulation have had their \$I\_S\$ and \$n\equiv\eta\$ set according to the values given in the assignment. The thermal voltage is slightly different since the value used by CircuitLab is not exactly 25mV, but we see that the simulation and the computed results agree to within 1mV or so.
70,682,367
I'm trying to click on an icon that appears on the page however despite trying everything I can think of I keep getting the following error: ``` waiting for selector "[aria-label="Comment"]" selector resolved to 2 elements. Proceeding with the first one. selector resolved to hidden <svg role="img" width="24" height="24" fill="#8e8e8e"…>…</svg> attempting click action waiting for element to be visible, enabled and stable element is visible, enabled and stable scrolling into view if needed element is not visible retrying click action, attempt #1 waiting for element to be visible, enabled and stable element is visible, enabled and stable scrolling into view if needed done scrolling element is not visible retrying click action, attempt #2 waiting 20ms waiting for element to be visible, enabled and stable ``` etc etc etc. So it looks like the element is hidden although I can't see any sign of that in the html....attached. Any help greatly appreciated. [enter image description here](https://i.stack.imgur.com/VKuAJ.png)
2022/01/12
[ "https://Stackoverflow.com/questions/70682367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17914989/" ]
You can use `nth` locator's method to get second element: ```js page.locator('svg[aria-label="Comment"]').nth(1); ``` or shorter version: ```js page.locator('svg[aria-label="Comment"] >> nth=1'); ``` Keep in mind that's zero-based numbering.
635,440
I am using debian 10 and I want to create a user with no home directory. the user should only have access to the directories that his or her group owns. that is the user has only to his or her group directories. This is my command information: `useradd -g mygroup-G mygroup1,mygroup2 -s /bin/bash -M username` However when I log into the system via putty and do ls command, I see the home folder and I can `cd` inside it. I don't understand why this is possible because `-M` should have prevented the creation of the home folder.
2021/02/19
[ "https://unix.stackexchange.com/questions/635440", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/457004/" ]
1. There are tools to manipulate filesystems as you ask. One such is the [mtools](https://www.gnu.org/software/mtools/) package, which does FAT filesystems. Another is [e2tools](https://e2tools.github.io), which does EXT2 and EXT3 filesystems. Both of these are available in debian linux, and probably many others. 2. These tools will probably not deal with an image in a partition. This should not be a problem. Simply split your template into separate files for the partition table and partition contents (probably ahead of time), add your files into the filesystem images, and then `cat` the pieces together in the right order to produce the final disk image.
4,490,691
I want to achieve this: ``` public System.Web.Mvc.ActionResult ExposureGrid(Guid? id, decimal stdDev) { //return null; try { var str = "<table border=1>"; str += "<tr><th>Date</th><th>Expected Credit Exposure</th><th>Max Credit Exposure</th></tr>"; str += "<tr><td>12/1/2010</td><td>100,000</td><td>50</td></tr>"; str += "<tr><td>12/2/2010</td><td>101,000</td><td>100</td></tr>"; str += "<tr><td>12/3/2010</td><td>102,000</td><td>150</td></tr>"; str += "<tr><td>12/4/2010</td><td>103,000</td><td>200</td></tr>"; str += "<tr><td>12/5/2010</td><td>104,000</td><td>250</td></tr>"; str += "<tr><td>12/6/2010</td><td>105,000</td><td>300</td></tr>"; str += "<tr><td>12/7/2010</td><td>106,000</td><td>350</td></tr>"; str += "</table>"; return Json(str); } catch (Exception e) { return Json(e.ToString()); } } ``` Then I take that Json and put it on my view like this: ``` $.ajax({ type: "POST", url: "<%= Url.Action("ExposureGrid", "Indications") %> ", dataType: "jsonData", data: tableJSON, success: function(data) { existingDiv = document.getElementById('table'); existingDiv.innerHTML = data; } }); ``` But what shows on the view in HTML is this: "\u003ctable border=1\u003e\u003ctr\u003e\u003cth\u003eDate\u003c/th\u003e\u003cth\u003eExpected Credit Exposure\u003c/th\u003e\u003cth\u003eMax Credit Exposure\u003c/th\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/1/2010\u003c/td\u003e\u003ctd\u003e100,000\u003c/td\u003e\u003ctd\u003e50\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/2/2010\u003c/td\u003e\u003ctd\u003e101,000\u003c/td\u003e\u003ctd\u003e100\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/3/2010\u003c/td\u003e\u003ctd\u003e102,000\u003c/td\u003e\u003ctd\u003e150\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/4/2010\u003c/td\u003e\u003ctd\u003e103,000\u003c/td\u003e\u003ctd\u003e200\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/5/2010\u003c/td\u003e\u003ctd\u003e104,000\u003c/td\u003e\u003ctd\u003e250\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/6/2010\u003c/td\u003e\u003ctd\u003e105,000\u003c/td\u003e\u003ctd\u003e300\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003e12/7/2010\u003c/td\u003e\u003ctd\u003e106,000\u003c/td\u003e\u003ctd\u003e350\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e" How do I fix this?
2010/12/20
[ "https://Stackoverflow.com/questions/4490691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534101/" ]
change: ``` dataType: "jsonData", ``` to ``` dataType: "json", ``` hopefully, issue should be resolved.
31,018,912
I am facing an issue probably with int to char conversion. What i am doing? ``` > Create random password using Membership.createPassword() > Create random digit. > Convert password to array > Get random array index and replace character with int ``` I have following code to generate random password with 1 digit at least. ``` GetRandomPassword(10, 1); private string GetRandomPassword(int length, int numberOfNonAlphanumericCharacters) { int index = new Random().Next(1, 9); string password = Membership.GeneratePassword(length, numberOfNonAlphanumericCharacters); char[] charArray = password.ToCharArray(); charArray[index] = Convert.ToChar(index); string newPassword = new string(charArray); return newPassword; } ``` However, the issue i am facing is with this line ``` charArray[index] = Convert.ToChar(index); ``` It does not store digit at given index but it stores ascii character like '\a'. Why? please advise, **How i can store number to char array at random index?**
2015/06/24
[ "https://Stackoverflow.com/questions/31018912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874957/" ]
Change ``` charArray[index] = Convert.ToChar(index); ``` to: ``` charArray[index] = (char)('0' + index); ``` Now... What does it means this line? `char` in c# are more like `int` than like `string`... So you can do ``` int x = 'A' + 1; ``` and you'll get that `x == 66` (that is the unicode code for `'B'`)... The same you can do with digits, that in the unicode table are like `'0'` (code 48), `'1'` (code 49)... ``` int x = '0' + 2; ``` and you'll get 50. You can the cast back the 49 to a char and you'll get `'2'`. Note that you are generating random numbers in the range `[1, 8]`. I hope it is what you really wanted.
35,030,962
I am following "The Big Nerd Ranch's Android Programming Guide" book (2nd edition) and in a particular chapter (chapter 21), they ask you to use a 9-patch image for some image assets. Up until then, the app that I wrote, called BeatBox, worked perfectly fine and compiled without error. But, when I go ahead and replace some drawables with a 9-patch image, I run into a build error and I just cannot make the app to build. The following is the error I get: ``` Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources] Configuration on demand is an incubating feature. :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72311Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72311Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42311Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugResources'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\<USERNAME>\AppData\Local\Android\sdk\build-tools\23.0.2\aapt.exe'' finished with non-zero exit value 1 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 12.753 secs ``` I have followed the exact instructions provided in the book, and so I presume that the result should be error free. Any idea why I am facing this error?
2016/01/27
[ "https://Stackoverflow.com/questions/35030962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2611713/" ]
First off a little sanity boost for you --------------------------------------- AAPT is exactly related to bundling the resources into your APK. Some great detail [here](http://www.alittlemadness.com/2010/06/07/understanding-the-android-build-process/) including (IMO) the best diagram showing the different build steps. So your aapt problem `aapt.exe'' finished with non-zero exit value 1` is almost certainly caused by your changing the 9-patches. No need to go back to square one, trying to remember what else you may have changed and eventually pulling all your hair out. Verification ------------ I was unable to duplicate your problem by directly running either of the root Gradle tasks (`:app:generateDebugSources` and `:app:generateDebugAndroidTestSources`). Nor was I able to duplicate the problem by running just the failing Gradle task: `:app:processDebugResources`. Not caused by Configuration on Demand ------------------------------------- It's unlikely that the problem is caused by a failure in the "configuration on demand". The line "Configuration on demand is an incubating feature." will also be printed if your build was successful. Thoughts -------- It looks like you are using the latest Build Tools (23.0.2 as of this writing) [versions](http://developer.android.com/intl/es/tools/revisions/build-tools.html), which is good. You don't list it, but I'm guessing that you are also using the latest version of the Android-Gradle plugin (since they both came out at the same time and Android Studio defaults to using the latest). [more info](http://developer.android.com/intl/es/tools/revisions/gradle-plugin.html) What I would suggest is to go back and start with the first Drawable we ask you to implement: the `ShapeDrawable` and confirm that this works, then move on to the next one. This will help pinpoint where the problem is. If you could provide link to your sample that would help too. In the future with Gradle-related problems you can always run the Gradle task yourself (as I did above) and add the `--info` flag. From command line or "terminal" within Android Studio just run (in your case): `./gradlew app:generateDebugSources --info` Lastly, whatever you discover please post back here. The problem you are seeing isn't directly related to our book and your answer will help others.
1,966,030
I'm writing a simple Twitter example that reads the Twitter Search RSS feed via: ``` http://search.twitter.com/search.rss ``` This works well except that the Description in this contains HTML such as Bold Tags and Link Tags, I have looked at the Atom feed via: ``` http://search.twitter.com/search.atom ``` It also has HTML in the description, is there a version that contains just the plain-text for a Tweet? The documentation is a little vague plus RSS is missing from the formats list even though this works. Is there a secret way into this I just want the raw non-HTMLed Tweet! Is this even possible, if not what would be the best way of stripping the HTML out of the string as all I need is the raw tweet.
2009/12/27
[ "https://Stackoverflow.com/questions/1966030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61529/" ]
There is a hack: ``` private void setDimButtons(boolean dimButtons) { Window window = getWindow(); LayoutParams layoutParams = window.getAttributes(); float val = dimButtons ? 0 : -1; try { Field buttonBrightness = layoutParams.getClass().getField( "buttonBrightness"); buttonBrightness.set(layoutParams, val); } catch (Exception e) { e.printStackTrace(); } window.setAttributes(layoutParams); } ```
33,762
I am flying from U.S. to India via Germany(2 stops - Dusseldorf and Munich). There is a 40 min layover at Dusseldorf and 1 h 40 min layover at Munich. I am concerned if I will be able to make to the connection to Munich. Is 40 mins enough time for a transit? Also, I am not a US citizen and will require an airport transit visa, which I am planning to get before I travel. Are there extra clearances/security checks required for Dusseldorf-Munich transit for people on transit visas, which may cause delays?
2014/07/12
[ "https://travel.stackexchange.com/questions/33762", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/18339/" ]
40 minutes could be enough but it could become scarce. As your second leg is a domestic Schengen flight, you will need to get through security and passport check. With only 40 minutes between the flights it's likely to miss the flight to Munich.
51,857,207
I want to change this: ``` input <- c("Théodore Agrippa d'AUBIGNÉ", "Vital d'AUDIGUIER DE LA MENOR") ``` into this : ``` output <- c("Théodore Agrippa d'Aubigné", "Vital d'Audiguier De La Menor") ``` The only words that should be modified are those that are all upper case. **Edit:** An edge case, where first letter of sequence isn't in `[A-Z]`: ``` input <- "Philippe Fabre d'ÉGLANTINE" ```
2018/08/15
[ "https://Stackoverflow.com/questions/51857207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2270475/" ]
Form two groups with boundaries on both sides as in ``` \b([A-Z])(\w+)\b ``` and use `tolower` on the second group (leaving the first untouched). See [**a demo on regex101.com**](https://regex101.com/r/gdaEQR/1/) (and mind the modifiers, especially `u`). --- *As a side note: you still have a couple of questions with (not yet accepted) answers.*
603,007
I have had the misfortune to need to clone a dual-booting Windows XP/7 box to replace its hard drive with a smaller one. I had great trouble getting it to boot and would like to understand what's going on and if I could be doing anything better. Background: the machine has a 750Gb drive with 3 partitions on it: * Windows XP * Windows 7 * Data The original installation was done in such a way that there is no separate Windows 7 recovery partition. I hope this fact simplifies things somewhat. I am replacing it with an 80Gb drive. The partitions have already been shrunk from within Windows 7 so that they fit onto the smaller disk. I used `GParted` (from a `PartedMagic` Linux LiveCD) to copy the partitions across. I mark the Windows XP partition as the active partition (the same as on the original disk). I was unable to use `CloneZilla` or do an entire disc copy due to the transition from a larger to a smaller disk. After copying the partitions, I manually copied the boot loader across (taking care not to copy the partition table): ``` $ dd if=/dev/sda of=/dev/sdb bs=446 count=1 ``` I removed the original disk, set the new one so it is physically connected the same as the original (IDE channel 1 master) and tried booting. This successfully presented the boot menu but failed upon selecting either option (there are two: one for XP and one for Win7). I did a fair bit of research which let me to realise the Windows 7 boot configuration data did not contain everything it should. I compared the BCD output from the original and new disks and noted that the device entries on the latter were `unknown`. So I manually changed them to match the original - like this: ``` $ bcdedit /set {ntldr} device partition=C: $ bcdedit /set {default} device partition=D: $ bcdedit /set {default} osdevice partition=D: ``` and rebooted. This time I could boot both XP and Win7. I need to do more testing because there appears to be other differences between the two BCDs, but making the above changes at least allowed booting to take place. So my question is really to ask why the BCD on a cloned partition would appear different to the original, and sufficiently so to prevent booting ? And a follow up to that would be to ask if I should be doing this another way?
2013/06/02
[ "https://superuser.com/questions/603007", "https://superuser.com", "https://superuser.com/users/101178/" ]
After cloning partitions containing Windows operating systems, it is necessary to fix up the boot configuration data if the cloned partitions are not in exactly the same position on the cloned disc as they are on the original. The Windows boot mechanism, since Windows Vista, stores its configuration as "Boot Configuration Data" (BCD) and this refers to partitions, not by partition numbers but by a disk signature and sector offset. The disk signature is a 32-bit value embedded in the Master Boot Record. Copying the first 446 bytes of sector 0 will copy the disk signature. If cloning activities result in the cloned disk partitions having different starting sector addresses then the original ones (highly likely unless a whole-disk clone was used) then the clone will most likely fail to boot until these remedies are applied. Basically, the sector offsets need to be updated and, for this, you'll need to use a recovery console (this is available on a Windows 7 install DVD). Ensure only the cloned drive is attached and boot from a Windows 7 install DVD. At the first screen make language selections and hit "next". At the next screen (where "install now" is displayed) press SHIFT+F10 to get a command prompt. First, confirm the drive letters that are in place and the partitions to which they relate: ``` diskpart list volume exit ``` Also, if you need to, re-confirm the active partition: ``` diskpart select disk 0 select part 1 detail part select part 2 detail part ... and so-on exit ``` On a BIOS system, the BCD is stored in a file at `X:\Boot\BCD` where `X` is the drive letter of the active partition (for UEFI it's in the EFI System Partition). Normally hidden, it can be seen with ``` dir /AH X:\Boot ``` It can be backed up like this: ``` bcdedit /export X:\path\to\bcd\backup ``` and restored ``` bcdedit /import X:\path\to\bcd\backup ``` If a disk has multiple operating systems on it, there may be multiple BCDs. The active BCD is the one in at `\Boot\BCD` on the partition that is marked as active - the *active partition*. To list its contents (in increasing order of verbosity:) ``` bcdedit bcdedit /enum bcdedit /enum ALL bcdedit /enum ALL /v ``` To fix up the active BCD, establish the drive letters for the correct partitions and do: ``` bcdedit /set {default} osdevice partition=X: bcdedit /set {default} device partition=X: bcdedit /set {bootmgr} device partition=X: bcdedit /set {memdiag} device partition=X: bcdedit /set {ntldr} device partition=X: ``` or, to fix up another BCD (at "X:\boot\bcd" in these examples): ``` bcdedit /store X:\boot\bcd /set {default} osdevice partition=X: bcdedit /store X:\boot\bcd /set {default} device partition=X: bcdedit /store X:\boot\bcd /set {bootmgr} device partition=X: bcdedit /store X:\boot\bcd /set {memdiag} device partition=X: bcdedit /store X:\boot\bcd /set {ntldr} device partition=X: ``` For example, my system which has XP and 7 and they show XP as being on `C:` and 7 being on `D:` and the active partition is `C:`. then the active BCD will be at `c:\boot\BCD`. The boot manager will be found at `C:\bootmgr` and the memory diagnostic will be at `C:\boot\memtest.exe`, The required commands would be: ``` bcdedit /set {ntldr} device partition=C: bcdedit /set {memdiag} device partition=C: bcdedit /set {bootmgr} device partition=C: bcdedit /set {default} device partition=D: bcdedit /set {default} osdevice partition=D: ``` With those changes, rebooting the computer (Pressing Alt-F4 will achieve this) and removing the DVD allowed the system to boot successfully. Further Reading: * <http://www.multibooters.co.uk/cloning.html> * <http://mrlithium.blogspot.co.uk/2011/10/my-boot-configuration-data-bcd-store.html> * <http://diddy.boot-land.net/bcdedit/files/bcd.htm> * <http://technet.microsoft.com/en-us/library/cc721886(v=ws.10).aspx> (a whole-disk clone should not suffer these issues because the partition layout on the copy should be exactly the same as the original)
4,312,386
I know it's similar to [this](https://math.stackexchange.com/questions/265809/sup-gyy-in-y-leq-inf-fxx-in-x) and I proved this inequality, but I'm stuck at finding examples that this inequality is strict. thanks. Edit: range is bounded.
2021/11/21
[ "https://math.stackexchange.com/questions/4312386", "https://math.stackexchange.com", "https://math.stackexchange.com/users/470876/" ]
The inequality can be strict if both $X$ and $Y$ have at least two elements. For an example pick arbitrary elements $x\_1 \in X$ and $y\_1 \in Y$ and define $$ f(x, y) = \begin{cases} 0 & \text{ if } x=x\_1 \text{ and } y = y\_1 \\ 1 & \text{ if } x=x\_1 \text{ and } y \ne y\_1 \\ 1 & \text{ if } x\ne x\_1 \text{ and } y = y\_1 \\ 0 & \text{ if } x\ne x\_1 \text{ and } y \ne y\_1 \, . \end{cases} $$ Then $\inf\{f(x,y) : x \in X\} = 0$ for all $y \in Y$, and $\sup\{f(x,y) : y \in Y\} = 1$ for all $x \in X$, and therefore $$ \sup\{\inf\{f(x,y) : x \in X\}: y \in Y\} = 0 < 1 = \inf\{\sup\{f(x,y) : y \in Y\}: x \in X\} \, . $$
31,607,465
I'm new here and registered because I couldn't find my answer in the existing treads. I'm trying to make a one-page website, and I want the 'landing page' to have a full background. I had the background on the whole page, but when I started placing text in the div, it broke. I used the following css (sass): ``` .intro { color: #fff; height: 100vh; background: url('http://www.flabber.nl/sites/default/files/archive/files/i-should-buy-a-boat.jpg') no-repeat center center; background-size: cover; &--buttons { position: absolute; bottom: 2em; } } p.hello { margin: 30px; } .page1 { color: #fff; height: 100vh; background: beige; } .page2 { color: #fff; height: 100vh; background: black; } ``` With the following HTML: ``` <html> <head> <link href="stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" /> <title>My title</title> </head> <body> <div class="container"> <div class="row"> <div id="intro" class="intro"> <div class="text-center"> <p class="hello"> Intro text is coming soon! </p> <div class="col small-col-12 intro--buttons"> <p>Buttons coming here. </p> </div> </div> </div> <div id="page1" class="col col-12 page1"> <p>Tekst test</p> </div> <div id="page2" class="col col-12 page2"> <p>Tekst test.</p> </div> </div> </div> </body> </html> ``` You can see the result here: <http://codepen.io/Luchadora/full/waYzMZ> Or see my pen: <http://codepen.io/Luchadora/pen/waYzMZ> As you see, when positioning the intro text (`p.hello {margin: 30px;}`, the background size changed and is not full screen anymore. (Btw: I used an example background). Also the other pages have white spaces now.. How can I fix this? I've read articles about viewports, but I think the only thing I need for this is *`height: 100vh;`*, right? Thanks in advance!
2015/07/24
[ "https://Stackoverflow.com/questions/31607465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5151678/" ]
Your problem is with [margin collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing): **Parent and first/last child** If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent. To solve your problem, add some padding to `.text-center`: ``` .text-center {padding:1px;} ``` [Updated pen](http://codepen.io/anon/pen/rVqMwy)
8,187,082
Suppose I have a class with a constructor (or other function) that takes a variable number of arguments and then sets them as class attributes conditionally. I could set them manually, but it seems that variable parameters are common enough in python that there should be a common idiom for doing this. But I'm not sure how to do this dynamically. I have an example using eval, but that's hardly safe. I want to know the proper way to do this -- maybe with lambda? ``` class Foo: def setAllManually(self, a=None, b=None, c=None): if a!=None: self.a = a if b!=None: self.b = b if c!=None: self.c = c def setAllWithEval(self, **kwargs): for key in **kwargs: if kwargs[param] != None eval("self." + key + "=" + kwargs[param]) ```
2011/11/18
[ "https://Stackoverflow.com/questions/8187082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12982/" ]
You could update the `__dict__` attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments: ``` class Bar(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) ``` then you can: ``` >>> bar = Bar(a=1, b=2) >>> bar.a 1 ``` and with something like: ``` allowed_keys = {'a', 'b', 'c'} self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys) ``` you could filter the keys beforehand (use `iteritems` instead of `items` if you’re still using Python 2.x).
148,065
I seem to see the phrase "shake his booty" being used to say something is good and attractive. But does it mean "shake his butt"? And if they are the same, why does "shake his butt" seem a somewhat distasteful action, but "shake his booty" all of a sudden becomes somewhat glamorous?
2014/01/26
[ "https://english.stackexchange.com/questions/148065", "https://english.stackexchange.com", "https://english.stackexchange.com/users/1204/" ]
"Neither is glamorous! "Booty" is [American slang for buttocks](http://www.urbandictionary.com/define.php?term=booty) but almost universally refers to that of a woman. "Butt" is also slang for "buttocks" but does not imply gender. Moreover, "booty" has overt sexual overtones (and is, in fact, slang for having sex in some cases), whereas "butt" is not. (A parent might refer to his/her child's butt, but never the child's booty.) You may be hearing the term "booty" in pop music lyrics or even some forms of pop journalism, but it is not considered a professional, polite, or glamorous word. As far as I know, the origin of the term is int he term for a pirate's treasure, called his "booty". The metaphoric link is to a woman's "treasure", I think.
45,541,902
Say we have 3 kafka partitions for one topic, and I want my events to be windowed by the hour, using event time. Will the kafka consumer stop reading from a partition when it is outside of the current window? Or does it open a new window? If it is opening new windows then wouldn't it be theoretically possible to have it open a unlimited amount of windows and thus run out of memory, if one partition's event time would be very skewed compared to the others? This scenario would especially be possible when we are replaying some history. I have been trying to get this answer from reading documentation, but can not find much about the internals of Flink with Kafka on partitions. Some good documentation on this specific topic would be very welcome. Thanks!
2017/08/07
[ "https://Stackoverflow.com/questions/45541902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3305586/" ]
So first of all events from Kafka are read constantly and the further windowing operations have no impact on that. There are more things to consider when talking about running out-of-memory. * usually you do not store every event for a window, but just some aggregate for the event * whenever window is closed the corresponding memory is freed. Some more on how Kafka consumer interacts with EventTime (watermarks in particular you can check [here](https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/event_timestamps_watermarks.html#timestamps-per-kafka-partition)
63,084
The background of my question relies on the following points. * Quine-Duhem thesis: it is difficult to test a theory with an experiment, because the test would rely on other theories. * The discussion of the previous point is difficult because we do not have a "theory of everything", so it is not clear if the chain of theories involved in an experiment ends somewhere. * It could be nice to make an attempt to reverse the logic: imagine a universe ruled by a given mathematical model (that we completely know), including entities able to perform experiments, and try to discuss to which extent they are able, by means of experiment, to discover the rules. * This approach does not require to mimic the real physical laws. In the past, it has been tried to imagine very unusual hypothetical universes and discus what the hypothetical inhabitants would see, e.g., "Flatland", or the non-Euclidean geometries. In some cases, scientists later discovered that the imagined universe had some relevance for the real life. Now, the question is: given a mathematical model of a hypothetical universe, possibly including entities (animals, or robots) that are able to perform experiments, how is it possible to discuss the results of their experiments? And the models and theories that they can test and verify? Is there any philosophical attempt in this direction? Can anyone suggest some literature? I do not think that these questions have a straightforward answer. Just to avoid misunderstandings: I already deposited a pre-print on this topic, with some thoughts in this direction, but without references to literature. I do not put here the link because I do not want that my question looks as an advertisement for my manuscript.
2019/04/24
[ "https://philosophy.stackexchange.com/questions/63084", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/39393/" ]
In addition to Nietzsche: --- [Rousseau](https://en.wikipedia.org/wiki/Jean-Jacques_Rousseau) wrote both the music and libretto for an opera - [Le Devin du Village](https://en.wikipedia.org/wiki/Le_devin_du_village). [Rousseau - Le Devin du Village on YouTube](https://www.youtube.com/watch?v=Ld7XDELDnto) --- [Adorno](https://en.wikipedia.org/wiki/Theodor_W._Adorno) was a classically trained pianist, studied composition with [Berg](https://en.wikipedia.org/wiki/Alban_Berg) in Vienna, and wrote piano music and a number of string quartets. [A selection of Adorno string quartets on YouTube](https://www.youtube.com/results?search_query=adorno%20string%20quartet)
5,094
Which of the following sentences is better to use? > > 1. Where it is concluded that the report is incorrect it will be returned. > 2. If the report is incorrect then it will be returned. > > > Or do they mean the same thing? These sentences will be used for a description of activities.
2010/11/16
[ "https://english.stackexchange.com/questions/5094", "https://english.stackexchange.com", "https://english.stackexchange.com/users/201/" ]
In your examples, the sentence starting with *if* is easier to understand. But it always depends on the context of what's being written as well as target audience. I find *where* is used more often in formal writings, but not always.
38,552,131
Question ======== I want to separate my prod settings from my local settings. I found this library [django-split-settings](https://github.com/sobolevn/django-split-settings), which worked nicely. However somewhere in my code I have something like this: ``` if settings.DEBUG: # do debug stuff else: # do prod stuff ``` The problem is that when i run my unit test command: ``` ./run ./manage.py test ``` the above if statements evaluates `settings.DEBUG` as false. Which makes me wonder, which settings file is the test command reading from and how to correct it What I have tried ================= I tried running a command like this: ``` ./run ./manage.py test --settings=bx/settings ``` gives me this crash: ``` Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/beneple/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/beneple/venv/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. ``` any ideas? --- ### update: this is what my run command looks like ``` #!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" docker run \ --env "PATH=/beneple/venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ -e "DJANGO_SETTINGS_MODULE=bx.settings.local" \ --link beneple_db:db \ -v $DIR:/beneple \ -t -i --rm \ beneple/beneple \ $@ ``` currently my manage.py looks like this ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ``` if I run this command: ``` ./run ./manage.py shell ``` it works fine.. but for example when i try to run ``` ./run ./flu.sh ``` which in turn runs test\_data.py which starts like so: ``` #!/usr/bin/env python if __name__ == "__main__": import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import django django.setup() .. from django.conf import settings from settings import DOMAIN ``` it gives me the error: ``` Traceback (most recent call last): File "./bx/test_data.py", line 18, in <module> from settings import DOMAIN ImportError: cannot import name DOMAIN Done. ``` I'm not sure why that's happening, since my base.py definitely has DOMAIN set.
2016/07/24
[ "https://Stackoverflow.com/questions/38552131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/766570/" ]
This is an old question, here is the answer: * with older versions of scapy, it simply was not possible * with newer scapy versions (2.4.0+), simply sniff using the monitor argument `sniff([args], monitor=True)` It shows all packets !
14,321,101
I'm using Flash Builder 4.7. When starting a new Actionscript Project, the first popup box where you define the project name etc doesn't show any SDK's. So under "This project will use" there is just an empty area... And in the created project I also can't link to a Flex SDK in the Actionscript Build Path. When starting a new Flex Project, everything is OK and I can choose between the different SDK's installed. Any idea what could be wrong? Thanks in advance for any help! Frank
2013/01/14
[ "https://Stackoverflow.com/questions/14321101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/278949/" ]
Problem found and solved thanks to this blog post: <http://www.badu.ro/?p=238> Apparantly when moving from Flex Builder 4.6 to 4.7 you have to use new workspaces. If you reuse the existing ones from version 4.6 you run into problems like I was having... Thanks for all your help, Frank
158,224
I am using the below code ``` Web rootWeb = clientContext.Site.RootWeb; rootWeb.Fields.AddFieldAsXml("<Field DisplayName='Session Name' Name='SessionName' ID='"+new GUID()+"' Group='SharePoint Saturday 2014 Columns' Type='Text' />", false, AddFieldOptions.AddFieldInternalNameHint); clientContext.ExecuteQuery(); Field session = rootWeb.Fields.GetByInternalNameOrTitle("SessionName"); ContentType sessionContentType = rootWeb.ContentTypes.GetById("0x0100BDD5E43587AF469CA722FD068065DF5D"); sessionContentType.FieldLinks.Add(new FieldLinkCreationInformation { Field = session }); sessionContentType.Update(true); clientContext.ExecuteQuery(); ``` This creates a site column and adds it to the group, but when I try to attach it to a content type it throws > > duplicate "SessionName" found > > > I also get the below error sometimes > > The field specified with name "SessionName" and ID{some-id} is not accessible or does not exist > > > **After creating site column using this code, I am not able to add site column to content type manually!!** It throws the same error
2015/09/29
[ "https://sharepoint.stackexchange.com/questions/158224", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/41560/" ]
I removed the ID parameter in the column creation and it worked fine ``` Web rootWeb = clientContext.Site.RootWeb; rootWeb.Fields.AddFieldAsXml("<Field DisplayName='Session Name' Name='SessionName' Group='SharePoint Saturday 2014 Columns' Type='Text' />", false, AddFieldOptions.AddFieldInternalNameHint); clientContext.ExecuteQuery(); Field session = rootWeb.Fields.GetByInternalNameOrTitle("SessionName"); ContentType sessionContentType = rootWeb.ContentTypes.GetById("0x0100BDD5E43587AF469CA722FD068065DF5D"); sessionContentType.FieldLinks.Add(new FieldLinkCreationInformation { Field = session }); sessionContentType.Update(true); clientContext.ExecuteQuery(); ```
18,466,107
I've created some utilities that help me at generating HTML and I reference them in my views as `@div( "class" -> "well" ){ Hello Well. }`. Until now those classes were subclassing `NodeSeq` because they [aren't escaped](https://github.com/playframework/playframework/blob/702d48bf4d9d24b58f247546b0cd0cb893659dc0/framework/src/templates/src/main/scala/play/api/templates/ScalaTemplate.scala#L71) then. But I need to get rid off the `NodeSeq` in the top of my class hierarchy because Scala's xml is flawed and makes my code hacky and because I could switch to Traits then. So I tried to find out how to prevent Play from escaping my `Tag`-objects. But unfortunately the only valid solution that I found is to override the template compiler and have the user specify my compiler in his `Build.scala` settings. But I hopefully have overlooked a way more simple approach?
2013/08/27
[ "https://Stackoverflow.com/questions/18466107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493269/" ]
If the PID is stored in a variable called `x`, then the last digit can be found as `x % 10`.
34,415,375
I have an entity with `@OneToOne` mapped subentity: ``` @Entity @Table public class BaseEntity { @Id private String key; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) private InnerEntity inner; } @Entity @Table public class InnerEntity { private String data; } ``` It was working perfectly on persist and merge operations until I decided to fetch all records in a named query (`SELECT e FROM BaseEntity e`). Problems are that after calling it, Hibernate fetches all records from BaseEntity and then executes distinct queries for each InnerEntity. Because table is quite big it takes much time and takes much memory. First, I started to investigate if `getInner()` is called anywhere in running code. Then I tried to change `fetchType` to `EAGER` to check if Hibernate it's going to fetch it all with one query. It didn't. Another try was to change mapping to `@ManyToOne`. Doing this I've added `updatable/insertable=false` to `@JoinColumn` annotation. Fetching started to work perfectly - one `SELECT` without any `JOIN` (I changed `EAGER` back to `LAZY`), but problems with updating begun. Hibernate expects `InnerEntity` to be persisted first, but there's no property with primary key. Of course I can do this and explicity persist `InnerEntity` calling `setKey()` first, but I would rather solve this without this. Any ideas?
2015/12/22
[ "https://Stackoverflow.com/questions/34415375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610215/" ]
If you want `inner` field to be loaded on demand and your relation is `@OnToOne`you can try this `@OneToOne(fetch = FetchType.LAZY, optional = false)`
57,412,417
i have a array `banks` and I need to return one object with all the parameters described below ``` const banks = [{kod: 723,name: "bank",},{kod: 929,name: "bank2"}] ``` i tried to do it with ``` const lookup = banks.map(item => { return ({[item.kod]: item.name }) }) ``` but it returns the result `[ {723: "bank"}, {929: "bank2"} ]` how can i achieve this result `{723: "bank",929: "bank2"}`
2019/08/08
[ "https://Stackoverflow.com/questions/57412417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10473328/" ]
You can use [`.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) with the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) like so: ```js const banks = [{kod: 723,name: "bank",},{kod: 929,name: "bank2"}]; const res = banks.reduce((acc, {kod, name}) => ({...acc, [kod]: name}), {}); console.log(res); ```
4,055,939
I am having a problem with the asp:Menu control. A menu control 2 levels deep does not play well with internet explorer on https. I continually get an annoying popup. I think in order to fix this I need to override a function in an automatically included script file. change this ``` function PopOut_Show(panelId, hideScrollers, data) { ... childFrame.src = (data.iframeUrl ? data.iframeUrl : "about:blank"); ... } ``` to this ``` function PopOut_Show(panelId, hideScrollers, data) { ... if(data.iframeUrl) childFrame.src = data.iframeUrl; ... } ``` however I have no clue how I would hack apart the asp:menu control to fix microsoft's javascript in their control. Is there a way I can just override the function to what I need it to be?
2010/10/29
[ "https://Stackoverflow.com/questions/4055939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102526/" ]
If you declare the overload later that should be the function that executes ``` function alerttest(){ alert("1"); } function alerttest(){ alert("2"); } alerttest(); ``` Here is another answer: [Overriding a JavaScript function while referencing the original](https://stackoverflow.com/questions/296667/overriding-a-javascript-function-while-referencing-the-original)
18,500,368
I'm learning JavaScript from w3schools and it talks about how "If you execute document.write after the document has finished loading, the entire HTML page will be overwritten" and I've seen from examples that this does in fact happen, but "I don't understand what is really going on and the website kind seems to skip over the explanation. I've moved parts of the script around ( ``` <h1>My First Web Page</h1> <p>My First Paragraph</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> </body> </html> ``` ) To see if loading different parts from different points in the script would change the effect, and nothing happened. I'd like to know what is really going on before I continue with the lesson, so if anyone can even just give me a brief summary of how it works I'd appreciate it.
2013/08/29
[ "https://Stackoverflow.com/questions/18500368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727356/" ]
If you're familiar with programming in general then you'll be aware of `stream`s, which represent something you can read from, or write to, in continuous fashion and (usually) lack random-access. Imagine that the `document` object contains hidden inside it a stream that represents the raw text response from the webserver which consists of the HTML text. The method `document.open()` grants access to this stream. When a page is being loaded (right as the bytes from the server arrive in your browser) the document stream is already opened and is being read from/written to. When the document has finished loading (that is, the HTML itself, not external resources like `<img />`) the stream is closed. ...that's why when `document.write` is used while the page is loading (i.e. as `<script>document.write("foo");</script>` it inserts the text "foo" directly into the document stream, whereas calling `document.write` *after* the document has loaded causes the stream to be (implicitly) re-opened from the beginning, which causes it to be overwritten.
72,998,115
My text in the button is not centered. I feel that this happens all the time. The text always seems to be a bit under the center. I tried to open the code with Chrome and Edge. They look the same. Here's a photo of the button ```css .button-container { display: flex; position: absolute; top: 10px; right: 10px; text-align: center; vertical-align: middle; } .button { color: white; font-family: arial; font-size: 28px; background-color: black; padding-left: 15px; padding-right: 15px; padding-top: 5px; padding-bottom: 5px; border-style: none; border-radius: 50%; } ``` ```html <div class="button-container"> <button class="button">x</button> </div> ```
2022/07/15
[ "https://Stackoverflow.com/questions/72998115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19480643/" ]
You are trying to position an element using hard coded padding values. My advice would be not to do that. Remove the padding and change your x -> X. Then add these to your class ``` .button {height: 15px; aspect-ratio: 1/1;} ``` Whatever you set the height to the width will follow. With your border radius you can turn that clean box into a clean circle. Edit: Recommendations aside, your main issue was caused by the use of a lowercase x which comes with a blank space 'baked in' above the letter. On the other hand, an uppercase X uses the whole line height and fills the container nicely.
1,685
This question may be interpreted as "too localized", but it is not. I'm interested in what you find to be the best sites for this type of operation, regardless of where they are located. For instance, I want to learn about how do these sites do the following: * How do they work with geographic information? * What search parameters do they use? * Can you personalize your search? How? and so on...
2010/07/07
[ "https://webapps.stackexchange.com/questions/1685", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/567/" ]
The ones I've had most sucess with is: * [Rightmove](http://www.rightmove.co.uk/)
10,051,395
``` public class Main { public static void main(String[] args){ Class2 class2Object = new Class2(); //class2Object //num1 class2Object.setNumber(class2Object.number1, 1) ; class2Object.getNumber(class2Object.number1); } } public class Class2 { public int number1; public void setNumber(int x, int value){ x = value; } public void getNumber(int number){ System.out.println("Class2, x = "+number); } } ``` I have 2 class: Class2 and Main. I assign an instance variable to 1 in Main class. Why is class2Object.number1 not assign to a value of 1? Output is 0.
2012/04/07
[ "https://Stackoverflow.com/questions/10051395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050548/" ]
Your setter doesn't do anything: ``` public void setNumber(int x, int value){ x = value; // This just overwrites the value of x! } ``` A setter should have only one parameter. You need to assign the received value to the member field: ``` // The field should be private. private int number; public void setNumber(int value){ this.number = value; } ```
19,772,164
I'd like to transition to a template but reloading the page content through a JSON request. In other words, I load initially my index template through a `getJSON` request and then I go to another template where I modify some data. Later, I'd like to return to my initial template through an action handler with the the same `getJSON` request (it'll return another data different from the first one). ```js App.IndexRoute = Ember.Route.extend({ model: function() { return $.getJSON("myurl"); }, actions: { goto: function(){ $.getJSON("myurl"); this.transitionTo('index'); } } }); ``` I'm able to transition to my template and to do a new JSON request but the data I see is the initial one. This only works if I click `F5` because ember renders the template with the first `getJSON` call from model function. EDIT: I've reached a solution but I'd like to know if there is another better one without reloading the page. ```js App.IndexRoute = Ember.Route.extend({ model: function() { return $.getJSON("myurl"); }, actions: { goto: function(){ this.transitionTo('index').then(function(){location.reload(true)}); } } }); ``` Thanks in advanced!
2013/11/04
[ "https://Stackoverflow.com/questions/19772164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2886221/" ]
You can do this purely at the UI level by handling the text box's KeyDown and KeyPress events: ``` Private Sub txtPostCode_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = vbKeySpace Then KeyCode = 0 End Sub Private Sub txtPostCode_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case Asc("a") To Asc("z") KeyAscii = KeyAscii + Asc("A") - Asc("a") End Select End Sub ```
68,656,785
If my code is: ``` context('The Test', () => { let testStr = 'Test A' it(`This test is ${testStr}`, () => { expect(testStr).to.eq('Test A') }) testStr = 'Test B' it(`This test is ${testStr}`, () => { expect(testStr).to.eq('Test B') }) testStr = 'Test C' it(`This test is ${testStr}`, () => { expect(testStr).to.eq('Test C') }) }) ``` [This image has the resulting tests](https://i.stack.imgur.com/hLSKl.png) -- My usage of testStr inside the backticks works the way I want it to (indicated by output having the correct test titles of Test A, Test B, and Test C), but the usage of testStr in the `expect(testStr).to.eq` cases fails the first 2 tests because testStr is always 'Test C' for these checks. Why does this occur, and how can I write this differently to do what I want?
2021/08/04
[ "https://Stackoverflow.com/questions/68656785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16595273/" ]
`it()`'s callbacks will be executed only after parent's one (`context` in your case). You can play with it in debugger and see it live: [![enter image description here](https://i.stack.imgur.com/AFUOV.gif)](https://i.stack.imgur.com/AFUOV.gif) So mocha will assign the final 'Test C' value and call the first `it()` callback after that. To solve the problem as close as possible to the structure of you current approach, you can use mocha context to capture the value at the time you define the `it()` case. Unfortunately, I found the mocha shares the context object between all of `it` siblings. So I had to wrap each of the case inside a child `context`: ``` context('The Test', function () { let curTestStr = 'Test A' context(`This test is ${curTestStr}`, () => { it("test", function() { expect(this.curTestStr).to.eq('Test A') }) }).ctx.curTestStr = curTestStr; curTestStr = 'Test B' context(`This test is ${curTestStr}`, () => { it("test", function() { expect(this.curTestStr).to.eq('Test B') }) }).ctx.curTestStr = curTestStr; curTestStr = 'Test C' context(`This test is ${curTestStr}`, () => { it("test", function() { expect(this.curTestStr).to.eq('Test C') }) }).ctx.curTestStr = curTestStr; }) ``` Please also note that you have to use a `function` callback to access variables from `this`. It will not work with an arrow function expression `() => {}`
27,420,848
My understanding of Oblique font styling in CSS3 is that it's the same as the normal font, with an angle applied. Italics on the other hand, is a separate set of glyphs, that while slanted also feature unique characters, like an extra curly z, or a pronounced y, whatever. Now, I've been running font-style: oblique, and font-style: italic, on many different fonts. One example would be <http://www.google.com/fonts#QuickUsePlace:quickUse> however, the situation appears to be no matter if I call Oblique, or Italic, the result looks the same. I've yet to find a font that contains both Oblique and Italic styling. In reality you seem to get one or another. Does anyone know why this is? I would have assumed by using Oblique as a setting, it would have taken the basic font, and simply displayed it at an angle. Am I misunderstanding this? And if Oblique and Italic just reference one set of characters, what is the point of it even being in CSS3 when it makes no practical different with all the fonts I've seen so far?
2014/12/11
[ "https://Stackoverflow.com/questions/27420848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4345631/" ]
Oblique and Italic are two different styles. They don't look the same; the fact that they *seem* to look the same is caused by the program that displays the font (i.e. the browser); it shows the variant that is present, so if you specify `oblique`, it uses italic if oblique isn't available, and vice versa. Now it's possible for a font to come with both an italic and an oblique variant, and then you can distinguish between those by using `italic` or `oblique`. However, in reality such fonts are rare. Very rare. [Lucida Grande](http://lucidafonts.com/fonts/family/lucida-grande) is one such font. If you're willing to fork money over for it. I also found [Kinnari](https://packages.debian.org/sid/fonts/fonts-tlwg-kinnari), a free font, which is in the Linux repositories even. (If anyone knows about more fonts like that, I'd be delighted!) However, if you're willing to experiment a little, you can use a font editor like [FontForge](http://fontforge.github.io/en-US/) to create slanted fonts from regular ones. So what do you do, you select a font on your machine that has an italic variant, then take the regular version, slant it with the editor and change the style to "Oblique" instead of "Regular". There, you now have a font with both oblique and italic!
39,328,291
I'm building a CMS where Administrators must be able to define an arbitrary number fields of different types (text, checkboxes, etc). Users then can fill those fields and generate posts. How can this be done in Rails? I guess that the persistence of these "virtual" attributes will be done in a serialised attribute in the database. But I am not sure how to struct the views and controllers, or where the fields should be defined.
2016/09/05
[ "https://Stackoverflow.com/questions/39328291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/182172/" ]
What you describe is called [Entity-Attribute-Value model](https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model). MattW. provided 2 possible solutions, but you can also use one of these gems that implement this data pattern instead of handling this yourself: * [eav\_hashes](https://github.com/iostat/eav_hashes) * [hydra\_attribute](https://github.com/kostyantyn/hydra_attribute) I haven't used any of these gems before, so I can't suggest which one is best. RefineryCMS has [this extension](https://github.com/jfalameda/refinerycms-dynamicfields) for the feature you need. You might want to take a look for ideas. There is also a similar [older question here on Stackoverflow](https://stackoverflow.com/questions/12057104/rails-eav-model-with-multiple-value-types).
66,998,989
I am working on a Rest API in TypeScript. The part I'm working on receives as a parameter a Type object containing a body attribute as being of type "Unknown". I have to check that the body attribute that I received in my object as a parameter is strictly compliant with my Type / Interface, here in the exemple : "account" And that's what I can't seem to do ... [![enter image description here](https://i.stack.imgur.com/f1FoJ.png)](https://i.stack.imgur.com/f1FoJ.png) [![enter image description here](https://i.stack.imgur.com/8GzMZ.png)](https://i.stack.imgur.com/8GzMZ.png)
2021/04/08
[ "https://Stackoverflow.com/questions/66998989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345150/" ]
You seem to want: Your query can be radically simplified: * The outer join is really an inner join due to the `WHERE` clause. * The boolean conditions are much more complicated than necessary ( "(A OR B) AND A" is really just "A"). * No subquery is necessary. * The `JOIN` conditions can be expanded. So: ``` SELECT id.id, id.phone, id.business_name, id.address, arr.lc_compliant, arr_record.dnc_compliant FROM import_data id JOIN api_request_record arr ON arr.company_id = id.company_id AND arr.data_record_id = id.id WHERE id.company_id = 1 AND arr.dnc_compliant ORDER BY id.phone DESC LIMIT 100 OFFSET 600; ``` Then for this query, I would recommend the following indexes: * `import_data(company_id, id)` * `api_request_record(company_id, data_record_id, dnc_compliant)` Note that these are indexes with multiple keys, not separate indexes on each key.
459,801
I'd like to ask for the community's opinion regarding the correct usage of a comma for a quoted question. In a situation such as this, which of the two following sentences would be correct? The placement of the comma is the only difference, and I can't seem to pinpoint which one is correct. > > A popular answer to the common introductory question "What is your favorite color?," red is a color that is beloved by many. > > > A popular answer to the common introductory question "What is your favorite color?", red is a color that is beloved by many. > > >
2018/08/12
[ "https://english.stackexchange.com/questions/459801", "https://english.stackexchange.com", "https://english.stackexchange.com/users/312127/" ]
Berserk is an odd option here. **Violent** would provide better meaning. (i)Brusque implies a lack of manners. That's a very *hoity-toity* way of putting it. Pacific is just flat out wrong, it means 'peaceful'. No one stops for picnics in the park in the middle of a revolution. (ii) "more peaceful" implies a calming down, so spreading, metastasizing is out, as is growing. That leaves only recede as viable. Crane Brinton [wrote on the French revolution in 1934](https://en.wikipedia.org/wiki/Crane_Brinton). There's been considerable linguistic drift since then. Brinton does *not* read like a modern American writer.
4,082,537
I am kind of stuck with a simple type check on a generic helper class I am writing. The idea will be clear if you take a look at the source code. It works nice for normal things, like DateTime and bool, but I got a problem with generics. How do I check for e.g. ObservableCollection < **something** > and count it. I do not want to be able to render everything (its a debug control after all), but if there is a collection, I want to know if it has elements. Tried some variations, but none worked. Can't be that hard, the search words just suck (generic, list, collection) - all not very google friendly :-) **[EDIT]** Ok, I played around a little bit, and I get closer. There is however a strange problem with the GetValue() function. If you take a look at the example class, the one string property is working fine, the one set in the constructor shows "NULL" - how can that be. Oh, btw. I am working in Windows Phone 7 - but this should not affect such basic stuff, should it? **[END EDIT]** Updated version of my function: ``` private static FrameworkElement CreateContent(System.Reflection.PropertyInfo propertyInfo, object parent) { var propValue = propertyInfo.GetValue(parent, null); // NULL if (propValue == null) return new TextBlock() { Text = "NULL" }; // Simple cases if (propertyInfo.PropertyType == typeof(int)) return new TextBlock() { Text = propValue.ToString() }; if (propertyInfo.PropertyType == typeof(DateTime)) return new TextBlock() { Text = ((DateTime)propValue).ToShortTimeString() }; if (propertyInfo.PropertyType == typeof(string)) return new TextBlock() { Text = propValue.ToString() }; // More exotic cases if (typeof(IList).IsAssignableFrom(propValue.GetType())) return new TextBlock() {Text = ((IList) propValue).Count.ToString()}; if (typeof(ICollection).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((ICollection)propValue).Count.ToString() }; if (typeof(IEnumerable).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((IEnumerable)propValue).Cast<object>().Count().ToString() }; // If all fails, at least tell me the type return new TextBlock() {Text = propertyInfo.PropertyType.Name}; } ``` Very very strange test case (look for StringPropertyA and B) ``` public class DebugService : ServiceBase, IDebugService { public DebugService(IUnityContainerPhone container) : base(container) { DateTimeProperty = DateTime.Now; StringEmptyProperty = ""; StringObsColl = new ObservableCollection<string>() {"A", "B", "C"}; StringList = new List<string>(){"X", "Y", "Z"}; StringPropertyB = "Will not show up"; } public override string Description { get { return "Does nothing, for debug purposes"; } } public DateTime DateTimeProperty { get; private set; } public int IntProperty { get { return 23; } } public string StringPropertyA { get {return "Is OK";} } public string StringPropertyB { get; private set; } public string StringEmptyProperty { get; private set; } public string StringNullProperty { get; private set; } public ObservableCollection<string> StringObsColl { get; private set; } public IList<string> StringList { get; private set; } } ```
2010/11/02
[ "https://Stackoverflow.com/questions/4082537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109646/" ]
Is it necessary to go this route? ``` if (parent is DateTime) return new TextBlock() { Text = ((DateTime)parent).ToShortTimeString() }; if (parent is ICollection) return new TextBlock() { Text = ((ICollection)parent).Count }; if (parent is IEnumerable) return new TextBlock() { Text = ((IEnumerable)parent).Count() }; //assumes System.Linq ... return new TextBlock() { Text = parent.ToString() }; ```
34,876,623
I got part of a sentence in my database like : ``` beautiful house close to the beach this peaceful touristic area under a beautiful tree behind the property ``` I would like to select sentence that does not contain a list of word like 'to','a' Wanted result: ``` this peaceful touristic area behind the property ``` I figured that I had to use something like ``` SELECT ID_sentence FROM sentence WHERE semi_sentence NOT RLIKE '(.*)[^A-Za-z]to[^A-Za-z](.*)' AND semi_sentence NOT RLIKE '(.*)[^A-Za-z]a[^A-Za-z](.*)' ``` but I can't get the regex right and I should probably group the list under one regex
2016/01/19
[ "https://Stackoverflow.com/questions/34876623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5809722/" ]
You can use *word boundaries* applied to the *group* of two alternatives listed after `|` operator: ``` WHERE semi_sentence NOT RLIKE '[[:<:]](to|a)[[:>:]]' ``` See [what this regex matches](https://regex101.com/r/vA5dB1/1) (you will get those that do not match since you are using `NOT`, and `\b` is used in PCRE instead of both `[[:<:]]` (leading word boundary) and `[[:>:]]` (trailing word boundary)).
47,724,573
I have: ``` myColCI<-function(colName){ predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial") summary(predictorvariable) confint(predictorvariable) } ``` One of the names of the column is parity so when after making my function, when I put `myColCI(parity)`, it says the > > object "parity" is not found > > > Can anyone give me a pointer to what's wrong with my code.
2017/12/09
[ "https://Stackoverflow.com/questions/47724573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9075008/" ]
Your formula is wrong here, hence you are getting the error, The right hand side after tilda side shouldn't be a reference to a dataframe. It should be column names separated by plus signs : From the documentation of `?formula` > > The models fit by, e.g., the lm and glm functions are specified in a > compact symbolic form. The ~ operator is basic in the formation of > such models. An expression of the form y ~ model is interpreted as a > specification that the response y is modelled by a linear predictor > specified symbolically by model. Such a model consists of a series of > terms separated by + operators. The terms themselves consist of > variable and factor names separated by : operators. Such a term is > interpreted as the interaction of all the variables and factors > appearing in the term. > > > `dependent_variable ~ Independent_variable1 + Independent_variable2` etc From data `mtcars`, I have written a glm formula as : `glm(am ~ mpg + disp + hp, data=mtcars, family="binomial")` So, your formula should be something like this: ``` glm(death180 ~ column1 + column2 +column3, data= nepalData, family="binomial") ``` To invoke this inside a function, since you have only one dependent variable it seems you can use below (Note here that, removing the datframe reference here and adding the as.formula expression to incorporate strings, convert the expression as valid formula): ``` myColCI<-function(colName){ predictorvariable <- glm(as.formula(paste0("death180 ~", colName)), data=nepalData, family="binomial") summary(predictorvariable) confint(predictorvariable) } myColCI("parity") ```
51,374,752
Trying to deal with CORS set up a simple Node / Express server like so: ``` const express = require('express'); var cors = require('cors'); const app = express(); const port = process.env.PORT || 3000; app.use(cors()); app.use(express.static('public')); app.listen(port, () => { console.log('Server active on port: ', port); }); ``` Using this cors lib: <https://www.npmjs.com/package/cors> The rest is a simple app using JQuery ajax to fetch some data... Works with the CORS chrome extension enabled but can't figure out how to set up a simple server so that I do not have to use the chrome extension...
2018/07/17
[ "https://Stackoverflow.com/questions/51374752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4750401/" ]
You may try setting the options to be passed to your `cors` package, like this, ``` const corsOptions = { origin: process.env.CORS_ALLOW_ORIGIN || '*', methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization'] }; app.use(cors(corsOptions)); ``` Hope this helps.
264,238
I was making some changes to a remote file in vi using the terminal when I accidently pressed `Ctrl`+`S` instead of `:wq`. Now everything got hanged. I tried `Escape,:q!` and all sorts of vi commans but nothing is responding. The Terminal Screen is stuck. I can't close the Terminal session as of now as it will lead to loss of all the changes. Please suggest what should be done
2013/03/05
[ "https://askubuntu.com/questions/264238", "https://askubuntu.com", "https://askubuntu.com/users/86687/" ]
`Ctrl`+`Q` will undo `Ctrl`+`S`. These are ancient control codes to stop and resume output to a terminal. They can still be useful, for instance when you are `tailf`-ing a log file and something interesting scrolls by, but this era of unlimited scrollback buffers has really obsoleted them.
14,085,881
I would like to implement a simple authentication in an JSF/Primefaces application. I have tried lots of different things, e.g. [Dialog - Login Demo](http://www.primefaces.org/showcase/ui/overlay/dialog/loginDemo.xhtml) makes a simple test on a dialog, but it does not login a user or? I also have taken a look at Java Security, like: ``` <security-constraint> <web-resource-collection> <web-resource-name>Protected Area</web-resource-name> <url-pattern>/protected/*</url-pattern> <http-method>PUT</http-method> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>REGISTERED_USER</role-name> </auth-constraint> </security-constraint> ``` With this everything under /protected is protected, but as far as i understand i need to define a realm in the server for authentication. I do not want to specify this in the server but just have a simple lookup in the database for it. Is there a way to authenticate a user without defining something in the application server? Or anonther simple solution to authenticate and protect different pages?
2012/12/29
[ "https://Stackoverflow.com/questions/14085881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936452/" ]
> > Is there a way to authenticate a user without defining something in the application server? > > > This is a long and *very* thorny story. It often comes up as one the main points of criticism against Java EE. The core of the story is that traditionally Java EE applications are supposed to be deployed with "unresolved dependencies". Those dependencies have to be satisfied at the application server, typically by someone who is not a developer, often by using some kind of GUI or console. Security configuration is one of those unresolved dependencies. If the security configuration is done at the application server, this is by definition always not portable, e.g. it has to be done in an application server specific way. It completely rules out using application domain models (e.g. a JPA entity `User`) for this authentication. Some servers (e.g. JBoss AS) allow configuring their proprietary security mechanisms from within the application, and additionally allow for 'custom login modules' (the term is different for pretty much every server) to be loaded from the application as well. With some small hacks, this will allow the usage of application domain models and the same data source that the application itself uses for authentication. Finally, there's a relatively unknown portable way to do authentication from within an application. This is done via the **JASPIC** SPI, also known as **JASPI** or **JSR 196**. Basically, this JASPIC seems to be what you are looking for. Unfortunately, JASPIC is not perfect and even though it's a technology from Java EE 6 and we're almost at Java EE 7, at the moment support for JASPIC in various application servers is still sketchy. On top of that, even though JASPIC is standardized, application server vendors *still* somehow require proprietary configuration to actually make it work. I wrote an article about JASPIC that explains the current problems in more detail: [Implementing container authentication in Java EE with JASPIC](http://arjan-tijms.blogspot.com/2012/11/implementing-container-authentication.html)
620,445
I am using a very simple model to show the unity gainbandwidth of a closed loop sample and hold with a closed loop gain of 2. One would expect an ideal OTA to have a GBW independent of rout as GBW is just \$ \frac{g\_m\*r\_{out}}{r\_{out}\*C\_L} \$ or \$GBW = g\_m/C\_L (\frac {rad}{s}).\$ Yet, the simulation I contrived shows something very different. It can be seen that \$f\_{unity} = GBW\$ varies with \$rout\$. It has a peak that matches the calc exactly, but tapers off to a value far different than calculated. A clue is that the closed loop gain also behaves oddly. We would expect it to start at 0 and rise and settle to an expected close loop gain of 2, as the open loop gain is getting larger with rout, and the closed loop accuracy should increase. The gain plot shows a peaking coincident with the \$f\_{unity}\$ far above 2. I'm not certain if it is the actual simulation or something with LTSPICE or my theoretical expectations that are amiss. Anyone have an explanation? [![enter image description here](https://i.stack.imgur.com/1zNEH.png)](https://i.stack.imgur.com/1zNEH.png)
2022/05/20
[ "https://electronics.stackexchange.com/questions/620445", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/11779/" ]
If it helps anyone, I figured out (through a fairly tedious analysis) that it's more complicated than the numerous texts, literature, and theses using sample and hold and multiplying dac calculations make it out to be (it can be quite sensitive to low feedback factor and output impedance for example). I found an [excellent paper/blog](https://www.electronicdesign.com/technologies/analog/article/21807892/gainbandwidth-product-is-not-always-constant) explaining the fallacy of perpetuating gainbandwidth product is always constant (even with very simple op amp open/closed loop structures). The author shows that it requires assumptions such as closed loop gain greater than about 20. Below that, the more rigorous calculations are called for. Notice that a common pipeline ADC MDAC uses a gain on the order of 2, falling into this zone. As an example, here, instead of just using \$fu= \frac {g\_m}{2\*pi\*C\_{L}}\$ as is typically shown in texts, a more complex analysis (for the circuit I showed) returns something like \$fu= \frac {g\_m}{2\*pi\*C\_{L}} - \frac{1}{r\_{out}\*{c\_{L}}}\$ where the sensitivity to rout is more clear for smaller rout.
5,847,598
i heard that domain driven design pattern but do not know what it is exactly. is it design pattern? if so then how it is different from mvc or mvp. please discuss this. how to implement domain driven design pattern with c#.
2011/05/01
[ "https://Stackoverflow.com/questions/5847598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728750/" ]
In short: It's not a design pattern. You can see it as **set of patterns** and **principles** where you write code that reflects real life objects and concepts in a specific domain (problem area): From the StackOverflow tag: > > Domain-driven design (DDD) is an > approach to developing software for > complex needs by deeply connecting the > implementation to an evolving model of > the core business concepts. > > > Here is a link to study: * [Wikipedia](http://en.wikipedia.org/wiki/Domain-driven_design)
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
**TL;DR:** In unoptimized code, `if` without `else` seems irrelevantly more efficient but with even the most basic level of optimization enabled the code is basically rewritten to `value = condition + 5`. --- I [gave it a try](https://gcc.godbolt.org/) and generated the assembly for the following code: ``` int ifonly(bool condition, int value) { value = 5; if (condition) { value = 6; } return value; } int ifelse(bool condition, int value) { if (condition) { value = 6; } else { value = 5; } return value; } ``` On gcc 6.3 with optimizations disabled (`-O0`), the relevant difference is: ``` mov DWORD PTR [rbp-8], 5 cmp BYTE PTR [rbp-4], 0 je .L2 mov DWORD PTR [rbp-8], 6 .L2: mov eax, DWORD PTR [rbp-8] ``` for `ifonly`, while `ifelse` has ``` cmp BYTE PTR [rbp-4], 0 je .L5 mov DWORD PTR [rbp-8], 6 jmp .L6 .L5: mov DWORD PTR [rbp-8], 5 .L6: mov eax, DWORD PTR [rbp-8] ``` The latter looks slightly less efficient because it has an extra jump but both have at least two and at most three assignments so unless you really need to squeeze every last drop of performance (hint: unless you are working on a space shuttle you don't, and even then you *probably* don't) the difference won't be noticeable. However, even with the lowest optimization level (`-O1`) both functions reduce to the same: ``` test dil, dil setne al movzx eax, al add eax, 5 ``` which is basically the equivalent of ``` return 5 + condition; ``` assuming `condition` is zero or one. Higher optimization levels don't really change the output, except they manage to avoid the `movzx` by efficiently zeroing out the `EAX` register at the start. --- **Disclaimer:** You probably shouldn't write `5 + condition` yourself (even though the standard guarantees that converting `true` to an integer type gives `1`) because your intent might not be immediately obvious to people reading your code (which may include your future self). The point of this code is to show that what the compiler produces in both cases is (practically) identical. [Ciprian Tomoiaga](https://stackoverflow.com/questions/43202012/if-statement-vs-if-else-statement-which-is-faster/43202221?noredirect=1#comment73501865_43202221) states it quite well in the comments: > > a **human**'s job is to write code **for humans** and let the **compiler** write code for **the machine**. > > >
23,572,110
I have the same command button called "Output" on many sheets in the same workbook. All of the buttons call the same "sub Output()" in module ModMain. I need to know what sheet the command call came from?
2014/05/09
[ "https://Stackoverflow.com/questions/23572110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3621609/" ]
Make sure this is at the top of every VBA module: ``` Option Explicit ``` Then change this: ``` Sub Output() ``` to this: ``` Sub Output(strSource as String) ``` You have added an argument to the `Sub`. Now your code will fail to compile. (Refer to help if you don't know this part.) Fix the code so it compiles. The VBA editor will direct you to every location. Those locations will be the VBA procedures for your "all the same" buttons. Where each calls `Output`, change it to `Output("ThisPlace")`. For *this place*, insert a unique name as identifier. Now the button is identified in a way you can grab from within the `Sub`.
155,428
Our Wordpress website was hacked. I couldn't find anything intelligible from my limited experience from the limited logs my hosting gives. However, browsing in the FTP files I found a post.php file in the root and two more themes. Nothing strange in the DB, nor a new user. In the index I found the string "Silence is golden". I spent my day reading about it and it seems one of the most classic WP attacks. The server hosts a directory of the root where there is a form powered by AppGini, which relies on another DB and is loaded in an iframe in the Wordpress pages. This form is not password protected, however AppGini ships by default protection of MySQL injection. In your opinion, could this form be the door to enter the WP installation? Is this technically possible? Or is it a 100% Wordpress attack, regardless of what is beside it?
2017/03/31
[ "https://security.stackexchange.com/questions/155428", "https://security.stackexchange.com", "https://security.stackexchange.com/users/143619/" ]
the entry points for attacker can include: outdated - PHP, themes, plugins, weak passwords, misconfigured php.ini file that can lead to issues. Please check if any of these have been overlooked.
6,662,087
I'm making an flight search app with Sencha Touch and have encountered a small problem. I want to create a textfield for all the airports and need autocomplete functionality for in order to make it easy for the user to choose departure airport and return airport. How can i implement this? The airports will be loaded via XML-schema and I can't seem to find any good documentation for this feature. Thanx in advance!
2011/07/12
[ "https://Stackoverflow.com/questions/6662087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618162/" ]
Since there were no custom components out there and I needed something like this myself as well, I smashed it together. So, here it is. **Sencha Touch 2 Autocomplete Textfield component:** <https://github.com/martintajur/sencha-touch-2-autocomplete-textfield> It currently uses AJAX request response for populating the autocomplete matches. It also supports custom input by the user. When serializing the form data, the value of this type of input will be: * the selected item ID in case user has selected a matched autocomplete result * the typed text when the user has not chosen an autocomplete result It is very basic at the moment and completely driven by own need for such a control. Feel free to fork, modify, adapt. It's MIT-licenced.
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
This substitute command should do it: ``` :%s#\($\n\s*\)\+\%$## ``` Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command. **EDIT** Explanation: * `\(` ..... Start a match group * `$\n` ... Match a new line (end-of-line character followed by a carriage return). * `\s*` ... Allow any amount of whitespace on this new line * `\)` ..... End the match group * `\+` ..... Allow any number of occurrences of this group (one or more). * `\%$` ... Match the end of the file Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
2,893,751
Here's a problem from Cohn's *Measure Theory*. > > [Cohn, 2.1.3] Let $f$ and $g$ be continuous real-valued functions on $\mathbb{R}$. Show that if $f =g$ for $\lambda$-almost every $x$, then $f = g$ everywhere. > > > Here $\lambda$ denotes Lebesgue measure. Here's what I do. Let $h: \mathbb{R} \to \mathbb{R}$ be a continuous function. Suppose that $h \neq 0$. Then for some $x \in \mathbb{R}$, there is $n \in \mathbb{N}$ such that $|h(x)| > 2/n$. Then by continuity for some $\delta > 0$, we may ensure that whenever $|y - x| < \delta/2$, we have $$ |h(y)| \geq |h(x)| - |h(y) - h(x)| > 2/n - 1/n = 1/n. $$ Hence, $\lambda(\{h \neq 0\}) \geq \lambda(\{|h| > 1/n\}) \geq \delta > 0$. Taking the contrapositive, we just showed if $h$ is a continuous real-valued function on $\mathbb{R}$, then $\lambda\{h \neq 0\} = 0$ implies $h = 0$ (everywhere). The result follows now by setting $h = f - g$, which is continuous. **Question.** Is this basically the simplest way to do it? Other ways?
2018/08/25
[ "https://math.stackexchange.com/questions/2893751", "https://math.stackexchange.com", "https://math.stackexchange.com/users/503984/" ]
I would say that $\{x:h(x)\ne0\}$ is an open set in $\Bbb R$. (Since it is the inverse image of the open set $\Bbb R\setminus\{0\}$ under the continuous function $h$). Each nonempty open set contains a nonempty open interval, which has positive Lebesgue measure. So if $h$ is continuous, and not identically zero, then it cannot be almost everywhere zero (w.r.t. Lebesgue measure).
123,917
I've been trying to train a model that predicts an individual's survival time. My training set is an unbalanced panel; it has multiple observations per individual and thus time varying covariates. Every individual is observed from start to finish so no censoring. As a test, I used a plain random forest regression (not a random survival forest), treating each observation as if it were iid (even if it came from the same individual) with the duration as the target. When testing the predictions on a test set, the results have been surprisingly accurate. Why is this working so well? I thought random forests needed iid observations.
2014/11/13
[ "https://stats.stackexchange.com/questions/123917", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/32018/" ]
Although there is structure to your data, it may be that the variation in baseline risk does not vary substantially enough among your subjects to cause a model without a frailty term to form poor predictions. Of course, it's perfectly possible that a model with a frailty term would perform better than the pooled random forest model. Even if you did run a pooled and hierarchical model and the pooled model did as well or slightly better, you may still want to use the hierarchical model because the variance in baseline risk is very likely NOT zero among your subjects, and the hierarchical model would probably perform better in the long term on data that was in neither your test or training sets. As an aside, consider whether the cross validation score you are using aligns with the goals of your prediction task in the first place before comparing pooled and hierarchical models. If your goal is to make predictions on the same group of individuals as in your test/training data, then simple k fold or loo cross validation on the response is sufficient. But if you want to make predictions about new individuals, you should instead do k fold cross validation that samples at the individual level. In the first case you are scoring your predictions without regard for the structure of the data. In the second case you are estimating your ability to predict risk within individuals that are not in your sample. Lastly, remember always that CV is itself data dependent, and only an estimate of your model's predictive capabilities.
37,252,793
I have the following ARM assembly code: ``` mov r0, SP mov r1, LR bl func ``` Is there a way of calling the function func using C code? something like `func(SP, LR)` Thanks!
2016/05/16
[ "https://Stackoverflow.com/questions/37252793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340494/" ]
Depends on what exactly you want to do and what compiler you use. With `gcc` something like this could work: ``` extern void func(void*, void*); void foo() { int dummy[4]; func(&dummy, __builtin_return_address(0)); } ``` This might not always give you the exact stack pointer, though. As per [godbolt](https://godbolt.org/g/aFvbrK) it produces the following assembly code: ``` foo(): push {lr} sub sp, sp, #20 mov r1, lr mov r0, sp bl func(void*, void*) add sp, sp, #20 ldr pc, [sp], #4 ```
18,786
> > **मानुष्यं च समासाद्य स्वर्गमोक्षप्रसाधनम्।** > > **नाचरत्यात्मनः श्रेयः स मृतः शोचते चिरम्॥३०॥** > > > The human body is the means for achieving of the heaven and moksa and even after achieving the same, he does not do good to himself. After death he keeps on thinking for a long time. > > > > > > It is difficult for even the gods and the demons to achieve the human body. Therefore after achieving the human body, one should act in a way that he has not to face the agonies of the hell. > > > > > And we all along find several verses through Hinduism saying this- **Human Birth is extremely rare and auspicious. We must not waste it and effect our Moksha practicing Yoga *(Karma, Gyaana, Bhakti, Kriya, Raaja Yog: means of attaining Brahma)*.** If it be argued- **'*God gave those human being punishment of previous Karma*'** , then also God could have given them inferior births such as- fishes, birds, animals, et cetera. Why does God give them Human Birth?
2017/06/09
[ "https://hinduism.stackexchange.com/questions/18786", "https://hinduism.stackexchange.com", "https://hinduism.stackexchange.com/users/-1/" ]
We all live in Mrityu Lok or Karma Lok. It is called karma lok because we do Karma in this world/lok and get karma phal in return. Whatever deeds we do, we will surely get Karma phal of that deed in return. The grief or joy we experience in life is nothing but result of our karma referred as karma phal. If we do good deeds then we will get joy and if we do bad then we will get grief. As per **Bhagwat Geeta** and **Garur Puran**, when human dies then he only carries his karma phal (not worldly things like money, fame etc) with him while traveling to other lok known as Yam lok. There Yamraj judges our all karma and decides whether we will stay in Hell or we will go to heaven. Whether we will go to hell or heaven, The main purpose of visiting those loks are just to get karma phal of those karma which we did when we were alive in karma lok. Even when we visit hell or heaven to get karma phal, our all karma phal can't be given in one lok at a time. Means, we have to take birth again to get all of our karma phal but that birth is not easy to get. We only get birth in karma lok if any of our karma phal is pending, hence we have to take birth to get our pending karma phal. And that pending karma phal can be of any kind of karma whether it was sin karma or saintly karma. **How Lord decide where and how we will be born** Following things are decided for us before giving us birth * whether we will born in rich family or in poor family. * We will born as beautiful/pretty person Or ugly person * We will born as healthy or with diseased (mentally or physically). * how long we will live or what will be our age. * How much joy and how much grief we will get during our life time. * How much struggle we need to do in our life to get success. and so on... All these things are decided by the Lord himself before giving us birth. And these things are decided by our karma phal, those karma phal which we earn in our previous birth. So whether people are **Lunatic**, **Autistic** or **Schizophrenic**... etc. It's not Lords wish to make such kind of people but It's karma phal of those people which they earn in previous birth and because of their karma phal they get diseases and other things, Lord can't do anything in this. Pretty much this is the only reason for getting birth in this lok so that we can get all of our karma phal because as par **Bhagawad Geeta** one can't get moksha, if their karma phal is pending. So to get moksha we have to get birth. But unfortunate thing is that, when we get birth to get our pending karma phal then we also do new karma and hence our new karma phal gets generated and to get karma phal of our new karma (which we do in our current birth) we have to take birth again then in next birth while getting our pending karma phal we again do new karma and to get karma phal of new karma we again take birth and then again and again... This cycle of rebirth continues to flow because our karma continues to flow. As long as we are doing karma in this lok, we will be getting birth again and again and we will never get moksha.
71,996,211
I'm only learning Java and Spring and after several projects/tutorials went well I'm stuck with this error on a new project: > > org.springframework.beans.factory.BeanCreationException: Error > creating bean with name 'entityManagerFactory' defined in class path > resource > [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: > Invocation of init method failed; nested exception is > java.lang.NullPointerException > > > I googled and checked stackoverflow questions, but haven't seen *"nested exception is java.lang.NullPointerException"* in any cases. It's quite a vague error message to me, so I can't understand what's causing the error. Here's my pom.xml file ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>shoptest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>shoptest</name> <description>Shop Test for my project</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` **Edit**: Stack trace: ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.7.jar:2.6.7] at com.example.shoptest.ShoptestApplication.main(ShoptestApplication.java:10) ~[classes/:na] Caused by: java.lang.NullPointerException: null at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1672) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1623) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:295) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.19.jar:5.3.19] ... 16 common frames omitted ```
2022/04/25
[ "https://Stackoverflow.com/questions/71996211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13447185/" ]
So to fetch all the unused docker images without actually pruning them, you could do the following 1. Fetch all the images belonging to the running containers(which are not stopped or exited) 2. Fetch all the images on the machine 3. Then filter the images in step 1 from step 2 Below are the shell commands ``` runningImages=$(docker ps --format {{.Image}}) docker images --format "{{.ID}} {{.Repository}}:{{.Tag}}" | grep -v "$runningImages" ```
3,220,890
`DataServiceRequestException` was unhandled by user code. An error occurred while processing this request. This is in relation to the previous post I added ``` public void AddEmailAddress(EmailAddressEntity emailAddressTobeAdded) { AddObject("EmailAddress", emailAddressTobeAdded); SaveChanges(); } ``` Again the code breaks and gives a new exception this time. Last time it was Storage Client Exception, now it is `DataServiceRequestException`. Code breaks at `SaveChanges`.
2010/07/10
[ "https://Stackoverflow.com/questions/3220890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388592/" ]
I was looking into implementing something like this a few month ago. Since GWT compiles your code to JavaScript there is no way for you to do that on the client side, JavaScript can't access the file system. So you would need to upload the file to the server first and do the conversion on the server side and send the converted file back. I have never heard of JODConverter before, the the library I wanted to use was [Apache POI](http://poi.apache.org/index.html) . Unfortunately I can't tell you anything about it, because I haven't tried it yet.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
An [`expl3`](https://ctan.org/pkg/expl3) implementation: ``` \nonstopmode \input expl3-generic \relax \ExplSyntaxOn % -*- expl3 -*- \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } { \int_eval:n { #1 / \l__svend_tmp_int } } \over { \int_eval:n { #2 / \l__svend_tmp_int } } } $$ \svend_reduced:nn {278922} {74088} $$ \bye ``` LaTeX version: ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn % ... code code code \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFraction { > { \SplitList { / } } m } { \int_compare:nTF { \tl_count:n {#1} = 2 } { \svend_reduced:nn #1 } { \msg_error:nn { svend } { malformed-fraction } } } \ExplSyntaxOff \begin{document} \[ \ReducedFraction{278922/74088} \] \end{document} ``` ### Edit with wrapper ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } \frac { \svend_reduced_wrap:n { \int_eval:n { #1 / \l__svend_tmp_int } } } { \svend_reduced_wrap:n { \int_eval:n { #2 / \l__svend_tmp_int } } } } \cs_new:Nn \svend_reduced_use_wrapper:N { \cs_set_eq:NN \svend_reduced_wrap:n #1 } \svend_reduced_use_wrapper:N \use:n %%% Interface \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFractionWrapper { m } { \svend_reduced_use_wrapper:N #1 } \NewDocumentCommand \ReducedFraction { o > { \SplitList { / } } m } { \group_begin: \IfValueT{#1}{\ReducedFractionWrapper{#1}} \int_compare:nTF { \tl_count:n {#2} = 2 } { \svend_reduced:nn #2 } { \msg_error:nn { svend } { malformed-fraction } } \group_end: } \ExplSyntaxOff \usepackage{siunitx} \begin{document} \[ \ReducedFraction[\num]{278922/74088} \] \ReducedFractionWrapper{\num} \[ \ReducedFraction{27892/74088} \] \end{document} ```
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Im geschriebenen Deutsch würde ich immer eher eine Formulierung im Passiv erwarten, die ohne Pronomen auskommt: > > * Wenn das so ist, *wird* keine Regierung mehr *gebraucht*. (*benötigt*) > * *Wird* die EU noch *gebraucht*? (*benötigt*) > * In dieser Region *wird* dringend mehr Regen *gebraucht*. (*benötigt*) > > > Mit dem etwas „feineren“ *benötigen* statt *brauchen*, welches außerdem nicht die missverständliche Nebenbedeutung ‚verwenden‘ aufweist, ist nur *man*, aber nicht *es* möglich: > > * Wenn das so ist, *benötigt man* keine Regierung mehr. (*benötigt \*es*) > * *Benötigt man* die EU noch? (*benötigt \*es*) > * In dieser Region *benötigt man* dringend mehr Regen. (*benötigt \*es*) > > > Dieses *be*-Verb kann wiederum durch *nötig* oder *notwendig sein* ersetzt werden. > > * Wenn das so ist, *ist* keine Regierung mehr *nötig*. (*notwendig*) > * *Ist* die EU noch *nötig*? (*notwendig*) > * In dieser Region *ist* dringend mehr Regen *nötig*. (*notwendig*) > > > Umgangssprachlich würde ich im Norden des Sprachraums eher *man* erwarten, aber ein passendes (Personal-)Pronomen wirkt noch natürlicher: > > * Wenn das so ist, *braucht ihr* keine Regierung mehr. („*brauchta*“; *brauchst du*, „*brauchste*“) > * *Brauchen wir* die EU noch? („*brauchwa*“) > * Hier, in dieser Region, *brauchen sie* dringend mehr Regen. (*brauchen die*, „*brauchense*“) > > > Noch eine Ebene flapsiger wäre *not tun*: > > * Wenn das so ist, *tut* keine Regierung mehr *not*. > * *Tut* die EU noch *not*? > * Hier, in dieser Region, *tut* dringend mehr Regen *not*. > > > Es gibt allerdings Verben (und Phrasen), bei denen *es* ein noch stärkerer Marker für „Süddeutsch“ ist als bei *brauchen*. Man kann *es* allerdings nicht immer durch *man* ersetzen, sondern muss ggf. ein anderes Verb wählen. > > * Hier, in dieser Region, *hat es* nicht genug Regen. (*?hat man* → *gibt es*, *haben sie*) > > > Subjektives Fazit: *braucht es* oder *braucht’s* fällt im direkten Vergleich als süddeutsch auf und wird kaum aktiv verwendet, wirkt aber im niederdeutschen Sprachraum nicht (mehr) so unnatürlich, dass man drüber stolpern würde.
55,275,032
I am new in PL/SQL for this reason sorry for easy question.I hope you will help me. My goal is add values to table with for loop.If you have a question please replay I will answer as soon as posible. This is my code which do not work. ``` declare cursor c_exam_info is select result1 from exam_info; begin for i IN c_exam_info loop if result1>60 then insert into exam_info(result1) values('pass'); else insert into exam_info(result1) values('fail'); end if; end loop; end; ``` [this is my table](https://i.stack.imgur.com/9K1Vg.png)
2019/03/21
[ "https://Stackoverflow.com/questions/55275032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11075976/" ]
I can't view images. Anyway: `INSERT` seems to be inappropriate - wouldn't `UPDATE` be a better choice? Something like this: ``` begin for i IN (select id, result1 from exam_info) loop update exam_info set result_type = case when c_exam_info.result1 > 60 then 'pass' else 'fail' end where id = c_exam_info.id; end loop; end; ``` Though, the same can be done in a SQL layer, you don't need PL/SQL (unless it is a homework so you're practicing PL/SQL). ``` update exam_info set result_type = case when c_exam_info.result1 > 60 then 'pass' else 'fail' end; ``` It doesn't make much sense updating (or even inserting) the same column with a string ('fail' or 'pass') if that column (`result1`) is a number (e.g. 60). Also, what kind of a table is it - having only one column; what good would such an `INSERT` do (the one you wrote in your code)?
38,680
I'm trying to find an efficient way to compute maximum of a signal using its DFT. More formally: $$\max\left\{ \mathcal F^{-1}\left(X\_k\right)\right\}, X\_k\text{ is the DFT of the signal and } \mathcal F^{-1} \text{ is the IDFT}$$ The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. I'm looking for a solution that is quicker than the actual IFFT since the signal is very long (but we have its DFT).
2017/03/27
[ "https://dsp.stackexchange.com/questions/38680", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/25521/" ]
This sounds like a good candidate for the Sparse Fast Fourier Transform (sFFT). Have a look at H. Hassanieh, P. Indyk, D. Katabi, and E. Price, **[sFFT: Sparse Fast Fourier Transform](http://groups.csail.mit.edu/netmit/sFFT/)**, 2012. I don't know details of the algorithm. You have the domains swapped, which should be fine as the discrete Fourier transform (DFT) and its inverse (IDFT) are nearly identical. [sFFT has been discussed](https://dsp.stackexchange.com/questions/2317/what-is-the-sparse-fourier-transform) also here on dsp.stackexchange.com.
37,441,689
I am working on a simple app for Android. I am having some trouble using the Firebase database since it uses JSON objects and I am used to relational databases. My data will consists of two users that share a value. In relational databases this would be represented in a table like this: ``` **uname1** **uname2** shared_value ``` In which the usernames are the keys. If I wanted the all the values user Bob shares with other users, I could do a simple union statement that would return the rows where: ``` uname1 == Bob or unname == Bob ``` However, in JSON databases, there seems to be a tree-like hierarchy in the data, which is complicated since I would not be able to search for users at the top level. I am looking for help in how to do this or how to structure my database for best efficiency if my most common search will be one similar to the one above. In case this is not enough information, I will elaborate: My database would be structured like this: ``` { 'username': 'Bob' { 'username2': 'Alice' { 'shared_value' = 2 } } 'username': 'Cece' { 'username2': 'Bob' { 'shared_value' = 4 } } ``` As you can see from the example, Bob is included in two relationships, but looking into Bobs node doesn't show that information. (The relationship is commutative, so who is "first" cannot be predicted). The most intuitive way to fix this would be duplicate all data. For example, when we add Bob->Alice->2, also add Alice->Bob->2. In my experience with relational databases, duplication could be a big problem, which is why I haven't done this already. Also, duplication seems like an inefficient fix.
2016/05/25
[ "https://Stackoverflow.com/questions/37441689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973615/" ]
Is there a reason why you don't invert this? How about a collection like: ``` { "_id": 2, "usernames":[ "Bob", "Alice"]} { "_id": 4, "usernames":[ "Bob", "Cece"]} ``` If you need all the values for "Bob", then index on "usernames". EDIT: If you need the two usernames to be a unique key, then do something like this: ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 } ``` But this would still permit the creation of: ``` { "_id": {"uname1":"Alice", "uname2":"Bob"}, "value": 78 } ``` (This issue is also present in your as-is relational model, btw. How do you handle it there?) In general, I think implementing an array by creating multiple columns with names like `"attr1"`, `"attr2"`, `"attr3"`, etc. and then having to search them all for a possible value is an artifact of relational table modeling, which does not support array values. If you are converting to a document-oriented storage, these really should be an embedded list of values, and you should use the document paradigm and model them as such, instead of just reimplementing your table rows as documents.
21,272,847
I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters. Here is the code: ``` #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); //gets user input stringstream(mystr) >> price; //converts string: mystr to float: price cout << "Enter quantity: "; getline (cin,mystr); //gets user input stringstream(mystr) >> quantity; //converts string: mystr to int: quantity cout << "Total price: " << price*quantity << endl; return 0; } ``` Just before the conversion here: `stringstream(mystr) >> price;` I want it to print a line to the console if the string is Not a Number.
2014/01/22
[ "https://Stackoverflow.com/questions/21272847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558108/" ]
You can find out if a read of an `int` has been successful or not by checking the `fail()` bit of your input stream: ``` getline (cin,mystr); //gets user input stringstream priceStream(mystr); priceStream >> price; if (priceStream.fail()) { cerr << "The price you have entered is not a valid number." << endl; } ``` [Demo on ideone.](http://ideone.com/Qh2qVr)
22,492,338
I am working on a Chrome extension that will add content to a particular set of pages. From my research, it sounds like what I want is a [content script](https://developer.chrome.com/extensions/content_scripts) that will execute for the appropriate pages. I can specify the "appropriate pages" using the `content_script.matches` manifest.json field. However, the problem I'm running into is that content scripts run in an isolated world, [separate from the rest of your extension](https://developer.chrome.com/extensions/overview#contentScripts). How I had envisioned my extension was a set of [UI pages](https://developer.chrome.com/extensions/overview#pages) that would be embedded on the appropriate pages by the content script. The [background page](https://developer.chrome.com/extensions/overview#background_page) would contain the code for build the content of the UI pages. The background page, and by extension, the UI pages, would need access to the various Chrome APIs (e.g., local storage), as well as being able to make cross-domain requests to retrieve their data. However, it seems this is not possible, since the content scripts run in an isolated world, and don't have access to the Chrome APIs that I need. [Message passing](http://developer.chrome.com/extensions/messaging) allows a content script to send and receive data from the background page, but doesn't allow you to take a UI page and embed it on the current webpage. I initially thought I was making some headway on this when I was able to make a [jQuery AJAX request from my content script for an UI page](https://stackoverflow.com/questions/22315091/can-a-chrome-extension-content-script-make-an-jquery-ajax-request-for-an-html-fi), but that only gets me the HTML file itself. My UI pages depend on code to programmatically build the content--it's not just a static HTML page. And that "build the page" JavaScript code depends on Chrome APIs that are not available to the content script. So, if I just tried to make all my UI pages and JavaScript resources [web\_accessible\_resources](http://developer.chrome.com/extensions/manifest/web_accessible_resources), I could inject them into the page but they wouldn't be able to run. Which brings me to my question: how can a content script pull down, or embed, [UI pages](https://developer.chrome.com/extensions/overview#pages) that can invoke code in the background page?
2014/03/18
[ "https://Stackoverflow.com/questions/22492338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450668/" ]
By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions. Assuming the rename option is not acceptable, use `::foo` to refer to `foo` at the global scope: ``` #include <iostream> int foo = 100; int bar(int foo) { int sum = foo + ::foo; // sum adds local variable and a global variable return sum; } int main() { int result = bar(12); cout << result << "\n"; return 0; } ``` Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the `-Wshadow` option with GCC (`g++`, and with `gcc` for C code) to report problems with shadowing declarations; in conjunction with `-Werror`, it stops the code compiling.
63,547,065
I am setting up a discord game which uses folders as profiles, how do I fix the problem that if someone changes their username the bot can no longer access their profile?
2020/08/23
[ "https://Stackoverflow.com/questions/63547065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14128938/" ]
Use the UserID instead of the Username. This never changes unless they change to a different account, so you won’t have to worry about usernames changing.
31,306,027
I'm working on an FAQ type project using AngularJS. I have a number of questions and answers I need to import into the page and thought it would be a good idea to use a service/directive to load the content in dynamically from JSON. The text strings are quite unwieldily (639+ characters) and the overall hesitation I have is adding HTML into the JSON object to format the text (Line breaks etc). Is pulling HTML from JSON considered bad practice practice, and is there a better way to solve this? I'd prefer to avoid using multiple templates but it's starting to seem like a better approach. Thanks
2015/07/09
[ "https://Stackoverflow.com/questions/31306027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4933483/" ]
I replaced ``` var listeRef = from r in db.refAnomalies select r; ``` with ``` String sql = @"select * from refAnomalie"; List<refAnomalie> listeRefference = new List<refAnomalie>(); var con = new SqlConnection("data source=(LocalDb)\\MSSQLLocalDB;initial catalog=Banque;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"); using (var command= new SqlCommand(sql,con)){ con.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) listeRefference.Add(new refAnomalie { code_anomalie = reader.GetInt32(0), libelle_anomalie = reader.GetString(1), score_anomalie = reader.GetInt32(2), classe_anomalie = reader.GetString(3) }); } } ``` and it worked fine
29,042,618
The app has a controller, that uses a service to create an instance of video player. The video player triggers events to show progress every few seconds. When the video reaches to a certain point, I want to show a widget on top of the video player. The view has the widget wrapped in ng-show directive. It takes more then 60 seconds for the dom element to receive the signal to remove the ng-hide class after the event has been triggered and the values have been populated. If I try to implement this using the plain dom menthod (like document.getElementById(eleId).innerHTML = newHTML), the update is instant. What am I doing wrong? Here is the complete sequence in code: Controller: ``` MyApp.controller('SectionController', ['$scope', 'PlayerService'], function($scope, PlayerService){ $scope.createPlayer = function() { PlayerService.createPlayer($scope, wrapperId); }}); ``` Service: ``` MyApp.service('PlayerService', [], function(){ this.createPlayer=function(controllerScope, playerWrapper){ PLAYER_SCRIPT.create(playerWrapper) { wrapper : playerWrapper, otherParam : value, onCreate : function(player) { player.subscribe(PLAY_TIME_CHANGE, function(duration){ showWidget(controllerScope, duration); }) } } } function showWidget(controllerScope, duration) { if(duration>CERTAIN_TIME) { $rootScope.widgetData = {some:data} $rootScope.showWidget = true; } }}); ``` View: ``` <div ng-show="showWidget"> <div class="wdgt">{{widgetData.stuff}}</div> </div> ```
2015/03/13
[ "https://Stackoverflow.com/questions/29042618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/979535/" ]
Solved it! $scope.$apply() did the trick. My guess is, due to other complex logic ad bindings inside the app, there was a delay in computing the change by angular the default way. @floribon Thanks for the subtle hint about "complex angular stuff". The code inside the service function changed to: ``` function showWidget(controllerScope, duration) { if(duration>CERTAIN_TIME) { $rootScope.widgetData = {some:data} $rootScope.showWidget = true; $rootScope.$apply(); }} ```
19,291,746
I have a string: `{2013/05/01},{2013/05/02},{2013/05/03}` I want to append a { at the beginning and a } at the end. The output should be: `{{2013/05/01},{2013/05/02},{2013/05/03}}` However, in my shell script when I concatenate the curly braces to the beginning and end of the string, the output is as follows: `{2013/05/01} {2013/05/02} {2013/05/03}` Why does this happen? How can I achieve my result? Am sure there is a simple solution to this but I am a unix newbie, thus would appreciate some help. Test script: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{"$valid_data_range"}" print $finalDates ```
2013/10/10
[ "https://Stackoverflow.com/questions/19291746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2844037/" ]
The problem is that when you have a list in braces outside quotes, the shell performs [Brace Expansion](http://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion) (`bash` manual, but [`ksh`](http://www2.research.att.com/sw/download/man/man1/ksh.html) will be similar). Since the 'outside quotes' bit is important, it also tells you how to avoid the problem — enclose the string in quotes when printing: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" print "$finalDates" ``` (The `print` command is specific to `ksh` and is not present in `bash`. The change in the assignment line is more cosmetic than functional.) Also, the brace expansion would not occur in `bash`; it only occurs when the braces are written directly. This bilingual script (`ksh` and `bash`): ``` valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" printf "%s\n" "$finalDates" printf "%s\n" $finalDates ``` produces: 1. `ksh` ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {2013/05/01} {2013/05/02} {2013/05/03} ``` 2. `bash` (also `zsh`) ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {{2013/05/01},{2013/05/02},{2013/05/03}} ``` Thus, when you need to use the variable `$finalDates`, ensure it is inside double quotes: ``` other_command "$finalDates" if [ "$finalDates" = "$otherString" ] then : whatever else : something fi ``` Etc — using your preferred layout for whatever you don't like about mine.
7,056,634
I'd like to read and write window registry in **window xp and 7** by using **vb6**. I'm not much strong in vb6. I tried this below ``` Dim str As String str = GetSetting("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines", "Text", "ImportMixedTypes") ``` My coding doesn't work. Please point out my missing.
2011/08/14
[ "https://Stackoverflow.com/questions/7056634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305732/" ]
You can't use `GetSetting` for that setting. That method is only for reading/writing configuration settings for your own application. If you want to read anywhere in the registry you have to use the Windows API function [RegOpenKeyEx](http://msdn.microsoft.com/en-us/library/ms724897%28v=vs.85%29.aspx) and friends. Here's a Microsoft support article that explains how to do this (with sample code): [How To Use the Registry API to Save and Retrieve Setting](http://support.microsoft.com/kb/145679) Note that you will have to have permission to read the relevant place in the registry, I'm not sure if you'll have access to that key so you'll have to try it out.
74,514,734
I want to fit parent div height to fit it's child that means I want height of parent div to fit red color and green part will hide <https://jsfiddle.net/zfpwb54L/> ``` <style> .container { margin-left: auto; margin-right: auto; padding-left: 15px; padding-right: 15px; width: 100%; } .section { padding: 20px 0; position: relative; } .style_content { color: #27272a; max-width: 700px; position: relative; text-align: center; z-index: 9; } </style> <div id="parent" style="background-color:green; position: relative; direction: rtl;width:fit-content;"> <div style="position: absolute; inset: 0px;"></div> <div style="width: 280px;; "> <div id="child" style="background:red;flex: 0 0 auto; width: 1400px; transform-origin: right top 0px; transform: matrix(0.2, 0, 0, 0.2, 0, 0);"> <section class="section"> <div class="style_content container"> <div><h1>Hello</h1></div> <div><p>that is for test.that is for test.that is for test.that is for test.that is for test. that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.</p></div> <a href="#" target="_blank">click me</a> </div> </section> </div> </div> </div> ```
2022/11/21
[ "https://Stackoverflow.com/questions/74514734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9779942/" ]
For testing your agent in a custom environment alter the endpoint URL to `https://dialogflow.googleapis.com/v2/projects/my-project-id/agent/environments/<env-name>/users/-/sessions/123456789:detectIntent` curl command: ``` curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "x-goog-user-project: PROJECT_ID" \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ "https://dialogflow.googleapis.com/v2/projects/my-project-id/agent/environments/<env-name>/users/-/sessions/123456789:detectIntent" ```
20,365
I cannot open a SQLConnection to a SQL vectorwise database and I assume the JDBC driver is the problem. A JAR file was provided to me - the only info additionally provided to me was the java class: **com.ingres.jdbc.IngresDriver** What would I have to do to add it to the JDBCDrivers that Mathematica can use? Hope this is sufficient information - please let me know, if more information is required. Thanks and regards Patrick
2013/02/27
[ "https://mathematica.stackexchange.com/questions/20365", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5797/" ]
Finally found the answer on how to connect MM to Actian vectorwise via SQL :) ``` Needs["JLink`"] AddToClassPath["C:\\Users\\Desktop\\iijdbc.jar"]; Needs["DatabaseLink`"]; OpenSQLConnection[ JDBC["com.ingres.jdbc.IngresDriver", "jdbc:ingres://HOST:VW7/DATABASE;user=xxx;password=yyy"]] ``` Feeling good! Pat