INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to reference embedded SQL Server Reporting Service 2008 images I have a SQL Server 2008 report with a bit field - **IsUS** I'd like to display embedded images depending on IsUS bit value. **How can I _reference_ embedded images within a column expression?** !alt text Below is the result after applying Fillet's answer \-------------------- **_Result_** \-------------------- !alt text
Drag the "checked" image into the Is US column. Then edit the properties of the image, and set the image expression to: =iif(Fields!IsUS.Value = 1, "checked", "unchecked")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql server 2008, reporting services, embedded resource" }
Can I have multiple FlutterPlugin in one Flutter plugin project? I'm working on a Flutter plugin for internal use. I have various domains in the plugin. So I would like to know if we can have multiple FlutterPlugin classes in a single project and how?
Update that I have found the way. So for iOS in `FlutterPluginRegistrant.m` You can register multiple swift FlutterPlugin, Which will allow you to have multiple method channels and classes that implement FlutterPlugin.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "flutter, flutter plugin" }
Galois Group of $f(x)=x^4 - 10 x^2 + 1$ I am trying to calculate the Galois group of $f(x)=x^4 - 10 x^2 + 1\in\mathbb Q[x]$ over $\mathbb Q$. In my notes it says that the four roots are $\pm\sqrt 2\pm\sqrt 3$. So the splitting field of $f(x)$ is clearly $\mathbb Q(\sqrt 2+\sqrt 3)=\mathbb Q(\sqrt 2,\sqrt 3)$. Now I can send $\sqrt 2\mapsto \pm \sqrt 2$ and $\sqrt 3\mapsto \pm\sqrt 3$, which gives me $4$ possibilites, and it is easy to see that Gal$(f)=$Gal$(\mathbb Q(\sqrt 2,\sqrt 3):\mathbb Q)=C_2\times C_2$. But how can I see that the roots are $\pm\sqrt 3\pm\sqrt 3$ ? If I just start by rearranging the terms of $x^4 - 10 x^2 + 1=0$, then I get $(x^2-5)^2-24=0$ and consequently $x=\pm\sqrt{5\pm2\sqrt 6}$. These roots are not as easy to work with as the first ones. So how do I proceed?
Note that $$(a\pm b)^2=a^2+b^2\pm 2ab.$$ Letting $a=\sqrt{3}$, $b=\sqrt{2}$, we have $$(\sqrt{3}\pm\sqrt{2})^2=5\pm2\sqrt{6}.$$
stackexchange-math
{ "answer_score": 3, "question_score": 4, "tags": "polynomials, galois theory" }
how to double-click on a cell in table with Selenium Ruby Webdriver I'm trying to use below codes to double-click on a cell in a table in my web application (I tried to do Click two times with the hope that they are equal to double-click). However, the cell is not clicked at all, but I expect that after double-clicking on the cell, the text field will be displayed for me to edit info of that cell. @driver.find_element(:xpath => "//table[@id='gridabc']//tr[1]/td[9]").click @driver.find_element(:xpath => "//table[@id='gridabc']//tr[1]/td[9]").click I'm using **Selenium Ruby Webdriver**. Please help guide me a way to resolve this. Thanks much.
#@example Double click an element el = driver.find_element(:id, "some_id") driver.action.double_click(el).perform Code shamelessly copied from the documentation :)
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "ruby, webdriver, selenium webdriver" }
Display and Data Value of percentage Please tell me, in my form, the user should enter percentage value between 1 to 100. For that matter, if the user entered 80% than I want to save it in the database as 0.80 - I want a different value when saving to the database. How can I do it? My app is MVC 3 and EF Code-First based. Thank you
It doesn't exists "as is". What you could try (they are really many other ways to do that, by the way). * Create a Custom Attribute (PercentageAttribute) that you will put on your "percentage" properties * Create a Custom ModelBinder, override the SetProperty, and divide value by 100 when propertyDescriptor has a "PercentageAttribute" But when you'll get value from the database, it will be divided by 100... So if your users can edit these data, you'll have to multiply by 100 before passing it to the "edit" view... I think ViewModels with a little bit of logic, or transient properties in your POCOs, or whatever else would be easier ! Hard to say without understanding WHY you really need this.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net mvc, model view controller, ef code first" }
Internet sharing with iptables: choosing which connection to share I have a computer with two network devices (`eth0` and `wlan0`), both connected to the internet (two different connections/isp). I'm trying to share the connection of `wlan0` to another computer connected via ethernet to `eth0`. What I'm doing is: # sysctl net.ipv4.ip_forward=1 # iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE From the client computer I can then connect to this one, but the internet connection that gets shared is the one on `eth0` and not the one on `wlan0`. If I disable the internet connection on `eth0` (by setting no gateway), then the connection to be shared is the one on `wlan0`. However, I'd like to have both internet connections enabled and specify to iptables which one to share. Is this possible? What am I missing? Do I need some forwarding rule?
Seem like your default gw is on eth0 and client is redirected to it (via a icmp redirect). To fix your setup you need to add a routing rule stating that all packets incoming from `client_ip` should be routed to `wlanO_gw`. Try adding a new routing table: * Edit `/etc/iproute2/rt_tables` and add a line for a new table, for example `252 masq` where `252` is the table id and `masq` is the new table name. * Add a rule to route ip_client packets with table masq ip rule add from ip_client/32 table masq * add a default gw to the masq table ip ro add default via wlan0_gw table masq
stackexchange-unix
{ "answer_score": 2, "question_score": 2, "tags": "networking, iptables, connection sharing" }
What does s/(\W)/\\$1/g do in perl? I went over a piece of code in which a subroutine takes `video filename` as argument, and then printing it's duration time. Here I'm only showing the snippet. sub videoInfo { my $file = shift; $file =~ s/(\W)/\\$1/g; } So far I understood is that it is dealing with `whitespaces` but I'm not able to break the meaning of code, I mean what is `$1` and how it will work?
It puts backslashes in front of non-word characters. Things like `"untitled file"` becomes `"untitled\ file"`. As in most regular expression operations `$1` represents the first thing captured with `(...)` which in this case is the `(\W)` representing a single non-word character. I think this is an unnecessary home-rolled version of `quotemeta`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "regex, perl" }
Can i use a sleep(60); in a script Is there any problem if i use `<?php sleep(60); ?>` in my script for 30 times, so that the script will load and finish its works in 30 minutes, is there chance of any problem? **Note:** if it fails , is there any way to do like this?
The client is likely to stop listening for a response, but it is still possible for the script to complete execution. You would have to configure your PHP installation for long execution times though. If you are using a browser and AJAX requesting data that will be returned after 30 minutes, it is better to poll a static resource. When you want to start the script, send an AJAX request to it. This request will eventually time out. Set up your script so that it saves its output to a static resource when it is done (text file / image / etc; depends on what your script is supposed to return). Poll this resource every five minutes using AJAX, and you will get the response from the server when it is ready.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php" }
Wordpress - Get custom page templates by post type I have this code that displays all the custom page templates in my theme directory... <?php $templates = wp_get_theme()->get_page_templates(); foreach ( $templates as $template_name => $template_filename ) { echo "$template_name ($template_filename)<br />"; } ?> However, I would like to only display the custom templates available to a certain post type. Is there any way to do this?
I figured it out... <?php $templates = wp_get_theme()->get_page_templates($post = null, $post_type = 'page'); foreach ( $templates as $template_name => $template_filename ) { echo "$template_name ($template_filename)<br />"; } ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, wordpress, custom post type" }
A question about the symbol $n$ in the additive group $\mathbb{R}^n$ As we know the symbol $n$ determines the dimension of $\mathbb{R}^n$ in the category of vector spaces. Also, in the category of manifolds, $n$ determines the dimension of $n$-manifold $\mathbb{R}^n$. Now, my question is that: Is there any algebraic property related to the additive group $(\mathbb{R}^n ,+)$ which is determined by $n$?
This answer proves that as additive groups $\mathbb{R}^n \cong \mathbb{R}^m$ for all $n,m$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "group theory, infinite groups" }
How to: Create an Event Handler Feature I was testing the code provided in below MSDN Link: < But I got **compile time** error as "Error1Error occurred in deployment step 'Retract Solution': Cannot start service SPUserCodeV4 on computer 'ComputerName'. $000DeletingEventReceiver"$0 Not sure what's wrong!! any help guys?
Try it from Central Admin first, see: < !enter image description here **OR** Go to run and type services.msc and open it. Please found SharePoint 2010 User Code Host and make sure that it is started. Once the Service starts the issue will resolved.
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 0, "tags": "sharepoint enterprise, event receivers" }
How long does it take to submit/approve a BigCommerce app? I'm thinking about making a BigCommerce app, and am wondering how long it takes to be reviewed and (hopefully) approved before it's live in the app store. Earlier this year, I submitted a Shopify app and it was 3 weeks before they even reviewed it, and after fixing one minor bug, a total of 6 weeks from submission date to being live.
The amount of time from submission to approval does depend on the number of apps in queue as well as the response time from the app partner if there are any issues to correct. A good rule of thumb is 2 weeks from submission to approval, but that time can be reduced if the app meets guidelines and there is good communication from the app partner. As long as the app meets BigCommerce guidelines, it should be a very streamlined process and can be done within a week: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "shopify, bigcommerce" }
Xamarin.Forms Open ContentView with parameters in xaml In my app there is a certain listview that I use over and over in my app, only with different elements in it. Therefore, I put everything inside a contentview and inflated it in my xaml like so: <ContentPage Title="Newbies" BackgroundColor="#fafafa"> <views:CV_AllAdsRes /> </ContentPage> The class looks like this: public partial class CV_AllAdsRes : ContentView { public CV_AllAdsRes(int id) { InitializeComponent(); SetAds(); } } Now, this doenst work, because I am not using a "default constructor". If I remove the "int id" from the constructor, it works no problem. But I need to be able to inflate this content view with different parameters inside the xaml. Am I understanding this concept wrong? How can I inflate my content view and give it parameters via xaml? Thank you
I solved it by using a second constructor next to the default one and giving it arguments from xaml like so: <views:CV_AllAdsRes > <x:Arguments > <x:Int32>5</x:Int32> </x:Arguments> </views:CV_AllAdsRes> this will give ID=5.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "xamarin.forms" }
iPhone Contact Picker behaviour (like in Mail.app) can you give me a hint how to customize such a contact picker from e.g. Mail or Facebook App with the (+) Adding Contacts (or other data) to a UITextField for recipients .. each of the entries can be deleted then with the (x) .. can you give me a hint where to start and what i should customize? thank you
Are you talking about something like this: !TTPickerTextField from Three20 If so, you'll want to check out the TTPicketTextField UI component from the Three20 framework. It does exactly what you're after.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "iphone, objective c, iphone sdk 3.0" }
How to delete a image icon in java? Hello I am trying to delete a imageicon named tree in my java game and am finding trouble with my if statements. How would I remove the image tree if the boolean drawimage equals false? if(r1.intersects(rectX, rectY, 25, 25)){ g.drawString("Cut Down Some Tree's To Get Some Wood To build Your Base", rectX, rectX); drawimage = true; } if(drawimage){ g.drawImage(tree,175, 75, 50, 50,null); //Check if the image has cloision if(r1.intersects(175, 75, 50, 50)){ drawimage = false; } if(!drawimage){ } } repaint(); }
correct your code `if(drawimage = false){ }` to `if(drawimage == false){ }` or if(!drawimage){ }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, image, variables, if statement" }
Unable to use EntityFrameworkCore.DataEncryption I am trying to use EntityFrameworkCore.DataEncryption. I am unable to retrieve records from the database. I am getting the encryption padding error while reading the records as per the example. < PS. @Eastrall I am unable to add comments for my query on Data Encryption in Data Layer with ASP.NET Core Entity Framework so added a new question here.
I have used the AES256Bits as block size and set PaddingMode.PKCS7. Make sure you save the keys and use the same key for subsequent read and write operations. This will stop any errors while parsing the records as well.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, encryption, entity framework core" }
Profiling a flash app in an html page I have a flash application, that uses functionality in its surrounding html page. I want to do some profiling with the Flex Profiler (or some similar tool, if you know a better one). But i cannot get it to work, if my flash app is run from within the html page. It only works, if i run the flash app alone, but that doesn't help me, because i need the full scenario. Any ideas on how to get this to work? Thank you!
i found the solution myself :o) If you do profiling in Flex Builder, essentially flex builder loads a ProfilerAgent.swf as a preload swf. this does not work however, when you start an html page, because then the html page initiates the swf and the ProfilerAgent.swf is not loaded. What you can do though is, you load the ProfilerAgent.swf in your app by yourself. Simply load it with the Loader (loading it in the main application domain) and addChild() it to your main stage. With doing so, profiling works even within an html page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flash, actionscript 3, flexbuilder, profiler" }
I have intalled magento2 into xampp server and i encountered with this error when i tried to run it locally Vendor autoload is not found. Please run **'composer install'** under application root directory. It asked me to install composer and when i attempted to do so, it returned, `C:\xampp\htdocs\develop\develop>composer` install Loading composer repositories with package information Installing dependencies (including require-dev) from lock file Your requirements could not be resolved to an installable set of packages. **Problem 1** \- The requested PHP extension ext-intl * is missing from your system. Install or enable PHP's intl extension. **Problem 2** \- The requested PHP extension ext-xsl * is missing from your system. Install or enable PHP's xsl extension.
You can enable `intl` and `xsl` extension from `php.ini` file from `C:\xampp\php\` by removing the comment from extension lines. like `extension=php_intl.dll` and `extension=php_xsl.dll` remove semicolon before this lines and then restart the Apache server.
stackexchange-magento
{ "answer_score": 2, "question_score": 4, "tags": "magento2, extensions" }
Solving logarithmic equation I'm having trouble solving this equation. I know there is a solution as my graphics calculator can solve it, but I want to see the steps on how to get the answer. The mathematical equation is: $$\log_{10}n = 0.07n$$
Not all equations can be solved algebraically. This equation can not be solved step by step to find the answer, you will have to use limits to get to the answer (which is kind of what your calculater does).
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "algebra precalculus, logarithms" }
Mean function in R (Dealing with factors) So I have this vector: x [1] 76 89 78 50 84 56 29 53 32 68 112 Levels: 0 1 10 100 101 102 103 104 105 106 107 108 109 11 110 12 13 ... eta why this happens? [1] NA Warning message: In mean.default(x) : l'argomento non è numerico o logico: restituisco NA
It looks like `x` is a factor. There is a gotcha when converting factors to numbers. You need to use: mean(as.numeric(as.character(x)), na.rm=TRUE) If you don't convert to character first, you will get the underlying factor codes.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "r" }
Cycle through windows in KDE 4 taskbar by shortcut? Is there a way to cycle through the windows in the KDE 4 taskbar with a shortcut? I want to have a _switch to next window_ function on a mouse button. Therefore `Alt+Tab` is not suitable because it uses a stack for the windows. This means if hitting `Alt+Tab`, releasing the `Alt` key and pressing `Alt+Tab` again will bring up the window I had before pressing the keys the first time. Maybe there is a solution using DBus. But I don't know how to use this.
It's not exposed in DBus. You can switch desktops, but not app windows. File a bug. qdbus org.kde.kwin /KWin This looks promising, but does something else. dbus-send --dest=org.kde.kwin /KWin org.kde.KWin.circulateDesktopApplications
stackexchange-superuser
{ "answer_score": 0, "question_score": 3, "tags": "kde, kde 4" }
Can I create more than 1 fork in GitHub? I forked a project a while back and made some changes. Some of these changes were pulled back into the original project, but some weren't. Other people have forked my fork as they find the changes that weren't pulled into the original useful. I now want to fork the original project again as I have some more changes that I'd like to contribute. I don't want to delete my original fork as it has some useful stuff, but I do want to fork again for my latest changes. Can I do this?
An indirect answer to your question: I've found it very useful, when cloning git projects, to leave the master alone and do all my work on a branch. That way, you can always base changes on the current "official" master.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "git, github" }
Different IDs for the "Usage and Health Data Collection Service Application" managed service I am working on sharepoint on-premises 2013. and i am trying to get the ID of the "Usage and Health Data Collection Service Application", but i got different IDs:- 1) When i run this powershell i get this ID:- PS C:\Users\spfarm.user> Get-SPServiceApplication -Name WSS_UsageApplication DisplayName TypeName Id ----------- -------- -- WSS_UsageApplication Usage and Health ... 80ace510-005c-4786-86fc-bfd3848e2d79 While using this powershell i got this ID:- PS C:\Users\spfarm.user> Get-SPServiceApplicationProxy DisplayName TypeName Id ----------- -------- -- WSS_UsageApplication Usage and Health ... 21c44849-db6e-4be8-9d2e-84755dcc664a so which IDs i should trust? or i have an issue inside our farm? Thanks
The ID which gets from Get-SPServiceApplication command is the ID of the "Usage and Health Data Collection Service Application". The second ID is the ID of Usage and Health Data Collection proxy. This is the proxy that virtualizes the access to the service application.
stackexchange-sharepoint
{ "answer_score": 2, "question_score": 1, "tags": "2013, sharepoint server, powershell, service application" }
Formula/algorithm to offset GPS coordinations I have GPS coordinates provided as degrees latitude, longitude and would like to offset them by a distance and an angle. E.g.: What are the new coordinates if I offset `45.12345`, `7.34567` by 22km along bearing 104 degrees ? Thanks
For most applications one of these two formulas are sufficient: "Lat/lon given radial and distance" The second one is slower, but makes less problems in special situations (see docu on that page). Read the introduction on that page, and make sure that lat/lon are converted to radians before and back to degrees after having the result. Make sure that your system uses atan2(y,x) (which is usually the case) and not atan2(x,y) which is the case in Excell.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "gps, geolocation, coordinates, offset, trigonometry" }
Edit a video to embed a bitmap I would like to edit a video so that i can embed a small bitmap image at any corner. The bitmap image has to be replaced with another image, for every two video frames. If somehow it is possible to covert a group of pictures into slideshow video then i want that video to be embedded at the corner of the main video. The size of the bitmap is about the size of a channel logo and that is exact space it will occupy in the video. Please guide me in accomplishing. Is there any existing libraries available to do this. I am working on .Net 4 platform but i do welcome support from other platforms
You can use Avisynth with the `Overlay()` function
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".net, video editing" }
installing old versions of cv2 using pip i've been trying to download older versions of cv2 as an easy way to get around not being able to use SIFT. I've tried the following: pip install opencv-contrib-python==3.4.2.17 however I get this error: ERROR: Could not find a version that satisfies the requirement opencv-contrib-python==3.4.2.17 (from versions: 3.4.8.29, 3.4.9.31, 3.4.9.33, 4.1.2.30, 4.2.0.32, 4.2.0.34) ERROR: No matching distribution found for opencv-contrib-python==3.4.2.17 All the advice I've seen on the site so far tells me to either download these older versions of opencv or to build it myself (which seems like an absolute nightmare) Anyone have any suggestions on how to install these older versions of cv2?
opencv-contrib-python 3.4.2.17 provides wheels for Pythons up to 3.7. Probably you use Python 3.8. Use Python 3.7 (or lower). Or compile from sources for 3.8.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "opencv, pip, cv2, sift" }
Visual Studio 2015: How to disable "How do I..." feature I am using `Visual Studio Community 2015`. Whenever I use intellisense menu, the `"How do I.."` option always be selected by default on the top and that is quite annoying me. ![enter image description here]( So could I disable that feature?
Ignore it. Just because I have installed the Developer Assisstant Extensions for Visual Studio 2015.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio, visual studio 2015, intellisense" }
Daisychaining 2 DisplayPort 1.2 monitors causes both to turn off I have two Dell U2414H monitors for my desktop. They worked great for years. A while back both monitors did not turn on after restarting from a Windows 10 update. Having an additional laptop, I lived with it for the time. Fast forward to August last year. I built a new computer and attempted to use these monitors. During the build I only used one and it worked. Post-build I plugged in both monitors via the daisy-chain to the second one and instantly they both entered power-saving mode and turned off, refusing to turn back on. Switching monitors did nothing. Using HDMI on one and DP on the other also causes the problem to manifest. Using only one monitor works either with HDMI or DP. What would cause this type of behavior?
I looked into purchasing a new set...Apparently this is a known issue that the monitors/DP ports/daisy-chaining just stop working: * Amazon 1-star reviews * Newegg reviews Long story short. The monitors are not great in long-term quality and their DP ports will die within 2 years.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "display, multiple monitors, displayport, daisychaining" }
Radius of convergence for series of $\frac{1}{x^2+\cos^2x}$ Given $$ f(x) = \frac{1}{x^2+\cos^2(x)} $$ We can use the binomial expansion to rewrite $f(x)$ as $$ f(x) = \sum_{k=0}^\infty {-1\choose{k}}\frac{\cos^{2k}x}{x^{2k+2}} $$ Or, in other terms $$ f(x) = \sum_{k=0}^\infty \frac{(-1)^k \cos^{2k}x}{x^{2k+2}} $$ If I remember correctly the formula for R.O.C is: $$ (x+y)^n \Longrightarrow \, -1<\frac{x}{y} < 1 $$ How would I go about solving this for: $$ -x^2 < \cos^2x < x^2 $$ Thanks.
The term radius of convergence is reserved for power series, such as $\sum_n a_nx^n$. Your series does not fit this format. However, it is a geometric series in $\cos^2 x/x^2$. It will converge if and only if $$ \left\lvert \frac {\cos^2 x}{x^2} \right \rvert < 1.$$ At a minimum this will be the case whenever $|x| > 1$ since (for real values of $x$) $|\cos x| < 1$. But in fact, still concentrating on real $x$, for $0 < x < 1$, the ratio $\cos^2x/x^2$ is decreasing and greater than $1$ for small $x$. Therefore the inequality is true for all larger $x$ once $x > \theta$ where $\theta$ is the solution to $\cos \theta = \theta$, about $0.7$. Because each term is an even function, the sign of $x$ is unimportant and convergence of your sum arises for all $|x|> \theta$, which is the solution to the inequality you have written.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, inequality, binomial theorem" }
Is there any statistcal testing method that test whether a given set of data is continous? I have some data which I hypothesis that is generated by continuous process. I expect that if I can have high resolution the data will change smoothly (with respect to time). The data I have is for certain intervals and I have no way to zoom in. How can I test my hypothesis that the data were actually continuously generated?
You can't. Continuity is a modelling assumption based upon your understanding of the process you're investigating.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "statistics, hypothesis testing" }
MS SQL и тип связи "Категория" Имеется 3 сущности: 1. User - описывает общие атрибуты 2. Категория - физическое лицо 3. Категория - юридическое лицо Как правильно организовать ограничение целостности данных, что бы User мог находится только в одной категории? На ум приходит следующее: 1. Повесить триггеры на категории, что бы при добавлении Юзера в категорию, проверялась противоположная категория на предмет наличия Юзера в 1 из категорий 2. Создать процедуру, в которой в рамках единой транзакции будет создаваться записи в : User+Юридическое лицо или User+Физическое лицо Что наиболее верно и нет ли еще способов?
Можно обойтись без триггеров, т.е. сделать декларативное ограничение целостности - CHECK + UDF. Похожая проблема рассмотрена здесь.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, база данных, sql server" }
How much memory a goal uses? In Swi-Prolog I can enclose a goal in `time/1` to see how much CPU time a goal takes. How do I do use `statistics/2` correctly to see how much RAM a goal takes?
Interestingly, **you can't**. For more information, please see this issue: < If you need this functionality, please participate in this discussion and outline your use case. It may help to implement this feature correctly, or to ensure that an alternative is available that does what you need.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "prolog, swi prolog" }
Converting a string of chars to an array of numbers according to a dictionary in matlab I have a string containing letters. I want to assing a number to each letter, and convert it to an array. Let's say I have 'ABAABCCBA' and I have a dictionary such that `A=1`, `B=2`, `C=3` and thus the array I want is [1,2,1,1,2,3,3,2,1] This is super easy to do in python, but I have to use matlab for some subsequent analysis. Any ideas as to how I can do this without switch case, as succinctly as possible? (Note that this is an MRE and the original string contains 20 different letters)
A general method, which doesn't assume that keys or values are consecutive, is as follows: keys = 'ABC'; values = [1 200 30]; data = 'ABAABCCBA'; [~, result] = ismember(data, keys); result = values(result);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "arrays, string, matlab" }
Solving a separable equation Solve the following separable equations subject to the given boundary conditions a) $\frac{dy}{dx}$ = $x\sqrt{1−y^2}$, $y=0$ at $x=0$, b)$(ω^2+x^2)\frac{dy}{dx} = y$, $y=2$ at $x=0$ ($ω>0$ is a parameter). **Edit:** Sorry I wasn't clear, I am fine with everything up to and including integration, it's just the boundary conditions that I cannot seem to grasp.
**Hint** : For the first one, rearrange as $$\frac{\mathrm dy}{\mathrm dx} = x\sqrt{1 - y^2} \implies \frac{\mathrm dy}{\sqrt{1 - y^2}} = x\,\mathrm dx$$ For the second one, we have: $$\left(\omega^2 + x^2\right)\frac{\mathrm dy}{\mathrm dx} = y \implies \frac{\mathrm dy}y = \frac{\mathrm dx}{\omega^2 + x^2}$$ After integrating you'll have to substitute the initial conditions in order to find the constants. **Example** After integrating the first one, you'll get: $$\arcsin y = \frac{x^2}2 + C\tag1$$ Now, substitute $x=0$, $y=0$ to get $$0 = 0 + C \implies C = 0$$ Once you know the constant, substitute back into $(1)$ and solve for $y$: $$\arcsin y = \frac{x^2}2 + 0 \implies y = \sin\left(\frac{x^2}2\right)$$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "real analysis, ordinary differential equations" }
database error when widget updates I have a DB in my app which normally works perfectly. Now, I have added a widget with an update function which also accesses the DB. Once in a while, I get this error but only from within the widget update method. Caused by:java.lang.NullPointerException at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118) Is there some kind of restriction on accessing a DB from within widget update method?
You shouldn't do any disk IO from the widget's BroadCast receiver (`onUpdate()`). Start a service that fetches the data and does the actual update. You might want to use an `IntentServcie` since it starts a worker thread by default.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, database, widget, nullpointerexception" }
Find absolute value inequality describing the result of measurement This is a problem from my homework where a sample of a quantity is $37.5\pm 1.2$ grams. And if the actual quantity is $x$, write the results as an absolute value inequality and solve for $x$. I think I know that $36.3\le x\le 38.7$. So all I am asking for is this absolute value inequality (equation?) and maybe the logic for finding it.
Probably you want $|x-x_0|\leq\delta$, where $x_0$ is the center of the interval and $\delta$ the half-width.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "inequality, absolute value" }
Run JavaScript from a TextArea I have to create an application in Node.js that executes algorithms (in js) and create graphs with their results. My problem is that I don't really know how to execute the JavaScript in my textarea, I didn't find a plugin that can run a javascript code in node.js. Thank you
I have also found that < which is perfect !!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, node.js, forms, algorithm" }
Conditionally add OR condition in query The orders table have a few columns, say email, tel and address. User provides email/tel/address, and any of them can be nil or empty string ( **EDITED** ). How to generate an OR query, so if any of the columns match, the record is returned? The only catch is that if any value provided is nil or empty, that will be ignored instead. I was able to do the following using Arel: email = params[:email] tel = params[:tel] address = params[:address] t = Order.arel_table sq = t[:email].eq(email) if email.present? sq = sq.or(t[:phone].eq(phone)) if phone.present? sq = sq.or(t[:phone].eq(address)) if address.present? Order.where( sq ) However it will err if email is nil, because sq will not instantiate. I want to prevent constructing sql string, and I use Squeel gem.
In order to prevent nil or empty string, I finally got the following: t = Order.arel_table conditions = [:email, :phone, :address].map{|attr| attr_value = params[attr] if attr_value.present? t[attr].eq(attr_value) else nil end }.compact if conditions.empty? Order.where('1=0') else Order.where( conditions.inject{|c, cc| c.or(cc).expr} ) end Ugly, but flexible.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, activerecord" }
Python - How to send data from a certain point (resume download) I'm trying to make a file server in Python using only sockets. What would be a way I could go about skipping reading the first "x" amount of bytes in a file then sending it? I'm pretty good at sockets but not at reading files so if anyone could help it would be great! Edit: No protocol. Just a Python server on a random port. Client and server will both be custom.
I can use the `.seek()` method to skip the data and then start reading from there and send the rest of the data as needed. Thanks @pm-2ring for showing me this method.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, sockets, fileserver" }
Does excludedUserAgents support wildcards? Sitecore docs says: > You can create a list to assign custom user agents and IP addresses to exclude in the Sitecore.Analytics.ExcludeRobots.config file. You can manually edit this list by adding the user agents that you want to block under the node and IP addresses under the node. More at: < But I can't find any information if some kind of wildcard can be used in `excludedUserAgents` node. I mean, can I use something like this: <excludedUserAgents> *Googlebot* </excludedUserAgents> instead of this: <excludedUserAgents> Mozilla/5.0+(Linux;+Android+6.0.1;+Nexus+5X+Build/MMB29P)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/80.0.3987.92+Mobile+Safari/537.36+(compatible;+Googlebot/2.1;++ </excludedUserAgents> Asking because I have quite a long list of user agents to exclude and most of them contains "crawler" as a substring.
The code is below. I uses a .Contains() against a List. It has to be an exact match. if (args.HttpContext.Request.UserAgent == null || !AnalyticsSettings.Robots.ExcludeList.ContainsUserAgent(args.HttpContext.Request.UserAgent)) Then it is just a simple list Contains public bool ContainsUserAgent(string userAgent) { Assert.ArgumentNotNull((object) userAgent, nameof (userAgent)); return this.userAgents.Contains(userAgent); } You can override the CheckUserAgent processor in the excludeRobots pipeline and role you own logic for partial. <excludeRobots> <processor type="Sitecore.Analytics.Pipelines.ExcludeRobots.CheckUserAgent, Sitecore.Analytics" /> </excludeRobots>
stackexchange-sitecore
{ "answer_score": 2, "question_score": 0, "tags": "experience analytics" }
lambda returns '1' all time Have code like this #include <iostream> using namespace std; int main() { cout<<[](){ return 0;}; cout<<[](){ return 3.2;}; cout<<[](){ return true;}; cout<<[](){ return false;}; cout<<[](){ return "Hello world!";}; cout<<[]()->int{ return 0;}; cout<<[]()->double{ return 3.2;}; cout<<[]()->bool{ return true;}; cout<<[]()->bool{ return false;}; cout<<[]()->const char*{ return "Hello world!";}; return 0; } Compile it with `gcc version 4.8.2` and my output is only `1111111111`. Why only "1"?
When a lambda expression has no capture, it is implicitly convertible to a function pointer. A function pointer, in turn, is implicitly convertible to `bool`, yielding `true` if the pointer is not null, which gets printed. If you `cout << std::boolalpha` before your outputs, you'll see `truetruetrue....` printed instead. If you capture something in your lambda, then it is no longer convertible to a function pointer, and you'd get a compiler error. If you want to print the result returned by calling the lambda, then you need `()`, as others have pointed out.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "c++, gcc, lambda, g++, return" }
Prompting for a password in Haskell command line application The following Haskell program prompts the user for a password in the terminal and continues if he has entered the correct one: main = do putStrLn "Password:" password <- getLine case hash password `member` database of False -> putStrLn "Unauthorized use!" True -> do ... Unfortunately, the password will appear on the screen as the user types it, which I want to avoid. > How can I read a sequence of characters that the users types without having the show up on the screen? What is the equivalent of `getLine` for this purpose? I'm on MacOS X, but I would like this to work on Windows and Linux, too.
Do this: module Main where import System.IO import Control.Exception main :: IO () main = getPassword >>= putStrLn . ("Entered: " ++) getPassword :: IO String getPassword = do putStr "Password: " hFlush stdout pass <- withEcho False getLine putChar '\n' return pass withEcho :: Bool -> IO a -> IO a withEcho echo action = do old <- hGetEcho stdin bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
stackexchange-stackoverflow
{ "answer_score": 40, "question_score": 29, "tags": "command line, haskell, passwords, terminal" }
readLines killing R in purrr::map I keep losing my session* in the console when trying to perform readLines (from base) with map (from purrr). *Don't get new line, and R doesn't seem to be running anything If I input a vector of file paths: paths <- c("a/file.csv", "a/nother_file.csv") And try and get all top lines out with map and readLines, R dies. result <- map(paths, readLines(n = 1)) But if I do: result <- map(1:2, function(x) readLines(paths[x], n = 1)) It works. What am I doing wrong?
this will work: `result <- map(paths, readLines, n = 1)` from `?purrr::map Usage map(.x, .f, ...) ... Additional arguments passed on to .f.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "r, purrr" }
Linear Function: y = mx + b (2 points given) in code I'm not quite sure what I'm doing wrong, as this should be fairly simple... I have 2 given points plus X from the third - and now I need Y from that third line. That's a really simple equation: y = mx + b. But because I can't use this in my C#-program (well, I'm sure there's a library for that, but performance matters here), I'm trying to "write the formula out". My function looks like this: public static float GetY(Vector2 point1, Vector2 point2, float x) { var m = (point2.Y - point1.Y) / (point2.X + point1.Y); var b = point1.Y - (m * point1.X); return m*x + b; } Now something in this formula is wrong, because sometimes I don't get the right value. Do you have any idea what I'm doing wrong?
In your posted code, you seem to have made a typo. This: var m = (point2.Y - point1.Y) / (point2.X + point1.Y); ...should be: var m = (point2.Y - point1.Y) / (point2.X - point1.X);
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "c#, math, linear algebra" }
Intersection of set partitions I am trying to figure out a good way of finding the intersection of two partitioned subsets of a set (or what to call what I'm trying to do so I can read something about it). Let's say I have two subsets, ABC and BCDE. The first is partitioned into A/BC (part A vs part BC) and the second is partitioned into B/CDE (part B vs part CDE). Whatever the two subsets are, the partitions are always bipartite. Now I want to combine these subsets, retaining the partitions so that I have A/B/C/DE. I may implicitly be treating the fact of the two subsets as a higher-order partition. This seems to me some sort of intersection of partitions (hence title). It seems there should be a clear algorithm for what I'm doing here but I just can't grasp it. To make things worse, I need to be able to scale this up to more than two subsets (but the partitions are always bipartite). Any advice would be appreciated. Thanks for reading--
You can equivalently think of partitions as equivalence relations, with elements in the same piece of the partition labelled as equivalent. So the partition in the first subset $S_1$ is given by the equivalence $$B \sim_1 C,$$ and the partition in the second subset $S_2$ is given by the equivalence $$C \sim_2 D \sim_2 E.$$ We can even suppose that we have more subsets, $S_1,...,S_n$, each with a partition defined by the equivalence relation $\sim_n$. In order to match your operation, it's actually better if we extend these relations to the union $\bigcup_1^n S_i$ by additionally declaring $X \sim_i Y$ if $X, Y \notin S_i$. Now I define a final equivalence relation $\sim$ by $X \sim Y \iff X \sim_i Y \;\forall\; i$. Translating this back into a partition should match the operation you've defined.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "elementary set theory, set partition" }
date-fns format does not format properly microSeconds? I am using the following script in order convert microSeconds in hh:mm using date-fns but I get the wrong formatting: `const microSeconds = 100000000 format(addMilliseconds(new Date(0), microSeconds / 1000), 'hh:mm')}` for example in this case I would need to get '00:01' but instead I get `01:01` Any idea how to fix it? Runnable code <
It's because `date-fns` format function relies on locales. Format's docs contains information (under table with accepted tokens): > The result may vary by locale. You could subtract timezone offset: const d = new Date(0); const formatedValue = format( addMilliseconds(new Date(0 + d.getTimezoneOffset()*1000*60), microSeconds / 1000), 'HH:mm') Change also date format to `HH:mm`, because `hh` is between 01 and 12
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, date fns" }
JavaScript global function I have a function in a JavaScript file: myscripts.js: function myOn(node,event, selector, data, handler) { document.write("This text comes from an external script."); } and in the HTML file, I have this: <body> <script src="myscripts.js"></script> ...//some text and tags <script> myOn(outer, 'click','.deleteButton ', "", deleteDiv); </script> <body> the function "myOn" don't run in the HTML file. How i make this work? I have searched the internet, but found some hard example for me to understand. I need a simple example for beginner like me.
You have a syntax error in the function definition, there shouldn't be another parenthesis inside the parentheses This line: function myOn(node,event, selector, data, handler(eventObject)) should be: function myOn(node,event, selector, data, handler)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Does $\mathbb N$ have a predecessor? Let $\mathbb N$ be the Von Neumann constructed natural numbers. Does $\mathbb N$ have a predecessor? **My try** $$\mathbb N^*:=\mathbb N \backslash \\{\varnothing\\}$$ Let $p$ be a map $$p:\mathbb N^* \to \mathbb N \\\n \to \bigcup n$$ namely the predecessor map. **Example** $$p(3) = \bigcup 3 = \bigcup \\{ \varnothing ,\\{\varnothing \\},\\{\varnothing, \\{\varnothing \\}\\}\\} = \\{\varnothing, \\{\varnothing \\}\\} = 2$$ **My try continuous** $$p(\mathbb N)=\bigcup \mathbb N = \mathbb N$$ thus, $$p(\mathbb N) \notin \mathbb N$$ But it does not make sense, because $\mathbb N \notin \mathbb N$.
No. The first infinite ordinal $\Bbb N$ (or better written $\omega$ in this context) is a limit ordinal, i.e. it has _no_ (immediate) predecessor.
stackexchange-math
{ "answer_score": 4, "question_score": -1, "tags": "set theory" }
Lightweight snmp check for printer toner status i hope this is the right site to post this question. First of all in my organization we have a lot of HP network printers (2015 and 2055) all have static ip configured and SNMPv2 up and running. I'm looking for a lightweight tool that allows me to monitor the toner status of these printers. Spiceworks do the job but IMHO has too many features and it's all except lightweight. I'd like to run it in a Linux VM with 512 Mb Ram (if possibile). I checked out Nagios, Cacti, Zabbix, Zenoss and many other i don't recall the name but all of these tools are studied to check uptime or route status. Any suggestion? Thank you in advance
You might want to try www.opennms.org You will have to do some amount of custom coding for your printers, but that's unavoidable no matter what platform you choose. Are you planning to check with SNMP traps (they send a trap when toner is low) or check it with SNMP reads (you read it every X minutes)? I also found this, which may be of assistance: <
stackexchange-serverfault
{ "answer_score": 0, "question_score": 1, "tags": "networking, snmp, printer" }
Finding an expression for a multi variate joint CDF. Let $X,Y$ and $Z$ be random variables with $X$ and $Y$ dependent, and $Z$ independent of both $X$ and $Y$. Let $f_{X},f_{Y},f_{Z}$ denote the density function's of $X,Y$ and $Z$ respectively and $f_{X,Y}$ denote the joint density function of $X$ and $Y$. Assuming the support of all three random variables is $[0,\infty]$, we can give an expression for $\mathbb{P}[Z>f(Y),Y<b],\;\mathrm{with}\;b\in[0,\infty),$ as: $\mathbb{P}[Z>f(Y),Y<b] = \int_{y=0}^{b}\int_{z=f(y)}^{\infty}f_{Z,Y}dzdy = \int_{y=0}^{b}\int_{z=f(y)}^{\infty}f_{Z}f_{Y}dzdy.$ The above problem is $fairly$ trivial. We now form a new, more complicated, problem by introducing $X$. The new problem looks like this: Given the definitions of $X,Y$ and $Z$ above, can we find an expression for: $\mathbb{P}[Z>f(X,Y),X+Y<b]\;?$
To get the expression you want, you will need the support for the joint p.d.f. of $X$ and $Y$ (i.e. the set of $(x,y) \subseteq \mathbb{R}^2$ for which $f_{X,Y} \neq 0$). For convenience I will let the support be given by $[u,v] \times [c,d]$ for some real numbers $u < v, c < d$. Since $Z$ is independent of $X$ and $Y$, we have that the joint p.d.f. of $X, Y,$ and $Z$ is given by $f_{X,Y,Z}(x,y,z) = f_{X,Y}(x,y)f_Z(z)$ and so $$\mathbb{P}[Z>f(X,Y) \cap X+Y<b] = \int_u^v\int_c^{b-x}\int_{f(x,y)}^{\infty} f_{X,Y}(x,y)f_Z(z) \; dz \; dy \; dx$$ So it's a similar procedure to the one you already have. You start by integrating $f_{X,Y,Z}$ over all values of $z$ for which $z > f(x,y)$, and then you integrate over the region for which $x + y < b$. That is, you integrate first over all $y$ for which $c < b - x$, and then over all possible values of $x$. If something about this is unclear or straight-up wrong, let me know and I'll try to correct :)
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "probability, probability theory" }
In Java how can I access a variable from outside the anonymous class for example: for (int i = 0; i < 10; i++){ SomeClass something = new SomeClass(); something.setOnClickListener(new OnClickListener() { public void onClick(){ doSomething(i); } }); } I am not allowed to use the variable `i`, Eclipse suggest me make the `i` `final`, but I cannot do that because I need it to iterate right?
Copy `i` to a `final` variable in the loop body. for (int i = 0; i < 10; i++){ final int j = i; SomeClass something = new SomeClass(); something.setOnClickListener(new OnClickListener() { public void onClick(){ doSomething(j); } }); }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "java, anonymous inner class" }
Can Virtual PC use the Boot Camp Windows Partition? Both Parallels and VMWare allow you to set up a virtual machine using your existing Boot Camp partition. Does Virtual PC for mac have a similar feature?
No as Virtual PC is form PowerPC macs and not Intel ones. You will need an intel virtualization product e.g. VirtualBox which is free or Parallels or VMWare
stackexchange-apple
{ "answer_score": 1, "question_score": 0, "tags": "windows, bootcamp, virtualization" }
django memcahed key generation Default django cache keys generator: def make_key(key, key_prefix, version): return ':'.join([key_prefix, str(version), key]) I want to change with: in settings.py def make_key(key, key_prefix, version): return key CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'KEY_FUNCTION' : 'settings.make_key', } } but django generate keys with old native function (prefix-version-key) how to change it?
Try: def make_key(key, key_prefix, version): return key CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'KEY_FUNCTION' : make_key } } I know that in documentation is "string containing a dotted path" but I see in the Django source code that you can also pass callable object (eg. function). If you really need to pass it as a string, you should move this function to another module and set `yourproject.module.make_key` as `KEY_FUNCTION`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "django, memcached" }
Parsing a REST Token Expiry Date I need to parse the expiry date that return by REST WebAPI (written in .NET) which return something like this `Sun, 24 Feb 2019 08:06:26 GMT`. I tried to parse it this way: SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); dateFormat.parse(issuedDate); //throws java.text.ParseException: Unparseable date - eg try to parse: Sun, 24 Feb 2019 08:06:26 GMT But sometimes, it throws `java.text.ParseException: Unparseable date`. Any idea how to parse the date that using this format (eg. `Sun, 24 Feb 2019 08:06:26 GMT`)? Thanks ## UPDATE I think I found the problem. The problem is that the Android language is set to "Bahasa Indonesia" which Sunday is not **Sun** but **Minggu**. Any idea how to parse token return by REST API (eg. `Sun, 24 Feb 2019 08:06:26 GMT`) in the language set to language other than English?
Hello you use the following code String cdate = "Sun, 24 Feb 2019 08:06:26 GMT"; SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); Date date = null; try { date=sdf.parse(cdate); } catch (ParseException e) { e.printStackTrace(); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, android" }
Align two DIVs in a TH I have a `table` in which I want to add sort icons to the right of the text in the `th`. Here is my current code: < The issue I am having is that when the columns are reduced in size due to resolution/browser window size, the text in the `th` gets moved above the icons. How can i use CSS to always have the text to the left of the icons?
Wrap text and icon into `flex-container` and use `flexbox` <div class="flex-container"> <div class="label"> Order Number </div> <div class="sort-icons"> <cfoutput> <div> <a href="?sortBy=OrderNumber&sortOrder=ASC" title="Sort Ascending"><span class="ui-icon ui-icon-circle-triangle-n"></span></a> </div> <div> <a href="?sortBy=OrderNumber&sortOrder=DESC" title="Sort Descending"><span class="ui-icon ui-icon-circle-triangle-s" style="display: block;"></span></a> </div> </cfoutput> </div> </div> CSS .flex-container { display: flex; } **Updated Fiddle**
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "html, css" }
Need help with Regular Expression for nine digit alphanumeric with minimum one space boundary I'm trying to match a CUSIP number. I have the following, but it is missing some edge cases. \s[A-Za-z0-9]{9}\s I need to omit strings which contain a space in the middle and I need it to match strings which may be bordered by some other text. My strings are generally surrounded by tabs, but it may be as little as one space char separating the CUSIP from other text. Thanks in advance, I'm pretty green with regex. P.S. I'm working in .NET Example "[TAB]123456789[TAB]" should be matched (I'm getting this now) "sometext[TAB]123456789[TAB]sometext" should be matched (this is not currently being returned) "some text" should not be returned (I am currently getting this kind of match)
According to this page, not just any 9-digit alphanumeric is a valid CUSIP. The first three characters can only be digits, and the ninth is a checksum So if you want to distinguish CUSIPs from other 9-character strings, I believe this should work better: \s[0-9]{3}[a-zA-Z0-9]{6}\s or, if you also want to match strings that are bordered by the beginning or end of input: (^|\s)[0-9]{3}[a-zA-Z0-9]{6}(\s|$) or, if you also want to match strings that are bordered by punctuation (such as "(100ABCDEF)": (^|[^a-zA-Z0-9])[0-9]{3}[a-zA-Z0-9]{6}([^a-zA-Z0-9]|$) I believe that should be a 99% solution, but if you want to be really robust you might also want to look into using the 9th (parity) character to verify that the strings are valid.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "c#, regex" }
How to put two equations in one line with different number? I have to short equations, and consume to much vertical space, I want to gather them in one line, but with different number. I want to the equation show like below a = b (1) c = d (2) d = e (3) e = f (4)
In case you don't need alignment across the equations (e.g. aligning all the equal signs), then a table can be a quick solution: \documentclass{article} \usepackage{lipsum} \begin{document} \lipsum[2] \begin{center} \begin{tabular}{p{3cm}p{3cm}} \begin{equation} a = b \end{equation} & \begin{equation} c = d \end{equation} \\ \begin{equation} d = e \end{equation} & \begin{equation} e = f \end{equation} \end{tabular} \end{center} \lipsum[2] \end{document} ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "latex, pdflatex, xelatex" }
Alias case statement I have stored procedure that sometimes return negative number in the ID. (on purpose). In additional, I have a view that shows this table (simple select), but I don't want that '-' will appear in the ID column, I mean, if the number is negative - I want to add the letter 'A' to the ID without '-'. How can I do this?
SELECT REPLACE (ID, '-', 'A') MyID Or if you were wanting to append the 'A' SELECT REPLACE (ID, '-', '') + 'A' MyID
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, stored procedures, view" }
mySQL case when only returning 1 result No idea why this is returning the first result only. The date is a Date format not datetime. I've only started using MySQL from using ORACLE and this is doing my head in. SELECT *, CASE d_date WHEN max(d_date) THEN 'Today' WHEN date_add(max(d_date), interval -1 day) THEN 'Yesterday' ELSE 'other' END dateID FROM mike.Tble
When aggregate function like MAX used it returns single record with max value. Thus my understandings need a sub query. I could not find how to optimize this query for a large record but I have following and lets optimize this for large records. set @today = (SELECT max(d_date) FROM mike.Tble); set @yesterday = (SELECT date_add(max(d_date), interval -1 day) FROM mike.Tble); SELECT *, CASE d_date WHEN @today THEN 'Today' WHEN @yesterday THEN 'Yesterday' ELSE 'other' END AS dateID FROM mike.Tble Note: I edited query and its performance is better then last query
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, case when" }
Picking 3 balls from 10 balls, each one with a number from 0 to 9 Given that we pick 3 balls from 10 balls, each one with a number from 0 to 9, I need to define the following event: "Number of balls that we picked, whose number on them is odd, is even". Meaning for example that (1,3,4) is in the subset that we want to find, but (1,3,5) is not. I tried to calculate the cardinality of the subset and got $3 \choose 2$$*5*4*5 = 300$. I don't know if it's right. I should add that it's an ordered sample without repetitions. Did I do a mistake ? Thank you for your help
Comment continued with simulation: set.seed(2021) odd = replicate(10^6, sum(sample(0:9, 3) %in% c(1,3,5,7,9))) mean(odd==0 | odd==2) [1] 0.49988 @ aprx 1/2 Approximate probabilities for 0, 1, 2, or 3 odd numbered balls. table(odd)/10^6 odd 0 1 2 3 0.083837 0.417324 0.416043 0.082796 Multiplying by 720 possible outcomes suggests 60, 300, 300, 60 favorable outcomes for 0, 1, 2, 3 odd marbles, respectively. [That's 100 each for EOO, OEO, OOE.] 720*table(odd)/10^6 odd 0 1 2 3 60.36264 300.47328 299.55096 59.61312
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "combinatorics" }
Fast merge of very many small matlab matrices I need to merge around 50 million small Matlab matrices. Using a script like the below seems never to finish. Is there a faster way? I'd be willing to try a non-Matlab Route if that were faster. main_data_a = zeros(10000000, 3); main_data_b = zeros(10000000, 3); main_data_c = ones(10000000, 1); for i=1:1:10000000 try to_load=sprintf('data/output%d.mat',i); load(to_load); catch end; if sum(a) ~= 0 main_data_a(i,:) = a; main_data_b(i,:) = b; main_data_c(i,:) = c; end; end;
Here is a complete example showing "parfor" usage. disp('Using for-loop') tmpData = zeros(100000,1); tic for i = 1:length(tmpData) tmpData(i) = max(max(eig(i*ones(100,100)))); % Some operation end toc disp('Using parfor-loop') tic parfor (i = 1:length(tmpData)) tmpData(i) = max(max(eig(i*ones(100,100)))); % Some operation end toc The above code resulted in the following timings on my machine. Using for-loop Elapsed time is 32.792182 seconds. Using parfor-loop Elapsed time is 7.673821 seconds. However, if some simple calculations are carried out inside the for (or parfor) loop body then "for-loop" runs faster than "parfor". For example, if you replace `tmpData(i) = max(max(eig(i*ones(100,100))));` with `tmpData(i) = i;` then you could see that for-loop performs better.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "matlab, performance, matrix, merge" }
Trouble identifiying a gauge I have made another trip to my grandfather's shed and I found some more tools that I am very interested to have and use _(like the adze I got!)_. I have been watching enough episodes of The Woodwright's Shop to know that I found a scratcher gauge. Also with it was what _appeared_ to be a pair of mortise gauges. One is pictured below. Good guess is that it is homemade so there's nothing to look up. I say "appeared" because all the mortise gauges I have seen both scratchers are on the same post with one of the "nails" being adjustable. !home made gauge My problem with this is that: If you were to use this for a mortise you would have lines protruding the mortise area which could be seen. Am I wrong about what this is? If I am right would you just use this like a regular mortise gauge?
For this gauge, I would imaging that you scribe with both beams _individually_ instead of scribing with both points active at the same time. So, if you're setting up the inside cheek of the mortise, you scribe with the shorter beam. Then rotate the tool slightly and scribe the outside cheek with the longer beam. This is a similar system to the Veritas Dual Marking Gauge (pictured below, images from Lee Valley), which I own and operate in the same fashion. ![Veritas Marking Gauge]( ![Marking Separate]( Note that this would require rotating each of the beams slightly opposite each other so that one is not active when using the other, or even having each point on opposite sides of the gauge.
stackexchange-woodworking
{ "answer_score": 8, "question_score": 8, "tags": "tool identification, traditional techniques, measurement" }
Clearing stdout errors from google test ones Is there any way (aside from stdout redirection) to avoid my code's error and warning messages to be sent to stdout when using google tests? I'd like to just get the tear-down and output from gtest instead of having my stdout log trashed with my program's manually generated warnings and exceptions that I need to test.
Assuming all your tests use fixtures, and all your output is `<iostream>`-based, you could do the following: using namespace std; class SomeTest : public testing::Test { protected: virtual void setUp() { storedStreambuf_ = cout.rdbuf(); cout.rdbuf(nullptr); } virtual void tearDown() { cout.rdbuf(storedStreambuf_); } private: streambuf* storedStreambuf_; }; This will suppress all output via `cout` during your test's run, it can be done the same way for `cerr` and `clog`. In order to keep this DRY, you could write a common base class inheriting from `testing::Test`, and make all your fixtures based on that.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, unit testing, stdout, googletest" }
Can you turn std::map into an unordered map with a custom comparator? Due to using a library that I don't want to edit the code of, I find myself requiring the use of `std::map<Identifier, String>`. struct compareIdentifiers { bool operator()(const Identifier& a, const Identifier& b) const { // return a < b; return true; } }; typedef std::map<Identifier, String, compareIdentifiers> IdentifierMap; Should I return true or false? No comparison needs to be made. I imagine returning true or returning false would be wildly different in efficiency because one will cause the map to re-order, the other won't... right? I tried to use `std::unordered_map<Identifier, String>` but got error: Error C2280 'std::hash<_Kty>::hash(void)': attempting to reference a deleted function
Always returning true is invalid. It would mean (for instance) that `A < B` and `B < A` would both be true. This contradicts the requirements of a `std::map` comparator, which are that it imposes a strict weak ordering. It's entirely possible returning true would crash your program. Always returning false is valid, it effectively means that all keys are considered equal. So only one key could be added to the map (thanks aschepler for the correction). What stops you writing a sensible comparator?
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "c++, stl, containers" }
Unable to access web application running on a certain machine Tried deploying a simple web application (jboss 5.1, jboss seam 2.2.1) on a machine. But for some weird reason, I am unable to access the application using ` Any access to the application on a IE 8 browser, just gets re-directed to the search page with a string "localhost:8080". Couple of observations:- 1. I tried switching off the firewall protection on the machine, but this didn't help 2. I tried switching off the Avast virus protection software process, but this didn't help. 3. Tried starting JBoss application server using run.bat -b 0.0.0.0 (didn't help) Any ideas on what is happening here?
Is it possible that the hosts file on that machine is not set correctly? Try < instead.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, windows, web applications, jboss, jboss5.x" }
I tried to create new react app with npx create-react-app but it's not working `npx create-react-app` is not working I tried `npm uninstall -g create-react-app` and `npm cache clean --force` but it is still not working. Here is the error message: npm ERR! Unexpected end of JSON input while parsing near '..."optional":true}},"fu' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Zee\AppData\Roaming\npm-cache\_logs\2021-10-13T16_22_36_156Z-debug.log
> You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine. To create a project, run: npx create-react-app my-app cd my-app npm start 1. To check the Node version, Go to the terminal and type the command `node -v` or `node --version` 2. And to check the npm version, type `npm -v` or `npm --version` For more details check the official docs: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "reactjs, create react app" }
How can I save the SwichButton setting? I've got 4 SwichButton, this is standard to Off. How can I save the setting when a switch button is set to on ? I have this: @IBAction func SwitchNofic(_ sender: UISwitch) { let switchTag = sender.tag if (switchTag == 1) && (sender.isOn == true){ print("1") createNoficationMorgen() }else if (switchTag == 2) && (sender.isOn == true){ print("2") createNoficationMittag() }else if (switchTag == 3) && (sender.isOn == true){ print("3") createNoficationAbend() }else if (switchTag == 4) && (sender.isOn == true){ print("4") createNoficationNacht() } }
It depends if you want to save it just for the time the app is alive. Just use a boolean variable so you know what is on and what is not, also each switchButton has a property **isOn**. If you want it to be persistant try **UserDefaults**. **Swift 4** To save permanently : UserDefaults.standard.set(true, forKey: “isDarkModeKey”) To retrieve (this should be called in viewDidAppear): let isDarkModeEnabled = UserDefaults.standard.bool(forKey: “isDarkModeKey”) if isDarkModeEnabled { mySwicth.setOn(true, animated : false) //set the background to dark } else { mySwicth.setOn(false, animated : false) //set the background to white }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "ios, swift" }
Measure theoretic integral notation Is there a difference between the following $\int_A \int_B F(dx,dy)$ and $\int_{A\times B}F(dx,dy)$ If there is not, is one preferred over the other?
First, I haven't come across any of the two, rather I have seen $\int_A\int_B F(x,y) \, dx \, dy $ or $ \int_{A\times B} F(x,y) \,dx \,dy $ Then, in fact, these are different things. The first is an integral of the function $\int_B F(x, y) dy $ over $A$ (which may or may not be defined and integrable), while the second is an integral in the product space $A\times B$. The pertinent theorem which says when the first is well defined and may equal the second is Fubinis' theorem. (And, since these are different things, it does not make sense to 'prefer' any of them).
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "integration, measure theory" }
Prove that $\displaystyle \sum_{k=1}^n \bigg(\dfrac{1}{k}+\dfrac{2}{k+n}\bigg ) \leq \ln(2n) + 2 -\ln(2)$ > Prove that $$\displaystyle \sum_{k=1}^n \bigg(\dfrac{1}{k}+\dfrac{2}{k+n}\bigg ) \leq \ln(2n) + 2 -\ln(2).$$ I was thinking of using mathematical induction for this. That is, We prove by induction on $n$. The case $n=1$ holds trivially since $2 \leq 2$. Now assume the result holds for some $m$. Then by assumption we know that $$\displaystyle \sum_{k=1}^{m+1} \bigg(\dfrac{1}{k}+\dfrac{2}{k+m}\bigg ) \leq \ln(2m) + 2 -\ln(2)+\dfrac{1}{m+1}+\dfrac{2}{2m+1}. $$ We must relate this somehow to $\ln(2(m+1)) + 2 -\ln(2)$.
First note, that we can rewrite the RHS of your inequality as $\ln(n) +2$. We proceed by induction. We compute $$ \sum_{k=1}^{n+1} \left( \frac{1}{k} + \frac{2}{k+n+1}\right) = \frac{1}{n+1} + \frac{2}{2n+2} + \sum_{k=1}^n \frac{1}{k} + \sum_{k=1}^{n} \frac{2}{k+n+1}$$ shifting the index yields $$ =\frac{2}{n+1} + \sum_{k=1}^n \frac{1}{k} + \sum_{k=2}^{n+1} \frac{2}{k+n} = \sum_{k=1}^n \frac{1}{k} + \sum_{k=1}^{n+1} \frac{2}{k+n} = \sum_{k=1}^n\left( \frac{1}{k} + \frac{2}{k+n}\right) + \frac{2}{2n+1}$$ applying the induction hypothesis gives $$ \leq \ln(n) + 2 + \frac{2}{2n+1} = \ln(n+1) +2 + \left( \frac{2}{2n+1} + \ln(n) - \ln(n+1) \right).$$ Hence, we are left to show that $$ \frac{2}{2n+1} - \ln\left(1 + \frac{1}{n}\right) = \frac{2}{2n+1} + \ln(n) - \ln(n+1) \leq 0. $$ This is already done in a previous answer.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "number theory, induction" }
What does struct.pack() do to network packets The python official document mentions that 'struct' module is used to convert between Python and binary data structures. What do binary data structures here refer to? As I understand, does the data structure refer to the packet structure as defined in network related C functions? Does struct.pack(fmt,v1,v2) build a C equivalent structure of the fields v1,v2 in format fmt?? For example if I am building an Ip packet, my fmt is the IP header and values are ip header feilds? I am referring to this example while understanding how network packets can be built.
Binary data structures refers to the layout of the data in memory. Python's objects are far more complicated than a simple C `struct`. There is a significant amount of header data in Python objects that makes completing common tasks simpler for the Python interpreter. Your interpretation is largely correct. The other important thing to note is that we specify a particular byte order, which may or may not be the same byte order used by a standard C structure (it depends on your machine architecture).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, struct, network programming" }
What should the behavior of unique_ptr be in this situation? Say I have the following: std::unique_ptr<A> pA; pA(new A); In this convoluted example, what should the behavior of `pA(new A);` be? As far as I can tell, in MSVC2010, `void operator()(T*) const;` from default_delete is called right after `new` returns and deletes the pointer right away. Whereas g++(4.7.0) gave me `no match for call (std::unique_ptr<A>)(A*)` error.
The code should not compile. `std::unique_ptr` does not overload `operator()`. The Visual C++ 2011 Developer Preview rightly rejects the code. Visual C++ 2010 only accepts the code due to a bug in its `std::unique_ptr` implementation.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "c++, c++11, unique ptr" }
Gedit's LaTeX plugin opens a dialog called "Choose Master Document" each time a .tex file is opened I use gedit-latex-plugin to edit my LaTeX documents. However, each time I open a .tex or .sty file, an annoying dialog labeled "Choose Master Document" pops up, and unless I select the same file again, gedit doesn't enter "LaTeX mode". Is there a way to disable this dialog or simply always load "LaTeX mode" when a .tex file is opened?
The LaTeX plugin creates a hidden file `.NAME.properties.xml` (where NAME ist replaced by your .tex file's name) in the same folder as your .tex file. This file contains the settings for the master document, and if it's found the plugin doesn't ask for a master document. A sample file looks like this: <?xml version="1.0" ?><properties><property key="MasterFilename" value="my_master_document.tex"/></properties> There doesn't seem to be a way to switch of this behaviour.
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 8, "tags": "gedit, latex" }
Is there a field in which PDF files specify their encoding? I understand that it is impossible to determine the character encoding of any stringform data just by looking at the data. This is not my question. My question is: Is there a field in a PDF file where, by convention, the encoding scheme is specified (e.g.: UTF-8)? This would be something roughly analogous to `<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">` in HTML. Thank you very much in advance, Blz
A quick look at the PDF specification seems to suggest that you can have different encoding inside a PDF-file. Have a look at page 86. So a PDF library with some kind of low level access should be able to provide you with encoding used for a string. But if you just want the text and don't care about the internal encodings used I would suggest to let the library take care of conversions for you.
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 36, "tags": "pdf, unicode, utf" }
detect object using switch How to determine if the `value` of a variable is an `object` using `switch`? var alice = condition ? true : {}; switch(alice){ case true: break; case undefined: break; // Is there something like: case object: break; } I am currently solving the problem above with an additional `if` statement (in addition to my existing `switch` which is already quite large and capable of handling values like `undefined` and `true`). So I was wondering if there is any way of detecting an object using only the existing `switch(alice)`.
This way is not possible. However checking your variable type might help you to accomplish what you are trying to do. var alice = condition ? true : {}; switch (typeof(alice)) { case 'boolean': break; // if it's true or false case 'undefined': break; case 'object': break; // {}, [], {"a": "b"} } Please note that `object` will also be thrown if you have a non-empty object or an array too.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, switch statement" }
How to convert print output to pyspark dataframe (no pandas allowed) The usual code print((sparkdf.count(), len(sparkdf.columns))) Since I using HDFS system that fully on HDFS, no pandas allowed, The output I need |-------|-------| |row |columns| |-------|-------| |1500 | 22 | |-------|-------|
Just use `spark.createDataFrame` and pass the values as a list of tuple: spark.createDataFrame([(sparkdf.count(), len(sparkdf.columns))], schema=['rows', 'columns'])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "dataframe, pyspark" }
ListDensityPlot and RegionFunction I have the following ListDensityPlot : ListDensityPlot[ Table[Y^2 + Z^2, {Y, -1, 1, Pi/300}, {Z, -1, 1, Pi/300}], ColorFunction -> "SunsetColors", RegionFunction -> Function[{x, y, z}, (0.74)^2 < x^2 + y^2 < (0.785)^2 ], PlotLegends -> Automatic, DataRange -> {{-1, 1}, {-1, 1}}] !enter image description here Here I have limited the ListDensityPlot over a crown. My problem is that I want to limit the ListDensityPlot following this multiple Plot bellow : Plot[{1/2 (ArcCos[1 - Cos[2 kx]]), -1/2 (ArcCos[1 - Cos[2 kx]])}, {kx,-1, 1}, AxesLabel -> {"kx", "ky"}] !enter image description here Is there a way to do this with RegionFunction like I did for the crown, or with an other way ? @shrx Why the thickness is not the same at right and top with your code ? Is there a way to rectify that ? Thank you Geoffroy
Maybe something like this: ListDensityPlot[ Table[Y^2 + Z^2, {Y, -1, 1, Pi/300}, {Z, -1, 1, Pi/300}], ColorFunction -> "SunsetColors", RegionFunction -> Function[{x, y, z}, TrueQ[0 <= y + 1/2 (ArcCos[1 - Cos[2 x]]) <= 0.785 - .74] \[Or] TrueQ[.74 - 0.785 <= y - 1/2 (ArcCos[1 - Cos[2 x]]) <= 0]], PlotLegends -> Automatic, DataRange -> {{-1, 1}, {-1, 1}}] // Quiet That `Quiet` is there because otherwise mathematica complains about the comparison of complex numbers. The output looks like this: !custom region function
stackexchange-mathematica
{ "answer_score": 1, "question_score": 0, "tags": "plotting" }
How can I port this "one-line for loop" from Python to JavaScript? I'm not sure about the terminology used (I think it's called "lambda" or something like that), so I cannot do a proper search. The following line in Python: a, b, c, d, e = [SomeFunc(x) for x in arr] How can I do the same in Javascript? I have this to begin with: let [a, b, c, d, e] = arr; But I still need to call `SomeFunc` on every element in `arr`.
A close approximation would be to use the array method `map`. It uses a function to perform an operation on each array element, and returns a new array of the same length. const add2 = (el) => el + 2; const arr = [1, 2, 3, 4, 5]; let [a, b, c, d, e] = arr.map(add2); console.log(a, b, c, d, e); Be careful when you use array destructuring to ensure that you're destructuring the right number of elements for the returned array.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "javascript, python" }
php if inside or outside the function I often get in this situation where I have an if statement and I can't deside where to put it. **As a wrapper around the function or inside the function?** Is one of the two solutions here better than the other? If so, why? **Solution 1** function one($something) { if( $something === 'yes') { two(); } } function two() { echo 'ok'; } one('yes'); **Solution 2** function one($something) { two($something); } function two($something) { if( $something === 'yes') { echo 'ok'; } } one('yes');
If you want to choose between your two variants - one should be used if you need it to be recursive. If you do not need it to be recursive, you can use both of them.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php, function, if statement, scope" }
Which format of STL file is faster to read: ascii or binary? I have to write an STL file with a large no. of triangles (about 2 millions). Currently I am writing and reading it in ascii format which takes too much time. My question is: "whether writing and reading in binary format will save significant amount of time?" Thanks
Almost certainly it will. If you're storing integers in the text file as human-readable numbers then they will all have to be converted to and from their internal 4-byte representation. If you're using binary, you just dump each number as 4 bytes (I assume 4 byte ints, you may use different types) Without this continual conversion from test strings a binary representation will obviously be faster. The only question is just how fast.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, stl" }
Javascript Regex with Special Character and Space By using Javascript, I want to convert text " [a] b [c]" to "[a] b [c]" My code as below: var test = " [a] b [c]"; test.replace(/\s+\[/g, "["); alert(test); However, the result is "[a] b [c]" I wonder why? Any idea? Thanks!
Strings are immutable. So `replace` doesn't change `test` but returns a changed string. Hence, you need to assign the result: test = test.replace(/\s+\[/g, "["); Note that this will result in `[a] b[c]`. To get your actual result, you might want to use: test = test.replace(/(^|\s)\s*\[/g, "$1["); This makes sure to write back the first of the space characters if it was not at the beginning of the string. Alternatively, use `trim` first and write back one space manually: test = test.trim().replace(/\s+\[/g, " [");
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, regex" }
Complex Matchstick puzzle This is my toughest invention so far, not sure if it's already been done but here it goes. Move a single stick to obtain a correct equality. (To be clear: the stick needs to be moved and placed down to be part of the new figure; not 'removed'). ![enter image description here](
I believe what you're looking for is this: > ![enter image description here]( where > $e^{-i\pi}=3-4=-1$ The title alludes to > the complex number $i$ found in the solution.
stackexchange-puzzling
{ "answer_score": 30, "question_score": 21, "tags": "mathematics, matches" }
Bootstrap tooltip without a link To save space in a narrow table cell I want to use the bootstrap tooltip to display extra content on hover. However, the tooltip uses the :rel option in the a tag. I do not need a link, just its options...and I don't want the link to go anywhere. I have used: link_to display.text, "#", :rel => "tooltip", ...blah..blah link_to_function display.text, "#", :rel => ...blah...blah Both work to an extent, however both return to the top of the page. Its probably smelly code to use a link that isn't really a link to get at some other function. Is there a rails way of creating a dummy link? Is there an "approved" method of accomplishing this?
You can initialize tooltips on other elements besides anchors. Try a span or a div.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "twitter bootstrap, tooltip" }
Using PHP itself to parse/find function calls I'm wondering if it's possible to use PHP's parser to parse files and search/find a given function call. For example, I want to know from which files the function `eval` is called. I could use `find` with `-exec` and some regex, but that returns a lot of false positives, and it also returns commented code. My question is: can I use somehow PHP's own parser to search in files and say if a given function/reserved word is used in that file?
You can use PHP's internal tokenizer to find direct calls to eval: <?php $data = file_get_contents('test.php'); $tokens = token_get_all($data); foreach($tokens as $token){ if($token[0]==T_EVAL){ echo "Eval found on line: ".$token[2]."\n"; } } If you want to look for other things you can change the constant from T_EVAL to one of the constants specified here: Tokens
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, regex, parsing" }
How should I sort object? By shaders or by meshes? To minimize count of state changes, I should sort drawing order of meshes. Anyway If I have multiple meshes using multiple shaders, I need to choose sorting by one of vertex attribute bindings or shader uniform parameters. What should I choose? I think I have to choose minimizing vertex attribute change because of GPU cache hit rate, but I have no idea about shader changing cost. What's the generic concern when deciding drawing order? Can I get some basis to choose this? PS. I'm targeting iOS/PowerVR SGX chips. ## Edit I decided to go sort-by-material because many meshes will use just a few materials, but there're bunch of meshes to draw. This means I will have more opportunity to share materials than share meshes. So it will have more chance to decrease state change count. Anyway I'm not sure, so if you have better opinion, please let me know.
You don't need to depth sort opaque objects on the PowerVR SGX since uses order-independent, pixel perfect hidden surface removal. Depth sort only to achieve proper transparency/translucency rendering. The best practice on SGX is to sort by state, in the following order: * Viewport * Framebuffer * Shader * Textures * Clipping, Blending etc. Texture state change can be significantly reduced by using texture atlases. The amount of draw calls can be reduced by batching. Thats just the golden rules, remember that you should profile first and then optimize :) See: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "sorting, opengl es, drawing" }
Why doesn't this code produce the desired result? def check_beta_code beta_code_array = ['AAAAAAAAAA', 'BBBBBBBBBB', 'CCCCCCCCCC', 'DDDDDDDDDD', 'EEEEEEEEEE'] if false == beta_code_array.include?(:beta_code) errors.add(:beta_code, "Invalid Beta Code") end end I created a user, `user = User.new{:beta_code=>'AAAAAAAAAA'}` and then `user.save #=> false` and then i do `user.errors #=>{:beta_code=>["Invalid Beta Code"]}` Why is it giving the error even though :beta_code is equal to one of the values? Help!
Look at your conditional: beta_code_array.include?(:beta_code) You're checking if `beta_code_array` includes a symbol `:beta_code`. I assume you meant to pass on a string parameter? I'm not too familiar with Rails — please correct me if this isn't the right form for the User model. def check_beta_code beta_code beta_code_array = ['AAAAAAAAAA', 'BBBBBBBBBB', 'CCCCCCCCCC', 'DDDDDDDDDD', 'EEEEEEEEEE'] unless beta_code_array.include?(beta_code) errors.add(:beta_code, "Invalid Beta Code") end end
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "ruby on rails, ruby" }
Creating one for loop for 3 different variables New to python here, trying to make a simple dice roller, created a func() that returns 3 variables after user input. Is there any way to make one function for the creation of the roll? tried with range but had no luck import random def user_input(): y = int(input("Number of yellow dice to roll? : ")) g = int(input("Number of Green dice to roll? :")) b = int(input("Number of Black dice to roll? :")) return y, g, b y, g, b = user_input() for n in range(y): print("Yellow Dice",n+1,":",random.randint(1,6)) for n in range(g): print("Green Dice",n+1,":",random.randint(1,6)) for n in range(b): print("Black Dice",n+1,":",random.randint(1,6))
As what @MichaelButscher suggested in the comments, you can create a function that takes number and color as parameters like this: def one_func(num,color): for i in range(num): print(f"Dado {color} {i+1} : {random.randint(1,6)}") Then, call this function in your `texto()` function three times. def texto(): a = int(input("Dados Amarillos que deseas tirar: ")) v = int(input("Dados Verdes que deseas tirar: ")) n = int(input("Dados Negros que deseas tirar: ")) one_func(a,"Amarillo") one_func(v,"Verde") one_func(n,"Negro") **Note** : `function` names referred to post-edit question. I also saw the error that wrong `variable` naming caused you from that post-edit question.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Python Tornado Request Handler Mapping I'm just getting started with Tornado and I was wondering how i can define a mapping so that all requests like below are are handled by a single handler. 1. /products/list 2. /products/find/123 3. /products/copy/123 4. /products/{action}/{argument1}/{argument2}/{argument3} > > class Application(tornado.web.Application): > def __init__(self): > handlers = [ > (r"/", home.HomeHandler), > (r"/products/", product.ProductHandler)] > > class ProductHandler(base.BaseHandler): > def get(self, action, *args): > self.write("Action:" + action + "<br>") > for arg in args: > self.write("argument:" + arg + "<br>") >
You aren't limited to listing a RequestHandler just once in the url matching, so you can do one of two things: Add a pattern explicitly matching each of the patterns you mention above like so: def __init__(self): handlers = [ (r"/", home.HomeHandler), (r"/products/list/([0-9]+)", product.ProductHandler) (r"/products/find/([0-9]+)", product.ProductHandler) (r"/products/copy/([0-9]+)", product.ProductHandler) (r"/products/(\w+)/(\w+)/(\w+)", product.ProductHandler)] Or you could say that "any URL that begins with "products" should be sent to the product handler," like so: def __init__(self): handlers = [ (r"/", home.HomeHandler), (r"/products/list/(.*)", product.ProductHandler) and parse the variable list yourself in the ProductHandler.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, wsgi, tornado, web.py" }
Using WCF 4 and EF 4 When using wcf and entity framework 4 is it necessary to use POCO? If not how to combine DataContracts with generated classes(i figure one solution is to recreate the domain classes as business classes)?Or what is the best way co combine wcf 4 and ef 4?
You can either create DTOs and then map to and from your EF objects or you can expose your Entities directly. I'd suggest if you're going to expose your EF Entities over WCF then take a look at Self Tracking Entities which were designed with WCF in mind, the T4 templates already annotate the Entities with the DataContract attribute.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wcf, entity framework" }
What fraction is $\frac{2}{5}$ of $\frac{3}{4}$? $\frac{2}{5}$ of blood donors at a centre have group **O** blood. $\frac{3}{4}$ of these donors are under 30. What fraction of the group **O** blood donors at the centre are under 30? What I did was divide $\frac{2}{5}$ by $\frac{3}{4}$ to get $\frac{8}{15}$. Am I heading in right direction or completely off?
**EDIT: As @TonyK pointed out, this answer is incorrect. See @TonyK's answer for why that is. I'll leave my own response here for reference.** * * * You need the fraction of people who $$ \Big(\text{have group O blood}\Big) \mathbf{AND} \Big(\text{are under 30}\Big) $$ This " **AND** " translates to multiplication, so the fraction of the group O blood donors at the centre that are under 30 would be $$ \Big(\text{fraction that have group O blood}\Big) \times \Big(\text{fraction that are under 30}\Big) $$ }
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "arithmetic, fractions" }
What happens in a static parametrized class regarding its instance? Suppose I have this class: public class DispatcherService<T> { private static Action<T> Dispatcher; public static void SetDispatcher(Action<T> action) { Dispatcher = action; } public static void Dispatch(T obj) { Dispatcher.Invoke(obj); } } Let me get this straight... I'll have only one instance of `DispatcherService<T>` for each type, and only when I call it. Right? Just asking for memory issues.
> I'll have only one instance of DispatcherService for each type Yes. > and only when I call it. Right? Yes. The code is emitted by CLR when it needs to use it. * * * ## Note if I where you I would change it to **singleton**. public class DispatcherService<T> { private static readonly DispatcherService<T> _dispatcher = new DispatcherService<T>(); private Action<T> _action; private DispatcherService() {} public static DispatcherService<T> Dispatcher { get {return _dispatcher ;} } public void SetDispatcher(Action<T> action) { Dispatcher = action; } public void Dispatch(T obj) { Dispatcher.Invoke(obj); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, .net, generics, type parameter, static classes" }
How to set user input as a variable for if statement How do you set user input to a variable in order to use 'if' statement effectively? My code seems to disregard the user's input (yes, no and even other) and defaults to the user's input being yes. input("...? ") yes = True no = False if yes: print("...") if no: print("...")
`input` is a function that returns the user input as a string, which you can save to a variable. Your code defaults to yes because you set `yes = True`, so it always enters the first condition. inp = input("...?") # save user input in the variable `inp` if inp == "yes": ... elif inp == "no": ... else: ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python 3.x" }
Localized values of ActionMessage in ValidatorForm I have localized messages, for example: error.message = Invalid {0} object.foo = Foo and some validation code within my `ValidatorForm`: `errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("errors.message", "Foo"));` This works just fine. But I want to localize the message arguments as well using key `object.foo`. I've tried: `getServlet().getInternal().getMessage("object.foo");` but this results in null. Is there some other way?
It's not so difficult, I'll try find harder next time... `org.apache.struts.validator.Resources.getMessage(request,key);`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, localization, struts, struts 1" }
Could not find com.google.android.gms:play-services-base:20.4.0. Android-Cordova Heyy friends! I have a problem that it couldn't solve, developing an application in ionic and angular after exporting it to android with capacitor, but I got the following error when exporting the apk. * What went wrong: Execution failed for task ':app:mergeDebugResources'. > Could not resolve all files for configuration ':app:debugRuntimeClasspath'. Could not find com.google.android.gms:play-services-base:20.4.0. As much as I try to change the versions in the build grandle, the error continues. I'm grateful if someone helps me!
I solved the error by changing the version from 20.4.0 to 18.0.1. This error happens when exporting ionic app to android studio with capacitor, I hope it helps someone.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, cordova, ionic framework" }
avoiding problems with spring cglib proxy Using cglib proxies in spring causes: a) double invocation of constructor b) not allow to intercept a method invoked from another method but why spring creates a bean and then a proxy? is it possible to dynamically generate class that extends a specified bean class and then invoke constructor only once? that would solve a) and b) for public and protected methods. am i missing something?
Good question. I think it's due to how Spring bootstraps application context: it first creates all raw beans and then applies post processors, e.g. adding AOP (including transactions). This layered architecture requires creating normal bean first and then wrapping it. One might argue that this approach follows _composition over inheritance_ principle. Also note that _a)_ should not be a problem. Class should not perform initialization in constructor but in `@PostConstruct` method - which is invoked only once. On the other hand this leads to another issue: c) one cannot use constructor injection with CGLIB proxies, see SPR-3150 But I understand your frustration. Guess the only valid workaround is to us full AspectJ weaving.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 7, "tags": "java, spring, proxy, cglib" }
Understanding Ukkonen's algorithm for suffix trees I'm doing some work with Ukkonen's algorithm for building suffix trees, but I'm not understanding some parts of the author's explanation for it's linear-time complexity. I have learned the algorithm and have coded it, but the paper which I'm using as the main source of information (linked bellow) is kinda confusing at some parts so it's not really clear for me why the algorithm is linear. Any help? Thanks. Link to Ukkonen's paper: <
Find a copy of Gusfield's string algorithms textbook. It's got the best exposition of the suffix tree construction I've seen. The linearity is a surprising consequence of a number of optimizations of the high-level algorithm.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 27, "tags": "algorithm, complexity theory, suffix tree" }
Why Bing Map not showing I have added all the required references like Bing Map and Others. I have added the credential as well. The problem : There is no map showing What need to be done? <bm:Map Credentials="Am5qxl1jqY2FumxPaUtRWPUasxxxxxxxxxxxx " x:Name="myMap" MapType="Aerial" ZoomLevel="12" Width="600" Margin="383,0,383,-593"> &ltbm;:Map.Center> < bm:Location Latitude="40.72367" Longitude="40.72367" /> </bm:Map.Center> </bm:Map>
Set `HomeRegion="US"` in `<bm:Map />` Here is the list of supported regions in Bing Map.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "winrt xaml" }
show that (A,B,C,D) isn't independent , (A,B,C) is independent flipping 3 coins. A={first coin head}, B={second coin head}, C={third coin head}, D={the total number of heads is odd} show that (A,B,C,D) isn't independent , (A,B,C) is independent I have to show it with the definition of independence: A and B are independent if: P(A∩B)=P(A)* P(B) I never did a independence proof before so can please someone help me?
> I have to show it with the definition of independence: A and B are independent if: P(A∩B)=P(A)* P(B) > > I never did a independence proof before so can please someone help me? Just do what you were told: Evaluate the probabilities of the marginals and the conjunctions. If the four events are mutually independent, then $\mathsf P(A\cap B\cap C\cap D)=\mathsf P(A)\,\mathsf P(B)\,\mathsf P(C)\,\mathsf P(D)$ . So is this true? $A\cap B\cap C\cap D$ is the event that the three coins coins show heads and the count of heads is odd. What is the probability for this event? What are the marginal probabilities for the individual events? * * * Likewise if the first three events are mutually independent, then $\mathsf P(A\cap B\cap C)=\mathsf P(A)\,\mathsf P(B)\,\mathsf P(C)$ . So is this true? So...
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "probability" }
Encoded url is not redirecting properly in angular, how to route encoded url to proper address? how to redirect encoded special characters url to proper address? in my project encoded url routing to web page. i created route something like this { path: 'welcome/:id', component: WelcomeComponent }, actually i am passing url like < but this is not accepting and it is accepting only <
{path: '**', component: 'NotFoundComponent'} export class NotFoundComponent{ constructor(private router:Router, private route: ActivatedRoute, ) { let url = this.router.url; url = url.replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/gi, '$') .replace(/%2C/gi, ',') .replace(/%3B/gi, ';') .replace(/%2B/gi, '+') .replace(/%3D/gi, '=') .replace(/%3F/gi, '?') .replace(/%2F/gi, '/'); if(url !== this.router.url){ this.router.navigate([url]); } }
stackexchange-stackoverflow
{ "answer_score": -2, "question_score": 1, "tags": "angular, angular7, urlencode, urldecode" }
php - Insert data into MSSQL I'm trying to insert data from php into MSSQL DB. I'm able to do this: sqlsrv_query($conn,"insert into <DB_Name> (First_Name,Last_Name) VALUES ('Dani','Yorgen')"); The thing is that i have an array which i want to use it instead of using static values. i found this command: $columns = implode(", ", array_values($headers)); this works perfeclty for me! however when itry to do the same for the data it doesnt come as i want. the result comes like this: First_Name,Last_Name when i need it to look like this: 'First_Name','Last_Name' any ideas? thanks in advance.
I managed to find the solution after bashing my head a little bit longer :) it should go like this: $columns = "'" . implode(",", array_values($headers)) . "'"; hope it will help those who needs.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -1, "tags": "php" }
Android clipborad which stores multiple texts I am bascially looking for Ditto for Andoid. * gratis * can store multiple texts * plus boilerplate * let's me edit & delete them * and search through them Please don't just Goole, or search Izzy's site - I can do that - recommend me soemthign which you yourself use
I myself use Clip Stack Clipboard Manager. Features: * free, * open source (available from F-Droid), * stores the clipboard history also if the phone reboots, * the 5 most recent texts are accessible in the notification, * allows editing and deleting, * search feature.
stackexchange-softwarerecs
{ "answer_score": 4, "question_score": 0, "tags": "gratis, android, clipboard" }