anchor
stringlengths
0
150
positive
stringlengths
0
96k
source
dict
Confusion about how quantum operators can be expressed
Question: I'm studying atomic physics as one of my physics modules for university and i'm really getting confused with the way operators can be expressed. Specifically when it comes to coupling in the spin-orbit interaction, my lecturer has put: $$ \hat{L}^2 = L\left(L+1\right) $$ and $$ \hat{S}^2 = S\left(S+1\right) $$. In his notes earlier when talking about angular momentum in quantum mechanics he states $$ \hat{L}^2 = \iota\left(\iota +1\right)\hbar^2 $$ where $\iota$ is the angular momentum quantum number. So my question is where is the Hbar in the equation: $$ \hat{L}^2 = L\left(L+1\right) $$ has he just left it out because its a constant? or is there a bit of theory i am missing? any help would help cheers Answer: Orbital and spin orbital energy, because we are dealing with the discrete measurement involved in quantum mechanics, have their values measured in either Planck constant $h$ or reduced $ \hbar$. http://hyperphysics.phy-astr.gsu.edu/hbase/quantum/qangm.html is a good reference for this. https://en.wikipedia.org/wiki/Atomic_units provides the values associated with $h$, which is known as an action. To avoid making equations longer than they need to be, we can set these values to 1, and put them back in at the end of the calculations.
{ "domain": "physics.stackexchange", "id": 38537, "tags": "quantum-mechanics, operators, atomic-physics" }
H6 tolerance shaft manufacturing
Question: I’m a electrical engineer but an amateur in mechanics. I’ve been checking some tools and machines in the market for small works which would allow me to manufacture small but precise pieces, such as a 5mm H6 tolerance shaft to fit a bearing bore under interference. The thing is this shaft should have a tolerance of +-4um, maximum. Ok, so usual lathe setups allow you to position the cutting tool in a scale of 50um marks, with god knows which accuracy. I’d guess no less than +- 50um. But even if it was perfectly match, 50um is rather large near H6 tolerances for my shaft. Ok, let’s assume I could iteratively remove material using a lathe and use a top precision micrometer to check if my shaft is within required dimension. Still it seems to be a very non-professional way to do it, basically a try-and-error approach, moreover I could accidentally remove more material than I should and end up losing all the work and also money. Could anyone tell me if there’s a more efficient method to produce such precise pieces? Answer: If you truly need that type of tolerance and repeatability, then you are way out of the hobby equipment territory. You’ll need high precision calibrated measuring equipment, temperature stability, and specialty manufacturing equipment. Likely an O.D. cylindrical grinding machine will get you there. If the bars are long, they need to be supported while being processed. If you want to get close at the hobby scale, patience, scrap material and some decent micrometers will get you close. You can turn(machine) your diameter oversize and then you could use some abrasives(Emory cloth and scotch bright to polish the diameter to size. You could also make a homemade toolpost grinder. Essentially mount a grinding wheel and motor to your carriage. Trial and error. Cut and measure. Adjust, re-cut. Possible, but seems like an academic effort. To start, I suggest you purchase pre-made shafts to that tolerance and focus on the lower precision items you can actually produce.
{ "domain": "engineering.stackexchange", "id": 2198, "tags": "tolerance, metrology, lathe" }
Web-scrape bonds information from nasdaqomxnordic
Question: I'm a newbie getting into web scrapers. I've made something that works, it takes 3.2 hours to complete job and randomly have 10 lines blank each time I run this job. Help is much appreciated! import sys import pandas as pd from selenium import webdriver import time from datetime import datetime from bs4 import BeautifulSoup from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import NoSuchElementException from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from webdriver_manager.chrome import ChromeDriverManager def getBrowser(): options = Options() options.add_argument("--incognito") global browser options.add_argument("start-maximized") s = Service('''C:\\Users\\rajes\\yogita\\drivers\\chromedriver.exe''') browser = webdriver.Chrome('''C:\\Users\\rajes\\yogita\\drivers\\chromedriver.exe''') return browser def getISINUrls(browser): url = 'http://www.nasdaqomxnordic.com/bonds/denmark/' browser.get(url) browser.maximize_window() time.sleep(1) bonds = {} try: getUrls(browser, bonds) pg_down = browser.find_element(By.CSS_SELECTOR, "#bondsSearchDKOutput > div:nth-child(1) > table > tbody > tr > td.pgDown") browser.execute_script("arguments[0].click();", pg_down) time.sleep(1) while (True): # pages = browser.find_element(By.ID, 'bondsSearchDKOutput') getUrls(browser, bonds) pg_down = browser.find_element(By.CSS_SELECTOR, "#bondsSearchDKOutput > div:nth-child(1) > table > tbody > tr > td.pgDown") browser.execute_script("arguments[0].click();", pg_down) time.sleep(1) except NoSuchElementException as e: pass return bonds def getUrls(browser, bonds): hrefs_in_table = browser.find_elements(By.XPATH, '//a[@href]') count = 0 for element in hrefs_in_table: href = element.get_attribute('href') if 'microsite?Instrumen' in href: bonds[element.text] = href count += 1 def saveURLs(bond): filename = "linkstoday.txt" fo = open(filename, "w") for k, v in bonds.items(): fo.write(str(v) + '\n') fo.close() def getSleepTime(count): first = 1 res = 1 i = 0; while i < count: i += 1 temp = res res = temp + first first = temp return res def getISINData(browser2): with open("linkstoday.txt", "r") as a_file: denmark_drawing = [] for line in a_file: result_found = False count = 2 Isin_code = str() short_name = str() Volume_circulating = str() Repayment_date = str() Drawing_percent = str() wait_time = getSleepTime(0) + 1 while not result_found and count < 5: stripped_line = line.strip() browser2.get(stripped_line) browser2.maximize_window() time.sleep(getSleepTime(count) + 1) WebDriverWait(browser2, 1).until( EC.element_to_be_clickable((By.CSS_SELECTOR, '#ui-id-3 > span'))).click() time.sleep(getSleepTime(count)) Isin_code = browser2.find_element(By.CSS_SELECTOR, '#db-f-isin').text short_name = browser2.find_element(By.CSS_SELECTOR, '#db-f-nm').text Volume_circulating = browser2.find_element(By.CSS_SELECTOR, '#db-f-oa').text Repayment_date = browser2.find_element(By.CSS_SELECTOR, '#db-f-drd').text Drawing_percent = browser2.find_element(By.CSS_SELECTOR, '#db-f-dp').text if Isin_code == " ": count += 1 else: result_found = True temp_data = [Isin_code, short_name, Volume_circulating, Repayment_date, Drawing_percent] denmark_drawing.append(temp_data) # Writing data to dataframe df3 = pd.DataFrame(denmark_drawing, columns=['ISIN', 'Shortname', 'OutstandingVolume', 'Repaymentdate', 'Drawingpercent']) df3.to_csv('Denamrkscrapedsata_20220121.csv', index=False) if __name__ == "__main__": browser = getBrowser() print(f'''Call to getISINUrls start at: {datetime.now()}''') bonds = getISINUrls(browser) print(f'''Call to getISINUrls ends at : {datetime.now()}''') print(f'''total records: {len(bonds)}''') browser.close() browser2 = getBrowser() print(f'''Call to getISINData start at: {datetime.now()}''') getISINData(browser2) print(f'''Call to getISINData ends at : {datetime.now()}''') saveURLs(bonds) browser2.close() sys.exit(0) Answer: Whereas it would be nice to use an official API, I don't see any. Scraping is morally ambiguous and in each case you need to think about the impact to the service. In this case I don't feel too bad about doing it. If you were to keep using Selenium, don't use BeautifulSoup: your browser already has a DOM, so you don't want a secondary library doing HTML parsing. But much more importantly, don't use Selenium at all, and don't even hit the HTML URLs themselves. Invest some time in reverse engineering and you'll see that the data actually come from a (strange, inconsistent, poorly-designed) API that is exposed unauthenticated to the internet. You can see traffic to this API in the developer tools of your favourite browser. Don't call sleep. Even if you were to keep Selenium, there are better ways to wait for conditions to be met. Don't save the URLs: instead, just save the instrument IDs. Don't use Pandas, since you're just writing to a CSV file; use the built-in CSV support. Don't exit(0) at the end; that's redundant. Suggested import csv from typing import Iterator, Iterable, Literal from xml.etree import ElementTree from requests import Session, Response class APIError(Exception): pass def fetch_data( session: Session, xml_query: str, bond_type: Literal[ 'doMortgageCreditAndSpecialInstitutions', 'doGovernment', 'doStructuredBonds', ] = 'doMortgageCreditAndSpecialInstitutions', ) -> Response: with session.post( url='http://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx', headers={ 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', }, cookies={'bonds_dk_search_view': bond_type}, data={'xmlquery': xml_query}, timeout=5, ) as resp: resp.raise_for_status() if resp.text == 'Invalid Request': raise APIError() return resp def get_isin_ids(session: Session) -> Iterator[str]: xml_query = '''<post> <param name="Exchange" value="NMF"/> <param name="SubSystem" value="Prices"/> <param name="Market" value="GITS:CO:CPHCB"/> <param name="Action" value="GetMarket"/> <param name="inst__an" value="ed,itid"/> <param name="XPath" value="//inst[@ed!='' and (@itid='2' or @itid='3')]"/> <param name="RecursiveMarketElement" value="True"/> <param name="inst__e" value="7"/> <param name="app" value="/bonds/denmark/"/> </post>''' xml_response = fetch_data(session, xml_query).text doc = ElementTree.fromstring(xml_response) for institution in doc.findall('./inst'): yield institution.attrib['id'] def save_ids(ids: Iterable[str]) -> None: with open('linkstoday.txt', 'w') as fo: for id in ids: fo.write(id + '\n') def get_isin_data(session: Session, ids: Iterable[str]) -> Iterator[dict[str, str]]: for id in ids: xml_query = f'''<post> <param name="Exchange" value="NMF"/> <param name="SubSystem" value="Prices"/> <param name="Action" value="GetInstrument"/> <param name="inst__a" value="0,1,2,5,21,23"/> <param name="Exception" value="false"/> <param name="ext_xslt" value="/nordicV3/inst_table.xsl"/> <param name="Instrument" value="{id}"/> <param name="inst__an" value="id,nm,oa,dp,drd"/> <param name="inst__e" value="1,3,6,7,8"/> <param name="trd__a" value="7,8"/> <param name="t__a" value="1,2,10,7,8,18,31"/> <param name="json" value="1"/> <param name="app" value="/bonds/denmark/microsite"/> </post>''' doc = fetch_data(session, xml_query).json()['inst'] record = { 'ISIN': doc['@id'], 'ShortName': doc['@nm'], 'OutstandingVolume': doc['@oa'], 'RepaymentDate': doc['@drd'], 'DrawingPercent': doc['@dp'], } yield record def save_csv(records: Iterable[dict[str, str]]) -> None: with open('DenmarkScrapeData.csv', 'w', newline='') as f: writer = csv.DictWriter( f=f, fieldnames=( 'ISIN', 'ShortName', 'OutstandingVolume', 'RepaymentDate', 'DrawingPercent', )) writer.writeheader() writer.writerows(records) def main() -> None: with Session() as session: session.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) ' 'Gecko/20100101 ' 'Firefox/96.0', } ids = tuple(get_isin_ids(session)) print(f'total records: {len(ids)}') save_ids(ids) records = get_isin_data(session, ids) save_csv(records) if __name__ == '__main__': main() Output This output comes from letting the program run for a few seconds and then cancelling it: ISIN,ShortName,OutstandingVolume,RepaymentDate,DrawingPercent XCSE-0:5_111.E.33,"-0,5 111.E.33",84493151,2022-01-01,2.8112571826 XCSE-0:5_PCT_111.E_2030,"-0,5 pct 111.E 2030",665797291,2022-01-01,3.2633533803 XCSE-0:5RDS20S33,"-0,5RDS20S33",451515514,2022-01-01,2.9740738964 XCSE-05NYK01EA30,-05NYK01EA30,878951074,2022-01-01,3.3091375583 XCSE-05NYK01EA33,-05NYK01EA33,881317489,2022-01-01,2.8425761917 XCSE0_111.E.33,0 111.E.33,653907754,2022-01-01,2.4804408498 XCSE0_111.E.38,0 111.E.38,564600489,2022-01-01,1.855852439 XCSE0_111.E.43,0 111.E.43,176772175,2022-01-01,1.3165659355 XCSE0_PCT_111.E.30,0 pct 111.E.30,1029518700,2022-01-01,5.9398552916 XCSE0_PCT_111.E.40,0 pct 111.E.40,1977182808,2022-01-01,1.554107146 XCSE0:0_42A_B_2040,"0,0 42A B 2040",209526702,2022-01-01,1.7771871286 XCSE0:0_ANN_2040,"0,0 Ann 2040",56394289,2022-01-01,1.5425031762 XCSE0:00NDASDRO30,"0,00NDASDRO30",1224109240,2022-01-01,3.8723465773 XCSE0:0NDASDRO33,"0,0NDASDRO33",860502381,2022-01-01,2.2338528235 XCSE0:0NDASDRO40,"0,0NDASDRO40",1459255905,2022-01-01,1.4938027118 XCSE0:0NDASDRO43,"0,0NDASDRO43",236599645,2022-01-01,1.3792804762 XCSE0:0RDSD20S33,"0,0RDSD20S33",718629368,2022-01-01,2.4815379285 XCSE0:0RDSD21S35,"0,0RDSD21S35",3462720875,2022-01-01,2.0717949411 XCSE0:0RDSD21S38,"0,0RDSD21S38",2251018344,2022-01-01,1.7993154025 XCSE0:0RDSD22S40,"0,0RDSD22S40",2011886347,2022-01-01,1.4705608857 XCSE0:0RDSD22S43,"0,0RDSD22S43",184303670,2022-01-01,0.8792686726 XCSE0:5_111.E.38,"0,5 111.E.38",338880761,2022-01-01,1.3969909037 XCSE0:5_411.E.OA.53,"0,5 411.E.OA.53",1393252566,2022-01-01,0.0591983882 XCSE0:5_42A_B_2040,"0,5 42A B 2040",8131539033,2022-01-01,1.3671120294 XCSE0:5_ANN_2040,"0,5 Ann 2040",451401810,2022-01-01,2.4906658405 XCSE0:5_ANN_2050,"0,5 Ann 2050",653730646,2022-01-01,0.8698109475 XCSE0:5_B_2043,"0,5 B 2043",3606287111,2022-01-01,1.2922558113 XCSE0:5_B_2053,"0,5 B 2053",1642437254,2022-01-01,0.8121455742 XCSE0:5_OA_2050,"0,5 OA 2050",99003000,2022-01-01,0.0 XCSE0:5_OA_43A_B_2050,"0,5 OA 43A B 2050",482048871,2022-01-01,0.0 XCSE0:5_OA_B_2053,"0,5 OA B 2053",219089000,2022-01-01,0.0 XCSE0:5_PCT_111.E.27,"0,5 pct 111.E.27",283502208,2022-01-01,8.3610097198 XCSE0:5_PCT_111.E.35,"0,5 pct 111.E.35",1583753306,2022-01-01,2.5446722633 XCSE0:5_PCT_111.E.40,"0,5 pct 111.E.40",6407716782,2022-01-01,1.4303071825 XCSE0:5_PCT_111.E.50,"0,5 pct 111.E.50",10350998334,2022-01-01,0.9164192286 XCSE0:5_PCT_411.E.OA.50,"0,5 pct 411.E.OA.50",3087755141,2022-01-01,0.0671974779 XCSE0:50_43_A_B_2050,"0,50 43 A B 2050",1343369361,2022-01-01,0.8540709785 XCSE0:5NDASDRO27,"0,5NDASDRO27",481074018,2022-01-01,8.803025784 XCSE0:5NDASDRO30,"0,5NDASDRO30",881168727,2022-01-01,7.5241365836 XCSE0:5NDASDRO40,"0,5NDASDRO40",11220224408,2022-01-01,1.5304442894 XCSE0:5NDASDRO43,"0,5NDASDRO43",5986915933,2022-01-01,1.3334597191 XCSE0:5NDASDRO50,"0,5NDASDRO50",9229180944,2022-01-01,0.8712084834 XCSE0:5NDASDRO53,"0,5NDASDRO53",6247426527,2022-01-01,0.8375194931 XCSE0:5NDASDROOA50,"0,5NDASDROOA50",5461281793,2022-01-01,0.0083519478 XCSE0:5NDASDROOA53,"0,5NDASDROOA53",3175404000,2022-01-01,0.0 XCSE0:5NYK01EA27,"0,5NYK01EA27",1269241062,2022-01-01,8.7144274945 XCSE0:5NYK01EA30,"0,5NYK01EA30",1753360650,2022-01-01,6.3398581018 XCSE0:5NYK01EA35,"0,5NYK01EA35",3850470214,2022-01-01,2.2289106154 XCSE0:5NYK01EA38,"0,5NYK01EA38",2292707137,2022-01-01,1.6186901466 XCSE0:5NYK01EA40,"0,5NYK01EA40",25051403176,2022-01-01,1.410155416 XCSE0:5NYK01EA50,"0,5NYK01EA50",23594969156,2022-01-01,0.8777441213 XCSE0:5NYK01EDA50,"0,5NYK01EDA50",9778359698,2022-01-01,0.010495042 XCSE0:5NYK01EDA53,"0,5NYK01EDA53",7720300441,2022-01-01,0.0015823625 XCSE0:5NYK01IA43,"0,5NYK01IA43",152247394,2022-01-01,1.2410533255
{ "domain": "codereview.stackexchange", "id": 42834, "tags": "python, web-scraping, selenium" }
Why the inconsistency, chain rule in $\text dS$ and $\text dU$
Question: So, we started the study of thermodynamics by introducing $\text dU$ in a logical way: $$ \text dU = T \text dS - P\text dV + \mu \text dN . \tag1 $$ Later we started to see that all the properties of a system can be defined by a function $U(S,V,N)$ or $S(U,V,N)$. When we calculate the differential of $U$ we get: $$ \text dU = \left(\frac{\partial U}{\partial S}\right) \text dS + \left(\frac{\partial U}{\partial V}\right) \text dV +\left(\frac{\partial U}{\partial N}\right) \text dN $$ Which, by comparison, we see that $\partial U/ \partial S = T$, $\partial U/ \partial V = -P$ and $\partial U/ \partial N = \mu$. And we can get the relation for $\text dS$ by isolating the term in equation $(1)$, which gets: $$ \text dS = \frac1T \text dU + \frac PT \text dV - \frac\mu T\text dN. $$ But if I try to get the same equation via the chain rule for $\text dS$, I get a switched sign for $P$ and $\mu$ For example: $$ \frac{\partial S}{\partial V} = \frac{\partial S}{\partial U} \frac{\partial U}{\partial V} = \frac{-P}{T} $$ Which should be positive, instead of negative. What am I missing? Answer: I recently opened my profile in this forum and faced this question from a year ago. Although @CRDrost answer is not wrong, I think it would be nice to write here in a clear way how I have managed to understand the problem a year ago. Here it goes: When we first learn about partial derivatives, in the case of functions depending on spatial coordinates (x,y,z), calculating partial derivatives in such a case is as simple as calculating normal derivatives, one just threats the other two variables as constants. Now when we start to change variables or dealing with a bunch of independent variables that have some relation to each other, we see that we must take more care. Following the example given by Mary Boas in his excellent approach to the topic, suppose we have the function $ z = f(x,y) = x^2 - y^2 $, we have no trouble to answer that: \begin{equation*} \frac{\partial f}{\partial x} = 2x \end{equation*} and\ \begin{equation*} \frac{\partial f}{\partial y} =- 2y \end{equation*} Now as an example, if we want to introduce polar coordinates in this case (it could be any other transformation or relation), we define two variables $r$ and $\theta$ that relates to $x$ and $y$ by the intuitive relations: \begin{equation*} x = r \cos(\theta)\\ y=r\sin(\theta) \end{equation*} Keeping this notation, if we now were asked to calculate $\frac{\partial z}{\partial r}$, what would be the correct answer? One could write z in multiple ways, always as a function of a different pair, including r, and give the following answers: \begin{equation} z = f(r,\theta) = r^2 \cos^2(\theta) - r^2 \sin^2(\theta) \Rightarrow \frac{\partial z}{\partial r} = 2r\left(\cos^2(\theta) - \sin^2(\theta)\right) \end{equation} or\ \begin{equation} z = f(r,x) = 2x^2 -r^2 \Rightarrow \frac{\partial z}{\partial r} = -2r \end{equation} or\ \begin{equation*} z = f(r,y) = r^2 - 2 y^2 \Rightarrow \frac{\partial z}{\partial r} = 2r \end{equation*} What answer is the right one? The fact is that none of these answers are wrong, they just represent different things. The first one represents how z varies if we keep the angle fixed and move radially. The second one represents how z varies with $r$ with a fixed $x$, we can see that for a fixed $x$, $(r, \theta, y)$ can have multiple values. And so on. By this reasoning, we can conclude that it makes no sense in asking just for $\frac{\partial z}{\partial r}$, we must specify what variable to keep constant during this evaluation. We can do that by writing, for example in case we want $x$ fixed: \begin{align} \left(\frac{\partial z}{\partial r}\right)_x \end{align} So the first mistake I made, was to not ask myself what variable I was keeping constant while calculating $\frac{\partial S}{\partial V}$, which in case was $U$. Another problem was not differing between functions and the variable itself. Now going straight to the derivative I wanted to calculate, the question I was asking was actually, what is: \begin{align} \left(\frac{\partial S}{\partial U}\right)_{V,N} \end{align} The procedure for calculating that is easy. Since we originally only know $U = f(S,V,N)$ and its derivatives, we do the same procedure to calculate derivatives of implicit functions. Let's derive everything with respect to $V$ keeping $U$ and $N$ constant. \begin{align} \left(\frac{\partial U}{\partial V}\right)_{U,N} = 0 = \left(\frac{\partial f}{\partial S}\right)_{V,N} \left(\frac{\partial S}{\partial V}\right)_{U,N} + \left(\frac{\partial f}{\partial V}\right)_{S,N} \end{align} The first derivative is zero, since $U$ is not the function itself, it is the variable. And for the right side, that is simply chain rule. As assumed we know that: \begin{align} \left(\frac{\partial f}{\partial S}\right)_{V,N} = T\\ \left(\frac{\partial f}{\partial V}\right)_{S,N} = -P \end{align} So: \begin{align} \left(\frac{\partial S}{\partial V}\right)_{U,N} = -\frac{\left(\frac{\partial f}{\partial V}\right)_{S,N}} {\left(\frac{\partial f}{\partial S}\right)_{V,N}}= -\frac{-P}{T}= \frac{P}{T}\\ \end{align}
{ "domain": "physics.stackexchange", "id": 66269, "tags": "thermodynamics, energy, entropy, differentiation, calculus" }
Transforming an arbitrary cover into a vertex cover
Question: Given is a planar graph $G=(V,E)$ and let $\mathcal{G}$ denote its embedding in the plane s.t. each edge has length $1$. I have furthermore a set $C$ of points where each point $c \in C$ is contained in $\mathcal{G}$. Furthermore, it holds for any point $p$ in $\mathcal{G}$ that there exists a $c \in C$ with geodesic distance to $p$ at most one. (The distance is measured as the shortest distance within $\mathcal{G}$.) I want to argue that given a $C$ for which the above condition holds, I can easily transform it into a vertex cover, or put differently, transform it into a $C'$ of same cardinality s.t any $c \in C'$ is placed in $\mathcal{G}$ at a vertex of $G$, and $C'$ still covers $G$. My approach was to orient the edges and move the points in $C$ at the end vertex of the arc. But so far I did not find a correct orientation which yields $C'$ from $C$. Does anybody have an idea? Answer: If no points in $C$ lie exactly on the mid-point of an edge in $\mathcal{G}$, then it suffices to associate each point in $C$ to the nearest vertex in $\mathcal{G}$. I will leave it as an exercise to the reader to prove this (hint: prove by contradiction). On the other hand, if points in $C$ are allowed to lie on the mid-point of edges, then we can provide a counter-example: The blue lines and circles are $\mathcal{G}$ and the red crosses are $C$. EDITED TO ADD: An example with a biconnected graph
{ "domain": "cs.stackexchange", "id": 1306, "tags": "algorithms, graphs, set-cover" }
Notation question for a classical field in QFT
Question: The equations of motion for a classical field $\phi$ can be obtained using the Lagrange: $$ \frac{\partial \mathcal{L}}{\partial \phi} - \partial_\mu \bigg ( \frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)} \bigg )=0 \tag{1}$$ A simple Lagrangian: $$ \mathcal{L} = \frac{1}{2} \partial_\mu \phi \partial^\mu \phi $$ Has the following equations of motion: $$ \partial_\mu \bigg (\frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)} \bigg ) = 0$$ My confusion is at the moment of calculating: $\frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)}$, I would think that since we are taking a partial derivative, the result would be: $$ \frac{\partial \mathcal{L}}{\partial(\partial_\mu \phi)} = \frac{\partial }{\partial(\partial_\mu \phi)} \frac{1}{2} \partial_\mu \phi \partial^\mu \phi =\frac{1}{2} \partial^\mu \phi$$ But I know it is $\partial^\mu \phi$. I understand this is a notation confusion, but what is an intuitive way to understand the correct process to take the partial derivative? Answer: Note that you have too many $\mu$'s floating around in your expression. The correct way to differentiate is to note that by definition, $\partial^\mu \phi = \eta^{\mu\nu} \partial_\nu \phi$. Therefore, $$\frac{\partial }{\partial (\partial_\sigma\phi)}\left[ \eta^{\mu\nu}(\partial_\mu \phi)(\partial_\nu\phi)\right] = \eta^{\mu\nu} \delta^\sigma_\mu (\partial_\nu\phi)+\eta^{\mu\nu}(\partial_\mu\phi)\delta^\sigma_\nu $$ $$ = \eta^{\sigma \nu}(\partial_\nu \phi)+\eta^{\mu\sigma}(\partial_\mu\phi) = 2\partial^\sigma\phi$$ where we've used that $\frac{\partial(\partial_\mu \phi)}{\partial (\partial_\nu\phi)} = \delta^\nu_\mu$.
{ "domain": "physics.stackexchange", "id": 71719, "tags": "quantum-field-theory, notation" }
Protecting a database from bad data
Question: I'm just getting into SQL injection and data sanitization and seeking some advice on my script to get started. I have made this simple program which allows the user to enter their name into a form and the information gets saved into the database. There is also a button that lists all the current names in the database. <?php require 'db.php'; //If the "name" form was submitted, enter it into the database. if (isset($_POST['submit'])) { $name = $_POST['name']; echo $name . ', you submitted it!'; $con->query("INSERT INTO name (name) VALUES ('$name')"); } //Delete name from database. if (isset($_POST['del_submit'])) { $con->query("DELETE FROM name WHERE name='$del'"); echo $del . ' deleted successfully!'; } ?> <form id="devvo" method="post"> <h2>Enter your name:</h2> <p><input type="text" name="name" /></p> <p><input type="submit" value="Submit" /></p> <p><input type="hidden" name="submit" /></p> </form> <br /> <br /> <form id="list" method="post"> <input type="submit" value="List Everyone..."> <input type="hidden" name="list" /></p> </form> <?php //If the "list" form was submitted, get all names from database and display them to the user. if (isset($_POST['list'])) { $result = $con->query("SELECT * FROM name"); while ($row = $result->fetch_assoc()) { $del = $row['name']; echo '<strong>Name:</strong> <br />'; echo $row['name']; echo '<form id="del" method="post"><input type="submit" name="del_submit" value="X" /><input type="hidden" name="del" value="'.$del.'" /></form>'; echo '<br />'; } } ?> My knowledge of PHP is very limited (as you can tell from the program) but I'm definitely seeking some best practices and simple ways to improve the security of a simple program such as this. Feel free to tell me all the different ways this program could be exploited! Answer: A few quick things: $del is never defined when you delete based on it Use prepared statements Not technically necessary here in your script (depending on $del) a good habit to have even when data is safe If you remove the filter later, then the escaping will already be there Don't silently change user's input If the user provides invalid input, tell him; don't silently change it. Not a hard rule by any means, but if a user provides a name and you change it for him, that might be a bit confusing. Strive for valid HTML Probably just meant to be a toy-esque script, but it's CodeReview, so might as well be pedantic :-). You do have a stray </p> though after the list input It's a good habit to separate business logic and presentation MVC is basically what I'm hinting at, but there's no need to go all the way New data should never be fetched or generated inside of HTML The best description of what I'm getting at that I've ever heard is probably (summarized): If you can't reskin your site without repeating PHP code other than simple output, something is wrong. A bit hard to explain if you've never seen it, so if you want, I can do a little example. Escape HTML Any time you put a variable into html, it should be escaped with htmlspecialchars or htmlentities. echo '<tr><td>' . htmlspecialchars($row['name']) . '</td>'; Just because one input is set does not mean that another is $_POST['submit'] and $_POST['name'] are not magically linked A user could exploit this to cause a notice Never directly access anything a user can control the existence or content of Use filter_input like showerhead suggested Or, if you want to do it more directly: $name = (isset($_POST['name']) && is_string($_POST['name'])) ? $_POST['name'] : null; Note: everything comes in as either a string or an array even if it's an integer. $id = (isset($_POST['id']) && is_string($_POST['id'])) ? (int) $_POST['id'] : null;' (Yes, I am 100% crazy-level paranoid) Edit: This is a response to the comment below if you could elaborate on a couple of your points that would be great. Particularly: "Just because one input is set does not mean that another is $_POST['submit'] and $_POST['name'] are not magically linked A user could exploit this to cause a notice" Consider this code: if (isset($_POST['submit'])) { $name = $_POST['name']; ... } As discussed above, you should never access a key that your not sure exists. I'm assuming the logic here is, "well if the form was submitted, then the name field must exist." That's not the case though. Consider this HTML: <form action="http://yoursite.tld/yourpage.php" method="POST"> <input type="submit" name="submit" value="Submit"> </form> Now imagine that someone submits this form. Reading $_POST['name'] will trigger an "undefined index" notice. So, in short, what I was getting at is that there is no link between the submit and name indexes. It's completely possible for one to be set and not the other. Would this actually ever matter? Probably not. But still, it can have bad effects like a malicious user seeing file path or trying to fill up a log file. The code should look like this: if (isset($_POST['submit'])) { $name = (isset($_POST['name']) && is_string($_POST['name'])) ? $_POST['name'] : null; ... } (Or you could use filter_input.) And: The $del issue. The script works great even though you say it isn't defined? The first time $del appears is on line 15 ($db->query("DELETE FROM name WHERE name='$del'");). This means that it is either defined in db.php, or it's not defined. If it's defined in db.php, it shouldn't be. If it's not defined, that means that it's issuing a notice and being treated as null. (There's a third, very unlikely possibility that register globals is enabled. If that abomination is enabled, immediately disable it, or if your hosting company has enabled it without you requesting it, promptly switch companies.) When null is casted to a string, it becomes an empty string, so the query is probably running like: $db->query("DELETE FROM name WHERE name=''"); Also, this query falls under my "Use prepared statements" point above. Imagine if someone submits the following form: <form action="http://yoursite.tld/page.php" method="POST"> <input type="submit" name="del_submit" value="Delete"> <input type="hidden" name="del" value="' OR 1"> </form> That means that this query would be executed: DELETE FROM name WHERE name='' OR 1 1 is always true, thus the entire table would be cleared.
{ "domain": "codereview.stackexchange", "id": 2215, "tags": "php, security, mysqli" }
NP-completeness of non-planar Ising model versus polynomial time eigenvalue algorithms
Question: From the papers by Barahona and Istrail I understand that a combinatorial approach is followed to prove the NP-completeness of non-planar Ising models. Basic idea is non-planarity here. On the other hand, we have polynomial time algorithms for calculating eigenvalues for matrices. This confuses me. Should not be solving an Ising model be equivalent to calculating the eigenvalue of the Hamiltonian matrix of that model? In that case why is it NP-complete? Is coming up with such a Hamiltonian matrix at the first hand is NP-complete? If it is so, it makes the whole project (coming up with such Hamiltonian and solving it) NP-complete. Answer: Okay, my comments are getting too much, so I will answer. If I understand your question correctly it says this: Papers show that the non-planar Ising model (finding its ground state) is NP complete On the other hand, finding the eigenvalues of a matrix is polynomial. So how do these points reconcile? The important point here is in the size of the input. If you want to use the matrix diagonalization as a subroutine for your solution to the Ising model, you have to feed it a matrix. The matrix is a square matrix of some size $M \times M$ where $M$ depends exponentially on the number of lattice sites. Suppose we have ising spins that can be either up or down. Then for $N$ lattice sites the Hilbert space has size $M = 2^N$. This means that your naive algorithm for solving the Ising model on a lattice with $N$ sites will be polynomial in terms of $M$ but therefore exponential in $N$. And what do I mean by a Hamiltonian that's not in matrix form? Well, take the Ising Hamiltonian $$H = -\sum_{\langle i,j \rangle} J_{ij} \sigma_i \sigma_j$$ First, since we're talking about Ising spins, the $\sigma$ are not the Pauli matrices! If you used the pauli matrices we'd be dealing with the Heisenberg model. But even then, it wouldn't be in "matrix form". By matrix form, I mean: Pick a basis for the full Hilbert space, then write down a matrix for $H$ in that Hilbert space. This matrix will be exponentially big, as I've explained above.
{ "domain": "physics.stackexchange", "id": 7778, "tags": "statistical-mechanics, condensed-matter, ising-model, eigenvalue, spin-statistics" }
C# - Linq - Techniques for avoiding repeating same pieces of code
Question: I am writing a piece of code for C# Web Api, letting the clients to pass a column name and sort direction as parameter. Although there are, like, 30-ish properties, so the following code (despite it works) gets ugly after a while. What are my options to avoid repeating this seemingly same pieces of code? if (column == nameof(MyModel.ColumnA).ToLower()) { if (parameters.IsOrderByAsc) { return queryResult.OrderBy(q => q.ColumnA); } return queryResult.OrderByDescending(q => q.ColumnA); } if (column == nameof(MyModel.ColumnB).ToLower()) { if (parameters.IsOrderByAsc) { return queryResult.OrderBy(q => q.ColumnB); } return queryResult.OrderByDescending(q => q.ColumnB); } if (column == nameof(MyModel.ColumnC).ToLower()) { if (parameters.IsOrderByAsc) { return queryResult.OrderBy(q => q.ColumnC); } return queryResult.OrderByDescending(q => q.ColumnC); } .... ``` Answer: If you don't want to pull in DynamicLinq its not a lot of Expression tree work to get exactly what OP is looking for. In the constructor getting the methods we need to call for the Queryable, I'm assuming this is IQueryable and not IEnumerable. If IEnumerable just swap all the Queryable for Enumerable. For the ToLower matching of the property using the BindingFlag.IgnoreCase. Also threw in ThenBy as a bonus as wasn't a lot of work. public static class QueryableExtensions { private static readonly MethodInfo _orderBy; private static readonly MethodInfo _orderByDescending; private static readonly MethodInfo _thenBy; private static readonly MethodInfo _thenByDescending; static QueryableExtensions() { Func<IQueryable<object>, Expression<Func<object, object>>, IOrderedQueryable<object>> orderBy = Queryable.OrderBy; _orderBy = orderBy.Method.GetGenericMethodDefinition(); orderBy = Queryable.OrderByDescending; _orderByDescending = orderBy.Method.GetGenericMethodDefinition(); Func<IOrderedQueryable<object>, Expression<Func<object, object>>, IOrderedQueryable<object>> thenBy = Queryable.ThenBy; _thenBy = thenBy.Method.GetGenericMethodDefinition(); thenBy = Queryable.ThenByDescending; _thenByDescending = thenBy.Method.GetGenericMethodDefinition(); } public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string propertyName, bool orderByAscending = true) { return CreateExpression(source, propertyName, orderByAscending ? _orderBy : _orderByDescending); } public static IOrderedQueryable<TSource> ThenBy<TSource>(this IOrderedQueryable<TSource> source, string propertyName, bool orderByAscending = true) { return CreateExpression(source, propertyName, orderByAscending ? _thenBy : _thenByDescending); } private static IOrderedQueryable<TSource> CreateExpression<TSource>(IQueryable<TSource> source, string propertyName, MethodInfo method) { var propInfo = typeof(TSource).GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) ?? throw new ArgumentException(nameof(propertyName)); var methodInfo = method.MakeGenericMethod(typeof(TSource), propInfo.PropertyType); var sourceParam = Expression.Parameter(typeof(TSource), "source"); var property = Expression.Property(sourceParam, propInfo); var lambda = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), propInfo.PropertyType), property, sourceParam); var call = Expression.Call(methodInfo, source.Expression, lambda); return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>(call); } } Now can just call it like return queryResult.OrderBy(column, parameters.IsOrderByAsc) This doesn't do nested properties but wouldn't be much work to make that w
{ "domain": "codereview.stackexchange", "id": 40721, "tags": "c#, linq" }
Print input one word per line (K&R 1-12 exercise) attempt
Question: I'm currently trying to learn C from the K&R book, reading through and attempting the exercises. I came across exercise 1-12 yesterday and was a little stumped but managed to complete it. I was wondering if someone on here would help me improve it, and also guide me on how to approach testing something like this too. The exercise is to write a program which "prints input one word per line". #include <stdio.h> #define TRUE 1 #define FALSE 0 int main(){ int c, previous_space; previous_space = FALSE; while ( (c = getchar()) != EOF ){ if ( c == ' ' || c == '\n' || c == '\t' ){ if ( previous_space == FALSE ){ putchar('\n'); } previous_space = TRUE; } else{ putchar(c); previous_space = FALSE; } } return 0; } Answer: Algorithmic flaw: Input begins with space Input that begins with ' ' prints a new-line. No point in that. // int previous_space; // previous_space = FALSE; int previous_space = TRUE; Or better with bool bool previous_space = true; Input might not end with a '\n' A line in C: each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined If code wants to handle the case where input does not end with white-space before the EOF, post-loop code is needed. Other white-spaces Aside from OP's 3 listed, there are other white-space characters (carriage return, form-feed, vertical tab, ...), all discernible with isspace(). (See similar idea in @Jerry Coffin) int c Good use of an int instead of char to save the return value from gethar(). Avoided that rookie mistake. Alternative #include <ctype.h> #include <stdbool.h> #include <stdio.h> int main(void) { bool previous_space = true; int c; while ((c = getchar()) != EOF) { if (isspace(c)) { if (!previous_space) { putchar('\n'); } previous_space = true; } else { putchar(c); previous_space = false; } } if (!previous_space) { putchar('\n'); } return 0; } Conceptual simplification Use the inverse flag like bool need_line_feed = false; to reduce ! use in the if()s.
{ "domain": "codereview.stackexchange", "id": 38199, "tags": "algorithm, c, design-patterns" }
What is the species of this strange insect?
Question: I first saw this photo long time ago, and I still can't identify the species of this insect: Answer: Looks to be in the family Dictyopharidae, a long nosed planthopper. This analysis is not absolute as there are exceptions. There are two features to put it in Dictyopharidae and Fulgoridae. The (tiny) antennae are below the eyes, not between them; and the head has a big protrusion. The pattern and placement of spines on the legs, and the pattern of veins on the wings would help to identify it to genus level. A helpful resource is http://hydrodictyon.eeb.uconn.edu/projects/cicada/simon_lab/peet_pages/07_Bartlett.pdf Picture is of Rhynchomitra spp. from Wikipedia.
{ "domain": "biology.stackexchange", "id": 10947, "tags": "species-identification, entomology" }
HDF5 and BioSQL solutions
Question: I'm looking at better database/storage solutions for NCBI virus data, with all attributes particularly year and country of isolation, together with structural data, possible antibody data, T-cell data and bioinformatics data such as %GC etc... The amount of data is comparatively small, with a maximum size of 3 x ([6000 < no. viruses < 20000] for 10 genes) and each entry will contain nucleotide, amino acid and one or more pieces of alignment data (i.e. with indels). The data will be used for numerous different calculations from structural biology, phylogenetics, and deep learning. Some of the calculations will require parallel processing. A typical calculation would be to identify a clade/similarity/difference then screen the database to look at the isolates information. Previously I've used lots of flat files which are loaded at initiation and are held within a data pipeline either as an object (Python) or especially a multi-dimensional hash (Perl, preferred). The two solutions that I think look suitable are: BioSQL - The official Genbank solution, however my SQL commands are very basic and the documentation appears minimal (for BioSQL) HDF5 (hierarchical data format) - this looks good because it uses complex hashes (dictionaries), and allows layering of multiple information onto a single Genbank sequence code (key). It has strong documentation. However, I understand this isn't a "database" (long term storage), but thats how I intend to use it. JSON/Pickling I had a look at JSON, which to me looks okay, because I'm fond of complex hashes / dictionaries, but it appears to be more of a Web solution. Finally, "pickling" (Python) is cool, very cool, but I understand this not a database solution, because it risk compatibility issues, e.g. with future Python releases. I am interested in knowing what archival systems board members are using, and a critique whether my assessment is ok for moving forward. Answer: Just to conclude on the solution to this ancestral question. HDF5 is very useful, but there are better solutions for this specific question if it is focused on pandas dataframes. If you've lots of data the pythonic way to do this is pandas and therefore storing as a pandas dataframe makes sense. For long term storage, which was the original question, the storage of choice for pandas is parquet. Described here Apache Parquet provides a partitioned binary columnar serialization for data frames. It is designed to make reading and writing data frames efficient, and to make sharing data across data analysis languages easy. Parquet can use a variety of compression techniques to shrink the file size as much as possible while still maintaining good read performance. In the following example, two methods parquet methods are used for a pandas dataframe proteinDF which is first written and then imported. from fastparquet import write write('outfile.parq', proteinDF) and import pandas as pd pd.read_parquet('proteindata.parquet', engine='fastparquet') The above approach appears to have received most current developmental attention. However, import pyarrow as pa import pyarrow.parquet as pq arrow_table = pa.Table.from_pandas(proteinDF) pq.write_table(arrow_table, 'myoutpath', use_dictionary=False, compression='SNAPPY') and import pandas as pd pd.read_parquet('example_pa.parquet', engine='pyarrow') The above approach is compatible with numba. 'Multithreading' is further described here. The differences between the methods appear slight. Parallelisation is a big deal and depends on the problem. A general discussion on the methods is here HDF5 vs parquet The backdrop for parquet is the method is used for batch I/O not record by record writing to disk and that is this question and for that is pretty fast (at a guess bit better than pickle, but a lot more compression). HDF5 is perfect for rapid record by record writing and that is what it is designed for, so 'benchmarks' comparing I/O speed are not realistic unless they compare batch vs. record by record timings, where HDF5 excels. parquet does achieve significantly better data compression and is considered a long term storage solution. In my hands HDF5 for fasta writing results in around half the size of the flat file (not much).
{ "domain": "bioinformatics.stackexchange", "id": 2198, "tags": "python, perl" }
Given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix
Question: Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. class DailyCodingProble11 { public static void main(String args[]) { String[] words = { "dog", "deer", "deal" }; Trie trie = new Trie(); for (String word : words) { trie.insert(word); } trie.search("de", trie.root, 0).stream().forEach(word -> System.out.println(word)); trie.search("do", trie.root, 0).stream().forEach(word -> System.out.println(word)); } } class TrieNode { public Character content; public TrieNode[] children = new TrieNode[26]; public boolean isWord; TrieNode(Character ch) { this.content = ch; } } class Trie { TrieNode root; Trie() { root = new TrieNode('*'); } public void insert(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { Character ch = word.charAt(i); if (currentNode.children[ch - 'a'] == null) { currentNode.children[ch - 'a'] = new TrieNode(ch); } currentNode = currentNode.children[ch - 'a']; } currentNode.isWord = true; } public List<String> search(String searchTxt, TrieNode currentNode, int index) { List<String> results = new ArrayList<>(); Character ch = searchTxt.charAt(index); if (currentNode.children[ch - 'a'] == null) { return results; } currentNode = currentNode.children[ch - 'a']; if (index == searchTxt.length() - 1) { findWords(currentNode, new StringBuilder(searchTxt), results); return results; } return search(searchTxt, currentNode, ++index); } public void findWords(TrieNode currentNode, StringBuilder sb, List<String> results) { for (TrieNode child : currentNode.children) { if (child != null) { if (child.isWord == true) { results.add(sb.append(child.content).toString()); } findWords(child, new StringBuilder(sb).append(child.content), results); } } } } How can I improve my solution? Are there any code improvements? Answer: Hide implementation details of Trie root should be private current search and findWords methods should be private write public version of search: should take only a String and call the private one make TrieNode a private static inner class of Trie Change storage of children Storing 26 pointers, most of which will be null in regular usage, is wasteful. You should use a more compact data structure; perhaps a TreeMap<Character, TrieNode>. You could even extend TreeMap for a cleaner interface. Only store characters once You effectively store each character in two places: explicitly in TrieNode.content, and implicitly by the node's position in its parent's children array (or in the key of the children map if you take my recommendation above). If you grab the character in the previous round of recursion, you should not need the TrieNode.content field at all. Fix bug using StringBuilder In findWords if a node is a word and has children, the character will be appended twice. Minor tweaks write a Trie(Iterable<String> content) constructor no need to store '*' in root use List.forEach() instead of List.stream().forEach() separate search functionality into findNode and findWords change if (blah == true) to if (blah) pass functions instead of using lambdas when possible fix indentation -- your IDE should do this for you Finally, variables names can often be shorter if their purpose is clear in context. For example: currentNode vs current. A lot of people say to "use descriptive variables names"; however, brevity can also help with readability as well. My stab at the changes class Trie { private static class TrieNode extends TreeMap<Character, TrieNode> { public boolean isWord; } private TrieNode root; public Trie(Iterable<String> content) { this(); content.forEach(this::insert); } public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { current = current.computeIfAbsent(word.charAt(i), k -> new TrieNode()); } current.isWord = true; } public List<String> search(String word) { List<String> results = new ArrayList<>(); TrieNode node = findNode(word, root, 0); if (node == null) { return results; } findWords(node, new StringBuilder(word), results); return results; } private TrieNode findNode(String word, TrieNode current, int index) { if (index == word.length()) { return current; } Character ch = word.charAt(index); if (!current.containsKey(ch)) { return null; } return findNode(word, current.get(ch), ++index); } private void findWords(TrieNode current, StringBuilder sb, List<String> results) { current.forEach((Character ch, TrieNode child) -> { StringBuilder word = new StringBuilder(sb).append(ch); if (child.isWord) { results.add(word.toString()); } findWords(child, word, results); }); } } class TrieTest { public static void main(String args[]) { Trie trie = new Trie(Arrays.asList(new String[] { "dog", "dee", "deer", "deal" })); trie.search("de").forEach(System.out::println); System.out.println(); trie.search("do").forEach(System.out::println); System.out.println(); } }
{ "domain": "codereview.stackexchange", "id": 41292, "tags": "java, programming-challenge" }
STFT output frequency does not match sin wave frequency
Question: I have the following function and pre definition for producing a sin and its' stft: fs=48000 nfft=2048 hop_len=nfft/2 win_len=2048 nfft = next_greater_power_of_2(win_len) def sinus_gen(f): np.expand_dims(np.sin(2*np.pi*f*np.arange(fs*20)/fs).astype(np.float64)... ,axis=1) I am trying to generate and plot an 8KHz using the following stft command: audio=sinus_gen(8000) s=librosa.core.stft(audio[:, 0], n_fft=nfft, hop_length=hop_len, win_length=win_len, window='hann') librosa.display.specshow(librosa.amplitude_to_db(abs(s)),x_axis='time',y_axis='log',cmap='jet') plt.title('Power spectogram before beamforming') plt.colorbar(format='%+2.0f dB') plt.clim(-60,30) plt.tight_layout() plt.show() I am getting the following spectrogram image, which shows 4000KHz for some reason: Why am I not seeing the expected 8000KHz frequency? what am I doing wrong? Answer: You have to pass sr=fs as well as hop_length=hop_length to the specshow function, as its default values are different from yours.
{ "domain": "dsp.stackexchange", "id": 7637, "tags": "frequency, stft" }
Delegate for GUI project
Question: I wrote simple delegate in C++11 for my GUI project. I think that some parts can be optimized or cleaned. #ifndef DELEGATE_H #define DELEGATE_H //Container interface template<typename... Args> class IContainer { public: virtual void Call(Args...) {} virtual ~IContainer() {} IContainer<Args...> *next; }; //Container realization template< typename T, typename M, typename... Args > class MContainer : public IContainer<Args...> { public: MContainer( T* c, M m ) : mClass( c ), mMethod( m ) {} void Call(Args... args) { (mClass->*mMethod)( args... ); } private: T *mClass; M mMethod; }; template< typename M, typename... Args > class FContainer : public IContainer<Args...> { public: FContainer( M m ) : mMethod( m ) {} void Call(Args... args) { (mMethod)( args... ); } private: M mMethod; }; //Delegate template<typename... Args> class Delegate { public: Delegate() { mContainerHead = new IContainer<Args...>(); mContainerTail = mContainerHead; mContainerHead->next = 0; } ~Delegate() { IContainer<Args...> *container = mContainerHead; while(container) { IContainer<Args...> *temp = container->next; delete container; container = temp; } } void Clear() { IContainer<Args...> *container = mContainerHead->next; while(container) { IContainer<Args...> *temp = container->next; delete container; container = temp; } mContainerHead->next = 0; mContainerTail = mContainerHead; } template<typename T, typename M> void Connect(T *c, M m) { mContainerTail->next = new MContainer< T, M, Args... >(c,m); mContainerTail->next->next = 0; mContainerTail = mContainerTail->next; } template<typename M> void Connect(M m) { mContainerTail->next = new FContainer< M, Args... >(m); mContainerTail->next->next = 0; mContainerTail = mContainerTail->next; } template<typename T, typename M> void Disconnect(T *c, M m) { IContainer<Args...> *container = mContainerHead; while(container->next) { MContainer<T, M, Args...> *temp = dynamic_cast< MContainer<T, M, Args...>* >(container->next); if(temp) { if(container->next == mContainerTail) { mContainerTail = container; } container->next = container->next->next; delete temp; break; } container = container->next; } } template<typename M> void Disconnect(M m) { IContainer<Args...> *container = mContainerHead; while(container->next) { FContainer<M, Args...> *temp = dynamic_cast< FContainer<M, Args...>* >(container->next); if(temp) { if(container->next == mContainerTail) { mContainerTail = container; } container->next = container->next->next; delete temp; break; } container = container->next; } } void operator ()(Args... args) { Call(args...); } void Call(Args... args) { IContainer<Args...> *container = mContainerHead; while(container) { container->Call(args...); container = container->next; } } private: IContainer<Args...> *mContainerHead; IContainer<Args...> *mContainerTail; }; #endif // DELEGATE_H Using example: struct TestClass1 { void hello(int a, int b) { std::cout << a << " + " << b << " = " << a+b << std::endl; }; }; struct TestClass2 { void hello(int a, int b) { std::cout << a << " - " << b << " = " << a-b << std::endl; }; }; struct TestClass3 { void hello(int a, int b) { std::cout << a << " * " << b << " = " << a*b << std::endl; }; }; int main() { TestClass1 t1; TestClass2 t2; TestClass3 t3; Delegate<int, int> d; d.Connect(&t1, &TestClass1::hello); d.Connect(&t2, &TestClass2::hello); d.Connect(&t3, &TestClass3::hello); d.Call(10,5); d.Disconnect(&t2, &TestClass2::hello); return 0; } Answer: IContainer In the class IContainer the member next is public. Which leads to potential incorrect useage. Non private members is a code smell they should be hidden behind access methods (not get/set but more like chain()). Also it would be easier if you used smart pointers to make sure that everything is correctly cleaned up. Delegate The Delegate class has owned raw pointers and does not follow the rule of five (google rule of three as it is more common but the rule of three was expanded to the rule of five with C++11). You can fix this be either implementing (or disabling) all the compiler generated methods. Or converting your owned raw pointers into smart pointers. My choice would be to convert them into smart pointers as correctly handing multiple RAW pointers with exceptions propagating is non trivial (a class with multiple owned RAW pointers is a Code smell even if you do implement the rule of five). The code ~Delegate() and Clear() is very similar (ie code duplication). You should refactor this to move common code to a single function. If the code changes you then only have a single location that will need fixing. In the method Conect() a lot of work is done that is usually associated with the constructor of the object. If you give IConnect an appropriate constructor this code becomes highly simplified and easier to follow. In the method Disconnect() IContainer<Args...> *container = mContainerHead; while(container->next) { // STUFF container = container->next; } This looks more like a for(;;) loop. for(IContainer<Args...> *container = mContainerHead; container->next; container = container->next) { // STUFF } I think this does not read as well as it could. container->next = container->next->next; // I would have done: container->next = temp->next; There is no indication that anything was removed from the list. There is also the possibility that might be multiple objects in the list that match the input requirements. So even if you remove one item this does not mean there does not exist an item with the same properties. Here you have two options: 1) Add another bool parameter (that defaults to false) to indicate that all matching items should be removed from the list. 2) Return a boolean that indicates if anything was removed from the list (this allows the user to manually loop until all matching items have been removed if required). In method Call() again I would have used a for(;;) loop. You can also do one small optimization by not calling Call() on the actual head node (as you using sentinal that does nothing no point it calling the sentinal).
{ "domain": "codereview.stackexchange", "id": 2682, "tags": "c++, optimization, c++11, delegates" }
Makefile that places object files into an alternate directory (bin/)
Question: I'm trying to learn how to use makefiles, and this is my attempt at making a makefile that compiles source files in a source directory (src/) into object files that are created in a bin directory. ########################################## # Editable options # ########################################## # Compiler options CC=g++ CFLAGS=-c -Wall LDFLAGS= EXECUTABLE_NAME=testes # Folders SRC=src BIN=bin OBJ=$(BIN)/obj # Files SOURCE_FILES=\ main.cpp \ test.cpp ########################################## # Don't touch anything below this # ########################################## OBJECT_FILES=$(addprefix $(OBJ)/, $(SOURCE_FILES:.cpp=.o)) build: create_directories create_executable @echo "Build successful!" create_executable: create_objects @$(CC) $(LDFLAGS) $(OBJECT_FILES) -o $(BIN)/$(EXECUTABLE_NAME) @echo "Created executable." create_objects: $(SOURCE_FILES) @echo "Created objects." create_directories: @mkdir -p $(OBJ) %.cpp: @echo "Compiling "$@ @$(CC) $(LDFLAGS) -c $(SRC)/$@ -o $(OBJ)/$(patsubst %.cpp,%.o,$@) clean: @rm -r -f $(BIN) This makefile works, I just want to make sure I'm doing everything correctly. Any changes you guys would suggest? Answer: You are not using the make system properly. As a result, it will always relink the executable, even when everything is already up to date. On the other hand, it might fail to recompile some source files into object files. When you run make… It will try to create the build target. No file named build exists, so… It will try to create the prerequisites of build, namely create_directories and create_executable, neither of which are names of existing files. In an attempt to create a file called create_directories, it runs mkdir -p $(OBJ). For create_executable, it needs to rebuild create_objects. For create_objects, it just verifies that all of the source files are present. For any of the $(SOURCE_FILES) that is missing, it "creates" it using the %.cpp: rule, which actually tries to compile the missing .cpp into a .o. Once all of the $(SOURCE_FILES) are present, it echoes "Created objects.". That's a false claim due to the error above. Having thus falsely satisfied the prerequisites for create_executable, it proceeds to attempt to link the executable, even if any of the $(OBJECT_FILES) is missing. The main remedy is to specify real targets and real dependencies, rather than phony labels like create_executable. Here is how I would write it. Other than the major problems cited above, I have also noted many minor issues in the comments. ######################################################### # Replacing everything that you told me not to touch... # ######################################################### EXECUTABLE_FILES = $(EXECUTABLE_NAME:%=$(BIN)/%) OBJECT_FILES = $(SOURCE_FILES:%.cpp=$(OBJ)/%.o) # ^^^ A more succinct expression for $(OBJECT_FILES), using # http://www.gnu.org/software/make/manual/make.html#Substitution-Refs build: $(EXECUTABLE_FILES) clean: rm -r -f $(BIN) @# ^^^ I don't recommend suppressing the echoing of the command using @ # http://www.gnu.org/software/make/manual/make.html#Phony-Targets .PHONY: build clean $(EXECUTABLE_FILES): $(OBJECT_FILES) @$(CC) $(LDFLAGS) -o $@ $^ @# ^^^ http://www.gnu.org/software/make/manual/make.html#Automatic-Variables @echo "Build successful!" # http://www.gnu.org/software/make/manual/make.html#Static-Pattern $(OBJECT_FILES): $(OBJ)/%.o: %.cpp @echo Compiling $< @# ^^^ Your terminology is weird: you "compile a .cpp file" to create a .o file. @mkdir -p $(@D) @# ^^^ http://www.gnu.org/software/make/manual/make.html#index-_0024_0028_0040D_0029 @$(CC) $(CFLAGS) -o $@ $< @# ^^^ Use $(CFLAGS), not $(LDFLAGS), when compiling.
{ "domain": "codereview.stackexchange", "id": 42797, "tags": "beginner, makefile" }
First Program Tic-Tac-Toe
Question: This is the first little project I've made that didn't feel it was complete gibberish. But I couldn't tell. The biggest problem I had with this was using the BoardValue enum working like I wanted to. I understand that classes should have a level of abstraction to them and I suspect that the way I implemented the at(int) returning a char over a BoardValue took away from that. However, I though having to convert the return from at(int) to a char if it returned a BoardValue would be redundant. For example, using a statement like this: char print_char = Board.at(some_index) == BoardValue::o ? 'O' : 'X'; I hope I've done a decent job describing my dilemma. Overall, I'm hoping for some overall general code style tips and pointers on how to write better code from here. tictactoe.h #ifndef TICTACTOE #define TICTACTOE #include <array> #include <iostream> enum BoardValue : char{ none = ' ', o = 'O', x = 'X' }; class Board { public: Board() { for(auto begin = board.begin(),end = board.end();begin != end; ++begin) *begin = BoardValue::none; } char at(int index) const{ return board.at(index); } inline bool check_win(BoardValue) const; bool place(int, BoardValue); private: bool check_diagonals(BoardValue) const; bool check_horizontals(BoardValue) const; bool check_verticals(BoardValue) const; std::array<char, 9> board{}; }; inline bool Board::check_win(BoardValue check) const { if(check == BoardValue::none) throw "Trying to check_win for check == BoardValue::none!"; return check_diagonals(check) || check_horizontals(check) || check_verticals(check); } #endif tictactoe.cpp #include "tictactoe.h" #include <iostream> //returns false if index is occupied bool Board::place(int index, BoardValue value) { if(board.at(index) != BoardValue::none) return false; board.at(index) = value; return true; } bool Board::check_diagonals(BoardValue check) const { //if middle is not check no diagnols will pass if(board.at(4) != check) return false; //backward diagonal '\' if(board.at(0) == check && board.at(4) == check) return true; //forward diaganol '/' if(board.at(2) == check && board.at(6) == check) return true; return false; } bool Board::check_horizontals(BoardValue check) const { for(int row = 0; row < 3; ++row){ if(board.at(row) == check && board.at(row + 3) == check && board.at(row + 6) == check) return true; } return false; } bool Board::check_verticals(BoardValue check) const { for(int col = 0; col < 3; ++col){ if(board.at(col * 3) == check && board.at(col * 3 + 1) == check && board.at(col * 3 + 2 ) == check) return true; } return false; } main.cpp #include "tictactoe.h" #include <iostream> int ask_input(char player, bool retry = false) { if(!retry) std::cout << "It's " << player << "'s turn. Where do you want to go(e.g. A1 B3 C2)? "; else std::cout << "No, no, no " << player << "! Input a letter followed bt a number: "; std::string input; std::cin >> input; if(input.size() < 2) return ask_input(player, true); int col_input{}; switch(*input.begin()) { case 'A': case 'a': col_input = 0; break; case 'B': case 'b': col_input = 1; break; case 'C': case 'c': col_input = 2; break; default: return ask_input(player, true); } int row_input = *(input.begin() + 1) - '0'; //convers char '1' to int 1 --row_input; return col_input * 3 + row_input; } BoardValue ask_turn() //ask whos first if return true O goes first { BoardValue turn; std::string input; std::cout << "Who goes first(X or O)? "; for(bool valid_input{false}; !valid_input;) { std::cin >> input; switch(input.front()) //input cannot be null at this point { case 'x': case 'X': valid_input = true; turn = BoardValue::x; break; case '0': case 'o': case 'O': valid_input = true; turn = BoardValue::x; break; default: std::cout << "Invalid input! Try X or O :"; } } return turn; } std::ostream &print_board(std::ostream &os,const Board &board) { os << " |A|B|C\n"; for(int row = 0; row < 3; ++row) { os << std::string( 8, '-') << '\n'; os << row + 1 << '|'; for(int col = 0; col < 3; ++col) { char follow_char{ col == 2 ? '\n' : '|' }; os << board.at(col * 3 + row) << follow_char; } } os << std::endl; return os; } int main(){ Board board{}; BoardValue turn{ ask_turn() }; //turn will be set back to appropriate value at start of game loop turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o; int turn_count{0}; while(board.check_win(turn) == false) { turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o; print_board(std::cout, board); bool input_valid{false}; while(input_valid == false) { int input; input = ask_input(turn); input_valid = board.place(input, turn); if( input_valid == false ) std::cout << "That place is take! Try again..\n"; } if(++turn_count == 9) //max amount of turns game is tie break; } print_board(std::cout, board); if(turn_count == 9)//game is tie std::cout << "Looks like its a tie...\n"; else std::cout << (char)turn << " wins!\n"; } Answer: Here are some things that may help you improve your code. Use the required #includes The code uses std::string which means that it should #include <string>. It was not difficult to infer, but it helps reviewers if the code is complete. Have you run a spell check on comments? If you run a spell check on your comments, you'll find a number of things such as "diagnols" and "diaganol" instead of "diagonals" and "diagonal." Since your code is nicely commented, it's worth the extra step to eliminate spelling errors. Be wary of recursive calls The ask_input routine has a subtle flaw. In particular, because it is recursive, it may be possible for a malicious user to crash the program by exhausting the stack. All that would be required would be to continue to input improperly formatted data. For this reason, as well as to make the code more understandable, I'd suggest instead to make retry a local variable and use that, as in a while loop, to re-ask if needed. Fix the bug The ask_input has a not-so-subtle flaw as well. It checks the letter, but not the number, so a user could input C9 or A0 and the program would attempt to use that! Don't use std::endl if you don't really need it The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized. Be judicious with the use of inline If a function is small and time critical, it makes sense to declare it inline. However, the check_win function is not really time critical, so I would say that there's no reason to make it inline. Consider using a stream inserter The existing print_board function is written exactly as one would write as one would write a stream inserter. The only thing that would change would be the declaration: std::ostream &operator<<(std::ostream& os, const Board& board) { /* ... */ } Simplify your constructor The Board constructor is currently defined like this: Board() { for(auto begin = board.begin(),end = board.end();begin != end; ++begin) *begin = BoardValue::none; } There are at least three ways to simplify it. One would be to use a "range-for" syntax: Board() { for(auto& space : board) { space = BoardValue::none; } } Another would be use fill: Board() { board.fill(BoardValue::none); } A third way would allow you omit the constructor entirely. Do that by using aggregate initialization in the declaration of board: std::array<char, 9> board{ ' ',' ',' ', ' ',' ',' ', ' ',' ',' ', }; Think carefully about the class design The structure of the code is not bad, but some things to think about are what things should be the responsibility of the Board class and which are not. For example, I think it might make more sense for Board to keep track of the number of turns. Simplify the code This line is not easy to read or understand: turn = turn == BoardValue::o ? BoardValue::x : BoardValue::o; I would suggest instead having turn be a bool that represents O. Then flipping back and forth would simply be turn = !turn;.
{ "domain": "codereview.stackexchange", "id": 34607, "tags": "c++, tic-tac-toe" }
A question concerning the strength of synapses
Question: Synaptic strength can be defined »as the average amount of current or voltage excursion produced in the postsynaptic neuron by an action potential in the presynaptic neuron« Synaptic strengths and their changes depend on many factors and mechanisms, from LTP and LTD to STDP and STF and STD. Possibly, also neuromodulators should belong to this list – but maybe they shouldn't. Assuming that synaptic strength is a well-defined quantity even when the synapse is at rest, the strength of a synapse is a continuous or non-continuous function over time, that ideally can be plotted. Now I wonder whether there have been recordings and/or simulations of the synaptic strength of a single synapse as such a function over time - and how the plot would look like at different time scales: long term trends superimposed by shorter and shorter fluctuations? Answer: What you are describing is exactly how long-term potentiation/LTP (or depression/LTD, for that matter) is measured electrophysiologically. Here's an example from a 1988 review by Nicoll et al: Nicoll, R. A., Kauer, J. A., & Malenka, R. C. (1988). The current excitement in long term potentiation. Neuron, 1(2), 97-103. The x-axis is time in minutes, the y-axis is a measure of synaptic strength: the slope of the local field potential response to simulation of a particular pathway. You could also measure an EPSP internally, measure voltage with a voltage-sensitive dye, etc. At the point marked "tetanus", a long train of pulses is delivered that is known to cause LTP. Afterwards, you see an increase in synaptic strength that is maintained for many minutes. It's also possible to perform these experiments over longer time scales, with different paradigms, in the presence of various drugs that influence LTP, etc. Different protocols will give different durations of LTP. These sorts of plots are ubiquitous in the LTP/LTD research field, so if you read any papers in that area you are likely to come across many similar presentations.
{ "domain": "biology.stackexchange", "id": 10329, "tags": "neurophysiology, synapses, memory, learning" }
Have we observed sufficient extra-solar planetary systems to establish a planetary distribution pattern?
Question: From Kepler And Extra-Solar Planetary Observations As of January 2015, Kepler and its follow-up observations had found 1,013 confirmed exoplanets in about 440 stellar systems, along with a further 3,199 unconfirmed planet candidates. Regarding the above observations, and the data gained from any similar programs, do we currently have an idea of the distribution of planets, in terms of mass and distance from their sun's? In particular, for stars similar in mass to our Sun, are there hints that a similar pattern to our own solar system distribution of planets exists? I appreciate that two factors that need to be taken into account before producing a model of a "typical" stellar planetary system are the mass of the star and the fact that our data to date is biased, as far as I know, in favour of large, Jupiter scale planets. My apologies if the answer is: ask again in 10 years when we have more data and improved observational techniques and instrumentation. Answer: the answer is no: for now there is a high correlation between the properties of planets (size, distance to their star) and their probability to be detected, which totally bias the observed distribution.
{ "domain": "physics.stackexchange", "id": 26153, "tags": "experimental-physics, astronomy, planets, exoplanets" }
No bootstrap value on single-copy gene tree created by OrthoFinder
Question: I'm running analysis with OrthoFinder and it produces a single-copy gene tree. When I visualize the tree with iTOL, there's no bootstrap value on the branches or nodes. There's a published paper in BMC Genomics that also didn't show the bootstrap value using OrthoFinder. https://bmcgenomics.biomedcentral.com/articles/10.1186/s12864-019-6065-7#Tab1 Does anybody know why there's no bootstrap values present on the phylogeny? How can this be corrected? Thanks Answer: Please check the file `$PWD/SpeciesTree_unrooted.txt" ` You should find the bootstrap support* values per branch there. If not make sure is the latest version is installed from https://github.com/davidemms/OrthoFinder The papers are: genomebiology.biomedcentral.com/articles/10.1186/… and genomebiology.biomedcentral.com/articles/10.1186/… Genome Biology 16:157 ... It officially offers tree stats: "OrthoFinder also provides comprehensive statistics for comparative genomic analyses" The documentation is here The question was raised how to increase replicates by one, two or three logs. This is not really orthodox technique. The way the issue should be first addressed is the user performs replicates manually, e.g. 10 new runs, and then looks across the consistency of bootstrap values for each manual replicate. If all values of interest between manual replicates are >80% or <70% it really doesn't matter. However if a key branch ranges from 70 - 75% that is strictly unresolved and would generally be resolved using an alternative test. If the variation is >= 10% that would need addressing. Generally variation between replicates is very low =< 2% note, the original answer just contained the word 'support' and has now been more correctly described as "bootstrap support". Thanks to the OP for pointing this out in the comments below.
{ "domain": "bioinformatics.stackexchange", "id": 2060, "tags": "phylogenetics, phylogeny, orthofinder" }
What is the probability of detecting Eve's tampering, in BB84?
Question: Alice sends a 0 in computational basis I understand that theres a $\frac12$ probability that eve guesses the basis wrong, and can go with Hadamard. So it's $\frac12$ chance Eve will pick computational and $\frac12$ chance of Hadamard. Now if Eve measured wrong and went with Hadamard, and Bob computational, however Bob got it wrong and got a $|1\rangle$ instead of $|0\rangle$, which is a $\frac12$ probability, Theres a $\frac14$ probability Alice and bob will detect Eve's intrusion if they verify that bit. This is all clear to me, however. Tampering is where I get confused. Detecting Eve tampered with a qubit is $\frac14$, and depending on the qubits $n$, Eve will go undetected with the probability $\left(\frac34\right)^n$ The question is (keep in mind there is an intruder), say Alice sent $20$ qubits to Bob, and only $10$ qubits Bob chose the correct basis, the rest are discarded. Alice and Bob then compare the results between the two to detect Eve, is the probability of detecting Eve $1-\left(\frac34\right)^{10}$ or just $\left(\frac34\right)^{10}$? Answer: Firstly we have $$ \mathbb{P}[\text{Eve detected in round $i$}] = \mathbb{P}[\text{Eve chooses wrong basis and Bob chooses correct basis}]. $$ As we assume Alice, Bob and Eve choose their basis independently and uniformly at random we have $$ \mathbb{P}[\text{Eve detected in round $i$}] = \frac12 \times \frac12 = \frac14. $$ So we also have $\mathbb{P}[\text{Eve not detected in round $i$}] = 1-\mathbb{P}[\text{Eve detected in round $i$}]=\frac34$. Now suppose we run the protocol for $n$ rounds $$ \begin{aligned} \mathbb{P}[\text{Eve detected}] &= 1-\mathbb{P}[\text{Eve not detected}] \\ &=1- \mathbb{P}[\text{Eve not detected in round $1$},\dots,\text{Eve not detected in round $n$}] \\ &=1-\prod_{i=1}^n \mathbb{P}[\text{Eve not detected in round $i$}] \\ &= 1 - \left(\frac34\right)^n \end{aligned} $$ where on the second line we used the fact that the event "Eve not detected" is the same as the event "Eve is not detected in every round", on the third line we used the assumption that each round is performed independently to take the joint probability to a product and on the final line we inserted our probability that Eve is not detected on round $i$.
{ "domain": "quantumcomputing.stackexchange", "id": 2641, "tags": "quantum-state, quantum-algorithms, bb84" }
Migrating data from multiple spreadsheets to multiple text files
Question: This is like the reverse functionality of Text file to spreadsheet. One or multiple .xlsx files in the path of the script get opened and the content is split into multiple .txt files. For example, say you have two excel files in the folder: file1.xlsx file2.xlsx The output created: spreadsheet_to_text.py """ Reads in .xlsx files from path were the script is located. Then the data of each column is split into a .txt file """ import glob import openpyxl from openpyxl.utils import get_column_letter def get_text_filename(filename: str, column: int)->str: """ Creates a text filename based on .xlsx file filename and column """ return (filename.rstrip(".xlsx") + "_" + get_column_letter(column) + '.txt') def xlsx_to_txt(filename: str): """ Extract data from a .xlsx file in the script folder into multiple .txt files """ workbook = openpyxl.load_workbook(filename) sheet_names = workbook.sheetnames sheet = workbook[sheet_names[0]] for column in range(1, sheet.max_column + 1): if sheet.cell(row=1, column=column).value: text_filename = get_text_filename(filename, column) with open(text_filename, mode='w') as textfile: for row in range(1, sheet.max_row + 1): if sheet.cell(column=column, row=row).value: textfile.writelines( sheet.cell(column=column, row=row).value + '\n') def spreadsheet_into_text(): """main logic for split spreadsheet data into multiple text files""" for filename in glob.iglob("*.xlsx"): xlsx_to_txt(filename) if __name__ == "__main__": spreadsheet_into_text() I already incorporated some improvements from Text file to spreadsheet. I wonder how the code can get further improved. Answer: This looks quite clean in general. May I suggest a few minor improvements: I think you could just use workbook.active to get the sheet instead of doing the rstrip(".xlsx") which would also right-strip out .sslsx or sl.xs.ss and even grab a part of the actual filename: In [1]: "christmas.xlsx".rstrip(".xlsx") Out[1]: 'christma' use os module or the beautiful pathlib to properly extract a filename without an extension: In [1]: from pathlib import Path In [2]: Path("christmas.xlsx").resolve().stem Out[2]: 'christmas' calculate what you can before the loop instead of inside it. For instance, sheet.max_row is something you could just remember in a variable at the top of your function and re-use inside. It's not a lot of savings, but attribute access still has its cost in Python: max_row = sheet.max_row something similar is happening when you get the value of a cell twice, instead: cell_value = sheet.cell(column=column, row=row).value if cell_value: textfile.writelines(cell_value + '\n') it may be a good idea to keep the nestedness at a minimum ("Flat is better than nested.") and would rather check for a reverse condition and use continue to move to the next iteration: for column in range(1, sheet.max_column + 1): if not sheet.cell(row=1, column=column).value: continue text_filename = get_text_filename(filename, column) Some out-of-the-box ideas: feels like if you do it with pandas.read_excel() it may just become way more easier and beautiful
{ "domain": "codereview.stackexchange", "id": 32985, "tags": "python, python-3.x, excel" }
4 axis orientation only robot solving inverse kinematics
Question: I'm working on a 4 axis robot that only changes orientation (every axis is revolute and rotates around a common point). My goal is to be able to provide a look vector (x,y,z) and have the robots tool point in that direction (converting 4 axes into 3 axes). I'm relatively new to robotics and am learning about Jacobian IK but I want to make sure that I'm going down a good path or if anyone has suggestions for other methods of solving this robot. Here's an illustration of the robot: In the robots home positive, roll is redundant to train. The pan axis has limited rotation of +/- 15° so that the tool doesn't hit the tilt arms. Tilt also is constrained +/- 240° so that the tool doesn't hit the train arms. Train and Roll have slip rings so they can infinitely spin. With this, if I wanted to have the robot look directly left (1,0,0) I would spin the train axis 90°, tilt 90° and roll -90°. That's the easy use case, but becomes more challenging if I wanted to have it look at vector (1,1,1). In this case there's a lot of valid combinations of rotations to make it look in that direction and solving it with trig doesn't seem feasible and needs to be an iterative solution. I've been watching lots of videos on DH tables, homogeneous transforms and now Jacobians but I don't have a big math background so its a lot to take in. Also most examples are for arm like robots and not just orientation. I want to make sure that before I spend a lot more time looking into Jacobian methods that its a good path forward. There also seems to be a lot of options for Jacobian methods such as transpose, pseudoinverse, dampened least squares and I'm not sure which one to look more into. Alternatively, I'm not tied to a Jacobian method if anyone has any other suggestions on algorithms that would work well for this. I've used FABRIK before but that doesn't seem appropriate here as it seems more suited for solving chains. Answer: Based on your comment I rewrote the answer. I was under the impression that you want to control a 3D orientation; however, what you seem to aim for is a pointing/ray style target. This is actually a 2D target (the position on a 3D unit sphere) and means you have one more DoF in your null space. The solution, however, is quite similar in either case. I also added a more detailed derivation to - hopefully - make it clear where things come from. Hope this helps. We can express the orientation of the tool frame in the world frame by tracing all the rotations used in the kinematic chain: $$ ^\mathrm{world}\mathbf{R}_\mathrm{tool} = \mathbf{R}_z(\theta_\textrm{roll})\mathbf{R}_x(-90°)\mathbf{R}_z(90°)\\ \mathbf{R}_z(\theta_\textrm{pan})\mathbf{R}_x(90°)\mathbf{R}_z(-90°) \mathbf{R}_z(\theta_\textrm{tilt})\mathbf{R}_x(90°) \mathbf{R}_z(\theta_\textrm{train})$$ In the tool frame, we know the direction of the ray, which is a constant $\mathbf{v}=(0, 0, 1)=\mathbf{e}_\mathrm{z}$ and we can work out the direction of the ray in world coordinates by taking the inverse of the above chain of rotations. This gives us the general forward kinematics: $$FK(\theta_\textrm{train}, \theta_\textrm{tilt}, \theta_\textrm{pan}, \theta_\textrm{roll})= {^\mathrm{world}\mathbf{R}}_\mathrm{tool}^{-1}(\theta_\textrm{train}, \theta_\textrm{tilt}, \theta_\textrm{pan}, \theta_\textrm{roll})~\mathbf{v}$$ Getting that inverse rotation is simple, because - as you probably know - $\mathbf{R}^{-1}=\mathbf{R}^T$, $\mathbf{R}^{-1}(\alpha)=\mathbf{R}(-\alpha)$, and $(\mathbf{A}\mathbf{B})^T=\mathbf{B}^T\mathbf{A}^T$. This gives us a (lengthy) formula for the FK: $$FK(\theta) = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_x(-90°)\mathbf{R}_z(-\theta_\textrm{tilt})\\ \mathbf{R}_z(90°)\mathbf{R}_x(-90°)\mathbf{R}_z(-\theta_\textrm{pan}) \mathbf{R}_z(-90°)\mathbf{R}_x(90°)\mathbf{R}_z(-\theta_\textrm{roll})\mathbf{e}_\mathrm{z}$$ At this point, we could use CCD (cyclic coordinate descent) to solve the IK problem and find the joint angles by choosing the current configuration as the initial condition. We can compute the Jacobian using the product rule $\mathbb{d}(\mathbf{A}\mathbf{x})/\mathbb{d}\theta_i = \delta\mathbf{A}/\delta\theta_i~\mathbf{x} +\mathbf{A}~\mathbb{d}\mathbf{x}/\mathbb{d}\theta_i$ and the derivative of a rotation matrix $\delta\mathbf{R_z(\alpha)}/\delta\alpha = \mathbf{S}((0,0,1))\mathbf{R}_z(\alpha)$, where $\mathbf{S}$ is the skew-symmeric matrix in 3D that associates with the cross product. Since any $\theta_i$ only occurs once in the chain, the derivative is straightforward. We simply replace the respective $\mathbf{R}_z(-\theta_i)$ in the $FK$ equation with $\mathbf{S}(-\mathbf{e}_z)\mathbf{R}_z(-\theta_i)$ and obtain the respective column of the Jacobian. Here is one example column: $$\mathbf{J}_{pan}=\mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_x(-90°)\mathbf{R}_z(-\theta_\textrm{tilt})\\ \mathbf{R}_z(90°)\mathbf{R}_x(-90°)\mathbf{S}(-\mathbf{e}_z)\mathbf{R}_z(-\theta_\textrm{pan}) \mathbf{R}_z(-90°)\mathbf{R}_x(90°)\mathbf{R}_z(-\theta_\textrm{roll})\mathbf{v}$$ Notice that $\mathbf{J}_\mathrm{roll} = 0$ because $\mathbf{S}(-\mathbf{e}_z)\mathbf{R}_z(-\theta_\textrm{roll})\mathbf{v} = \mathbf{S}(-\mathbf{e}_z)\mathbf{v} = 0$. With this, we get access to all the variants of Jacobian-based IK, e.g., inverse jacobian. Solving the IK problem analytically would mean that we wish to find all combinations of $(\theta_\textrm{train}, \theta_\textrm{tilt}, \theta_\textrm{pan}, \theta_\textrm{roll})$ such that $\mathbf{v}_\mathrm{target} = FK(\theta_\textrm{train}, \theta_\textrm{tilt}, \theta_\textrm{pan}, \theta_\textrm{roll})$. We have 4 unknowns, so we will need 4 (non-redundant) equations. You might think that we can get 3 from the above $\mathbf{v}_\mathrm{target} = FK(\theta)$, but we can actually only get 2. Although we have formulated the problem in 3D, we are moving around on the unit sphere, which is a 2D subspace. This becomes particularly clear if we transform the entire problem into spherical coordinates and then look at the radius $r$ component: $$r_\textrm{FK} = |FK(\theta)| = 1 = |\mathbf{v}_\mathrm{target}| = r_\textrm{target}$$ The above is independent of $\theta$ and hence a redundant equation. Hence we will have to "add" two equations/constraints while solving the IK. The first equation shall be $\theta_\textrm{roll} = 0$, because $\mathbf{R}_z(-\theta_\textrm{roll})\mathbf{v} = \mathbf{v}$. We can also see this from the Jacobian of $\theta_\textrm{roll}$, which is always be 0. Hence, a solution of the IK will be a solution regardless of the angle we choose here. This reduces the number of unknowns down to 3: $$ \mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_x(-90°)\mathbf{R}_z(-\theta_\textrm{tilt}) \mathbf{R}_z(90°)\mathbf{R}_x(-90°)\mathbf{R}_z(-\theta_\textrm{pan}) (-\mathbf{e}_x) $$ We can then do some reordering (variable terms to the front, constant terms towards the back) via $\mathbf{R}_x(-90°)\mathbf{R}_z(\alpha) = \mathbf{R}_y(-\alpha)\mathbf{R}_x(-90°)$: $$ \mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_y(\theta_\textrm{tilt})\mathbf{R}_x(-90°) \mathbf{R}_z(90°)\mathbf{R}_y(\theta_\textrm{pan})\mathbf{R}_x(-90°) (-\mathbf{e}_x) $$ and $\mathbf{R}_z(90°)\mathbf{R}_y(\alpha) = \mathbf{R}_x(\alpha)\mathbf{R}_z(90°)$: $$ \mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_y(\theta_\textrm{tilt})\mathbf{R}_x(-90°) \mathbf{R}_x(\theta_\textrm{pan})\mathbf{R}_z(90°)\mathbf{R}_x(-90°) (-\mathbf{e}_x) $$ and finally $\mathbf{R}_x(-90°)\mathbf{R}_x(\alpha) = \mathbf{R}_x(\alpha)\mathbf{R}_x(-90°)$: $$ \mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_y(\theta_\textrm{tilt}) \mathbf{R}_x(\theta_\textrm{pan})\mathbf{R}_x(-90°)\mathbf{R}_z(90°)\mathbf{R}_x(-90°) (-\mathbf{e}_x) $$ We can then combine all the constant terms: $$ \mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_y(\theta_\textrm{tilt}) \mathbf{R}_x(\theta_\textrm{pan})\mathbf{e}_z $$ Unsurprisingly so, we can identify the above as the unit vector along the tool's z-axis being rotated by a xyz intrinsic Euler rotation (from the tool frame into the world frame). At this point we can make a choice for the second equation we need to add and pick $\theta_\mathrm{pan}=0$. This would reduce the problem to $$\mathbf{v}_\mathrm{target} = \mathbf{R}_z(-\theta_\textrm{train}) \mathbf{R}_x(\theta_\textrm{tilt})\mathbf{e}_z$$ which is exactly the two angles measured by your standardspherical coordinate system (mind a minus): $$\theta_\mathrm{train} = -\arccos(v_{\mathrm{target},3})$$ $$\theta_\mathrm{tilt} =\operatorname{atan2}(v_{\mathrm{target},2}/v_{\mathrm{target},1})$$ This gives us one of the various IK solutions: $$ \theta_\mathrm{train} = -\arccos(v_{\mathrm{target},3})\\ \theta_\mathrm{tilt} =\operatorname{atan2}(v_{\mathrm{target},2}/v_{\mathrm{target},1})\\ \theta_\mathrm{pan}=0\\ \theta_\mathrm{roll}=0\\ $$ The above works if you just want to steer to a given position. If you want to do some kind of tracking or use cartesian control, however, this will fail once $`\theta_\mathrm{tilt}$ approaches $\pm 180°$. There, the robot/gimbal will do a flip/spin to the other side and lose track or deviate significantly from the desired trajectory. You can avoid that by involving $\theta_\mathrm{pan}$. Another, easier, way would be to make your tool face along any of roll's axes that isn't the z-axis. That way you get two joints without constraints and will never run into this problem.
{ "domain": "robotics.stackexchange", "id": 2436, "tags": "inverse-kinematics, jacobian" }
How are programs split up into pages in Memory Paging?
Question: I am a bit confused about how the logical addresses are generated in a paging memory architecture and where and when a program is split up into pages. I understand how logical addresses are translated to physical addresses and everything that happens after that. I just don't understand how a program is split into distinct pages and where and how this happens. For example, if we consider a non-paging architecture which uses contiguous memory and execution-time binding, a CPU instruction like JUMP 8, where 8 is a logical address, I understand how an MMU with a base register can dynamically relocate a program anywhere in main memory by changing the value stored in base register, while the object code stored in memory is still using the logical address of 8. However, how is this JUMP 8 instruction handled in a paging architecture, as in when will all these simple logical addresses like 8 be converted into logical addresses suitable for paging (with a page number and offset value), does the compiler split the program into pages? Also, how is the program stored in memory, are the simple logical addresses stored like in execution-time binding, or is the program in memory stored with the paging logical addresses? Answer: The program is not really split up into pages. The program is unaware of where it lands in physical memory. This is all the essence of paging. For example, if you take Linux on x86 CPUs and the C++ language, you will have the compiler generating machine code which will be linked into a final executable which has a .ELF extension. ELF files support virtual addresses. ELF files specify the virtual addresses at which the code is going to land. The linker or compiler is going to write the starting virtual address at which the code is going to land. The default virtual address is 0x400000 with ld and g++. So basically, the ELF executable specifies where the program lands in virtual memory. Since the default virtual address is always 0x400000, then a lot of programs will have that starting virtual address. The kernel thus creates page tables for each process (each executable that you start). These processes will land at different places in memory even if they all have the same virtual address. This is due to the fact that they have different page tables. In fact Linux holds a page struct for every physical page in the system. This takes up quite some space and there have been discussion to change this pattern. I don't know if it is yet done. The page struct allows the kernel to map all physical pages to know what every page is used for. So when you start an executable/process the kernel determines what physical pages are available and set up the page tables for that process so that virtual address 0x400000 lands there once translated by the MMU. The JMP 8 instruction will be translated by the MMU before being placed on the address bus. So the 8 is a virtual address. This virtual address is determined by the compiler and the linker. There are 2 different kinds of JMPs. Relative JMPs and absolute JMPs (far JMPs). Relative JMPs are calculated as an offset from the current position in the code. Far JMPs in the meantime are calculated as absolute address. They contain a virtual address where the JMP should go. They can JMP anywhere in RAM. For example, label: jmp label is a relative JMP, while jmp 0x8000 is an absolute JMP. These jumps are calculated by the compiler and linker. The compiler places the functions you call from main at different positions in the code that it places in the relative JMPs. Far JMPs are mostly used in operating-system development. The linker plays the role of linking several files. So you have a symbol section in the ELF file. This symbol section contains entries which associate each symbol with an address. I'm not totally aware since I never wrote an ELF interpreter. What I can tell is that the address is the address of the beginning of something like a variable or mostly functions. What happens is that the linker takes the symbol and checks it against other object files you included in the linking command. If it finds the symbol in another file, it places the address of the code in the relative JMP to tell the code where to JMP to get to that function. That is why it is called a linker, because it resolves links. This is why you have to include header files in C++. You tell the linker where to find these other symbols (functions, variables, classes).
{ "domain": "cs.stackexchange", "id": 17525, "tags": "computer-architecture, memory-management, memory-hardware, virtual-memory, memory-allocation" }
Wick rotation of the Schrödinger equation
Question: Studying the following paper: https://www.nature.com/articles/s41534-019-0187-2.pdf Trying to figure out how $ E_T$ shows up from (1) and (2). Any suggestion or guidance would be appreciated. We focus on many-body systems that are described by Hamiltonians $H=\sum_{i} \lambda_{j} h_{i}$, with real coefficients, $\lambda_{i}$, and observables, $h_{i}$, that are tensor products of Pauli matrices. We assume that the number of terms in this Hamiltonian scales polynomially with the system size, which is true for many physical systems, such as molecules or the Fermi-Hubbard model. Given an initial state $|\psi\rangle$, the normalised imaginary time evolution is defined by $$ |\psi(\tau)\rangle=A(\tau) e^{-H \tau}|\psi(0)\rangle\tag1 $$ where $A(\tau)=1 / \sqrt{\left\langle\psi(0)\left|e^{-2 H \tau}\right| \psi(0)\right\rangle}$ is a normalisation factor. In the instance that the initial state is a maximally mixed state, the state at time $\tau$ is a thermal or Gibbs state $\rho_{T=1 / t}=e^{-H \tau} / \operatorname{Tr}\left[e^{-H t}\right]$, with temperature $T=1 / \tau$. When the initial state has a non-zero overlap with the ground state, the state at $\tau \rightarrow \infty$ is the ground state of $H$. Equivalently, the Wick rotated Schrödinger equation is, $$\frac{\partial|\psi(\tau)\rangle}{\partial \tau}=-\left(H-E_{\tau}\right)|\psi(\tau)\rangle,\tag2$$ where the term $E_{\tau}=\langle\psi(\tau)|H| \psi(\tau)\rangle$ results from enforcing normalisation. Even if $|\psi(\tau)\rangle$ can be represented by a quantum computer, the non-unitary imaginary time evolution cannot be naively mapped to a quantum circuit. Answer: As hinted in the highlighted text, $E_T$ arises from the normalization factor $A(\tau)$. Specifically, differentiating $(1)$, we get two terms $$ \begin{align} \frac{\partial|\psi(\tau)\rangle}{\partial\tau} &= \frac{\partial}{\partial\tau}\left(A(\tau)e^{-H\tau}|\psi(0)\rangle\right) \\ &= \frac{\partial A(\tau)}{\partial\tau}e^{-H\tau}|\psi(0)\rangle + A(\tau)\frac{\partial e^{-H\tau}}{\partial\tau}|\psi(0)\rangle.\tag3 \end{align} $$ Computing the derivative in the first term, we obtain $$ \begin{align} \frac{\partial A(\tau)}{\partial\tau} &= \frac{\partial}{\partial\tau}\left(\frac{1}{\sqrt{\langle\psi(0)|e^{-2H\tau}|\psi(0)\rangle}}\right) \\ &= -\frac{1}{2\sqrt{\langle\psi(0)|e^{-2H\tau}|\psi(0)\rangle^3}} \langle\psi(0)|\frac{\partial}{\partial\tau}e^{-2H\tau}|\psi(0)\rangle \\ &= A(\tau)^3 \langle\psi(0)|e^{-H\tau}He^{-H\tau}|\psi(0)\rangle \\ &= A(\tau) \langle\psi(0)|e^{-H\tau}A(\tau)HA(\tau)e^{-H\tau}|\psi(0)\rangle \\ &= A(\tau) \langle\psi(\tau)|H|\psi(\tau)\rangle \\ &= A(\tau) E_T\tag4 \\ \end{align} $$ where we took advantage of the facts that $A(\tau)\in\mathbb{R}$, that $H$ is Hermitian, and that $e^{-H\tau}$ commutes with $H$. Finally, substituting $(4)$ into $(3)$, we find $$ \begin{align} \frac{\partial|\psi(\tau)\rangle}{\partial\tau} &= A(\tau)E_T e^{-H\tau}|\psi(0)\rangle - A(\tau)He^{-H\tau}|\psi(0)\rangle \\ &= (E_T-H)|\psi(\tau)\rangle \end{align} $$ as advertised.
{ "domain": "quantumcomputing.stackexchange", "id": 3111, "tags": "quantum-algorithms, mathematics, hamiltonian-simulation" }
Question on the invariance of Hooke's law for isotropic materials
Question: Hooke's law for an elastic isotropic 2-d material is a rank 4 tensor with 16 elements $$ \begin{pmatrix} a_{11} & a_{12} & 0 & 0 \\ a_{12} & a_{11} & 0 & 0 \\ 0 & 0 & a_{33} & 0 \\ 0 & 0 & 0 & a_{33} \end{pmatrix} $$ Since the material is isotropic the tensor is the same for all orthogonal frames, hence it is invariant for for all orthonormal coordinate transformations. But, looking at an orthonormal coordinate transformation for the top left $2\times2$ submatrix, $$ \begin{pmatrix} \cos(1) & \sin(1) \\ -\sin(1) & \cos(1)\end{pmatrix} \begin{pmatrix} .9 & .1 \\ .1 & .9\end{pmatrix} \begin{pmatrix} \cos(1) & -\sin(1) \\ \sin(1) & \cos(1)\end{pmatrix} $$ doesn't equal $\begin{pmatrix} .9 & .1 \\ .1 & .9\end{pmatrix}$. So, where is the error in the above? Answer: Looks like you've confused a fourth rank tensor with a $4\times4$ matrix. Often a condensed notation (Voigt notation) is used for these tensor elements: each index of $a$ really stands for two indices in the true tensor. You seem to have adopted this. If you want to express the transformation properties of the tensor, you need to express it in the full notation, where each element has four indices. Then the transformation will involve a summation over indices in which the typical term has four contributions from the transformation matrix, like this $$ a_{IJKL} = M_{Ii}M_{Jj}M_{Kk}M_{Ll} \, a_{ijkl} $$ where the $M$ terms describe the coordinate rotation (this corresponds to your $2\times2$ rotation matrix) and we sum over the lowercase indices (Einstein convention). You should be able to express all the $a_{ijkl}$ in terms of two Lamé constants $\lambda$ and $\mu$ (see here for example), and it will take the form explained in the answer of @JEB ; then you can easily verify that it is isotropic, according to the transformation rule given here.
{ "domain": "physics.stackexchange", "id": 53864, "tags": "tensor-calculus, stress-strain" }
Bug in stim HERALDED_PAULI_CHANNEL_1?
Question: Tried this simple example where initializing two qubits in $|0\rangle$ state, performing biased bit flip erasure on qubit 1 using HERALDED_PAULI_CHANNEL_1 while measuring qubit 0: import stim import numpy as np circuit = stim.Circuit() circuit.append_operation("R", (0, 1)) p = 0.2 circuit.append_operation("HERALDED_PAULI_CHANNEL_1", 1, (p, p, 0, 0)) circuit.append_operation("M",0) N = 1000 result = circuit.compile_sampler().sample(shots = N) one_num = np.sum([int(True == j[-1]) for j in result]) print('%s/%s' %(one_num, N)) display(circuit.diagram("timeline-svg")) I get around 200/1000 measurement error on the qubit 0 as if the error is on qubit 0. What is wrong here? Thank you. Answer: Update: This is fixed in stim~=1.12.1 and in stim~=1.13.dev1701377008. The only stable version affected was 1.12.0, since HERALDED_PAULI_CHANNEL_1 was released in 1.12. This is a bug. Good catch. I've written a fix and am merging it: https://github.com/quantumlib/Stim/pull/676. Also added some tests that verify it's fixed. I also checked HERALDED_ERASE, which historically was added at the same time but didn't have the same bug. Within two hours you should be able to pip install stim~=1.13.dev and get a version with the bug fixed. I'll also backport the fix to 1.12 and release a version 1.12.1. That should be done before the end of the day.
{ "domain": "quantumcomputing.stackexchange", "id": 5319, "tags": "stim" }
NASDAQ Trade Data
Question: I am trying to find stock data to practice with, is there a good resource for this? I found this but it only has the current year. I already have a way of parsing the protocol, but would like to have some more data to compare with. It doesn't have to be in the same format, as long as it has price, trades, and date statistics. Answer: You can pull stock data very easyly in python and R (probably other languages as well) with the following packages: In python with ystockquote This is also a really nice tutorial in iPython which shows you how to pull the stock data and play with it In R with quantmod HTH.
{ "domain": "datascience.stackexchange", "id": 6968, "tags": "data-mining, dataset" }
How is equilibrium achieved in osmosis?
Question: According to BRS Physiology book: excessive NaCl intake will lead to an increase in the osmolarity of the Extracellular Fluid (ECF) compartment, and thus will lead to water shift from the Intracellular Fluid (ICF) compartment to the ECF so the ICF osmolarity increases until the osmolarities equal each other. But if water shifts from the ICF to the ECF, wouldn't the osmolarity of the ECF decrease also as a result of the decreased concentration of the solutes, and this cycle continues? Answer: If there is a difference in osmolarity and therefore in the osmotic pressure, water flows from solution with lower osmotic pressure to the higher one, decreasing this difference and therefore the flow itself as well. The kinetic of this process follows the first order kinetics. The flow rate is proportional to the osmotic pressure difference. Therefore, the water flow exponentially decreases with time, as the osmotic pressure difference decreases, reaching the equilibrium theoretically ( mathematically ) in infinite time. $$ \frac {\mathrm{d}\Delta p}{\mathrm{d}t} = - k \cdot \Delta p$$ $$ \Delta p = \Delta p_{t=0} \cdot \exp {(-k \cdot t) }$$ The kinetic constant $k$ depends on the membrane permeability, water diffusion coefficient and geometry of the scenario. Therefre, there is no cyclic oscillation of osmotic pressures like: 1 - 9 -> 9 - 1 -> 1 - 9 but there is an exponential convergence like 1 - 9 -> 3 - 7 -> 4 - 6 -> 5 - 5
{ "domain": "chemistry.stackexchange", "id": 14589, "tags": "chemical-biology, osmosis" }
Is modular square roots modulo primes in $NC$?
Question: Assume modulus is prime. Is modular square roots then in $NC$? If not then, are there special primes or prime powers or numbers related to these (such as $2^k\pm i$ where $i\in\{-1,0,+1\}$) where it is in $NC$? Answer: Square roots modulo $2^n$ can be computed in (uniform) $\mathrm{TC}^0$. More generally, just like in On parallel complexity of modular inverse, given $X$ and $M$ in binary and $b$ in unary such that $M$ is $b$-smooth, you can compute in $\mathrm{TC}^0$ a square root $Y^2\equiv X\pmod M$ if it exists. The general set-up is the same as in the linked answer for inverses (factorize $M$, compute square roots modulo each prime power factor, combine them using the Chinese remainder theorem). The only difference is in the computation of $Y=\sqrt X$ modulo $p^n$ when a prime $p$ and $n$ are given in unary, which is done as follows: If $X\equiv0\pmod{p^n}$, take $Y=0$. Otherwise, write $X=p^kX'$ with $k<n$ and $X'\not\equiv0\pmod p$. If $k$ is odd, no square root exists. Otherwise, we can take $Y=p^{k/2}Y'$, where $Y'^2\equiv X'\pmod{p^{n-k}}$. Hence we may assume without loss of generality that $X\not\equiv0\pmod p$. For $p$ odd: if $X$ has no square root modulo $p$, it has no modulo $p^n$. Otherwise, find $y$ such that $y^2\equiv X\pmod p$ by brute-force selection. Then $y^{-2}X\equiv1\pmod p$, thus using $y^{-1},4^{-1}\bmod{p^n}$ (that we can compute as in the linked answer), we can compute $Z\equiv0\pmod p$ such that $X\equiv y^2(1-4Z)\pmod{p^n}$. For $p=2$: the cases $n=1,2$ are left to the reader. If $n\ge3$, there exists no square root unless $X\equiv1\pmod8$; putting $y=1$ and $Z=(1-X)/4$, we again have $X\equiv y^2(1-4Z)\pmod{p^n}$ and $Z\equiv0\pmod p$. It remains to compute $\sqrt{1-4Z}$ modulo $p^n$ for $Z\equiv0\pmod p$: we do this by evaluating the sum $$1-2\sum_{k=0}^{n-2}C_kZ^{k+1},$$ where $C_k=\frac{(2k)!}{k!(k+1)!}$ are the Catalan numbers. This can be done in $\mathrm{TC}^0$ using iterated sums and products. The reason the last step works is that for $Z\equiv0\pmod p$, the infinite series $$1-2\sum_{k=0}^\infty C_kZ^{k+1}$$ converges in the ring $\mathbb Z_p$ of $p$-adic integers, and since the square of the corresponding formal power series in $\mathbb Z[[T]]\subseteq\mathbb Z_p[[T]]$ is $1-4T$, it computes a square root of $1-4Z$ in $\mathbb Z_p$. Reducing this series modulo $p^n$, all the $Z^{k+1}$ terms with $k\ge n-1$ vanish, and the remaining finite sum computes a square root modulo $p^n$.
{ "domain": "cstheory.stackexchange", "id": 5717, "tags": "cc.complexity-theory, complexity-classes, dc.parallel-comp, nt.number-theory, comp-number-theory" }
Top angular speed of electric motor
Question: I recently came across a question asking the following: If a motor is switched on, it quickly reaches a top speed. Why does it not just go faster and faster and faster? I thought it might be related to the fact that the electrical power is constant, so I tried approaching with $P=\tau \cdot \omega$. However I still do not have any clue to reaching the conclusion. Is it somehow related to the energy loss (due to friction)? Like the terminal speed of a parachute or something? But I was thinking that friction should be constant ($f=\mu \cdot N$) while air drag is related to the speed, so this may not be the answer. Thank you. Answer: Surpringingly the top speed is not necessarily anything to do with friction, though friction will of course have some effect. A motor acts as a generator, i.e. if you turn a motor it will generate a potential difference just like a generator, and this potential difference (usually called the back EMF) is proportional to the motor speed. So if you connect a X volt battery to an unloaded motor the armature will accelerate until the back EMF rises to the same value as the applied voltage. At this point the motor will settle to a steady angular velocity. The equations describing this are given in the Wikipedia article on the DC motor, though this is far from the best written article I've seen. Basically the back EMF, $E_b$, is given by: $$ E_b = \omega \Phi k_b $$ where $\phi$ and $k_b$ are dependant on the motor design and for the sake of this discussion can be treated as constants. So ignoring friction, the internal resistance of the motor and with no load on the motor the top speed will be when $E_b$ is the same as the applied voltage $V$ so: $$ \omega = \frac{V}{\Phi k_b} $$ So it predicts angular velocity is proportional to applied voltage. The effect of internal resistance, $R_i$, is easily included since it just creates a potential drop of $IR_i$ and the equation changes to: $$ \omega = \frac{V - IR_i}{\Phi k_b} $$
{ "domain": "physics.stackexchange", "id": 12008, "tags": "homework-and-exercises, electromagnetism, rotational-dynamics" }
How to write recurrence relation for backtracking problem?
Question: I am not able to understand how to write a recurrence relation for n queen problem. I searched on web and everywhere it was given directly without explaining how can we arrive to that. Recurrence relation is for n*n board $T(n)=n*T(n-1)+O(n^2)$ but think it should be $T(n)=T(n-1)+O(n^2)$ as if we put the queen anywhere in first row, we are left with $(n-1)*(n-1)$ board and it is sub-problem for T(n-1). But how n gets multiplied is not understandable. Can anyone help in explaining such recurrence relation. Answer: Recurrence relation is for n*n board $T(n)=n*T(n-1)+O(n^2)$ but think it should be $T(n)=T(n-1)+O(n^2)$ as if we put the queen anywhere in first row, we are left with $(n-1)*(n-1)$ board and it is sub-problem for T(n-1). But how n gets multiplied is not understandable. How many cells are there in the first row? $n$. That is where the factor $n$ come from. We put the Queen in the first cell of the first row. Removing the first row and first column, we then check the remaining $(n-1)*(n-1)$ board. We put the Queen in the second cell of the first row. Removing the first row and second column, we then check the remaining $(n-1)*(n-1)$ board. $\vdots$ We put the Queen in the last cell of the first row. Removing the first row and last column, we then check the remaining $(n-1)*(n-1)$ board.
{ "domain": "cs.stackexchange", "id": 13109, "tags": "time-complexity, recurrence-relation, divide-and-conquer" }
How to derive Ehrenfest's theorem?
Question: $$\frac{d\langle p\rangle}{dt}=-i\hbar \int_{-\infty}^{\infty}\frac{d\psi^*}{dt} \frac{d\psi}{dx}+\psi^*\frac{d}{dt}\Bigr(\frac{d\psi}{dx}\Bigr)$$ I didn't know the coding of partial derivative which are inside the integral There is a question about this on site, but I don't have much experience with bra -ket notation. Ehrenfest's theorem derivation. The first integrand makes sense but I'm completely at odds with the second one Answer: $$\langle p \rangle = -i\hbar\int\psi^*\frac{d \psi}{dx}dx$$ $$\implies\frac{d\langle p \rangle}{dt} = -i\hbar\frac{d}{dt}\int\psi^*\frac{d\psi}{dx}dx$$ $$\implies\frac{d\langle p \rangle}{dt} = -i\hbar\int\frac{d}{dt}\left(\psi^*\frac{d\psi}{dx}\right)dx \ \ \ \ \text{By Leibniz's Rule}$$ $$\implies\frac{d\langle p \rangle}{dt} = -i\hbar\int \left(\frac{d\psi^*}{dt}\frac{d\psi}{dx} + \psi^*\frac{d}{dt}\frac{d\psi}{dx}\right)dx \ \ \ \ \text{By the Product Rule}$$
{ "domain": "physics.stackexchange", "id": 69129, "tags": "quantum-mechanics, homework-and-exercises, operators, wavefunction, observables" }
Efficient Algorithm for determining who wins a game of Chess
Question: I was reading Jeff E's lecture notes on Algorithms when I came upon the following question: Describe and analyze an efficient algorithm that determines, given a legal arrangement of standard pieces on a standard chess board, which player will win at chess from the given starting position if both players play perfectly. [Hint: There is a trivial one-line solution!] My only thought is to form a tree of possibilities and go down every tree to see where it ends. But this is neither one line or efficient. Any help is appreciated(I prefer hints to full solutions, and I will accept a hint as an answer if it leads me to the answer). Answer: When talking about standard chess with an $8\times 8$ board, there is no asymptotics, so you can solve the problem in $O(1)$ time. Your idea works fine, since for each position the size of the tree is bounded by some constant independent of the input (the tree size is bounded by the number of possible positions). You can now ask whether this solution is feasible or has any practical implications? The answer is obviously no, but when analyzing the asymptotic complexity of the algorithm, this doesn't matter.
{ "domain": "cs.stackexchange", "id": 9173, "tags": "algorithms, graphs" }
App initialisation and simple game loop
Question: Summary I come from a Java background but I am trying to make a game in C++. This is my attempt at a state management system, which should allow me to easily switch between "states" (menu, game, scoreboard, etc.). The idea is that: When the program starts, I create an Application. The Application contains the game loop, which runs until the program exits. Each frame, the application updates and renders the current state. State is an abstract class, and Rival is a concrete subclass. Feedback I would really love any feedback. Specifically, the areas I am most concerned about are: Inheritance: I have not really used this before in C++. My understanding is that by using a unique_ptr my state gets stored on the heap, and this avoids the problem of object slicing. My State methods are all pure virtual, and overridden by the subclass. Am I missing anything? Ownership: The Application owns the current State; Rival owns the current Scenario. My understanding is that when the Application exits (or changes to a new state), the current state will be destroyed / freed. When Rival gets freed, the current Scenario will subsequently be freed. Have I got that right? Heap vs Stack: I understand that the stack is faster to access, but it is quite small and not particularly suitable for long-lived objects (they are freed when they go out of scope), polymorphic objects or variable-size objects. For this reason the State and Scenario live on the heap, but everything else lives on the stack. Does this sound ok? NOTE: I am not too worried about the technical aspects of the game loop itself at this point (fixed or variable time step, sleep duration, etc.) - I just want to make sure the code is clean, free from bugs / memory leaks, and follows best practices where possible. I would be grateful if you could try to include an explanation along with any suggestions, so that I can learn WHY and not just WHAT. Code I have tried to omit any details which are not relevant to this particular mechanism, but the full code can be found here. Main.cpp #include "pch.h" #include <iostream> #include <stdexcept> #include "Application.h" #include "Rival.h" #include "Scenario.h" #include "ScenarioBuilder.h" #include "ScenarioReader.h" #include "Window.h" /** * Entry point for the application. */ int main() { try { // Create our Window Rival::Window window(800, 600, "Rival Realms"); window.use(); // Create our Application Rival::Application app(window); // Load some scenario Rival::ScenarioReader reader(Rival::Resources::mapsDir + "example.sco"); Rival::ScenarioBuilder scenarioBuilder(reader.readScenario()); std::unique_ptr<Rival::Scenario> scenario = scenarioBuilder.build(); // Create our initial state std::unique_ptr<Rival::State> initialState = std::make_unique<Rival::Rival>(app, std::move(scenario)); // Run the game! app.start(std::move(initialState)); } catch (const std::runtime_error& e) { std::cerr << "Unhandled error during initialization or gameplay\n"; std::cerr << e.what() << "\n"; return 1; } return 0; } Application.h #ifndef APPLICATION_H #define APPLICATION_H #include <memory> #include "Resources.h" #include "State.h" #include "Window.h" namespace Rival { class Application { public: bool vsyncEnabled; Application(Window& window); /** * Runs the Application until the user exits. */ void start(std::unique_ptr<State> state); /** * Exits the Application cleanly. */ void exit(); Window& getWindow(); Resources& getResources(); private: Window& window; Resources res; std::unique_ptr<State> state; }; } // namespace Rival #endif // APPLICATION_H Application.cpp #include "pch.h" #include "Application.h" #include <SDL.h> namespace Rival { bool vsyncEnabled = true; Application::Application(Window& window) : window(window) { // Try to enable vsync if (SDL_GL_SetSwapInterval(1) < 0) { printf("Unable to enable vsync! SDL Error: %s\n", SDL_GetError()); vsyncEnabled = false; } } void Application::start(std::unique_ptr<State> initialState) { // Event handler SDL_Event e; state = std::move(initialState); bool exiting = false; Uint32 nextUpdateDue = SDL_GetTicks(); // Game loop while (!exiting) { Uint32 frameStartTime = SDL_GetTicks(); // Is the next update due? if (vsyncEnabled || nextUpdateDue <= frameStartTime) { // Handle events on the queue while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { exiting = true; } else if (e.type == SDL_KEYDOWN) { state->keyDown(e.key.keysym.sym); } else if (e.type == SDL_MOUSEWHEEL) { state->mouseWheelMoved(e.wheel); } } // Update the game logic, as many times as necessary to keep it // in-sync with the refresh rate. // // For example: // - For a 30Hz monitor, this will run twice per render. // - For a 60Hz monitor, this will run once per render. // - For a 120Hz monitor, this will run every other render. // // If vsync is disabled, this should run once per render. while (nextUpdateDue <= frameStartTime) { state->update(); nextUpdateDue += TimerUtils::timeStepMs; } // Render the game, once per iteration. // With vsync enabled, this matches the screen's refresh rate. // Otherwise, this matches our target FPS. state->render(); // Update the window with our newly-rendered game. // If vsync is enabled, this will block execution until the // next swap interval. window.swapBuffers(); } else { // Next update is not yet due. // Sleep for the shortest possible time, so as not to risk // overshooting! SDL_Delay(1); } } // Free resources and exit SDL exit(); } void Application::exit() { SDL_Quit(); } Window& Application::getWindow() { return window; } Resources& Application::getResources() { return res; } } // namespace Rival State.h #ifndef STATE_H #define STATE_H #include <SDL.h> namespace Rival { // Forward declaration to avoid circular reference class Application; class State { public: /** * Handles keyDown events. */ virtual void keyDown(const SDL_Keycode keyCode) = 0; /** * Handles mouse wheel events. */ virtual void mouseWheelMoved(const SDL_MouseWheelEvent evt) = 0; /** * Updates the logic. * * It is assumed that a fixed amount of time has elapsed between calls * to this method, equal to TimerUtils::timeStepMs. */ virtual void update() = 0; /** * Renders the current frame. */ virtual void render() = 0; }; } // namespace Rival #endif // STATE_H Rival.h #ifndef RIVAL_H #define RIVAL_H #include <SDL.h> #include <memory> #include "Application.h" #include "Scenario.h" #include "State.h" #include "Window.h" namespace Rival { class Rival : public State { public: Rival(Application& app, std::unique_ptr<Scenario> scenario); // Inherited from State void keyDown(const SDL_Keycode keyCode) override; void mouseWheelMoved(const SDL_MouseWheelEvent evt) override; void render() override; void update() override; private: Application& app; Window& window; Resources& res; std::unique_ptr<Scenario> scenario; }; } // namespace Rival #endif // RIVAL_H Rival.cpp #include "pch.h" #include "Rival.h" namespace Rival { Rival::Rival(Application& app, std::unique_ptr<Scenario> scenarioToMove) : app(app), window(app.getWindow()), res(app.getResources()), scenario(std::move(scenarioToMove)) {} void Rival::update() { // ... } void Rival::render() { // ... } void Rival::keyDown(const SDL_Keycode keyCode) { // ... } void Rival::mouseWheelMoved(const SDL_MouseWheelEvent evt) { // ... } } // namespace Rival ``` Answer: Answers to your questions Inheritance: I have not really used this before in C++. My understanding is that by using a unique_ptr my state gets stored on the heap, and this avoids the problem of object slicing. My State methods are all pure virtual, and overridden by the subclass. Am I missing anything? Object slicing happens when you copy a derived class variable into a base class variable. Using any kind of pointer prevents a copy from being made. However, you probably want to use a pointer (or reference) anyway, even if there was no object slicing. Ownership: The Application owns the current State; Rival owns the current Scenario. My understanding is that when the Application exits (or changes to a new state), the current state will be destroyed / freed. When Rival gets freed, the current Scenario will subsequently be freed. Have I got that right? Yes, as soon as a class is destroyed, all its member variables are destroyed as well. If a member variable is a std::unique_ptr, this will ensure delete is called on the pointer. Heap vs Stack: I understand that the stack is faster to access, but it is quite small and not particularly suitable for long-lived objects (they are freed when they go out of scope), polymorphic objects or variable-size objects. For this reason the State and Scenario live on the heap, but everything else lives on the stack. Does this sound ok? The main thread of an application typically has megabytes of stack space on a desktop computer, so I wouldn't worry about it that much. For regular variables, even if their type is that of a large class, it will mostly be fine, but if you start allocating arrays on the stack you have to be careful. The lifetime depends on the lifetime of the scope, but that can be very long; for example the variables allocated on the stack frame of main() will basically live for as long as the program lives. As for faster access: the only issue with variables on the heap is that they are access via a pointer, so at some point the pointer has to be dereferenced. This may or may not be an issue for performance. I wouldn't worry about it in the early stages of your program, it is something you can worry about later if you are doing performance tuning, and only then if a profiler tells you that this is actually a problem. It should be fine to declare a State and Scenario variable on the stack of main(): // Load some scenario Rival::ScenarioReader reader(Rival::Resources::mapsDir + "example.sco"); Rival::ScenarioBuilder scenarioBuilder(reader.readScenario()); Rival::Scenario scenario = scenarioBuilder.build(); // Create our initial state Rival::Rival initialState(scenario); // Run the game! app.start(initialState); This requires the constructor of Rival::Rival and Application::start() to take a plain reference as an argument. This means those objects also no longer own the scenario and state. But it should be fine, those variables will now be destroyed when main() exits. Don't catch exceptions if you can't do anything about them In main(), you catch any std::runtime_error(), but the only thing you do is to print an error and exit with a non-zero exit code. This is exactly what will already happen if you don't catch exceptions there, so it is a pointless excercise. Perhaps Java taught you that you have to catch 'm all, but that's not the case in C++. Just let fatal exceptions you can't deal with fall through. Aside from that, if you do want to have a generic exception catcher, then you should catch std::exception instead, it's the base class of std::runtime_error and will also catch other types of exceptions. Not everything needs to be a class Again, I think this comes from your background in Java, where all functions must live inside a class. This is not the case in C++. In particular, class Application is just something that you construct once, call start() on, and then it exits and you're done. For such a one-shot operation, you can just use a single function. Since Application primarily implements the main loop of your application, I would just create a single function called main_loop(): void main_loop(Window& window, State& initialState) { bool vsyncEnabled = SDL_GL_SetSwapInterval(1) == 0; if (!vsyncEnabled) { printf("Unable to enable vsync! SDL Error: %s\n", SDL_GetError()); } SDL_Event e; bool exiting = false; Uint32 nextUpdateDue = SDL_GetTicks(); // Game loop while (!exiting) { ... } } And then in main(): Rival::Window window(800, 600, "Rival Realms"); ... Rival::State initialState(scenario); // Run the game! main_loop(window, initialState); Do you need inheritance at all? Is there a reason why you have made the pure virtual base classes Rival::State? If you only have one derived class Rival::Rival, it really does not do anything, except you have to now keep the members of the base class and the derived class in sync, which is work for you, and now access to the state will have to go via a vtable, which might impact performance. Even if you think you might need it in the future, the YAGNI principle applies here: if you don't need it now, don't write it. Don't call SDL_Quit() too early In your original code, after exitting the main loop, you call Application::exit(), which in turn calls SDL_Quit(). However, as far as I can tell, nothing in class Application ever initialized SDL, so it should also not deinitialize it. In particular, the destructor of the variable window in main() will be called afterwards, so that might still rely on SDL being initialized properly. Consider moving event handling into its own function In the main loop, you have a switch() statement handling all possible SDL events. Consider moving this part into its own function, so that the main loop looks as simple as possible: while (!exiting) { handle_events(); // or maybe state.handle_events()? state.update(); state.render(); window.swapBuffers(); } This will keep the main loop short, and give you a clear high-level overview of what you are doing for each frame you render. Avoid busy-waiting and arbitrary delays If you want to wait for some time to pass or an event to happen, never implement a busy wait, nor a loop that calls SDL_Delay(1). That is just going to waste CPU cycles, and while the SDL_Delay(1) statement will certainly use less cycles, waiting for just a millisecond will likely prevent the processor from going into a low power state while you are waiting for the next update. This means it will have a higher temperature, which could cause thermal throttling to kick, and for users on a battery-operated device, they will drain their batteries faster. If you know that nextUpdateDue > frameStartTime, just call SDL_Delay(nextUpdateDue - frameStartTime).
{ "domain": "codereview.stackexchange", "id": 39512, "tags": "c++, game" }
Predict actual result after model trained with MinMaxScaler LinearRegression
Question: I was doing the modeling on the House Pricing dataset. My target is to get the mse result and predict with the input variable I have done the modeling, I'm doing the modeling with scaling the data using MinMaxSclaer(), and the model is trained with LinearRegression(). After this I got the score, mse, mae, dan rmse result. But when I want to predict it with the actual result. It got scaled, how to predict the after result with the actual price? Dataset: https://www.kaggle.com/code/bsivavenu/house-price-calculation-methods-for-beginners/data This is my script: import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, MinMaxScaler from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, mean_absolute_error train = pd.read_csv('train.csv') column = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt'] train = train[column] # Convert Feature/Column with Scaler scaler = MinMaxScaler() train[column] = scaler.fit_transform(train[column]) X = train.drop('SalePrice', axis=1) y = train['SalePrice'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=15) # Calling LinearRegression model = LinearRegression() # Fit linearregression into training data model = model.fit(X_train, y_train) y_pred = model.predict(X_test) # Calculate MSE (Lower better) mse = mean_squared_error(y_test, y_pred) print("MSE of testing set:", mse) # Calculate MAE mae = mean_absolute_error(y_test, y_pred) print("MAE of testing set:", mae) # Calculate RMSE (Lower better) rmse = np.sqrt(mse) print("RMSE of testing set:", rmse) # Predict the Price House by input: overal_qual = 6 grlivarea = 1217 garage_cars = 1 totalbsmtsf = 626 fullbath = 1 year_built = 1980 predicted_price = model.predict([[overal_qual, grlivarea, garage_cars, totalbsmtsf, fullbath, year_built]]) print("Predicted price:", predicted_price) The result: MSE of testing set: 0.0022340806066149734 MAE of testing set: 0.0334447655149599 RMSE of testing set: 0.04726606189027147 Predicted price: [811.51843959] Where the price is should be for example 208500, 181500, or 121600 with grands value in $. What step I missed here? Answer: First, you can't use anything from the test set before training. This means that the scaling should be done using only the test set, otherwise there's a risk of data leakage. Then remember that scaling your features means that the model learns to predict with scaled features, therefore the test set should be passed after it has been scaled as well (using the same scaling as the training set, of course). Finally you could obtain the real price value by "unscaling" with inverse_transform. But instead I decided not to scale the target variable in the code below because it's not needed (except if you really want to obtain evaluation scores scaled). It's also simpler ;) full = pd.read_csv('train.csv') column = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt'] full = full[column] X = train.drop('SalePrice', axis=1) y = train['SalePrice'] # always split between training and test set first X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=15) # Then fit the scaling on the training set # Convert Feature/Column with Scaler scaler = MinMaxScaler() # Note: the columns have already been selected X_train_scaled = scaler.fit_transform(X_train) # Calling LinearRegression model = LinearRegression() # Fit linearregression into training data model = model.fit(X_train_scaled, y_train) # Now we need to scale the test set features X_test_scaled = scaler.transform(X_test) y_pred = model.predict(X_test_scaled) # y has not been scaled so nothing else to do # Calculate MSE (Lower better) mse = mean_squared_error(y_test, y_pred) print("MSE of testing set:", mse) # Calculate MAE mae = mean_absolute_error(y_test, y_pred) print("MAE of testing set:", mae) # Calculate RMSE (Lower better) rmse = np.sqrt(mse) print("RMSE of testing set:", rmse) # ... evaluation etc. ```
{ "domain": "datascience.stackexchange", "id": 11181, "tags": "machine-learning, python, linear-regression, feature-scaling, mse" }
Is it possible to describe wordle as a multi armed bandit problem?
Question: Game wordle got fame in January 2022 on Twitter (now knows as X). Rules are pretty simple. Player has to guess a word of length 5 Player can make at most 6 guesses If player guesses the correct word or when 6 guesses are exhausted, game ends. Once player guesses any word, he/she gains information regarding the actual word using colors. If a character is placed at correct position, it is denoted by green color. If a character is in the actual word but at a different position, then it is denoted by yellow color. I want to describe this as a reinforcement learning problem. My question is: Can we describe this as a multi armed bandit problem ? Edit-1: I have found these two research papers which address wordle as reinforcement learning problem. None of them has talked about seeing wordle as a bandit problem. D Bertsimas et al. S Bhambri et al. Answer: Is it possible to describe wordle as a multi armed bandit problem? Yes, although the data management to present the current choice would involve constructing a state much like a reinforcement learning (RL) version of the same problem. An agent that attempted to solve Wordle with a multi-armed bandit approach would likely be less efficient than the RL version, since the reinforcement learning version would be able to select an answer with a lower immediate chance of winning, but that gave more information and thus a higher chance of solving. You can intuitively see that is the case since a bandit version would learn to equally select any one of the few thousand possible start words (assuming they are equally likely to be chosen by the problem setter) for a 1-in-2390 probability of winning, whilst it is a proven strategy that some start words are more informative when they fail. Bandit algorithms however do not consider "next state". A multi-armed bandit version would be a contextual bandit, with the input state being known letter information from previous attempts - e.g. an array of 26 x 5 x 2 with the known results of placing each letter in each position so far. The output could be the possible class values - e.g. all allowed words, one-hot encoded. Other structures are possible. You could also make the agent's life slightly easier by ruling out words logically - although that's 90% of the work so there's not much learning to do at that point. A bandit's best strategy assuming the target word was chosen randomly, is simply to choose from available valid words completely at random*. The reinforcement learning version could use identical structures, but in its Q table it would be able to learn about the advantages to reducing the space of valid words through careful choice in early guesses. An optimal play of Wordle assuming random pick of target word is also entirely possible using a logical look-ahead search. By choosing test words that are guaranteed to split the remaining valid words into the smallest groups (probabilistically) depending on the results, you can dramatically reduce the search space in only a few steps. This resolves to minimising the mean square size of each group (the frequency of ending up in the group times the remaining size). You could probably write this optimal search just as easily as writing a bandit or RL agent to solve the problem. However, that only makes sense if you want an optimal agent by any means - if you want to use Wordle as a way to try out RL or bandit algorithms, then there is no need to write this "expert" agent. * You could use reward shaping to reward the bandit for reducing the remaining candidate words. At that point you have almost implemented the full reinforcement learning version by proxy though.
{ "domain": "ai.stackexchange", "id": 4142, "tags": "reinforcement-learning, multi-armed-bandits" }
Derivation of Boltzmann distribution - two questions
Question: I understand that the usual way of deriving the Boltzmann distribution involves considering a small system of energy $\epsilon$ embedded in a much larger heat bath of energy $E - \epsilon$ and the total system energy is $E$. Given that the bath has accessible microstates $\Omega_b(E - \epsilon)$ and the system has microstates $\Omega_s(\epsilon)$ and the total system + bath has microstates $\Omega_t(E)$. We now state that the probability of finding the system in energy $\epsilon$ is simply \begin{equation} P(\epsilon) = \frac{\Omega_s(\epsilon)\Omega_b(E - \epsilon)}{\Omega_t(E)} \end{equation} $\textbf{Question 1}$: This is usually replaced by \begin{equation} P(\epsilon) = \frac{\Omega_b(E - \epsilon)}{\Omega_t(E)} \end{equation} Why should this be so? Why can we ignore the fact that the number of accessible microstates in the system that should vary with $\epsilon$? Moving on, the usual trick is to use logarithms, since the $\Omega$ terms are all very large. Thus, \begin{equation} \ln P(\epsilon) = \ln\Omega_b(E - \epsilon) -\ln \Omega_t(E) \end{equation} A Taylor expansion of the first term about $E$ gives us \begin{equation} \ln P(\epsilon) = c - \epsilon\frac{\partial\ln\Omega_b(E)}{\partial E} + O(\epsilon^2), \end{equation} where c is just a constant that depends on the bath and will be fixed when we normalize $P(\epsilon)$. Ignorning the higher order terms, we get $P(\epsilon) \propto e^{-\beta\epsilon}$ where we identify $\beta = \frac{\partial\ln\Omega(E)}{\partial E}$. $\textbf{Question 2}$: Why can we ignore the higher order Taylor terms? I understand that $\epsilon$ is small compared to the heat bath energy $E$ but why am I comparing it to $E$ to get the right measure of the error in probability? Answer: I think the confusion here has to do with what the Boltzmann distribution describes. It does not give you the probability of finding your small system with a particular energy. Instead, it tells you the probability of finding it in a particular microstate. If you want to know the probability of getting a particular energy, you have to sum the Boltzmann probability over the degenerate microstates. This is how you get the Maxwell-Boltzmann distribution. So, a more correct way to write down what you have above is $$ P_s \propto \Omega_b\left(E - \epsilon\right)\,, $$ where $s$ is some microstate of the small system. This leads you to your formula. Concerning the second order of $\epsilon$. As you say, in equilibrium, we define $\beta = \frac{\partial \ln\Omega\left(E\right)}{\partial E}$. Since $\beta = \frac{1}{k_B T}$ (a constant), the second derivative of the logarithm vanishes, taking away $\epsilon^2$.
{ "domain": "physics.stackexchange", "id": 45167, "tags": "statistical-mechanics" }
retrieve phase of an extrapolated periodic 1D signal
Question: I have a periodic signal on a given grid, say (in matlab format): t = 1:30; omega = 2*pi/18.431; phi = -pi+2*pi*rand(1); % a random phase [-pi,pi] x = sin(omega*t+phi); % the signal x = x+0.5*rand(1,length(x)); % add some noise Now I want to retrieve the phase phi. There are a few approaches to that, one is to use fft. The problem is that my grid is not good enough to pick that frequency, hence the phase. (another way is to fit to a sin, but that takes way too long if I need to do it 1e6 times) I tried to implement the "Autoregressive all-pole model parameters — Burg's method" that is mention in an answer to this question. I manage to pick up the frequency quite well, but fail to pick up the phase. I was trying to use angle(fft_vec(idx)), where fft_vec is the spectrum obtained after extrapolating the original signal (using arburg), and idx is the index where the frequency omega is picked up. What am I doing wrong? and how can I manage to get that phase by other means? Answer: if you know, in advance, the frequency of the sinusoid, so only the phase (and perhaps the amplitude) is unknown, the simplest noise-immune method i know of to get amplitude and phase is (i'm gonna do this in continuous time and let you translate it to discrete time and eventually to MATLAB): $$ x(t) = \sin(\omega t + \phi) + n(t) $$ compute $$ \begin{align} a & = \int\limits_0^{\frac{2 \pi}{\omega}} x(t) \sin(\omega t) dt \\ & = \int\limits_0^{\frac{2 \pi}{\omega}} \left(\sin(\omega t + \phi) + n(t) \right) \sin(\omega t) dt \\ & = \int\limits_0^{\frac{2 \pi}{\omega}} \sin(\omega t + \phi) \sin(\omega t) dt + \int\limits_0^{\frac{2 \pi}{\omega}} n(t) \sin(\omega t) dt \\ & = \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \cos(\phi) dt - \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \cos(2\omega t + \phi) dt + \int\limits_0^{\frac{2 \pi}{\omega}} n(t) \sin(\omega t) dt \\ & \approx \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \cos(\phi) dt \\ & = \frac{\pi}{\omega} \cos(\phi) \\ \end{align} $$ and $$ \begin{align} b & = \int\limits_0^{\frac{2 \pi}{\omega}} x(t) \cos(\omega t) dt \\ & = \int\limits_0^{\frac{2 \pi}{\omega}} \left(\sin(\omega t + \phi) + n(t) \right) \cos(\omega t) dt \\ & = \int\limits_0^{\frac{2 \pi}{\omega}} \sin(\omega t + \phi) \cos(\omega t) dt + \int\limits_0^{\frac{2 \pi}{\omega}} n(t) \cos(\omega t) dt \\ & = \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \sin(\phi) dt + \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \sin(2\omega t + \phi) dt + \int\limits_0^{\frac{2 \pi}{\omega}} n(t) \cos(\omega t) dt \\ & \approx \frac{1}{2} \int\limits_0^{\frac{2 \pi}{\omega}} \sin(\phi) dt \\ & = \frac{\pi}{\omega} \sin(\phi) \\ \end{align} $$ in both expressions (on the bottom line) we know the middle integral is zero and expect the integral on the right to tend toward zero because $n(t)$ is bipolar and ain't correlated with anything. i think, then, that you'll find the phase $\phi$ to be: $$ \phi = \arg\left\{a + jb \right\} $$ which is, if $a>0$ $$ \phi = \arctan\left(\frac{b}{a} \right) $$ otherwise, you might have to add or subtract $\pi$ to that expression.
{ "domain": "dsp.stackexchange", "id": 2309, "tags": "matlab, sampling, phase" }
Why do states with $m_1 + m_2$ have to vanish in the Clebsch-Gordon expansion of combined states?
Question: I'm currently studying QM and more specifically addition of spin angular momentum. I'm using the handbook from Griffiths. A combined state $|s m \rangle$ can be written using Clebsch-Gordon coefficients as: $$ |s m \rangle = \sum_{m_1+m_2=m}C^{s_1 s_2 s}_{m_1 m_2 m}|s_1 s_2 m_1 m_2 \rangle $$ It is then argued that only composite states which have $m_1+m_2=m$ are included in the sum, or equivalently: the CG-coefficients vanish if $m_1+m_2 \neq m$. Griffiths explains this by saying this that the $z$-components add. But let's look at the combined state $|1 0 \rangle$. Why can't the states $|\frac{1}{2} \frac{1}{2}\frac{1}{2}\frac{1}{2} \rangle$ and $|\frac{1}{2} \frac{1}{2} -\frac{1}{2} -\frac{1}{2} \rangle$ be included in the sum. the first one has a spin $z$-component of $1$ and the second of $-1$, and they just add to $0$, in agreement with the total $z$-spin of the combined state. So why is there a problem? Why can't these states be included? Answer: Here's a proof (first I act $\hat{J}_z$ on the right, and second I act it on the left): $$ \langle sm|\hat{J}_z|s_1s_2m_1m_2\rangle=\hbar(m_1+m_2)\langle sm|s_1s_2m_1m_2\rangle=\hbar m\langle sm|s_1s_2m_1m_2\rangle $$ So if $m_1+m_2\neq m$ then $\langle sm|s_1s_2m_1m_2\rangle$ has to be zero. Conceptually... if two states are eigenstates of any Hermetian operator with different eigenvalues they have to be orthogonal. This is an immediate consequence of the spectral theorem. A bit speculative, but it feels like you're confusing "adding angular momenta" in the sense of combining two systems into one combined wavefunction like: $$ \left|\frac{1}{2},m_1\right\rangle \otimes\left|\frac{1}{2},m_2\right\rangle =\left|\frac{1}{2}\frac{1}{2}m_1m_2\right\rangle $$ versus adding two wavefunctions to form a linear combination like: $$ \frac{1}{\sqrt{2}}\left(\left|\frac{1}{2},-\frac{1}{2}\right\rangle+\left|\frac{1}{2},\frac{1}{2}\right\rangle\right) $$
{ "domain": "physics.stackexchange", "id": 95338, "tags": "quantum-mechanics, angular-momentum, conservation-laws, quantum-spin" }
Understanding mathematically the free expansion process of an ideal gas
Question: I'm trying to understand mathematically that for the free expansion of an ideal gas the internal energy $E$ just depends on temperature $T$ and not volume $V$. In the free expansion process the change in internal energy $\Delta Q = \Delta W = 0$, therefore by the first law $\Delta E=0$. Energy is a function of state so $E=E(V,T)=E(p,T)=E(p,V)$, using $V$ and $T$ as the state variables we have $E=E(V,T)$. I have the following written mathematically in my notes but do not understand how it is derived. If $E=E(V,T)$ then $dE=\left(\frac{\delta E}{\delta V}\right)_T dV+\left(\frac{\delta E}{\delta T}\right)_V dT$ since we know experimentally that $dT=0$ and $dE=0$ from the first law we can write: $\left(\frac{\delta E}{\delta V}\right)_T=0$, as required. I have two main problems with this, firstly I do not understand where $dE=\left(\frac{\delta E}{\delta V}\right)_T dV+\left(\frac{\delta E}{\delta T}\right)_V dT$ comes from. My guess is that it is the differential of $E(V,T)$ but I do not fully understand the notation of what $E(V,T)$ represents that is, I understand that $E$ is a function of temperature and volume but I do not know how this can be written mathematically other than $E(V,T)$ so I can't differentiate it myself to check this. Again if I were to guess I would get an expression for $V$ and $T$ using the ideal gas equation and try to differentiate that? Secondly even with the results I do not understand why the end result is $\left(\frac{\delta E}{\delta V}\right)_T=0$ and not $\left(\frac{\delta E}{\delta V}\right)_T dV=0$. Has $dV$ simply been omitted because multiplying it by 0 in turn makes it 0? This question has arisen from me looking back over my lecture notes so it is possible I have written something down incorrectly which is now confusing me. If you could help to clarify any of the points above that would be great. Please let me know if more information is needed. Edit: I should also add I am not clear on the significance of the subscripted values $T$ and $V$ on either of the fractions represent. Update: I found the suffixes $T$ and $V$ mean that the temperature and volume is constant in the process. Answer: $E(V,T)$ is an unspecified function. You don't need to know the form to get the derivation correct. The equation: $$dE=\left(\frac{\delta E}{\delta V}\right)_T dV+\left(\frac{\delta E}{\delta T}\right)_V dT$$ is called the differential form of the total derivative and can be written for any function regardless of the form; it's simply a definition. As you noted in your edit, the subscripts on the derivatives indicate that they are to be taken with that variable held constant. So the first term on the RHS is the change in energy with change in volume for a constant temperature multiplied by the incremental change in volume. If we know $dT = 0$ and we've established from the first law that $dE = 0$ then we are left with: $$dE=\left(\frac{\delta E}{\delta V}\right)_T dV=0$$ Since the gas is expanding, we know that the incremental change in volume $dV \neq 0$. Since the product is zero (because $dE = 0$) then the only conclusion is that $\left(\frac{\delta E}{\delta V}\right)_T = 0$
{ "domain": "physics.stackexchange", "id": 28433, "tags": "thermodynamics, energy, ideal-gas" }
Mechanism of the reaction of an alkene with excess HI in presence of CCl4
Question: Problem Answer 2-iodopropane Question I thought of Markovnikov's rule and suggested 1,2‐diiodopropane as the the final product: Apparently, this is wrong. I can not figure out the mechanism of this reaction (will $\ce{HI}$ dissociate in the presence of $\ce{CCl4}?)$ And what is the significance of excess $\ce{HI}$ here? Answer: I am at a loss to supply the mechanism, but based on the problems I've worked, and based on the theory that my instructor has taught, a general thumb-rule is that iodine on adjacent carbon atoms (vicinal di-iodo, if you will) are unstable, and they are eliminated as $\ce{RCHICH2I -> RCH2=CH2 }$ An idea for this can be picturised (though this may possibly be the incomplete or even incorrect reasoning) by considering that iodine atoms are bulky, and steric factors cause strain in the main chain. Moreover, there are possibilities of van der Waals' forces between vicinal iodine atoms, and also the good leaving tendency of iodine, that may favour the formation of $\ce{I2}$ by elimination. A brilliant example that lucidly explains this is the reaction of glycerol with excess of HI; after substitution of all the hydroxyl groups, there is an elimination of $\ce{I2}$ as discussed above, leading to the alkene of your original question. Subsequently, there is an addition of HI, indeed following Markovnikov sensibilities, that leads to the formation of 1-propene. It subsequently adds HI to yield your final product. Thus, 1 mole glycerol consumes 5 moles of HI; 3 via substitution, 2 via addition. Now, the last example of glycerol wasn't strictly necessary, but I personally find the sequence quite beautiful; a single pathway leading to 3 rounds of substitution, two of addition and all interspersed with a unique type of elimination, and all this when we barely had a handful of reactants to begin with.
{ "domain": "chemistry.stackexchange", "id": 14956, "tags": "organic-chemistry, reaction-mechanism, halides, hydrocarbons" }
Using multiple LaserScan
Question: I use two different laser scan on my Pioneer robot. The first is a Sick LMS100, the second a Sick TiM300. How can I integrate their scan data in a single ROS node? In my launch file I call the two laser drivers, but in the main scan data overlap: in a cycle, I obtain the first laser scan data, in another cycle I obtain the second laser scan data and so on... Thanks Originally posted by daddy88 on ROS Answers with karma: 41 on 2012-07-02 Post score: 4 Answer: I would say it completely depends on your system configuration. Normally, it should not be a problem when both lasers publish their data on the same topic since the LaserScan message contains a header with a frame_id and a time stamp. Of course, this requires a valid TF tree and the laser drivers to be configured to use a different frame id for each scanner. Amcl, for instance, supports several lasers on one topic. By using topic remapping, you can configure your laser scanners to publish on different topics. Have a look at this question/answer for more information on that. Finally, if you don't want to use the LaserScan message but a point cloud, you can use the laser_assembler node as @weiin suggests in his answer. However, this solution won't work for amcl or any other node that requires a LaserScan message. On our robot, we use two Hokuyo lasers for amcl. Both laser drivers publish on separate topics and in the amcl node, we relay both topics to amcl's input topic using topic_tools' relay. That way, we can access the laser scans separately or, if needed, on one single topic. Originally posted by Lorenz with karma: 22731 on 2012-07-03 This answer was ACCEPTED on the original site Post score: 10
{ "domain": "robotics.stackexchange", "id": 10027, "tags": "ros, sicklms, multiple, laserscan, sick" }
Get Moon libration data from JPL Horizons
Question: I've been searching Horizons settings to find lunar librations but can't find. How can I get the libration data? So I have tested this Horizons Web Application and selected Moon as the target. Whether I select Vector Table or Osculating Orbital elements or Observer Table as Ehpemeris Type there's no lunar libration column in the output data. I'm expecting two parameters like libration_lon, libration_lat or something. I've tested both ecliptic and equatorial reference planes (in Table Settings). Answer: For Ephemeris Type, choose Observer Table. Under Table Settings, select: ☑ Observer sub-lon & sub-lat They don't use the word "libration" because it also applies to other bodies e.g. Mars. Then the output has: 'ObsSub-LON ObsSub-LAT' = Apparent planetodetic longitude and latitude of the center of the target disc seen by the OBSERVER at print-time. [...] Note that at 1 lunar distance, the observer's geographic location can change the results by as much as 1° due to parallax.
{ "domain": "astronomy.stackexchange", "id": 7129, "tags": "the-moon, lunar-libration" }
In a simple battery + resistor circuit, what form of energy is lost from the electrons upon exiting the resistor?
Question: I will give this question a little context. Firstly, as I understand it, as soon as I "close the switch" on a circuit, electric current pretty quickly establishes a steady state where, at any given cross section along a wire, the average kinetic energy of that slice is both constant and equal anywhere along the wire. (Please correct me if I am misunderstanding). If the average kinetic energy is constant anywhere throughout the wire in the circuit (which confuses me, as I would think that the electrons should all accelerate after exiting the resistor since they are no longer being impeded as much), that means that the average velocity is constant. So, in the example of a simple circuit with a battery of v Volts and a resistor of o Ohms, my question is the following: Because a 'voltage drop' is known to occur across the resistor, what type energy is being "traded" to generate the heat that radiates from the resistor? I would think that the reflexive answer is "electrical energy"...hence the VOLTAGE drop (the sacrificed energy is clearly not kinetic, as the velocity is constant everywhere). However, I find this confusing. Does this mean that if I had a positive test charge, it would be easier for me to bring it to the beginning of the resistor as compared to bringing it to the end of the resister? Further, if the correct answer IS "electrical energy", why exactly DOES electrical energy get "dissipated" as the electrons pass through the resistor? I always here the comment Oh! It's because all the electrons are running into densely packed crap which impedes their flow but that to me sounds like a reason for their KINETIC energy to be reduced. However, clearly that's not the case. So, ultimately, I guess the real question is: **What goes on in the resistor that is literally removing electrical energy **. I am sure that this is a quantum mechanics question, but my quantum mechanics knowledge is not terribly strong. If I could get an answer that is devoid of crazy wave function equations, I would greatly appreciate it. Thanks! Answer: Let's assume that the average speed of an electron should be the same everywhere in the circuit, including wires and resistors. This is generally not true (for instance, when the diameter of a wire changes), but is a reasonable simplification. If we track an individual electron, we'll, presumably, see that it speeds up due to the electric field, then it collides with an atom (ion), loses its speed and its kinetic energy (which is turned into heat energy) and speeds up again. If we assume that the frequency of the collisions in a resistor is greater than in a wire, then, given the same electric field (i.e., the same acceleration), the average speed of electrons in the resistor would be lower than in the wire, so the electrons will pile up at the front end of the resistor and will be at deficit at the back end, which will increase the electric field inside the resistor. As a result, the electrons inside the resistor will accelerate faster, so that, even with the increased frequency of collisions, they will have the same average (and top) speed as the electrons in the wire. Since the frequency of collisions has increased and the kinetic energy loss (heat gain) associated with each collision is the same (due to the same top speed), the heat generated by each passing electron per unit length in the resistor will be greater than in the wire.
{ "domain": "physics.stackexchange", "id": 66406, "tags": "electromagnetism, thermodynamics, electric-circuits, electrical-resistance, dissipation" }
Can you be blinded by a 'dim' light?
Question: From what I can tell, if you pick a color near the extreme of the visible light spectrum, let's say red, and trace a path across the spectrum until you are outside of the visible range, at some point the red color will begin to darken and dim until it's invisible (ie. black), indicating that you are now outside the range. If this is the case, does that mean that if you were to observe a powerful enough light source emitting solely that dim frequency, that it could be blinding to your eyes? By blinding, I don't think I mean literally blocking the rest of your vision, but more as in painful or overly-stimulating, the same way a bright white or bright blue light can affect a person's sight. It is hard to imagine being blinded by a dim light, because usually when you increase the intensity of the light, the saturation of the color will increase, until it appears bright. In this special case though, the color is already fully saturated to begin with, so no matter how high you increased the intensity, it will always appear 'dim'. Is this right? EDIT: Comments have shown that the word I was searching for is dazzled, not blinded. There are some great answers here explaining the harmful effects of this type of light, and this is a legitimate interpretation of what I am looking for. The essence of the question, however, is to understand if a near-IR or near-UV light could have a dazzling effect on the observer's eyes. Answer: Yes indeed, infrared light (the wavelengths beyond those of red light) can be very harmful to your eyes even though you don't see them. The same applies for ultraviolet light (the wavelengths beyond those of violet light). You can read more under the topic of laser eye safety. People that work with lasers need to use safety glasses if these lasers fall within certain categories. These include infrared and ultraviolet lasers.
{ "domain": "physics.stackexchange", "id": 45960, "tags": "visible-light, electromagnetic-radiation, vision" }
Deduce the possible structure given spectroscopic data for the aromatic compound
Question: For $\ce{C11H13NO}$, I have the following $\ce{^1H}$ NMR data: shift (ppm) 3.00 (6H, s) 6.55 (1H, dd, $J=15.5, \pu{9 Hz}$) 6.70 (2H, d, $J=\pu{8Hz}$) 7.35 (1H, d, $J=\pu{15.5Hz}$) 7.45 (2H, d, $J=\pu{8Hz}$) 9.60 (1H, d, $J=\pu{9Hz}$) I also know there are two absorptions from IR at $1600$ and $\pu{1660cm^{-1}}$. From the IR it seems reasonable to suggest an aromatic amide ($\pu{1660cm^{-1}}$). The shift of $\pu{9.60ppm}$ is huge and I think this could really only come from a proton connected to the carbon of a carbonyl. The 6H peak could be two equivalent $\ce{CH3}$ groups, and as it is singlet, I thought they could hang off the nitrogen of the amide, then it wouldn't split. The two sets of 2H atoms I thought could be from the aromatic ring. The problem is piecing all of it together! The closest structure I have is this: but I know this is wrong as it lacks a $\pu{9.60ppm}$ shift. How can I arrive at the correct structure? Answer: It always helps to start with the ‘blooming obvious’: the signal at $\pu{9.60ppm}$. This is obviously an aldehyde. It also obviously couples ($^3J=\pu{9Hz}$) with the signal at $\pu{6.55 ppm}$. This proton is either in the range of a dihalogenated carbon, an electron-rich aromatic system or an alkene. We can rule out all possibilities except for the alkene: it can’t be aromatic because there would be no $^3J$ coupling to a non-aromatic proton (there has to be at least one quarternary carbon in-between). Moving on, we have a very high coupling constant of $J = \pu{15.5 Hz}$. While it would, in theory, be possible that this arises from a geminal $^2J$ coupling of two diastereotopic protons (although those are typically on the order of $\pu{12Hz}$, so slightly less), the more reasonable explanation is an (E)-configured alkene. If it were a $\ce{CH2}$ group, we not only would get into trouble explaining the extremely high chemical shift but also why the aldehyde only couples to one of those protons. Thankfully, an alkene is what we already guessed from the chemical shift. So we now have three protons out of the way and a $\ce{?-CH=CH-CH=O}$ substructure. Now we might choose to take double bond equivalents into play. The sum formula $\ce{C11H13NO}$ evaluates to 6 double bond equivalents. We have used two for the alkene and the aldehyde. The four remaning double bond equivalents together with the region the chemical shifts are in scream substituted benzene. We may now take a look at the actual integrals and couplings of the protons we deem can still be aromatic (all except for the 6 singlet protons at $\pu{3.00ppm}$). We have two sets of two and each are an apparant doublet. Therefore, we must have a disubstituted with a para-substitution pattern. The two fragments we have so far, a $\ce{C6H4}$ and a $\ce{C3H3O}$ one, add up to $\ce{C9H7O}$, meaning that $\ce{C2H6N}$ is still missing. We should also note that all these six hydrogens are chemically equivalent. You can play around with this, but the only way to have six chemically equivalent hydrogens and a nitrogen in a group that connects only once is in a dimethylamino group. Thus, the final structure is: Finally, allow me a few words on why your structure is incorrect apart from the missing proton corresponding to $\pu{9.60ppm}$: The phenyl protons would show up as a set of three (so far so good). However, they would be a doublet and two triplets (one of the triplets corresponding to the single proton). Your spectrum does not contain any apparant triplets. Also, monosubstituted phenyl groups tend to have much more similar shifts to the point where they often only give a $\ce{5H}$ multiplet. The six protons on the $\ce{NMe}$ groups must be equivalent. Since they are obviously on different carbons, there must be some rotation that maps one set onto the other. In my structure, you can easily rotate the $\ce{Ph-N}$ bond to transform one group onto the other. In your structure, rotation around the $\ce{C(O)-N}$ bond is restricted due to the partial double bond character. Therefore, the two methyl groups would show up as two separate signals of three hydrogens each. Look up the spectrum of DMF (dimethylformamide) to confirm this. Final note: I know nothing about IR and I do not consider it a helpful tool in structure determination. Thus, I cannot comment on the IR frequences and what they can, would or cannot correspond to.
{ "domain": "chemistry.stackexchange", "id": 8929, "tags": "spectroscopy, nmr-spectroscopy" }
Unsigned 64bit subtract-with-borrow in Standard C++
Question: I'm writing a (compile-time-)fixed-width unsigned big integer. To implement subtraction, a subtract-with-borrow primitive is required. When efficient platform-specific implementation isn't available (e.g. x86_64's _subborrow_u64 intrinsic), it needs to be implemented in Standard C++. I've been able to come up with the following implementation: #include <stdint.h> inline auto subtract_with_borrow( uint64_t& result, uint64_t left, uint64_t right, uint64_t borrow /* only 0 or 1 */) -> uint64_t /* borrow */ { result = left - right - borrow; return (left < right) | ((left == right) & borrow); } However, I suspect it might be suboptimal since it requires roughly twice as many operations as add-with-carry (don't review it): inline auto add_with_carry( uint64_t& result, uint64_t left, uint64_t right, uint64_t carry /* only 0 or 1 */) -> uint64_t /* carry */ { result = left + right; uint64_t next_carry = result < left; result += carry; return next_carry; } I intuitively expect a certain symmetry to exist here. Can subtract_with_borrow be simplified further? Or is my intuition wrong and this is indeed the optimal implementation? And no, the compiler optimization doesn't manage to magically transform it into a better version. Answer: Your intuition is correct, but the issue is that your add_with_carry lacks the carry propagation in subtract_with_borrow. That's a general observation - if the new code looks more complicated than the old code, you should also consider that the old code lacked something. Consider the call add_with_carray(0,2^64-1,1): result=0+(2^64-1); // 2^64-1 next_carry=(2^64-1)<0; // False result+=1; // causing result=0; due to overflow return next_carry; // 0 In general you should test such routines for carry=0,1 and left, right close to 0 and 2^64-1
{ "domain": "codereview.stackexchange", "id": 41656, "tags": "c++, performance, algorithm, integer, c++20" }
malloc in main() or malloc in another function: allocating memory for a struct and its members
Question: When initializing a struct in C, we can allocate memory inside the main function or within another function and return a pointer to the newly created struct. This first example shows the latter; memory is allocated in Buffer_create and a pointer is returned: #include <stdio.h> #include "buffer.h" int main(int argc, char *argv[]) { struct Buffer *tx_buffer = Buffer_create(8); Buffer_destroy(tx_buffer); return 0; } And this one shows how all memory allocations can be done within the main function: #include <stdio.h> #include "buffer.h" int main(int argc, char *argv[]) { uint8_t *ptr_rx_buffer = malloc(sizeof(uint8_t)*8); struct Buffer *rx_buffer = malloc(sizeof(struct Buffer)); Buffer2_create(rx_buffer, ptr_rx_buffer, 8); Buffer2_destroy(rx_buffer); return 0; } And here are the contents of the header file buffer.h: #ifndef _buffer_h #define _buffer_h #include <stdint.h> #include <stdlib.h> struct Buffer { uint8_t *buffer; size_t size; }; struct Buffer *Buffer_create(size_t size); void Buffer_destroy(struct Buffer *who); void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size); void Buffer2_destroy(struct Buffer *who); #endif And buffer.c: #include <stdint.h> #include <assert.h> #include <stdlib.h> #include "buffer.h" struct Buffer *Buffer_create(size_t size) { struct Buffer *who = malloc(sizeof(struct Buffer)); assert(who != NULL); who->buffer = malloc(sizeof(uint8_t)*size); who->size = size; return who; } void Buffer_destroy(struct Buffer *who) { assert(who != NULL); free(who->buffer); free(who); } void Buffer2_create(struct Buffer *who, uint8_t *buffer, size_t size) { assert(who != NULL); who->buffer = buffer; who->size = size; } void Buffer2_destroy(struct Buffer *who) { assert(who != NULL); free(who->buffer); free(who); } The Result Both approaches work and the executable files for both end up being the same size. My Question Will either of these approaches result in memory leaks or poor performance? Answer: In C, initialization and destruction should be done at the same level of abstraction. This is important because it defines who is responsible for the memory. There are two good ways to follow this guideline: Allocate and deallocate in the API's init/destroy functions (your first code example). fopen does this although it maps files rather than regular memory. type *t = CHECK(init_t()); ... CHECK(destroy_t(t)); Allocate and deallocate at the call site before/after the API calls. pthread_mutex_create does this. type t; CHECK(init_t(&t)); ... CHECK(destroy_t(&t)); It is not acceptable to allocate in an initializer and then free outside. There are many examples of this pattern in the Windows API, and it is extremely error prone. You have to check the docs for which deallocation function needs to be called each time. I personally prefer to allocate/deallocate outside the API. That way I can use automatic variables and the return value of the initializer can be a specific error code.
{ "domain": "codereview.stackexchange", "id": 34281, "tags": "performance, c, comparative-review, memory-management, pointers" }
Notation: What's the group $G_1\backslash G_2$ compare to $G_2/G_3$?
Question: Quote Clifford Johnson D-brane page 108 This group includes the T-dualities on all of the $d$ circles, linear redefinitions of the axes, and discrete shifts ofthe $B$-field. The full space of torus compactifications is often denoted: $${\cal M} = O(d, d, Z)\backslash O(d, d)/[O(d) × O(d)].$$ The $/[O(d) × O(d)]$ meant module the group by equivalence class of $[O(d) × O(d)]$ but what was $\backslash O(d, d)$? From the various context it seemed to be an extension. But why not just write $\otimes$ or $\oplus$? What does $\backslash O(d, d)$ mean? Answer: The notation in the title stands for left and right cosets of a group $G$ wrt. a subgroup $H$. $H_1\backslash G/H_2$ denotes a double coset of a group $G$ wrt. two subgroups $H_1$ and $H_2$; one from left and one from right.
{ "domain": "physics.stackexchange", "id": 91975, "tags": "group-theory, definition, notation, mathematics" }
Similarity measure based on multiple classes from a hierarchical taxonomy?
Question: Could anyone recommend a good similarity measure for objects which have multiple classes, where each class is part of a hierarchy? For example, let's say the classes look like: 1 Produce 1.1 Eggs 1.1.1 Duck eggs 1.1.2 Chicken eggs 1.2 Milk 1.2.1 Cow milk 1.2.2 Goat milk 2 Baked goods 2.1 Cakes 2.1.1 Cheesecake 2.1.2 Chocolate An object might be tagged with items from the above at any level, e.g.: Omelette: eggs, milk (1.1, 1.2) Duck egg omelette: duck eggs, milk (1.1.1, 1.2) Goat milk chocolate cheesecake: goat milk, cheesecake, chocolate (1.2.2, 2.1.1, 2.1.2) Beef: produce (1) If the classes weren't part of a hierarchy, I'd probably I'd look at cosine similarity (or equivalent) between classes assigned to an object, but I'd like to use the fact that different classes with the same parents also have some similarity value (e.g. in the example above, beef has some small similarity to omelette, since they both have items from the class '1 produce'). If it helps, the hierarchy has ~200k classes, with a maximum depth of 5. Answer: While I don't have enough expertise to advise you on selection of the best similarity measure, I've seen a number of them in various papers. The following collection of research papers hopefully will be useful to you in determining the optimal measure for your research. Please note that I intentionally included papers, using both frequentist and Bayesian approaches to hierarchical classification, including class information, for the sake of more comprehensive coverage. Frequentist approach: Semantic similarity based on corpus statistics and lexical taxonomy Can’t see the forest for the leaves: Similarity and distance measures for hierarchical taxonomies with a patent classification example (also see additional results and data) Learning hierarchical similarity metrics A new similarity measure for taxonomy based on edge counting Hierarchical classification of real life documents Hierarchical document classification using automatically generated hierarchy Split-Order distance for clustering and classification hierarchies A hierarchical k-NN classifier for textual data Bayesian approach: Improving classification when a class hierarchy is available using a hierarchy-based prior Bayesian aggregation for hierarchical genre classification Hierarchical classification for multiple, distributed web databases
{ "domain": "datascience.stackexchange", "id": 187, "tags": "similarity" }
Help with bullet and vrpn_client on Hyrdro on Ubuntu 12.04
Question: Hello, I am having to upgrade to hydro and in the process of getting my enviroment set up I ran into a stumbling block. ROS_VRPN_Client requires bullet3. After downloading bullet3 and making it I still get an erros when trying to run ROSMAKE on vrpn_client. This is the error I keep getting. package/stack 'ros_vrpn_client' depends on non-existent package 'bullet' and rosdep claims that it is not a system dependency. Check the ROS_PACKAGE_PATH or try calling 'rosdep update I understand why it wont compile, I need Bullet but the problem is I have downloaded it and have followed the steps by bullet to get it compiled. The question is, where am I doing things wrong at? Any help will be appreciated. Originally posted by TheHenshinger on ROS Answers with karma: 3 on 2014-12-11 Post score: 0 Answer: There is a rosdep key for bullet which is defined on Precise. You should be able to resolve it if you run rosdep update. That said, it looks like the packaged version of bullet on 12.04 is version 2.8, which isn't the version you want. In that case, you should probably just remove the dependency on bullet from your manifest.xml altogether. Originally posted by ahendrix with karma: 47576 on 2014-12-11 This answer was ACCEPTED on the original site Post score: 0 Original comments Comment by TheHenshinger on 2014-12-19: hmmm, I ran rosdep update with no luck. How will removing the dependency in the manifest.xml file fix the problem?
{ "domain": "robotics.stackexchange", "id": 20311, "tags": "ros, bullet" }
What is the Grassmann parameter $\epsilon$ in the BRST transformation?
Question: Whenever I learn about anything involving fermions and the path integral, I get confused about Grassmann numbers. I'm currently following Weigand's notes, specifically the section on BRST symmetry. The BRST symmetry transformation is defined by $$\delta_\epsilon \Phi = \epsilon\, S \Phi$$ where $\epsilon$ is a Grassmann parameter, $\Phi$ is a field, and $S\Phi$ obeys $$S A_\mu = - D_\mu c = - (\partial_\mu c + i g [A_\mu, c]), \quad Sc = \frac{i}{2} g f^{abc} c^b c^c t^a, \quad S \bar{c} = - B, \quad SB = 0.$$ First off, what is the Grassmann parameter $\epsilon$ here? I get the feeling that for the manipulations to go through, it must be independent of the Grassmann numbers $c(x)$ and $\bar{c}(x)$ for any $x$. But that means that to define the BRST transformation at all, we must enlarge the space of Grassmann numbers in our theory, which doesn't make sense to me. So far we've been working semiclassically. Next, Weigand quantizes the theory, giving a BRST charge operator $\hat{Q}$ satisfying $$[\epsilon \hat{Q}, \hat{X}] = i \delta_\epsilon \hat{X}.$$ Now I don't understand what $\epsilon$ is in this context. If it's still Grassmann, then we now have a Hilbert space where the scalars include Grassmann numbers, which doesn't make any mathematical sense to me. Alternatively, is $\epsilon$ supposed to be an operator that anticommutes with all the other operators? In that case, why doesn't it have a hat over it? I'd really appreciate clarification on what $\epsilon$ means in both these contexts! Answer: That's a very good question. At the pragmatic level: The field of complex numbers $\mathbb{C}$ has been replaced by the set of supernumbers. Hilbert spaces and operators are not just (conjugate) linear wrt. $\mathbb{C}$ but are $\mathbb{Z}_2$-graded (conjugate) linear wrt. supernumbers. The BRST parameter $\epsilon$ is an independent infinitesimal Grassmann-odd supernumber (aka. a Grassmann number). It should be stressed that (soul-valued) supernumbers belong to an intermediate mathematical construct, and that they cannot be part of/have been integrated out/have been differentiated out/ in physically measurable quantities at the end of the calculation. This fact should be fairly obvious in the path integral formalism. In the operator formalism, if a creation operator creates a Grassmann-odd variable, then the corresponding annihilation operator behaves like a Grassmann-odd differentiation operator (wrt. that variable), or vice-versa. For more details, see also e.g. this & this Phys.SE posts; this & this Math.SE posts, and links therein.
{ "domain": "physics.stackexchange", "id": 47714, "tags": "quantum-field-theory, grassmann-numbers, brst" }
Crystal structures exhibiting dimeric arrangement of tetrahedrally coordinated cations
Question: I am looking for inorganic crystal structures that exhibit tetrahedrally coordinated cations arranged in a vertex-sharing dimer arrangement, where the cation - shared vertex - cation angle is close to 180°: Are there any known instances of such crystal structures? If there are, then any number of examples would be welcome. If there are examples of compounds with just similar features (dimers with different coordination, for instance), then this would also be appreciated. Answer: Given the unit must be isolated and should not be the subunit of an ionic network, the following graph model for CCDC ConQuest's (ver. 2022.3.0) query with restraints based on connectivity $(\mathrm T_n)$ and fixed the central bond angle within 170° to 180° range gave 119 hits. The unique found moieties are as follows with exemplary references from CSD database: Formula Name Bridging angle Conf. CSD ID $\ce{[Fe2OCl6]^2-}$ (μ-Oxo)bis[trichloroferrate(III)] $\angle\ce{Fe-O-Fe} = 180°$ Staggered ADETIM $\ce{[Fe2OBr6]^2-}$ (μ-Oxo)bis[tribromoferrate(III)] $\angle\ce{Fe-O-Fe} = 180°$ Staggered AWIDEQ $\ce{[Be2F7]^3-}$ (μ-Fluoro)bis[trifluoroberyllate(II)] $\angle\ce{Be-O-Be} = 180°$ Staggered SEYHOT $\ce{[Hg2I7]^3-}$ (μ-Iodo)bis[triiodomercurate(II)] $\angle\ce{Hg-O-Hg} = 180°$ Staggered GODDUY $\ce{Zn(CH3)2}$ Dimethylzinc $\angle\ce{C-Zn-C} = 180°$ Staggered SAJDEO $\ce{Cd(CH3)2}$ Dimethylcadmium $\angle\ce{C-Cd-C} = 180°$ Eclipsed AROPAA $\ce{[Tl(CH3)2]^+}$ Dimethylthallium(III) $\angle\ce{C-Tl-C} = 179°$ Eclipsed DOMHAO $\ce{[Cu(CH3)2]^-}$ Dimethylcuprate(I) $\angle\ce{C-Cu-C} = 180°$ Staggered DAZWIK $\ce{[Cu(CF3)2]^-}$ Bis(trifluoromethyl)cuprate(I) $\angle\ce{C-Cu-C} = 180°$ Staggered NONVIW $\ce{Hg(CF3)2}$ Bis(trifluoromethyl)mercury $\angle\ce{C-Hg-C} = 180°$ Staggered DTFMHG $\ce{Hg(CHCl)2}$ Bis(dichloromethyl)mercury $\angle\ce{C-Hg-C} = 180°$ Staggered PIPFEZ $\ce{[Mg(NH3)2]^2+}$ Diamminemagnesium(II) $\angle\ce{N-Mg-N} = 180°$ Eclipsed QUQQEB $\ce{[Ag(CF3)2]^-}$ Bis(trifluoromethyl)argentate(III) $\angle\ce{C-Ag-C} = 180°$ Staggered ATABAB $\ce{[Ag(NH3)2]^+}$ Diamminesilver(I) $\angle\ce{N-Ag-N} = 178°$ Staggered AWEGOZ $\ce{[Au(CF3)2]^-}$ Bis(trifluoromethyl)aurate(I) $\angle\ce{N-Au-N} = 178°$ Staggered QOCPAC $\ce{[Au(CH3)2]^-}$ Dimethylaurate(I) $\angle\ce{C-Au-C} = 180°$ Eclipsed WEMGOK $\ce{[Au(NH3)2]^+}$ Diamminegold(I) $\angle\ce{N-Au-N} = 180°$ Staggered DIWZOB $\ce{[Au(GeCl3)2]^-}$ Bis(trichlorogermyl)aurate(I) $\angle\ce{N-Au-N} = 180°$ Staggered RAGGEL Notes There are different conformations as well as several entries that do not follow your cation-anion assignment exactly. There is a bias for protons placement for the structures refined with Shelx due to the limitations of the riding model, so the confirmations for H-containing (methyl, ammonia) ligands might be incorrect. The database contains about four structures with linear diethyl ether moieties, which I omitted as outliers.
{ "domain": "chemistry.stackexchange", "id": 17278, "tags": "inorganic-chemistry, coordination-compounds, crystal-structure, solid-state-chemistry" }
Get _m_s time format from milliseconds value
Question: I could have any value in milliseconds like: 1040370 I must alert a specific converted time format : _m_s (ie:17m20s) Here is how I do it: function ms(a){ var m = a/1000/60, s = Math.floor(('0.'+(''+m).split('.')[1])*60); m = (''+m).split('.')[0]; alert(m+'m'+s+'s'); } ms(1040370); What do you think? Is it satisfactory or is there a better way to accomplish the same? Answer: Seems overly complicated. Let the builtin math and parsing functions do the work for you. And name time values something like t. const ms = t => alert( `${parseInt( t/1000 / 60 )}m${parseInt( t/1000 % 60 )}s` ) ms(1040370);
{ "domain": "codereview.stackexchange", "id": 34050, "tags": "javascript, datetime, formatting" }
Is it possible to measure x & y displacement components with a single point (out-of-plane) vibrometer?
Question: Originally I was going to use accelerometers, but they are to big for the disk I'm trying to measure. Basically I have a set of planetary gears for which I need to measure the vibrations in the x and y components, mainly. I´ll be performing modal testing with an instrumented hammer and a laser single point vibrometer. Since my gears are straight teeth spur gears I didn't take into account the "z" coordinate or vibrations of the system for my dynamic model, so if I point the laser perpendicularly to the gear´s plane the vibrations being measured by the laser will be those in z, which I'm not interested in. I read that if I had two Laser Doppler Vibrometers I could measure the in-plane motions I'm looking for, but since I only have one I was wondering if there´s a way of decomposing the projected component by pointing the laser at certain angle? Answer: There's just no way that you are going to turn a single Z measurement into an X or Y measurement. With multiple Z measurements, you could calculate pitch and yaw angles, but for a spur gear, that's not going to get you want you want as the gear is going to translate, not bend or rotate. Suggestion 1: Glue something to the spur gears that sticks up far enough out of plane that you can get the laser to reflect off of it in the X and Y direction. e.g. glue a small reflective cube to the disk. Point the laser at it in the X direction, perform the impact test, and then move the laser to the Y direction, and repeat. Suggestion 2: regarding accelerometers... How big of a disk are we talking here? They do make some very small accelerometers. e.g. Endevco Model 22 is a mere 0.14 grams.
{ "domain": "engineering.stackexchange", "id": 1662, "tags": "optics, vibration" }
Need help in writing a query using ADQL (Astronomical Data Query Language)
Question: I am trying to query Gaia archive to get the medium quality sample as mentioned in Reico-Blanco et al. (2022) Gaia Data Release 3: Chemical cartography of the Milky Way. The idea is to query the flags_gspspec string where every letter represents one flag. The criteria for selecting the medium quality flag is as follows, The first 13 characters are taken into consideration. The last 4 characters must always be 0. The seventh character could be one of one of (0,1,2,3). The remaining eight flags must be either 0 or 1. The problem gets even more complicated when we look at the allowed values for the flags, The seventh character could take one of the values from (0,1,2,3,4,5,9). All the other characters could take one of the values from (0,1,2,9). I tried writing a Regular expression to match the type and it failed because ADQL does not support Regex. The only option that I could think of is to write a list of all possible combinations and include them in the LIKE clause. The problem is I am getting 1024 such combination from elementary combinatorics and its not practical to write down all the possible combinations. If there is anybody out there who has worked on a similar problem before, please let me know. I would like to discuss this further. PS: I do not know whether this is the right forum to post this since the query is more related to a database query and less of an astronomical question. Incase, this is not the right place, please redirect me to the right forum. Thank you in advance. Answer: I figured out the database query. There is a similar example on Gaia archive and a similar code is also available in the Reico Blanco paper linked in my question above. Below is the query that goes in with the WHERE clause. ((param.flags_gspspec LIKE '____________0%') OR (param.flags_gspspec LIKE '____________1%')) AND ((param.flags_gspspec LIKE '0%') OR (param.flags_gspspec LIKE '1%')) AND ((param.flags_gspspec LIKE '_0%') OR (param.flags_gspspec LIKE '_1%')) AND ((param.flags_gspspec LIKE '__0%') OR (param.flags_gspspec LIKE '__1%')) AND ((param.flags_gspspec LIKE '___0%') OR (param.flags_gspspec LIKE '___1%')) AND ((param.flags_gspspec LIKE '____0%') OR (param.flags_gspspec LIKE '____1%')) AND ((param.flags_gspspec LIKE '_____0%') OR (param.flags_gspspec LIKE '_____1%')) AND ((param.flags_gspspec LIKE '______0%') OR (param.flags_gspspec LIKE '______1%') OR (param.flags_gspspec LIKE '______2%') OR (param.flags_gspspec LIKE '______3%')) AND ((param.flags_gspspec LIKE '_______0%') OR (param.flags_gspspec LIKE '_______1%') OR (param.flags_gspspec LIKE '_______2%')) One could similarly define queries for the best quality sample too.
{ "domain": "astronomy.stackexchange", "id": 6555, "tags": "observational-astronomy, galactic-dynamics, gaia" }
What's wrong with this argument that Newton's second law implies all potentials are quadratic?
Question: Newton's second law states: $$F(\vec{x})=m\vec{\ddot{x}}$$ For $\vec{x}$ scaled by some arbitrary constant $s$, we obtain: $$F(s\vec{x})=ms\vec{\ddot{x}} \Longleftrightarrow \frac{F(s\vec{x})}{s}=m\vec{\ddot{x}}$$ Which is clearly just $F(\vec{x})$! Therefore: $$F(\vec{x})=\frac{F(s\vec{x})}{s} $$ for any $s$, which can only be satisfied by a quadratic potential. Therefore, if Newton's second law is to hold and be consistent, all potentials in the universe are quadratic! Is there a very obvious mistake here, or is this inconsistency related to the fact the classical mechanics is not a complete description of nature? Because this discrepancy does not seem to arise if we use Ehrenfest's theorem in QM. Answer: While other answers are correct, they fail to address your specific issue. It looks like you are treating Newton's second law like it defines a single function, when it does not. For example, in algebra if I say a function is $f(x)=x^2 + 3$, then I can "plug into" this function something like $sx$ so that $f(sx)=(sx)^2+3$ by how we defined the function. This is not what Newton's second law is doing. $F(x)=m\ddot x$ is not a function saying "whatever I plug into the function $F$ I take its second derivative with respect to time and multiply it by $m$." So, your statement of $F(sx)=ms\ddot x$ is not correct. Newton's law is a differential equation, not a function definition. $F(x)$ is defined by the forces acting on our system, and Newton's second law then states that the acceleration is proportional to this force.
{ "domain": "physics.stackexchange", "id": 67716, "tags": "newtonian-mechanics, forces, mass, acceleration, scale-invariance" }
RemoveDuplicateElement
Question: public class ArrayUtil { /** * Field INPUT_LESS_THAN_TWO. (value is 2) */ private static final int INPUT_LESS_THAN_TWO = 2; /** * Method removeDuplicateElement. Given a sorted array of integers, this * method removes the duplicate elements. Input array is sorted array and * can have only negative values, only positive value or a mix of both. * * @param inputArray * int[] * * @return int[] * @throws IllegalArgumentException */ public int[] removeDuplicateElement(final int[] inputArray) throws IllegalArgumentException { int j = 0; // Marks the begining of the array int i = 1; // Points toward the second element in the array if (null == inputArray || 0 == inputArray.length) { throw new IllegalArgumentException( "Input Array is either null or of zero length"); } // end of null and 0 length check // Return if the input array has only one item if (inputArray.length < INPUT_LESS_THAN_TWO) { return inputArray; } // end of check for length less than 2 while (i < inputArray.length) { if (inputArray[i] == inputArray[j]) { i++; } else { inputArray[++j] = inputArray[i++]; } } // end of while loop // copy and return the array final int[] outputArray = new int[j + 1]; for (int k = 0; k < outputArray.length; k++) { outputArray[k] = inputArray[k]; } return outputArray; } } I believe that the time complexity of this algorithm is \$O(N)\$. Answer: Style Comments I stated this in a comment (pun unintended but a happy side effect) that I think comments like this are unneeded and make the code harder to read. if (null == inputArray || 0 == inputArray.length) { throw new IllegalArgumentException( "Input Array is either null or of zero length"); } // end of null and 0 length check // Return if the input array has only one item if (inputArray.length < INPUT_LESS_THAN_TWO) { return inputArray; } // end of check for length less than 2 Compare that to this if (null == inputArray || 0 == inputArray.length) { throw new IllegalArgumentException( "Input Array is either null or of zero length"); } // Return if the input array has only one item if (inputArray.length < INPUT_LESS_THAN_TWO) { return inputArray; } Because everything is properly indented I just know by looking that the if-block if over. Lastly, the comments for i and j are poor. You state what they are originally pointing to but not what they're used for throughout the method which would be more useful. Something like this, int j = 0; // Marks the end of the sorted subarray to return int i = 0; // Points to the element being checked (It may be better to switch the names of i and j because i is usually used for the outer most "loop" meaning it moves less.) Doc Comments Adding javadoc comments is good practice and it's good to see you do this. The only issue I see with it is it starts by saying it's a method and it gives the name. This is redundant. The name is beneath the doc comment and if you view the javadoc as html it is still clear what the name is. Just remove "Method removeDuplicateElement." Throws IllegalArgumentException See this if you do not know the difference between checked and unchecked exceptions. IllegalArgumentException extends RuntimeException. Because of this it is an unchecked exception. The throws clause of a method is to alert the compiler that it can possibly throw the exception. Because this is an unchecked exception though the compiler doesn't care if the caller handles/throws it or not, and because of that it is redundant. I suggest either removing this or making your own exception that doesn't extend RuntimeException if you really want to make the called handle/throw the error. (I think this is a bad idea.) Note: I did not say there was an issue with throw new IllegalArgumentException( ... ); when the array is invalid for your method, this is fine. However, one could argue that because the point of the method is to remove duplicate elements that a null/empty array has the elements removes and you could simply return the null/empty array instead of throwing the error. In fact, I think I like that better. It's best to throw little and handle quietly when it comes to exceptions. Utility Class I seem to be linking back to my own answer a lot. For the same reasons as here I suggest you make this into a "utility class". Because everything about this class is always the same no matter how you make an instance of it, there's no point in having to make an instance of it. Quick summary, make it a final class, add a private constructor, and make all methods static. private static final fields There is nothing wrong with these but in this case I don't think making INPUT_LESS_THAN_TWO into one makes sense. You'd return the array if it only had one element no matter what, there's not something that's likely to change down the line that would make this value different. inputArray.length < 2 is simply more readable in this case, or better yet inputArray.length == 1 because earlier you already checked if it was 0 and it should never be below 0. (If it's ever below 0 the JVM is messing up and there's bigger issues! It's safe to assume it won't.) Code choice System.arraycopy Edit: 200_success's suggestion of Arrays.copyOf is better than my suggestion here. System.arraycopy is better when you already have an array you want to put things in, Arrays.copyOf makes a new array for you. Better to do away with making outputArray altogether and simply doing return Arrays.copyOf(inputArray, j + 1);. System.arraycopy is still a good tool to know of so I will leave this section, bold italic text is text I added in this edit. This is preferred to using a for-loop to make an array from an array specifically when you already have an array that you want to put the copied elements in. for (int k = 0; k < outputArray.length; k++) { outputArray[k] = inputArray[k]; } That becomes simply System.arraycopy(inputArray, 0, outputArray, 0, outputArray.length); (You may need to remove the final modifier for the output array, I am not entirely sure.) Increment operators This is simply my taste, no issue with your code, but I dislike inputArray[++j] = inputArray[i++]; because it's a little confusing. I prefer j++; inputArray[j] = inputArray[i]; i++;
{ "domain": "codereview.stackexchange", "id": 13438, "tags": "java" }
Failed to build octomap_server
Question: Hello, I'm new both to ROS and to linux. I've tried to build 3d_navigation package as it is described in tutorial: 3d_navigation. After completing all the steps to check out the code from svn repositories and calling rosmake --rosdep-install 3d_navigation I get an error that octomap_server fails to be built. If I install just single package octomap_server and build it rosmake octomap_server I get the same error. Below is the log of build failures. Note that I install packages in custom folder ~/ros_stacks and all the paths are configured in bashrc. The OS I use is Ubuntu 11.04. The distribution of ROS is Diamondback. How can I solve this problem? Build failures with context: --------------------- octomap_server mkdir -p bin cd build && cmake -Wdev -DCMAKE_TOOLCHAIN_FILE=`rospack find rosbuild`/rostoolchain.cmake .. [rosbuild] Building package octomap_server [rosbuild] Including /opt/ros/diamondback/stacks/ros_comm/clients/roslisp/cmake/roslisp.cmake [rosbuild] Including /opt/ros/diamondback/stacks/ros_comm/clients/rospy/cmake/rospy.cmake [rosbuild] Including /opt/ros/diamondback/stacks/ros_comm/clients/cpp/roscpp/cmake/roscpp.cmake -- Configuring done -- Generating done -- Build files have been written to: /home/probob/ros_stacks/octomap_server/build cd build && make -l2 make[1]: Entering folder `/home/probob/ros_stacks/octomap_server/build' make[2]: Entering folder `/home/probob/ros_stacks/octomap_server/build' make[3]: Entering folder `/home/probob/ros_stacks/octomap_server/build' make[3]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' [ 0%] Built target rospack_genmsg_libexe make[3]: Entering folder `/home/probob/ros_stacks/octomap_server/build' make[3]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' [ 0%] Built target rosbuild_precompile make[3]: Entering folder `/home/probob/ros_stacks/octomap_server/build' make[3]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' make[3]: Entering folder `/home/probob/ros_stacks/octomap_server/build' [ 20%] Building CXX object CMakeFiles/octomap_server.dir/src/OctomapServerCombined.o /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp: In member function ‘void octomap::OctomapServerCombined::insertCloudCallback(const sensor_msgs::PointCloud2_<std::allocator<void> >::ConstPtr&)’: /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:164:3: error: ‘KeySet’ is not a member of ‘octomap::OctomapROS<octomap::OcTree>::OcTreeType’ /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:164:33: error: expected ‘;’ before ‘free_cells’ /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:177:6: error: ‘free_cells’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:183:7: error: ‘occupied_cells’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:189:9: error: ‘free_cells’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:198:33: error: ‘octomap::OcTreeType::KeySet’ has not been declared /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:198:50: error: expected ‘;’ before ‘it’ /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:198:97: error: name lookup of ‘it’ changed for ISO ‘for’ scoping /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:198:97: note: (if you use ‘-fpermissive’ G++ will accept your code) /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:198:102: error: ‘end’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:199:12: error: ‘occupied_cells’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:200:51: error: no matching function for call to ‘octomap::OcTree::updateNode(const pcl::PointXYZ&, bool, bool)’ /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:206:9: note: candidates are: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::point3d&, bool, bool) [with NODE = octomap::OcTreeNode, octomap::point3d = octomath::Vector3] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:214:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::point3d&, float, bool) [with NODE = octomap::OcTreeNode, octomap::point3d = octomath::Vector3] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:222:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::OcTreeKey&, bool, bool) [with NODE = octomap::OcTreeNode] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:234:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::OcTreeKey&, float, bool) [with NODE = octomap::OcTreeNode] /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:205:31: error: ‘octomap::OcTreeType::KeySet’ has not been declared /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:205:48: error: expected ‘;’ before ‘it’ /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:205:104: error: ‘end’ was not declared in this scope /home/probob/ros_stacks/octomap_server/src/OctomapServerCombined.cpp:206:47: error: no matching function for call to ‘octomap::OcTree::updateNode(const pcl::PointXYZ&, bool, bool)’ /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:206:9: note: candidates are: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::point3d&, bool, bool) [with NODE = octomap::OcTreeNode, octomap::point3d = octomath::Vector3] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:214:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::point3d&, float, bool) [with NODE = octomap::OcTreeNode, octomap::point3d = octomath::Vector3] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:222:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::OcTreeKey&, bool, bool) [with NODE = octomap::OcTreeNode] /home/probob/ros_stacks/octomap_mapping/octomap/octomap/include/octomap/OccupancyOcTreeBase.hxx:234:9: note: NODE* octomap::OccupancyOcTreeBase<NODE>::updateNode(const octomap::OcTreeKey&, float, bool) [with NODE = octomap::OcTreeNode] make[3]: *** [CMakeFiles/octomap_server.dir/src/OctomapServerCombined.o] Error 1 make[3]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' make[2]: *** [CMakeFiles/octomap_server.dir/all] Error 2 make[2]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' make[1]: *** [all] Error 2 make[1]: Exiting from folder `/home/probob/ros_stacks/octomap_server/build' make: *** [all] Error 2 Originally posted by VitaliyProoks on ROS Answers with karma: 75 on 2011-07-28 Post score: 0 Answer: I am currently working on all of it for improvements - 3d_navigation, octomap_server and octomap. Some of these improvements require changes in all of these packages simultaneously, and the underlying OctoMap library package itself. There is now a new OctoMap 1.1.1 released for testing and the octomap package is updated to use the new version. Update your packages ("svn up" in octomap should be enough) and all should compile again. That being said, expect changes throughout the code as it is still under active development. Originally posted by AHornung with karma: 5904 on 2011-07-28 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 6290, "tags": "ros, octomap, octomap-mapping, octomap-server" }
Using sinc as a filter
Question: I'm trying to use a cardinal sine as a lowpass filter for a cosine signal with a fundamental of 1k. In frequency domain, what really happens is that I'm multiplying two impulses (centered at -1k and 1k) with a rectangular pulse of width equals 2 (convolution is multiplication in frecuency domain). The result would be a constant zero function. However using the above code in Matlab I'm getting again the sinc function as output. Any help would be appreciated (attached the full plot). D = 5; f0 = 1000; fm = 2*f0; % nyquist reestriction t = (-D:1/fm:D); x = cos(1000*2*pi*t); h = sinc(t); x_p = filter(h,1,x); plot(x_p); Answer: Probably the problem was happening because I was using a filter as long as my signal, so I was getting only the transient instead of the whole filtered result; as Honglei Chen graciously explained in this thread. He also suggested to me to use this version of the code: D = 5; f0 = 1000; fm = 2*f0; % nyquist reestriction t = (-D:1/fm:D-1/fm); x = cos(1000*2*pi*t); h = sinc(t(3*numel(t)/8:5*numel(t)/8-1)); x_p = filter(h,1,x); plot(x_p);
{ "domain": "dsp.stackexchange", "id": 1770, "tags": "filters" }
Is Qiskit transpile function (with basis_gates=['u', 'cx']) universal?
Question: It's well known that the single-qubit rotation gate $U(\theta, \phi, \lambda)$ and the controlled-not gate $CX_{i,j}$ form one of the universal set of gates for quantum computation. So here's my question: is the Qiskit transpile function able to compile any given quantum circuit by using u and cx gates only? In particular, I would assume that the following code will always work with no errors: from qiskit.circuit.random import random_circuit from qiskit.compiler import transpile qc = random_circuit(num_qubits=5, depth=10) tqc = transpile(qc, basis_gates=['u', 'cx']) Unfortunately, it would seem not to be so and I was wondering why. I also noticed that, if I add the identity gate id in the list of basis_gates, the transpilation looks to always run successfully and I'm not sure about the reason for this. The error produced by qiskit is: QiskitError: "Cannot unroll the circuit to the given basis, ['u', 'cx']. Instruction id not found in equivalence library and no rule found to expand." Answer: The basis gates u, cx are universal. This error is an artifact of the Qiskit transpiler. Change your transpiler call line to this: tqc = transpile(qc, basis_gates=['u', 'cx', 'id']) And the error should be fixed. The reason this error occurs is because the identity gate (called id) can be used as a sort of timing enforcement gate for when the circuit is executing/or compiling. But, of course it is not actually needed in order to completely specify any intended quantum circuit. I assume in future versions of Qiskit this may be changed somehow so that users can be more selective for when they want to strictly include id gates or not. By the way, this may actually be a bug in some cases (you should check this for your test cases), for example if id is not ever used by the transpiler for an example random circuit. In this case you should report this as a bug in the Qiskit Github.
{ "domain": "quantumcomputing.stackexchange", "id": 4505, "tags": "qiskit, universal-gates, transpile" }
implementing a wall following robot in ros
Question: Hi all, I have a mobile robot and I would like it to follow a wall of a room. I already have a map of the room. I am using Wheel encoders for odometry. I am fusing data from wheel encoders and IMU using robot_pose_ekf. I have a Hokuyo lidar for localization and obstacle avoidance. I am also using Kinect to see obstacles which can not be seen by the hokuyo. I am using amcl for localization. I have couple of sharp sensors on the side for wall following. Now, I would like to know what is the best technique for wall following? Couple of techniques which I can think of: Use the map to come up with an initial global plan and then follow that global plan and change it if you see an obstacle which is not in the map. Dont use any global plan. Just follow the wall using the data from the sensors. This might be more difficult given that there can be wide variety of obstacles close to the wall and making sure that staying at a fixed distance from them might be tricky. My one constraint is that I want the robot to be always at a fixed distance of 2 inches approx. from the wall (or an obstacle close to the wall). I know this is a very general question but any suggestions regarding it will be appreciated. Please let me know if you need more information from me. Thanks in advance. Naman Kumar Originally posted by Naman on ROS Answers with karma: 1464 on 2015-07-06 Post score: 1 Original comments Comment by NEngelhard on 2015-07-07: Why do you want to use the sharp sensors if you have a hukuyu? Answer: I'll choose plan 1,which use the map of room. In the beginning, a global plan to walk through all the walls are planned. Then you can define two states for your robot to follow, "Wall following" and "Obstacle avoidance". This might be implemented by using SMACH, But the tricky part is in the state changing condition. This might be interesting, you can test different strategies. Another solution is to use ROS navigation, but implement your own global planner (by writing a plugin) to let it generate a plan that follows the wall. Originally posted by Po-Jen Lai with karma: 1371 on 2015-07-07 This answer was ACCEPTED on the original site Post score: 2 Original comments Comment by Naman on 2015-07-07: Thanks @Ricky! Do you know of any good resource/paper/forums/links for generating a global plan for wall following in ROS? TIA Comment by Po-Jen Lai on 2015-07-07: Forum: http://robotics.stackexchange.com/, As for paper: (I just did a quick survey, you might get more useful info by doing more survey) http://ieeexplore.ieee.org/xpl/abstractCitations.jsp?tp=&arnumber=220250&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D220250
{ "domain": "robotics.stackexchange", "id": 22088, "tags": "navigation, move-base" }
Balancing forces in a movable piston
Question: I need to balance forces on the "plate" of a piston situated in a closed container of a given spring constant k and area A with a compression x. It is also given that the initial pressure inside the container is P° Thus PA = kx Now here is my question, would P be the value of the net final pressure inside the container or would it be the change in pressure relative to initial pressure ? I think it should be the former but i've been told otherwise and can't wrap my brain around as to why is it so. Answer: Initially, the spring is uncompressed. The force on the piston due to the internal pressure of the container is balanced by the force on the piston due to the external pressure of the atmosphere. Once the spring is compressed, there are three forces acting on the piston: $F_1=$ The outward force $kx$ due to the spring $F_2=$ The inward force $P_0A$ due to atmospheric pressure $F_3=$ The outward force $P'A$ due to pressure inside the container The force balance gives us $$kx = (P_0-P')A$$ Since $P_0$ was the initial pressure inside the container, the pressure $P=P_0-P'$ is the decrease in pressure inside the container relative to the initial pressure, not the final pressure inside the container.
{ "domain": "physics.stackexchange", "id": 94147, "tags": "newtonian-mechanics, thermodynamics, ideal-gas" }
Algorithm to find leaders in an array
Question: An element in an array X is called a leader if it is greater than all elements to the right of it in X. The best algorithm to find all leaders in an array. Solves it in linear time using a left to right pass of the array Solves it in linear time using a right to left pass of the array Solves it using divide and conquer in time \$Θ(n \log n)\$ Solves it in time \$Θ(n^2)\$ At the start the right most element will always be a leader. If an element is greater than our current_max, it will a leader. Add this element to leaders. Set current_max to this element and carry on leftward. Time complexity would be \$O(n)\$. Can you give an algorithm for another way or better way to find leader in an array? #include <iostream> using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size-1]; /* Rightmost element is always leader */ cout << max_from_right << " "; for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << " "; } } } /* Driver program to test above function*/ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; } Answer: First off this is a C solution there is nothing inherently C++ about this code. You just seem to be using the output stream. We refer to this as kind of code (in the C++ community) as C with classes. Note this is not a good designation. As C and C++ are completely different languages with different styles and idioms you should not write a piece of code for one and expect it to be good code in the other language. The fact that the compiler may compile it is just a historical artifact. You should remove one of the tags from question (Since it will not compile as C I suggest you remove the C tag). Since the question is tagged C++ I will review your code as a C++ program and point out why it is badly designed. Never do this: using namespace std; See: Why is “using namespace std;” considered bad practice? Useless comments are worse then no comments. /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) I don't need a comment to tell me this. The name of the function and its parameters are actually very well named. Restrict your comments to a description of why (the code describes how) and well named functions and variables describe what is happening. C++ code prefers to use iterators it situations like this. void printLeaders(int arr[], int size) The problem here is that it is so easy to use this incorrectly. Arrays decay into pointers way to easily. If you use the iterator interface this will prevent this happening accidentally. template<typename I> void printLeaders(I begin, I end) { // Code } // Calling: int arr[] = {16, 17, 4, 3, 5, 2}; printLeaders(std::begin(arr), std::end(arr)); // If you change the code now and accidentally cause the array to decay into a // pointer then the compiler will generate a compile time error. The current // code is way to susceptible to refactoring mistakes. // Also it allows you to use any container that supports the iterator // interface (which is all of them including built in array). You have forgotten to validate your input. int max_from_right = arr[size-1]; If the size is zero. Then this is undefined behavior. I know you are printing here. But that looks like for de-bugging. if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << " "; } You could just use std::max() to simplify the code. You should basically never use the built in array. int arr[] = {16, 17, 4, 3, 5, 2}; The container library contains several classes for storing a set of obejcts that are better. std::vector<int> for dynamically sized objects or std::array<int,size> for fixed size containers. Built in arrays are hard to use correctly. Passing them by reference the syntax is non-trivial. They decay into pointers way to easily. Getting the size of an array is obnoxious as you have to remember to plant the correct division that is easy to mistype (with no compiler checking). No need to return 0 at the end of main (its special). return 0; Normally in C++ you leave out the return value to indicate that main can never fail. If you explicitly plant return 0 here it is an indication that it succeeds but also a hint there are other return paths that will fail (so I start looking for other return statements in main())
{ "domain": "codereview.stackexchange", "id": 18053, "tags": "c++, algorithm, array" }
Run RGBDSLAM program computer configuration requirements
Question: I want to achieve RGBDSLAM procedures, but do not know the requirements of this program on your computer's performance.cpu, Gpu has what requirements?Or what is the minimum configuration? Originally posted by longzhixi123 on ROS Answers with karma: 78 on 2012-09-09 Post score: 0 Original comments Comment by longzhixi123 on 2012-10-18: @yangyangcv It seems that you have RGBDSLAM running success.I want to know your specific process in accordance with the method on the website, I always can not succeed Answer: well, the following is my computer's configuration: CPU: intel i5-2400 @3.1GHz RAM: 4G graphics card: ATI Radeon HD 5450 with this configuration, i can get about 10 fps Originally posted by yangyangcv with karma: 741 on 2012-09-10 This answer was ACCEPTED on the original site Post score: 1
{ "domain": "robotics.stackexchange", "id": 10963, "tags": "slam, navigation" }
What is the method for calculating the instantaneous angular velocity for an arbitrary 3D trayectory?
Question: I am working on a simulation of a point moving in an elliptical 3D trayectory as shown in the image . I wish to calculate the angular velocity vector of the motion . In this case I can't supose a single axis of rotation for all the trayectory because the orientation of the axis is changing every instant of time . Is there any method for calculating the angular velocity vector given the position at every instant of time ? Answer: It's not clear what you mean by angular velocity. Angular velocity is only defined relative to some origin, and even then you must specify the definition clearly. The usual definition is this: first, pick an origin. Let the position of the particle with respect to the origin be $\vec{x}(t)$ and $\dot{\vec{x}}(t)=\vec{v}(t)$. We can then decompose the velocity vector into a part that is parallel to the line from the origin to the particle and a perpendicular part. If $\hat{x} = \vec{x}/|\vec{x}|$ then $\vec{v}_{\parallel} = (\vec{v}\cdot \hat{x})\hat{x}$ and $\vec{v}_\perp =\vec{v}-(\vec{v}\cdot \hat{x})\hat{x}$. Then if we use the cross product to define $\vec{\omega} = (\hat{x}\times\vec{v})/|\vec{x}|$ we can always get the perpendicular part of the velocity back via $$\vec{\omega}\times\vec{x} = \vec{v}_\perp$$ where that equality follows from the definition of $\vec{\omega}$ and some cross product identities. Note that the angular velocity thus gives you information only about the perpendicular part of the velocity. The parallel or radial velocity has to be tracked separately. And, once again, there are other definitions of angular velocity that you might want to use, so think carefully about what you need.
{ "domain": "physics.stackexchange", "id": 44843, "tags": "classical-mechanics, differential-geometry, rotational-kinematics, angular-velocity" }
Pull, Tag, Save, Delete Multiple Docker Containers
Question: First time posting and first real Python program that I use fairly frequently. I needed a way to pull a large amount of containers, re-tag them, save them (docker save) and clean up the recently pulled containers. I did this pretty easily with bash, though depending on the container and depending how many containers I quickly did not like how slow it was and wanted a way to do it faster. I am looking to make any improvements possible, it works, and it works well (at least I think). I tend to always come across more Pythonic ways to do things and would love the additional feedback. Couple things that I am currently tracking: I need docstrings (I know, small program, but I want to learn to do it right) I tossed in the if __name__ == "__main__":, and if I am being honest, I am not confident I did that right. I know, I am terrible at naming functions and variables :( #!/usr/bin/env python3 import sys import os from os import path import concurrent.futures # https://docs.python.org/3/library/concurrent.futures.html import docker # https://docker-py.readthedocs.io/en/stable/ cli = docker.APIClient(base_url="unix://var/run/docker.sock") current_dir = os.getcwd() repository = sys.argv[2] tar_dir = os.path.join(current_dir, "move") if path.exists(tar_dir) is not True: os.mkdir(tar_dir) def the_whole_shebang(image): img_t = image.split(":") img = img_t[0].strip() t = img_t[1].strip() image = f"{img}:{t}" print(f"Pulling, retagging, saving and rmi'ing: {image}") # Pulls the container cli.pull(image) # Tags the container with the new tag cli.tag(image, f"{repository}/{img}", t) new_image_name = f"{img}{t}.tar" im = cli.get_image(image) with open(os.path.join(tar_dir, new_image_name), "wb+") as f: for chunk in im: f.write(chunk) # Deletes all downloaded images cli.remove_image(image) cli.remove_image(f"{repository}/{image}") if __name__ == "__main__": with concurrent.futures.ProcessPoolExecutor() as executor: f = open(sys.argv[1], "r") lines = f.readlines() executor.map(the_whole_shebang, lines) Anyways, I assume there are many things that I can do better, I would love to have any input so that I can improve and learn. Thank you! Answer: Global variables These: cli = docker.APIClient(base_url="unix://var/run/docker.sock") current_dir = os.getcwd() repository = sys.argv[2] tar_dir = os.path.join(current_dir, "move") probably shouldn't live in the global namespace. Move them to a function, and feed them into other functions or class instances via arguments. Command-line arguments Use the built-in argparse library, if not something fancier like Click, rather than direct use of sys.argv. It will allow nicer help generation, etc. Boolean comparison if path.exists(tar_dir) is not True: should just be if not path.exists(tar_dir): Pathlib Use it; it's nice! For instance, if tar_dir is an instance of Path, then you can replace the above with if not tar_dir.exists(). It should also be preferred over manual path concatenation like f"{repository}/{img}"; i.e. Path(repository) / img there are other instances that should also use pathlib; for instance rather than manually appending .tar, use with_suffix. Split unpack img_t = image.split(":") img = img_t[0].strip() t = img_t[1].strip() image = f"{img}:{t}" can be image, t = image.split(':') image_filename = f'{image.strip()}:{t.strip()}'
{ "domain": "codereview.stackexchange", "id": 38481, "tags": "python, beginner, python-3.x" }
Solving recurrences by substitution method: why can I introduce new constants?
Question: I am solving an exercise from the book of Cormen et al. (Introduction To Algorithms). The task is: Show that solution of $T(n) = T(\lceil n/2\rceil) + 1$ is $O(\lg n)$ So, by big-O definition I need to prove that, for some $c$, $$T(n) \le c\lg n\,.$$ My take on it was: $$\begin{align*} T(n) &\leq c\lg(\lceil n/2\rceil) + 1 \\ &< c\lg(n/2 + 1) + 1 \\ &= c\lg(n+2) - c + 1\,. \end{align*}$$ As this doesn't seem satisfactory I looked up a solution and the author after getting to the same stage as me decided to introduce a new arbitrary constant $d$: $$\begin{align*} T(n) &\le c\lg(\lceil n/2-d\rceil) + 1 \\ &< c\lg(n/2+1-d) + 1 \\ &< c\lg((n-2d+2)/2) + 1 \\ &= c\lg(n-2d+2) - c + 1 \\ &= c\lg(n-d-(d-2)) - c + 1\,. \end{align*}$$ And now, for $d \ge 2$, $c \ge 1$ and $n > d$, $$c\lg(n-d-(d-2)) - c + 1 \le c\lg(n-d)\,.$$ What I don't understand is how does it prove that $T(n) \le c\lg n$? Cormen et al. make a big point that you have to prove the exact form of the inductive hypothesis which in this case was $T(n) \le c\lg n$. They then go on to show example similar to one above. How is that the exact form of the inductive hypothesis? This doesn't seem to fit the big-O definition. When can I omit constants or cheat them away? When is it wrong? Answer: I am guessing that the book wants you to proof the stronger hypothesis $T(n) \leq c\log( n -d)$ which implies $T(n) \leq c log(n)$ is also true ( because $n \geq n -d$ for $d\geq 0$. )
{ "domain": "cs.stackexchange", "id": 5535, "tags": "algorithm-analysis, proof-techniques, recurrence-relation" }
Span decimal point precision
Question: In a JSP page I have a number of Span elements. Each of this span element will be floating point numbers. All these span elements has class "format-decimal-precision": <span class="format-decimal-precision">${info.flaot_val}</span> I would like to display all this floating point numbers with 3 decimal point precision. Example: 123.12867 should be displayed as 123.123 var floatFields = $('.format-decimal-precision'); var iter = floatFields.length; var mDecDisplay = 3; while(iter--) { floatFields[iter].innerHTML=roundNumber($.trim(floatFields[iter].innerHTML),mDecDisplay); } function roundNumber(num, places) { return Math.round(num * Math.pow(10, places)) / Math.pow(10, places); } Though the code is working fine, I would like to know a better program to achieve the same behavior. Answer: Styling and readability Your indentation is inconsistent. This can lead to developers wrongly assuming code belongs to a different block. I would recommend fixing this for all code. Your use of whitespace is inconsistent. You sometimes use a space after a comma, you sometimes do not. You sometimes use spaces around operators, you sometimes do not. Re-inventing the wheel Your function roundNumber is somewhat re-inventing the wheel. You are basically recreating the toFixed function with a cast back to a number. function roundNumber(num, places) { return Math.round(num * Math.pow(10, places)) / Math.pow(10, places); } function roundNumberFixed(num, places) { return Number(num).toFixed(places); } function roundNumberFixedAsNumber(num, places) { return Number(Number( num ).toFixed(places)); } function test(num, places) { console.log("== Testing with", num, "and", places, "=="); console.log(roundNumber(num, places)); console.log(roundNumberFixed(num, places) ); console.log(roundNumberFixedAsNumber(num, places)); } var testvalues = [["1.234567", 3], [" 1 ", 2], ["123512.2", 2], ["-55.2121", 5], ["13.223 ", 1]]; console.log("=== Starting tests ==="); for(i in testvalues) { test(testvalues[i][0], testvalues[i][1]); } You seem to be using jQuery. You can use .each (docs) to loop over all elements in an jQuery object. Similarly, you can use .html (docs) to change the innerHTML of an element. Termination of loop on referenceError You use a while loop without a way of terminating it. It actually terminates, because you try to modify the innerHTML of undefined. That's... silly.
{ "domain": "codereview.stackexchange", "id": 17669, "tags": "javascript, floating-point, jsp" }
Are units of force on prismatic joints Newtons?
Question: As opposed to newton-meters as shown in the 2.2.3 UI. In my case I'm using ROS Indigo and I have an EffortJointInterface with a mechanicalReduction of 1. when I echo the state for the position controller it has a command field I believe to be newton-meters when the joint is rotary, but is it newtons for prismatic? Originally posted by Lucas Walter on Gazebo Answers with karma: 115 on 2014-11-13 Post score: 1 Answer: As long as all other units you use are SI-metric consistent, then yes, it's Newtons :) Originally posted by hsu with karma: 1873 on 2014-11-18 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by Lucas Walter on 2014-11-18: Thanks! I also just did some physics experiments with primatics lifting loads against gravity and confirmed this.
{ "domain": "robotics.stackexchange", "id": 3673, "tags": "gazebo" }
What is the analysis of the Bell Inequality protocol in Cirq's 'examples'?
Question: This question is taken from https://github.com/quantumlib/Cirq/issues/3032. The "standard" protocol measures Alice's and Bob's qubits in different bases, while the one in Cirq measures in the same basis. I can't prove the equivalence of these seemly different protocols that violate Bell's inequality. Answer: The part you're overlooking is these lines: # Players do a sqrt(X) based on their referee's coin. circuit.append([ cirq.CNOT(alice_referee, alice)**0.5, cirq.CNOT(bob_referee, bob)**0.5, ]) The players rotate their qubits conditioned on what the local referee said. This is equivalent to changing the measurement basis conditioned on what the local referee said. The only relevant property is that the effective measurement bases start off offset by -45 degrees (mostly agree), so that a 90 degree rotation by one player gets you to +45 degrees (still mostly agree) while a rotation by both players gets you to +135 degrees (mostly disagree). The example sets up such a situation.
{ "domain": "quantumcomputing.stackexchange", "id": 1842, "tags": "programming, circuit-construction, cirq, bell-experiment" }
UVa Challenge Problem: 3n+1
Question: For anyone familiar with the UVa Programming Challenges website, I have started experimenting with some of the basic challenges. I was hoping to get critique for the code I wrote for "The 3n+1 Problem" (Problem ID 100). The run-time for this submission was 0.040 and my best submission was only 0.036. Looking at the scoreboard I have seen that many people have attained 0.000 runtime scores. I would really like some feedback for any/all of the following: My choice of "algorithm" C++ Implementation [code (re-)structure] How did others attain the amazing runtime scores? Math trick(s) ? To help with code readability: My code calculates the length of a sequence with compute() and stores the result in a table (vector of sequence lengths which is indexed by the value). Along the way, any intermediate values encountered are saved on a temporary 'stack', and when the final result is computed, all the values in the list are also entered into the table. For example, for compute(8) the sequence becomes 8 4 2 1. So, table[8] = 4; table[4] = 3; table[2] = 2; At the beginning of compute(), any nonzero value in the table causes it to return the length immediately. Besides reducing table size, and using a loop/goto instead of recursion, I can't think of a way to improve my current approach. For curious readers, before I implemented the intermediate value stack, my best run-time of 0.036 was from using this table approach but 'seeding' the table with values 1 to 200 before accepting user input, a la start(1,200). Thanks! /// The 3n+1 Problem // Consider the following algorithm to generate a sequence of // numbers. Start with an integer n. If n is even, divide by 2. If n // is odd, multiply by 3 and add 1. Repeat this process with the new // value of n, terminating when n = 1. For example, the following // sequence of numbers will be generated for n = 22: // // 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 // // It is conjectured (but not yet proven) that this algorithm will // terminate at n = 1 for every integer n. Still, the conjecture holds // for all integers up to at least 1, 000, 000. For an input n, the // cycle-length of n is the number of numbers generated up to and // including the 1. In the example above, the cycle length of 22 is // 16. Given any two numbers i and j, you are to determine the maximum // cycle length over all numbers between i and j, including both // endpoints. // // Input // // The input will consist of a series of pairs of integers i and j, // one pair of integers per line. All integers will be less than // 1,000,000 and greater than 0. // // Output // // For each pair of input integers i and j, output i, j in the same // order in which they appeared in the input and then the maximum // cycle length for integers between and including i and j. These // three numbers should be separated by one space, with all three // numbers on one line and with one line of output for each line of // input. #include <iostream> #include <vector> template<typename T = int> class BlackBox { public: BlackBox(T maxsize) : tablesize_(maxsize) { table_ = std::vector<T>(maxsize, 0); // Seed the table for values 0 and 1 // Note: 0 treated as odd=> 0: 3*(0) + 1 => 1 // Sequence 0 1 => length = 2 table_[0] = 2; table_[1] = 1; } ~BlackBox() { } void print() { std::cout << current_ << " "; } void printn() { std::cout << "\n"; } // compute the length of the sequence started from 'current' if not // found in the table, we will compute the sequence storing each // value on a 'stack' so we can update it along with the final value // sequence S=> // compute(S[0]) => length(S) // compute(S[1]) => length(S) - 1 // ... // compute(S[n-1]) => 1 std::size_t compute(T current) { std::size_t count = 0; if (current < tablesize_ && table_[current]) { //std::cout << "=> " << current << " "; return table_[current]; } // Not in table, increment operation count and // perform at least one operation stack_.push_back(current); count++; //std::cout << current << " "; // Detect odd (1s bit) if ((current & 0x01)) { // odd // 3n+1 current = 3 * current + 1; //std::cout << current << " "; // After performing an expensive 3n+1 operation // the number will always be even, so increase // count and perform divide by two operation stack_.push_back(current); count++; } // even // divide by two current = current >> 1; return ( count + compute(current) ); } // if compute() put anything on the stack, we will update the table // containing the sequence lengths // compute(index]) = table[index] void update_table() { T thecount = count_; typename std::vector<T>::iterator it = stack_.begin(); typename std::vector<T>::iterator it_end = stack_.end(); for ( ; it != it_end; it++) { T index = *it; if (index < tablesize_) table_[index] = thecount; thecount--; } } // find the longest sequence over the range [start, end] void start(T start, T end) { T index; maxcount_ = 0; if (end < start) { std::swap(start, end); } for (index = start; index <= end; index++) { current_ = index; count_ = 1; stack_.clear(); count_ = compute(index); if (!stack_.empty()) update_table(); if (count_ > maxcount_) maxcount_ = count_; } } std::size_t max() { return maxcount_; } protected: private: std::vector<T> table_; std::vector<T> stack_; std::size_t tablesize_; T input_; T current_; std::size_t count_; std::size_t maxcount_; }; // usage: ./100 // // on each line enter a range, n m // where 0 <= n,m <= tablesize // the output will be // n m MAXSEQLENGTH int main(int argc, char *argv[]) { // Table size for tracking (FULL SIZE) long long const tablesize = 1000000; // TODO: // Could consider splitting the table in half since // for even_num/2 => odd num // the sequence length is given by: // table[even_num] = table[even_num/2] + 1 // Potentially good idea? BlackBox<long long> box(tablesize); long long start; long long end; while (std::cin >> start >> end) { box.start(start, end); std::cout << start << " " << end << " " << box.max() << "\n"; } return 0; } Answer: This is overly confusing, and things are obscurely named. This is a one-off for a programming contest thingy, so it doesn't seem like it's that important. But I find that organizing my code well helps me think. You might find that's true of you. Also, you have several fixed sized tables that are very huge. Quite likely unnecessarily so as the short cycle lengths for large numbers indicate that most sequences converge rather rapidly on a common chain. Lastly, you keep a stack of values when no such stack is necessary because the problem description doesn't require you to print out what the chains are. And even if it did, a very slight tweak to the table contents would allow you to easily print out the chains by just following pointers with no stack necessary. There are other details that seem minor but are actually a big deal. For example, you create an empty vector, then assign it a very large table. This will create two copies of the very large table, and throw away the (rather minimal admittedly) work done to create the empty vector. Since this last is a very specific coding flaw, here's how it would be fixed: BlackBox(T maxsize) : table_(maxsize, 0), tablsize_(maxsize) { // Seed the table for values 0 and 1 // Note: 0 treated as odd=> 0: 3*(0) + 1 => 1 // Sequence 0 1 => length = 2 table_[0] = 2; table_[1] = 1; } Lastly, your organization is very confused. You make one class responsible for too many things. There is no need for one class to both handle finding the max value in a range and to compute the cycle lengths. But, while these issues are important, I can't see that fixing them is going to shave more than about 20% off your time. :-/
{ "domain": "codereview.stackexchange", "id": 1490, "tags": "c++, algorithm" }
regex to extract version info
Question: I have written a small Python function to extract version info from a string. Input is of format: v{Major}.{Minor}[b{beta-num}] Eg: v1.1, v1.10b100, v1.100b01 Goal is to extract Major, Minor and beta numbers. import re def VersionInfo(x): reg = re.compile('^v([0-9]+)([.])([0-9]+)(b)?([0-9]+)?$') return reg.findall(x) if __name__ == '__main__': print(VersionInfo('v1.01b10')) print(VersionInfo('v1.01')) print(VersionInfo('v1.0')) Output: [('1', '.', '01', 'b', '10')] [('1', '.', '01', '', '')] [('1', '.', '0', '', '')] Question is: Is it sufficient to cover all cases? Better regex? Answer: Compile your regexp only once. Doing it each time you call VersionInfo kind of defeat its purpose. You can extract it out of the function and give it a proper capitalized name to indicate it is a constant. Use blank lines to separate logical sections of your code, especially after imports and before functions definition. According to PEP8, function names should be snake_case and not TitleCase.
{ "domain": "codereview.stackexchange", "id": 19359, "tags": "python, python-3.x, regex" }
Gram-Schmidt Orthogonalisation for scalars
Question: I'm reading Chapter 11 (Normal Modes) of Classical Mechanics (5th ed.) by Berkshire and Kibble and came across this on pg. 253: The kinetic energy in terms in terms of the generalised coordinates is given by: $$T=\frac{1}{2}a_{11}\dot{q_1}^2+a_{12}\dot{q_1}\dot{q_2}+\frac{1}{2}a_{22}\dot{q_2}^2.$$ It is a considerable simplification to choose the co-ordinates to be orthogonal, and this can always be done. For instance, we may set $$q_1'=q_1+\frac{a_{12}}{a_{11}}q_2,$$ so that $$T=\frac{1}{2}a_{11}\dot{q_1}'^2+\frac{1}{2}a_{22}'\dot{q_2}^2 \,\,\text{with}\,\,a_{22}'=a_{22}-\frac{a_{12}^2}{a_{11}}.$$ A similar procedure can be used in the general case. (It is called the Gram–Schmidt orthogonalization procedure.) We may first eliminate the cross products involving $\dot{q}_1$ by means of the transformation to $$q_i'=q_i+\frac{1}{a_{ii}}\sum^{n}_{r \neq i}a_{ir}q_r. \tag{1}$$ From the vector definition of Gram–Schmidt $$\boldsymbol{b'}=\boldsymbol{b}-(\boldsymbol{b} \cdot \boldsymbol{a})\hat{a}$$ I'd expect something like $$q_i'=q_i-\sum_{r\neq i}^n\frac{a_{ir}q_r}{a_{rr}}. \tag{2}$$ Could someone explain where (1) comes from? EDIT Also, I noticed that the expression for the kinetic energy has the resemblance of the metric tensor: $$ds^2=g_{\mu \nu}dx^{\mu}dx^{\nu} \iff T=\frac{1}{2}a_{11}\dot{q_1}^2+a_{12}\dot{q_1}\dot{q_2}+\frac{1}{2}a_{22}\dot{q_2}^2. $$ so that $$g_{ij}=\frac{1}{2}a_{ij}$$ Does that mean it is possible to obtain (1) by a transformation to the rectangular coordinates with something like $$\frac{\partial^2x^n}{\partial \bar{x}^i\bar{x}^j}=-\frac{\partial x^p}{\partial \bar{x}^i}\frac{\partial x^q}{\partial \bar{x}}^j \Gamma^n_{pq} \to \frac{\partial^2q_n}{\partial q'_i \partial q'_ j}=-\sum_{p, r}\frac{\partial q_p}{\partial q'_i}\frac{\partial q_r}{\partial q'_j} \Gamma^n_{pr} $$? where $\bar{x}^i$ are coordinates in the rectangular system. Answer: You are misreading the orthogonalization involved. Your authors state clearly they wish to eliminate all cross terms involving $\dot{q_1}\equiv \boldsymbol{b}$ terms, where $ \boldsymbol{a}\equiv a_{12} \dot{q_2}+ a_{13} \dot{q_3}+ ...$ . That is, $$ \frac{1}{2}a_{11} \boldsymbol{b}^2+ \boldsymbol{b} \boldsymbol{a}+...= \frac{1}{2}a_{11} \left (\boldsymbol{b}+{1\over a_{11}}\boldsymbol{a}\right )^2+...= \frac{1}{2}a_{11} (\boldsymbol{b}')^2+..., $$ where the ellipses ... represent terms independent of $\boldsymbol{b}$. The bold symbols are not vectors. So the coefficient of the square of $\boldsymbol{b}$ is special and distinctly outside the definition of $\boldsymbol{a}$. (The authors remind you you could have started from any i instead of 1.) So (1) is right and (2) is wrong. Recall you have to modify the coefficients of all quartic components of $\boldsymbol{a}$ accordingly. I ignored the time derivatives for simplicity: you may remove them and reinsert them where appropriate. As for your differential geometric proposal, well, this is a rigid change of variables, and I, not sure what you'd be proposing. You might, instead, think of all this as the nonorthogonal diagonalization of a symmetric matrix.
{ "domain": "physics.stackexchange", "id": 76637, "tags": "classical-mechanics, energy, lagrangian-formalism, differential-geometry, metric-tensor" }
Securely hash passwords
Question: Since hashing algorithms isn't something to mess around with as a beginner. Several howto's explain that one should use already made solutions. Examples of such pages: https://crackstation.net/hashing-security.htm https://owasp.org/www-project-cheat-sheets/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 So I opted for ready-made solutions from java.security and java.crypto library packages. But I feel there is still room for messing up, especially with regard to the parameters in PBEKeySpec(password, salt, iterations, keyLength). According to some HOWTOs, salt should be as long in bytes as the output from the hash function. So I chose 64, since SHA-512 outputs (64*8=512 bits) 64 bytes. (Although, it seems I can get larger output simply by increasing keyLength argument above 512, which makes me wonder). So basically. Do you guys/girls find this code reasonable? Especially in regards to the arguments passed? If not, please tell me what to change, how and why. package my.application; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import org.apache.commons.codec.binary.Hex; public class PasswordHasher { private int ammountOfBytes = 64; private int keyLength = 512; private int iterations = 100000; private byte[] salt; private byte[] hash; private char[] password; private String saltHex; private String hashHex; public void hash(String rawPassword) { makeSalt(); password = rawPassword.toCharArray(); PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength); SecretKey key; try { SecretKeyFactory generator = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); key = generator.generateSecret(spec); hash = key.getEncoded(); hashHex = Hex.encodeHexString(hash); spec.clearPassword(); key = null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } } public void destroy() { saltHex = null; hashHex = null; Arrays.fill(password, (char) 0); Arrays.fill(salt, (byte) 0); Arrays.fill(hash, (byte) 0); } private String makeSalt() { try { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); salt = new byte[ammountOfBytes]; random.nextBytes(salt); saltHex = Hex.encodeHexString(salt); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return saltHex; } public String getSaltHex() { return saltHex; } public String getHashHex() { return hashHex; } } Answer: There are a few things wrong security wise before we even get to the parameters. private char[] password; Storing the plain text password in an instance field makes it discoverable from memory dumps for a considerably long time. There is no need for the field to be an instance field since it is only used in the hash method. public void hash(String rawPassword) { Passing plain text password as a String parameter makes it impossible to be securely disposed of. When being passed around, passwords need to be char arrays and they need to be cleared immediately when they are no longer needed. public void destroy() { You have the right idea that the class needs to be cleared from sensitive data, but here you have made the clearing the responsibility of the caller while the data needing to be cleared is completely irrelevant to the caller. You should avoid having to rely on other people when dealing with sensitive data. Someone will forget to call destroy() because it is not something that needs to be done in a garbage collected environment. At least you could make it Closeable so there is some common contractual indication about the class needing cleanup. Because the method also clears the actual payload it is guaranteed that the sensitive data will be in memory as long as the payload is needed, which is much longer than the sensitive data needs to exist. But it's better to write the class so that it doesn't need external cleanup at all. private int ammountOfBytes = 64; private int keyLength = 512; private int iterations = 100000; These should be static and final constants, since you don't have any means to change them. private String saltHex; private String hashHex; These are the only fields that have a information that needs to be kept for a longer period. Instead of wrapping all the fields into a same PasswordHasher class, you should put these two fields into a dedicated data class called HashedPassword, have all the other code be static utilities and have the hash method return the data class. If we look at the naming, PasswordHasher implies that the class is an actor that implements an algorithm. Your implementation uses it as both a data container and the algorithm. It is better to separate the responsibilities to two different classes (single responsibility principle)
{ "domain": "codereview.stackexchange", "id": 37389, "tags": "java, security, hashcode" }
What is an example of a system with non-vanishing topological entanglement entropy at finite temperatures?
Question: In this paper: https://doi.org/10.1088/1367-2630/14/3/033044 it is show that for Kitaev toric code looses topological entanglement entropy over long times if it is thermally opened. What is an example of a system which does not loose topological entanglement entropy over time at finite temperatures? Answer: The Toric Code in four space dimensions is thermally stable. (The excitations are loop-like, rather than point-like, and possess a tension, and thus tend to stay small.) Some references: https://arxiv.org/abs/0811.0033 https://arxiv.org/abs/1411.6643 : Section V.C and references therein.
{ "domain": "physics.stackexchange", "id": 69193, "tags": "quantum-information, entropy, quantum-entanglement, open-quantum-systems" }
Convert image into ASCII art
Question: I made a python script that takes an image and converts it into an ASCII-art representation and saves it as a .txt file. The logic is somewhat simple. It resizes the image to a manageable size, converts it to gray-scale, takes the value of each pixel and assigns it a character according to it. Then appends the characters to a string and wrap it to the number of pixels of width. Can this be improved in any way? Does it follows conventions and best practices? import PIL.Image image=None def closest(myList, myNumber): from bisect import bisect_left pos=bisect_left(myList, myNumber) if pos==0: return myList[0] if pos==len(myList): return myList[-1] before=myList[pos-1] after=myList[pos] if after-myNumber<myNumber-before: return after else: return before def resize(image,new_width=300): width,height=image.size new_height=int((new_width*height/width)/2.5) return image.resize((int(round(new_width)), int(round(new_height)))) def to_greyscale(image): return image.convert("L") def pixel_to_ascii(image): pixels=image.getdata() a=list("@$B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]) #remove the slice to get light mode pixlist=list(pixels) minp=min(pixlist) maxp=max(pixlist) vals=[] lst=list(range(minp,maxp+1)) def chunks(lst,n): import numpy as np return np.array_split(lst,n) lchunks=list(chunks(lst,len(a))) for chunk in lchunks: vals.append(chunk[0]) avals={vals[i]:a[i] for i in range(len(vals))} ascii_str=""; for pixel in pixels: ascii_str+=avals[closest(vals,pixel)]; return ascii_str if __name__='main' path=#drop your path here image=PIL.Image.open(path) name=input("enter the image name here: ") image=resize(image); greyscale_image=to_greyscale(image) ascii_str=pixel_to_ascii(greyscale_image) img_width=greyscale_image.width ascii_str_len=len(ascii_str) ascii_img="" for i in range(0,ascii_str_len, img_width): ascii_img+=ascii_str[i:i+img_width]+"\n" with open("{}.txt".format(n ame), "w") as f: f.write(ascii_img); print(ascii_img) Answer: myList should be my_list by PEP8. Add PEP484 type hints. from bisect import bisect_left should be moved to the top of the file. I think it's clearer, rather than image.getdata(), to just use the np.array() call on the image file. That way you can min and max on it without converting it to a list. I don't see a lot of value in defining a local function chunks that you only call once and has only one line (the import not counting; that should also be moved to the top). avals should not use a range, and should just zip over the two sub-series. You should extract from your main code a conversion function that neither prints nor saves to a file. Suggested import PIL.Image from bisect import bisect_left import numpy as np CHARSET = ( "@$B%8&WM#*oahkbdpqwm" "ZO0QLCJUYXzcvunxrjft" "/\|()1{}[]?-_+~<>i!l" "I;:,\"^`'. " ) def closest(my_list: list[int], my_number: int) -> int: pos = bisect_left(my_list, my_number) if pos == 0: return my_list[0] if pos == len(my_list): return my_list[-1] before = my_list[pos - 1] after = my_list[pos] if after - my_number < my_number - before: return after else: return before def resize(image: PIL.Image.Image, new_width: int = 300) -> PIL.Image.Image: width, height = image.size new_height = int((new_width*height/width)/2.5) return image.resize((round(new_width), round(new_height))) def to_greyscale(image: PIL.Image.Image) -> PIL.Image.Image: return image.convert("L") def pixel_to_ascii(image: PIL.Image.Image, light_mode: bool = True) -> str: pixels = np.array(image.getdata()) direction = 1 if light_mode else -1 charset = CHARSET[::direction] minp = pixels.min() maxp = pixels.max() lst = np.arange(minp, maxp+1) lchunks = np.array_split(lst, len(charset)) vals = [chunk[0] for chunk in lchunks] avals = dict(zip(vals, charset)) ascii_str = ''.join( avals[closest(vals, pixel)] for pixel in pixels ) return ascii_str def convert(path: str) -> str: image = PIL.Image.open(path) image = resize(image) greyscale_image = to_greyscale(image) ascii_str = pixel_to_ascii(greyscale_image) img_width = greyscale_image.width ascii_str_len = len(ascii_str) ascii_img = "" for i in range(0, ascii_str_len, img_width): ascii_img += ascii_str[i:i+img_width] + "\n" return ascii_img def main() -> None: ascii_img = convert('archived/image2l.png') name = input("enter the image name here: ") with open("{}.txt".format(name), "w") as f: f.write(ascii_img) print(ascii_img) if __name__ == '__main__': main() Output IxL00QOqW%Q)I... . . .``',~tCd****#MW&%%%%&*d0c/?~<i!I;;:,""^`'``'....'...'''````^`'... ....'' .'`'. ln0ZOQ0wMBO\!'`` . ..`:~(vma**o*#W8%%%BB%MdUr([-+>!I;;I;:,"""^'''```````^^^^"^`'`'''''.'' .'''. ;xQZOCQm#8Zti'`' .'^^;+\Uq*M##*#MW8%BBB8*pUf([_<!I::,,,,,^```^"^^^^`^^^^^``''''''..'` ..... IrQqwQ0wMBwj>',". `"^^:~|cZk##*ooM&8BBBB8#pUt}?+<il;:;I;:"^"","^^"^^^^````'``''. '` .''. . ,\UqpO0m#Bqri."". ....'`^``,<(vmoWWM##W8%BB$$8bCr([_<illI;:"^^^^^^","^^^`````````. '''... .'''. ")XdkmZq#8dc+'""'. .'^^,<(Xqa####M&8%BB$%MdUj1-<>>!I,^```^^^"^^`''.''.'''. `^`'.. ....''. .. . ^{cpkmmqo#mn<',,. .. .^,,,;~(u0kM&WMMWW8%BB8a0u|}-<!lI;:,,"^`^^````. .'..`^`' .''.....'. .. . ... .... ...... ^1cqdOOwkaOx<`,". . .. .`"I!Il</Qa%8M*o#M&%B%8Ma0v\[+<ilI;:"",,"^""`'..'''..`^. .... .``'.... .... .. .. '_xmpQ0w*&qu+^;: ..''. `,;li]fO&%&8888WW8%%BB%8owv([_~>!;"""``^^^``^^`'`^'.....'. .''.. ....''..`^,;l>+{|frxnnuvr\{_l"""^`. 11{{1)))1}]?---__-___-_1uZ**pqbW$#mzft\(1}[[[})|/rcCOJj?"`' `;-fLaaaWB$$B%%%%8W&%BB*qUx\[++?}1|/tfjxuvvvvxjf\}_<iI:"```,l<-]]-<;^"I+1fvYJLQ0QLQQCUXzzzzUQO0LX\+:`'. .. bbbbdddddpppppppdbkaahhaoo**oaa#&W#abbdddddbkkkbbkk#$#C|;,,' I|L*ada#MWB$$$$%8&&W&%B8MkZCOpqwZ0CYczYcxvYUC0wkbmX|{1\xcJOZQLQLJLOmwqqZ0CXuxxf/|)1{}[]][][\vmakOx(1{{]+!:^'''.. . bbbbdppppdbbbdbkbppqpddpqwmmwZOmqqwwwqqqqwqqwwZOOZmdobL\:^^. .. . I\O8MbbkbkoM%$$$$B%&W&8$$$&hq0Yurt|))))1{{{11)|xYmbhbwwm0Jznt//|(fzZbkqzf/|){}}}{{[[[[[[???)rUZqq0LCL00Q00CXr(]>:^..''......... 00QLLQ000OOZO0000QQLLLQQQQ00OOOOO00OOOOZZOZmZO00OZwdhbOf!::`. !jm&Waaakka#B@@$%88B$$8#bOYnt|(()1{}}}{}}{11{{|uQbkqCnf\||()}[{{1}}(/jf)}{}}[[[[[[]]???]]]][[{1111{{{1)\/jcC0ZZJj}!:,"^```'.....''...... mZZOOZZmmmwwwmmwqqqpddbbkkkkhhahkbbkhbddppqwZZZmmwmqbdZfI,:`. ijw%Wao#&8&Wokq0COd##qJvj/()}]??]]]]]]]][[]--1fzYcr|1}[][}{{[]]][[][[[]--][[[]]]]][[[]???]]]][}}[]]???--][]?])uCwC/_;^```^`..``^`'''... ... #######MMMMM####MWWWMM#*********oaao**#W%B8#bmqdpqmmppZt,`"' !fm%8M%BWk0XnjfnYwkOzt()))11}[}}}[[[[[[}{}]???]]]??]][]?][[]???][]]]]]]??]]]]]???]]]]??------???????--????]]?-+)zQ0u}i,^^^^.'^"^``..`````''''.... . . .. . pppqwwwwwwwmmmwwwqqwmmZZZZZZOZZmmZZmmmqb*%B8awqpqmZmdp0/,^,` !fw$@@8oLuf\\||cmmLx|()1{{}]]]}}[]]][]]]]]]]??????]]]]????[}]]?]]??]]]]]][[]???]]]?-------???????????-?]]]?-]?__?tC0Ct~I:"^`````''..'''''''............................ ..... zzXXzzzXXXzccczXYUJJCCJUUUJJCCLLLLQ0OOZqhW8&hwqqwOQ0mqZjI,:`. . ixp$@&pUx/|){{(tj/(1{11}}}[?][[]]]??]]]]][[11[?????????-??]]]?-__--???]?]]??---?????----?]]]]?????]]]??????---]?~?\YqOc1lllI:"`'...''```````'''````'..'''''''.''''..'''..................... ... .... czzzzccczzzzzXXXXXYUJJCCCJJJCCLLQ0000Zwpa&8&apqqZ0LLOmZf:":^. .,>}jXZ*BWpXff/)}[[}}[]???-?[]?][[]???][[]]?????]]?---------?]]?-??--_--??]]]??-------??]]]???]]]]]???]]]]?]]]]--]}}}}[[\cwokwOQCXx\}+!I::,,,,,""^^```^^''''''''''''..''''''''''``'''''''.'........... YYXXXzvccXXXzXXXYUUYYUJCCJJJCCLLLQ00OZwdo&%8aqqqmOQQQZZj;,;"'. .. `l?jXUUXux0#kLj1))1{}[[]]???--?[}]]]]]]]??]]]?--????????????????--?????--??????]]]]]???---???]]]?--????--?]]]????????][[]]]][)/jxrxzJ0wqOYj1~!lI,"^^"^`^^^````'''`''`^'..'```''````""^`^``''''....''.'''. UYXzzzzczXYYYXXzXUUYYUUUYUCLLLLLLLQ0OZmpa&%8aqqqwOCJLZwx!;I"'. ."-fJmLzj|11|cZJr([}{}[]]]]??]???]]]?]]]]]]???]]?--??????????????-------????]]]??-????-----------???----???--?]????]]]]??]]??----?]]]?_-}(fcLZZJn1~l;:::"^""^^""^^^^^^`^^`'```^"^```'`^^^``'''...........''....... . JJYYXXYYUUJJUUYYYUYXYYUUUUJJJCLLLLLQ0Omqa&%8hmmmZ0CJQwpxI,:"'. `?nLZUr)[{{[]]}1}]][[[]?_-]?--?--]]??????]]?--?]??---????????????-------??---????---???-----------????---?]?????????][[]]]]]]?--?[}]??][[[[[?]|nJOOLct?>!I:;I;:,"^^^^^^^^^`''''`^^'````^""^`'''..... ....''......... ...... JJJUYYYUJJUUUUUYYXXYYYUUJJJJJCCLLLCLQ0Zwh&%&hmZmZ0CJLZmj;,;"'. I|YwLx([}}]][[?][[[[[??][[]]??????[]??]]?????--???-__---??????--------------__----??]]]????????????????--?]]]???]]]?-?]?-___-----?][]???][}[??]??](nCqmX\~!!ll:,::,","^""""^````^"^```''^^^``'''..'.. ....''''''........... JJJJUJJJUYXYYYYYXXXYYUYYUJLLLCCLQLCLLQOwa8%WhwwmZOQLQZmj:^,^'. ^<jqpJx()1{}??[[?][[[[[??][[]--?--??]?]??-_-???---??-__----???-------------??-__-------?????-------????--_--?----???-----__--??-___?]]?----??][}{{}?_+{rJwz]>!lI;:;:,,:,"","^^```^""^^^^``^^''''`''''.....'.''''''''''........... CCCJJCLCUYYUUUJJJJUYUUYYYJLLCCCLQLCLLQOwh8%WappqZ0QQOwqr;`^'. ';}nm*Mmx/|()){[]][}[?????-----_-?]?-????]]?-------_----__-------------_______---------___-???-______--???-_________-----???------_____------??-?]\vC0Xx/|/Ya0(+i;:::;:,,""^"""^``'`^^^^^^`'`^^``^^`''``'''''''''``````'''''''''```` LLCCUJJJUJJJCCCCCLCJJCUYUUJJJCLQQLLQ0Omqa88MhpqmZ0QLQZZf,'^. .. 'l|vzUOqpU\)(1[[[]???]]???????]??---???-_--------_____---------___-------___+__------___+____--??--_-???-?????--__+____--?-___-----------_+-?-------+-/XmpCcnQWm)<lII;;II;:,"^"""""^```""""^``^"""""^`'`""^```````^"""""^^^""^^`^^^^^^ CLLLCCCCCCCCCCCCCJJJCCCJUUCCCLQ00QQQ0Ompo8&obqwmZ0LL0ZOt"'`. .+fUCx/\/t([}{[]]??????????????????-???????---_-??------------?-_++___--------___------_____----?????]]]??-?????--------_________---------___---?--?[]-+]x0baddbX}+<!IllI;:,""",,,,,,"",,,"^``^,,,,""""","^```^,,"""""""^^^",,,"^"",::: QQQQLLCCCCLLLLCCCJCLLLLLLLQLCLQ000Q0OZwpo%8*bqwmOQL0wmL('."`. `ijJvt({[?--?[[?-]]??????-?]]??-?????????????-_-?]?-----?????????-___--------_____-------__---?????????]]]??]?----------______---------________--?--?[[[_+?/Qa&bu1+~_<!I;;;:,,,,,::::::::;;;:,,,,:,,:;I;;;,"""^";II;,"^"""^^":;I;::::::: QQQQQQLLLLLLLLCJJJCLLCCLQQQLCLQQQ00Zmmqd*B%*kpwmmZLOdpC1 .,' `-rYUt}{1}[}]??]]??]]]????-??]]?-?????????????----??-------????????]]]]]]????-____---???-------?]???????-??]]]?---???????----___---??????----??-__??-?]]]]]+-|XhhCt+<+ill!I;;;:::::;;;;;:::;;::::::,,:;;;IlI;;:::III;;;;II;;;;III;;;I;;;; 00QQQLLLLCCCLLCJUUJCCCCCQQQLLQ000OOmmwqb#$8adwmZZ0COapX[ ',' :[vOUj)}))}[]]]]]-_-?????]??????????--???--__????-__-----------------????]]]]?????????]???------???--???---??]?-____---???????-__--?]]]]]]?????--??????-???-??_(YpoQ1+<!l!!II;;;;;;;;;;IIII;::,",:::,,:I;:;lIIIl!!III;:;l!!lllII;,,":;:,,, OO000QLLQLLLLLLLCJJCLLLQQQLQ00OOOOZZmmqkM$&hdpwZZ0CmMpr~.'"' >jUCj[}11{]?]]]]]?-----??]]?????????---??--_--???-_+_---____-------__-----------__?]?]????--------__-?]]]]?]]??--------????]]]]????]]]]]]?-------------?????]]])rZB8qz\[+~<!lllII;::::;;;;:::::;;;;;:;;;::;Il!!!lI::;;:::IIII:,,,"",,:;;;; OOZOO0Q00O0QLLLLCCCLLLQQQQQ0OO000OZZmZwkM@%obpwmZOCwMw/i..'. `{YUu|]{1[?-??][]]??????]]]]]]]]]?---_-????????--__++_------_____----_----??---__+__-_____--???--____-??]]]]]???------??--?????][]]???????--__----???????]]]]?--](UW$8bJt[_~il!llI;;;;;;:,:::;;;;I;::;I;,:IIII;;;::::;;II;II;:,,,,,,,:;IIII ZO0OOOO00QLLQ00QLQQQLLLLQ000Q00OOOZmmmqbM$%obqwZ0QLqWq\i' .:/ZJt)}11]----?]?-__-??]??]]??????-----?????????----____-???--____-?-----??????????---------?????-_+_____--------__---??????????]???---????----?????]]]]][[[]]??}\U*&*aqj+~<!llIIIII;;::::I!!llIIIIIIIII:,::;;;;;;;;;IllI;;I;;::::::::;Illl ZZOOOOOOO0QLQ000QQQ0QQLLQ000000OZZZmwwqd*$%*kqmO0QCwWpf+^ `(0Ln|[[[?-___---__--???---------______-----??????]]]?-----???----------????????]]]----------__________________--___-------?--????-----????-------------??????]?1jCbakobx~<<>i!llIII;;;IIl!!!llIll!!!lll;;Ill!!!llIII;;;;:;;;::::::,,,::;;; ZZZZO0QOZZOQLQQ0QLQ00O000OOOO0OZmZZmwqpdo%8#kqmZZ0UZMpr+' -zCYf}}}]-___----????????---------????????----------??------?]]?--_----______---??-_--------??????---_______-------______--?????--------??------------??????]?-?1\fYmdmti><>i!!lll!!llllll;IIIIll!!lllllIIIll!!llI;;;;;;;;;::,,:::,,,,:;;; ZZZZZO00000QQ000QLQOZZOOOOOO00OZmmmmwqpda88MkwmmmOJmWdr~ . . itYLx1)(}]??]][]?---?-??????-----???]]]]??--________-??------?????-????--______---___-----____------___________________---------_____--????---------????????]]]-~_{zbqY)!!!IIIllI;;;;;;;;;;IlI;;;;;,,:;!l;;;;II;;::;;;IIllI;:,:;;;;;;II;;; ZZZZmZZZOO00000QQQQ0OOOOZZZZZOOZZmmwqqpdo&8WkmmmmOCw&bx_'.`. I)Ywc))1[????][[[]????----______----?????-----_____--?------------????-----___--?----????---____-____________________--??--____--_-__-----_--------??--??---???-+1vqWO\->iii!lI;::;;;;II;IllII;;;:,"",:;;IIIIlIIII;IIllllIII;::;;;;IIlIIII OOOOOZmZZ0QQ00000O00OOOOOOOOOOOZZZmwqqpb*8%&hwmmZ0CZMdn?^.'. "_vwz(1{[?---?][{[]??_______----?????????]]]??-____--___--------___--_++++++++__--------_____________--__-??--?--_____----__++-[?------____-?--__-???-----__?}1)(zhowx_<<i!!l;::;;;;;;;IIIII;;;Il!!lIII::I;:l>ii>>>i!!!lII;IlI;IIIIIII;::: ZZmmZZZO00QQQLQ0OO0Q0OOOOZZZZZOZmwwqqqqdo8%8aqwwZ0Lmoqu?. ... ;1Xwc1[]??--???][]?----????????????????]]]??-__+______-----------______+++_---____--_+++++__-______+______--__----___++______+-]?_______----------???-------[\zOb*#Of[<<~illlIIl!ii!lllllIll!lllliiiiii!i>!I!>>i!!l!ii>i!!lIII;:;I;:;IIIII ZZmmmZOOOOOZO000OZO0OZZOOZZZZZZZZwqppppdaW%B*qwwmOCZopu?. . `1CQYf{{{[?---???]]?-_----------------___--___++++__---??-______-?---?-___--?????-________--------_______________---__+++__--___---------__---??---???---??---(UphZr{~<~>lI;;;;Il!llIIIl!!i>>>i!!>~+~<>>><~<<>><~<>!iii!ii>>>ii!I;II;Il!!!! ZZZZOOZZZOOOZZO0OZO0OZZZZmmmmmmmmwqpddddhM%$*qqqmOJOapc]..^' ^+udC\)111[??--?]]?]]?-??????----------____--_____-?????---______--???--__---__-???-+++_----_______--__-_______+__----_____---____-?-__-]1||1[-?]?-???----????-(JZJtl,!!!!lII;;IIl!!!!!iii!i<<>i!!i<<<<<<<<~+_++~<>ii!!!ii>>>>>>i!!!!!ii!lll qqwmZZZZZZOZOOOOZZZOZZZZZmZmmmmmwqppppdbaM%B*qwwwZLZapz[..^' >nL0n[}1}?]]]]?][]?????]]]]]?]????------__--???------?-___--------___---???--___--??__----------__-------______+__??-__-????-------?-_---\CCu/}]]?????----??-?|zb*qJrtt////tft//ttffrncYCLQ0OO0QCCCLQZmqqmZZmmZOO0CJJYzvxf\(()1{}{{{{}[[[]]] qqwwmmmmZOOOZZZOOOOOOZZmmmmmmmmwwqpqqqpbaM%B*qqqmZ0mkdC(^`"' -LOXj{[[?-]]?--?]?????]]]]]?????---?-??-_+__----____---__------??--_---]]]?-_+_--])tnx1?-_+_-____++------_-?---???][{1)}]?????????--____+|L0zf1[[?-?]]]?]]?]1j0hohpph*W&&#ahhbdpddbkkbkkkkbbkkkao*#MM*oabpwwwqqqkoaaoM%%&*hddkahaoooooaaaaaa mmwwwmZZZZZZmmmmZOO0OZmmmmmmmmmmwqpppqpdh#%$#pppwmOmkkZfI"^' ]O0x|{}[-_??----?----?]]]]??????----???-_++______+___--______________++_---_++__+_)vaaj??--][{1}]--_--_-)jcXf1[???[tzUXf1{}]?]]]?_--??+-|vmQr([][???]]]]-_[/YpMMqCXzJZhMMdO00LCCCCLLLCJUUUYYYYXYJCL0O0QLCCCJCCCCLCJYYJObM%@@$%Makbbbbbbbdppp mwqqqwZZZmmwmZZmZZOOOOZmmwwmmmwwwqpqqwqdh#%@#ppqwm0wahZj!:,' .)pwx|}}[?-??--??----?]]]????????????------?????---------______-----__------??-?]++|X*oj-_?1xJCXf)1}--}\nUQJu|[}]_[/UdZz/}}}[[][[]?---}/vQ0Ux)}}]--?---]1tzOk#Mkw0Q0QJOkoaOYJCCJUUUUJJJJCCCLLLCCCCLQQQ0QLLLLLLLQ0QQCJJUYJ0kWMhwQLLLCJCQOOQLLL mwwwwmZZZmwwwmZZZmmZOOOZmwwwmmmwwqpqqqpbh#%@#qwmmOLZabJ(,^"' .(bm/1{[?--??????----?]]]???????????----_+_____+++__------_____-----__-???----___]|YqbOt}1jJwpUt1]?]{tU0OYf)]?-_-[j0pwu[?]]???]?-__-1rUOOYx({}[]-__?1\rUp*8&opO0QQLCUYZohmYuXJJJUUUUJCCLLLQQQLLLLLQ0QQ00QLLLLLLQ000LCCCCJCp#aqQJQQLQQQQQQ0000 wwmmZZZZZmmmmZZZOOZZZZmmmmmmmmwwqppqqqpbh#%@MdwZZOQmodX1:,:` .(kwt)1]-__??--??----?]]]????????????-----??]???--_____---__++_----______+___+~+[x0bdz/1/YmkOn|})\fvOqmYt){}[?_+1u0dLf}+?[-_-?}{)fcQqdwUnt|()(\juXUQqh#MMadwOQQ00QLJUJw#amJzJCUUYYYYJCLLLCCLLQLLLCLLLLLQQQQLCJCLQOO0QQLCCQd*hqO0OOQQ0QLLLQQQQ ZZZZOOOOZZZZZZZO00OOZmmmZZZZZZmwqppqqpdbh*8@WkqZZZOqapY(I,,' ^/opf1}1)[???----?---?]]]]???????----???????----_+++++_--__+++__---_++_-_+~~_{fUd*#bZLQp*&#dLzYLOmdqLv/{--?-]1tYmahOzjnzvnnuzUCJULZb*M#kpppqqqpdhooabpmOQQ000QQQQQQLLLq*odOCLQLLLCJJJCLLLCCLLLLCCCLLQQLCCLQQLCCLQQQLLLLCL0dapOLLOOQLQLLCCCLLL ZmmmZO0OOZmmZOOOOOZZmmmmmmZOOZmwqqqqqqpbh*%@&adwqwmqapY(;``. .}mwc\[}{}]]]?--???????]][]]??----?]?---__++++______+__---_--??----_-----[|xJ0O0CYzccunucYYXU0bMMawJr/fjxvzUL0Zwm0CUUUJJYcvnrt\)[+>?/UqbbwZZOQQQLLLLCCCLQQQQQLLLLLLLCCmhbw0CCCCCCCCCJCLLLCCLLCCCLLLLLCCCLLLLLLLLLLLLQQQQQOdap0CJLLLLQQQ0QLCCC wmmZZOOZZmmmZZZZO0OZmwqwmZ000OZwwwwqqqpdh*8@&hqmqqZqadC|;""`. <uCUj}}1{}[]]]]]????]]]]][]??---????-_______________---____-??-__+~+-[\cQZ0Xj1+!lllI;::;I;;I!+}|fnzUJUYzcnj\1-<!llllllllIIIIIIIII;:;~(z0ZOCJCJUCQLCCCCCLLLLLCCCCCCLCUQpdpOCJCCCCCCCJJCCCJJLLLCCCLLLQQLLLLLQQQQ0000OO0QQQOk#dQCCLQQQLLLQQLLLL wwwwmZZZZmmmmZZZZZZmmmwwmmZOOZZwqwwqqppdko8@8odqppmqabQ/l,:^``. 'l1r/[[[]?-??]]???????---???-__-????]?--__----__------??----?]----[\nYJXr)-<ii!lllI;IIllII;;IIIIIl!>>i!lllII;;;;;;:::;;;;;;;;;;;;;;:,:<)zOpwLJUJLLLQQLCUJLLLLLCUUJCJYLqhhZJJCCCCCCJJJCCCJJCCCLLLLLLQQ00QLCQ00QQQQ000QQQQZaWdQLLQ00QQQQQLLQQQ wwwwwwwmZZZmmwwmZZZmmwwwwmmZOZmwqwwqqqpdbaWB8#kppqmpabL/l::`.. ^</Xr[?]???????]]]]??------__---??]]????_--------????---????]]_+?tU0Lu(_illllI;:::;;::;;;Il!!lIIIIIII;;;;;;;IIIIIIIIIII;;;;;;;;;::;;II:;</QqmQYXXJLLLLCJLQQLCJCLCCCJYQphhOUJCCCLLLLLLLLCJJJCCLLQQQ000QQQQQ0O0QQLCCLQ0000ZhMqCJCLQ00QQQLLQ0QQ mmwwwwwmZZZZmwwwmZZOmwwwZZZZZZmmwqqqqqqdbhMB8#bwqqZwkdQ\;,;^' ,]fct_?}}}[]???]]]??----?]?-???---??---------------??----?]?+_[tUQJj-il!!I;IlI;:,,::::;;;;:;;II;;;;;;II;;:::;;III;::;;IllllII;;;IlIIlll;,l[uwwQYcYCCCCCLLLLCUUJCCJJUYQphk0YJCCCLLCLLLQLLCCCCLLQ0000000Q000000000QQQ00QQLQd*qCCCQ000QQQQQQQQQ qwmmmmmmmmmmmmmmmZZOZmmmZZmZZZmmwqpqqwqdbb*%%WbZwwZmbpL(``;,`' ,?fXr}{))1}[[[[]]?????????]]??????--------___--------?--?]__-|YQCr?i!!i!llI;;;;;;;;;::::;;:::::,,;;:;III;:::::;;;::::;;;IIIII;;;IllIlllII:,+fCqOJUUJJJJJJUUUUUYYUUYYYLwkh0zJLCCLCJJJCCCCLLLLLCLLLLLLLLQQLLLLQQ0000QLCCCLOb*dOLL0O00QQQQQLLLL mwwmZZZwwwmmmwwmmZZZZZmmZZO0OOZmwqqwwwqdbk*&%&kmqqOZdqJ(^'"`. "_jJu)11[]??]]]??---??-__--??----__-?]]]----____________-?_}rY0z}>l!i!IIII;;;;;;::;;;;:::::::::::;;::;III;;:;;;:,::::::;;;;;;;;;IIIIIlII;:::I)XZqLXYUUUUUUUYYYUUYYUYXU0pbQzUCCCCCCJUUUJCCCLLCJJJCCLLLLLCLLQQQQQQQLQLCCCLObodOQQ00QLJCLLLLCCC wwwmZmwwqwwwwmmmZZZmZZmZZO00OZmmwqqwwqppdkoM%8bOwqZwkpC(^^;` .:(Jc|{]+~_-?----__----__------------???--___---__++++_-++?/Q0j[il!!lI;;;;;;;;;:::;;;;;;:::::::;;;;::;;;;;;;;;::,,::::::::::::::::::::::;Il;:I-vqqZJXXXUJUUYYYXXzzzXXCZqqCcXUJCCCCCJUUJJCCCCCCJCCLQQQLCCCLLLQQQQLLLLLCCLOpbZCJCLLCJJLQQLLCCC pqwmZZwwwwmmmZZZZmmmmmZZZO0OZZmmwwwwqpppdbaM%%bOwwZmdqC)`"l^ .. .-cJXf1{}[]]]?---??]]]]]??---------???-__-----_____+++++]tzLz]!iii!l;;;I;;;::;;;;::::::;;;;;;;::::;;:::;;;;;:::::;;;;;;;;;;;;;;;:;I;:::;;;Il;;]j0pLXccXYYYYUUYXYYXXYQpdwCzYUUUJJJJJJJJJCCJJJCLLCLLLLLLLLCCCLQQQLCLLCCCLOdhmLLLLLCCCCCCCCCCC ppqmZZmqpqwmZZZZZmmmmZmmmZOOZZmwwqqwwqpddbh#&8kmwwOZpwL|"^:^.. ;1Xmc()1[???---???????---??????--_------_______________{XQc\<l>ilI;;;III;;;;;;;;;:::::;;;;;;;::::;;::::;;;::::;;;;;;;;;;;;;;;;;:;;I;:;II;I!l;;<umZQXczXYYYYYYYUUUXcCqdqLXUCUUJJJJCCJUUUJUJJCCCJJJJJJCLLCCCCCLLQQQQCJJLOdhmJJCCCCJJUYJCCCJJ wwwmOOZwqwmZZmmZmmmmZZmmwmZZZZmwqqwwwqpdbbh*&8kZmwqdhkO/,";"'. "\LXf{-][?-----?---_-_--?]]]]?-___----______+___---_-[tmpt~>iil;;;;;IIII;;;;;;;;;::::;;;;;;;:::;;;;::::::::::;;:::::::::::::::::;l!I;IIIIII;:l|zOZYczXXXzXXXXXXXzzLqpwJcYJUUUUUJJJJUUUUJJJCCJUYYYYYUUUUUUUJJCLQQLJUUCOdk0XXYJJUUUYUJLCCCC mmmmZZmmwmmmmmZZZmwwmZmmwmZZmmwwwwwmwqppdbh*8BhZmwwphkmt,";,`'. ~fULr1)1}]?-??????-??????]]???--____++______-_--___?{fwdf+<i!lllIII;;;;III;;;;;;;;;;:::::::;;;;;;;;;:,,,::;;;:::::::::::::::;I;:;II;;;;;III:;>)JmCYzzzzzXXXXzzcvcJmwZUcXUUUUUJJJJUUUYUJJYYYYUYYYYYYXXXYYUUUUUUUUXXYC0dhZUYYUUYYYYUJCCCCC wwZZZZmZZZZmmZZZZmwqwmmZZZZZmwqqqwmmmwqppdh*%$hZwqwpbbwt^^;"'. ^+XpX\(1[?---????-_-????----------_________----___~+[tOm|>i!lI;;I;;;;;;;;:::::;;;:::::::;II;:::;;:::::::;;:::::::;I;;:;;;;;I;;:::::;;;;;;;;;;;_uQ0LXczXYcvczccvvvCwqOUvXYYYXXYYYUUUUYXYYYXXXYYXzzXYUUYUJJUUUYYXXXYUJLqhmJYYXXYXXXYUUUUUU pqmZZmmmZZZZZZZmmmmmmmmZZZZZmmwwwwwmmwppdbh#B$*pppppdbpj,";^.. . `t0Lv\{}[?------__-??-______--??-?_+++__+++~~~++_~~}jOZ\<>ii!lI;;::::::::::::::;;;::::;IIII;::;;:::::::;;:::::::;I;;::;;:;I;:::::::;;;;;;;;I,itY0LvuvccvvccvvvvuJqqZUvzYYXzzzXXXXXXzzXYXXXXXXXXXXXXzcXUUXYYUUYYYYUYYOpQzcvczXXXXXYYYYYY qwmZZZZZOOOOOOZmmmmZZZZZZZmZZZmmmwwwwqpdbka#B$oqppqqpdqr:";^'. )XJc|}1{]-__-___-?]]?-____--??--__---___________~+1xmw\<i!!lIII;::::::::::::::;;::,,:::;;;;::;::::::::;;::::::::::::::::;;;:::::;;;;;;;;;II:>fUZLnxvunuvvvvccvuUmwOYuczccccczzXzzzcczzzXYYYXzzzXXzzzXYUUYYXXXXXzzXUOwCvnnuczzzXXXYXzzz wwmmZZZZZO000OZmmmZOOZZZZZZZZZmmmmmwwqpdbho#%Bhmqpqpkhdn!;I"'. .. . .?rYz|[}[-__---?]][[[]?-____----__________--__+~~<+[fZw\>>i>!;II;::::::::::::::::::,,,,,::::::::::;:::::::::::::::::::::;;;::::::;;;;;;;;;II;~rJQXttxxxxnuvccvvcJmqZYnczcvvvvczzzzccvuvccczzccvvuvvvuvvcXzzcczzcvuvX0wCcvczXXzcvvvczXXX mmZZOOOOO0QQ0OZZZZZZZZZZZZZOOZmmZmmmwwqpbka#%$hZwpwpboac>II,`'. .l1XJ/[]?-------?]]?---______---??-__-----_+~~~~~<<_|Opr?+<>l;;;;::::::::::::::;:::::::::;;:;:::::;;:::::::;;::;:::;;;;;I;;::::;;;;;;;;;;;II;~xJUcffnxxnnnuvvuuvJZZLzxucccvuuuvccccccvvcccvvuuuuvccvvuvvvvvvcczzcvvcQwCvuuvcccvuvczzccc ZZZZOOOOO00Q0ZZZOOZZZZZZZZO0OZwmZmmmmmwpdka*%$amwwwwqa#Xi:;^.. `~zQf}]][[[?_++__---------____---???---_++++++++~~<}Cwr]iIIIl;::;;;;;;;;;;;;;:,,,,:::::::::::::::;;:::::::;;;;;:,:;II;;II;;:::;;;;;;;;;;;Ill-cQYutfxxrxnnuuvuuvCqmCznuvvvvvvvzzzcvccvvuvcccvuvcccvvcvuuvvvvvccccvcYOpLvnxuvcvuvvzXXzzz wmmZZZZmmZOOOOOOOOOOOOOOOZZZZwqqwmmmmmwqdkho8$hZmwwZOkWU>::^'.... . "xLn\{[{}]?????-__?]?????--------?---_______++~~++[zQz/~lii!lI;:::::;;;;;I;I;;;;;;;;I;;;IIII;;:;III;;;;;III;;;;;;;;;;;II;I;;;;;;;;;;;;;;Ili}zLXujjxuuuuuuccvuvCqmLXuvvccvczzcccvvczcvvvccvvvvvuvczzzcvvvcvvvvvvccz0pQzunvvuuvvvvvzXzz wmZZZZZmmZZOOOZZZZZZZZZZZZmmmmwwmmmwwwqpbkao%$hZwqwZQb&C~:,"`'... . `|zzx1[1[-_--????-----------------_______---___+++]jUOY[i>ilII;;;;;;;;;;;II;l?|rj)]_~ilIl!lI;;I;;;;;;I;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;I!+)XLvrjrxnnnnnuvvnnvJZOLzuczcvuvzcvczvvczcvuuvvvvcccvvccvvccccvvuuvvcczXOdQzuuvcvvvvuuuuuuu wmZOOOOZZZZZZmmZZZZZZZZZZZZZZmmmmmwwqpddka*MB$hZwqwZLd&Q]I"""'... .~/CU)-]?-----?---______-----------___++__------_+-1nbp/+>i!lII;;;;;IIIIIII;l>]/rruzzv\?<i!lIIll;;II;;;;;;;:::::;;;;;;;;;:,,::;;;IIIIIII;![jQ0ujxnunnnnxnvvunnYZOJvxuccvvvzcvccvuczccczzzcczzccvvvvvvccccvvvvvvvcY0wCvuuuuvvuvvvuvvvv ZZOOZZmmmmZZOOOOOZZZZZOOOOOOOZZZZZZmwwqdko#W$$awqqm0QdWO(!^""'. ^-UQt11}]-__-??--??-------_____-]]?-__++______-?_++\dhv{ili!lIIIIIIIIIIIIIIIII;Ili~(xvuxf/)+!ll!!lI;;;II;;::;;;;;;;;;;;;:,,::;;IIIIIIII,I)cmmurvvuuuvvunnuuunYO0CcnvzzzcvvvvvvcczzccczzXXXXzcvvccccvccvuunuvcvvXLmqJvcccczzcczzzcccc mmZZZZZmmZZOOOOZZZZZZZZZZOOOOOOOOZZmmwqpko#&B$*pqwZ0QdMZt<`^"' IxQQv{__-?-_?]????????------__?[]?-__+_______-?_+<1LqJtiIi!lIIII;;II;;;;;;;II;:,,":l+{\rzcf1~!lII;;;;;::;;;;;;;;IIIIIIIIII;;;;;;;;;;;;"I/JZ0urvvnnuuuuuvvvuuUZm0zrucccvvvvcvuvcccccvccccvvunnnuvvvvccvvuvvvcvnX0wwJvvcvvcccccvvczzz wwmZZZZZZZOOOOOOOOOOOOOOO0QQQQ000OZmmwqpbh*MB$#dqwmOCq#wx~''^. 'i/OL/}[]?-__---??---????????????-______------_++<[vQLx>I!lI;III;;;;;;:::::,:;;::::::::;i}xvrt|)}_>!III::;I;IIIIIIIIIIIIIII;;;;;;;;;;I:>xQ0JurnuunnnnunnnunxYZmQcrnvuunnuvvvvvvvunnuuuunuuunnnuunuvccvuuvvvvunYmwOYnuvvvvvcvvcczzzz ZZZZmmZZZmmmZZOZO0ZmwmZOOmdkhahdqwwwwmwpka*#B@owOOwZQq#qu-`",' IfYCn{?]??--__--??]?---???--??]]?-____-?--?-_-_>-uQOv~I!lII;;IIIIIIII;;;;;;;;;IllllIII:I~}\rzJCj]<!lIIIllI;:IlI;IllI;IlII;:;;;;;;;Ill_zwLcrjnxxrxxnnnnxxrxYmm0XnuvvvunnuvcccvuunnnuuuuuuuvvvvunuvvvuuvvccvvuUZZLznucczzzcvcczzXXX wwmmmZZZZZZZZZZZZZmmZO0Zk#88&%B&odmwwwwpbho*8BMahoWMbh#dY{",:`.. 'Itw0j1??]?-----???--__---____-?----_-??-___-_+~-tUpC}<<!IIIIIIIIIIIII;;;IlIIIllII;;;;;;;;::I]tnccvvr(]~>ilI!i!!lIllIII;;;;::;;;;III![CbLvxrnuunxnuxrxxnnvJww0zxucczzcvuuuvvvuunnuvcvuuuuuvvvvnuccvuuuvczzcvY0Z0XuvzzzXzcvvczXXXX qwmmZZZZZZZOOZZOOZZZZwph8B#bmbW&#dZmwmwpkaooW%BB$$@$8%%aC1":I^'. !tvcf{1)}]__???]]?---??-___--___--_+_------??-])vbO(+>lIIlllllllllIIIII!!I;IIllII;;IIIII!!lIl_1|tnXCXf}<i>!!!!ll!!!lIIIII;::;Il!ll>1QbJnuvvvvunvvuuvcvucLqmCcnzXvuccvvvczzzvuvcczXzcvvvvvczcuuvvvvvcccccvvJwwOUcXYXXYYYXXXYXXXX mZZZZZmmwmmZZZZO00Ommwb*$%bmOp*WWbZmwmwpko*#&%$@$$$@@@@#0/>i!,`'. .I\Ju)}]?-__-????-----?-__---?-_--__-----????--}xbZ\_i!llllllllllllllll!!IIIl!lIIIllIIl!!iii!l;:""i|ncj?>illl!!!!!!lIIlIIllIIIIl!~)vp*wCUYzcvvvvccvcvnuzLmOJzvXYcvzXzzzzXXzccczzzXzcvvvvcczcvvcccccczzzzzcJmwZJzYUYXYYUYXXYXXXX mmZZZZmmwwwmZZZmZZZmmwkM$8pOOqhW&b0Ommwdh*#M8$$$$$$@@@@#Zj_<>:^'. . [YYx)_?[?????]]????][]]]?-???-]}{{}]-?[]?-_+-1vkm|+>!!!!!!lllllllll!!lIl!!!l!i<~__-?--?-??]?---__?/ULUzuxf([_<i!ll!i>i!!llI;i?/zZh*awQCYcuuuvvcczzzvvzQbqQznvzczYYXXXXXzzXYYXXXzzzzzzzXXzzzzXXXXXYUUUUYY0dbwLYUJUUJUYYXYYYYYY qwwmZZZZZmmmmZZZZOZZOmkM$%bmZwh&BhZZZZmdho*M8$$$$B$$$@@Mmx]+>;"`. itYLf-[{[?---?]???][[[[[]-?])fcJQ00Cvf)[]???{fUkO)~>i>>>ii!!llllllll!lIl!!<}jJmkaaooaaooao*######o*W&8%BB8#kmLXuf)?_+<>i+1tuYLOmpbkd0CLQQLCCCUXYYYYXzz0hhwXxzUzzXXXYJJUXzYUUYXzccXXXXYYXzzXXXXXYYUUUUUYY0dpmCYUJUUUUUUUYYUJJJ ZZmmZZZZmmmmmmmZZOOOOZd*B8pOZqk&@aZZmZwph*M&%@$B8W#M%$@*0/>i!:^'.. . ,?vOn{}}[]__-][[]]]]]]]]??}\XZQz|(uCmZQ0Omwwpk*WoZ0ZO0OZO000QLJJUYXcvxf/trUpW@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$&qu|}}(nQa%$BW**WB$@$$B$@@@B8#hZQ0QJYX0khdJvYJYzzXXXXXXzcczXzzccccXUUUXzzzXzzzzYYYXYYYYYQqw0YcYJUYJUYYXYUUJJJ mmmmmmZmmmZZOZZZZ00QL0p*$8qQ0mb&@aZZmZmpko#WB@@$BB%88$@aJ(lII"'. ,f0Xt)[[]?---?---?]]?-_-]|uwhY(+l!-/LW$@@@@@@@@@@@@@@@@@@@@@@@@@@@@@$B%%$@@@@@@$B&*bqm00mdho#M&W*abpppppdbhM%$@@&hm0wh&$@@@@@@@@@@@@@@@@@@@@$Wp00QUXXCmppCczXzzczzzcccczXXzzzzzzccczXXXXXcczzXYYzzXXzzX0dpOUcXYYYUUUYXYUUUUU mmmmmmmmmmmZZZZmmO0QQ0p*$8qQ0ZdW@ammmmmqba*M%@@@@@@@@@$aC/+>!:^' -nJJf{{[-_---????]]]?-1jQ*B%J\|/xf{/Up#*aaadwZ00QQCUC00Zqdkao#MMMMMMW8%8%B$@@$8aJj)-!l<xZ0z/{1\nYCLCzr\{_[j08@@@@@@@@@$WhZLJLOmOXnrjjuLkB@$&amLLCYXYLmddLvczXzcvvvvczcvcczXXXzcvvczzcczccczXXXXcczXcccQddZJcXUUYYYUUYYYYYYY OZZZOOOOZZZZZmmZZOOO0Zp*$8pOZwb&@omwqwqbh*M&%@@$@$$8#MMwn];;;^. ^~u0ct({{}}[]][[]]]-?}nqW@Baz()xmOr1[fCZwp0j[+>iiil;;;;I!><~~++___+<~]]-|Xb$@$hJ)~_<:":1zQ0v|~;:i}jYQOLz/)fL8@@@@@@@@@8dX(-?|uXv],,"`I1C8@$Md0JUYXXYCmbkLvucXXcvvvvzzcvvczXzzccvczzzvvvcccczXXzcvvvccc0kbmCXYUUUUUUYYUCUYYY OZZZOOOOZZZZZZmZZZZZZmd*$%dZwqk&@aZmwwqbho#M%@@$@@$&dh&pn]:;;^. .[nUYt)()1[?????]]?{f08@@hJt(xJq0/-!<])()]>llI;;l!!llllIIII;;;IllIIIllI?rq@@Bpc1~~<i;"^:[rJ0Ux[i;"",i}fz0d*B@@8*dwa8@&QnfjcLwq0f?-~!>1J8@$*qQJJUYzcUOko0vvcccvvcczzzzzXYYXcccvvcczcccccczXYUYXXXXXYYX0dbqQUJJYYUJJUYJCCCCC OOOOOOOOOO00000OOOOO0Zd*$%dmwpk&@hOZmwqbh*#M%@@@$$@&dkWqr_":;^. . ,]Cwu(}][[]???]]?-)uq$@@wx|jdoLt>!+<lII;;;IlI;Il!!lIIIIIII;;Ill!!lIlll}ud@@Bmx1_~>l;:^'`"!]tncu/}~i>+}\vqM$@@#ZufLoB%bmZJnjjYQn)-i;>(L%@$omQJJJUYXYCb#OunnuvccccvvcvvvczzccvvuvvczzzzzzzXXXXXXXXXUYY0dkbQXUJUUUJJJCCCCCCC OOOZZZZmZZOO0QQQ00OOOZpoB%hqwqb&$kQZmZwdh*#W%@@@@@$%M8$dx];,"`. . ,vmUr1[1{?-_][]?-?)xQk#qz|(UZLn]~~>iI;;;Il!!IIllllIIIIIlllIIIIll!!lIl[up@@Bpz(_~!;::,,"^^`.,-|xunvzJCzYpM$@@oLr/Yb8BhOc/{(jcc)i!I,-vpB@$hOLCJUYXXczmhZYcvczcczcvczcccvvvvvvvczXXXXXXXXYYXXXYUJJCCJULwkh0zUCLLJUCCLLLLLLL OOOOOOOZZZOO0QQ000ZmZZqaB%kwmmpMBkOmwZZwdaM8$@@@$B8W#&$dn{i;,`.. ']xLCf((1}]]][[[]?-]1umaaCf1{t\]<llilIIIIIIIII;;;;IIIIIIIIIlllIl!!lII<(0$@@%oQn|]~l:,,"^^`...`,!-)fnXLqW$$@Bdv//Yb%%p0Q0mOJx)+lllI)Q*$@%b0LLCJUYXccQdwQUYUUXXXXXXYYYYXzzczzzXXXYYUUUUUUUUUJCCCCCLLJCQqbZCCLQQCJJLQLCCLLL OOOOO0OOOOOO00000Q00Q0whBBaqZwkM8kOZmOZqboM8B@$$$$%WaW$pj+"",'. .^?U0v/}]}[[?-??--]/XYcXCdpx[<!>]|)-<llII;;;;;;IlI;IIIIIIIIlllII;IlllI>jwM$@@@%Mokpm0LUzvxf//\|||/rYw#B$@@8hLj|/Yd%%p00Zwc[~>>i!>?u*$@%#wCJJJUYYUYX0pqZUzXYXXXXXzzXXXXXzczYYXzcXYYYXXYYYYUJJUUYUCJUUCZpZLJUJJUUJJCCJJJJJ OO00QQQ00000000OOO00Omdo%B#dZwhWBW**adqdh*&%BBBB$$$%M&%px-,",`. ;jJLz\)1[???]??[(zpY}i>tJw0j\rCdJ(_!!!!llI;;II;;;IIII;;IIlllII;;;IllIl~/Up*&B$@@@@@@@@@@@@@@@@@@@@@@@@@BaCx(?]xZ&$Maho*qUXXzXJObM$@@&kOJCCJUYXzccQpqOcxvcccccczzXzccczzzYXzzzXYYYYYUYXYJJUJUUUUYXUQdamJYYCLJJJJJLQLCCC OO00QQQQQ00000OOOOmqaW%B@$8Mo#8$@@@@B*hhoM&%B$$$$@@BMW&pu],,,`.. `?nwL|}1}[[}[[[\zLLj<!ii?uL00Czr{ilIllIIll;;;::;II;IIIIIIIIIIIIIlllIIIIIl+{|tjuYCQZpka*#W8%$@$$$$%WW#kZzj(]<l!1chB@@@@@@@@@@@@@@@$8*d0CJUUYYUXcczLqpmzxvcvvuvvczXYXzzXYXXXXXXXXXXYYYUUUUUYUUJUUYYJ0boZYYULLJUUUUCQLCCC 000QLLLLLQ00000000mbW$@@@$BBBB$B$$@@B*hhao#M8B$@@$B8M%@bn+`^,`. .")wmj(1{{{}-]|cpOf]!!ii!!i<<ilI;:;::::;;;:,::;II;;;;IIIIIIIIIlllI;;;;:;III;;;;Ill!iii>>><+_-__]}_<~~>!!lll!I;;</Xmko#MM*akkdqmOLYzzXXXzccczzcvvcULZZXxuuuuuczcczXXXXXYYXXXXXYYYYYYUJCCJUJCLCJUUUJLqhmJJJJJJUUUUJCCCCC QLLCCCCCLLQQQQQQQ0mbMBBB@%addka&@@@@$8&&WWMWW&%$$B&#hM$bx+^",`. !vQCu|(()}_[rQhL[><>i!I;:::;IlII;;;;;;;::::;;;;;;;IIIIIlllI;;;;;;;IIIIIIIIl!l;IlIIII;::;IIllIIIlI;:;;;IlIIII::![uOahmUuuvunnnnnnuvccvvczzzccvvcXCqdCcccccvvccvczXYYYYYYYYYYUUUUUUJJJUUJLLCCJJUUJ0b#d0CUUJCJUUUUUCCCC LLLLCCCLLLLLLLLQ0Zb#8$BB@B#ahoW%@@@$$$@@@$$$$$$$$BW*aW$dx-,,,`.. ,1YkQ\)11{]1xLbY~li!llII;;IIII;;Il;;;III;::,,:;IIIII;;IIllllI;;;IIIIIIIIIIIII;;;:::;::;IllI;II!+}(tjrxrrrrt(}-ii-fOkadOmpqm0JzzYYXzcczXYzzXXzccYQhoOXXXYXccczzXXYYXXYUUUUUUJJJJJJCCCJJCCJJJJJUYUQdop0LJUUJUUUJUJCCCC QQQQLLQQQQQQQLQOmb#B$@@@$$$$$@@@$@@@@@@@@@$$$@@@@%#ak#%du?"",^.. .:x&ac/{1){|z0qviI<il;;IIIIII;;;;I;;;;;:,:;::::;;;;;;III;;;;IIIIIIIIIIIIIIIII;III;;;;I;;,;i?|rvcvxjf/(1{{1{[_<>!II<tOdpCcX0aMawUXYUUUUXcczzXYYXU0o&mXzzXXvcXYYYYUUXXYUJJJJUJCCCJJJCLLCCCJUJJUUYULd*pQUXYUJJJUUUYJCCC 00QQQQQQQQQQQLQZqhW$@@@@@$%B@@$@@@@@@@@@@@@$@@$B%&*hb*8bc?^",^. (kWaQx/(1tQwQr>i+>l;;IIIIIIIIIIII;;:::;III;;;I!iilIIllI;IIIIIIIIIIIII;;;IIIII;;IIlll;I>{rczr)-<!i~]1)(()[_~>i!!l:I+\zUUucwo*pYzYUUUUYYYYYYXzvcUbMwJYXXzvzUUUUUJJYYUUJJJJJJJCCCJJJJCCJJCLCCJJCJJqadOCUJCJJCCCCCCLLL 000QQLLLQQQQQL0ZqbM@@$@$$%W&B$$$$$@@@@B88B$@$%*kbbbdpo8pn+'^,`'. "|q&$#mcfjXbpn{ii~>lI;II;III;;;;IllIIIIll!~[fXOqqm0Xf}i!i!lllllIIIII;;;;;;lllllIIII;;!}uzx(<IIi}n0hM&&88&MaQn|}]-+>l;!)vOkohZJzzYYYYUCCUUUUYYXXJb#mUzczXzYJJJUUJUUUUJCCCCCLQLCJUJCLLLCJJCCCCCLCCp#hwQCLLLL000QLLQQQ 00QLCCCCCCCCCCLQmb#B@$$$$B88%B$$@$$$@@%okh#%8#bwqppqwa%dn-^,:^'. .:|Z#%BMmYXQ*p/+!!i!lIIIIIII;;;;IIIlIIIIIl>}/jf([??]]_>I;I;IIlIIIIIIIIIII;IlllIII;;:;!+|Uc[iIIli[u0pbqwZ0QQLcf)]-~<i!!lIl_|c0pq0JXXYXXXXXXUJJJUYJb#mUzzYUYUJCCLLLCLLCLLLLLQQQLLCCLLLLLLCJJCLQLCCLb#kZLJLQQQQQ0QQQQQQ O0LCCLLLLLCCCJC0md#B$@@$$B%%B$$$@$$$@@B*hhMB8#kqqqddqo%dx_^":^' .;\ma#%BdQZpkC-I!!!lIIIIIIII;;;IIIllllllllllllI;Ii+]?+illi!!!llIIIIIIIlllllIllI;II;;;!+)uu/\\()11)(((()){]?-~<>>>ilIIIllI;;!]jJqmJYYXXYUUUJCLCJUCdomJUUJJJCCLQQLCCLLLLLLLQQQQQQQLLLLCCLQQLLLLCJJLbMpCUUCLLLQQQQQQLLL 00QQQQQLCCCLLLQ0md*%@@@$@$$$$$@$$$$$$@%ohaM%&*kqwwqwZh%dx+`^,^' ,\wkboWMM%Mmu?ii!!llIIIIIIIII;;;;;IIIIIIIIllI;:;i(JwwY\]~>illllI;I;;;;;;IIIIl!lIIIIIlIi_{\jrxnxxrrrrrrrnvJ00QCCQQUUUXcr/({-+?xdb0JXXYYUJJJJCJJJQh#wJUUJJJJCCLLLLQ0QQLLQQQQQQQQLLLLLCJCL00000QLLOkMbOOO00QQQQQ00QQQQ 00QLLLCCCLLQQLL0wkoM&%B$$$$B%%B$$@@@@$&hbk#B8#kpqqpwZk%dx_^^"`' .:tdhwph%@%kc|}_>!!llI;;;II;III;IIIIIIIIIIllllIII;>(nCCXUYx|?<i!lIIl!lII;IIllIIIIIIIl!ll;Illll!!l!!!i!!!i-uwdqLJOZQQOZmqddddqqkW*q0JJCCCJCCLQLCCQhMpQLLLQQQQQQQQLQQQLLLLLLQQQQQQQQ0ZOQQQQQQQLLLQOhWaqmZO0QQ0OO000000 0QLCCCJJCLQQLCC0wdbbbbhaaaaoo*#W8&&WM*abbhMB&*bqqqqmOk%qt>`^"^'. ,thowZq&$kY)~+~>i!llIIIIllIIII;;;;;;;IIIIIIIllll;I>}fnzOdw0QJXur\}]]-+~<i!!!lIIIIII;Ill;;Illl!llll!ii!!li|Uda0XXzcczXYUJCLQQLLQQ0QCCJCCCCCCCCCC0aMwCCCLQ0OOO00000000000000QQ000000O0000000000QLQbWaq0LOO000OZZZmwww QLLLLLLCLLQQLLCLZpbbdqqqqqqqpdbkahhhkbpwqk#%WobqqwwZOk%m|>"",^'. ^\dhmmqM8bU|-_<ii!llllllIIII;;;;;;;;;IIIlIIIIIIllI;l_fJCv)>i>-\X0wm0LLCCQQJXuxxjt/|1[-+>!!!lllIIl!ii>iill?rd&wJUUJJJJCJUUUJUYYYUCCCCLLLLLQQQQQOwM8qLLQQ0OZZO000OOOOOOOOOOOOOOOZZZZOOZZZZZZZZmZOOb#hqZOZZmmwwwmZmwww 00QQQQQLCLQ00QQ0ZwmOQLCCLQQQLLQQLLLLQ00QZd#%WabpqqwmZaBZ1l^^"`. ^/kawZwa#*mf[-~i!!llllllIIII;IIII;;;IIlllllll!lIIIll;l_/vcx|1)xZC|>`'`:?XJ|+!i-{\rvJQCUzccvuvzXYvnnnnxj|}?)Q*kZJYUJCCJCCJJCLCCCCCCLLQQQ000QQQQ0moMqQ0OOOZZZO0Q00OOZZZZOOOOOOOOZZZmmmmZZmmmmmmmZZdabqmZOZmwqqwwmmwmm O0QQQQQLCCLLQLLQLJUYYYYUJCCCCCCJUUJJCLLLOp*%Wadqwwmmwa8L-:`^"'. "f*#qwqk*%av)}_>i!!!ll!!llIIIIIII;;;;;;;;IIIll!!lIIII;:l~1fzOk&@WZu)-~_|O0-. ;rUf1}[}}}\uqbu}]?][1fcXUp**bQUCCLCCCCCCCLLLLLLLLLCQ000QQ0QQ0m*WwL0OmmmZZOOOZZZOOZZOOOOOOOOOOZmwwwwwwmwwwwmZZZb*hpmZmwwmmmmwwwmmm LLLLLLLLLCCJJCCCJUUUUUCCJJJJJCCJUJJJJCCLOp*%Whpwmmmwp*&C+;:"^'. "fo*wwqpk$8Lf[~ii<>i!!!!!llllIIII;;;;;;;IIIIIIllI;;;III;;Ili~-)ruvvcczCqM#Lnf|{<I~\waY)I'. i|L0? ~upWaqmOCCLLJJCJJCLQQQLLCCCCLLQQLLQQ00QOq&BdLQ0OOO0QQ0ZmmmOOOOZZZZOOOOOZZZZmmmmmmmmmmmZOOb*#aqZZmmmmmwwqmZZZ LLLLCJJUJJJCJJJUUUJJJJCCCCCCJCCJUCCJJCLLOq*%#bpwmZZmd#&J~;:,^'. .:j**Zmqqk%&0r]i!i>i!l;IIII;;IIIII;;;;;;;IIIIIIllllIlllIIIIl!!llIIIIl>_]}1(truzXzXLwh#WM*bwZZd*WoU/[<:"l\0bkQzXYUUUYYYUUJCCCCCLLLLCCLLLLLLLLLCCQZoMqLCLQQ00000OOZZZO00OOZOO0OOOOO0OZZZZZmmmwwwmmmdo#aw0OZZZOmqqqwmmm LLCCCCCCCJJJJJUYYYXYUJJJJJJJCCCCCCCJUJCC0q*%#dqwwmZmd*WY>::,"'. '!uW*OZppk8&mu[<<>>ilI;;;IIIIIIIII;;;;;;IIIIll!!!!lIIIIlllllIIllIIIll!!I;;;llll!><~_-}|rYCQmd#%B$$B&*kbhW$$%&*dwmZO0QLJJCCCJJJCLLLLCCCCCLQQ00QQQOdkZLQ0OZZZ00Q00OOOO0OOZZZZZZOOOOOOZZZOOOOZZZZOOOqh##q0OOZZOZmwwwwww LLLLCCCCCCJJJCCUUJJUUUUUJJJJJUJCLLLJJCLC0qo8#bqwwmZwb*MXi::"`'. . 'iuW*Ompwqa*kC(??+>!llI;;Il!!lIIIIII;;;;IIIllII;I;IIIIIIllIIllIIIl!lIl!!i!l!lIII;;;I;;;;Ill!>_[1(\tfxvUOkW%$@@$%&WM#obwZ0QCJJJCCLQQQCCLLLLQQLLL0mh*qQLLQQ0OOOOOOZZZZOOZZZmmmZZZZZZmwmZZZOOOOOZZOOwboowQ0OZZZmmmZZmmm JJJJUYYUUJJJUUUUYYUUUYYYYUUJJJJCCCCUUUUULwo%#dwmwwmqb*#Xi::,^'. 'lxoaOwdqqba#qr1]+>!llIII!ii!II;II;;;;;IIIIIIIIIIII;IIIIIIIIll!lII!lll!!lll!!llIIlllI;IllIII;II:,:;;;;Il<]\nXYcr({)cbokmLCCJJJCLLQQQQQQQLLLLLCCLOh#pO00QQ00OO00000OZZZZZOZZZOOOOOZmmZZOOOOOOOOO0OOwo#q00OOOOOOZZmmmm JJUUUJJJJJJJUYYYYYUUUUUYUYYYUJLCJCCCJUYYLwo%#bwmmmmqk*#X<Il:^'. .;jhhOwdqqkoMqf}-~i!llIll!!lII;;II;;IlllllII;IIIIIIllllllIIIllll!lIIllllll!!!lllllllllI;;III;;IIIlllllllIIII;;;Il[uw8MdOCCLCCCCCCCLLLQQQQQCCCJJJQdawQLLQ000QLLLQQ000OOOOOO0O000000OZZOOZZZOO00000Ow#8kZO00OOOOOOOOOO CCCJUUUUJCCJUYYUUUJJUYYYUUYUJJUUUJCLCJUJQq*%MbqmZZZwboovl","^'. ';jaamqdddka#wt}]+>!!!!!!!lIII;;II;;l!llllII;IIIIll!!!!!!!i!IIl!!!!!!!ii>iii!!i>i!ll!!ll!!lllllllllllllll!!l!!!?rO&&bZCJCJJJJJUUUJCLLLLLLLLLLLCCQb*dOCCLQQQQLLLQQQQQQ00OOOOO00000000OOOOO0OO00QLLLOaWkm00ZZOOOO0OZZZ JJCCJJJCLCJUUJJJJUJCCJUYUUJUUUJJJCCCCJJULmo%MhdqmZ0mdaocl"""^' . .IjhamwppdhahQ/[]+>i!llllllII;;IllIIlllllllllllllll!!!lllll!llllIIllllllllll!!!!llllllllllllll!!!!!!llll!i!llll[YdMdXcYUUUUJJJJJJJJCCCCCJJJJJJJUCb#kmLJLLLLCCCLQQQQQLQQ0000QQLQQ000Q0OZOOOOOO0QQQLQkMkwQLZZOOO0Q0000 CCLLLCCLLCCJUYUJCLLQLCCCCCJJJCQLCLLLCUUULwo%WhbqmZOmdaavl:I,`' .IjbkZwpqp**wz(]?_~>i!lll!!!lIIl!!IIIl;IIl!!i!l!!!!lllllllllllli~++_-??-+~<>>!!lIII;;IIIl!!!!!!!!iii!!ll!i!ll!l?vq8hXvzXYUUYYXXXXXXYUJJUYYYUUUYXYwhbmLUJCCCLLLLLLLLLCCLLLLCCCCCLQQQLLQQQQQQ00QLLLC0kMhwCJ00QQ0QLLLLL LLLLLLLLCJJJJUJCCCCCCCJJJUYUJCLLCLLLLJJJ0p#BMbqwmZ0ZpaauI;!:`. .. ,-vh*hkhho%WZu(]-~>ii!llllllllIIIlIIII;;IIll!!i!l!!ii!!l!!>~-)uCwba*######hm0LYvuxj/)}?_~<>i!!lll!iiii!l!>!l!!l>{Y&#CXXYUUUUUYXXzzXYUJJJYXXXYXzczOdkpLYYYYUJJJJJJCLLCCCLLLLLLQQQQQQQLLQQQQQLLLLLLCLbodZJULQCLLLLLLLL QLCCLCCCCCCCCJCLLCCCCCJJUYUJJJCCCLLCCJUULq*$MbpqwZ0OdaavlI!,'. ... ^i)uOb*M&8%$@@&Ou|}?+>ii>>>iiii>>illlIllllIll!!!!!!iiii!!<]tz0doW%%&#ahbqqo&&oZOdhaaooabqqwZQUcnt)1{]-+<ilI!>!liili[z&M0JJZdbpZQCUXULQ0QLCJYYYUUUUYUQmbdQYUUUJCCCJJJCCLCLQLLLQQ0000QQQLCCLLQQLCCLQQLCLdobmJYCQ0wbbdwZOO QLCLQLCJJJJCCLLLLLCJCLLCJUJUUJCCCCCCJCJUQp#$MdqqmZ0Zk#*cl:I"'. `}cd#abqb*W&W#&aYf([+>!!i>><>ii>>iiiii!ll!!i!ll!i!l!!!<]/XwokmQQbokpqqqqqZZh#awznvvuXQhMpCXY0b&%8&##*bwOJvj/|)[-__-(Xd%*CJ0wbaokmJXX0h&8k0JUJJUYUJJYYCmM8aq0LLCJJCCCLLLLCCLLLLLCJLLLCCCLLLLLLCCCLCJUUUCpahmXcCOpko*apO00 LCJCQLCJUUJCCCJJCCCJCLCJUUYYYUJJJJCCCCCJ0p#B#dqqwZQOd**cl;l"'.. .. ."~\QkakpqpbaM&M**qx){?~<>>ii>>>!!!iiii!!ll!i>>iiiii!ll_fJdkwUf_:,?LapwqqqwmOOk#*b0CLCCma%$h0UCwhM&8%&hmOZpo%$$%Madqqpa88amCOdppbkdmJXUZo8$MbOJUYXXXXzczCqW$%#q0JUJUYUUUUUUUYYUJJUYUJCJJUUUUYYYYYJCCL00LXzQpdwJYQmdkkhk0UUJ CCCCLCJJJUUJJCCJJJJUCLJUJUXXXYYUUJCCCLCC0p#$MbpqwZQZk*avl:I".. .. . `I-/zZkkbddppddbh*&&*qXr/)[_~>iiii>>>>>iiiii!!l!!i><<>>~{vm#Wh0urr\)(rp#dwwwwmmOZa&#hqqppqoB@$#bpk&B%%B@$*pwwpa%$@$8#a*MMMW#akk*WM*##abwmpaWWM88*kpwwmwmOQQOwbho*#kOQQQQQLLLCCL0mwwmZOOZwdkhdZ00000QLQOb&8#qLZpkbmmdkhhhhbOCLQ LLLLCJUJLCCJJCCCCCJCCLJJJUYYYUUJCLQLLCCULw*BMbpwZOQma#hu!;I"`'... . ';[vOhoohkbbddddppddpdk#WW#hbpLuf\{-~<>i!!!iiiiiiiii>>>>!~/C#@@BW#*###**#88W#okpqwZmo&M##WBB&%$@@$B%B$$BB$$@$$BB$$@@$$BB%%%%%%%BB%BB8&%B8WMW8&Moa*&%$$BBBB%8WMWW#akaW8&*bdpdpmOOmd#B&apmwdoMMW%B%&#abppdkaMB@$8#ooMMooMW&&888M*## JJJCCJUUJUYUUJCCJUUJJUUUUYXXYYYUUJCCCLLC0pM$MbpwmOQmh*hu!Il,`'... .. `+uqWWabdddddbbdddbbdppddbbh*M&8%%&*d0Uzx\)1]_~<<<>><<<i!<{cpW$B&*hbdbbbbkho#W&888WhdoW#aqpho**okdbhookpmwdkaahhkdppqmmwqppwmmqpdbbkkpqbaMWWW#ohbddbko##aaa*W&&88W#aha*WWWWM####*#MWM#***###ohbkh*MW&&MM&8&W**#W&8&&&8%8&MabbhM%88 YYYUUUYYYYYYYUUJUUUUUUUYXXXXXYYUUUUJCCCJ0dM$#dqqwZLZh#oc!:I,`'.. ... ,1zb#okppddddddddddbbdddddpddddbbkkko##MWW#*akdqZCzxft/())tcp&B$%W*ahkkbbbbbbkbbh*W%8&%%*pCYYXzccuxxnczcvuuccczzccvuuuvvvvvvvuuvcczXUUYXYUL0O0LLCCCCCJJCJJJJJJCQQQ0QLLCJCQOwpbkbdqmOQCLOwppqZQCUYXXYJL0OmwqwmOOOO0OOQQ00QQQ00LCQO0Q YYUUJJJJUUUUUUUJJJUUJCJUYYUUUUYYYYYJJJUYQdW@#pwwZ0J0b*av!:;^'....... .>/Zoakqqdddpddddpdddppppdbppddppddpddbbbbbkhhh*WWW&8&&WWWWWWWWWWM*akbbbbddbkdddbbbdbaM%$BMdLYYXvvvunxxnuuunuuuuuunnnnnnnuvccvuuunnnuvvvvvccXXYYYXzzzXXYYXzcccvvcccvvvvvvvvuuuvczcvuuvvvvuvczzccvvvcccvvcvvzXzXYYXXzcvzzzcczXYYYXXXYY CCCCJJJUUUUJJJCCCCCCLLCJUUJCCCJJCJJCCJJJ0bW@MbqmOQCQqa*X>"^^`''`'. '^>up##bppddddddddbbddbbbbbbbddbbbbbddbkkkbbbbbbbbbddddbkkkkhahkdpbkkbbbkkbdpdbkbddbbkbdkoW88oZCJXcccvvuuuuuunnuuvuuuuuuvvuuvvccvvvvuuvvvvnnvzXYYYXzzXXYYXzzzccczzzzzccvcccccccccccvvuvvczzzcczzzzzzzXYYYYXXUOwwOCUXXXYYUYzczXXzvzXzzYU QQQQLLCCJJJCCCLLCCCLQQQLLLQQQQLQ0000QLLLZk&@WhdqmOL0qoWJ~,^""``^`..'.^_rq#hdpdkbddbkkkkkbbbbddbbbbbbbbbbbddbbbbbbkkkkkkkkkbbkkkkbkkbdbkkkkbbdbbkkkbbkhkkbkkkbdbaM%8kZCYXzccvccccccvvvvcunuvvvccvccvvuuuuuuuuuvvuuucczzzzXXXXXzzzzzzzXXXXXYUUYXzzXYYXXXXXzzXXXXXzzczXYYYYYUUJJUUJQZdhapLUJLZpkkdwZO0000QLCJUU LLLLCCJJJJJCCLQ0QLLQQQLLLLCLLCCLLLQ0O0LLObW@&hdqZ0LOb#&Y>:;"^^^^^'..`ixqaobppdddpdkkbbbddbbbbbbbddbbbdbbdddbbkkbbkkbbbbbbbbdbbbbbbbbbkbbdddbkkbbbbkkhhkbbddbkhhkhM&&oZQCJJUYYYXXzzccvvvuuuuuuvuuvzcvuuuuvvuuuvcvvvvvvcczXXXXzcczzXYYXXXzczzzzzzzXYYYXzcczXYYXXXXYJJJJUUUUJJUUUJLOOCLZqbkaakpZOZqbbbdbkhahbwm LLLLLLCCCCCCLLQLCJCLLCJJJUUUJCLLLLLQQLCJQp#$WhpmZOQZkMWY<;I,^^^`''.'!(OWodpdbbddddbddddpddbdbbkbddbbddbbbbbbbkkbdddbbddbbbbbdddbkkkkkkkbdddbbkbbbbbbkkbbbddddkhkba#B&d0JUUYYXYYYXzcccvvcccvvvnnnuvuuvvuuuvcvuuuuuuuvvcccccccccvvvvzzcczzczzzzXXzXXXXzccczXUUzccXJLLCUYXYYYYUUJL0LJXXCZdbdmQJUYYUJJJUUJJCQQLL CCCCJJJJUJCCCCCCCJCCCCCJJJJJCCLLQLLQQCCJObMBWhpmmZOmb#8J~l!I:,"..`^;{zbWhpbkbbdddddbbbbddbbbbbddddkkdddbbbkbbbdddbbbbdppddbbddbbkbdbkkbbdbbbbbbdbkkbbbbbbbbbbbkkbba88oqCYYXzccczzzXXzzzzzcczcvvuunnuvvvuvczzccccvuuuuvvvvvvvvvvvvvczzXXXzzzczXYXXXzzzXYYYYYYXzzXYYYYYYUUYYYYYYYYzzzXYUUYXzzzzzzXXXXzzcccczzz CCCCJJUUYJJJJJJJJJJJCCCCCCCCCCCLLLLQQQQQmkW$WhdwmZOZq#$O[l:^`^^`'.`lfmo#bwpdbbddbbddddddba*M*kbdddbkbbkkbbbbbbbbkkkkbbbbkkkbbbbbkbdbbbddbkkbbbbbkkkkbbbbbbbbbbbbbbh#W&ow0JYXzczccccvuuuuuvvvvvvvvcvvvvccccccczzcvvvvcccccccczzzzcccczXXzzcccczXYYYXzccccvczzXXXXzzzzXXXXXzcczXXXXXXXXXzccczccccczzzzzzzXXXXX JJCJUUUUUCLLLLLCCCCJUUYYUUUUYUJLLQQ00QLLObM$WkpwmmmZmo$q/~,^^^`''':-za*adqpdddppddbddbbbkhM%Wahkbbbbkhkkbbkkkbbbbbbkbbbkkkbbkkkkkkkbkkkbbkbdddbbkhkbbbddbbbddbkkkbka#8#pQXzcunnnrrxxxnuuunnuunnxnnxrrrxnnxjjjrxrrrxxxxxxxxxxrrnunnnnnnnnxxxnnunnnnxxxnnnxxnuuuuuuunnnuuunnnuuvvuunnuvvvuuvcccvvvvvvvvvvuuuuu JJJUYYYYYJCCCCCCLLLCJJUUJJUUUUCLLLLCCCCC0q*%&obqwmmmma%dn-";I^. '~jw&oqpbao##*##MM*ooaaaoM%&#ohhhhhhhkkkhhkkbddddbbbbbbbbbdkkbbdbbkkkbddbbbbbddbkbbbbbbbbbka**ahhkk*8MbQvnxjft/\|||/fjft////\\\||||((|\||(((|||||\|||||\\\\\\tfjjjjjftt/tfjrrrjjjffjrrrjjrxxxrxxxrrrxrrrrxnxrrjjjrrrjjjjrrxxrjfffffjfffffff CCJUYYYYUJCCCJJCCCCJJJJJJJJJJJJJCCCJJJJC0w*B&okpmOOOZk8hY},;I"' !\Ca**&88#dOJJJXcYC0mh*#&B8#ahhoW&WWWW&&WMMMM#*ahhkhhaahhkkkbbkhkbbddbbkkbbkbbbbbbbbbbbddh*MMakbbbo88#mXvurft/\\\\||||()1)(|()))(((((|||||\\\\/\\\\\\||\//////ttffft////tjrjjjjjfffffftfjjffjjjrrxrjjjjjjfffjjrrjft/ttfftttfftttttffffffff JJJUYYUUUCCCJUJJJJJJJJJJJUUUJJJCLLLCJCCCQwo%WhdwZOOOObMa0|Il!,`'...'I?\v0db0f1]??_~+--|Jk8B%Moao#W%$BB$$BBBBB%8W#**M&8&M#***#MMMWM*ahkh*#M*ahhhkkkkkkkbbkbbh*W&#ahaoM%%WqYzvxft/////\()\jxnf\()(((((|||||\\\|\\/\((|\//||\/t/\\||||\\//////ttttffft/ttffffjjfffjrrxrjft///////////\\|||\\\\\\\////\\\\\///// 000QLCCJUUUUJJUYYUJJJUUUUUJJJUJCCLLCJJJCQZh&*pZQ00QQQwohZ/Ili:^^^'''. `}xJz[<?-~~~<<+|Ch8&abbaM&%88&&W&&%$$B%&M*oo#W%WoaoM8BBBBB8MoahoM&&Mo*WM#oahhaao*#*aaoW8M*o*WWodOUvnxrft///\|()\XZdmr\xJwmJx|(|\///||(((()11)|//|()))(||(((((||\\\\\||||\\\\\//ttt//tttttftttt/\\||||((|||(||()(())(|||(((((((|\/\||| UUJJJCCJUUUUUUUYYYYXXXYYUUYYYYUJCLLCCJJL0mhWopZQO0CUJZaopr<~+I"^^^`'.. `/UJn?<]-<<~<+[jw**oa*MW&M*akkkbh*W%B%&#*aao#&BWooM8BBBBB$%W#*aoW%8Wo*&8&888888%BB%&WWMaJjtckomJcuxrffttttt//txXQmZ0JLw*BMqOLJzxt/\\||()11))(|||(){{{1)(((((((((||((()))(((((|\\\\\\\\\\|\||||||||||))(||)1)((())1)|||((()))))((((((( UUUYXXXXXXXYYXXXXXXXXXXYUUUUYYUJLQQQ00Zwpb#%MkwOZ0JYUZaaqtI!!^. "vmXt-<_+~~+>_\Uo&hh#WW#akbbkkbbddh*MWM#oahhoM&W##MMM**#M&8&W##M8B%&MM88888888%$$BB%B%Mpu)\X#WZUcunrftfxvXC0Zw0JUJ0ZZQYQbdZmqhk0zr/|(())1)(((()1)))))))(((()))))))))))11)(()))(((())((((((((((||||||)(||((((()(()1)(((((((())(()))))) OOZmmmwwwwwqpddbbbbkkkkkkkkkkkkao***#W&%%8B$&admOLUYJma#aLnnunxrjfjrrxxXo80x|{[_<~_~[cp88kdkkbppdkkkbddbbbbbbbkhkkkbkkhhhkbbbkkkkhhhkkhao*****oa*M&%B%W&B$$$B#wn|tJW&ZUvnrrrjffffruczx//fjjft\/ft|11rYQOLJYzcunxxjt\|(()((||||((((((((((((|||))((((((|||(()((||||||||||(((()(|((|||())()11111)((())))())1111 #MWW&&WWW#*###*o****ahbddppqqwmwwqqqqmmZZwh&&#dOCUXXJZa&%Moaaao*###MMM&%$WQnj\)[-__+1Uh88kdbbbbbbbbbbbbbbkkbbbddbbkkkbbbbbkkkkbbkkkkbbbbddbkhkbbh*W8W#hh*&B$$oOvffY#Wp0Jzvuunnnnxxrrjjfjrffrrjt/\//\|\fnvXUUYUUYzurf//\||||||||||||((())))))))(|||(((((())1)|||||||||(()))111))((())()1{{{{11)((()))))(((((( OOOO00QQQCJCCJUUUUUUYYYUUUUYYYYYYYYYYYXXYCwo8$8M*ooo###ohqOOOQQ00QLLQOda#dn(/([??_-}jq&&#bdbbbbddbbbbbbbkbbbbbbbbbbbbbbbbbbkkkkkbkkbbbbbbbbbdpddkhhhhkkkbaWB$hCx/tUW8pQUzccvnxnunnnxrxnnuuuuxffrrfffffffft////tttt///ttft////////tttt//\\\\\\((||||((||(()))||||||((((((((||()11(()))1{1(()(((((((())1)))111 YYXXXXXXXXYYUUYYXXXXYUUUUUUUUUJJJJJUUUUUJCL0wdppppqwwZ00QQLLQ00000OOZm*8hQr||)]--_?/U#$*kbddppdbbkbbbbkbbbbbbbbbbbbbbbbbbbkkbbbbbbbkkkbkbbbbbbbbbbdbkkkbpdh&$hJj\x0%%qQCYXXXcuxxnuuunnnnnnnxrrrxxxrrxxxrrrrrjjffffjjjjjjfttt//////tffffffffjjtttt/\\\\/\\\\\///\|||\\|((((||)111)(((())))1111{{{11)))))))((( uuunuunnxnnuvvuuuvvccczzvvccccXXzzzccvvczXzzzzzzzczcvczXXYXYYXXYYUUJLmW$qc/)){]-??)YdW&kpkkbbdbbkkbbbbbbbbbbbbbbbbbbbbbbbbbbkkkbbbbbkkkkkbbkkkkkkkbbkkkkkka&$dXjjJd%WmLLJUYYzcccccvvuuuuuunnxxxnnunnxxnnxxxxnxxxrjjrxnnxrjjjjffffffjjfffttfjjttffftttfff//////tttttfftttttftt/\\/tt/\\/\||||((((|\\\\///tfff xrjjjjjffjjjjjfffjjjjjrrrrnxrxxxxrrjrrrrjjrxrrrrrrjffjrxnnxjffrnnnxxcLM$Zx/(1[-+_[/m&MobdkkkkbbkkkkkbbbbbbbbbbbbbbbbbbkkbbdbbkkkkbbbkkkkkkkkkkkkkkkbkbkkbbkWBdXrn0hWo0JJUYXzzzccccvvvvvvvvvunnnuuunxrrrxxrrrxrrrxrrxnnxrrxnuxrjjjjffjjfttffjjjfjjrjffjrxjjjjttjjffffjjrxxxxjrrrrxxrjffjfffjftttffjjfffjjjjjj jjjjjjjfftffjfjjjjjjjjjjffft//fffjjfftttfjjjt//tfjfffjjrrjffjjrrrrxxuU*B0f\()}?-](nbB#kkkhhhkkkkkkkkbbbbbbbbbbbbbbbbbbkhkdddbkhkkbbkkkkkbbbbbkkkkbbbkhhkbbkWBdXrxOa#hQUYzvccccvuuuuunuuuvvunnnnnnnnnnnxxxnnnxrrxxnxxrjjjrxnnnnxxxxrrrrrjfjrxxrrxxxxjjrxxrjrrffjjjjjrrrxxxrjfjxxrxxxrjjrrjxxxrjjjjjjjjjjjjjjj ffttffffffffffffjjjjjfff//tt//tfffffft////tft//ttfffffrrrjjrxxxrrnnncC#BQt(11[--[tUo$Mkhhhkbbbbkkkkkkbbkkkkkkkkkkkkkkkkkbbbbkkkkbbbkkkkkkbbbbkkkkbbbbbkkdba&$pcfrZo#kQJUXcvvunxnuunnxxxxnnxxxxxxxxnuuunnnnnnrrxnnnxxxxxxxxnnuunxnnnnxxrrrrrrrxxxxxxrrxrrrrnuuuunnnnnnnnuunrjrnnnxxnnxxxxxxxxxrrrjjjrrjjjjjjj tt/tttftttffffffftttttff//////ttttttffffffffjjfffffffjrxnuuuuuuvvuuuUm&BQft|{]__[r0#B*bkhkkbddbkhhkkbkkkkkkkkkkkkkkkkkbbbkkkkkbbbbkkkkkkkkkkkkkkkkkbbbkkbbh&$pcjnq#MkLYYzvunnnnnuuvuunnuuuunnuuuunnuunnnnxrrrnuvvuuuvcvvuuvvuunuuvccvuuvvvvuuuuuuuuvvunxrxnuuunnnuvunxxnnnnnnuunxxxnnxrrrrrxxxrjjrxnnnnxxxxx fttt//////ttfffjjtttjjjffjxxxrjjjjfjrrxxnunnnnuuuxjjrxnuunxnuvvvuvuvQb#az||)[--?1vqM%obbkhhkkkkkkkkkkkkkkkbbbbbbkkkkkkkkkkkkhhkkkkkkkbbbbbbbkkkkkkkkbbkkkkkW$bUnuZoWhCXzccvuvuuunnvvvunuvvuuuvuxrxuvunuunxrrrxnuuuuunnnnuvvuxrrrxnuuuuuuuuuvvvvvvvvvvvunxxxnnnnxxxxxxnnnnnnnuuunnxrxnnnxxnuunxxuvcvuuvuuuvvv ///\\\\//tffffjrrrrrjjjjrrjjrjjjrrrrrrrxxxxxxnnnxrjjxxxnnnnnnnuvuunvQkhqu|\|}?][(UaMMakhhhhhhhkkkkkkkkkkkkkbbbbbkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkbbbkkbbW$kUxrCbWoLXXzccvuuuuuuvvuuuuvvunnunrjjrxnnxxnxxxxnnnuxrrrxnnxrrrxxxxrrxnnxxrjjjrxrrxxnnuuuunxxnnnnnnnxxxxnnnxxxnnnnxnnxxnunxxxnnnrrnuuunnuuuuuuu \\\/ttttt////ttffjjjftffjf//tttttfjjjjjfffjrrrftfjjrrjjrxrrxnxxrxxxv0hhZt-1)}?-]|C#W#kdkkbbkkkkkkkkkbbbkhhkkkkbbbbbkkkkkkkbbbbbbkkkkkkkkkkkkkkbbbbbbbkkkkkhW$hCnn0a8oLXXcvvunnnnnnnnxnnnnunrrnnxrrrxnnxrxrjjrjjjjjrrxxxxxrrxxxjjrxuunxxnnxrrjrrrrrrxnnnxxrxxxxnnnnnnnnuunxnunxrjrxxxnxxxrrrxnnxxxrjjrnnnnuuu ffffffffffffftfjrrrrrxnnxrxxxrjffjxxxxnxxxnuunrfjjxrjfffjjruvxrjjxxnLkhmt-)(}]??{nmW$#kkkbbkkkkkkkbbbbbbhhhkkkkbbbbkkkkkkkkkbbbbbbkkkkkkkkkkkkkkbbbkkkkkkkh&$aQuuZaMkYvcuxnnxrrrxnnxrjjjjxnrjrjjjrjfjjjrxjttjjjjjjjrrjjfffjjrrjffrnnnnnuunxxxxxnnnnuuunxrrxxxxxnnnxxxxxxxrxxrjt/tfffjjfjjjjrrxxrjjrrxnnnnnnn nxxrrrrxxxrjjfjxxxrxnnnxxxnxxrrrxxxxrxxnnnnnxxxxxxnnxxxrrxnuunnuunxnYwMWU|(1}[[-~]tOM8WkdkhkkkkkkkkkkkkkkkkkkkkbbkkkkhkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkhkbdkMB*mzvZa#bXvcuxnnnxxxnnxrjjjjjxxrjjrrxnxjjrxxxrjjxxxxrxxxxxxrrrrrrrxxrrrrjjjrrrrxxjfffttffjffttfffffjjjjjjfffjjrrrjttffffffffjffjrrrrjffjjjrrjjjj xxnnuuunnnnnnunxxxnnnxxxnnnnnnvvunxxnnnnnnnxxrnnnnnnxxnnnnuxxnuvuxrjxzp*qYt)(1]-_+?/Y*$&ohkkkkkkkkkkkkkkbbkkkkkbbkkhhhhkkkkkhhhkkkkkkkkkkkkkkkkhhhhhkkhhkka&BoZvnOhMbYcXvxxnxrrjjjrjfftffjjfftfrxxrjffjjftttjjjftfffffjjjrrrrrrrrrjjjjjjjrrrrjjjffffffftttfft/////tt/\\\/ft/tt//ttt/t/////tttffffffjffffjjjj On path-likes @TamoghnaChowdhury suggests taking path as an actual pathlib.Path instead of as a str, at least for the purposes of the type hint. Maybe even path: pathlib.Path | str to shut the type checker up (I'm not sure where you can get the type annotation PathLike from)? You can use os.PathLike. However, if we were to abide by the protocol of the inner open() call, then a PathLike is incorrect, because it can also take a file-like: :param fp: A filename (string), pathlib.Path object or a file object. The file object must implement ``file.read``, ``file.seek``, and ``file.tell`` methods, and be opened in binary mode. But I consider all of that to be a bit much for this application, and would constrain it to PathLike for simplicity and clarity. Simplified algorithm I don't think you need to bisect. You can simply load the image in 'F' mode (32-bit floating-point), scale to your min and max, round to the nearest index and then index into your charset. You can take the opportunity to improve Numpy vectorisation and eliminate your loops. from os import PathLike from pathlib import Path import PIL.Image import numpy as np CHARSET = ( "@$B%8&WM#*oahkbdpqwm" "ZO0QLCJUYXzcvunxrjft" "/\|()1{}[]?-_+~<>i!l" "I;:,\"^`'. " ) def resize(image: PIL.Image.Image, new_width: int = 300) -> PIL.Image.Image: width, height = image.size new_height = new_width * height / width / 2.5 return image.resize((round(new_width), round(new_height))) def pixel_to_ascii(pixels: np.ndarray, light_mode: bool = True) -> str: direction = 1 if light_mode else -1 charset_str = CHARSET[::direction] charset = np.array(tuple(charset_str), dtype='U1') minp = pixels.min() maxp = pixels.max() scaled = (pixels - minp) / (maxp - minp) * (len(CHARSET) - 1) indices = np.around(scaled).astype(int) ascii_array = charset[indices] rows = ascii_array.view(f'U{pixels.shape[1]}')[:, 0] return '\n'.join(rows) def convert(path: PathLike) -> str: greyscale_image = resize(PIL.Image.open(path).convert('F')) return pixel_to_ascii(np.array(greyscale_image)) def main() -> None: ascii_img = convert('archived/image2l.png') print(ascii_img) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43684, "tags": "python, image, ascii-art" }
How do you obtain transition relation of a PDA?
Question: I know how to figure out the start state, accepting state, input alphabet, and all that stuff. But how do you develop the transition relation of a PDA? For an FSM, (q0,a),q1) means if you start at q0 and get an a, you transition to q1. But what does (S,a,e),(S,a) mean? (S is start state and e is epsilon) Here's a picture if that helps. I want to understand the circled part. I will be extremely appreciative of any help. Answer: As you can see, $\Delta$ is a set of pairs that represent a transition function. First element of the pair is a triple $(q, a, X)$, where $q$ is a state, $a$ is an input symbol (possibly empty string), and $X$ is the top stack symbol. The other element of the pair describes the action of PDA when its configuration fits the above triple. This other element is again a pair $(p, \gamma)$, where $p$ is a new state and $\gamma$ is a sequence of symbols replacing $X$. If $\gamma = \epsilon$, then $X$ is just popped. It might help to view $((q, a, X), (p, \gamma))$ as $$(q, a, X) \rightarrow (p, \gamma)$$
{ "domain": "cs.stackexchange", "id": 2030, "tags": "pushdown-automata" }
How much difference to interior temperature would a white car roof make?
Question: My van has a mostly dark green exterior which becomes extremely hot to the touch by the middle of the day. Inside the only thing that keeps it bearable is having air con at full and as soon as the engine is cut and hence air con its only minutes before the temperature rises again. I am toying with the idea of getting up on the roof with a can of white or silver spray paint. How effective could that be - would it be worth the hassle plus the loss of aesthetics (I'm traveling in it so I'll take function over form if it could drop the ambient temp by more than a few degrees)? Answer: Having lived in Arizona for 23 years, experience has taught me that black cars get hotter than white. I found this article where "The researchers had two cars in the sun for an hour, one black and the other silver, parked facing south, in Sacramento, California," which would be a much milder example than all day in the Phoenix sun, but in just one hour there was a difference. Also, note their conclusions about fuel economy and greenhouse and pollution emissions. http://phys.org/news/2011-10-silver-white-cars-cooler.html
{ "domain": "physics.stackexchange", "id": 27711, "tags": "thermodynamics" }
Question about pointer in PCB structure and meaning of job queue
Question: PCB structure exists inside kernel area. And in ready queue, which is Linked List, each Node of the queue is PCB. And this mean PCB Node has the next address of PCB in the queue, right?? Then My question is this.. Does PCB structure has pointer field that has address of next PCB structure?? According to Wikipedia, Job Queue consists of process waiting to be allocated to Memory. But, in terms of 'process', process means the program loaded on the Memory waiting to be executed or being executed. And how can Job Queue consists of process, that is not loaded onto the memory(I think we can't say it is process because it is not on the Memory) Answer: PCB structure exists inside kernel area. And in ready queue, which is Linked List, each Node of the queue is PCB. This is correct, however in most operating systems, ready tasks are sorted by priority to ensure that the most important task will run next. So the design of the ready queue may be more sophisticated than this in practice. Does PCB structure has pointer field that has address of next PCB structure?? This is the way that it's usually done. Of course, if it is implemented as a doubly-linked list, it will have a "previous" pointer too. According to Wikipedia, Job Queue [...] I can see why this may be confusing. The Wikipedia page that you're talking about is about batch processing systems. This is a related idea, and there are batch processing systems without user interaction, but it's not relevant to what you're trying to understand.
{ "domain": "cs.stackexchange", "id": 17757, "tags": "operating-systems, process-scheduling" }
Why is this mapping from binary to natural numbers surjective?
Question: In my Lecture we came across something of importance for the Church-Turing-Thesis and i noticed one particular function, which confused me. Function: Let $bin(x)$ be the injective binary extension without leading zeros. It is not surjective because of the extension without leading zeros. $$cod := \{0,1\}^* \to \mathbb{N} \hspace{2mm} x \mapsto bin^{-1}(1x)-1$$ Question: Why is this particular map from the binaries and the natural numbers surjective ? I do not need a intricate proof, but a explanation is enough to wrap my head around this topic. They also noted that $bin^{-1}$ can be written, because 1x is in the image of $bin$. Injectivity is given, because $bin$ is injective and on two different strings $x$ and $y$ we get two different decimal numbers out of the function. Thanks in advance for any awnser on this question, or any comments posted on it. Answer: For any number $n\in\mathbb{N}$, consider $bin(n+1)$. Since $n+1>0$, there must be at least one bit in $bin(n+1)$ in the state of "1". Its not too hard to see why this immediately implies that there exists some $x\in \{0,1\}^*$ such that $bin(n+1)=1x$ (since we can remove the trailing zeros), and hence $n+1={bin}^{-1}(1x)$, meaning that $n={bin}^{-1}(1x)-1=cod(x)$. Therefore $cod$ is surjective by definition.
{ "domain": "cs.stackexchange", "id": 19415, "tags": "mathematical-foundations" }
Which force is responsible for victory in tug of war?
Question: I'm confused: In a tug of war game on rough ground who will win? The one who applies greater force on the rope or the one who applies greater force on ground? Answer: The force on rope is equal for both of them at any time. For winning the game the force on ground is responsible.
{ "domain": "physics.stackexchange", "id": 43591, "tags": "newtonian-mechanics, forces, everyday-life" }
PR2 Segfaults Gazebo World
Question: I have been trying to get the pr2 simulator up and running but I seem to be having issues with segfaults that have something to do with pr2_no_controllers.launch. I ran the following, roslaunch gazebo_worlds empty_world.launch roslaunch pr2_gazebo pr2_no_controllers.launch I went into the launch file to see what I could comment out and see when segfaults stop. It seemed to be when the pr2_description is pushed to the robot_description. <!-- push robot_description to factory and spawn robot in gazebo--> <node name="spawn_pr2_model" pkg="gazebo" type="spawn_model" args="$(optenv ROBOT_INITIAL_POSE) -unpause -urdf -param robot_description -model pr2 -ros_namespace /gazebo" respawn="false" output="screen" /> I also ran, roslaunch gazebo_worlds debug.launch and bt after (gdb) This code block was moved to the following github gist: https://gist.github.com/answers-se-migration-openrobotics/8675ab3497ba3637428494164e1b9fe3 Originally posted by ncr7 on Gazebo Answers with karma: 38 on 2013-09-11 Post score: 0 Answer: So Apparently if this happens it means something didn't install correctly. It seemed to about get loaded before, but crash right before it finished loading the PR2. Basically the only thing not loaded would be the arms. I think it was a problem with the cameras loading. I uninstalled everything having to do with ROS and Gazebo and reinstalled. I am not sure what I did differently than any other time I reinstalled Groovy, I reinstalled several times, eventually it seemed to do the trick though... a bit odd. Originally posted by ncr7 with karma: 38 on 2013-09-11 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 3455, "tags": "gazebo" }
What to publish from a new camera driver
Question: Hi! im want to write camera driver for ROS. and got some question: ive read page about ROS camera drivers and did not understand - what type of image have to publish driver: as is image or undistored image (if the camera/camera_info was given)? Originally posted by noonv on ROS Answers with karma: 471 on 2011-11-15 Post score: 1 Original comments Comment by noonv on 2011-11-15: thanks! yes - im want to write camera driver for ROS (update question) Comment by Mac on 2011-11-15: It's not clear what you want to know. Are you asking what you need to publish if you write a new camera driver? Are you asking what existing drivers publish? Answer: Based on the camera drivers wiki page and the first few lines of the image pipeline wiki page, you should publish raw (distorted) images, or the closest thing your camera's API can provide. A user would almost certainly pass these to various parts of image_pipeline to get undistorted, debayered, etc. images for their particular application. Originally posted by Mac with karma: 4119 on 2011-11-15 This answer was ACCEPTED on the original site Post score: 1 Original comments Comment by noonv on 2011-11-15: i see. Thanks!
{ "domain": "robotics.stackexchange", "id": 7313, "tags": "ros, driver, camera, best-practices, camera-drivers" }
Failed to find stack for package [joy] (installing for Nao or PR2 robot)
Question: Hi, I am a newbie here. I got an error message when trying to install ros package for nao robot. I am planning to install ros for pr 2 and nao. I have successfully configured my environment for pr 2. ...[ rosmake ] Generating Install Script using rosdep then executing. This may take a minute, you will be prompted for permissions. . . Failed to find stack for package [joy] Failed to load rosdep.yaml for package [joy]:Cannot locate installation of package joy: [rospack] couldn't find package [joy]. ROS_ROOT[/opt/ros/electric/ros] ROS_PACKAGE_PATH[/home/anshar/ros_workspace:/home/anshar/ros_workspace:/opt/ros/electric/stacks:/opt/ros/electric/stacks] ...... Thank you Cheers, ryann2k1 Originally posted by ryann2k1 on ROS Answers with karma: 128 on 2012-05-03 Post score: 0 Answer: Please be more specific. What exactly are you installing, and where? The error is not specific to either the PR2 or Nao robot. What command causes this error? Looking at "Failed to find stack for package [joy]", it seems like you don't have the "joy" package installed. By looking at its wiki page, you can infer that it's in the "joystick_drivers" stack. You need to install that stack, either from source or with the debian package ros-electric-joystick-drivers. Originally posted by AHornung with karma: 5904 on 2012-05-03 This answer was ACCEPTED on the original site Post score: 0
{ "domain": "robotics.stackexchange", "id": 9240, "tags": "ros, pr2, joy, nao" }
Why are wet bulb temperatures so warm compared to a naive calculation?
Question: Wikipedia defines wet bulb temperature as: the temperature of a parcel of air cooled to saturation (100% relative humidity) by the evaporation of water into it, with the latent heat supplied by the parcel. I would like to calculate this temperature for: $$\begin{align*} T & = 300\;\mathrm{K} \\ RH & = 0.5 \\ P & = 1\;\mathrm{atm} \approx 10^5\;\mathrm{Pa} \end{align*} $$ where $RH$ is the relative humidity. The vapor pressure under these conditions is about $P_V \approx 3.5 \times 10^3\;\mathrm{Pa}$ (source) So I estimate $$\Delta T = \dfrac{Q}{n_{air}c_P}$$ where $\Delta T$ is the difference between wet bulb temperature and ambient temperature, $Q$ is the heat absorbed by the water as it evaporates, $n_{air}$ is the number of moles of air, and $c_P$ is the heat capacity at constant pressure of air. Using $Q = n_{water} L,$ where $n_{water}$ is the number of moles of water that evaporate and $L$ is the latent heat of fusion of water, $$\Delta T = \dfrac{n_{water}L}{n_{air}c_P}$$ The ideal gas law says $$\dfrac{n_{water}}{n_{air}} = \dfrac{\Delta P_{vapor}}{P_{air}}$$ where $\Delta P_{vapor}$ is the change in the water vapor pressure as the water evaporates. I have $$\begin{align*} \Delta P_{vapor} & = .5\cdot 3.5\times 10^3 \;\mathrm{Pa} \\ L & = 40.8 \;\mathrm{kJ/mol} \\ c_P & = 30 \;\mathrm{J/(K\;mol)} \end{align*}$$ $c_P$ is calculated from $c_P = \dfrac72 R$ for a diatomic gas. The source on $L$, the latent heat of vaporization of water, is here. Putting in these numbers, I find $$\Delta T \approx 24 K$$ However, calculators like this one give $\Delta T \approx 7\;\mathrm{K}$. My calculation leaves off some effects such as the heat needed to cool the vapor, but because the partial pressure of the vapor is small compared to that of air, this should be a small effect. So where is the factor of $\approx 3-4$ error coming from? Answer: The problem in your calculation is that it is not possible to evaporate the amount of water that you assumed. You took 50 % of the vapor pressure at $27\ ^\circ$C ($300$ K). But that many moles would supersaturate at the calculated $\Delta T = 24$ K. The amount of water evaporated in a parcel of air is much less. The psychrometric chart below shows the evaporative cooling line from $27\ ^\circ$C at 50 % RH intersecting with the vapor pressure curve at a wet bulb temperature of $20\ ^\circ$C. This is the limit for evaporative cooling, in agreement with the calculator that you quoted. (from http://www.coolbreeze.co.za/psyevap.htm )
{ "domain": "physics.stackexchange", "id": 56664, "tags": "thermodynamics, phase-transition" }
Catenary shape of transmission lines
Question: When flexible metal transmission lines are hung between two poles, the shape they assume to minimize the action of gravitational and tensile forces is a called a catenary. While assuming that shape, the line undergoes stretching and internal shear which will cause it to degrade. Further, the shape keeps changing due to the extensibility of the line. Consider a transmission line design consisting of flexible transmission wires wrapped around a rigid supporting metal beam (pole). Is there a benefit (in terms of material degradation) in manufacturing the supporting rigid beam (made of metal) in the shape of the catenary to begin with? Answer: The shape of the catenary is the result of the requirement that internal forces are only acting tangential to the curve shape, and there is no shear or bending moment along the wire. If $H$ is the horizontal tension, and $V$ the vertical (shear) tension then you have $$ \frac{V}{H} =\frac{{\rm d}y}{{\rm d}x} $$ The segment's total weight is balanced by the difference in vertical forces (and hence zero internal shear forces). $$ {\rm d}V = \lambda \sqrt{1+ \left(\tfrac{{\rm d}y}{{\rm d}x}\right)^2} {\rm d}x $$ Here is a post of mine about the development of the equations. So now what can happen if you design a cable with built-in curvature to match the shape? well, essentially a thin wire has zero resistance to bending (an assumption for the catenary shape development since internal moments are zero). So the initial shape of the cable does not matter. In fact, it comes in a spool that is much more curved than when installed. Or maybe you are thinking of replacing the stranded wire with a solid one of the correct shape, which has other problems. For one, the internal tensions are still going to be tangential only, but due to the extra weight, natural frequencies will be much lower and hence more prone to galloping vibrations. And the friction between the strands provides a level of vibration damping that protects the cable. Also, the current capacity will be diminished as electrons like to travel on the surface of the metal and the stranded shape has a much higher surface to volume ratio. Finally, mechanically speaking it would be harder for a solid wire to respond to changing environmental conditions (like temperature, ice and wind) which change the loading and the force balance shape.
{ "domain": "physics.stackexchange", "id": 78525, "tags": "newtonian-mechanics, variational-calculus, solid-mechanics, structural-beam, structure-formation" }
CSV parsing in Perl
Question: I am looking for a Perl (5.8.8) script for CSV parsing that would follow CVS standards. (See Wikipedia or RFC-4180 for details) Sure, code should be fast enough, but more important is that it should use no libraries at all. This is what I have for now : #!/usr/bin/perl use strict; use warnings; sub csv { no warnings 'uninitialized'; my ($x, @r) = (pop, ()); my $s = $x ne ''; $x =~ s/\G(?:(?:\s*"((?:[^"]|"")*)"\s*)|([^",\n]*))(,|\n|$)/{ push @r, $1.$2 if $1||$2||$s; $s = $3; ''}/eg; $r[$_] =~ s/"./"/g for 0..@r-1; $x? undef : @r; } @test = csv( '"one",two,,"", "three,,four", five ," si""x",,7, "eight",' . ' 9 ten,, ' . "\n" . 'a,b,,c,,"d' . "\n" . 'e,f",g,' ); (!defined $test[0])? die : print "|$_|\n" for @test; Same code, but with comments : #!/usr/bin/perl use strict; use warnings; sub csv { no warnings 'uninitialized'; # we can use uninitialized string variable as an empty without warning my ($x, @r) = (pop, ()); my $s = $x ne ''; # function argument (input string) goes to $x # result array @r = () # variable $s indicates if we (still) have something to parse $x =~ s/\G(?:(?:\s*"((?:[^"]|"")*)"\s*)|([^",\n]*))(,|\n|$)/{ # match double-quoted element or non-quoted element # double-quoted element can be surrounded with spaces \s* that are ignored # and such element is any combination of characters with no odd sequence # of double-quote character ([^"]|"")* # non-quoted element is any combination of characters others than double-quote # character, comma or new-line character ([^",\n]*) # element is followed by comma or new-line character (for non-quoted elements) push @r, $1.$2 if $1||$2||$s; # if match found, push it to @r result array $s = $3; # do we (still) have something to parse? '' # replace match with empty string, so at the end we can check if all is done }/eg; # /e = execute { ... } for each match, /g = repeatedly $r[$_] =~ s/"./"/g for 0..@r-1; # replace double double-quotes with double-quote only $x? undef : @r; # if $x is not empty, then CSV syntax error occurred and function returns undef # otherwise function returns array with all matches } @test = csv( '"one",two,,"", "three,,four", five ," si""x",,7, "eight",' . ' 9 ten,, ' . "\n" . 'a,b,,c,,"d' . "\n" . 'e,f",g,' ); # simple test (!defined $test[0])? die : print "|$_|\n" for @test; # die if csv returns an error, otherwise print elements surrounded with pipe char | The code gets the following output: |one| |two| || || |three,,four| | five | | si"x| || |7| |eight| | 9 ten| || | | |a| |b| || |c| || |d e,f| |g| || All improvements will be appreciated. Answer: General Overview It is unreadable This is OK as an exercise for your reg ex muscles. BUT this is not maintainable code. As such it is would never get past a code review at any company or get placed in production. You may get away with it for a one off script that you throw away. Code Comments Perl has a reputation as being unreadable. Fortunately it does not need to be (unless you are entering the Perl obfuscated contest). So best not to write Perl that is unreadable (as you will not understand it next year) Your code is written in a way that makes modification after release nearly imposable. A bug fix or update will have to build the reg-exp from the ground up to understand how it works. Variable names should be meaningful. There is no reason to use @_ for example as your own variable. Always have the following in your code (unless there is a very good reason not too) use strict; use warnings; It is always a good idea to run your code through lint perl -MO=Lint foo.pl Algorithm Regular expressions are not well suited for parsing complex structures. Though CSV may look simple on the surface; it is unfortunately inherently complexity with nested line breaks and quotes. A better idea would be to define a real parser using the grammar defined in RFC-4180 as a starting point.
{ "domain": "codereview.stackexchange", "id": 1539, "tags": "parsing, perl, csv" }
How do we conclude that polarized dielectric in electric field reduces overall field?
Question: If we have a dielectric inside an electric field, the dipoles in the dielectric will align in the following direction due to the torque on them by the external field. The conclusion then is that the overall field is reduced since positive charges appear on the bottom plate and negative on the top, opposite to the applied field. But if we consider the field of the electric dipole itself, we know that it points in the same direction as the dipole moment. The dipole moments clearly point in the same direction as the applied field. So shouldn't the field due to the polarized dielectric point in the same direction as the applied field, thus strengthening it? Answer: You need to at least assume a convention for direction of electric fields. I am using the conventions that is used pretty much everywhere, in this convention the electric field points from positive to negative. I have marked the external field in blue and field of dipole in green, it is clearly evident that both the fields are opposing and hence cancel each other. Therefore, the net field magnitude reduces. Edit/Update (To explain the question raised in comment) : I think you understand that the field reduces inside the dielectric medium. But pay attention, if you look at the dielectric material on an atomic scale will you call the dipoles the dielectric material or the spaces between them? When we look at the dielectric material on atomic scales we need to start looking at the dipoles and not outside them because these dipoles are what make rhe dielectric material. Moreover for a solid or liquid dielectic material these dipoles are far more than the spaces between them, your picture in this sense is a little misleading. The following picture is a better depiction of what is more likely to be found in dielectrics.
{ "domain": "physics.stackexchange", "id": 16127, "tags": "electrostatics, dielectric" }
Normalization problem with hydrogen wavefunction
Question: Suppose you have a mix of states made up of the Hydrogen $\lvert nlm \rangle$ states where one of the coefficients is unknown. For example: $$ \lvert \psi\rangle=A\lvert 100\rangle + \sqrt{\frac{2}{3}}|210> + \sqrt{\frac{2}{3}}\lvert 211\rangle - \sqrt{\frac{2}{3}}\lvert 21-1\rangle $$ Since all the hydrogen wavefunctions $\lvert nlm \rangle$ are orthonormal I suppose that the normalization condition does not work for the above example since $$ \lvert A\rvert^2+\frac{2}{3}+\frac{2}{3}+\frac{2}{3} =\lvert A \rvert^2+2 > 1 $$ regardless the value of $A$. Even if one takes $A=i$ (purely imaginary) still the normalization does not work. Am I missing something here? Can the above function be normalized by a particular choice of $A$ coefficient? Answer: The answer is that the premise is wrong. There can't be a hydrogen wave function with the coefficients you have written. Even if there was no $| 1 0 0 \rangle$ state present, the state isn't normalized. That means that it isn't physical. However, remember that the coefficients are somewhat arbitrary, that is, we're allowed to multiply the whole wavefunction by some constant $C$. That's how we normalize them in the first place. So the important thing about your state isn't the $\sqrt{\frac{2}{3}}$ part, it's the fact that all the other coefficients are the same, have equal probability. So you could write something like $$ \newcommand{\ket}[1]{| #1 \rangle} \ket{\psi} =A\ket{100} + B\ket{210} + B\ket{211} - B\ket{21-1} $$ $$ |A|^2+3 |B|^2 =1 \\ |A|^2 = 1 - 3 |B|^2 $$ So from this you can see the condition on $B$ for your example to make sense, we need $|B|^2 < 1/3$. (We can get a negative square from imaginary numbers, but never a negative absolute square.) Basically, there needs to be some probability left over for the other state you want to insert. Give me that probability for the other three states and I can tell you the magnitude of the other one, but I can't do that for the state you provided.
{ "domain": "physics.stackexchange", "id": 21470, "tags": "quantum-mechanics, homework-and-exercises, hilbert-space, hydrogen, normalization" }
X Linked Hardy Weinberg Equilibrium Problem
Question: In a given population under Hardy Weinberg equilibrium, 40.0% of men have hemophilia. What is the probability that a random man and random woman will have a daughter with haemophilia? I think the answer is 16%, but the answer given is 9.6%. According to Hardy-Weinberg principle, p2 + 2pq + q2 = 1. In order to inherit the disease, the mother must either be a carrier of have the disease, which occurs with probability 1-q2 = 0.72 Therefore, the odds of having a child with the disease is (0.84)(0.4). Since it asks for the probability of a girl, the total must be divided by two, so the answer is 0.168 Where am I wrong? Answer: I make it 8%. Here is my reasoning. The gene is X-linked. 40% mutant males, so freq(mutant allele) = p = 0.4, and freq(wt allele) = q = 0.6 To get a mutant female we have to have a mutant male parent, probability = 0.4 Of these matings one half will produce a female offspring so 0.4*0.5 = 0.2 i.e. 20% of matings derive from a mutant male and produce a female offspring. Now look at the female mate: probability(mutant) = p2 = 0.16 probability(carrier) = 2pq = 0.48 probability(wt) = q2 = 0.36 so our 20% of matings that have the potential to produce a mutant female offspring partition as: mating with a mutant female: 0.2 x 0.16 = 0.032 mutant female offspring mating with a carrier female: 0.2 x 0.48 = 0.096 of which: 0.048 mutant female offspring 0.048 carrier female offspring mating with wt female: 0.2 x 0.36 = 0.072 carrier female offspring (sanity check - 0.032 + 0.096 + 0.072 = 0.2) Thus the probability of random mating producing a mutant female is 0.032 + 0.048 = 0.08 (8%) Incidentally there is another way of thinking about this. Note that the H-W frequency of mutant females in the population is 16%. One of the assumptions of H-W is random mating. So the probability of a random mating producing a mutant female = p(female) * p(mutant if female) = 0.5 x 0.16 = 0.08 So - where have I gone wrong?
{ "domain": "biology.stackexchange", "id": 8517, "tags": "genetics, hardy-weinberg" }
MATLAB 3D Simulation with SOLIDWORKS model
Question: I'm learning to make a 3D simulation in MATLAB based on a model designed from SOLIDWORKS. There is an example: SIMULINK+SOLIDWORKS The way used here is: Create a 3D model in SOLIDWORKS Create a xml file applicable to import to MATLAB via SimMechanics Link Import the model to MATLAB/SIMULINK. A simulink system is created. After these steps, controlling the system will be implemented in SIMULINK. But I feel simulink is kind of strict to control. I want to be more flexible, apply any algorithm to the model. And using matlab *.m file to control is more efficient way. So my question is this: Is there any way to do 3D simulation (MATLAB+SOLIDWORKS) by using only *.m file to control, no SIMULINK anymore? All model information will be contained in the *m.file. Maybe the step 1 and 2 are inherited, but step 3 is different. Answer: I use CAD software to generate 3D models, convert those 3D models to an STL format, then load those STL files to Matlab with the following script: function [points,success] = LoadSTL(path) % LoadSTL loads an ASCII STL file with units in [mm]. % The output is a structure array where each element in the array is % a vertex. % % [points , success] = LoadSTL(path) % % path = String containing the path and extension of the file to be loaded. % points = Matrix of locations where each column is a vertex, rows are x/y/z/1: % points(1,:) = x % points(2,:) = y % points(3,:) = z % points(4,:) = 1 % NOTE - every three columns is a new face/facet. % success = Bit indicating if the file was successfully opened or not. success = 0; fileID = fopen(path); if fileID <0 fprintf('File not found at path %s\n',path); return; end fprintf('Loading Path %s...\n',path); fileData = fread(fileID,'*char'); eol = sprintf('\n'); stlFile = strsplit(fileData',eol); fclose(fileID); fprintf('Done.\n') pause(0.25); clc assignin('base' , 'stlFile' , stlFile) pointsTracker = 1; for i=2:size(stlFile,2) if mod(pointsTracker,100)==0 clc fprintf('Parsing file at %s...\n',path); fprintf('Currently logged %d points\n',pointsTracker); end testLine = stlFile{i}; rawStrip = strsplit(testLine , ' ' , 'CollapseDelimiters' , true); if numel(rawStrip) == 5 points(1,pointsTracker) = str2double(rawStrip{1,3})/1000; points(2,pointsTracker) = str2double(rawStrip{1,4})/1000; points(3,pointsTracker) = str2double(rawStrip{1,5})/1000; points(4,pointsTracker) = 1; pointsTracker = pointsTracker + 1; end end disp('Done.') pause(0.25); clc; if mod(size(points,2),3) > 0 disp('File format in an unexpected type.') disp('Check the file specified is an STL format file with ASCII formatting.') disp('(Error - number of vertices not a multiple of 3)') disp(numel(points.x)) return; end success = 1; return; Once this is done I save the resulting output (points) as a .mat file and load exclusively from that .mat instead of the STL file because the .mat file loads significantly faster than parsing the STL file every time. Once you've loaded the file, you can quickly plot the STL file in Matlab with the following command: myPlotColor = [0.5 0.5 0.5]; nFaces = size(points,2)/3; patch(... reshape(points(1,:),3,nFaces) , ... reshape(points(2,:),3,nFaces) , ... reshape(points(3,:),3,nFaces) , ... myPlotColor); At this point, standard Matlab plot commands work; e.g., axis equal, hold on, etc. Now, given how to load and display STL files in Matlab plots from an m-file, you can go about doing whatever form of control you want. Transform the CAD file with any 4x4 transform matrix composed of a rotation matrix $R$ and translation vector $s$: $$ \mbox{transformedPoints} = \begin{bmatrix} & R& & s \\ 0 &0 &0& 1 \\ \end{bmatrix} \mbox{points} $$ Plot the transformed points with the patch command shown above. As long as you've generated your CAD model such that the origin of your 3D model corresponds with the origin of your mathematical model then any movement/rotation of the mathematical model about its origin can be correctly applied to the CAD model, which can then be displayed. I'd just like to reiterate that this file loads STL files that are in ASCII format with units in millimeters, and the resulting plot is with units in meters, but of course you can change that with the /1000 scaling during the loading of the file.
{ "domain": "robotics.stackexchange", "id": 759, "tags": "matlab, simulation" }
Splitting a UTF-8 string into equal-sized byte-arrays for parallel processing
Question: Based upon a question from Stack Overflow, I wanted to expand on the answer I wrote and define a solution that would support ordering the strings (after processing). So this starts off with a basic struct, and you can guess what it's going to do: public struct Line<T> { public int Order { get; set; } public T Value { get; set; } } I am using it to track a Value and the order the value goes in. Next, we have to have some way of taking a UTF-8 array and determining, at any given index, where does that character start? public static int GetCharStart(ref byte[] arr, int index) { if (index > arr.Length) { index = arr.Length - 1; } return (arr[index] & 0xC0) == 0x80 ? GetCharStart(ref arr, index - 1) : index; } Now I used ref here to help performance: it doesn't modify the array so there's no need to pass anything special around, just reference it as a "pointer". (Though, in reality, ref here is superfluous as the array is a reference already, but it's good to be explicit when possible.) Next, we need to take a byte[] and get a section from it, so I wrote a helper-method: public static byte[] GetSection(ref byte[] array, int start, int end) { var result = new byte[end - start]; for (var i = 0; i < result.Length; i++) { result[i] = array[i + start]; } return result; } Then, finally, we need to be able to return the byte[] array sections, one-by-one, to pass to our parsing. This uses IEnumerable and yield return to be lazy (I'm a lazy dev, so I may-as-well write lazy code). public static IEnumerable<Line<byte[]>> GetByteSections(byte[] utf8Array, int sectionCount) { var sectionStart = 0; var sectionEnd = 0; var sectionSize = (int)Math.Ceiling((double)utf8Array.Length / sectionCount); for (var i = 0; i < sectionCount; i++) { if (i == (sectionCount - 1)) { var lengthRem = utf8Array.Length - i * sectionSize; sectionEnd = GetCharStart(ref utf8Array, i * sectionSize); yield return new Line<byte[]> { Order = i, Value = GetSection(ref utf8Array, sectionStart, sectionEnd) }; sectionStart = sectionEnd; sectionEnd = utf8Array.Length; yield return new Line<byte[]> { Order = i + 1, Value = GetSection(ref utf8Array, sectionStart, sectionEnd) }; } else { sectionEnd = GetCharStart(ref utf8Array, i * sectionSize); yield return new Line<byte[]> { Order = i, Value = GetSection(ref utf8Array, sectionStart, sectionEnd) }; sectionStart = sectionEnd; } } } The if block in this just prevents the last line from being ~2x the size of previous lines (which can be the case if there are high-code-point UNICODE glyphs. Finally, I assemble the entire result in a GetStringParallel method: public static string GetStringParallel(byte[] utf8ByteArray, int sections = 10, int maxDegreesOfParallelism = 1) { var results = new ConcurrentBag<Line<string>>(); Parallel.ForEach(GetByteSections(utf8ByteArray, sections), new ParallelOptions { MaxDegreeOfParallelism = maxDegreesOfParallelism }, x => results.Add(new Line<string> { Order = x.Order, Value = Encoding.UTF8.GetString(x.Value) })); return string.Join("", results.OrderBy(x => x.Order).Select(x => x.Value)); } This does the parallelization, handles parsing the results, and joins everything together. Now, ignoring the lack of a class that does this work, I'd love any suggestions. It would be a class in the real-world, and I understand that, I just didn't make it a class because (again) I'm lazy. Also note that this is probably a hell-of-a-lot-slower than the built-in decoding, and I make no claims for either case. This is just a really cool experiment that also demonstrates the self-synchronicity of UTF-8. Test case: var sourceText = "Some test 平仮名, ひらがな string that should be decoded in parallel, this demonstrates that we work flawlessly with Parallel.ForEach. The only downside to using `Parallel.ForEach` the way I demonstrate is that it doesn't take order into account, but oh-well. We can continue to increase the length of this string to demonstrate that the last section is usually about double the size of the other sections, we could fix that if we really wanted to. In fact, with a small modification it does so, we just have to remember that we'll end up with `sectionCount + 1` results."; var source = Encoding.UTF8.GetBytes(sourceText); Console.WriteLine("Source:"); Console.WriteLine(sourceText); Console.WriteLine(); Console.WriteLine("Assemble the result:"); Console.WriteLine(GetStringParallel(source, 20, 4)); Console.ReadLine(); Result: Source: Some test ???, ???? string that should be decoded in parallel, this demonstrates that we work flawlessly with Parallel.ForEach. The only downside to using `Parallel.ForEach` the way I demonstrate is that it doesn't take order into account, but oh-well. We can continue to increase the length of this string to demonstrate that the last section is usually about double the size of the other sections, we could fix that if we really wanted to. In fact, with a small modification it does so, we just have to remember that we'll end up with `sectionCount + 1` results. Assemble the result: Some test ???, ???? string that should be decoded in parallel, this demonstrates that we work flawlessly with Parallel.ForEach. The only downside to using `Parallel.ForEach` the way I demonstrate is that it doesn't take order into account, but oh-well. We can continue to increase the length of this string to demonstrate that the last section is usually about double the size of the other sections, we could fix that if we really wanted to. In fact, with a small modification it does so, we just have to remember that we'll end up with `sectionCount + 1` results. Answer: Well, using ref as a way to improve performance doesn't sit well with me, as it kind of violates the contract. I doubt the gains (if any) justify it. Micro-optimizations should probably begin with replacing recursion with a loop. Another thing to optimize is your partitioning logic: Encoding.GetString has an overload that takes start index and count. If you use it instead, you can avoid new byte[end - start]; call and subsequent copying. If you do need a copy for some reason, then you should use Buffer.BlockCopy method. Element-by-element copying in for loop is considerably slower for larger arrays. GetByteSections is a bit counter-intuitive as it apparently returns sectionCount + 1 items. That's not what I would expect. There is also a little bit of copy-paste in for loop's body, that can probably be avoided. You can use Line<string>[] instead of ConcurrentBag and put results in correct order straight away using indexer: results[resultLine.Order] = resultLine;. No additional synchronization is needed as long as Order values are unique, which seems to be the case. Everything else looks alright to me.
{ "domain": "codereview.stackexchange", "id": 26601, "tags": "c#, strings, .net, iterator, task-parallel-library" }
What would be the reaction if melting iron is put in normal water?
Question: What would be the reaction if melting iron is put in normal water? Will water be chemically changed? Answer: Unlike the other metals we usually see in the reactivity series, such as calcium, magnesium, zinc, etc., hot iron does not form iron hydroxide, instead it forms iron oxide. The reaction is: $\ce{3Fe + 4H2O <=> FeO.Fe2O3 + 4H2}$ Iron is similar to magnesium and zinc as they react only with hot water (not cold water). But the reaction of iron with hot water is less vigorous than that of magnesium and zinc.
{ "domain": "chemistry.stackexchange", "id": 2229, "tags": "water, metal" }
Photon near a black hole - find distance of closest approach from impact parameter
Question: I have the equation relating the impact parameter $b$ to the distance of closest approach $R$. $R^3 - b^2R + 1 = 0$ which can be solved in python. I have a given $b$ and have to find $R$. however, in some cases of $b$ there are up to 3 solutions which are real and positive. How to I choose the true answer? eg for $b = 5$ i have solutions $[-5.01988126, 4.9798787 , 0.04000256]$ NOTE this is in units of c = r_schwarzchild = 1 Answer: Peter Schor's comment that one of the three roots of the cubic must be negative is correct. In general, you have to select the root that is physically relevent. You can reject the negative root, and for the Schwarzschild geometry, any root smaller than the photon sphere radius at $1.5 r_s$. Also, I believe that you have an error in your equation for $R$, since as written, it does not have the correct solution at the critical impact parameter, that allows the closest approach where it is still possible for a photon to escape. I assume that you derived the equation by solving for $\frac{dr}{dt}=0$ at closest approach, and using normalized radius and impact parameter as follows, where $r_s$ is the Schwarzschild radius. $$R = \frac{r}{r_s}$$ $$B = \frac{b}{r_s}$$ I believe that the equation for $R$ should be as follows. $$R^3 - B^2(R-1) = 0$$ Solving this equation for the critical impact parameter, $B=3 \sqrt{3}/2$, results in a double root at $R = 3/2$, and a negative root at $R = -3$. Solving the equation at a slightly larger impact parameter, say $B=3$, gives roots at about 2.227, 1.185, and -3.411. Clearly only the larger radius can be a solution. The solution at $B=5$ is about 4.394.
{ "domain": "physics.stackexchange", "id": 61560, "tags": "general-relativity, black-holes, photons, astrophysics, linear-algebra" }
How to BLAST a protein against a large set of organisms?
Question: I have a list of organisms with their full scientific names and Taxonomy IDs, total ~1500. I want to BLAST my protein against this 1500 genome or proteome. How can I do that? Here a sample protein that I want to search the following database: http://togodb.org/db/thermobase Please note that database can be downloades as CSV file. I am very comfortable using web tools or programmatic tools such as Perl, Python, bash, or Entrez Programming Utilities. >QCC44558.1 chitinase [Halobacterium salinarum] TaxID 641522631 MPHDRRSYLRTSSAVIASLLAASTPTSAADTPPEWDPDTVYTDGDKATFDGYVWEAKWWTKGDKPGADEW GPWTQRRPVDGSPGGPTAAFTVTDTTVEPGTAVTVDASDTTGSVDSYEWAFGDGTTAAGVTASHTYDAAG EYTIELTVTTGDGTTDTATQQITATTSPGDDEFKVVGYYPSWKGTDDYDFYPADVPFDQVTDVLYAFLDV QPDGTVVLPDSDVDHESLLASFASLKQDRAADTRLKLSIGGWGLSPGFEDAAADQASRERFATTAVDLMR TYDFDGIDVDWEHPGPRRGKCECGSAQGPANHVALLETVRDRLNDAEVEDGRTYDLSVANGGSDWNAALI NHREVAAVVDDIYMMAYDFTGVWHGTAGLNAPIYGTPPDYPPSGDAQQYTLETTLTIWKEQGYWVDWMEW EDHGDPVDDPGTLVLGMPFYGRGCNVENGIWDTFSLSEWQQGDPKYQNDVIPPGTWNDLRGPDDANTGAF DYGDLAANYEGADAWTKQRNEQGGVPYLWNDSEGVFISYDDPTSIAAKVELAVAEDLGGVMIWELSQDYD GTLLETINQHTP Answer: My solution is simply. perform a web-based Blastp using the following parameters: most dissimilar 5000 hits (maximum limit) Restrict to Archaea (which is what you samples appear to be)* If you hit the limit of 5000 results, I would repeat the search for each class or phylum within Archaea. I can't remember if it was re-classified as a kingdom or was just another phylum. Concatenate all hits into a single fasta file. Reg-ex your extremophiles database (personally I'd use pandas), so that the species name of each bacterium is recovered no other information is present. Or this is an easily accessible value within a hash/database (this is a better solution). Use Biopython to loop through your blast fasta file and filter using re search against the species from your database. If you get a hit save that sequence. Ideally, the point 2 and 3 would be a pandas merge operation, but looping is easier. *, If there are extremophiles which are not Archaea (I don't know much about them), then take each general taxonomic group and repeat the operation for the search criteria "restrict the blastp to ... specific group". Issues The issues with command line blastp, not via the web, is that access is greatly restricted during US working hours. If you are searching more than 100 hits and carrying out the search during the working day US time - they will not let it through. 100 hits or less is fine however. For >100 hits (e.g. 5000) it's got to be done well outside US working hours/ weekends. Web-based blastp doesn't carry this restriction of access during US working hours. Basically, the API route is deprioritised for the web-based approach. I assume this is to stop bots - albeit of course a bot can automate through NCBI's webpage. Note The original solution by @terdon might easily work as a remote blastp because each query is restricted to <100 - so it will always get through during working hours. What I am saying is if you're using Blast API it needs a carefully defined strategy, else shift to the web for blanket approaches. Entrez operations from a commandline do work ok during US working day time - albeit it's got to be coded to deal with "random" server refusals otherwise it will break the code (sporadic queries are refused). This is just my recent experience nothing more. Just to be clear - this is potentially a medium sized project. Once the strategy has been decided then specific code that supports this approach can be given in separate questions.
{ "domain": "bioinformatics.stackexchange", "id": 2596, "tags": "blast, ncbi, blastp, makeblastdb, e-utilities" }
Simple stopwatch class
Question: I'm not sure what the best way is when dealing with users calling start() multiple times or stop() before calling start(), I decided to silently return. I lean towards not using exceptions for these situations. Is there a good argument to be made for exceptions? Is there a different or better mechanism? Looking for: Suggestions on missing operations (Provide bool has_started() noexcept;?). Handling special cases (calling start on a stopwatch that has already started, etc.) General suggestions: Better idioms, code clarity, etc. #ifndef CR_STOPWATCH_H #define CR_STOPWATCH_H #include <chrono> //#include <stdexcept> namespace cr { /* DECLARATION */ template < typename TimeUnit = std::chrono::milliseconds, typename Clock = std::chrono::high_resolution_clock > class stopwatch { public: explicit stopwatch( bool const = false ) noexcept; void start() noexcept; void stop() noexcept; TimeUnit elapsed() noexcept; void reset() noexcept; template <typename F, typename... FArgs> inline static TimeUnit measure( F&&, FArgs&&... ); private: bool stopped_; std::chrono::time_point<Clock> stop_; bool started_; std::chrono::time_point<Clock> start_; }; /* IMPLEMENTATION */ template <typename TimeUnit, typename Clock> inline cr::stopwatch<TimeUnit, Clock>::stopwatch( bool const start_stopwatch = false ) noexcept : stopped_{ false }, stop_{ TimeUnit{ 0 } }, started_{ start_stopwatch }, start_{ start_stopwatch ? Clock::now() : stop_ } { } template <typename TimeUnit, typename Clock> inline void cr::stopwatch<TimeUnit, Clock>::start() noexcept { if ( started_ ) { return; //throw std::logic_error( "stopwatch: already called start()" ); } start_ = Clock::now(); started_ = true; } template <typename TimeUnit, typename Clock> inline void cr::stopwatch<TimeUnit, Clock>::stop() noexcept { if ( !started_ ) { return; //throw std::logic_error( "stopwatch: called stop() before start()" ); } stop_ = Clock::now(); stopped_ = true; } template <typename TimeUnit, typename Clock> inline TimeUnit cr::stopwatch<TimeUnit, Clock>::elapsed() noexcept { if ( !started_ ) { return TimeUnit{ 0 }; } if ( stopped_ ) { return std::chrono::duration_cast<TimeUnit>( stop_ - start_ ); } return std::chrono::duration_cast<TimeUnit>( Clock::now() - start_ ); } template <typename TimeUnit, typename Clock> inline void cr::stopwatch<TimeUnit, Clock>::reset() noexcept { started_ = false; stop_ = start_; stopped_ = false; } template <typename TimeUnit, typename Clock> template <typename F, typename... FArgs> inline TimeUnit cr::stopwatch<TimeUnit, Clock>::measure( F&& f, FArgs&&... f_args ) { auto start_time = Clock::now(); std::forward<F>( f )( std::forward<FArgs>( f_args )... ); auto stop_time = Clock::now(); return std::chrono::duration_cast<TimeUnit>( stop_time - start_time ); } } #endif Sample tests: #include <iostream> #include <thread> #include "stopwatch.h" void f() { std::this_thread::sleep_for( std::chrono::milliseconds( 250 ) ); } int main() { using namespace std::chrono_literals; cr::stopwatch<std::chrono::microseconds> sw{ true }; std::this_thread::sleep_for( 100ms ); std::cout << sw.elapsed().count() << '\n'; std::this_thread::sleep_for( 100ms ); sw.stop(); std::cout << sw.elapsed().count() << '\n'; std::cout << cr::stopwatch<>::measure( f ).count() << '\n'; } Answer: What is a stopwatch? My definition of a stopwatch is different than your implementation of a stopwatch. A stopwatch tracks the amount of time that has elapsed while the stopwatch is in an active state. The basic functionality is broken down into the following parts: start() - If not running, begin a new interval (update state and start time). stop() - If running, accumulate the current interval into the total elapsed time. elapsed() - If running, accumulate the current interval into the total elapsed time and begin a new interval. reset() - Set the stopwatch to its inactive state and wipe the total elapsed time. In your implementation, you track the absolute time since the stopwatch construction or reset(). Your start() essentially acts as a reset() when stopped, thus making your stopwatch non-resumable. Consider the following example: stopwatch<> sw(true); std::this_thread::sleep_for(1s); sw.stop(); std::this_thread::sleep_for(1s); sw.start(); std::this_thread::sleep_for(1s); auto elapsed = sw.elapsed(); What should be the value of elapsed? Prefer non-member, non-friend functions Functions should only be class members if they are required to be members (constructors, inherited functions, etc) or they need access to the internals to your class. Your measure() function is a candidate for being a free function and the implementation is roughly the same. template <typename Callable, typename... Args> auto measure(Callable&& func, Args... args) { cr::stopwatch<> sw{ true }; func(std::forward<Args>(args)...); return sw.elapsed(); } You can extend it to take any timer object (countdown timer, named timers, etc) if you wanted that functionality. Use const consistently Your implemented elapsed() function does not mutate the state of your stopwatch and can be marked as const. Avoid latent usage errors by properly ordering headers #include <iostream> #include <thread> #include "stopwatch.h" While this is a small project and your includes are minimal, I would still recommend you order your includes. From John Lakos' "Large Scale C++ Software Design": Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file). To illustrate a clean and ordered header collection: #include "stopwatch.h" // Prototype/Interface header #include "my_graphics/graphics.hpp" // Other headers in project #include <boost/foreach.hpp> // Non-standard headers #include <boost/spirit/include/qi.hpp> #include <iostream> // Standard headers #include <vector> #include <windows.h> // System headers Avoid "magic" constants int main() { using namespace std::chrono_literals; constexpr auto short_delay = 100ms; constexpr auto long_delay = 250ms; ... } Use symbolic constants as they offer semantic meaning to a statement, clearing up any confusion. Prefer default arguments be assigned in declarations class stopwatch { ... explicit stopwatch( bool const = false ) noexcept; ... } template <typename TimeUnit, typename Clock> inline cr::stopwatch<TimeUnit, Clock>::stopwatch( bool const start_stopwatch /* = false */ ) noexcept ^^^^^^^^^^^^^ C++ Standard section 8.3.6 covers the rules regarding default arguments. From 8.3.6.4: A default argument shall not be redefined by a later declaration (not even to the same value). Since programmers and their tools work mostly from header files, prefer to assign default values at the function declaration site, and only assign to that parameter once.
{ "domain": "codereview.stackexchange", "id": 17548, "tags": "c++, timer, c++14" }
School Administration System in Python 3
Question: This is not an actual administration system. It is just homework. I haven't finished the project yet, but I would like some advice on how to improve what I have done so far. main.py: from file import File from random import choice class Main: def __init__(self): # The file_handler object will be used to read and write to files. self.file_handler = File() login_menu_is_running = True while login_menu_is_running: print('1 - Sign up') print('2 - Login') menu_choice = input('\nEnter menu option: ') login_menu_is_running = False if menu_choice == '1': self.signup() elif menu_choice == '2': self.login() else: print('Please choose a number from the menu.') login_menu_is_running = True menu_is_running = True while menu_is_running: print('\n1 - Add a new student to the system.') print('2 - Display a student\'s details.') print('3 - Edit a students details.') print('4 - Log out.') menu_choice = input('\nEnter menu option: ') if menu_choice == '1': self.add_student() elif menu_choice == '2': self.print_student_details() elif menu_choice == '3': self.edit_student_details() elif menu_choice == '4': menu_is_running = False else: print('Please choose a number from the menu.') def signup(self): username = input('Enter username: ') password = input('Enter password: ') if len(password) < 8: print('Password should contain at lease 8 characters.') self.signup() else: self.file_handler.add_account(username, password) def login(self): accounts = self.file_handler.get_accounts() input_loop = True while input_loop: username_attempt = input('Enter username: ') for account in accounts: account = account.split(', ') if username_attempt == account[0]: password_attempt = input('Enter password: ') if password_attempt == account[1]: print('\nLogin successful.') return print('Incorrect username or password.') def add_student(self): print('Please enter the student\'s details:\n') surname = input('Surname: ') forename = input('Forename: ') date_of_birth = input('Date of birth: ') home_address = input('Home address: ') home_phone_number = input('Home phone number: ') gender = input('Gender: ') student_id = self.get_new_id() tutor_group = self.get_tutor_group() school_email_address = student_id + '@student.treehouseschool.co.uk' details = [ student_id, surname, forename, date_of_birth, home_address, home_phone_number, gender, tutor_group, school_email_address ] details = ', '.join(details) self.file_handler.add_student(details) print('\nThe new student has been added.') print(('His' if gender.lower() == 'male' else 'Her'), 'student ID is', student_id) def get_new_id(self): lines = self.file_handler.get_students() if len(lines) <= 1: return '0000' last_line = lines[-2].split(', ') new_id = str(int(last_line[0]) + 1) zeros = '0' * (4 - len(new_id)) new_id = zeros + new_id return new_id @staticmethod def get_tutor_group(): return choice(['Amphtill Leaves', 'London Flowers', 'Kempston Stones', 'Cardington Grass']) def edit_student_details(self): print('Sorry, this feature has not been added yet.') def print_student_details(self): student_id = input('Enter student ID: ') lines = self.file_handler.get_students() details_found = False for line in lines: details = line.split(', ') if details[0] == student_id: details_found = True break if details_found: print('ID: ', details[0]) print('Surname: ', details[1]) print('Forename: ', details[2]) print('Date of birth: ', details[3]) print('Home address: ', details[4]) print('Home phone number: ', details[5]) print('Gender: ', details[6]) print('Tutor group: ', details[7]) print('School email address: ', details[8]) else: print('Student ', student_id, ' could not be found.') if __name__ == '__main__': Main() file.py: class File: @staticmethod def get_accounts(): with open('accounts.txt', 'r') as file: return file.read().split('\n') @staticmethod def add_account(username, password): with open('accounts.txt', 'a') as file: file.write(username) file.write(', ') file.write(password) file.write('\n') @staticmethod def get_students(): with open('student_details.txt', 'r') as file: return file.read().split('\n') @staticmethod def add_student(student_details): with open('student_details.txt', 'a') as file: file.write(student_details) file.write('\n') @staticmethod def remove_student(student_id): pass Answer: This isn't a comprehensive review because that's not possible with incomplete code, but I think there's enough here to make a few remarks. First, a few things I like: The careful control flow, including making sure that menu entries are valid, is good. The use of the if expression as in 'His' if gender.lower() == 'male' else 'Her' is very Pythonic. The if __name__ == '__main__': guard is a useful check against improper use of the program that could otherwise cause confusion. Then a few areas to check. File names should be meaningful. "main.py" isn't a particularly descriptive name: it could be the file that holds the main function in any program ever. Likewise "file.py" isn't particularly descriptive. Be wary of using @staticmethod. If your class only contains static methods, that may indicate that you don't really need a class to begin with. Python is perfectly happy with top level function definitions in a file. Be careful to think about input validation. What happens if a mischievous kid includes a comma or a newline in their password? Before you write code, have a look at whether there is library functionality that you can use (which there very often is, especially in Python.) For example, Python comes with inbuilt support for CSV and padding with zero. It is helpful that things that aren't ready are marked as such. To make it really clear, it may be better to throw a NotImplementedError to make sure that the issue gets noticed if the function is used. Experienced programmers generally prefer for things that are going to break to break as obviously as possible so they can quickly find and fix the issue.
{ "domain": "codereview.stackexchange", "id": 31956, "tags": "python, python-3.x" }
Collective excitations: localized or delocalized?
Question: When condensed matter physicists talk about collective excitations in a crystal such as phonons, magnons etc, do they picture these excitations as necessarily delocalized in the crystal? If they do not i.e., if they can be thought of as local excitations, will the name "collective excitations" be justified and make sense? EDIT: If they are delocalised, why don't the sound waves travel instantaneously? Answer: Collective excitations can be either localized or delocalized. For example, in a conductor the low-energy excitations are particles or holes near a Fermi surface, which are delocalized. But in an insulator, the excitations are often localized. Several commentators have claimed that Bloch's theorem requires all collective excitations to be delocalized in a translationally invariant system. But this is incorrect; Bloch's theorem only applies to noninteracting systems. The Coulomb repulsion can result in an interaction-driven Mott insulator, whose low-energy excitations are usually very localized. Localized excitations can still be legitimately thought of as "collective," because they're usually not perfectly localized to a single site in the microscopic lattice - they typically have an exponentially-decaying tail in space. E.g. this can arise from screening effects. These localized quasiparticles are not identical to the microscopic particles: they get "dressed" by their interactions with nearby particles - but not with those far away. These interactions can renormalize their mass, Lande g-factor, etc., as in Fermi liquid theory. Thus the presence of nearby microscopic particles is still important, even if the excitations are localized. Regarding the finite speed of sound: for a lattice system whose interactions decay exponentially (e.g. because of screening), there are Lieb-Robinson bounds that mathematically limit the speed at which information and entanglement can spread. This is true regardless of whether the excitations are localized or delocalized.
{ "domain": "physics.stackexchange", "id": 37599, "tags": "condensed-matter, solid-state-physics, phase-transition, phonons, quasiparticles" }