source
sequence
text
stringlengths
99
98.5k
[ "ru.stackoverflow", "0000930223.txt" ]
Q: Операции сравнения полиномов произвольной степени Помогите правильно сформулировать операции сравнения, т.к. все мои попытки не увенчались успехом. Получается, что: полиномы у нас равны, если равны их степени, а потом и каждый коэффициент. Если хотя бы одно из условий не выполнено, то он должен возвращать false. И другие в этом же роде. Я просто не могу правильно сформировать эти операции. bool Polinom::operator == (const Polinom &t) { if (deg = t.deg) { for (int i = 0; i < deg; i++) { if (koef[i] = t.koef[i]); return true } } else return false; } bool Polinom::operator < (const Polinom &t) { if((deg < t.deg) || (koef[deg] < t.koef[deg])) return true; else return false; } A: Операция сравнения имеет представление ==. Вы используете присваивание =. Это большая ошибка. При сравнении коэффициентов вы поставили после if(..) знак точку с запятой ;. Это означает пустой оператор (в смысле ничего не делать). Это вторая ошибка. Внутри цикла нужно при разных коэффициентах прекратить цикл и вернуть отрицание. Примерно так: bool Polinom::operator == (const Polinom &t) { if (deg == t.deg) { for (int i = 0; i < deg; i++) { if (koef[i] != t.koef[i]) return false; } return true ; } else return false; }
[ "math.stackexchange", "0000673872.txt" ]
Q: Convert hexadecimal fraction to hexadecimal I have been trying to convert a hexadecimal fraction to a hexadecimal value. 3/4(hex) = 0.C(hex) What are the steps needed to convert? A: In base $10$ (i.e. standard numbers), each place value represents a power of $10$. So $0.37$ represents $3$ tenths ($10^{-1}$) and $7$ hundredths ($10^{-2}$). The same principles apply when working in other bases. Hexadecimal is base $16$. So the first place to the right of the decimal represents sixteenths ($16^{-1} = \frac{1}{16}$). Rewriting in base $10$, we get $\dfrac{3}{4} = \dfrac{12}{16}$ . This tells us that in hex, we need $0.C$ since $12_{10} = C_{16}$ (subscripts indicate what base we are working in).
[ "stackoverflow", "0037283766.txt" ]
Q: GSA sorting with over multiple metadata indexes I am familiar with how to sort GSA results on metadata. I'm interested in sorting across multiple indexes. For example, sort by Last Name, then by First Name. So that Alice Smith appears before Bob Smith. In SQL, this would be quite simple, equivalent to: SELECT value FROM table ORDER BY last, first Does GSA support this? I've been playing with a few different syntaxes, but haven't found a way yet. If it's only possible to sort on one index, how does google sort within the set of equivalent results? e.g. How does GSA determine whether Alice or Bob appears first? I can't find any good explanation on this. A: From what I can tell, GSA does not support multiple dependent sort order. Instead, I've built an additional meta index that combines the two indexes I want to sort. So, for example, I have index A for "First Name", index B for "Last Name", and index C which is the combination of both values into "Last Name"_"First Name". This seems to be working well for me so far.
[ "stackoverflow", "0049113777.txt" ]
Q: Rails default parems for id set to new? I am getting a 404 error on my RoR app and i found that it was because one of the method in the controller, which should only triggers when the record is not new, triggered when the record is new. I do by that checking if the id of that record nil in my controller. before_action :create_record, if: proc { not params[:id].nil? } I was confused by it was triggered so i went head and checked my front-end network, which show following: Request Parameters: {"format"=>"json", "id"=>"new"} <----Set to new by default My completely controller looks like this: class Api::MyController < ApplicationController before_action :create_recotrd, if: proc { not params[:id].nil? } def show end def index @my_model = MyModel.all end def create @my_model = MyModel.new(my_model_params) respond_to do |format| if @my_model.save format.json { render json: @my_model, status: :created} else format.json { render json: @my_model.errors, status: :unprocessable_entity} end end end def update @my_model = MyModel.update end private def create_record @my_model = MyModel.find(params[:id]) end def my_model_params params.require(:my_model).permit( :city, :state, :county, :zip, :telephone, :email, ) end end I cant seem to find out why the id in the parameters is set to "new" instead of "nil". I tried in the console by doing MyModel.new, the default id was nil, but then when i do the GET request, the id was set to "new" A: This is a really weird approach to set a new record. I think the problem lies in your routes. You are probably trying to access yoursite.com/your_model/new and your routes are configured to look for get "your_model/:id" => "your_controller#show" You are probably missing get "your_model/new" => "your_controller#new" So when you try to visit your_model/new the routes map the "new" as the :id param in your url. I don't see a new action in your controller as well. You should read up on basic resource set up for rails here: http://guides.rubyonrails.org/routing.html.
[ "stackoverflow", "0060519713.txt" ]
Q: iterate through a lisit which would have range as an element and expand it I'm a newbie to python I want to iterate through a list which might have ranges in it and expand it. def ExpandList(c): new_list = [] for i in c: print(i) if '-' in i: low,high=i.split('-')[0],i.split('-')[-1] if low !=high: for j in range(low,high): new_list.append(j) else: new_list.append(low) else: new_list.append(i) return new_list c = [1001-1002,1005-1009,1010,1010-1025] with the above input I want to expand the list. when I iterate through the given list, it does not take 1001-1002 as the single element unless i mention it as a string '1001-1002'. I cannot force user to give that as string.. how do i evaluate this and acheive what i intend to. kindly advise A: The easiest option is to ask the user to provide all the values as strings. Either inputting them by hand to the program or writing them into a text file one per line. That way no quotes would be necessary. That said, in python 3.8 you can use the brand new walrus operator in a generator expression and then chain all the ranges import itertools as it c = ['1001-1002','1005-1009','1010','1010-1025'] cx = (range(int(r[0]), int(r[1])) if len((r:=el.split('-')))>1 else [el] for el in c ) res = it.chain.from_iterable(cx) print(list(res)) produces [1001, 1005, 1006, 1007, 1008, '1010', 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024] Note: I am passing the upper range limit to range as it is. In case it needs to be included, increase it by one range(int(r[0]), int(r[1])+1)
[ "stackoverflow", "0007612478.txt" ]
Q: Error while adding WebSphere in Eclipse I am trying to use WebSphere v6.0 with Eclipse. When I try to add the runtime server for a Dynamic Web Project, I get the following error: Missing classpath entry \your_server_root\was-6.0\properties Why? A: My thought? Add that entry to the CLASSPATH. Another thought would be to ditch WebSphere and use Tomcat, JBOSS, or Glassfish.
[ "stackoverflow", "0016537909.txt" ]
Q: Rickshaw only show gridlines on some points I have a graph made with rickshaw: I have the tick marks setup so that they only have a label if the value is -24, 0, or 24: // Instantiate x-axis var xAxis = new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', pixelsPerTick: 25, element: graphXAxis, tickFormat: function(n) { switch(n) { case -24: return '24 hours ago'; case 0: return 'Now'; case 23: return '24 hours from now'; } } }); But the gridlines show up on every single tick, even the ones that my case statement doesn't return for! How can I get rid of the rest of the gridlines? A: You can specify a desired number of ticks with the ticks key. However that will not give you specific control over where those ticks are generated and you may not get exactly the number requested. With some additional extension to RickShaw you can gain more control over the ticks, which is detailed with supporting code here. var xAxis = new Rickshaw.Graph.Axis.X({ graph: graph, orientation: 'bottom', pixelsPerTick: 25, ticks:3, element: graphXAxis, tickFormat: function(n) { switch(n) { case -24: return '24 hours ago'; case 0: return 'Now'; case 23: return '24 hours from now'; } } });
[ "stackoverflow", "0004715676.txt" ]
Q: Auto populate form fields on external sites from local MySQL Howdy folks, I am wanting to build a script or something to take a single row from my MySQL database and use that data to pre-populate form fields on one of multiple sites that aren't mine. What I'd like to do is to take information a user has entered on my site and when they click a link to one of the sites in my system it loads the external site with certain pre-mapped fields populated with the info they entered. But I can't seem to get my head around a way to do this, seeing as I can't add anything to these pages. Do you guys have any suggestions? A: The flow you described is not possible due to cross-site scripting constraints. This post is relevant: Browser Automation and Cross Site Scripting The closest thing I can think of is Greasemonkey, which would force the user to download the plugin from Mozilla, plus a new userscript from your website. Another option would be reproducing the form on your own web server, and hoping the form action doesn't perform referrer checks.
[ "stackoverflow", "0020826410.txt" ]
Q: can i downgrade app from production to beta testing in Playstore Hi accidently uploaded an apk to production , instead of beta. Is it possible to dowgrade it to beta , without having an apk in production? A: You can certainly remove the app from the play store and use the beta/alpha testing tabs on the developer console. I am not sure about how beta works, but if you choose alpha testing,your app doesn't go into production. You are send a link for your app and you need to send invites to people on their google+ accounts so that they can access your app and be able to download it. UPDATE: Right from the official docs Alpha- or beta-test apps will only appear in Google Play for testers that opt-in and not to any other users. A production APK is not required to publish an alpha- or beta-test app. It may take up to 24 hours after publishing for the test link to become active.
[ "pt.stackoverflow", "0000021398.txt" ]
Q: Como saber qual SQL é gerado pelo ORM Entity Framework? Com a utilização do ORM, e a prática empregada esquecemos que eles geram SQLs e retornar Objetos (vice-versa). Como posso descobrir em tempo de execução a SQL gerada pelo Entity Framework direto no Visual Studio, para que possa debugar e ter um maior controle no que está sendo gerado? A: No que eu sei existem duas formas: 1) Cria a expressão lambda expression (Linq) com retorno IQueryable e em outra variável SQlExecutar execute um ToList(). Na variável com retorno IQueryable tem a SQL gerada. Nesse código apresentado, quando passar na instrução SQL.ToList() acima a variável SQL mostrará a SELECT gerada: using (GenericsEntities db = new GenericsEntities()) { //Quando a variável "SQL" der um ToList() ela mostrado a "SELECT" IQueryable<Tipos> SQL = db.Tipos.AsQueryable(); IList<Tipos> SQLExecutar = SQL.ToList(); } Uma forma de visualizar isso também é com Breakpoint com F11 na janela IntelliTrace ver o output, observer: 2) Na versão EF 6+, existe um Action responsável por isso tendo uma saída de todas as informações de conexão e a SQLs. O Database.Log resgata tais informações com a codificação logo abaixo. Eu crie um function que tem um parâmetro do tipo String que recebe os dados e imprime na tela do console. using (GenericsEntities db = new GenericsEntities()) { db.Database.Log = StrRestult => fs(StrRestult); IQueryable<Tipos> SQL = db.Tipos.AsQueryable(); IList<Tipos> SQLExecutar = SQL.ToList(); } //função que irá imprimir na tela (console) tudo o que //aconteceu nas instruções de conexão e SQLs geradas private static void fs(string StrRestult) { System.Console.WriteLine(StrRestult); } É de grande utilidade como forma de debugar e visualizar como ele trabalha internamente. A segunda opção é a mais eficaz, porque, consigo também visualizar Insert, Delete, Update e Select de forma bem clara.
[ "stackoverflow", "0014324194.txt" ]
Q: Dialog box unresponsive with Windows Script Host (Python) I am trying to modify the Print Setup option found under File > Print Setup. I am using Windows Script Host with Python. I use the Alt + F followed by S to open the appropriate dialogue box: When I do those commands by hand, the Print Setup box is in focus, so I can press F to select "Print to File" then {ENTER} or O to accept the changes. However, I neither ALT+F nor F is selecting the File option. shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('Point of Sale') shell.SendKeys("%fs") # I also tried "%fsf and "%fs%f" removing the other call to SendKeys" time.sleep(0.1) # Removing this (or using a longer wait) makes no difference shell.SendKeys("F") A: This problem had to do with incorrect implementing on part of the developer of this software. To solve the problem, I used SendKeys to send multiple TABS until File was selected.
[ "stackoverflow", "0009055779.txt" ]
Q: AFNetworking - Download multiple files + monitoring via UIProgressView I am trying to change my code from ASIHTTPRequest to AFNetworking. Currently I want to select 10-15 different HTTP URLs (files) and download them to a documents folder. With ASIHTTPRequest that was pretty easy with [myQueue setDownloadProgressDelegate:myUIProgressView]; In AFNetworking I can't figure out how to do it. I have the following code which downloads the files, stores them and notifies when a file downloads successfully, but I can't create the progress bar for this queue with total size. for (i=0; i<3; i++) { NSString *urlpath = [NSString stringWithFormat:@"http://www.domain.com/file.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlpath]]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"testFile%i.zip",i]]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Successfully downloaded file to %@", path); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; [operation setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { NSLog(@"Sent %d of %d bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path); }]; [myQueue addOperation:operation]; } A: I think you will have to create your own UIProgressView, which I will call progressView for the example. progressVu = [[UIProgressView alloc] initWithFrame:CGRectMake(x, y, width, height)]; [progressVu setProgressViewStyle: UIProgressViewStyleDefault]; Then just update the progress bar: [operation setDownloadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { float percentDone = ((float)((int)totalBytesWritten) / (float)((int)totalBytesExpectedToWrite)); progressView.progress = percentDone; NSLog(@"Sent %d of %d bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path); }];
[ "math.stackexchange", "0001902561.txt" ]
Q: Omitting twiddle factors in Cooley–Tukey FFT algorithm The discrete Fourier transform $$ X_k = \sum_{m=0}^{n-1} x_m e^{-2\pi ikm/n} $$ can be computed via Cooley–Tukey FFT algorithm The key of the algorithm is the butterfly transform, given by $$ X_k = E_k + \omega^k \cdot O_k\\ X_{k + N/2} = E_k - \omega^k \cdot O_k\\ \omega = e^{\frac{2\pi i}{N}}. $$ The $\omega^k$ value is called "twiddle factor". I've implemented this algorithm and it worked flawlessly. Then I've replaced twiddle factor with unity, making the butterfly transform look like $$ X_k = E_k + O_k\\ X_{k + N/2} = E_k - O_k $$ This looks very much like Haar transform, but is different. This transform has some remarkable properties: It transforms real data to real data Its matrix is symmetric Its matrix is orthogonal (up to $\sqrt{n}$ factor) It is self inverse (follows from previous two) Its matrix contains only $\pm 1$ (no zeros). Here's the matrix portrait for $n = 32$ and the matrix for $n=8$ $$ \begin{pmatrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & -1 & -1 & -1 & -1 \\ 1 & 1 & -1 & -1 & 1 & 1 & -1 & -1 \\ 1 & 1 & -1 & -1 & -1 & -1 & 1 & 1 \\ 1 & -1 & 1 & -1 & 1 & -1 & 1 & -1 \\ 1 & -1 & 1 & -1 & -1 & 1 & -1 & 1 \\ 1 & -1 & -1 & 1 & 1 & -1 & -1 & 1 \\ 1 & -1 & -1 & 1 & -1 & 1 & 1 & -1 \\ \end{pmatrix} $$ There are some questions that interest me: Is this discrete transform known? Can it be expressed like DFT? Is there any convolution theorem for this transform? Update. Here's an explicit formula I've obtained. Let $\vec k$ be the binary representation of $k$ treated as a vector in $\mathbb Z^d$. Then $$ X_k = \sum_{m = 0}^{n-1} x_m (-1)^{\vec k^\top J \vec m} $$ where $J$ is the exchange matrix. In other words $$ X_k = \sum_{m = 0}^{n-1} x_m (-1)^{\phi(\vec k, \vec m)} $$ and $$ \phi(\vec k, \vec m) \equiv \sum_{i = 1}^{d} k_i m_{d+1-i} = \phi(\vec m, \vec k), \qquad d = \log_2 n $$ Also, removing bit-reversal permutation in CT algorithm leads to a similar transform with $$ X_k = \sum_{m = 0}^{n-1} x_m (-1)^{\psi(\vec k, \vec m)}\\ \psi(\vec k, \vec m) \equiv \sum_{i=1}^d k_i m_i = \psi(\vec k, \vec m). $$ A: The transform matrix is a Hadamard matrix, and the transform that you described is is known as fast Walsh-Hadamard transform. See also the more general description of Hadamard transforms.
[ "stackoverflow", "0018135116.txt" ]
Q: `volatile` to sync variable between threads I have a variable int foo that is accessed from two threads. Assuming I have no race-condition issues (access is protected by a mutex, all operations are atomic, or whatever other method to protect from race conditions), there is still the issue of "register caching" (for lack of a better name), where the compiler may assume that if the variable is read twice without being written in between, it is the same value, and so may "optimize" away things like: while(foo) { // <-may be optimized to if(foo) while(1) do-something-that-doesn't-involve-foo; } or if(foo) // becomes something like (my assembly is very rusty): mov ebx, [foo]; cmp ebx, 0; jz label; do-something-that-doesn't-involve-foo; do-something-else-that-doesn't-involve-foo; if(foo) // <-may be optimized to jz label2; do-something; does marking foo as volatile solve this issue? Are changes from one thread guaranteed to reach the other thread? If not, what other way is there to do this? I need a solution for Linux/Windows (possibly separate solutions), no C++11. A: What you need are memory barriers. MemoryBarrier(); or __sync_synchronize(); Edit: I've bolded the interesting part and here's the link to the wiki article (http://en.wikipedia.org/wiki/Memory_barrier#cite_note-1) and the associated reference (http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.07.23a.pdf) Here's the answer to your other question (from wikipedia): In C and C++, the volatile keyword was intended to allow C and C++ programs to directly access memory-mapped I/O. Memory-mapped I/O generally requires that the reads and writes specified in source code happen in the exact order specified with no omissions. Omissions or reorderings of reads and writes by the compiler would break the communication between the program and the device accessed by memory-mapped I/O. A C or C++ compiler may not reorder reads and writes to volatile memory locations, nor may it omit a read or write to a volatile memory location. The keyword volatile does not guarantee a memory barrier to enforce cache-consistency. Therefore the use of "volatile" alone is not sufficient to use a variable for inter-thread communication on all systems and processors[1] Check this one out, it provides great explanations on the subject: http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2 http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-2-of-2 A: If access is protected by a mutex, you do not have any issue to worry about. The volatile keyword is useless here. A mutex is a full memory barrier and thus no object whose address could be externally visible can be cached across the mutex lock or unlock calls.
[ "stackoverflow", "0005954527.txt" ]
Q: Remove NA when using "order" I have this huge matrix of data with columns for year, month, day and precipitation which I need to order and also delete the row when the precipitation is NA (which happens on the day 31 of every month that only has 30 days and Februaries...). After consulting the r help files I used the following code: dat<- aa[order(aa$year, aa$month, aa$day, na.last=NA),] It ordered my data perfectly but I still have all the NAs... Can anyone tell me why it hasn't work? thanks > head(dat) code year month station ALTITUD PROV LONGITUD LATITUD day P1 id 1.1 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 1 0 1 1.2 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 2 0 1 1.3 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 3 0 1 1.4 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 4 0 1 1.5 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 5 0 1 1.6 3059 1940 11 ALBALATE DE LAS NOGUERAS 855 CUENCA 216372 402200 6 0 1 A: The na.last argument to order only removes NA from the objects passed to order via .... Your NA are in aa$precipitation, not aa$year, aa$month, or aa$day, so you need: dat <- na.omit(aa[order(aa$year, aa$month, aa$day),]) You may want to consider using a time-series class like zoo or xts for time-series data. A: Because na.last is to see if NA should be last of first when ordering not to remove the NA. Use na.omit(dat) to remove the NA. Hope that helps.
[ "askubuntu", "0000431911.txt" ]
Q: How can I verify the speed of my NIC in ubuntu? Is there a command that I can verify by its output the speed of my NIC and some information about its characteristics such as duplex full or half . A: Suppose your NIC name eth0 : You can verify the speed and some informations by three Commands : First Command : dmesg |grep eth0 Output : Second Command : mii-tool -v eth0 Output : FD : full duplex , Logic that enables concurrent sending and receiving. This is usually desirable and enabled when your computer is connected to a switch. HD : half duplex , his logic requires a card to only send or receive at a single point of time. When your machine is connected to a Hub, it auto-negotiates itself and uses half duplex to avoid collisions. Third command : ethtool eth0 ethtool - Display or change ethernet card settings Install ethtool : sudo apt-get install ethtool Output : Settings for eth0: Supported ports: [ TP ] Supported link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full 1000baseT/Full Supported pause frame use: No Supports auto-negotiation: Yes Advertised link modes: 10baseT/Half 10baseT/Full 100baseT/Half 100baseT/Full 1000baseT/Full Advertised pause frame use: No Advertised auto-negotiation: Yes Speed: 1000Mb/s Duplex: Full Port: Twisted Pair PHYAD: 0 Transceiver: internal Auto-negotiation: on MDI-X: Unknown Supports Wake-on: d Wake-on: d Current message level: 0x00000007 (7) drv probe link Link detected: yes Hope it helps . A: To obtain the link speed of an interface without parsing logs or installing additional tools, simply read its corresponding speed sysfs node, as follows: cat /sys/class/net/<interface>/speed where is the name of your NIC, e.g. eth0
[ "stackoverflow", "0019669904.txt" ]
Q: Displaying a menu child in drupal 7 How to make a child menu visible in Drupal 7 ? The child menu appears just when I inter to the page of the parent menu. I want to make it visible whenever i put the mouse on the parent menu. I hope it's clear! thank you A: This is the answer : Go to your parent menu item, edit it and click on the 'Show as expanded' checkbox. Now all the children menu items should be visible from the top level.
[ "stackoverflow", "0034040928.txt" ]
Q: AxWindowsMediaPlayer - black screen I'm building a desktop app in c# that uses AxWindowsMediaPlayer and is working nice, but when i kill explorer.exe (because i'm trying simulate kiosk mode on windows 10 home) the AxWindowsMediaPlayer control doesn't play, only shows a black screen. What can i do to put it work? Or any alternative for AxWindowsMediaPlayer? I just need something to simulate screen saver; slide show to pictures and sometimes play some videos with no play/pause/stop... controls. Thank you A: Adding this line resolved the issue. Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Thank you.
[ "stackoverflow", "0014958933.txt" ]
Q: Extract the last characters I'm trying to extract the last two digits in a string. First I remove any spaces or special characters and replace them with a hyphen then if there are two hyphens following each other, I remove them. ext I remove any trailing hyphens. Next I want to extract the last two characters after the lat hyphen in the string. For example how do I extract the last characters in this string i.e 1 after the last hyphen? awesome-page-1. My code is here $string = 'awesome page@1'; $slug = preg_replace('/[^a-zA-Z0-9]/', '-', $string);//replace spaces and special characters with space $slug = preg_replace('#-{2,}#', '-', $slug);//two hyphens following each other $slug = trim($slug, '-');//remove trailing hyphens A: You can use strrchr() to find the last dash in the created slug and then skip past that using substr(). $slug = trim(preg_replace('/[^a-z0-9]+/i', '-', $string), '-'); echo substr(strrchr($slug, '-'), 1); If there are no dashes in $string, the result will be empty Demo
[ "askubuntu", "0000746994.txt" ]
Q: Make my Apache2 server public I'm really confused how to make my Apache2 web server public. I've setup everything and when I type localhost:80 it comes up properly. But, I need very clear and detailed instructions on how to make it public! And also have it used by its alias which I set to pcpcpc12.com [EDIT] Output of /var/log/apache2/access.log 127.0.0.1 - - [16/Mar/2016:20:04:23 +0000] "GET / HTTP/1.1" 200 3594 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:04:23 +0000] "GET /icons/ubuntu-logo.png HTTP/1.1" 200 3688 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:04:24 +0000] "GET /favicon.ico HTTP/1.1" 404 498 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:04:24 +0000] "GET /favicon.ico HTTP/1.1" 404 498 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:10:34 +0000] "GET / HTTP/1.1" 200 661 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:10:34 +0000] "GET /icons/blank.gif HTTP/1.1" 200 430 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:10:34 +0000] "GET /icons/folder.gif HTTP/1.1" 200 507 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:10:40 +0000] "GET /pcpcpc12.com/ HTTP/1.1" 200 3594 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:11:31 +0000] "GET /pcpcpc12.com/ HTTP/1.1" 200 732 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:11:31 +0000] "GET /icons/back.gif HTTP/1.1" 200 498 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:11:31 +0000] "GET /icons/blank.gif HTTP/1.1" 304 178 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:11:31 +0000] "GET /icons/folder.gif HTTP/1.1" 304 178 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:11:42 +0000] "GET /pcpcpc12.com/public_html/ HTTP/1.1" 200 280 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:14:26 +0000] "GET /pcpcpc12.com/ HTTP/1.1" 200 734 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:14:26 +0000] "GET /icons/blank.gif HTTP/1.1" 304 178 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:14:26 +0000] "GET /icons/back.gif HTTP/1.1" 304 178 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:14:26 +0000] "GET /icons/folder.gif HTTP/1.1" 304 178 "http://localhost/pcpcpc12.com/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:14:44 +0000] "GET / HTTP/1.1" 200 280 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:51:41 +0000] "GET / HTTP/1.1" 200 548 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:51:42 +0000] "GET /favicon.ico HTTP/1.1" 404 498 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:51:42 +0000] "GET /favicon.ico HTTP/1.1" 404 498 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" 127.0.0.1 - - [16/Mar/2016:20:51:45 +0000] "GET /pcpcpc12.com/public_html/index_two.html HTTP/1.1" 200 505 "http://localhost/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0" Output of error.log [Wed Mar 16 19:18:41.713986 2016] [mpm_event:notice] [pid 4282:tid 140223239657344] AH00489: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations [Wed Mar 16 19:18:41.714259 2016] [core:notice] [pid 4282:tid 140223239657344] AH00094: Command line: '/usr/sbin/apache2' [Tue Jan 01 00:00:48.990306 2013] [mpm_event:notice] [pid 1316:tid 140375846848384] AH00489: Apache/2.4.7 (Ubuntu) configured -- resuming normal operations [Tue Jan 01 00:00:49.019771 2013] [core:notice] [pid 1316:tid 140375846848384] AH00094: Command line: '/usr/sbin/apache2' A: when you "set the alias to pcpcpc12.com", others will not be able to view it unless you create a public DNS record. this will require knowing your public IP address. you can just google "what's my public IP" If you own pcpcpc12.com, registered through godaddy or someone, then they should have an interface for you to create an A host record, use your public IP for that. If you don't own the domain, then others can still reach your website by typing your public IP address in their browser, for example, http://192.168.0.1/ (your public IP will not start with 192.168) since you mentioned in the comments that you are using a TalkTalk home gateway router, I'm assuming you're using a residential internet connection. Depending on your ISP, such as Cox (my beloved ISP), they may choose to block your public http port as an incentive to get you to upgrade to a costly business internet connection. You can check by going away from home somewhere on some other network, and running network map. Install the utility sudo apt-get install nmap and then run the command nmap -Pn -p 80 192.168.0.1 and change the 192.168.0.1 IP to the public IP from step one. With luck, you'll get an open scan like this: Starting Nmap 6.40 ( http://nmap.org ) at 2016-03-22 22:17 CDT Nmap scan report for 192.168.0.1 Host is up (0.0028s latency). PORT STATE SERVICE 80/tcp open http Nmap done: 1 IP address (1 host up) scanned in 0.13 seconds Otherwise, you'll get a filtered scan like this: Starting Nmap 6.40 ( http://nmap.org ) at 2016-03-22 22:19 CDT Nmap scan report for 192.168.0.1 Host is up. PORT STATE SERVICE 80/tcp filtered http Nmap done: 1 IP address (1 host up) scanned in 2.58 seconds In this case, then others can still reach you on a non-blocked port. 8080 is a popular choice. you will need to adjust the settings in your router to port forward map your incoming external port 8080 to your internal port 80 of the internal IP of your server. You will only have one public IP, but you will have a different internal IP for every device on your network. Internal network IPs usually start with 192.168. or 10. You can find out your internal IP by running the terminal command ifconfig Once you have that setup correctly, then the world will be able to reach your site at http://192.168.0.1:8080, again making sure to use your public IP and not the 192.168.
[ "stackoverflow", "0029786719.txt" ]
Q: No Such User Here VPN/WHM with Mail Routed through Separate Server Ok, I am using a VPN on GoDaddy for webhosting. But on one of the websites that I am hosting, the email is handled on a separate VPN. So I have an A record for domain.com set to the GoDaddy VPN and an A record for mail.domain.com set to the IP of the other domain and several CNAMES pointed to that A record. It's all working beautifully except for one thing.... Email from other domains on the GoDaddy VPN cannot send to this domain. So [email protected] cannot send to [email protected] I get error "No Such User Here" from my server. I understand that the GoDaddy VPN is checking for that user locally and not finding it, but I don't know how to make it NOT check for this domain. I am using WHM/cPanel with Exim and SpamAsassin. Thanks! A: Not sure what the deal is with the downvotes, but here was my solution (probably obvious). From Linux Terminal: sudo su (for admin rights) nano /etc/localdomains (erase domain from local domains) nano /etc/remotedomains (add domain to remote domains) Now it doesn't check that domain for users locally before it sends it out to the remote server.
[ "photo.stackexchange", "0000037610.txt" ]
Q: Are older macro lenses soft at long focus distances? I have an old (20+ years old) Nikon mount Sigma 50mm f/2.8 macro lens with a 2X Tamron teleconverter that I use on my Canon body. When taking macro (1:1) or general close-up shots, the lens is very sharp and quite usable even with the TC. However, when I take photos of further away subjects, especially when attempting to use the lens while experimenting with landscapes, the lens is soft and not very nice at all. In fact, even stopping down to f/8 or f/11 doesn't improve things much. I know that the current breed of Canon and Nikon macros are incredibly sharp, even at far away focus distances, making them suitable for portrait use. Is this a recent phenomenon? Did old macro lenses exhibit softness when focused at further away objects? A: That would depend on the individual lens, but to make a general statement: no, direct-mount macro lenses that could focus to infinity were generally sharp throughout their focal range. In particular, a macro lens in the 90-105mm range was usually the sharpest lens in a photographer's kit, regardless of the brand (within limits, of course—there have always been $25 specials of dubious origin, whether on eBay, Amazon, or in the black-and-white ads at the backs of photo magazines). I qualified that somewhat, since there were lenses produced that either required a focusing bellows or that could only focus at all at relatively close distances. Some of them were adaptations of microscope optics; others were highly corrected for apochromaticity (a near-complete absence of chromatic aberration of any kind) and rectilinearity over a relatively small reproduction range (around 1:4 to 4:1), and while that made them spectacular within their range, it would mean they were less than spectacular outside of it. Such lenses generally couldn't be focused farther away than their far-focus limit without deliberate action on the part of the photographer (using short extension tubes rather than bellows, "freelensing", etc.). That's not to say that no designs were ever compromised for cost and simplicity. In order to maintain correction across a larger-than-normal focus range, some elements of a lens have to be able to move in relation to other elements, even in a unit focus design. (That is, on a lens where focus is achieved by moving the majority of the lens elements, as a group, further away from the film plane/sensor. Unit focus lenses will get physically longer as you focus closer.) And the corrective elements often need to be aspherical (exotic shapes) or have low- or anomalous-dispersion characteristics (exotic materials, like fluorite or expensive-to-produce and hard-to-work-with optical glasses). If the lens was particularly inexpensive, something had to give somewhere, and if the lens was primarily aimed at macro at a time when owning a 50mm "kit lens" was a given, then it is possible that any compromises made were towards the infinity-focus end of the lens's range.
[ "serverfault", "0000237781.txt" ]
Q: Sharepoint Webpart for Exchange 2010 EWS I hear that Sharepoint Webparts don't work with Exchange 2010 EWS. Any ideas? We want users to be able to use the portal site as their one stop for email, calendar, announcements, etc... A: SharePoint 2010 exchange webparts should work just fine but make sure that SP1 is installed on your Exchange 2010 box. However you will probably run into authentication challenges. If you create your own wp's you will need to enable / configure an impersonation account on your Exchange box. Which you will use in your custom exchange wp. Some usefull links that I have used: http://geekcroft.wordpress.com/2009/12/17/exchange-2010-owa-authentication-issues/ http://markhaverty.com/sharepoint/configuring-the-my-calendar-and-my-inbox-web-parts Also checkout the exchangewp project on codeplex. Hope this helpes.
[ "stackoverflow", "0038063344.txt" ]
Q: links to other AMP pages in an AMP article I have several non-AMP pages within a topic. My non-AMP pages will have links within the body of the article to other non-AMP pages in the same topic. Should the AMP versions of the pages link to the other AMP pages in the same topic or should all links in the articles point to the non-AMP (canonical) versions of the pages? Using the following link formats for the example: Non-AMP version: /muffins/blueberry/ AMP version: /muffins/blueberry/amp/ /muffins/blueberry/ has a link to /muffins/strawberry/ Should /muffins/blueberry/amp/ link to /muffins/strawberry/amp/ or to /muffins/strawberry/? Or said another way, if a visitor comes to your site on an AMP page, do you continue to offer them links to other AMP versions of your pages or should you switch them over to the full pages as soon as possible? A: As far as I know, it is up to you to decide since no where in the docs does it state that we must have links leading to one or the other. If it helps, we decided to have all links within the AMP page link back to the canonical page and our pages are appearing in the carousel perfectly fine. If you look at the AMP HTML Specs, it only states that links cannot begin with javascript:.
[ "stackoverflow", "0036583598.txt" ]
Q: Break Line on TextArea I have Text\n Text stored in the database. When I select the text and put in on the Text Area, it doesn't show a new line. Instead, it shows \n. I already tested with .replaceAll to replace \\n to \n and still nothing. How to fix it? My code: rs = stat.executeQuery("SELECT * FROM sobre WHERE codsobre = 0"); String old; while (rs.next()) { old = rs.getString("texto"); String nova = old.replaceAll("\\n", "\n"); TextArea.append(nova); } A: String nova = old.replace("\\n", System.getProperty("line.separator"));
[ "stackoverflow", "0008724882.txt" ]
Q: Convert HTML & CSS to DOC(X)? Is there some utility that could be called via command line to produce a doc(x) file? The source file would be HTML and CSS. I am trying to generate Word documents on the fly with PHP. I am only aware of phpdocx library, which is very low level and not much use for me (I already have one poor implementation of Word document generation). What I need from a document: TOC Images Footers/Headers (they could be manually made on each HTML page) Table Lists Page break (able to decide what goes to which page, eg one HTML file per page, join multiple HTML files to produce the entire document.) Paragraphs Basic bold/etc styles A: I didn't find PHPDOCX very useful either. An alternative could be PHPWord, i think it covers what you need. According the website it can do these things: Insert and format document sections Insert and format Text elements Insert Text breaks Insert Page breaks Insert and format Images and binary OLE-Objects Insert and format watermarks (new) Insert Header / Footer Insert and format Tables Insert native Titles and Table-of-contents Insert and format List elements Insert and format hyperlinks Very simple template system (new) In your case that isn't enough, but there is a plugin available to convert (basic) HTML to Docx and it works very good in my opinion. http://htmltodocx.codeplex.com/ I am using this for a year or two now and am happy with it. Altough i have to add that the HTML can't be to complex.
[ "stackoverflow", "0057635055.txt" ]
Q: Passing all http requests and React Routes through node backend first for session verification and then return path I'm trying to pass all http requests and React Routes through a node backend to verify session. I am also using webpack-dev-server, so I assume in my dev environment I will need to use the proxy feature. But once the request hits the node server, I'm not sure how to pass the results back to react front end and proceed with the normal react router page. Something like: 1. Click React Router link to /contact /contact route in node verifies session Session is/isn't valid If valid proceed with normal page load If not valid return to homepage and change state. I assume at least some of this will be done with lifecycle methods? Is any of this possible without using front end functionality other than react router. I want to make this entirely back end dependent to verify the existing session or generate a new session. A: React handles all routing on the client side, if you want to access /contact outside your web app you must have something like this: app.get('*', (req, res) => { res.render('index'); }); If you want to handle a predefined route you can also do this: // Path can be anything you want check in this case any route app.use('/', (req, res, next) => { const { token } = req.cookies; if (!token) { res.status(400).send({ data: 'error' }); } else { // Verifying some token function verifyIdToken(token) .then((claims) => { // Perform some operations or assignments req.claims = claims; // Countinue next(); }) .catch((error) => { res.status(400).send({ data: 'error', message: error }); }); } }); But if you want to verify session in the client I suggest making a call to an '/authenticate' route, then update your state accordingly to your response, for example: I have a Home component, it can only be visible to logged users, so I created a high order component to wrap it that looks like this: hoc-admin.js // Generic validation method const isEmpty = prop => ( prop === null || prop === undefined || (prop.hasOwnProperty('length') && prop.length === 0) || (prop.constructor === Object && Object.keys(prop).length === 0) ); // This receives the props I want to check and the component to render const userHOC = (props, Comp) => (WrappedComponent) => { return class userHOC extends Component { render() { let valid = false; props.map((prop) => { valid = this.props && !isEmpty(this.props[prop]) // You can also check redux state props // valid = this.props.common && !isEmpty(this.props.common[prop]) }); return valid ? ( <WrappedComponent {...this.props} /> // My wrapped component (Home) ) : ( <Comp {...this.props} /> // My parameter component (Login) ) } }; }; export default userHOC; Then I just need to wrap every component that needs some prop to show, in this case we arre looking for users in my home component so: import HocUser from '../hoc/hoc-user'; class Home extends Component { ... } export default HocUser(['user'], Login)(Home); ``
[ "anime.stackexchange", "0000020376.txt" ]
Q: Roronoa Zoro's boasts I'm quite interested in Zoro's personality, especially when he boasts to others about his powers. Can someone list out all or some of Zoro's lines so far in the manga? I can only remember two: In Dressrosa arc: During his fight with Pica, he said "Only if your Haki is stronger than mine". In Punk Hazard arc: When he and Tashigi are fighting with Monet, I can't remember exactly. A: I don't have an exhaustive list of Zoro's quotes, so until someone comes up with such a list, I'll give you the ones I could find googling this problem. Keep in mind that these are translations and he might have said it differently in Japanese. Have fun reading. His most recent one liner on Dressrosa is: Over the 9 mountains and 8 seas... Throughout the world itself... There is nothing I cannot cut. The quote you were looking for when fighting Monet is: You've underestimated me, snow woman. When you thought you couldn't beat me, you should have run. Of course, there are things that I don't wanna cut. But... let me ask you something. Have you ever seen a fierce animal you were sure would never bite? Because I haven't. You can find 29 quotes on less-real. They don't say when he said them though. If I die here, then I'm a man that could only make it this far. You need to accept the fact that you're not the best and have all the will to strive to be better than anyone you face. Bring on the hardship. It's preferred in a path of carnage. Either in belief or doubt, if I lean to one of these sides, my reaction time will be dulled if my heart thinks the opposite of what I choose. I don't care what the society says. I've regretted doing anything. I will survive and do what I want to. You want to kill me? You couldn't even kill my boredom! You sure can talk the talk, but you're not quite ready to walk the walk. Time's up, it's my turn. When the world shoves you around, you just gotta stand up and shove back. It's not like somebody's gonna save you if you start babbling excuses. So, are you stupid enough to fall for such a stupid trap that such stupid people set up? I'm a pirate hunter. A wound that'd make an ordinary man unconscious... I won't lose to it. A wound that would kill an ordinary person... I won't lose to it! To face one who is extraordinary, Hawk Eyes... I can't allow myself to be ordinary! There should be a limit to how similar a couple looks like. When I decided to follow my dream, I had already discarded my life. If you kill yourself, I'll kill you. Well, how about this. My "luck" versus this thing's "curse". Wanna see what's stronger..? If I lose, then I'm just that much of a man anyways... There is someone that I must meet again. And until that day...not even Death itself can take my life away! I don't know. I'm not sure why myself. But if I were to take even one step back, I believe that all those important oaths, promises and many other deals 'til now, will all go to waste and I'll never be able to return before you, ever again. So what if you're a girl. If I can't even protect my captain's dream, then whatever ambition I have is nothing but talk... When you decided to go to the sea, it was your own decision. Whatever happens to you on the sea, it depends on what you've done! Don't blame others!! You'll never understand...your swords will never be as heavy as mine! If you do anything that would cause me to abandon my ambitions... You will end your own life on my sword! Fine! I'd rather be a pirate than die here! I am always serious. I do things my own way! So don't give me any lip about it! I'm going to be the world's greatest swordsman! All I have left is my destiny! My name may be infamous...but it's gonna shake the world!!! If you die, I'll kill you! Bring on the hardship. It's preferred in a path of carnage. More quotes can be read on animequotes. There is someone that I must meet again. And until that day… not even Death himself can take my life away! Well, how about this. My “luck” versus this thing’s “curse”… wanna see what’s stronger…? If I lose, then I’m just that much of a man anyways… There is also wikiquote, which has a compilation of quotes, phrases, dialogues from One Piece. You could search for Zoro in the page for more dialogue from him, but I'll stick to his single quotes here. I will... I will never... LOSE AGAIN! Until I defeat him [Mihawk] and become the world's greatest swordsman, I'll never be defeated by anyone! This is the burden of a captain, you can't doubt yourself. In times like these if you lose your confidence, then who can we have faith in? When the world shoves you around, you've just gotta stand up and shove back. It isn't like you can do anything just by giving excuses. If I die, then I am just a man who can only make it this far. I'll get strong, stronger than she[Kuina] ever was, you hear me! Strong enough that my name reaches up to the heavens! I am going to be the world's greatest swordsman. I promised her... I promised.. I did... I tried to weed out the doubles, but forgive me if I put the same quote more than once. You can read more one liners of One Piece on reddit, but they aren't all Zoro's.
[ "stackoverflow", "0022149760.txt" ]
Q: UIlabel with Custom cell not appear I'm confused !, it is not my first time to create Custom Cell but this time UILabel doesn't appear I don't know where is the problem ? This the custom cell Cell.m mainView = [[UIView alloc] initWithFrame:CGRectZero]; mainView.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:249.0/255.0 blue:249.0/255.0 alpha:1.0]; profile = [[UIImageView alloc] initWithFrame:CGRectZero]; profile.layer.masksToBounds = YES; profile.layer.cornerRadius = 22.5; profile.layer.borderColor = [UIColor whiteColor].CGColor; profile.layer.borderWidth = 1.0f; profile.clipsToBounds = YES; tweet_is = [[UILabel alloc] initWithFrame:CGRectZero]; tweet_is.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:20]; tweet_is.backgroundColor = [UIColor clearColor]; tweet_is.textColor = [UIColor blackColor]; [self.mainView addSubview:tweet_is]; [self.mainView addSubview:profile]; [self.contentView addSubview:self.mainView]; -(void)layoutSubviews { [super layoutSubviews]; self.mainView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 10.0f); self.profile.frame = CGRectMake(15, 15, 45, 45); self.tweet_is.frame = CGRectMake(30, 30, 300.0f, 300.0f); } This is the tableView - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.tweet_is.text = @"Not approve"; return cell; } A: Change this line: self.tweet_is.frame = CGRectMake(30, 30, 300.0f, 300.0f); set it self.tweet_is.frame = CGRectMake(30, 30, 300.0f, 30.0f); If your cell height is less than 300 (I think it is) then you can not see the text. Let me know if that helps.. :)
[ "stackoverflow", "0049751311.txt" ]
Q: Are browsers supposed to handle 304 responses automagically? Might be a silly question, but I haven't found any clear answer yet. My server handles ETag caching for some quite big JSON responses we have, returning 304 NOT MODIFIED with an empty body if the If-None-Match header contains the same hash as the one newly generated (shallow ETags). Are browsers supposed to handle this automagically, or do the in-browser client apps consuming the API asynchronously need to implement some logic to handle such responses (i.e. use the cached version if 304 is responded, create/update the cached version otherwise)? Because so far, I've manually implemented this logic client-side, but I'm wondering whether I just reinvented a square wheel... In other words, with the Cache-Control header for example, the in-browser client apps don't need to parse the value, check for max-age for instance, stores it somehow, setup a timeout, etc.: everything is handled ahead by the browsers directly. The question is: are browsers supposed to behave the same way when they receive a 304? Here is how I wrote my client so far (built with AngularJS, running in browsers): myModule .factory("MyRepository", ($http) => { return { fetch: (etag) => { return $http.get( "/api/endpoint", etag ? { headers: { "If-None-Match": etag } } : undefined ); } }; }) .factory("MyService", (MyRepository, $q) => { let latestEtag = null; let latestVersion = null; return { fetch: () => { return MyRepository .fetch(latestEtag) .then((response) => { latestEtag = response.headers("ETag"); latestVersion = response.data; return angular.copy(latestVersion); }) .catch((response) => { return 304 === error.status ? angular.copy(latestVersion) : $q.reject(response) }); } }; }); So basically, is the above logic effectively needed, or am I supposed to be able to simply use $http.get("/api/endpoint") directly? This code above is working fine, which seems to mean that it needs to be handled programmatically, although I've never seen such "custom" implementations on the articles I read. A: The 304 responses are automagically handled by browser as such So I created a simple page <html> <head> <script src="./axios.min.js"></script> <script src="./jquery-3.3.1.js"></script> </head> <body> <h1>this is a test</page> </body> </html> and the added a test.json file root@vagrant:/var/www/html# cat test.json { "name": "tarun" } And then in nginx added below location ~* \.(jpg|jpeg|png|gif|ico|css|js|json)$ { expires 365d; } Now the results AXIOS As you can see the first request is 200 and second one 304 but there is no impact on the JS code jQuery Same thing with jQuery as well From the curl you can see that server didn't send anything on the 2nd 304 request $ curl -v 'http://vm/test.json' -H 'If-None-Match: "5ad71064-17"' -H 'DNT: 1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.9' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' -H 'Accept: */*' -H 'Referer: http://vm/' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' -H 'If-Modified-Since: Wed, 18 Apr 2018 09:31:16 GMT' --compressed * Trying 192.168.33.100... * TCP_NODELAY set * Connected to vm (192.168.33.100) port 80 (#0) > GET /test.json HTTP/1.1 > Host: vm > If-None-Match: "5ad71064-17" > DNT: 1 > Accept-Encoding: gzip, deflate > Accept-Language: en-US,en;q=0.9 > User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 > Accept: */* > Referer: http://vm/ > X-Requested-With: XMLHttpRequest > Connection: keep-alive > If-Modified-Since: Wed, 18 Apr 2018 09:31:16 GMT > < HTTP/1.1 304 Not Modified < Server: nginx < Date: Wed, 18 Apr 2018 09:42:45 GMT < Last-Modified: Wed, 18 Apr 2018 09:31:16 GMT < Connection: keep-alive < ETag: "5ad71064-17" < * Connection #0 to host vm left intact So you don't need to handle a 304, browser will do that work for you. A: Yes, probably all modern major browsers handle response validation using conditional requests well. Relevant excerpt from The State of Browser Caching, Revisited article by Mark Nottingham: Validation allows a cache to check with the server to see if a stale stored response can be reused. All of the tested browsers support validation based upon ETag and Last-Modified. The tricky part is making sure that the 304 Not Modified response is correctly combined with the stored response; specifically, the headers in the 304 update the stored response headers. All of the tested browsers do update stored headers upon a 304, both in the immediate response and subsequent ones served from cache. This is good news; updating headers with a 304 is an important mechanism, and when they get out of sync it can cause problems. For more information check HTTP Caching article by Ilya Grigorik.
[ "stackoverflow", "0007875453.txt" ]
Q: XLink & XPointer in real world app Do you know some real examples of implementation and real use of extended XLink and XPointer? Does extended XLink or XPointer have some data model - can it be somehow a part of the DOM? Are there some standard approaches (libraries) how to process extended XLink on .NET (Visual Basic)? I'm interested in XBRL whose concept partly stands on the use of extended XLink (linkbases), but I have a doubts whether the XBRL could be succesfull in practice in its whole complexity (if government does not declare it as an obligatory accounting format). A: 1 Docbook uses extended XLink 2 XLink DTD includes the extended element and attribute, so they are accessible using XPath. 3 XPath API should be able to process the extended XLink nodes 4 Microsoft and Apple platforms have XBRL tools, and IBM has best practices References Docbook Release Notes Accelerating XBRL Adoption (pdf)
[ "japanese.stackexchange", "0000054376.txt" ]
Q: でございまして in this sentence? それが困ったことに、次はスープでございまして。 Now that I think of it, I had jotted down another sentence that looks like the same : 海外では魔女はとても人気のあるカテゴリーでしてね Why are ございます and です conjugated that way ? A: Japanese is a rare language in that it is often the listener/reader (instead of the speaker/writer as in English) who must finish the sentence and understand exactly what the speaker/writer would have wanted to say. Not saying everything is a virtue in the Japanese culture whereas saying everything as clearly as possible is a virtue in many others. For that reason, you will keep encountering "sentences" ending with conjunctions and verbs/adjectives in the te-forms for as long as you study Japanese. We call those 「言{い}いさし表現{ひょうげん}」. 「さす」 is 「止す」 in kanji, but you do not have to know that as it is rarely written in kanji. 「さす」 means "to stop (in the middle)", so 「食べさしのハンバーガー」 means a "half-eaten hamburger". The sentence version of that burger is the 言いさし表現, one might say. おもろいこと言うな、ワシも・・ BTW, I have no idea what to call 言いさし表現 in English mainly because it is not a term needed in the English-speaking culture. Thus, every time one uses an 言いさし表現, one is leaving something unsaid. You as the listener/reader, however, will usually have no problem understanding from the context or situation/occasion what was left unsaid by the other person. Context is of utmost importance in Japanese. What might confuse the beginning Japanese-learners the most, however, is the fact that what is left unsaid would almost always be the main clause. So, what kinds of things are most often left unsaid in 言いさし表現? Those would generally be explanations of matters, exclamations, apologies, gratitude and criticism. Finally, though I wish to tell you what is left unsaid in your example sentences, I could not do so for the complete lack of context. 「それが困{こま}ったことに、次{つぎ}はスープでございまして。」 = "Unfortunately, the next course is the soup..." I have no idea in what situation someone might say this. It sounds like the speaker is being apologetic, but that would be all I could say. Context is everything in 言いさし表現. Next, 「海外{かいがい}では魔女{まじょ}はとても人気{にんき}のあるカテゴリーでしてね」 = "Witches are a very popular category abroad..." Again, without context, I have no idea what type of phrase would follow here. All I could guess would be some kind of explanation.
[ "stackoverflow", "0019266694.txt" ]
Q: Order by clause within the Set of an Update Statement I am trying to pick the top 1 result from a select statement inside the set statement of an Update. I can pick the top 1 but the order by clause does not work. Is there a way to make it work or a workaround please? UPDATE a1 SET a1.ServiceLength = ( SELECT TOP 1 a3.START_DATE ORDER BY a3.START_DATE DESC ) FROM #t a1 JOIN #TempService a2 ON a1.EmployeeNo = a2.EMPLOYEE_NO JOIN #TempService a3 ON a3.EMPLOYEE_NO = a2.Employee_No WHERE a2.START_DATE = a3.END_DATE + 1 AND @specifiedDate > a2.START_DATE A: Try to do this using a CTE: WITH TopDate AS ( SELECT TOP 1 a3.START_DATE, a3.employee_no FROM #t a1 JOIN #tempservice a2 ON a1.employeeno = a2.employee_no JOIN #tempservice a3 ON a3.employee_no = a2.employee_no WHERE a2.start_date = a3.end_date + 1 AND @specifiedDate > a2.start_date ORDER BY a3.START_DATE DESC ) UPDATE a1 SET a1.ServiceLength = t.START_DATE FROM #t a1 INNER JOIN TopDate AS t ON a1.employeeno = t.employee_no
[ "stackoverflow", "0031800706.txt" ]
Q: Code coverage with qemu I recently started using qemu and it's a great tool when you don't have the required hardware to run your firmware (currently using it for cortex-m3). Now what I want to do is to do some test coverage with it. I tried using GNUC ARM Eclipse, and I've been successfull compiling and executing the code in qemu, but whenever I add the -fprofile-arcs -ftest-coverage flags (for the project and then for the desired file to run coverage) I am able to create the .gcno file, which means that after executing my code it will generate a .gcda file and then I should be able to see the coverage. Thtat's where everything goes wrong. I was able to generate a .gcda file but whenever I try to open any of them, eclipse tells me that it wasn't able to open the file because it was null. I've tried replicating the procedure in another computer, but I haven't been successful creating the gcda file (probably different binaries). At this point I don't really know how to proceed. Should I abandon ARM Eclipse and stick to makefiles (is it possibll to run gcov this way?) or am I missing something really small that is fixable? PS: I using windows 7 64 bits, the latest versions available on the GNU ARM Eclipse website. Also the idea of doing it via makefiles just occurred to me (it was a stresfull day, it's really late) so I haven't tried it yet, I've only tried executing the code, but without coverage. A: As far as I know, qemu is not able to generate DWARF information. But there is a project with the proposal of code coverage with qemu: Couverture Project
[ "stackoverflow", "0002270852.txt" ]
Q: Set Excel sheet as datasource to Gridview I have the excel sheet, I want to keep it as datasource to the gridview. gridview will be editable so whatever the data updated sholud be write to again in excel sheet with respected location in sheet. How can I do this? A: You could use the Jet driver to select from the spreadsheet via OLEDB. Your spreadsheet will need to be laid out in a table-like fashion, and you can have some painful problems with type guessing, but this may work for your situation. Connection string samples here
[ "stackoverflow", "0026652453.txt" ]
Q: If 2 jqgrid tables are present(with frozen functionality) in same page, frozen columns are not working properly If 2 jqgrid tables are present(with frozen functionality) in same page, frozen columns are not working properly. Second table works fine. But the first table header is messed up. Seems there is some bug in jqgrid css. Oleg please help :) A: Fixed it by adjusting the some CSS properties.
[ "stackoverflow", "0018175385.txt" ]
Q: Is there a way to pass objects from php to javascript like node.js does I'm trying to port an app written in node.js to php for a client and I need to know if there is a way to pass objects from php to javascript like this: <script> var a = <%- instance %>; a.someMethod(); </script> A: Your best bet is to encode your data in JSON format first. your data $data = array( "foo" => "bar", "hello" => "world" ); your script <script> var data = JSON.parse(<?php echo json_encode($data) ?>); </script> PHP json_encode(value[, options]) this function has several options; read more in the docs for dictating a specific encoding behavior JSON_HEX_QUOT JSON_HEX_TAG JSON_HEX_AMP JSON_HEX_APOS JSON_NUMERIC_CHECK JSON_PRETTY_PRINT JSON_UNESCAPED_SLASHES JSON_FORCE_OBJECT JSON_UNESCAPED_UNICODE JavaScript JSON.parse(text[, reviver]) this function takes a reviver and prescribes how the value originally produced by parsing is transformed, before being returned. An alternative (to the above method) would be to provide an asynchronous JSON API Your JavaScript could make a call // using (e.g.,) jquery var loadPeople = function(data) { console.log(data); }; $.getJSON('/api/people.json').done(loadPeople); Your PHP server would have to respond on this route // response to /api/people.json header("Content-type: application/json"); var $data = array( "foo" => "bar", "hello" => "world" ); echo json_encode($data); exit; JavaScript console output {foo: "bar", hello: "world"}
[ "stackoverflow", "0014935126.txt" ]
Q: installing and using python-oauth2 I installed oauth2: $ pip install oauth2 But running the python-oauth2/example/client.py returns: Traceback (most recent call last): File "client.py", line 31, in <module> import oauth.oauth as oauth ImportError: No module named oauth.oauth I tested pip freeze: oauth2==1.5.211 Thanks in advance A: As it turns out, the example directory in the oauth2 package should be ignored. It is broken code as far as the package is concerned. See these issues for examples of other people discovering this: https://github.com/simplegeo/python-oauth2/issues/33 https://github.com/simplegeo/python-oauth2/issues/12 https://github.com/simplegeo/python-oauth2/pull/64 The last one is a pull request that includes new examples to use instead.
[ "stackoverflow", "0055127043.txt" ]
Q: Disable the ServiceBrokerExceptionHandler of the Open Service Broker API I implemented the Open Service Broker API with Spring 2.0. Currently, every exception is caught by the ServiceBrokerExceptionHandler: @ControllerAdvice(annotations = ServiceBrokerRestController.class) @ResponseBody @Order(Ordered.LOWEST_PRECEDENCE - 10) public class ServiceBrokerExceptionHandler { ... } This handler propagates every internal exception to the user. Recently, I saw an EclipseLink exception thrown to the user exposing table structures of my database. I would like to overwrite or fully disable the ServiceBrokerExceptionHandler. I tried implementing my own exception handler with a higher @Order of the ServiceBrokerExceptionHandler: @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE -10) @ResponseBody public static class MyOwnExceptionHandler extends ServiceBrokerExceptionHandler { ... } While the exception handler works for "normal" REST calls it does not for calls to the OSB API. Is there a way to overwrite/disable the built-in ServiceBrokerExceptionHandler`? A: I made kind of a stupid mistake. Ordered.HIGHEST_PRECEDENCE is defined as Integer.MIN_VALUE. So if I subtract the value -10 in @Order(Ordered.HIGHEST_PRECEDENCE -10) the lowest possible integer will be exceeded. While this is a wrong usage by me, I wonder what the default order is, if the user/developer handles the order wrong. For now, it's good enough for me to set the order to a valid number: @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE + 10) @ResponseBody public static class MyOwnExceptionHandler extends ServiceBrokerExceptionHandler { ... }
[ "stackoverflow", "0048116374.txt" ]
Q: Skips animation for custom card stack view So my goal was to do this (do not look at disfigured layouts, i just removed logos): sing in card photo On click "Sign up" sign in card slides down to screen and registration card goes from the bottom: register card photo 3 card (all cards are custom View) on second poto have almost same layouts and each sliding down on click "Continue" button Issue Sliding animation from sign in card to registration skips. Sing in card slides down perfectly but then start delay in ~1 sec and registration card skips sliding in animation and just appears. Animation from registration to sing in card works correct on both cards though. Question How to solve problem with skipping animation from sing in card to registration? Code This is paren class for all cards: public abstract class CardStackView extends RelativeLayout { protected CardStackListener cardStackListener; public CardStackView(Context context) { super(context); } public CardStackView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public CardStackView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setCardStackListener(CardStackListener cardStackListener) { this.cardStackListener = cardStackListener; cardStackListener.onCreated(this); } protected interface CardStackListener { void onCreated(CardStackView view); void onRemove(); void onAdd(); } public abstract void setShade(float value); public abstract void enable(); public abstract void disable(); } And this is class of card holder which is responsible for cards swiching: public class CardStackFragmentView extends FrameLayout { private static final int MARGIN = 10; private static final float SCALE = .1f; private static final float ALPHA = .1f; private List<CardStackView> totalCards = new LinkedList<>(); private List<CardStackView> cards = new LinkedList<>(); private Handler cardHandler = new Handler(); public CardStackFragmentView(Context context) { super(context); Log.i(this.getClass().getName(), "CardStackFragmentView"); } public CardStackFragmentView(Context context, AttributeSet attrs) { super(context, attrs); Log.i(this.getClass().getName(), "CardStackFragmentView"); } /** * Adds cards from params to this card holder * and adds proper sizes and shade to be viewed like a card stack * @param cardStackViews cards for this card holder */ public void addCards(CardStackView... cardStackViews) { totalCards.addAll(Arrays.asList(cardStackViews)); cards.addAll(Arrays.asList(cardStackViews)); for (int i = cards.size() - 1; i >= 0; i--) { CardStackView card = cards.get(i); int offset = i; if (i == 0) { card.enable(); } else { card.disable(); } card.setCardStackListener(new CardStackView.CardStackListener() { @Override public void onCreated(CardStackView view) { view.animate() .scaleX(1 - SCALE * offset) .translationY(-MARGIN * offset); view.setShade(ALPHA * offset); } @Override public void onRemove() { removeFromTop(); } @Override public void onAdd() { addCardToTop(); } }); } //I thought may be if i ll add cards in different threads it solves the problem for (int i = 0; i < cards.size(); i++) { int tmp = i; cardHandler.postDelayed(() -> addView(cards.get((cards.size() - 1 - tmp))), i * 20); } } /** * Adds card on top of stack and reanimates all cards in stack */ public void addCardToTop() { CardStackView fragment = totalCards.get(totalCards.size() - (cards.size() + 1)); fragment.animate().translationY(-(fragment.getHeight() + 30)); cards.add(0, fragment); fragment.enable(); for (int i = 0; i < cards.size(); i++) { CardStackView card = cards.get(i); if (i == 0) { card.enable(); } else { card.disable(); } card.animate() .scaleX(1 - SCALE * i) .translationY(-MARGIN * i); card.setShade(ALPHA * i); } } public void removeFromTop() { Log.i(this.getClass().getName(), "removeFromTop"); CardStackView fragment = cards.get(0); fragment.animate().translationY(fragment.getHeight() + 30); fragment.disable(); cards.remove(0); for (int i = 0; i < cards.size(); i++) { CardStackView card = cards.get(i); if (i == 0) { card.enable(); } else { card.disable(); } card.animate() .scaleX(1 - SCALE * i) .translationY(-MARGIN * i); card.setShade(ALPHA * i); } } } This is onClick method to start animation: @OnClick(R.id.tv_login_register) public void createAccountClicked(View view) { LoginActivity loginActivity = ((LoginActivity) getContext()); RegisterCard registerCard = new RegisterCard(loginActivity); loginActivity.hideMenu(); view.setEnabled(false); startAnimation(AnimationUtils.loadAnimation(loginActivity, R.anim.move_out)); new Handler().postDelayed( () -> { loginActivity.getCardsRelativeLayout().removeView(LoginCard.this); loginActivity.getCardsRelativeLayout().addView(registerCard); registerCard.startAnimation(AnimationUtils.loadAnimation(loginActivity, R.anim.move_in)); }, 400); } Thanks for your time. I hope this help you to help me) A: Problem was not in my custom card stack view, but in activity that contained this view (animation was skipping because there was huge freeze). It was too heavy and with big depth of layouts. So i just light up layout of activity and lags and freezes are gone =) So here is conclusion : Make your xml layouts as light as possible. This was simple answer for my complicated problem.
[ "pt.stackoverflow", "0000273698.txt" ]
Q: Separação ideal de um conjunto de dados em: Treinamento, Validação e Teste Gostaria de saber qual se existe uma recomendação do tipo "rule of thumb" para, em um problema de Aprendizado de Máquina, dividir um conjunto de dados em 3 sets: Treinamento, Validação e Testes. Se sim, qual seria essa divisão ideal? Eu também gostaria de entender melhor qual é a diferença entre o conjunto de validação e o conjunto de testes, e por que é necessário ter os dois. A: De forma geral separamos aleatóriamente uns 70% para treino, 15% de validação e 15% p/ testes... Mas isso varia muito e pode depender do problema, por exemplo quando existe um fator temporal, não podemos separar aleatoriamente e aí é comum pegar um períodos diferentes para treino, validação e teste. Dependendo do tamanho do conjunto de dados, também nem faz sentido usar esses percentuais... Sobre a sua outra pergunta: porque usamos um conjunto de validação e um outro de testes? Em geral ajustamos uma quantidade grande de modelos e verificamos o erro de predição no conjunto de validação, no fim escolhemos o modelo com menor erro no conjunto de validação. O problema é que como ajustamos muitos modelos, é fácil encontrar um modelo que se torna específico (superajustado ou overfitado) para a base de validação e não funciona para outros conjuntos de dados. Por isso deixamos um conjunto de teste para estimar o erro de predição do modelo escolhido e ter certeza de que o modelo não está superajustado.
[ "codegolf.stackexchange", "0000067256.txt" ]
Q: Shorten an already short mathematical expression For once, I was doing some real work, updating old code, and bumped into an expression that is equivalent to what would be written as πx + ex in good old-fashioned math. I thought it would be possible to write it shorter than it was written in the language I work with (APL), and therefore present this very simple challenge: Write a function or program that (by any means) accepts zero or more numbers, and returns (by any means) the result of the above expression for x = each of the given numbers with at least 3 significant digits for each result. If your language does not have π and/or e, use the values 3.142 and 2.718. Scoring is number of bytes, so preface your answer with # LanguageName, 00 bytes. Standard loop-holes are not allowed. Edit: Now the solution I came up with, ○+*, has been found. The original code was (○x)+*x. A: Emotinomicon, 48 bytes / 13 characters I do it, not because it is short, but because it is fun. Try it here. You'll have to copy+paste it into the textbox. ⏪✖➕⏩ Explanation: ⏪ ✖ ➕ ⏩ explanation take numeric input ⏪ open loop duplicate top of stack push pi ✖ multiply top two elements on stack reverse stack pop N, push e^N ➕ add top two elements on stack take numeric input duplicate top of stack pop N, push N+1 ⏩ close loop Here is the program in its native environment, the mobile phone: A: Dyalog APL, 3 characters As a tacit phrase. ○+* Monadic ○ multiplies its argument with π, monadic * is the exponential function exp. ○+* is a train such that (○+*)ω is equal to (○ω)+(*ω). Since this is APL, the phrase works for arguments of arbitrary shape, e. g. you can pass a vector of arbitrary length. The same solution is possible in J as o.+^ with o. being ○ and ^ being *. A: R, 25 24 bytes cat(exp(x<-scan())+pi*x) Is this it? It gets input from user, assign it to x, calculates its exponential multiply it to pi, and finally cat()prints the result. edit: 1 bytes saved thanks to Alex A.
[ "stackoverflow", "0024083491.txt" ]
Q: How do I set div height proportional to screen resolution? I saw there are many similar questions, but I can't find one solution working for me. My page has this structure: <body> <div id="whole_page"> <div id="header"></div> <div id="main"> <div id="img_container"></div> <div id="img_container"></div> <div id="img_container"></div> </div> </div> </body> My css is: html,body{ height:100%; width:100%; padding-top:50px; } #whole_page{ height:calc(100%-50px); width:100%; } #header{ position:fixed; height:50px; // header } #image_container{ width:100%; height:30%; } I want to set "main" 's height to 100% (window height) minus header height (50px). Further, I want each div with id "image_container" to be 30% of the "main" div and large 100% of widonws width. So that I have approximately 3 of those div in the page, before needing to scroll. The problem is that % seem to not work at all. As I didn't write them (tried with Chrome's dev tools). Actually I am using bootstrap to fill content of header/main but as far as I know this shouldn't give problems with height. Any clue? Thanks in advance A: Your key problem is that you did not change the height of #main. You also had a miss type between your CSS and HTML, in your CSS you referred to #image_container while in your HTML you used 'id="img_container"'. I change both CSS and HTML to '.img_container' and 'class="img_container"' respectively. I also noticed that you had twice the amount of space at the top than the size needed for your #header since 'padding-top: 50px;' was applied to html and body. Here is the code: <div id="whole_page"> <div id="header" style="background-color: yellow;"></div> <div id="main"> <div class="img_container" style="background-color: red;"></div> <div class="img_container" style="background-color: blue;"></div> <div class="img_container" style="background-color: green;"></div> </div> </div> and html, body { height:100%; width:100%; } body { margin: 0; padding-top:50px; } #whole_page { height: calc(100% - 50px); width: 100%; } #header { position: fixed; height: 50px; width: 100%; top: 0; } #main { height: 100%; } .img_container { width: 100%; height: 30%; } PS - add color to some of the tags so I could see them. You can just delete the style attribute from the '#header' and '.img_container' tags. EDIT - Here is a jsfiddle: http://jsfiddle.net/xiondark2008/DJJ2d/ EDIT2 - Just side thought, 'height: calc(100%-50px);' is an invalid property, at least in chrome, however 'height: calc(100% - 50px);' is a valid property, again, at least in chrome.
[ "stackoverflow", "0018108749.txt" ]
Q: Java (swing) paint only what's viewable on the screen I am making a tile based platformer game in java. I render a map which is stored in a 2 dimensional array but when this array is very big my game starts to become slow. I realised that I had to only render the part of the map that is viewable, I tried to do that but i wrote very hacky code that only worked partly so I removed it. How can I do this properly? Here is my code (without the hacky stuff). Also how could I use System.nanoTime() rather than System.currentTimeMillis()? package sexy_robot_from_another_dimension; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.TexturePaint; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Timer; import java.util.TimerTask; import javax.swing.JPanel; @SuppressWarnings("serial") public class Game extends JPanel { int playerX = 50; int playerY = 50; static boolean up = false; static boolean down = false; static boolean right = false; static boolean left = false; int playerSpeed = 1; String[][] map; int blockSize = 20; int jumpLoop = 0; int maxJumpLoop = 280; static BufferedImage block, player; int playerWidth = 20; int playerHeight = 35; int cameraX = 0; int cameraY = 0; long nextSecond = System.currentTimeMillis() + 1000; int frameInLastSecond = 0; int framesInCurrentSecond = 0; public Game() { super(); try { map = load("/maps/map1.txt"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if(up) { if((!playerIsOnBlock(playerX, playerY).equals("0")) || (!playerIsOnBlock(playerX + (playerWidth - 1), playerY).equals("0"))) { timeToJump(); } } if(down) { } if(right) { if((playerIsLeftBlock(playerX, playerY).equals("0")) && (playerIsLeftBlock(playerX, playerY + (playerHeight/2 - 1)).equals("0")) && (playerIsLeftBlock(playerX, playerY + (playerHeight - 1)).equals("0"))) { playerX += playerSpeed; } } if(left) { if((playerIsRightBlock(playerX, playerY).equals("0")) && (playerIsRightBlock(playerX, playerY + (playerHeight/2 - 1)).equals("0")) && (playerIsRightBlock(playerX, playerY + (playerHeight - 1)).equals("0"))) { playerX -= playerSpeed; } } repaint(); } }; timer.scheduleAtFixedRate(task, 0, 10); Timer timerGrav = new Timer(); TimerTask taskGrav = new TimerTask() { @Override public void run() { if((playerIsOnBlock(playerX, playerY).equals("0")) && (playerIsOnBlock(playerX + (playerWidth - 1), playerY).equals("0"))) { playerY += playerSpeed; repaint(); } } }; timerGrav.scheduleAtFixedRate(taskGrav, 0, 6); } void timeToJump() { if(jumpLoop == 0) { jumpLoop = 1; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { if((playerIsBelowBlock(playerX, playerY).equals("0")) && (playerIsBelowBlock(playerX + (playerWidth - 1), playerY).equals("0"))) { playerY -= playerSpeed; jumpLoop++; repaint(); } else { jumpLoop = maxJumpLoop; } if(jumpLoop == maxJumpLoop) { jumpLoop = 0; cancel(); } } }; timer.scheduleAtFixedRate(task, 0, 3); } } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); long currentTime = System.currentTimeMillis(); if (currentTime > nextSecond) { nextSecond += 1000; frameInLastSecond = framesInCurrentSecond; framesInCurrentSecond = 0; } framesInCurrentSecond++; g.drawString(frameInLastSecond + " fps", 10, 20); cameraX = -playerX + getWidth()/2; cameraY = -playerY + getHeight()/2; g.translate(cameraX, cameraY); for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { switch(map[x][y]) { case "0": break; case "1": if(block != null) { TexturePaint tp0 = new TexturePaint(block, new Rectangle(0, 0, blockSize, blockSize)); g2.setPaint(tp0); } g.fillRect(y*blockSize, x*blockSize, 20, 20); break; } } } g.setColor(Color.BLACK); if(player != null) { TexturePaint tp0 = new TexturePaint(player, new Rectangle(playerX, playerY, playerWidth, playerHeight)); g2.setPaint(tp0); } g.fillRect(playerX, playerY, playerWidth, playerHeight); g.setColor(Color.black); g.setFont(new Font("Droid Sans Mono", Font.PLAIN, 12)); g.drawString("Sexy!", playerX - 5, playerY - 10); } boolean outOfMap(int x, int y) { y -= blockSize - 1; x -= blockSize - 1; if((y/blockSize <= map.length - 2) && (y/blockSize >= 0) && (x/blockSize <= map[0].length-2) && (x/blockSize >= 0)) { return false; } return true; } String playerIsOnBlock(int x, int y) { y += playerHeight; if(!outOfMap(x, y)) { if(map[y/blockSize][x/blockSize] != "0") { return map[y/blockSize][x/blockSize]; } } return "0"; } String playerIsBelowBlock(int x, int y) { y -= playerSpeed; if(!outOfMap(x, y)) { if(map[y/blockSize][x/blockSize] != "0") { return map[y/blockSize][x/blockSize]; } } return "0"; } String playerIsLeftBlock(int x, int y) { x += playerWidth; if(!outOfMap(x, y)) { if(map[y/blockSize][x/blockSize] != "0") { return map[y/blockSize][x/blockSize]; } } return "0"; } String playerIsRightBlock(int x, int y) { x -= playerSpeed; if(!outOfMap(x, y)) { if(map[y/blockSize][x/blockSize] != "0") { return map[y/blockSize][x/blockSize]; } } return "0"; } String[][] load(String file) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file))); int lines = 1; int length = br.readLine().split(" ").length; while (br.readLine() != null) lines++; br.close(); br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(file))); String[][] map = new String[lines][length]; for (int i = 0; i < lines; i++) { String line = br.readLine(); String[] parts = line.split(" "); for (int y = 0; y < length; y++) { map[i][y] = parts[y]; } } br.close(); return map; } } Thank you! A: Set the clipping region to the visible area with Graphics.setClip(), that will prevent most rendering operations from taking effect outside that region. For drawing operations where this isn't sufficient (perhaps you also want to avoid doing calculations or something for objects outside the clipping area), test your objects bounds against the clipping rectangle and skip the object if it doesn't intersect. See Graphics.setClip(). A further optimization can be done by, for example, calculating the range of blocks on your map that is definitely outside of the visible area, and excluding that from your for loop (no sense testing blocks against the clipping region if you know they are outside already). Take the clipping region, transform it to map index coordinates, then you will know where in your map the visible area is and you can just iterate over that subsection of the map. A: It seems your camera is centered on the player, then there are two ways of doing this, I like the first way, it is a bit cleaner: 1th: Create a rectangle that bounds your cameras view, and check if the map x,y is within this view, render only if true. Rectangle cameraView = new Rectangle(playerX - getWidth() / 2, playerY - getHeight() / 2, getWidth(), getHeight()); for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { if (!cameraView.contains(x*blockSize, y*blockSize)) continue; switch (map[x][y]) { case "0": break; case "1": if (block != null) { TexturePaint tp0 = new TexturePaint(block, new Rectangle(0, 0, blockSize, blockSize)); g2.setPaint(tp0); } g.fillRect(y * blockSize, x * blockSize, 20, 20); break; } } } The second option is to simply calculate the distance to the center of the screen (playerX,playerY) from each map[x][y] and skip all map[x][y] that falls outside your viewing bounds, this is a bit uglier to code and I really don't recommend this, the rectangle option above should be fast enough. Edit: @JasonC That is true, I didn't consider for instance when an x value is definitely outside the view, it will still go into the y loop through all the y values. One can simply create a dummy variable in the x-loop and do the following check for (int x = 0; x < map.length; x++) { int dummyY = playerY if(!cameraView.contains(x,dummyY)) continue; .... //rest of code ommitted Another optimization you can do is considering not setting a TexturePaint (expensive operation) but instead simply drawing the image of the block: g.fillRect(y * blockSize, x * blockSize, 20, 20); Replaced with g.drawImage(block, y*blockSize, x*blockSize, null); The same with the playerimage.
[ "stackoverflow", "0030242911.txt" ]
Q: Retrieve subscription with Stripe Parse api At the moment, I don't see any functionality to retrieve a Stripe subscription from Stripe's Parse.com module. Does anyone know how to do this? Thanks A: The Parse API library is extremely old (only one subscription per customer), so the subscription object is just part of the customer object.
[ "math.stackexchange", "0003736914.txt" ]
Q: Toward creating the neighborhoods of a point in the Zariski Topology. In the instance of a line $L$ intersecting with a parabola I need to find out if the intersection is a dense subset. Here's my work / question so far: For another point $P$ on the parabola not in the intersection of $L$, is the entire complement of another variety which contains that point counted as a neighborhood or just the connected part around the point? That is whenever I look at a circle $C$ centered at $P$ which doesn't have the intersection of the line within the radius then is the complementary set of $C$ which has two parts- one which has the point in it and the other with the line intersecting the parabola counted as a neighborhood around $P$ which contains the intersection of the line? The text 'An Invitation to Algebraic Geometry' does say that the open sets are very large so can't that just mean that the set is dense along with that the two parts in and outside of the circular variety are connected, because they can not really be complementary sets of any polynomials! A: From your question you seem to be slightly confused about what the Zariski topology looks like. We do not want to look at "open balls of radius $r$" like we would in the usual euclidean topology, instead we want to be looking at zero sets of polynomials. Recall that a set $Y \subset X$ is dense if and only if $\bar{Y} = X$. Now, the line $L$ and the parabola $X$ are both closed subsets of $\mathbb{A}^2$ since they are the vanishing sets of some polynomials $y - mx - c$ and $y - x^2 - ax - b$ respectively. Thus the intersection $L \cap X$ is a proper closed subset of $X$ hence not dense.
[ "stackoverflow", "0032097356.txt" ]
Q: Why does running UIAutomation methods from KIF result in: "UIAutomation is not enabled on this device. UIAutomation must be enabled in Settings"? Using: iOS 8.4, XCode 6.4, KIF 3.2.1 (https://github.com/kif-framework/KIF) I encounter the following problem on a real device: While running a KIF test case, calling the method, "deactivateAppForDuration" results in the following output seen in the XCode console: "UIAutomation is not enabled on this device. UIAutomation must be enabled in Settings." On the simulator, the app does indeed go to the background for the duration specified in the parameter of that method call. I can confirm that the setting in device settings, "Developer > UIAutomation" is toggled on. The build that I am compiling and running is a Debug build and is signed with my Developer Provisioning Profile (not a distribution profile). All the possible compile configurations in the scheme are set to debug (profile for example) I can record and playback UI interactions in the instruments developer tool (confirms that the app is built right and that the phone settings are correct) Specific Code: [tester deactivateAppForDuration:5]; What could I be missing? A: This is a known issue with UIAutomation on the device, see here.
[ "engineering.stackexchange", "0000028843.txt" ]
Q: How were horizontal and vertical structures ensured in old times? In modern times bubble levels and water levels are used to check if a surface if strictly horizontal/vertical. How did people ensure vertical/horizontal surfaces in older times? A: Well, the Romans did lots of surveying and built some excellent roads, using the Groma. The plumb line is still handy... Also, water find its own level so a crude level is also available and before lasers came along, many large sites were set up with flexible pipes with transparent sections to provide a level across a longer distance, 20 or 30m or more. A: Egyptians used shallow water trenches as level complemented with "Merchet and Groma" to build the great pyramids. In old Persia they had plumbed levels and used ropes and triangulation. They used those tools to great accuracy to build those Qanats, (subterranean irrigation canals) In the old Roman empire they recognized surveying as a profession and had skilled masons. .
[ "stackoverflow", "0003678393.txt" ]
Q: Why does Win32 API function CredEnumerate() return ERROR_NOT_FOUND if I'm impersonated? I've written some sample code which when I call from the windows command prompt under the context of a normal user account, dump's all the user's saved credentials using CredEnumerate(). However, I really want to be able to do this from SYSTEM user context so I've tested my program from a SYSTEM cmd prompt. When I running my program as SYSTEM, I run LogonUser like so: bLoggedOn = LogonUser(userName.c_str(), domain.c_str(), password.c_str(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &userToken_); Then I run ImpersonateLoggedOnUser() on the token to give me the security context of the local user. After this I do: bOk = CredEnumerate(NULL, 0, &count, &pCredentials); And I'd expect this to return the credentials in the same way as if I'd not gone in from system and impersonated. Can anyone spot anything that I've missed to truly put myself in the user's context? A: I guess I aught to answer this question myself since I've now spent ages working out how to do this and I'm not sure it's widely known. CredEnumerate/CredRead will never provide password information for domain passwords no matter what process context you're in or what token you have despite what it seems to hint at on MSDN. The only way to get access to the saved credential information is to do so using the undocumented function LSAICryptUnprotectData() which is in lsasrv.dll. This can decrypt the files you find in %APPDATA%\Microsoft\Credentials and can provide an identical data structure to CredEnumerate except with the password filled in. The only catch is that this must be done in the process context of lsass.exe (The windows security subsystem), no setting of privilledges etc is enough to give a normal process the rights to do this. If you're a hacker you can do this by performing a CreateRemoteThread() to inject a thread into lsass.exe or if you're trying to do this in a legitimate way, i.e you're extending the Windows operating system in some way for a third party application, like I was, you can do this by creating a Windows authentication package which lsass will load. This AP can then use a named pipe or some such method to allow interaction with the rest of your code.
[ "stackoverflow", "0006759800.txt" ]
Q: SQL Multiple Row Subquery I have a table Studies that I perform a SELECT on. I then need to perform a further SELECT on the recordset returned. I've tried this (simplified for clarity): SELECT * FROM Studies WHERE Id = '2' OR Id = '3' OR Id = '7'; SELECT * FROM Studies WHERE (Name = 'Test') AND Id IN (SELECT * FROM Studies WHERE Id = '2' OR Id = '3' OR Id = '7'); But I keep getting the following SQL error: Only a single result allowed for a SELECT that is part of an expression Where am I going wrong? If it's not evident from my code - I am relatively new to database programming. Thanks A: You can't return more than one column in a IN (...) subquery. You have to change the * (return all columns) to ID. But your query does not need a subquery, You can just add the ID's to the first query. You usually want to avoid subqueries where you can because of performance reasons. SELECT * FROM Studies WHERE Name = 'Test' AND ID IN ('2', '3','7') Or if you want to keep your structure: SELECT * FROM Studies WHERE (Name = 'Test') AND ID IN (SELECT ID FROM Studies WHERE ID = '2' OR ID = '3' OR ID = '7');
[ "stats.stackexchange", "0000022061.txt" ]
Q: VIF values in regression Do high VIF values for a a particular variable $x$ just indicate that it is highly correlated with at least one of the other variables in the model? Does it specify which variables and how many variables that $x$ is correlated with? A: No. That's one reason it is better to look at condition indices and the variance proportion matrix. In SAS PROC REG you can get this with the /collin option on the model statement. See Regression Diagnostics by Belsley, Kuh & Welsch or Conditioning Diagnostics: Collinearity and Weak Data in Regression by Belsley (out of print, but more thorough on the problem of collinearity specifically). Or you could even look at my dissertation: Multicollinearity Diagnostics for Multiple Regression: A Monte Carlo Study (haven't really looked much at this since then, though).
[ "academia.stackexchange", "0000000555.txt" ]
Q: Does a informative and clear professor webpage often increase the number of prospective PhD students who apply to work for the professor? Here is what I would call a particularly informative and clear professor webpage. Of course, it's not the most important thing (for me, personally, I mostly discovered professors through asking current professors whom to contact). But a lot of PhD students do discover professors to contact through Internet searches, which may be especially relevant for PhD students who might not have as many connections (especially international ones). And maybe a strong professor webpage could also increase the "fit" of the applicants who do decide to contact the professor. A: As an international student who is (was?) looking for potential advisors, I'd say yes (As far as I know)! The algorithm for me worked as follows: Contact the obvious ones. These were authors of papers I read recently (& liked), editors of journals etc. Basically, the ones with good "academic presence". Look at professors who have written textbooks or survey papers. Look at strong departments for professors. (By strong I mean : Reputation, Rankings and Star Power/Infrastructure) If a professor has a good webpage (Updated recently with list of current/past projects, list of graduate students and alumni), Shoof! Time saved! If a professor has a bad webpage (Last updated in 2001 or with minimal content or whatever), then run him on google scholar. Read his papers and try to find out what his students are upto. Once a professor has been selected, run youtube and ratemyprofessor on him. This is usually worthless but it did yield some awesome results once in a while. It did help get a virtual lab tour at times. In conclusion: Maintaining a good website does help students (especially international) get to know the professor better. It does save us a lot of time by having access to all relevant information at one place What is most irritating is webpages with very old content. I would prefer limited recent content to old obsolete content.
[ "stackoverflow", "0059599263.txt" ]
Q: Keeping local changes after git Untracked Files Prevent Merge I have an Android app in GitHub which uses an API key. I have set it up in my local.properties and ignored it in gitignore. However, in order for GitHub Actions to build my app, it looks for a local.properties file with a certain key, and as it is ignored, the build process fails. I created a fake local.properties in GitHub with an empty key and it works (the tests don't need to see the map itself, but they just need the app to compile and run), but unfortunately, whenever I try to pull from the remote, I get: error: The following untracked working tree files would be overwritten by merge: local.properties Of course, I want to keep the local copy of local.properties as it is the one that contains the valid API key. What can I do in order to prevent this, so I can be able to push and pull, and have the project built but without exposing my keys? Thanks! A: Why not create the fake local.properties file in your workflow instead of committing it. Then it will only exist temporarily. - name: Create local.properties run: echo "apikey=empty" > local.properties Alternatively, commit a file with a different name and rename it just before building. - name: Create local.properties run: mv local.properties.fake local.properties
[ "stackoverflow", "0026956498.txt" ]
Q: How to call stored procedure from Oracle using PetaPoco I have stored procedure in Oracle CREATE OR REPLACE PROCEDURE proc1 (p_param1 INTEGER, p_param2 CHAR, p_param3 INTEGER) AS BEGIN ... END; and I call it in Oracle SQL Developer using this statement: EXECUTE proc1(2013, 1, 3); I try to call it in C# from Visual Studio but it doesn't works _db.Execute("EXEC proc1 (2013, 1, 3)"); How can I properly call it in C#? Thanks. A: EXEC is a command of SQL*Plus. Try to use command without EXEC or in anonymous PL/SQL block: _db.Execute("proc1 (2013, 1, 3)"); or _db.Execute("begin proc1 (2013, 1, 3); end;"); Also, in this case, 1 could be converted to CHAR automatically, and in other cases you need to use quotes '': _db.Execute("begin proc1 (2013, 'abc', 3); end;");
[ "stackoverflow", "0023024321.txt" ]
Q: Specify range for numeric variable in R I'm trying to produce a linear model from one dataset then use that linear model to predict values for another dataset. However the problem I'm getting is the predicted values are outside of the range of acceptable values. Im predicting a value between 0-30 and get values greater than 30. How do I restrict the model to this range? A snippet of my code: results.lm <- lm(y~a1+a2) predict(results.lm,newdata) My results look like this: 1315 1316 1317 27.271558 31.196606 24.736370 A: Rather than restricting your model predictions (which can't be prespecified) you can put a ceiling on the output vector afterwards: preds <- predict(results.lm,newdata) So try: preds <- ifelse(preds > 30, 30, preds)
[ "stackoverflow", "0054354075.txt" ]
Q: How can I stop these variables from resetting while still being able to loop them? Here's part of my code: def dice_game(): dice_window = Tk() dice_window.geometry('450x450') player1_score = 0 player2_score = 0 def player1_turn(): player1_num1 = random.randint(1, 6) player1_num2 = random.randint(1, 6) player1_score = player1_num1 + player1_num2 player1_total = player1_num1 + player1_num2 if (player1_total % 2) == 0: player1_score = player1_score + 10 else: player1_score = player1_score - 5 player1_result = Label(dice_window, text = ( "Player 1 got", player1_num1, "and", player1_num2, "and their total score is:", player1_score)) player1_result.pack() for x in range(1, 6): player1_turn() I've tried putting the loop inside the player1_turn () function and in the dice_game() function but the outcome is always the same. How can I keep the 2 players score without resetting them every time this section loops 5 times? A: Let's break this down. I can see that player1_turn() is nested because you want to have access to dice_window. But there is a better way! First separate the functions. player1_turn needs a dice window, and it looks like the thing you want to save is player1_score, so we'll return that. def player1_turn(dice_window): player1_num1 = random.randint(1, 6) player1_num2 = random.randint(1, 6) player1_score = player1_num1 + player1_num2 player1_total = player1_num1 + player1_num2 if (player1_total % 2) == 0: player1_score = player1_score + 10 else: player1_score = player1_score - 5 player1_result = Label(dice_window, text = ( "Player 1 got", player1_num1, "and", player1_num2, "and their total score is:", player1_score)) player1_result.pack() return player1_score Now onto the game: def dice_game(): dice_window = Tk() dice_window.geometry('450x450') # we're not using x, so we should make it clear that this is a loop of 5 scores = [] total = 0 for x in range(5): player1_score = player1_turn(dice_window) # now what to do with the score? scores.append(player1_score) # save it? print(player1_score) # print it? total += player1_score # add it up print(scores) print(total)
[ "stackoverflow", "0014013025.txt" ]
Q: C++ 'delete' an object which has a reference It seems that 'delete' (free memory in C++) does not work when I'm trying the following code... Well, I know the reference is not suitable for "refer to an object which will be freed later on". I am just playing the code.. class A{ public: int val; A(int val_=0):val(val_){} }; A* ptrA = new A(10); A &refA = *ptrA; printf("%d\n", refA.val); delete ptrA; refA.val = 100; printf("%d\n", refA.val); The output is : 10 100 A: It does work, and everything you do on refA causes undefined behavior, i.e., as far as the standard is concerned, anything may happen, including "it seems to work". In practice, for the moment it may seem to work because that memory hasn't been reused yet, but wait a few allocations and you'll see you'll be overwriting other, unrelated objects. Remember, when you go into "undefined behavior"-land you get a crash or a failed assertion if you are lucky; often, you'll get strange, non-reproducible bugs that happens once in a while driving you mad. Well, I know the reference is not suitable for "refer to an object which will be freed later on". I am just playing the code.. There's nothing bad in having a reference to stuff that will be freed... the important point is that it has to be freed after the reference goes out of scope. For example, in this case it's perfectly fine: A* ptrA = new A(10); { A &refA = *ptrA; std::cout<<refA.val<<"\n"; } delete ptrA;
[ "worldbuilding.stackexchange", "0000010236.txt" ]
Q: How can I make rapid recovery from prosthetic arm surgery more plausible? Near the beginning of my story, my main character loses an arm, and is going to get a prosthetic replacement. I've done some research on prosthetic limbs, and as one might expect, you're not good to go in a week. The problem is, I had intended for everything to be occurring during a serious winter storm, in order to limit communications in a fairly remote area. I'm willing to scale this back to an especially bad winter season, but I still don't seem to have enough time for recovery. I'm somewhat limited in using different ways to knock communications out, because the story is drawing a parallel with a storm, and doing almost meta-commentary with it. The good news, is I'm operating maybe 5-15ish years in the future, so that I can have some more advanced genetics/biotech stuff going on. I don't mind saying that the hospital he will be at is the world's leader, as a major plot point is a nearby top-tier research lab. Is it plausible that prosthetic technology might advance enough in that timeframe, so that I could have my main character up and active in 2-3 weeks? I wouldn't even mind if he has some ongoing pain/fatigue from cutting things a bit short. Thanks! A: TL;DR Screw an ITAP into the bone stub, reinforce it with some titanium bands, take some drugs, and pet a kitty with your new cyborg arm. Ah, cyborgs. Personally, I design the electronics (neurostimulators) for cyborgs (usually old people), but the mechanical stuff is pretty rad, so I follow it too. There are some relatively recent advancements in prosthetics that you should be aware of, though it doesn't currently reduce healing time, I think this method would be the easiest to start with in order to accelerate healing time. The Prosthetics Intraosseous transcutaneous amputation prosthesis or ITAP. Translated to English that means, in-the-bone and through-the-skin limb replacement. The very cool thing about these prosthetics is that they attach directly in the bone and don't rest on a healed over stump. This means that loads experienced by your character, such as shoveling snow, can be taken through the skeleton rather than through soft tissue. The lost limb is better replaced because the user regains sensory signals to the bone; so called osseoperception. This reduces the learning time compared to normal prosthetics, because it's much more like the original limb. The most famous patient, currently, for these special prosthetics is a cat named Oscar. There are several human patients, and most of the photos for them are a bit more gruesome looking, so I won't add them here. But have yourself a google image search. Accelerating Recovery The main concern you'll have is allowing sufficient time for the bone to heal and hold onto the titanium bone implant. I think you can accelerate the bone healing with drugs and by reinforcing the bone with a custom boot or bands. There are a few examples of this with femur fractures or hip replacements, but typically medicine is not concerned with making someone better in three weeks, because we're still working on the getting better part. The best path for further research, since ITAP is still fairly new, is with osseointegrated titanium implants in general. Any advancements there will, for the most part, also apply to ITAP devices. Once the bone part is taken care of the rest is not as much of a concern. The skin and other soft tissue around the titanium will not be load bearing, so it can take longer to heal. This can be made easier for your character by having a 'convenient' amputation location, like just below the elbow. A: Nueroscientist Miguel Nicolelis has been working on a brain machine interface. He claims this interface has allowed monkeys to control robotic arms. Here is a Nicolelis TED talk. Dr. Nicolelis is hoping this will restore ability to those with spinal cord injuries. It might also be an interface to remotely operate tele-robots. I am hoping tele-robots will become more common in industry doing work in hard to reach or inhospitable places. ROVs are already doing work on the sea floor. If someone has grown practiced at using a Nicolelis cap to operate a tele-robot, it would be a small step to use the same interface to operate a robotic arm prosthetic.
[ "stackoverflow", "0034273458.txt" ]
Q: Parsing columns lines with a single double quotations in Graphlab.SFrame I have lines as such from this dataset (https://raw.githubusercontent.com/alvations/stasis/master/sts.csv): Dataset Domain Score Sent1 Sent2 STS2012-gold surprise.OnWN 5.000 render one language in another language restate (words) from one language into another language. STS2012-gold surprise.OnWN 3.250 nations unified by shared interests, history or institutions a group of nations having common interests. STS2012-gold surprise.OnWN 3.250 convert into absorbable substances, (as if) with heat or chemical process soften or disintegrate by means of chemical action, heat, or moisture. STS2012-gold surprise.OnWN 4.000 devote or adapt exclusively to an skill, study, or work devote oneself to a special area of work. STS2012-gold surprise.OnWN 3.250 elevated wooden porch of a house a porch that resembles the deck on a ship. I have read it into a graphlab.SFrame using the read_csv() function: import graphlab sts = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', column_type_hints=[str, str, float, str, str]) And there were lines that are not parsed. The traceback is as follows: PROGRESS: Unable to parse line "STS2012-gold MSRpar 3.800 "She was crying and scared,' said Isa Yasin, the owner of the store. "She was crying and she was really scared," said Yasin." PROGRESS: Unable to parse line "STS2012-gold MSRpar 2.200 "And about eight to 10 seconds down, I hit. "I was in the water for about eight seconds." PROGRESS: Unable to parse line "STS2012-gold MSRpar 2.800 "It's a major victory for Maine, and it's a major victory for other states. The Maine program could be a model for other states." PROGRESS: Unable to parse line "STS2012-gold MSRpar 4.000 "Right from the beginning, we didn't want to see anyone take a cut in pay. But Mr. Crosby told The Associated Press: "Right from the beginning, we didn't want to see anyone take a cut in pay." PROGRESS: Unable to parse line "STS2014-gold deft-forum 0.8 "Then the captain was gone. Then the captain came back." PROGRESS: Unable to parse line "STS2014-gold deft-forum 1.8 "Oh, you're such a good person! You're such a bad person!"" PROGRESS: Unable to parse line "STS2012-train MSRpar 3.750 "We put a lot of effort and energy into improving our patching process, probably later than we should have and now we're just gaining incredible speed. "We've put a lot of effort and energy into improving our patching progress, p..." PROGRESS: Unable to parse line "STS2012-train MSRpar 4.000 "Tomorrow at the Mission Inn, I have the opportunity to congratulate the governor-elect of the great state of California. "I have the opportunity to congratulate the governor-elect of the great state of California, and I'm lookin..." PROGRESS: Unable to parse line "STS2012-train MSRpar 3.600 "Unlike many early-stage Internet firms, Google is believed to be profitable. The privately held Google is believed to be profitable." PROGRESS: Unable to parse line "STS2012-train MSRpar 4.000 "It was a final test before delivering the missile to the armed forces. State radio said it was the last test before the missile was delivered to the armed forces." PROGRESS: 22 lines failed to parse correctly PROGRESS: Finished parsing file /home/alvas/git/stasis/sts.csv PROGRESS: Parsing completed. Parsed 19075 lines in 0.069578 secs. Look at these lines there seems to be a problem if any of my Sent1 or Sent2 columns contains odd-numbered double quotation marks. Using the error_bad_lines to track the problematic lines: sts = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', column_type_hints=[str, str, float, str, str], error_bad_lines=True) It throws the traceback: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-15-a1ec53597af9> in <module>() 1 sts = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', column_type_hints=[str, str, float, str, str], ----> 2 error_bad_lines=True) /usr/local/lib/python2.7/dist-packages/graphlab/data_structures/sframe.pyc in read_csv(cls, url, delimiter, header, error_bad_lines, comment_char, escape_char, double_quote, quote_char, skip_initial_space, column_type_hints, na_values, line_terminator, usecols, nrows, skiprows, verbose, **kwargs) 1537 verbose=verbose, 1538 store_errors=False, -> 1539 **kwargs)[0] 1540 1541 /usr/local/lib/python2.7/dist-packages/graphlab/data_structures/sframe.pyc in _read_csv_impl(cls, url, delimiter, header, error_bad_lines, comment_char, escape_char, double_quote, quote_char, skip_initial_space, column_type_hints, na_values, line_terminator, usecols, nrows, skiprows, verbose, store_errors, **kwargs) 1097 glconnect.get_client().set_log_progress(False) 1098 with cython_context(): -> 1099 errors = proxy.load_from_csvs(internal_url, parsing_config, type_hints) 1100 except Exception as e: 1101 if type(e) == RuntimeError and "CSV parsing cancelled" in e.message: /usr/local/lib/python2.7/dist-packages/graphlab/cython/context.pyc in __exit__(self, exc_type, exc_value, traceback) 47 if not self.show_cython_trace: 48 # To hide cython trace, we re-raise from here ---> 49 raise exc_type(exc_value) 50 else: 51 # To show the full trace, we do nothing and let exception propagate RuntimeError: Runtime Exception. Unable to parse line "STS2012-gold MSRpar 3.800 "She was crying and scared,' said Isa Yasin, the owner of the store. "She was crying and she was really scared," said Yasin." Set error_bad_lines=False to skip bad lines Is there a way to resolve this problem where my lines contains odd number of double quotes? Is there a way to do it without cleaning the data (e.g. identifying the problematic lines and then clean/correct them but keep another SFrame to track the cleaning/correction? As a sanity check, if we do a search \t in the raw csv file, there's a tab in the rows that gives problem but when graphlab parses it, it disappears: As another sanity check, reading the file line by line and splitting it by \t returns 5 columns for the whole file: alvas@ubi:~/git/stasis$ head sts.csv Dataset Domain Score Sent1 Sent2 STS2012-gold surprise.OnWN 5.000 render one language in another language restate (words) from one language into another language. STS2012-gold surprise.OnWN 3.250 nations unified by shared interests, history or institutions a group of nations having common interests. STS2012-gold surprise.OnWN 3.250 convert into absorbable substances, (as if) with heat or chemical process soften or disintegrate by means of chemical action, heat, or moisture. STS2012-gold surprise.OnWN 4.000 devote or adapt exclusively to an skill, study, or work devote oneself to a special area of work. STS2012-gold surprise.OnWN 3.250 elevated wooden porch of a house a porch that resembles the deck on a ship. STS2012-gold surprise.OnWN 4.000 either half of an archery bow either of the two halves of a bow from handle to tip. STS2012-gold surprise.OnWN 3.333 a removable device that is an accessory to larger object a supplementary part or accessory. STS2012-gold surprise.OnWN 4.750 restrict or confine place limits on (extent or access). STS2012-gold surprise.OnWN 0.500 orient, be positioned be opposite. alvas@ubi:~/git/stasis$ python Python 2.7.10 (default, Jun 30 2015, 15:30:23) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> with open('sts.csv') as fin: ... for line in fin: ... print len(line.split('\t')) ... break ... 5 >>> with open('sts.csv') as fin: ... for line in fin: ... assert len(line.split('\t')) == 5 ... >>> Even more sanity check that it's the no. of columns, @papayawarrior example of the 4 columns line was correctly parsed in my version of graphlab: I have manually checked the problematic lines and they're: STS2012-gold MSRpar 3.800 "She was crying and scared,' said Isa Yasin, the owner of the store. "She was crying and she was really scared," said Yasin. STS2012-gold MSRpar 2.200 "And about eight to 10 seconds down, I hit. "I was in the water for about eight seconds. STS2012-gold MSRpar 2.800 "It's a major victory for Maine, and it's a major victory for other states. The Maine program could be a model for other states. STS2012-gold MSRpar 4.000 "Right from the beginning, we didn't want to see anyone take a cut in pay. But Mr. Crosby told The Associated Press: "Right from the beginning, we didn't want to see anyone take a cut in pay. STS2012-train MSRpar 3.750 "We put a lot of effort and energy into improving our patching process, probably later than we should have and now we're just gaining incredible speed. "We've put a lot of effort and energy into improving our patching progress, probably later than we should have. STS2012-train MSRpar 4.000 "Tomorrow at the Mission Inn, I have the opportunity to congratulate the governor-elect of the great state of California. "I have the opportunity to congratulate the governor-elect of the great state of California, and I'm looking forward to it." STS2012-train MSRpar 3.600 "Unlike many early-stage Internet firms, Google is believed to be profitable. The privately held Google is believed to be profitable. STS2012-train MSRpar 4.000 "It was a final test before delivering the missile to the armed forces. State radio said it was the last test before the missile was delivered to the armed forces. STS2012-train MSRpar 4.750 "The economy, nonetheless, has yet to exhibit sustainable growth. But the economy hasn't shown signs of sustainable growth. STS2014-gold deft-forum 0.8 "Then the captain was gone. Then the captain came back. STS2014-gold deft-forum 1.8 "Oh, you're such a good person! You're such a bad person!" STS2015-gold answers-forums "Normal, healthy (physically, nutritionally and mentally) individuals have little reason to worry about accidentally consuming too much water. It's fine to skip arm specific exercises if you are already happy with how they are progressing without direct exercises. STS2015-gold answers-forums 1.40 "The grass family is one of the most widely distributed and abundant groups of plants on Earth. As noted on the Wiki page, grass seed was imported to the new world to improve pasturage for livestock. STS2015-gold answers-forums "God is exactly this Substance underlying who supports, exist independently of, and persist through time changes in material nature. I'd argue that matter and energy are substances in the category of empirical scientific knowledge. STS2015-gold belief "watching the first fight i saw that manny pacquiao was getting tired, and i wasn't. at the same time, an asian summit is being held in a tourist resort. STS2015-gold belief "global warming doesn't mean every year will be warmer than the last. doesn't matter, that will just be obama's fault as well. STS2015-gold belief "the only reason i'm not as confident that there's something about the birth certificate... the conventional view is that the us and ussr fought it out in the body of vietnam. STS2015-gold belief "im not playing these bullshit games... if not get the hell out of there. STS2015-gold belief "that oil is already contaminating our shoreline. what point are you trying to relay? STS2015-gold belief "we cannot write history with laws. "she's not sitting here" he said. STS2015-gold belief the protest is going well so far. our request is the same. STS2015-gold belief "for over 20 years, i have illustrated the absurd with absurdity, three hours a day, five days a week. for the first 1-2 years he hated me going out with my friends. Instead of finding these lines manually by repeatedly cleaning out these lines from the PROGRESS: ... verbose message, is there a way to just dump these lines out when loading it into a Graphlab SFrame? A: UPDATED ANSWER Apologies to @alvas, I didn't see that a full dataset was linked in the original post. There are indeed five columns in all of the rows, and the problem does seem to be mismatched quotes. The SFrame CSV parser gets confused if there aren't matching quotes within a column, so the short answer is to change the quote character to something you know doesn't appear in the dataset. import graphlab sts = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', column_type_hints=[str, str, float, str, str], quote_char='\0') This successfully reads all 19,097 rows for me. As an aside, there is also an SFrame.read_csv_with_errors method that will read the "good" lines into an SFrame, and collect the "bad" lines in an un-parsed SArray. That would let you keep track of the problematic lines in a programmatic way. ORIGINAL ANSWER Your data rows don't appear to contain any quotes, so this is not the problem. The problem is that you have 5 columns in some rows of data (and the header), but only 4 columns in other rows of data. The first row has four columns: STS2012-gold surprise.OnWN 5.000 render one language in another language restate (words) from one language into another language. while the second row has five: STS2012-gold surprise.OnWN 3.250 nations unified by shared interests, history or institutions a group of nations having common interests. To work around this I would call the SFrame csv parser twice, once for the four-column data, and once for the five-column data. Because the first fow has four columns, that one is a little more straightforward: import graphlab sts4 = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', header=True) For the five-column data we have to skip the header and the first row, then rename the columns: sts5 = graphlab.SFrame.read_csv('sts.csv', delimiter='\t', header=False, skiprows=2) sts5 = sts5.rename({'X1': 'Dataset', 'X2': 'Domain', 'X3': 'Score', 'X4': 'Sent1', 'X5': 'Sent2'}) Then sts4 looks like +--------------+---------------+-------+-------------------------------+ | Dataset | Domain | Score | Sent1 | +--------------+---------------+-------+-------------------------------+ | STS2012-gold | surprise.OnWN | 5.0 | render one language in ano... | | STS2012-gold | surprise.OnWN | 4.0 | devote or adapt exclusivel... | +--------------+---------------+-------+-------------------------------+ And sts5 is +--------------+---------------+-------+-------------------------------+ | Dataset | Domain | Score | Sent1 | +--------------+---------------+-------+-------------------------------+ | STS2012-gold | surprise.OnWN | 3.25 | nations unified by shared ... | | STS2012-gold | surprise.OnWN | 3.25 | convert into absorbable su... | | STS2012-gold | surprise.OnWN | 3.25 | elevated wooden porch of a... | +--------------+---------------+-------+-------------------------------+ +-------------------------------+ | Sent2 | +-------------------------------+ | a group of nations having ... | | soften or disintegrate by ... | | a porch that resembles the... | +-------------------------------+
[ "opendata.stackexchange", "0000000554.txt" ]
Q: English news dataset for sentiment analysis I am looking for an English news dataset with (relevant) entities mentioned in the article labelled with the sentiment/connotation expressed on the entity by the article. e.g. A sense of the change in political winds in Karnataka is also evident with how Bangalore has voted. The state capital, which hugely favoured the <NEGATIVE>BJP</NEGATIVE> last time with hopes of development, chose to ignore it. Of course, I am not looking for the data in the exact same format as above. A: Could you explain more about what you need the data for? I'm not aware of any pre-built data sets, but you could attempt to construct your own. You'll need to break the problem into two parts though. The easiest route to identifying the entities is the OpenCalais API, which despite its name is a closed-source service, but has generous usage limits. You can also look at the American National Corpus, which contains a large number of automatically-tagged entities in an open data set. You'll then separately need to figure out the sentiment associated with each entity, which is still an AI-complete problem to do totally accurately, especially in an example like yours where it would require understanding the meaning of the sentence. Most sentiment analysis techniques look at the frequency of particular words or small sequences of words, you can find a good overview of the algorithms here, along with some datasets matching words with their sentiment.
[ "stackoverflow", "0046204254.txt" ]
Q: Customize app icon as build phase in Xcode 9/iOS 11 My app is setup to add a banner to the app icon based on the configuration being build. It was done following these steps. https://www.raywenderlich.com/105641/change-app-icon-build-time As of Xcode 9/iOS 11, this doesn't seem to work anymore. The images are still correctly being modified and they exist in the app bundle, but they are not being used as the app icon on the device. Is there any way to do this again? A: Here's the solution I ended up going with. Remove the app icons from Assets.xcassets Create new xcassets for each configuration that needs a custom icon. I named them AppIcon-{CONFIGUATION}.xcassets Create a default AppIcon.xcassets file for release builds. In the targets build settings, add the following to Excluded Source File Names $(SRCROOT)/$(PRODUCT_NAME)/AppIcon*.xcassets Also in the targets build settings, add the following to Included Source File Names, customizing for each configuration as needed. $(SRCROOT)/$(PRODUCT_NAME)/AppIcon-Debug.xcassets This will cause the built application to only include the app icon assets for configuration being built. This can also be extended to other assets.
[ "stackoverflow", "0027164202.txt" ]
Q: how to add cocoapods to an exsisting project? I have a project written in Objective-C with libraries. Is it possible to migrate this project to CocoaPods? If yes, please explain how to do this? A: Just add CocoaPods to the project usual way. Add your existing libraries to the project using Podfile as well. Then once you update pods , all the libraries will be available in your project under the Pods. Now you can safely delete previous libraries from your project if you had copied them into your project.
[ "stats.stackexchange", "0000109507.txt" ]
Q: Feature Selection using (low) MCC I have approximately 1200 input parameters that I am trying to whittle down with the following rough process: 1) Fit rbf SVM with n = 1200 parameters and calculate Matthews Correlation Coefficient(cross validation with 10 partitions) 2) Fit linear SVM, find the lowest weight (absolute value) parameter 3) Fit rbf SVM with n-1 parameters, compare the average MCC and delete the parameter IF my MCC is the same or better Unfortunately, I didn't have high predictive power in the first place. With all 1200 parameters, the MCC of the rbf SVM was around 0.018. And deleting just one parameter significantly lowered the MCC, sometimes to 0.0. I'd like some help interpreting these two things: 1) Why should there be a significant difference in predictive power when I use 1200 parameters versus 1200-1 parameters? 2) What does an MCC of around 0.018 mean? Is it all noise? So there is no true predictive power? And as a last question: Is comparing the MCC not the best approach? Perhaps I can use ROC, but I don't know why one would be preferred over the other. What else would you suggest and why? Any other comments about my procedure would be appreciated! A: Based on my own experience, albeit with a smaller number of inputs than you are using, here are some comments & suggestions that I hope might be helpful to you: A) Matthews correlation coefficient is generally a good, unbiased metric. I had a very similar problem with zero values of MCC sometimes occurring incorrectly. If you are using python, as i am, then your problem may be the same as mine was, as follows. In calculating MCC, the denominator term involves taking the square root of (TP+FP)(TP+FN)(TN+FP)*(TN+FN), all parts of which are >= 0. In the code, there should be a "> 0" test before evaluating the square root. With TP, FP, TN, FN all being integers, the true value for the denominator of MCC may be a very large number and, although python itself can handle integers of any size, numpy cannot and gives overflow errors in int32. As a result, the denominator calculation for MCC is sometimes an overflow and an apparent negative result, which will then give a zero value for MCC. There are several different solutions to this but effectively they all correspond to forcing TP, FP, TN, FN to "float" in the MCC calculation. For me, this worked fine and removed the erroneous "zero MCC" problem. B) Using ROC is fine and, from the ROC chart of TPR vs FPR, the difference TPR-FPR is in fact equal to Informedness, a measure of the distance-from-random, which you are obviously seeking to maximize. If you display unit-slope iso-quality lines on your ROC chart, you may find this to be a useful visual display tool to help you. C) The other good unbiased metric to complement Informedness is Markedness, which is in fact an unbiased version of Precision and is defined as Markednes = TP/(TP+FP) - FN/(TN+FN). D) The MCC, which you are already using, is just the geometric mean of Informedness & Markedness, so basically you can either use MCC as a single metric, or both Informedness & Markedness together. Whichever you choose, these 3 metrics are generally better than other alternatives such as F1 score because they give a measure of the quality of your ML itself, without the problem of results being biased by changes in input data. E) Although using MCC as a single metric may be convenient, you can probably gain more insight into what is happening if you look at your ROC chart and values of Informedness & Markedness. Best wishes.
[ "stackoverflow", "0049032485.txt" ]
Q: PHP upload to AWS S3 produces wrong destination path I want to upload an image file to my S3 storage using PHP. I use this helper library: https://github.com/psugand/CodeIgniter-S3 This is my PHP code: $this->s3->putObject($this->s3->inputFile($tmp), 'dreamboks-assets-2017', '/test_example/' . basename($_FILES["userfile"]['tmp_name']), S3::ACL_PUBLIC_READ); The problem is S3 always creating an empty directory first before my desire directory (test_example/). Screenshot: How to avoid the unwanted empty directory? Is there any problem with my destination path parameter? A: You need to use a relative path. The API wrapper you're using is probably being thrown off by the leading /. So use it like this: $this->s3->putObject( $this->s3->inputFile($tmp), 'dreamboks-assets-2017', 'test_example/' . basename($_FILES["userfile"]['tmp_name']), // relative path S3::ACL_PUBLIC_READ ); Changed the formatting a bit to emphasize the change
[ "stackoverflow", "0045826905.txt" ]
Q: What is the point of adding an exclamation mark before git add? I'm looking at the dotfile for git aliases here. Why is there an exclamation mark before the git add? And looking at other aliases, quite a few use !, in the formal of $alias_name$ = "!...". Are the two uses different? I looked up some bash uses of ! and it seems to be used to get previous commands, but this use seems to be different. Any ideas? Thanks! A: ! is not before git add, it's before the entire command line. It means "run the command with a shell". Git aliases are usually simple substitutions: [alias] ca = commit -a means that the command git ca will be interpreted by git as git commit -a. For more complex tricks in aliases people use shell commands and functions, and ! calls shell. For the alias you pointed to it means that git ca will execute git add -A && git commit -av in a shell.
[ "stackoverflow", "0026819992.txt" ]
Q: Why is my list comprehension causing the code to return my entire text document rather than only matches of words from permutations of a word? My code: from itertools import permutations original = str(input('What word would you like to unscramble?: ')) inputFile = open('dic.txt', 'r') compare = inputFile.read().split('\n') inputFile.close() for now in permutations(original): car = [print(now) for now in compare if now in compare] #supposed to compare iterations of input word to text file. I am trying to unscramble a word by finding all permutations of a word and running each permutation through a text file of English words to see if it is a real word or not. My previous version stored all the permutations in a list (now I know that's a bad idea). This code here just prints my entire text file, and I'm not entirely sure why. I would like to know what I'm doing wrong with the list comprehension that prints the entire text file of words rather than only iterating through the permutations of the input word. A: You can make you code more python-idiomatic in multiple ways: from itertools import permutations original = str(input('What word would you like to unscramble?: ')) with open('dic.txt') as input_file: compare = input_file.readlines() for permutation in permutations(original): if permuation in compare: print(permutation) Does this do what you are looking for?
[ "stackoverflow", "0035441474.txt" ]
Q: Warning: A long-running operation is being executed on the main thread. try! get data(). Swift I know that the error comes from try! converyPFFile.getData() Wondering how to get rid of the error if I don't want to get data in background because if I get data in background, the image cannot be appended to the array. Thanks. query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in for object in objects! { self.senderArray.append(object.objectForKey("sender") as! String) self.messageArray.append(object.objectForKey("message") as? String) if object.objectForKey("photo") != nil { if let converyPFFile = object.objectForKey("photo") as? PFFile{ let temp = try! converyPFFile.getData() let image = UIImage(data: temp) self.photoArray.append(image) } } else { self.photoArray.append(nil) } } // create a chat interface if self.senderArray[i] == self.userName { if self.messageArray[i] != nil { // using scroll view // create username label // create message text label } else { // using scroll view // create username label // create message image messageImage.image = self.photoArray[i] } .... A: I found this warning is coming from Parse. You can overcome it by using getDataInBackgroundWithBlock and then append to your array within that block. Therefore your code becomes something like (untested and I think I have mis-paired braces): query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in for object in objects! { self.senderArray.append(object.objectForKey("sender") as! String) self.messageArray.append(object.objectForKey("message") as? String) if object.objectForKey("photo") != nil { if let converyPFFile = object.objectForKey("photo") as? PFFile{ converyPFFile.getDataInBackgroundWithBlock { (data: NSData!, error: NSError!) -> Void in let image = UIImage(data: data) self.photoArray.append(image) } } else { self.photoArray.append(nil) } } // create a chat interface if self.senderArray[i] == self.userName { if self.messageArray[i] != nil { // create username label // create message text label } else { // create username label // create message image messageImage.image = self.photoArray[i] } ....
[ "math.stackexchange", "0001611431.txt" ]
Q: Order of operation for the Cross Product in linear algebra I realize that the order of operation for the Cross Product actually matters. I understand that AxB = -BxA. (when A and B are vectors) But I'm confused in finding the correct order. If you take a look at the picture I linked below, the exercise decided to label PQ vector U, and PR vector V. After that, they used the Cross Product with the following order: UxV. So, is there a reason for assigning PQ vector U, and PR vector V? Why not the other way? Why can't PQ be V, and PR be U? A: In this case, a choice of sign does not matter, since the area of the triangle is given in terms of the norm of the cross product of two vectors. Remember that the norm of a vector is equal to the norm of the negative of that vector. Note the solution in the image is missing a bit: It should be $$\frac 1 2 \|u \times v \|$$ at the first step, not just $\frac 1 2 u \times v$. A similar caveat applies to the right hand side of the first equality. (Notice the type error: the first line is about vectors, the second line is about numbers).
[ "stackoverflow", "0041480785.txt" ]
Q: MySQL multiple IN conditions to subquery with same table I have multiple IN conditions with subqueries. SELECT S.name, S.email FROM something S WHERE 1 NOT IN (SELECT id FROM tags WHERE somethingId = S.id) AND 2 NOT IN (SELECT id FROM tags WHERE somethingId = S.id) AND 3 NOT IN (SELECT id FROM tags WHERE somethingId = S.id) Maybe there are better solutions? Something like: (1, 2, 3) NOT IN (SELECT id FROM tags WHERE somethingId = S.id) A: Re-write to use NOT EXISTS instead. I.e return from S when there is no row in tags with somethingId equals to s.id and id is 1, 2 or 3. SELECT S.name, S.email FROM something S WHERE NOT EXISTS (SELECT 1 FROM tags WHERE id in (1, 2, 3) and somethingId = S.id) Also NOT EXISTS is "null-safe". (NOT IN (select returning a null) will return no rows at all.)
[ "stackoverflow", "0049345881.txt" ]
Q: What is difference between "var deckSize = 20" and "deckSize := 20" in GoLang, if written outside the main function body? I am new to Go, and learning the basics of the language. This is where I am stuck. I understand from the basic course that var x int = 10 and x := 10 are supposed to be equivalent, the latter being a shorthand notation. It all made sense till these two were inside the main() function. That means: package main import "fmt" func main() { var x int = 20 fmt.Println(x) } , func main() { var x := 20 fmt.Println(x) } and func main() { x := 20 fmt.Println(x) } All these run fine. But when I move this variable outside the main function, the behavior is different and I couldn't find an explanation in the tutorials I could find. That means, package main import "fmt" var x int = 20 func main() { fmt.Println(x) } and var x = 20 func main() { fmt.Println(x) } run as expected, but, x := 20 func main() { fmt.Println(x) } Gives an error : syntax error: non-declaration statement outside function body Why did this statement become a "non-declaration" one, and how is it different from same syntax being used inside the main() function? A: The designers of Go chose not to allow this shorthand outside of functions. The Go folks hint at their reasons here Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available. The designers preferred every single statement at the top level to start with a keyword. Perhaps for aesthetics. Perhaps for ease of parsing. Perhaps because the top level things are the things you can export if you capitalize. This construct is called both a short assignment statement (in the Go Tour) but officially, in the grammar it is indeed called a short variable declaration! Given that it officially is a declaration, the error message, as you are alluding to, is IMHO wrong! They could do better. They should say "short declaration found outside function." UPDATE This question looks like a dupe: Why isn't short variable declaration allowed at package level in Go? However, if the question is not "why is it not allowed?" but rather "why does the error message say it is a non-declaration?" then it's a good, distinct question.
[ "stackoverflow", "0040000691.txt" ]
Q: Loop over array I need a piece of powershell-code to search and replace a certain string inside a text-file. In my example, I want to replace 23-06-2016' with '24-06-2016'. The script below does this job: $original_file = 'file.old' $destination_file = 'file.new' (Get-Content $original_file) | Foreach-Object { $_ -replace '23-06-2016', '24-06-2016' ` } | Out-File -encoding default $destination_file As the search / replace string change I want to loop over an array of dates which might look like this: $dates = @("23-06-2016","24-06-2016","27-06-2016") I tried use the $original_file = 'file.old' $destination_file = 'file.new' foreach ($date in $dates) { (Get-Content $original_file) | Foreach-Object { $_ -replace 'date', 'date++' ` } | Out-File -encoding default $destination_file } In a first step, the date '23-06-2016' should be replaced by '24-06-2016' and in a second step, the date '24-06-2016' should be replaced by '27-06-2016'. As my script is not working I am seeking for some advice. A: You are using $date as your instance variable in your foreach loop but then referencing it as 'date', which is just a string. Even if you used '$date' it would not work because single-quoted strings do not expand variables. Further, $date is not a number, so date++ would not do anything even it were referenced as a variable $date++. Further still, $var++ returns the original value before incrementing, so you would be referencing the same date (as opposed to the prefix version ++$var). In a foreach loop, it's not very practical to refer to other elements, in most cases. Instead, you could use a for loop: for ($i = 0; $i -lt $dates.Count ; $i++) { $find = $dates[$i] $rep = $dates[$i+1] } This isn't necessarily the most clear way to do it. You might be better off with a [hashtable] that uses the date to find as a key, and the replacement date as the value. Sure, you'd be duplicating some dates as value and key, but I think I'd rather have the clarity: $dates = @{ "23-06-2016" = "24-06-2016" "24-06-2016" = "27-06-2016" } foreach ($pair in $dates.GetEnumerator()) { (Get-Content $original_file) | Foreach-Object { $_ -replace $pair.Key, $pair.Value } | Out-File -encoding default $destination_file }
[ "stackoverflow", "0054015269.txt" ]
Q: IOS Chart / MPAndroidChart. Axis Height I need to give the x-axis labels more space. Is this possible? If you see the green box, the axis' labels are cut off. I have tried this but with no effect: xAxis.labelHeight = CGFloat(40) I just added the colors to show the areas. Thanks. A: You can try this solutions for give more space to labels in charts yourGraphView.setViewPortOffsets(left: 35, top: 15, right: 20, bottom: 30) It will set offset of view in charts. Hope this will help you.
[ "android.stackexchange", "0000196289.txt" ]
Q: Is my Android device booting into a "stealth" partition? OK, this is a weird problem I’m encountering with an Android system I’ve been using without problems for several years now… and I’m practically out of ideas on how to potentially fix it. Let’s start at the beginning to describe the problem and what I’ve been trying for the past 12 hours. I woke up to my device this morning seeing that a recently installed app (via Google Play store) had crashed, and obviously a truckload of other apps and services also showed a hickup too. I decided to simply uninstall it and reboot my phone (clearing the Dalvik cache while I was at it to avoid any hickups). The system booted as usual, but I noticed the app I just uninstalled is still there. Tried again, same result. Knowing I have a 5-day old TWRP backup, I decided to restore that to get back to my old system state. Done, wiped Dalvik cache and rebooted. No success, the old system (with the app that shouldn’t be there) boots up. So, that TWRP backup wasn’t a solution. Crying a silent tear, I decided to whipe all partitions via TWRP and simply reflash the ROM from scratch. Rebooted… and to my surprise the old system showed up (incl. wallpaper, settings, and that one weird app et al.) Not wanting to give up, I even tried to install another ROM. TWRP confirms this succeeds. But rebooting again ignores every system change and boots that darn old OS (incl. settings and apps – which shouldn’t exist due to a factory reset.) Getting a bit upset by all this I said to myself – OK, I’ll wipe all partitions and reboot. Having no OS the device should not boot at all, confirming I got rid of whatever messed up my device. Booted into TWRP, whiped ALL partitions listed (including the external SD). I confirmed this worked by using the TWRP file manager to check on the contents of every partition available. They are all empty. I was convinced this was going to work and my device would hickup due to a missing OS. So, I rebooted… and whoops, the device again boots into the system (with that app, the old wallpaper, etc.) Logic says this can’t be – since all partitions are empty. Long story short: I meanwhile tried about every trick in my bag to get rid of the old OS, but no matter what I do – I can’t. Whiping, flashing, etc. doesn’t seem to change the fact the phone happily boots into an OS that – according to the TWRP file manager – doesn’t exist. Now, I’m out of ideas on how to fix it. It’s almost as if I’m fighting some "hidden/stealth" partition which gets booted into. As said: this even happens when I whipe all partitions (System + Cache + Data + Internal Storage + Micro SD card) followed by a Format Data) and then reboot. Meanwhile, I’m starting to suspect the last app I installed via the Google Play store might have been malware. But that shouldn’t result in a bootable OS after a complete device whipe. Can it nevertheless be that my Android device boots into a "stealth" partition? If, how can I get rid of it when I can’t see it via TWRP? Is there any way to hard-format and repartition the internal SDs and recreate the partitions besides TWRP’s functionality? (In case there’s some problem with one of the partitions, which TWRP doesn’t actually whipe.) Or (which would really make my day) has anyone ever experienced something alike and has a solution which might help me fix this by getting rid of the old OS which the device seems to detect who-knows-where and happily boots up? EDIT Since a comment asked for some version details et al: Device is a Samsung GT-P3100, aka espresso3g TWRP 3.2.1-0 Rom that is (let’s just call it) “non-killable” is SlimKat. To be more specific Slim-4.4.4.build.9.0-OFFICIAL-8293 Looking at things again and again it seems TWRP fails to correctly whipe one or more partitions (System, Data), even though there is not a single error message or warning when doing so. I also tried erasing all partitions as well as the internal storage and flash lineage-13.0-20180211-nightly-espresso3g-signed, which results in an error 7 (rebooting the same darn “non-killable” SlimKat). Same goes for trying to erase all partitions as well as the internal storage and flash Slim_espresso3g-6.0.1-20180414-1959, which results in an error 7 (rebooting the same darn “non-killable” SlimKat). Also, it might be helpful to know I have another espresso3g device available, which doesn’t show any similar problems. On that other device, I can flash, whipe, backup, recover, and consequently successfully boot into the related ROM as expected. Therefore, I’m suspecting there’s something wrong with one or more partitions, which also prevents TWRP from correctly formatting in contrast to its claims. Even using the TWRP terminal and being crazy enough to try rm -rf /data/* and rm -rf /system/* seemed to work at first glimpse. Yet, the partition contents simply shows up on reboot as if nothing happened. Another indicator it might be some partition hickup is that – any change to any setting or even starting any app in the booting “non-killable” SlimKat results in the whole OS collapsing piece by piece until the device reboots into recovery. A: Seems I’ve found the answer at https://andi34.github.io/faq.html Quote: I can't change my rom, wipe / format doesn't work. Nothing changed after flashing with Odin. 16 GB Tab 2 have a known faulty EMMC (MAG2GA). It can happen, that your EMMC get “read only”, so you can’t perform any write actions (also you can’t format) anymore. From the EMMC data sheet: 5.1.7 End of Life Management: The end of device life time is defined when there is no more available reserved block for bad block management in the device. When the device reaches to end of its life time, device shall change its state to permanent write protection state. In this case, write operation is not allowed any more but read operation are still allowed. But, reliability of the operation can not be guaranteed after end of life. On a faulty EMMC firmware it happens a lot faster. What are the symptoms? Uninstalled apps and deleted files are back after a reboot Formating the storage doesn’t work (after reboot the old rom and apps are back) You can flash whatever you like via Odin it showes “passed” but after reboot nothing changed (e.g. still no StockRom or still the old Recovery you had previously installed) … there might be some more, but only to mention some … In most cases, the issue can be fixed by a EMMC firmware update, but you need someone who’s able to do it (possible via ISP, nothing you can do esylie at home yourself). In some bad cases you need to find someone who can replace your EMMC. Well, that’s that then. Obviously I will have to buy myself a new device first thing in the morning, after crying a river all the way to the bank while blaming Samsung for its End of Life Management.
[ "stackoverflow", "0041096159.txt" ]
Q: Webpack/babel/es6 forward slashes being removed from image src So I have the following code: import Menu from './menu'; import Kitten from './kitten'; const content = () => Kitten + Menu.menu var app = document.getElementById('app'); app.innerHTML = content(); console.log(content()); Now this logs the following to the console: <img src"/dist/197a114e185cbd7e1bfdb9ca2074492f.jpeg"/><button id="menu">Menu</button> However the following is being rendered: <div id="app"><img src"="" dist="" 197a114e185cbd7e1bfdb9ca2074492f.jpeg"=""><button id="menu">Menu</button></div> This is what kitten looks like: const kitten = require('./images/kitten.jpeg'); const Image = `<img src"${kitten}"/>`; export default Image; Any ideas what this could be? A: You've missed the equal sign in the img: <img src"/dist/197a114e185cbd7e1bfdb9ca2074492f.jpeg"/> \/ <img src="/dist/197a114e185cbd7e1bfdb9ca2074492f.jpeg"/>
[ "stackoverflow", "0011787883.txt" ]
Q: pandas - More efficient way to calculate two Series with circular dependencies I have a DataFrame that represents stock returns. To split adjust the closing price, I have the following method: def returns(ticker, start=None, end=None): p = historical_prices(ticker, start, end, data='d', convert=True) d = historical_prices(ticker, start, end, data='v', convert=True) p['Dividends'] = d['Dividends'] p['Dividends'].fillna(value=0, inplace=True) p['DivFactor'] = 1. p['SAClose'] = p['Close'] records, fields = p.shape for t in range(1, records): p['SAClose'][t] = p['Adj Close'][t] / p['DivFactor'][t-1] + \ p['Dividends'][t-1] p['DivFactor'][t] = p['DivFactor'][t-1] * \ (1 - p['Dividends'][t-1] / p['SAClose'][t]) p['Lagged SAClose'] = p['SAClose'].shift(periods=-1) p['Cash Return'] = p['Dividends'] / p['Lagged SAClose'] p['Price Return'] = p['SAClose'] / p['Lagged SAClose'] - 1 return p.sort_index() Note how SAClose (i.e. Split Adjusted Close) depends upon lagged DivFactor values. In turn, DivFactor depends on both lagged DivFactor values as well as the current SAClose value. The method above works, but it is incredibly slow in the loop section. Is there a more efficient way for me to do this in pandas? Given the "circular" dependency (not really circular given the lags), I'm not sure how I could do either regular series math or use normal shift operations (e.g as I do with Cash Return). A: You can try creating a cumulative adjustment factor series in one shot then you don't need to loop: (p['Dividends'].fillna(1.) + 1.).cumprod()
[ "stackoverflow", "0050925126.txt" ]
Q: Vue.js - Firebase Auth cannot check correctly error message on Reset Password I am sending a password reset email to a user; when the number of request exceed a certain level, Firebase raise an error RESET_PASSWORD_EXCEED_LIMIT I am trying to capture this message to alert the user ( account unavailable for a period of time ... cannot find how long..) but I cannot correctly grab the message .. auth.sendPasswordResetEmail(this.email) .catch((error) => { console.log('ERROR: ', ... console.log('ERROR: ', error.message) ERROR: {"error":{"code":400,"message":"RESET_PASSWORD_EXCEED_LIMIT","errors":[{"message":"RESET_PASSWORD_EXCEED_LIMIT","domain":"global","reason":"invalid"}]}} console.log('ERROR: ', error.message.error.message) ERROR: undefined console.log('ERROR: ', error.message['"error"']) ERROR: undefined console.log('ERROR: ', error.message['"error"']) ERROR: undefined It is a very strange error object format A: I believe the error message is stringified. You should use JSON.parse.
[ "stackoverflow", "0033582237.txt" ]
Q: Difference between next( ) and next( ).CharAt(0); I have created an abstract class Employee which displays and calculates the Details of Weekly and Hourly Employee.In the main method i have used switch case for a menu and do while to continue using the program as long as the user want.But I'm getting an Error when compiling the code.: *javac "AbstractDemo.java" (in directory: /home/user/Desktop) AbstractDemo.java:52: error: incompatible types ch=s.next(); ^ required: char found: String 1 error Compilation failed.* This is the Source Code: import java.util.*; abstract class Employee{ Employee(float amt,int n){ float sal; System.out.println("The amount paid to Employee is:"+amt); sal=amt*n; System.out.println("Total Salary is:"+sal); } } class WeeklyEmployee extends Employee{ WeeklyEmployee(float a,int n){ super(a,n); } } class HourlyEmployee extends Employee{ HourlyEmployee(float amt,int hrs){ super(amt,hrs); } } public class AbstractDemo { public static void main (String args[]) { int a; char ch; float amount; int hours; int weeks; Scanner s=new Scanner(System.in); do{ System.out.println("Enter the choice"); a=s.nextInt(); switch (a) { case 1 : System.out.println("Enter the salary of weekly employee(Per Week):"); amount=s.nextFloat(); System.out.println("Enter the total no of week"); weeks=s.nextInt(); Employee W=new WeeklyEmployee(amount,weeks);break; case 2: System.out.println("Enter the salary of hourly employee(Per hour):"); amount=s.nextFloat(); System.out.println("Enter the total no of hours"); hours=s.nextInt(); Employee H=new HourlyEmployee(amount,hours);break; default:System.out.println("Error invalid Choice"); } System.out.println("Do you wish to continue?(Y/N)"); ch=s.next(); }while (ch== 'y'||ch== 'Y'); } } But When i use s.next().ChatAt(0); the code compiles successfully.Could somebody explain why this is happening?Is Char taking input as String?Or if it is a string why its showing an Error when i edit the while condition to while(ch=="y"||ch=="Y"); ? A: ch is a char. s.next() returns a String. You can't assign a String to a char. You can assign the first character of the String to a char, which is what you do in ch = s.next().charAt(0);. It's a good thing you are not trying while(ch=="y"||ch=="Y"), since that would fail even if you changed ch to be a String (which would allow it to pass compilation, but wouldn't give the expected result), since you can't compare Strings in Java with == (you should use equals instead).
[ "stackoverflow", "0019600173.txt" ]
Q: error accessing array of structure pointers I am trying to build an adjacency list but get the following error graph.c:16: error: subscripted value is neither array nor pointer I read that this error occurs when a non array is trying to be indexed. When I am able to add an element to it directly (line 58: graph[i] = root), can I please know what is the error in assigning a member of the structure array to a NODE? #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 10 struct node{ int data; struct node * link; }; typedef struct node * NODE; NODE graph[MAX]; void displayGraph (graph, n){ int i; NODE cur; for (i=0;i<n;i++){ cur = graph[i]; while(cur != NULL){ printf("%d ", cur->data); } } } NODE insert (NODE root, NODE temp){ NODE mine; mine = root; if (mine == NULL) return root; while(mine != NULL){ mine = mine->link; } mine->link = temp; return root; } main () { int n=0; int i; int val; char * choice; NODE temp, root; printf("Enter the number of nodes\n"); scanf("&d", n); for (i=0;i<n;i++){ root = NULL; while(1){ printf("Is there an adjacent node?Y:N"); scanf("%s", choice); if(!strcmp(choice, "N")); break; printf("Enter the adjacent node\n"); scanf("%d", val); temp = malloc(sizeof (struct node)); temp->data = val; temp->link = NULL; root = insert(root, temp); } graph[i] = root; } displayGraph (graph, n); } A: You haven't specified a type for the variable graph when you declared the displayGraph function. void displayGraph (graph, n); Seeing as graph is declared globally, you can technically omit graph as an argument to this function. You will also need to provide a type for the variable n, but if you insist on having displayGraph accept the graph array, then change: void displayGraph (graph, n){ to void displayGraph (NODE graph[], int n){ There are a few other problems with your code, but this should fix the error you are asking about.
[ "stackoverflow", "0040436430.txt" ]
Q: JList of TextFields and JScrollPane doesn't show / Java Swing I am trying to create a window that shows a dynamic list of textFields and if the number of textfields is large then I want to add a scroller. I am using GridLayout. The problem is that the panel I added the Jlist and scroller doesn't show anything, neither the list nor the scroller. Below you will find a part of my code. //Label JLabel numberOfTxt = new JLabel("Please enter the number in every TextField"); int n = 11; //A random number of TextFields firstPanel.add(numberOfTxt, BorderLayout.NORTH); //Add label to panel JList textFieldList = new JList(); //Create a list of TextFields for (int i = 0; i < n; i++) { //Add TextFields to list JTextField textField = new JTextField(); textField.setBounds(0, 0, 6, 0); textFieldList.add(textField); System.out.println("textFieldList" + textFieldList); } textFieldList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); textFieldList.setLayoutOrientation(JList.HORIZONTAL_WRAP); textFieldList.setVisibleRowCount(8); //Create scroller JScrollPane listScroller = new JScrollPane(textFieldList); listScroller.setBounds(0, 20, 600, 600); //Create layout for panel where the textfields will be added if (n % 2 != 0) { n = n + 1; } thirdPanel.setLayout(new GridLayout(n / 2, 2, 10, 6)); thirdPanel.add(textFieldList); thirdPanel.setVisible(true); //ContentPane has BoxLayout contentPane.add(firstPanel); contentPane.add(thirdPanel); contentPane.repaint(); window.pack(); } window.revalidate(); } }); A: JList does not works this way. If you really need a JList of TextFields you should use ListCellRenderer (probably you don't, see p.3). You adding textFieldList both to listScroller and thirdPanel. Probably, you should replace thirdPanel.add(textFieldList); by thirdPanel.add(listScroller);. thirdPanel uses GridLayout, but only one control is ever added to it. You should either add TextField directly to thirdPanel (easier way), or let the JList manage them.
[ "stackoverflow", "0019378576.txt" ]
Q: Regex for texts NOT enclosed in angled bracket - python I need to get the texts that are not enclosed in angled brackets. my input looks like this: > whatever something<X="Y" zzz="abc">this is a foo bar <this is a > < whatever>and i ><only want this and the desired output is: > whatever something this is a foo bar <this is a > and i ><only want this I've tried first detecting the things inside the brackets then remove them. But seems like i'm matching the attributes inside the <> instead of the whole <...>. How do i achieve the desired output? import re x = """whatever something<X="Y" zzz="abc">this is a foo bar <this is a\n< whatever>and i ><only want this""" re.findall("<([^>]*)>", x.strip()) ['X="Y" zzz="abc"', 'this is a\n ', ' whatever'] A: You should move the parenthesis just inside the quotes (and remove the parenthesis you already have) in the regex pattern to grab all of the text between <...> including the brackets themselves. You also need to exclude the \n characters to achieve the output you want. import re x = """whatever something<X="Y" zzz="abc">this is a foo bar <this is a\n\ < whatever>and i ><only want this""" y = re.findall("(<[^>\n]*>)",x.strip()) z = x[:] for i in y: z = z.replace(i,'\n') print(z) whatever something this is a foo bar <this is a and i ><only want this The parentheses indicate which text you want to group when the findall finds a match.
[ "stackoverflow", "0010305967.txt" ]
Q: selenium web driver - passing variable value from one test case to another I have a variable stateID with value 11 in test case CreateStateID. How do I pass this value to test case DeleteStateID in selenium wedriver? This works fine in selenium IDE but not in webdriver. In selenium IDE CreateStateID storeEval | /\d*$/.exec(storedVars['myLocation']) | stateID I had to write java code for above statement in my selenium2 program. In selenium IDE DeleteStateID echo | ${stateID} the selenium2 code for this is System.out.println("${sid}"); which prints out null. Is the best way to write java method where I pass stateID from one test case to another? Thanks A: As stated in the comments: check this question - it could help. Another approach would be have the variable as static variable inside the tests, with getters and setters: private static String neededVariable; public String getVariable(){ return neededVariable; } public void setVariable(String var){ this.neededVariable = var; } And later in the code: String stateID = //the way how you get it from the storeEval setVariable(stateID); And in another test: String stateID = getVariable(); //... and work with the stateID as you need Works ok in mine tests
[ "stackoverflow", "0010953066.txt" ]
Q: ui:composition template=" I would like to place the Facelets template file for JSF in a JAR file. I tried to reference it by EL as <ui:composition template="#{resource['templates:template_pe_layout.xhtml']}"> which works perfect for CSS or images, but not for the composition template. How could I achieve the goal? A: The #{resource} expression is initially designed for use inside CSS files only like so .someclass { background-image: url(#{resource['somelibrary:img/some.png']}); } It's not intented for usage in <h:outputStylesheet>, <h:outputScript> or <h:graphicImage> which should rather be used as follows: <h:outputStylesheet library="somelibrary" name="css/some.css" /> <h:outputScript library="somelibrary" name="js/some.js" /> <h:graphicImage library="somelibrary" name="img/some.png" /> As to the templates, just specify the full /META-INF/resources relative path in there. <ui:composition template="/templates/template_pe_layout.xhtml"> See also: Packaging Facelets files (templates, includes, composites) in a JAR Changing JSF prefix to suffix mapping forces me to reapply the mapping on CSS background images
[ "stackoverflow", "0043431525.txt" ]
Q: Filter distinct on both columns in MySQL I have the following table +-------------------+----------------------+ | original_language | translation_language | +-------------------+----------------------+ | en | pl | | en | ru | | pl | en | | pl | ru | | ru | pl | +-------------------+----------------------+ Right now there are some duplicates like en - pl and pl - en but I want to remove them. So result should look like +----+----+ | en | pl | | en | ru | | pl | ru | +----+----+ I used group by to filter the results, but I assume I should use something else or just filter the result array on server side. A: This might work for you: SELECT DISTINCT least(original_language,translation_language) as Col1, greatest(original_language,translation_language) as Col2 FROM MyTable
[ "stackoverflow", "0057918055.txt" ]
Q: Commit transaction without begin transaction I accidentally ran into a situation that I didn't put Begin Transaction at the beginning of my stored procedure and just wrote Commit Transaction as you can see below ALTER PROCEDURE dbo.spTest AS BEGIN DECLARE @MyId INT=1 BEGIN TRY UPDATE Test SET -- Id -- this column value is auto-generated CharName = 'david' WHERE id=4 --Just to test locking behavior WHILE(1=1) BEGIN SET @MyId=2; END COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION END CATCH END I expected SQL Server to give me a run time error but it didn't happen. Of course I should mention that based on my test it didn't acquire any lock on the table due to the lack of Begin Transaction but what is the point of COMMIT TRANSACTION and ROLLBACK TRANSACTION in such a condition and why didn't SQL Server raise any error? Edit: if i remove while block and put WaitFor Sql raise error when reaches to COMMIT TRANSACTION ALTER PROCEDURE dbo.spTest AS BEGIN UPDATE Test SET CharName = 'david' WHERE id=4 PRINT 'waiting for a minute ' WAITFOR DELAY '00:00:10'; COMMIT TRANSACTION END Now i am receiving this error The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION A: what is the point of COMMIT TRANSACTION and ROLLBACK TRANSACTION in such a condition? There is no point in this case and why didn't SQL Server raise any error? I don't see any code that would raise an error. It would help if you could explain where and why you think an error should be raised With regards to whatever you're actually doing here; If the purpose of this proc is to hold a transaction open, you'd need something more like this: ALTER PROCEDURE dbo.spTest AS BEGIN BEGIN TRANSACTION UPDATE Test SET CharName = 'david' WHERE id=4 --Endless loop WHILE(1=1) BEGIN PRINT 'waiting for a minute inside a transaction. Try something from another session' WAITFOR DELAY '00:01'; END -- Transaction will actually never be committed -- Because this line will never be reached -- because it's preceded by an endless loop COMMIT TRANSACTION END The TRY / CATCH is a bit of a distraction. I've removed it.
[ "stackoverflow", "0045004926.txt" ]
Q: React-Router: Not working for me i am newbies in React-Router, create one project using React-Router first time. But not working properly for me, i think i have missed out something. Requirement: 1) Default it should load logininput.js 2) for path='/Login' load logininput.js 3) for path='/Register' load registerinput.js Source Code: Login.js import React, { Component } from 'react' import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' import LoginInputs from "./loginInputs" import RegisterInputs from "./registerInputs" require('./Login.css') class Login extends Component { constructor(props, context) { super(props, context) } render() { return ( <Router> <div> <div className="container" > <div className="row"> <div className="col-md-6 col-md-offset-3"> <div className={'panel panel-login'}> <div className={'panel-heading'}> <div className="row"> <div className="col-xs-6"> <Link className={'active'} to="/Login">Login</Link> </div> <div className="col-xs-6"> <Link to="/Register">Register</Link> </div> </div> <hr/> </div> <div className={'panel-body'}> <div className="row"> <div className="col-lg-12"> <Switch> <Route path="/Login" components={LoginInputs}/> <Route path="/Register" components={RegisterInputs}/> <Route exact path="/" components={LoginInputs}/> </Switch> </div> </div> </div> </div> </div> </div> </div> </div> </Router> ) } } export default Login loginInputs.js import React, { Component } from 'react' class LoginInputs extends Component { constructor(props, context) { super(props, context) debugger; } render(){ debugger; return( <form id="login-form" method="post" role="form" style={{"display": "block"}}> <div className="form-group"> <input type="text" name="username" id="username" tabindex="1" className="form-control" placeholder="Username" value="" /> </div> <div className="form-group"> <input type="password" name="password" id="password" tabindex="2" className="form-control" placeholder="Password" /> </div> <div className="form-group"> <div className="row"> <div className="col-sm-6 col-sm-offset-3"> <input type="submit" name="login-submit" id="login-submit" tabindex="4" className="form-control btn btn-login" value="Log In" /> </div> </div> </div> </form> ) } } export default LoginInputs registerinputs.js import React, { Component } from 'react' class RegisterInputs extends Component { constructor(props, context) { super(props, context) } render(){ return( <form id="register-form" action="http://phpoll.com/register/process" method="post" role="form" style={{"display": "none"}}> <div className="form-group"> <input type="text" name="username" id="username" tabindex="1" className="form-control" placeholder="Username" value="" /> </div> <div className="form-group"> <input type="text" name="userid" id="userid" tabindex="2" className="form-control" placeholder="userid" value="" /> </div> <div className="form-group"> <input type="email" name="email" id="email" tabindex="1" className="form-control" placeholder="Email Address" value="" /> </div> <div className="form-group"> <input type="password" name="password" id="password" tabindex="2" className="form-control" placeholder="Password" /> </div> <div className="form-group"> <input type="password" name="confirm-password" id="confirm-password" tabindex="2" className="form-control" placeholder="Confirm Password" /> </div> <div className="form-group"> <input type="text" name="age" id="age" tabindex="2" className="form-control" placeholder="age" /> </div> <div className="form-group"> <input type="text" name="contactno" id="contactno" tabindex="2" className="form-control" placeholder="contactno" /> </div> <div className="form-group"> <div className="row"> <div className="col-sm-6 col-sm-offset-3"> <input type="submit" name="register-submit" id="register-submit" tabindex="4" className="form-control btn btn-register" value="Register Now" /> </div> </div> </div> </form> ) } } export default RegisterInputs Full source github link : https://github.com/piyushdhamecha/samplerouterui A: after long research here the code works. Replaced components={LoginInputs} with render={(props) => (<LoginInputs/>)} in Route. import React, { Component } from 'react' import { BrowserRouter as Router, Route, NavLink, Switch } from 'react-router-dom' import LoginInputs from "./loginInputs" import RegisterInputs from "./registerInputs" require('./Login.css') class Login extends Component { constructor(props, context) { super(props, context) } render() { return ( <Router> <div> <div className="container" > <div className="row"> <div className="col-md-6 col-md-offset-3"> <div className={'panel panel-login'}> <div className={'panel-heading'}> <div className="row"> <div className="col-xs-6"> <NavLink exact activeClassName="active" to="/LoginPage/">Login</NavLink> </div> <div className="col-xs-6"> <NavLink activeClassName="active" to="/LoginPage/Register">Register</NavLink> </div> </div> <hr/> </div> <div className={'panel-body'}> <div className="row"> <div className="col-lg-12"> <Switch> <Route exact path="/LoginPage/" render={(props) => (<LoginInputs/>)}/> <Route path="/LoginPage/Register" render={(props) => (<RegisterInputs/>)}/> </Switch> </div> </div> </div> </div> </div> </div> </div> </div> </Router> ) } } export default Login Thanks for contribution.
[ "stackoverflow", "0015904333.txt" ]
Q: How to read specific column and cell in mysql in c#? I use ExecuteReader to select all (SELECT*) for all field like this string query = "SELECT* FROM tb_patient_information "; if (this.OpenConnection() == true) { //Create Command MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { ... } but I only want to select in specific column and cell like in red square.. like this picture A: You can get the specific column inside the while clause. while (dataReader.Read()) { var _column = dataReader["Nama_Kategori"]; }
[ "stackoverflow", "0051370379.txt" ]
Q: Why does my forge bucket not show any objects? I have followed this tutorial and have uploaded my file successfully to: https://developer.api.autodesk.com/oss/v2/buckets/timmyisabucket/objects/audobon_arch.rvt It has uploaded successfully and I can verify this by calling https://developer.api.autodesk.com/modelderivative/v2/designdata/dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6dGltbXlpc2FidWNrZXQvYXVkb2Jvbl9hcmNoLnJ2dA==/metadata/c63a6682-a73c-a2a8-a08c-dfeee25781f4/properties which successfully returns all the object properties. However, when I ask the api to list all the objects inside the bucket, it simply returns an empty list! The endpoint I'm calling: https://developer.api.autodesk.com/oss/v2/buckets/timmyisabucket/objects The response: { "items": [] } Where am I going wrong? Thanks A: Just to close this off, the helpful comment by Xiaodong Liang led me to the the fact that my bucket type was created with the incorrect type of "Transient" meaning that all my stuff gets deleted after 24 hours. It should have been Temporary or Persistent. Retention policy Transient Think of this type of storage as a cache. Use it for ephemeral results. For example, you might use this for objects that are part of producing other persistent artifacts, but otherwise are not required to be available later. Objects older than 24 hours are removed automatically. Each upload of an object is considered unique, so, for example, if the same rendering is uploaded multiple times, each of them will have its own retention period of 24 hours. Temporary This type of storage is suitable for artifacts produced for user-uploaded content where after some period of activity, the user may rarely access the artifacts. When an object has reached 30 days of age, it is deleted. Persistent Persistent storage is intended for user data. When a file is uploaded, the owner should expect this item to be available for as long as the owner account is active, or until he or she deletes the item.
[ "stackoverflow", "0003252666.txt" ]
Q: provisioning profile problem after upgrading to snow leopard? i just upgraded my macbook OS to Snow Leopard but all the provisining profiles were deleted..Do i need to create new provisioning profiles for all applications or just copy my bACKUP OF provisioning profiles folder to the Library(havent installed xcode 3.2 iphone sdk4 yet)?? A: Install xcode 3.2 and then install all profiles.
[ "stackoverflow", "0047009237.txt" ]
Q: What is the difference between git fetch and git fetch origin What is the difference between these two commands? git fetch and git fetch origin A: This is simpler than the linked answer (which is really about what name(s) are updated with git fetch origin vs git fetch origin master vs git fetch origin master:master; and that answer is slightly different for very old versions of Git as its behavior changed a bit in Git version 1.8.4). To quote the git fetch documentation: When no remote is specified, by default the origin remote will be used, unless there’s an upstream branch configured for the current branch. In other words: git fetch is exactly the same as: git fetch origin unless the current branch has an upstream setting that refers to a remote other than origin. So if, for instance, the current branch is rumpelsnakeskin and the upstream of rumpelsnakeskin is habitat/rumpelsnakeskin, then git fetch means git fetch habitat. But if the current branch is, say, master and its upstream is origin/master or is not set at all, then git fetch means git fetch origin.
[ "stats.stackexchange", "0000063669.txt" ]
Q: How can you implement a two-way ANOVA with nesting in R or SPSS? I currently am conducting a study where I have three variables: one that is binary, and two numerical ratio variables. Each of the subjects in my study has values for each of the three variables. Variables: Condition (binary): Values 0 and 1 Pre (ratio) Post (ratio) I want to test if there is a significant difference between the the pre and post variables of the 0 control group and the 1 experimental group. Both groups have 103 subjects. The data meet all typical ANOVA assumptions such as normality and the like. I was thinking of nesting the variables as follows and then running a two-way ANOVA. Variable 1 is exposed / not and variable 2 is pre / post. People are nested in Variable 1 (meaning that each person gives both pre and post information for either exposed or not exposed conditions) Would this be the correct way to approach this problem? Also how would I implement this statistical analysis, preferably in R or SPSS? A: Pre-post designs are quite common and the standard method is to use the pre-measure as a control variable and the post-measure as the response with the binary variable as the covariate. This is quite simple: m0 <- lm(Post ~ Pre, data=dat) m1 <- lm(Post ~ Pre+Condition, data=dat) anova(m1,m0) # test for difference in mean(Post) after control for Pre m2 <- lm(Post ~ Pre*Condition, data=dat) anova(m2, m1) # test for interaction: different slopes in the two Conditions If this had been with repeated measures within subject (i.e, pre-post measures in each Condition, you would need to specify the error structure in the aov function: You could compare this model in R where the errors for each Condition are nested in subject-ID: m1 <- aov(post ~ pre + Condition+Error(subjID/Condition), data=dat) Ratio variables are notorious for being poorly behaved statistically (i.e., often having significant skew and blowing up as the denominator goes near zero.) However, if the denominator is far from zero, you should not make the mistake of looking at the raw distributions and deciding that the data fail the assumptions needed for validity of linear methods. You need to look at the residuals before conducting any test. (And even then, there is some doubt whether minor departures from normality invalidate inferences.) The help page for aov warns you to use orthogonal contrasts. There was an article in R-News several years ago on multi-variate (as opposed to multi-variable) methods and this would provide further options for model comparisons and measures of sphericity. Another option is offered by the Anova function in John Fox's car package. A useful link: http://blog.gribblelab.org/2009/03/09/repeated-measures-anova-using-r/ Another approach is to analyze the pairwise differences, but that approach has flaws.
[ "pt.stackoverflow", "0000462941.txt" ]
Q: nao consigo usar :checked css: .menu { display: block; } /* CSS quando o checkbox está marcado */ #bt-menu:checked~.menu { display: none; } <div class="menuu"> <input type="checkbox" id="bt_menu"> <label for="bt_menu"></label> <span></span> </div> <div> <nav class="menu"> <ul> <li><a href="#">home</a></li> <li><a href="#">Serviços</a> <ul> <li><a href="#">criação de sites</a></li> <li><a href="#">arte visual</a></li> </ul> </li> <li><a href="#">cursos</a> <ul> <li><a href="#">java</a></li> <li><a href="#">photoshop</a></li> <li><a href="#">criação de sites</a></li> </ul> </li> <li><a href="#">contatos</a></li> </ul> </nav> </div> no caso eu clico para sumir e nada acontece, continua como se fosse display:block A: Motivos de não estar funcionando: seu input tem o ID "bt_menu" mas no CSS está "bt-menu"; para usar o sibling combinator ("~"), o input deve estar num nível que tenha acesso aos elementos que você queira controlar. E, no caso, ele está travado dentro da div "menuu", então o selector não funciona para nada fora dela; também é necessário incluir o * no selector: #bt_menu:checked ~ * .menu Segue abaixo exemplo funcional com algumas modificações: Movi o checkbox para o nível mais alto, dessa forma ela tem acesso a todos os outros elementos; Criei uma classe "escondivel". Tudo que usar ela será escondido. Achei que fazia mais sentido. .menu { display: block; } #escondido:checked ~ * .escondivel { display: none; } <input type="checkbox" id="escondido"> <div class="menuu"> <label for="escondido" id="btn-esconder">esconder</label> </div> <div> <nav class="menu escondivel"> <ul> <li><a href="#">home</a></li> <li><a href="#">Serviços</a> <ul> <li><a href="#">criação de sites</a></li> <li><a href="#">arte visual</a></li> </ul> </li> <li><a href="#">cursos</a> <ul> <li><a href="#">java</a></li> <li><a href="#">photoshop</a></li> <li><a href="#">criação de sites</a></li> </ul> </li> <li><a href="#">contatos</a></li> </ul> </nav> </div>
[ "stackoverflow", "0058546520.txt" ]
Q: In app maker, how can I clear a column sort? When app maker creates a table it can make the columns sortable, which is great, but after a user clicks on a column, how can you clear that sort setting to get the table back to either the default settings from when the page first loaded or a specific sort order as in the script below? I am presently using a Refresh button which merely reloads the datasource, but the column sorting remains. Suggestions? I have tried reloading or navigating back to the page itself, but that had no effect either. this is the augmented Refresh onClick script that includes the sort order: widget.datasource.query.sorting.App._ascending(); widget.datasource.query.sorting.Role._ascending(); widget.datasource.query.sorting.Name._ascending(); widget.datasource.load(); A: Morfinismo gave me the code fragment I was missing, but here's the breakdown: This will reset any filters and clear out filter fields like dropdowns or suggest boxes: widget.datasource.query.clearFilters(); This will clear any sorting, so if you want sorting, you will need to add it like so: widget.datasource.query.clearSorting(); widget.datasource.query.sorting.App._ascending(); widget.datasource.query.sorting.Role._ascending(); widget.datasource.query.sorting.Name._ascending(); which will clear the sorting and reset it to your liking, but will not remove the little arrow graphic on the column heading. For that you will need to navigate back to the page you are already on to refresh it like this: app.showPage(app.pages.AppRoles); Here is the complete Refresh button onClick script: app.showPage(app.pages.AppRoles); widget.datasource.query.clearFilters(); widget.datasource.query.clearSorting(); widget.datasource.query.sorting.App._ascending(); widget.datasource.query.sorting.Role._ascending(); widget.datasource.query.sorting.Name._ascending(); widget.datasource.load(); This worked for me, but I'm sure there are other approaches and tricks of the trade. Feel free to post them here for future answer seekers.
[ "stackoverflow", "0018901310.txt" ]
Q: TinyIoC, Xamarin.iOS, linker settings I'm trying to get TinyIoC working on Xamarin.iOS, but I'm not having a lot of luck. My project linker settings are set to "Link SDK assemblies only". I'm literally doing something this simple: public interface IPerson { int age { get; } } public class Person : IPerson { public int age { get { return 99; } } } Then my registration code looks like this (I've just placed it in my AppDelegate in a toy app): TinyIoCContainer.Current.Register<IPerson,Person>.AsMultiInstance(); When I attempt to grab an IPerson, I get a runtime exception saying that IPerson cannot be resolved (this code is found immediately after the registration code in the AppDelegate of the toy app): IPerson person = TinyIoCContainer.Current.Resolve<IPerson>(); Here's the error: Unable to resolve type: TinyTest.IPerson If, however, I change the linker settings to "Don't link", everything works fine. This is obviously untenable, though, because the binary becomes enormous. I've tried placing [Preserve] attributes on the IPerson interface and the Person class, but no dice. I also tried just manually declaring a variable of type IPerson and instantiating it with a new Person() and then grabbing the age property, just to make sure the type was included in the build, but no luck there either. Feel like I'm missing something here - can someone point me in the right direction? Thank you! A: This is a bug because reflection is used to call an internal Expression<TDelegate> constructor. The linker cannot analyze reflection usage (it's beyond static analysis) so it must be aware of those special cases. This is obviously untenable, though, because the binary becomes enormous. Keep using the default Link SDK option but add the --linkskip=System.Core to your Additional mtouch arguments, inside your Project Options, iOS Build. That way only System.Core (from the SDK) will not be linked and the increase in size will be much smaller. Of course this is only a workaround until a new version fix the issue properly.
[ "stackoverflow", "0050795241.txt" ]
Q: Sort list of tuples by element two of all tuples I want to show the list from the large age to the small age.   Here is my list:   player = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)]   I can sort list using name element by player.sort and get this list:   [('Andrey',12),('Dima',11),('Dmitry',15),('Nikita',13),('Sergey',14)]   But I want this list, where ages are large age to small age:   [('Dmitry',15),('Sergey',14),('Nikita',13),('Andrey',12),('Dima',11)]   How I can do this? A: You can achieve your desired sort by using the itemgetter() function as the key parameter and also setting reversed to true so the list is in decending order: >>> from operator import itemgetter >>> players = [("Dmitry", 15), ("Dima", 11), ("Sergey", 14), ("Andrey", 12), ("Nikita", 13)] >>> players.sort(key=itemgetter(1), reverse=True) >>> print(players) [('Dmitry', 15), ('Sergey', 14), ('Nikita', 13), ('Andrey', 12), ('Dima', 11)]
[ "stackoverflow", "0015307367.txt" ]
Q: Why is the value of this variable changing to garbage once inside for-loop? C Why is the value of n changing to garbage inside the for-loop? (I'm new to C language, I come from a C++ background) float n = 3.0; printf ("%f\n", n); for (; n <= 99.0; n += 2) printf ("%f\n", &n); A: You are printing the address of n (&n) inside the for-loop. Get rid of the &
[ "stackoverflow", "0012669057.txt" ]
Q: How to Convert DateTime to boolean in ASP.NET GridView? I have a column with DateTime datatype. i want to display value of this column as Yes/No in GridView in ASP.NET. if DateTime field "Is Null" then Display "No" and If Datetime field column "Is Not Null" then display "No" in grid view how to do it.Whether to do it in SQL Query or in GridView binding. I have tried in GridView but it fails.I know the following code is wrong & in SQLQuery i have checked it for ISNULL. <ItemTemplate> <asp:Label ID="lblOndate" runat="server" Text='<%# Convert.ToBoolean(Eval("OnDate")) ? "Yes" : "No" %>' ReadOnly="true"> </asp:Label> </ItemTemplate> Help Appreciated! Thanks in Advance. A: You can do it in the GridView without any checking in SQL. Just amend your code in the GridView to check for DBNull.Value instead of attempting to convert to a boolean. i.e. <asp:Label ID="lblOndate" runat="server" Text='<%# Eval("OnDate") == DBNull.Value ? "No" : "Yes" %>' ReadOnly="true"></asp:Label>
[ "stackoverflow", "0026935754.txt" ]
Q: Outlook VBA - Msg.SaveAs "Path" issue Hi all, I have written a code that saves a mailitem in a folder. It was working perfectly well, except for an issue: a few times, Outlook did not respond and I had to close it by Ending Task. At first, I thought it was because of the file size. Then, I found out that this issue was due to the length of the MailItem. When the message is too long, Outlook starts not responding and I have to close it. Can someone help me? Code is: Private Sub CommandButton3_Click() Unload Me Dim Path As String Dim Mes As String Dim Hoje As String Dim Usuario As String Dim Diretorio As String Dim olApp As Object Dim olNs As Object 'Path do servidor Path = "\\Brsplndowd009\DMS_BPSC_LAA\Customer_Service\Unapproved\Samples\Sample Orders - 2014" 'Mes Mes = Mid(Date, 4, 2) 'Data Hoje = Left(Date, 2) & UCase(Left(MonthName(Mes), 3)) & Right(Date, 2) 'Usuário Usuario = "LEVY" '1. Nome da Pasta Diretorio = Path & "\" & Source & "\" & Tracking & " - " & Customer & " - " & Material & " - " & Hoje & " - " & Usuario 'Dim Msg As Outlook.MailItem' Dim Msg As Object Dim Att As Outlook.Attachment Dim olConc As Outlook.Folder Dim olConc2 As Outlook.Folder Dim olItms As Outlook.Items 'Get Outlook Set olApp = GetObject(, "Outlook.application") Set olNs = olApp.GetNamespace("MAPI") Set olItms = GetFolder("Caixa de correio - FLHSMPL\Inbox\00-Levy").Items Set olConc2 = GetFolder("Caixa de correio - FLHSMPL\Inbox\00-Levy") Set olConc = GetFolder("Caixa de correio - FLHSMPL\Inbox\00-Levy\Encerrar") 'Loop For Each Msg In olItms If InStr(1, Msg.Subject, Tracking) > 0 Then MkDir Diretorio If InStr(1, Msg.Subject, Tracking) > 0 Then Msg.Move olConc If InStr(1, Msg.Subject, Tracking) > 0 Then Msg.SaveAs Diretorio & "\" & "Caso" & " " & Tracking & ".msg" If InStr(1, Msg.Subject, Tracking) > 0 Then Success.Show If InStr(1, Msg.Subject, Tracking) > 0 Then Exit Sub Next Msg Fail.Show End Sub A: Firstly I ma not sure why you have 5 If statements with the same condition. Wjy not roll them into one? Secondly, You are calling Move, then try to us the original message. You cannot do that - the old item is gone. You need to use the new one retruned by Move: If InStr(1, Msg.Subject, Tracking) > 0 Then MkDir Diretorio set Msg = Msg.Move(olConc) Msg.SaveAs Diretorio & "\" & "Caso" & " " & Tracking & ".msg" Success.Show Exit Sub End If
[ "math.stackexchange", "0000166792.txt" ]
Q: Need a formula for a quadratic spline I'm trying to reproduce some results from a paper and I need an explicit formula for a specific quadratic spline to do so. The problem is, I've only got a plot of it. The quadratic spline is from figure 2 (a) of Stephane Mallats paper "Singularity Detection and Processing with Wavelets" in IEEE Transactions on Information Theory, Vol. 38, No. 2. March 1992. Link to journal. Link to PDF. The spline has a positive lobe lobe from $[-1,0]$ and a negative lobe from $[0,1].$ It appears to go to zero from $[-2,-1]$ and from $[1,2].$ It also acheives a peak values of about $0.66$ or $-0.66$ in either lobe as measured in imageJ. This spline is bound to be a wavelet so it's necessarily $0$ on the average and is compactly supported from $[-2,2]$ (possibly a smaller interval if it goes to zero where I think it does.) A: From appendix A of the Mallat paper linked to in the comment by J.M., the smoothing spline figure is the Fourier transform of the following function: $\hat{\psi}(\omega) = i \omega (\mathrm{sinc}(\omega/4) )^4$ where $\mathrm{sinc}(\omega) = \frac{\sin(\omega)}{\omega}$ and $\omega = 2 \pi f$ The FT of a sinc function is simply a rectangle of width 1 $\mathcal{F}^{-1}\{sinc(\omega)\} = Rect(\omega)$ Multiplication becomes convolution: $\mathcal{F}^{-1}\{sinc(\omega)^4\} = Rect(t) \star Rect(t) \star Rect(t) \star Rect(t)$ Working out these four convolutions gives a curve defined piecewise from $t \epsilon [-2,2]$: $\mathcal{F}^{-1}\{sinc(\omega)^4\} =$ $t^3/6 + t^2 + 2t + 4/3,\text{ } -2 \le t \le -1$ $-t^3/2 - t^2 + 2/3,\text{ } -1 <t \le 0$ $t^3/2 - t^2 + 2/3,\text{ } 0<t \le 1$ $-t^3/6 + t^2 - 2t + 4/3,\text{ } 1 <t \le 2$ The FT of a scaled sinc is a scaled Rect having width 1/4 and height 4: $\mathcal{F}^{-1}\{sinc(\omega/4)\} = 4 Rect(4t)$ The extra factor of $i\omega$ is equivalent to a derivative in the time domain according to: $\frac{d}{dt}(f(t) ) = i \omega \mathcal{F}^{-1}\{\hat{f}(\omega)\}$ Scaling the convolved sincs gives a curve defined piecewise from $t \epsilon [-1/2,1/2]$, which we then take a derivative of to get the final result: $\mathcal{F}^{-1}\{i \omega sinc(\omega)^4\} =$ $4*((4t)^2/2 + 2*(4t) + 2), \text{ } -1/2 \le t \le -1/4$ $4*(-3/2*(4t)^2 - 2(4t) ) ,\text{ } -1/4 <t \le 0$ $4*(3/2*(4t)^2 - 2*(4t)) ,\text{ } 0<t \le 1/4$ $4*(-(4t)^2/2 + 2*(4t) - 2),\text{ } 1/4 <t \le 1/2$ The plot looks like this: The problem with this spline is that it is half the width of the plot shown in figure 2 of Mallat's paper. I believe the difference between the two is just a scaling factor though.
[ "apple.stackexchange", "0000347407.txt" ]
Q: How an I confirm my Bluetooth 3.0 Keyboard is encrypted? I have a MacBook pro Retina 15, Late 2013 running Mojave. I also have an off brand Bluetooth 3.0 Keyboard ( GeneralKeys PX-4068-675 ). The keyboard connects fine to the MacBook WITHOUT asking for a pin ... but I'm not clear if the connection is using/requiring encryption. Is here a way to verify it is encrypted? A: I suspect you should assume your keyboard is not secure. Much depends on who is likely to be attacking you – prankster or nation state: While Bluetooth has its benefits, it is susceptible to denial of service attacks, eavesdropping, man-in-the-middle attacks, message modification, and resource misappropriation. These two questions on related StackExchanges give a good overview: Is Bluetooth 4.0 traffic encrypted by default/design? How secure is a bluetooth keyboard against password sniffing? Hopefully you can secure the environment in which the keyboard can broadcast. WireShark The WireShark tool maybe able to intercept the Bluetooth traffic. See Bluetooth Smart Wireshark Plugin for a guide. Also see Bluetooth Smart Security for more technical details.
[ "stackoverflow", "0031843088.txt" ]
Q: isinstance doesn't work when use reflection of python protobuf v2.6.1 I am using dynamic reflection functionality of python protobuf v2.6.1, and have a function like below: # initilization code des_db_ = descriptor_database.DescriptorDatabase() des_pool_ = descriptor_pool.DescriptorPool(des_db_) fdp = descriptor_pb2.FileDescriptorProto.FromString( a_pb_module.DESCRIPTOR.serialized_pb) des_db_.Add(fdp) def unpack_PB_msg(type_name, pb_msg_str) factory = message_factory.MessageFactory(des_pool_) msg_class = factory.GetPrototype(des_pool_.FindMessageTypeByName(type_name)) pb_msg = msg_class() pb_msg.ParseFromString(pb_msg_str) return pb_msg But following client code will fail hello = Hello_msg() hello_str = hello.SerializeToString() hello2 = unpack_PB_msg(Hello_msg.DESCRIPTOR.full_name, hello_str) hello3 = Hello_msg() hello3.CopyFrom(hello2)# failed here!!! The error message is: hello3.CopyFrom(hello2) File "C:\Localdata\Python27\lib\site-packages\google\protobuf\message.py", line 119, in CopyFrom self.MergeFrom(other_msg) File "C:\Localdata\Python27\lib\site-packages\google\protobuf\internal\python_message.py", line 971, in MergeFrom "expected %s got %s." % (cls.__name__, type(msg).__name__)) TypeError: Parameter to MergeFrom() must be instance of same class: expected Hello_msg got Hello_msg. It seems CopyFrom fails because isinstance fails. def MergeFrom(self, msg): if not isinstance(msg, cls): raise TypeError( "Parameter to MergeFrom() must be instance of same class: " "expected %s got %s." % (cls.__name__, type(msg).__name__)) When print data type of hello2 and hello3, it seems they are different. hello2 : <class 'Hello_msg'> hello3 : <class 'a_pb_module.Hello_msg'> Is this a protobuf bug? or I made something wrong? A: This may be able to help someone. I had the same error TypeError: Parameter to MergeFrom() must be instance of same class: expected Hello_msg got Hello_msg. when I imported the same class twice at two different paths, it results in two different classes imported at different paths (Even though they might have the same class name, Python sees them as two completely different class (check the ID of the class, you should find them to be different)). To solve this issue, you need to make sure the same class (Hello_msg) is imported only once.