text
stringlengths
64
81.1k
meta
dict
Q: Prism v2: seeking clarification on why modules need to "register view types with the shell" I'm reading through the Prism v2 guidelines in which they state: During initialization, modules use the RegionManager to locate regions in the shell and add one or more views to those regions or register one or more view types to be created within those regions I understand that views are added in the bootstrapper e.g. in the GetModuleCatalog() method: protected override IModuleCatalog GetModuleCatalog() { ModuleCatalog catalog = new ModuleCatalog() .AddModule(typeof(HelloWorldModule.HelloWorldModule)); return catalog; } But what does it mean to register a view type? Why do modules need to "register a view type" with the shell if they are already "adding their views" as with the above code? A: In your code you are not adding Views to the bootstrapper but Modules to the ModuleCatalog. A Module in the CAB/Prism/Composite UI world can contain Views, but many times it provides some sort of add-on service that other Modules can use. For example, let's say I have a Shell that happens to uses some docking manager to display views. I want modules to use an API IDockingWindowService to show/hide window. I want the service implementation to be easily interchangeable so I create a Module that contains a service called DockingWindowService and implements IDockingWindowService. I register this Module with the ModuleCatalog. The composite framework workflow would create this service, registers it with the bootstrapper and any modules loaded after this fact would be able to use the IDockingWindowService. This service is not a view, but logic; just wanted to point out that distinction. That being said, a Module can contain 0 or more Views (or, as a simplification, UserControls). The unit of UI is the View. A Module is more of a logic and/or UI bundling concept. Back to your particular question: What the documentation is saying is that if you use Regions to display your Views, you can register the View types with the Region. Whenever the Region is shown, it will automatically build the View using the Unity container.
{ "pile_set_name": "StackExchange" }
Q: Apache tomcat stops after RHEL server patching I've RHEL server where security team keeps on applying security patches every month and then reboot the server. I've apache tomcat installed on RHEL server and a web application (HTML/CSS/Javascript front end and Spring boot backend) running (WAR deployed). After every security patching, I notice 503 Service Unavailable on my web browser and I have to manually start the apache tomcat server (sudo bin/startup.sh) everytime. Is there a way this can be configured in RHEL server so that I don't have to manually start the server everytime after patching is done? Spring boot has it's own embedded tomcat server which I am not using in this case since I am deploying my app as a WAR in the tomcat server installed on RHEL server. A: https://platform.igrafx.com/doc/installation-guide/install-application-server-environments-for-development-and-testing/installation-tomcat-8-on-centos-7-or-rhel-red-hat-enterprise-linux-7 It appears that there is not any service registered that is related to tomcat, which points to it likely being installed from source. You'll need to create a service script, register the script, test if starting/stopping works and then enable it to start at boot. The link above should give the information needed to perform all of these actions. Just make sure it's during an acceptable maintenance window and the current running process for tomcat is shut down.
{ "pile_set_name": "StackExchange" }
Q: Unit Testing Async Methods Using NUnit and C# I am trying to unit test an async methods of a search query. The unit test is defined below: [Test] public async Task MyTest1() { var readyToScheduleQuery = new ReadyToScheduleQuery() { Facets = new List<Facet>() { new Facet() { Name = "Service Type", Values = new List<FacetValue>() { new FacetValue() { Value = "SomeJob", Selected = true } } } } }; var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub); Assert.IsNotNull(result); } The ExecuteAsync method of readyToScheduleQuery is defined below: internal async Task<ReadyToScheduleResult> ExecuteAsync(IAppointmentRepository appointments) { var query = await appointments.GetReadyToSchedule(this.Id, exclude: NotificationTags.Something); The unit test just hangs up and never returns a result. Any ideas? It hangs up if I do the following: (Note the Result property at the end) var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub).Result; A: You are missing an await. When writing your async/await you continue to call await on everything that is marked as async all the way down your callstack. [Test] public async Task MyTest1() { var readyToScheduleQuery = new ReadyToScheduleQuery() { Facets = new List<Facet>() { new Facet() { Name = "Service Type", Values = new List<FacetValue>() { new FacetValue() { Value = "SomeJob", Selected = true} } } } }; // missing await var result = await readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub); Assert.IsNotNull(result); // you will receive your actual expected unwrapped result here. test it directly, not the task. } This will hang. var result = readyToScheduleQuery.ExecuteAsync(_appointmentRespositoryStub).Result; See this previous answer from Stephen Cleary as to why that is. Here again that answer (refer to the link though in case it has changed since the writing of this answer). You're running into the standard deadlock situation that I describe on my blog and in an MSDN article: the async method is attempting to schedule its continuation onto a thread that is being blocked by the call to Result. In this case, your SynchronizationContext is the one used by NUnit to execute async void test methods. I would try using async Task test methods instead.
{ "pile_set_name": "StackExchange" }
Q: What is the meaning of (resp. closed) in set theory? I'm sure this a spectacularly basic question but I can't seem to find the definition of this anywhere. Here's some context: If $U$ and $V$ are open (resp. closed) then $U\cup V$ is open (resp. $U\cap V$ is closed). If $\left\{U_{i}\right\}_{i=1}^{\infty}$ is a countable collection of open sets, must $\bigcap_{i\in I} U_{i}$ be open? Provide a proof or counterexample. Similarly, if $\left\{A_{i}\right\}_{i\in I}$ is an infinite collection of closed sets, must $\bigcap_{i\in I} A_{i}$ be closed? A: Here, "resp." is an abbreviation for "respectively". So: If $U$ and $V$ are open (resp. closed) then $U\cup V$ is open (resp. $U\cap V$ is closed). means: If $U$ and $V$ are open (respectively closed) then $U\cup V$ is open (respectively $U\cap V$ is closed). which is a lazy way to write: If $U$ and $V$ are open then $U\cup V$ is open. If $U$ and $V$ are closed then $U\cap V$ is closed.
{ "pile_set_name": "StackExchange" }
Q: Attach a jquery event after object is created I am using the bPopup jquery library.. the syntax to add to the onclose event is pretty straightforward: $('element_to_pop_up').bPopup({ onOpen: function() { alert('onOpen fired'); }, onClose: function() { alert('onClose fired'); } }) What I want to do is add something to the onClose event after the object is created.. is it possible? A: You can access the bPopup object which will be present inside the data of the element. $('element_to_pop_up').bPopup({ onOpen: function() { alert('onOpen fired'); }, onClose: function() { alert('onClose fired'); } }); $('element_to_pop_up').data('bPopup'); NOTE: There is no guarantee that the created object will be always present in element's data. But this is widely used approach. It is better to rely on the callback provided.
{ "pile_set_name": "StackExchange" }
Q: TRIM/UNMAP Zvol over iSCSI I am currently setting up a SAN for diskless boot. My backend consists of ZFS-Vol shared via iSCSI. So far everything is working just fine except for TRIM/UNMAP. For test puposes I setup two VMs running Ubuntu20.04 in VirtualBox networked together via an internal network with static IPv4 addresses. On the target (tgt) got a second virtual drive formatted with ZFS. On this zpool I created a zVol and formatted it with GPT and ext4. /etc/tgt/conf.d/iscsi.conf <target example.com:lun1> <backing-store /dev/zvol/tank/iscsi_share> params thin_provisioning=1 </backing-store> initiator-address 192.168.0.2 </target> On the initiator (open-iscsi) I use this command to provoke a TRIM operation: sudo mount /dev/sdb1 /iscsi-share sudo dd if=/dev/zero of=/iscsi-share/zero bs=1M count=512 sudo rm /iscsi-share/zero sudo fstrim /iscsi-share but the shell responds with "fstrim: /iscsi-share: the discard option is not supported". If I issue those commands on the target machine the "REFER" property of the zVol decreases as expected. As I found nothing while searching the web I found no hint as to why this is not working or if this is even possible at all. Edit: As I got the advice to use the option thin_provisioning. After I repartitioned the drive and mounted it on the initiator I got error message blk_update_request: critical target error, dev sdb, sector 23784 op 0x9:(WRITE_ZEROES) flags 0x800 phys_seg 0 prio class 0 for several sectors and after creating and deleting my testfile, fstrim send the message blk_update_request: I/O error, dev sdb, sector 68968 op 0x3:(DISCARD) flags 0x800 phys_seg 1 prio class 0 fstrim: iscsi-share: FITRIM ioctl failed: Input/output error Edit: As there were Answers refering to LIO I now also tried targetcli. There I setup a target with my zVol under /backstores/block/iscsi and set attribute emultate_tpu=1. After importing this into my initiator I repartitioned, formatted and mounted it on the initiator. Then I created my test file, deletetd it and issued the fstrim command and it worked. Thanks for the help. A: What you're asking is highly iSCSI target implementation specific. Most of them don't do 1:1 SCSI command mapping, so if iSCSI target emulates hard disk - it won't bypass unrecognized commands (incl. UNMAP of course) to underlying storage @ back-end UNLESS you'll explicitly ask iSCSI target to do so. With TGT you ment'd you specify "thin_provisioning=1" for your virtual LUN in config file. A: TRIM is enabled by default to run weekly in Ubuntu 20.04 so there should be no problem even if you run it manually. You can check this in the fstrim.service and fstrim.timer just in case: https://askubuntu.com/questions/1034169/is-trim-enabled-on-my-ubuntu-18-04-installation However, this indeed looks like you need to enable UNMAP on the target as already mentioned. Since many SATA SSDs had issues with UNMAP, it was disabled in LIO by default: http://www.linux-iscsi.org/Doc/LIO%20Admin%20Manual.pdf. On the side note, of course, things are getting a lot easier when an iSCSI target natively supports TRIM/UNMAP with no further tinkering. Here is an example: https://forums.starwindsoftware.com/viewtopic.php?f=5&t=5343
{ "pile_set_name": "StackExchange" }
Q: Local site within Dropbox using IIS I am trying to have my local website within dropbox using IIS. When I add the dropbox directory I get the error: The server is configured to use pass-through authentication with a built-in account to access the specified physical path. However, IIS Manager cannot verify whether the built-in account has access. Make sure that the application pool identity has Read access to the physical path. If this server is joined to a domain, and the application pool identity is NetworkService or LocalSystem, verify that \$ has Read access to the physical path. I am admin and have allowed all access to the dropbox folder. What is wrong? A: You should add IIS user account to the list of users who are allowed to view/read the files. IIS usually runs via separate user account for security reasons. This is done the following way: Right-click on your site folder in Dropbox Select "Security" Click "Add" Find IUSR user and/or IIS_IUSRS group Add them both (or one, if only one is present) and assign them read permissions Try adding your site folder again. This should fix the issue.
{ "pile_set_name": "StackExchange" }
Q: How to plot data approaching zero in pgfplots log plot? I'm trying to generate a log plot of some data using pgfplots. I've mostly got it looking how I want, but I'd like the plot to show the data continuing down toward the origin rather than stopping at the x=0.05 datapoint. I've tried adding an extra ytick for 0, and it horribly distorts the look of things, as expected. I also tried adding a "fake" data point (for which I could remove the dot(?)) in approximately the right place on the plot, but this is tedious, error-prone, and [frankly] dishonest. I have made great strides with LaTeX through internet searches. However, in this case my google-fu fails me. How can I get the plot to extend toward the origin (while the origin remains "offscreen")? To be clear, I would like the x/y windowing to remain how it is -- I just want the plot to continue to the edge rather than stopping at the x=0.05 datapoint. This code is probably a mess, so I apologize in advance for anything in here that's done in a terrible way. \begin {figure}[H] \centering \begin{tikzpicture} \begin{axis}[ xlabel={$v_D$ (\si{\volt})}, ylabel={$i_D$ (\si{\ampere})}, ytick={0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.001}, yticklabels={$\SI{10}{\nano\ampere}$, $\SI{100}{\nano\ampere}$, $\SI{1}{\micro\ampere}$, $\SI{10}{\micro\ampere}$, $\SI{100}{\micro\ampere}$, $\SI{1}{\milli\ampere}$}, ymode=log, ymajorgrids=true, legend pos=outer north east, ] \addplot table{ -1.000 -1.429E-08 0 0.000E+00 0.05 2.343E-08 0.10 8.547E-08 0.15 2.497E-07 0.20 6.842E-07 0.25 1.831E-06 0.30 4.843E-06 0.35 1.265E-05 0.40 3.227E-05 0.45 7.824E-05 0.50 1.726E-04 0.55 3.340E-04 0.60 5.646E-04 0.65 8.532E-04 0.70 1.210E-03 }; \addlegendentry{$i_D$} % diagonal extension line \addplot[mark=none, black, dotted, line width = 1] coordinates { (0, 2E-08) (0.45,7.824E-05) }; \end{axis} \end{tikzpicture} \caption{Finding $I_S$} \label{fig:3_is} \end {figure} A: I have no time now to derive the diode equation parameters , but what about this? You just substitute the correct current value for the point at $V_D=\SI{0.01}{V}$ (btw, $v_{\scriptscriptstyle D}$ looks better ;-), I even have a macro for it). Then you manually fix the range (xmin=0, xmax=0.6, enlarge x limits, ymin=1e-8, ymax=4e-3) and plot (I added smooth but that's a matter of taste). The key enlarge x limits is used to have the same effect as the "expanded" x-axis you have. The part of the graph going outside is automatically clipped (look at the description of the key clip mode). Obviously, you can do the same on the other side (add one value for 0.9 V, for example). \documentclass[border=10pt]{standalone} \usepackage{tikz, siunitx} \usepackage{pgfplots}\pgfplotsset{compat=1.13} \begin{document} \begin{tikzpicture} \begin{axis}[ xmin=0, xmax=0.7, enlarge x limits, ymin=1e-8, ymax=4e-3, xlabel={$v_D$ (\si{\volt})}, ylabel={$i_D$ (\si{\ampere})}, ytick={0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.001}, yticklabels={$\SI{10}{\nano\ampere}$, $\SI{100}{\nano\ampere}$, $\SI{1}{\micro\ampere}$, $\SI{10}{\micro\ampere}$, $\SI{100}{\micro\ampere}$, $\SI{1}{\milli\ampere}$}, ymode=log, ymajorgrids=true, legend pos=outer north east, ] % first point added semi-"randomly", substitute the correct value \addplot+[smooth] table{ 0.01 4.0E-09 0.05 2.343E-08 0.10 8.547E-08 0.15 2.497E-07 0.20 6.842E-07 0.25 1.831E-06 0.30 4.843E-06 0.35 1.265E-05 0.40 3.227E-05 0.45 7.824E-05 0.50 1.726E-04 0.55 3.340E-04 0.60 5.646E-04 0.65 8.532E-04 0.70 1.210E-03 }; \addlegendentry{$i_D$} % diagonal extension line % just to show that you can use TikZ normal drawing commands here \draw[mark=none, black, dotted, line width = 1] (0, 2E-08) -- (0.45,7.824E-05); \end{axis} \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Internal crash on Android Q I haven't had time to start testing Q yet but I've noticed on crashlytics this error being reported. My app itself doesn't use android.media.MediaHTTPConnection so i'm guessing it is probably an ad network that is using it but that is all I get on the stack trace. Anyone have any idea what might be the fix? And yes I know what a NPE is but that issue is deep within the Android code and like I said this isn't even something I'm calling on my code. Fatal Exception: java.lang.NullPointerException: Attempt to read from field 'int com.android.okhttp.okio.Segment.limit' on a null object reference at com.android.okhttp.okio.Buffer.write(Buffer.java:1184) at com.android.okhttp.okio.Buffer.read(Buffer.java:1223) at com.android.okhttp.okio.RealBufferedSource.read(RealBufferedSource.java:56) at com.android.okhttp.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:395) at com.android.okhttp.internal.Util.skipAll(Util.java:165) at com.android.okhttp.internal.Util.discard(Util.java:147) at com.android.okhttp.internal.http.Http1xStream$FixedLengthSource.close(Http1xStream.java:412) at com.android.okhttp.okio.RealBufferedSource.close(RealBufferedSource.java:397) at com.android.okhttp.okio.RealBufferedSource$1.close(RealBufferedSource.java:385) at java.io.BufferedInputStream.close(BufferedInputStream.java:485) at android.media.MediaHTTPConnection.teardownConnection(MediaHTTPConnection.java:161) at android.media.MediaHTTPConnection.access$000(MediaHTTPConnection.java:43) at android.media.MediaHTTPConnection$1.run(MediaHTTPConnection.java:149) A: Thanks to b0b there’s a tracking bug on the AOSP issue tracker. Want to make sure this gets Google’s attention? Please star this issue: https://issuetracker.google.com/issues/130410728
{ "pile_set_name": "StackExchange" }
Q: Multivariate Time Series Binary Classification I have continuous (time series) data. This data is multivariate. Each feature can be represented as time series (they are all calculated on a daily basis). Here is an example. Days F1 F2 F3 F4 F5 Target Day 1 10 1 0.1 100 -10 1 Day 2 20 2 0.2 200 -20 1 Day 3 30 3 0.3 300 -30 0 Day 4 40 4 0.4 400 -40 1 Day 5 50 5 0.5 500 -50 1 Day 6 60 6 0.6 600 -60 1 Day 7 70 7 0.7 700 -70 0 Day 8 80 8 0.8 800 -80 0 F1, F2, .. F5 are my features and Target is my binary classes. If I use a window size of 3, I can convert my features into time-series data. Then, I will have [10,20,30] for feat_1, [1,2,3] for feat_2 and so on. With the window size of 3, I have 5 feats * 3 window_size, a total of 15 features if written in the same vector. The problem with this method is putting them into the same vector might cause some problems since the feature values are different Example of multivariate time series (15 features in 1 network): [10, 20, 30, 1, 2, 3, 0.1, 0.2, 0.3, 100, 200, 300, -10, -20, -30] [20, 30, 40, 2, 3, 4, 0.2, 0.3, 0.4, 200, 300, 400, -20, -30, -40] .... [60, 70, 80, 6, 7, 8, 0.6, 0.7, 0.8, 600, 700, 800, -60, -70, -80] The other option is to create separate time series network (RNNs mostly, LSTM or CNN or their combination) for each of the features with the same target and then combine their results. In this scenario, I have 5 different networks and all of them are univariate time series binary prediction. Example of different networks with univariate time series data (3 features in 5 networks): [10, 20, 30] ... This is for network 1 [60, 70, 80] [1, 2, 3] ... This is for network 2 [6, 7, 8] ... [-10, -20, -30] ... This is for network 5 [-60, -70, -80] The problem with this one is, I might lose information of the feature correlation even though I'm putting their results into another network. My question is, which is the best way to use when dealing with multivariate time series problems? I want to use the first method but value differences worry me. Second method is easier but I worry that I might be losing some essential information. A: You can add all features as input to RNN/LSTM (Day #, F1, F2, ... F5) and binary class as output. This article has an example of such network.
{ "pile_set_name": "StackExchange" }
Q: Unable to parse jsp indexOf statement correctly It appears that the .indexOf("://") portion of this .jsp file is breaking the proper rendering of this file... how can I escape this to ensure it's not a problem? <c:choose> <c:when test="${cssFile.indexOf("://") > 0}"><link rel="stylesheet" href="${cssFile}" type="text/css" /></c:when> <c:otherwise><link rel="stylesheet" href="/cmt/css/${cssFile}" type="text/css" /></c:otherwise> </c:choose> A: You could use <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> ... test='${fn:indexOf(cssFile, "://") > 0}'
{ "pile_set_name": "StackExchange" }
Q: In a native debugger, what must be done in order to resolve ntdll/other API symbols manually? I'm reversing a Windows binary using x32Dbg and I have the following instruction: call ntdll.776C695A. What steps should I take in order to find out which function this is and/or what it does? The debugger seems to provide some symbols but not all. Thank you. A: Simply execute downloadsym ntdll in the command field at the bottom of x32dbg. As you can see in the documentation: Command: symdownload / downloadsym Attempt to download a symbol from a Symbol Store. arguments [arg1] - Module name (with or without extension) to attept to download symbols for. When not specified, an attempt will be done to download symbols for all loaded modules. [arg2] - Symbol Store URL. When not specified, the default store will be used. result This command does not set any result variables. This should retrieve the Debugging Symbols from the Microsoft public symbol server and update the assembly accordingly.
{ "pile_set_name": "StackExchange" }
Q: Why would you take the logarithmic derivative of a generating function? Today, my climbing expedition scaled Mt. Sloane to request the Oracle's Extensive Insight into Sequences. The monks there had never heard of our plight, so they inscribed our query in mystical runes on a scrip of paper and took it into a room we were not permitted to enter. The Superseeker, as they called it, eventually responded with a fresh scroll, bearing (among other, more familiar, symbols) six imposing letters: LGDEGF. "Logarithmic Derivative Exponential Generating Function," the monks muttered in unison as I unravelled the scroll, nodding and tittering amongst themselves. But what is such a thing? They were quick to recite that it is a function $f$ such that $$\exp\biggl(\int f(x) \,dx\biggr) = \sum_n a_n \frac{x^n}{n!}$$ for my sequence $a_n$, and that the information in the scroll pertained to this $f$, but they refused to answer any further questions. My expedition crew was well-versed in the basic science of generating functions, ordinary power series and exponential. But why might taking the logarithmic derivative of either generating function give interesting or exciting information? Where do they occur in the wild? Most importantly, where in the literature can we learn about them? A: For starters, let's talk about why you might want to take the logarithm of an exponential generating function. The starting point here is the exponential formula, one version of which, roughly speaking, says that if $A(x) = \sum a_n \frac{x^n}{n!}$ is the exponential generating function of structures of some kind (e.g. graphs) which have a decomposition into connected components, then $\log A(x)$ is the exponential generating function of connected structures (e.g. connected graphs). This is a powerful and general result and has many applications, in both directions (taking logs and taking exponentials). As a simple example, the EGF for the number of ways to partition a set into subsets with cardinalities lying in some $S \subseteq \mathbb{N}$ is $$\exp \left( \sum_{n \in S} \frac{x^n}{n!} \right).$$ The exponential formula comes in a "cyclic form" where instead of thinking of $\log A(x)$ as an exponential generating function we write it in the form $\sum b_n \frac{x^n}{n}$; see this blog post for full details. This version of the exponential formula implies, for example, that the EGF for the number of permutations in $S_n$ whose cycles have cardinalities lying in some $S \subseteq \mathbb{N}$ is $$\exp \left( \sum_{n \in S} \frac{x^n}{n} \right).$$ This version of the exponential formula is more relevant to taking logarithmic derivatives since taking the derivative of the logarithm removes the factor of $n$. There's a lot more to say here, including a general interpretation of what it means to compose generating functions; for more see the first half of Analytic Combinatorics. A: Let $X$ be a real-valued random variable. Then we have $$ \operatorname E(e^{tX}) = 1 + m_1 t + m_2 \frac{t^2} 2 + m_3 \frac {t^3} 6 + m_4 \frac{t^4}{24} + \cdots $$ and $m_k = \operatorname E(X^k)$ is the $k$th moment of the probability distribution of $X.$ The $k$th central moment of the distribution is $\mu_k(X)=\operatorname E((X-m_1)^k).$ The central moment enjoys the properties of shift invariance, which means $\mu_k(X+c) = \mu_k(X)$ for constants $c,$ and homogeneity, which means $\mu_k(cX) = c^k \mu_k (X).$ But only when $k=2\text{ or }3$ does it enjoy the property of additivity, which means that if $X_1,\ldots, X_n$ are independent random variables, then $\mu_k(X_1+\cdots+X_n) = \mu_k(X_1)+\cdots+\mu_k(X_n).$ However, for each $k\ge2$ there is a $k$th-degree polynomial in the first $k$ moments that simultaneously has all three properties. It is called the $k$th cumulant. The fourth cumulant is the fourth central moment minus $3$ times the square of the second central moment. (The second and third cumulants are merely the second and third central moments.) For $k\ge2,$ the cumulants are fully characterized by this description plus the condition that the coefficient of the $k$th moment is $1.$ Theorem: The exponential generating function of the sequence of cumulants (where the $1$st cumulant is $m_1$ as defined above, so it is shift-equivariant rather than shift-invariant like the higher cumulants) is the logarithm of the exponential generating function of the moments. A: There is more than one way to interpret the logarithmic derivative. One way is that it is a sequence transform related to sequence recursions. For example, suppose that we have two sequences with corresponding exponential generating functions $ A(x) = \sum_{n=0}^\infty a_n x^n/n!, \, B(x) = \sum_{n=0}^\infty b_n x^n/n! $ related such that $\, A\,'(x) = A(x) B(x). \,$ This means that $\, a_{n+1} = \sum_{k=0}^n {n \choose k} a_k b_{n-k} \,$ which is a recursion for sequence $\,a\,$ using binomial convolution with the other sequence $\,b.\,$ Another way to write the relation between the generating functions is that $\, B(x) = \log(A(x))'. \,$ Thus, $\, B(x) \,$ is the logarithmic derivative of $\, A(x). \,$ Turning this around we have $\, A(x) = \exp\big(\int B(x)\, dx\big). \,$ A simple example of this is for OEIS sequence A000085 which is the number of permutations that are involutions. One recursion is $\, a_{n+1} = a_n + n\, a_{n-1} \,$ which corresponds to $\, b_0 = b_1 = 1. \,$ Thus, the exponential generating function of the sequence is $\, A(x) = \exp(x + x^2/2!). \,$ Another simple example is for OEIS sequence A182386 which is related to derangments. One simple recursion is $\, a_{n+1} = -(n+1)a_n + 1, \,$ but more useful for our purpose is the recursion $\, a_{n+1} = \sum_{k=1}^n {n \choose k} (-1)^k k! \, a_{n-k} \,$ which implies that the exponential generating function of the sequence is $\, \exp(x)/(1+x). \,$
{ "pile_set_name": "StackExchange" }
Q: Tiled map service base layer does not display properly in ESRI Javascript map I am adding a map to a website built in asp.net and Javascript. When I add the esri.Map using a tiled map service layer base map, the map overlaps the map div and what I assume are tiles show up out of order and with spaces between them. Picture a large checkerboard with transparent squares alternating with map squares and Antarctica in the map square to the right of North America and Greenland at the bottom. There also appears to be some metadata text appearing in the div in a transparent square. There is another overlapping div that is turned off and the map div is turned on in response to a button click to display the map. A dynamic map service layer displays properly, but it behaves a bit oddly on zoom, extending to take up the whole page during the zoom, then snapping to the div when the zoom is complete. The map div is being set in css to relative position, and I've tried also giving it a set size in pixels, with no change in behavior. Originally the div was not given any position or size attributes, but the behavior was the same. I get the same result in Opera, Chrome, and Firefox. Nothing shows up in Explorer, but I think that may be a security setting issue. I'll try to attach code and screenshot of the map. Below is the javascript code adding the map. I'll just note that I've tried various extents and spatial references, including copying and pasting from standard "add a map" tutorials, so this is just what's there now. They all look the same. I've also added the basemap with addLayer by url with the same results. Javascript function to add map: function MapIt(msg) { //display map box $("div.selection-criteria").hide(); $("div.map").show(); map = new esri.Map("map", { extent: new esri.geometry.Extent({ xmin: 38.705772, ymin: -84.820221, xmax: 39.610317, ymax: -83.683907, spatialReference:{wkid:4326} }), zoom: 3, basemap: "streets" }); } ASP code for the content and divs, with the fieldsets for the div that gets hidden when the map is show obfuscated: <asp:Content ID="Content1" ContentPlaceHolderID="contentMain" runat="server"> <div class="selection-criteria"> <fieldset class="somefields"> </fieldset> <fieldset class="someotherfields"> </fieldset> <input type="button" id="btnMap" class="map-button" value="Map it!" /> </div> <div class="map" id="map"> </div> CSS div styles: div#map{position:relative; width:800px; height:400px;} ![map]: http://i.imgur.com/65yxznk.jpg A: With versions 3.2 and later of the ArcGIS JavaScript API, you are required to add their css file in order for the map to show up properly. Leaving it out would result in the checkerboard effect you noticed. For example, if you were using v.3.2, here's the link to the css you would put in your header. <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.2/js/esri/css/esri.css" /> As for later versions up to 3.5 so far, I think all you have to change is the version number in the link.
{ "pile_set_name": "StackExchange" }
Q: Laravel setting images path I'm trying to change paths for my images. The images are stored in public\image. I was using src="image/name" on my laravel project in locan and now I want to put it on the internet. But src="asset('image/logo.jpg')" doesn't work. What can I do? A: You need to use blade syntax correctly. Try using: src={{ asset('image/logo.png') }} if that doesn't work, try: src={{ url('/').'/image/logo.png' }}
{ "pile_set_name": "StackExchange" }
Q: Can I kill everybody? In Deus-Ex, I'm trying to play a run wherein the main character is a cruel, merciless cyborg who cannot distinguish between friend and foe. Basically, everybody dies. Things seemed to be going well in the first mission, where one of my comrades greeted me after I annihilated the enemy's leader and I proceeded to unload a 12 gauge into his lovable face, causing him to keel over and die. I stole his assault rifle and went down the stairs to my next friend, who told me what a great guy I was. I smiled and agreed and stabbed him 37 times in the chest. The only problem is that this didn't kill him; it caused him to get aggravated at me and shoot me with several poisonous darts as a form of comeuppance, rendering me quite dead. Are there some comrades who simply won't die and who will endure whatever pains I put them through, or do I lack the necessary firepower to eliminate them at this point? A: There are definitely characters you can't kill, or that you can't kill until certain points in the plot. I'm not sure about all of them, but Paul springs to mind in the first mission. I've unloaded a great deal of ammo into him many a time, and he just keeps running around and eventually shoots me to death with a plasma rifle. Your best bet is to save before you try to kill any main-plot characters, I suppose; hopefully that won't ruin the experience for ya.
{ "pile_set_name": "StackExchange" }
Q: Is there a generic swap method in the framework? Does a method like this exist anywhere in the framework? public static void Swap<T>(ref T left, ref T right) { T temp; temp = left; left = right; right = temp; } If not, any reason why? A: There is Interlocked.Exchange. This does it in a thread-safe, atomic call. Edit after comments: Just to clarify how this works using Interlocked.Exchange, you would do: left = Interlocked.Exchange(ref right, left); This will be the equivalent (in effect) to doing: Swap(ref left, ref right); However, Interlocked.Exchange does this as an atomic operation, so it's threadsafe. A: No, the framework does not have such a method. Probably the reason is there's not much benefit to have it built-in and you could very easily (as you did) add it yourself. This also requires use of ref as parameter, which will greatly limit the use cases. For instance, you couldn't do this: List<int> test; // ... Swap(ref test[0], ref test[1]); // won't work, it's an indexer, not an array
{ "pile_set_name": "StackExchange" }
Q: Combined box-violin plot not aligned I want to graph a distribution along two dimensions using a violinplot with a boxplot in it. The result can be really fascinating, but only when done right. ToothGrowth$dose <- as.factor(ToothGrowth$dose) head(ToothGrowth) plot <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) + geom_violin() + geom_boxplot(width=0.1) + theme(legend.position="none") ggsave(filename="Violinboxplot.png", plot, height=6, width=4) This is however what I get: The boxplots are aligned along the axis belonging to the factor. How can I shift them to be in the center of the violinplots? A: There is an answer to this question here: how to align violin plots with boxplots You can use the position argument to shift the graph elements as needed: dodge <- position_dodge(width = 0.5) ggplot(ToothGrowth, aes(x=dose, y=len, fill=supp)) + geom_violin(position = dodge) + geom_boxplot(width=.1, position = dodge) + theme(legend.position="none")
{ "pile_set_name": "StackExchange" }
Q: How do I get a blur effect in pencil drawings? When drawing pictures with a pencil, I often want to create a more or less solid darker colour in some region. It's easy to shade an area so that it appears a solid dark colour from a distance, e.g. by hatching or cross-hatching, but I'd like to be able to blur the lines in a hatched or cross-hatched area so that the darkness is uniform even when looking at the picture close up. In the past I achieved this using a special eraser I had. As an eraser it was very bad, since instead of rubbing out pencil marks it blurred them and made them spread darkly across a bigger region. This, however, made it perfect for creating uniformly dark areas in pencil drawings. Now that I don't have that eraser any more (or at least, I don't know where it is to lay my hands on it), I'd like to know a better method. After shading an area with pencil strokes, how can I blur these strokes together to get a uniformly dark region? A: The blurring you're talking about sounds like blending, which is the technique of evening out or gradating values and colors. Fingers Probably the simplest way of blending your regions together, whether matching values or values you want to merge together, is by rubbing it with your finger tip! You'll want to make sure your fingertip is clean, and oil-free, so that you don't smudge it with something else. Then, you simply rub. The direction you rub can have an effect. If you have two parallel lines and rub following their direction, you won't get much blending between them. Instead, you'll end up just blurring the lines, instead of having sharp edges. This technique is often used to blur the curved lines when shading spheres, on of the most common shading practice exercises for beginners. Blending at angles away from the lines will great a smudge of sorts that causes a gradation from the lines value to a light grey. The closer the lines, the less likely you'll run into greys. You can see this by just drawing a dark area on a blank page and smearing away, to see how your pencil and pencil pressure have affected it. You need to avoid back-and-forth strokes if you want a gradation. Always start your stroke from the darkest value and move outward. You can also blend in circles or back and forth, which may be the most helpful for trying to get a single area to be one value that's smoothed out, so the strokes don't show. Tools Now, there's also tools made specifically for this, called tortillons and blending stumps. They're made of tightly-wound paper. Tortillons being less tight than stumps, likely hollow, and you can clearly see the layers of paper, like the tip of a grease pencil. Blending stumps are so tightly wound that the seem more like a solid chunk of the paper with a point sanded off. Left: Pic courtesy rapidfireart.com. Right: The top is the back end of the tortillon, where you you can see how it's layered and hollow. The back end of the stump is more stump! These give you much more precision over the blending. They come in many sizes, which makes them more adaptable than the five sizes of your fingers. A plus to these is that as they blend, they tend to pick up more of the graphite dust in their fibers, evenly spreading it around the area and getting dust off so you don't need to use a brush or air. Your finger will end up absorbing the graphite or charcoal, but will layer it and compress it from the pressure. These can lead to you smudging dark areas of light ones accidentally if you forget to clean up. The downside is that the tortillons don't really clean up, so if they get too much graphite built up, you'll only want to use them for matching values. To counter this, most tortillons you can purchase have the ability to peel away the outside layer. Failing that, you can use a sandpaper pad, similar to what you can use to sharpen a pencil, to rub off the rough edge. In my experience, tortillons, both bought and homemade, tend to give a softer blend than stumps. I've made my own tortillons by wrapping up old drawing paper (possibly with a bad sketch on the inside) and taping the end seam. These homemade tortillons have given me the softest blends, as the dull point often frays. My homemade tortillon, not a weird cigarette. Notice the curved, feathery tip. Here's a comparison of the four tools I mentioned, using an HB pencil: The first column is blending a solid area, mostly back and forth (not against the strokes, which would blend more evenly). The stump and homemade tool hide the strokes the best, in this case. The second column is a few tight lines, stroking along them. Notice the finger smudged well outside it (oops!), and the others were more precise. However, the homemade one had much "fuzzier" edges, which can be nice. The last column is gradating out from dark. As you go down the column, you'll see each tool, in this case, was better and blending from the dark line, so there's not so much of a hard edge between the dark and light. The other thing to notice is that the strokes are almost invisible on the finger patch, and much less visible on the homemade stick. I didn't blend any two values together for this demo. You will probably not just lay down a single dark line and blend outward, like my last column. Instead, you'd create a gradation yourself by using pencil pressure and different hardness pencils, then blend those values together with your tool.
{ "pile_set_name": "StackExchange" }
Q: slimScroll 'auto': div height in percentages to work on iPhone and desktop; pushes bottom div down Apologies for the title but I couldn't think of a better way to word it. I recently stumbled upon Firebase and wanted to have a go making a simple shopping list app so my wife and I could add/remove items to it whether we were at work, home or out and on our phones. I have created this fiddle to show what I am currently doing: http://jsfiddle.net/YJQ8R/6/ I have a container div that wraps everything: #container { position: relative; margin: 0 auto; width: 400px; height: 668px; } Which is modified as follows for the iPhone: @media screen and (max-device-width: 480px){ #container { height: 100%; width: 100%; } } Along with some code I found online to disable the pinch-zoom to make it behave more like a native app, which is only added if the browser is iPhone: <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" /> The shopping list items get added to this div: #shoppingListContents { min-height: 70%; max-height: 70%; padding-top: 10px; padding-left: 5px; padding-right: 5px; } When trying to use slimScroll as follows (commented out in the fiddle as I couldn't see how to include it): $("#shoppingListContents").slimScroll({ height: 'auto', wheelStep: 2 }); to accommodate for the percentage height div, it pushes the form way down below the bottom as showin in the following image: It worked okay when I used a constant height for the slimScroll but wanted to avoid that for the iPhone. Ultimately what I would like to achieve is the use of slimScroll on the #shoppingListContents div which will take up about 70% of the container with the form at the bottom taking up 25% or so. Am open to any and all criticisms/suggestions on anything as every day is a good day to learn to do things better! NB. Stripped out the Firebase stuff as it's not relevant to the problem. A: I'm sure this is probably horrible but I was able to pretty much solve my issue with the following: if(navigator.platform === "iPhone") { containerHeight = $(window).height(); formHeight = 0.24*containerHeight; listHeight = 0.7*containerHeight - 40; $("#container").css({"height": containerHeight}); $("#shoppingListContents").css({"min-height": listHeight}); $("#shoppingListContents").css({"max-height": listHeight}); $("#shoppingListForm").css({"height": formHeight}); } 70% of the container for the list height was pushing the the form outside it so that's why there is the 40 px offset. By then setting the slimScroll height to listHeight I was able to get slimScroll working on my iPhone but it was really slow and actually took away from the normal browser scroll so I only add it for the desktop version.
{ "pile_set_name": "StackExchange" }
Q: VBA Cells.select copy paste not bringing images over consistantly I have some data and some images on a sheet. I have some code that copies the data & images from this sheet in one workbook to a sheet in another workbook. The problem: it seems to be hit or miss if it will bring over the images. Sometimes they copy, sometimes they don't WTF? wb.Sheets(form).Activate wb.Sheets(form).Cells.Select Selection.Copy objwbk.Activate ws.Range("A1").Select ActiveSheet.Paste A: Set Application.CopyObjectsWithCells = True Before copying BTW your code wb.Sheets(form).Activate wb.Sheets(form).Cells.Select Selection.Copy objwbk.Activate ws.Range("A1").Select ActiveSheet.Paste will reduce to: Application.CopyObjectsWithCells = True wb.Sheets(form).Cells.Copy ws.Range("A1")
{ "pile_set_name": "StackExchange" }
Q: Geocode sync with GoogleMaps I need to put Info Window on markers in a Google Map. I make an Ajax query to get a list of markers to draw in my map and I have a sync problem because the: geocoder.geocode( { 'address': citta}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) {} Is asynchronous so if I call it inside a loop I get the wrong results. Can anyone tell me if there is a way to do a synchronous call? A: See the following answer Google Maps API Geocode Synchronously. The answer is no.
{ "pile_set_name": "StackExchange" }
Q: Joomla Profile Custom Field Placement I just successfully added a custom field "Address" in the User Profiles using this tutorial. However, in the picture below, the custom field is in a separate <div> from the core fields. Is there any way I could have the "Address" field right below the "Confirm email Address"? Given that the tutorial never included any HTML files for layout. Thanks. A: You have to use Joomla's Override facility, that is the standard way for customizing any component views HTML according to our requirement. In JED already some extensions available to add custom registration fields you can check that too. Hope its helps..
{ "pile_set_name": "StackExchange" }
Q: GestureRecognizers does not work inside a ListView I have a ListView as follows <ListView Grid.Row="0" Margin="0" x:Name="ItemsListView" ItemsSource="{Binding SourceItems}" VerticalOptions="FillAndExpand" HasUnevenRows="false" RefreshCommand="{Binding LoadItemsCommand}" IsPullToRefreshEnabled="true" IsRefreshing="{Binding IsBusy}" ItemSelected="OnItemSelected" IsVisible="{Binding ShowListView}" RowHeight="55"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid Margin="15,0,0,0" Padding="0" RowSpacing="0" ColumnSpacing="0"> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="7*" /> <ColumnDefinition Width="1*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <Image VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" HeightRequest="35" WidthRequest="35" Grid.Row="0" Grid.Column="0" Aspect="AspectFit" Source="{Binding Icon}"> </Image> <StackLayout VerticalOptions="CenterAndExpand" Spacing="0" CompressedLayout.IsHeadless="true" Margin="15,0,0,0" Grid.Row="0" Grid.Column="1"> <Label VerticalTextAlignment="Start" Text="{Binding Name}" FontAttributes="Bold" LineBreakMode="NoWrap" Style="{DynamicResource ListItemTextStyle}" FontSize="16" /> <Label VerticalTextAlignment="Start" Text="{Binding Description}" LineBreakMode="NoWrap" Style="{DynamicResource ListItemDetailTextStyle}" FontSize="13" /> </StackLayout> <Image Grid.Row="0" Grid.Column="3" HeightRequest="20" WidthRequest="20" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Aspect="AspectFit" Source="{Binding Icon}" /> <Image BackgroundColor="Lime" Grid.Row="0" Grid.Column="2" InputTransparent="false" Margin="0,0,10,0" HeightRequest="20" WidthRequest="20" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Aspect="AspectFit" Source="ic_two"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding OnFavouriteCommand}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"> </TapGestureRecognizer> </Image.GestureRecognizers> </Image> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> and in my ViewModel I have public ICommand OnFavouriteCommand { get; set; } public MyViewModel() { OnFavouriteCommand = new Command<Object>(OnFavourite); } void OnFavourite(Object ob) { Debug.WriteLine(ob); } I don't get a Break Point hit on OnFavourite. I can't figure out what am I missing here? The idea was to get a gesture recognizers attached to each image and pass down the item bound to that row only. I've just noticed, if I bring <Image BackgroundColor="Lime" Grid.Row="1" InputTransparent="false" Margin="0,0,10,0" HeightRequest="20" WidthRequest="20" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Aspect="AspectFit" Source="ic_favourites"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding OnFavouriteCommand}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"> </TapGestureRecognizer> </Image.GestureRecognizers> </Image> Out side of the ListView the break point does get hit!. Left me scratching my head... :| A: To work gesture in listview use like this <Image BackgroundColor="Lime" Grid.Row="1" InputTransparent="false" Margin="0,0,10,0" HeightRequest="20" WidthRequest="20" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Aspect="AspectFit" Source="ic_favourites"> <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding Binding Path=BindingContext.OnFavouriteCommand,Source={x:Reference root}}" CommandParameter="{Binding .}" NumberOfTapsRequired="1"> </TapGestureRecognizer> </Image.GestureRecognizers> </Image> Here root will be page name like set X:Name of your page be root like x:Name="root" A: While what Adit wrote is true, let me give you some background. Within the DataTemplate, the BindingContext of the cells (and hence the children of them) are not set to the BindingContext of the parent (i.e. the ListView), but for each element from your ListView.ItemSource a cell is created and its BindingContext is set to that element. Otherwise you would not be able to bind the properties of the ViewCells children to your fields like Icon, Name, Description, etc. In WPF there is the possibility to bind to the parents DataContext (see here), but AFAIK this is not possible in Xamarin.Forms (see here). Therefor you'll have to reference the parent explicitly, i.e. assign a name via x:Name="Page" (or whatever name you'd like to give it) and then reference it via the Source property in your binding Command="{Binding Path=BindingContext.OnFavouriteCommand,Source={x:Reference Page}}" Since you set the binding source not the the BindingContext of Page, but to Page, you'll have to add the BindingContex to the path. Furthermore, in order to pass the element that is represented by the current cell, to the command, you'll have to set CommandParameter="{Binding .}" which binds CommandParameter to the element that is referenced by the cell (which you already did).
{ "pile_set_name": "StackExchange" }
Q: Do Calvinists rejoice in the destruction of sinners? I recently re-read "Sinners in the Hands of an Angry God" and I was struck by the pleasure Jonathan Edwards seemed to have taken in describing the imminent destruction of sinners: The God that holds you over the pit of hell, much as one holds a spider, or some loathsome insect over the fire, abhors you, and is dreadfully provoked: his wrath towards you burns like fire; he looks upon you as worthy of nothing else, but to be cast into the fire; he is of purer eyes than to bear to have you in his sight; you are ten thousand times more abominable in his eyes, than the most hateful venomous serpent is in ours. You have offended him infinitely more than ever a stubborn rebel did his prince; and yet it is nothing but his hand that holds you from falling into the fire every moment. It is to be ascribed to nothing else, that you did not go to hell the last night; that you was suffered to awake again in this world, after you closed your eyes to sleep. And there is no other reason to be given, why you have not dropped into hell since you arose in the morning, but that God's hand has held you up. There is no other reason to be given why you have not gone to hell, since you have sat here in the house of God, provoking his pure eyes by your sinful wicked manner of attending his solemn worship. Yea, there is nothing else that is to be given as a reason why you do not this very moment drop down into hell. One can almost see Edwards "rubbing his hands together gleefully and cackling a little" over the plight of unbelievers. Is this attitude toward the damned common among Calvinists? Is it a necessary conclusion from their particular set of assumptions? A: My Thesis While you won't find many modern Calvinists preaching firebrand sermons of this sort, that has more to do with the change in American culture than with a change in theology. The point of the sermon is not to rejoice in the suffering of sinners, but to warn of the very real danger (under Calvin's theology) of falling into hell. Edwards was warning against a false sense of security based on striving for holiness rather than relying on the grace of God. The Great Awakening It's hard to emphasize the difference between the way sermons from the First Awakening are viewed now compared to the way they were viewed at the time. For one thing, unlike later revival movements, the target of Edwards' and Whitefield's sermons were very devote, conservative, religious, churchgoing Christians. In other words, when Edwards says, "he looks upon you as worthy of nothing else, but to be cast into the fire" we need to picture folks who resemble Westboro Baptist Church1, not the people they attack. Edwards was actually addressing a church that fit into the stereotype of intolerant Puritanism: How dreadful is the state of those that are daily and hourly in the danger of this great wrath and infinite misery! But this is the dismal case of every soul in this congregation that has not been born again, however moral and strict, sober and religious, they may otherwise be. Oh that you would consider it, whether you be young or old! There is reason to think, that there are many in this congregation now hearing this discourse, that will actually be the subjects of this very misery to all eternity. We know not who they are, or in what seats they sit, or what thoughts they now have. It may be they are now at ease, and hear all these things without much disturbance, and are now flattering themselves that they are not the persons, promising themselves that they shall escape. The picture Edwards paints is not a crowd of Christians rejoicing over the destruction of evil, but a congregation that feels pretty self-righteous and confident that hell is the destination of other people. The Great Awakening has sometimes been credited with breaking up the conservative hold on American and fueling (in part) the American Revolution. The Danger of Hell Calvinists tend to be more sympathetic to this sort of firebrand preaching since they believe a literal hell exists to punish sinners. Warning people about the danger of hell is actually loving in this context. If you happen to know that there's a speed trap ahead, it's a kindness to tell the driver that they might want to slow down. At least part of the revulsion to hell-fire and damnation sermons comes from folks who don't believe hell exists or that sin carries any eternal consequences.2 Further, Calvinists are especially known for believing, along with Paul, that: For there is no distinction: for all have sinned and fall short of the glory of God,—Romans 3:22-23 (ESV) and: But because of your hard and impenitent heart you are storing up wrath for yourself on the day of wrath when God's righteous judgment will be revealed.—Romans 2:5 (ESV) A Gracious Solution In our eagerness to read the shocking bits of sermons such as "Sinners in the Hands of an Angry God", we skip over or forget impassioned pleas for sinners to find salvation: And now you have an extraordinary opportunity, a day wherein Christ has thrown the door of mercy wide open, and stands in calling and crying with a loud voice to poor sinners; a day wherein many are flocking to him, and pressing into the kingdom of God. Many are daily coming from the east, west, north and south; many that were very lately in the same miserable condition that you are in, are now in a happy state, with their hearts filled with love to him who has loved them, and washed them from their sins in his own blood, and rejoicing in hope of the glory of God. How awful is it to be left behind at such a day! To see so many others feasting, while you are pining and perishing! To see so many rejoicing and singing for joy of heart, while you have cause to mourn for sorrow of heart, and howl for vexation of spirit! How can you rest one moment in such a condition? Are not your souls as precious as the souls of the people at Suffield, where they are flocking from day to day to Christ? The point wasn't to enjoy the suffering of others, but to wake people up to the problem and point them to the solution. Whether or not we agree that the problem exists or agree with the proposed solution, we must not assume that Calvinists are pleased to see others suffer anymore than God is: But if a wicked person turns away from all his sins that he has committed and keeps all my statutes and does what is just and right, he shall surely live; he shall not die. None of the transgressions that he has committed shall be remembered against him; for the righteousness that he has done he shall live. Have I any pleasure in the death of the wicked, declares the Lord GOD, and not rather that he should turn from his way and live? But when a righteous person turns away from his righteousness and does injustice and does the same abominations that the wicked person does, shall he live? None of the righteous deeds that he has done shall be remembered; for the treachery of which he is guilty and the sin he has committed, for them he shall die.—Ezekiel 18:21-24 (ESV) Conclusion Frankly, the idea that Calvinists enjoy talking about the damnation of sinners or feel good about themselves for being better/chosen/more-worthy than others is an unwarranted stereotype. While there are certainly folks who live into that ugly picture, I find most Calvinists to be about the same as other folks in terms of pride, humility, kindness, and cruelty. If anything, Calvinist theology should lead people to be more humble and kind than normal, though evaluating that statement is beyond our scope. Footnotes: These jerks are by no means the only group giving Calvinism a bad name. They are, however the most "successful" at leading a compliant media to a juicy, but empty, story. I was surprised to learn that the doctrine of universal salvation is among the beliefs circulating in Edwards' time. A: I believe you are misreading the intent of the sermon. For some historical context, here is an excellent essay When Jonathan Edwards preached during July, twelve slaves had already been burned and nine were hanged, and the minister had no way of knowing how the horror would end. So he was describing what God would do to us, were it not for grace, in the very same terms that were being done to real people nearby. Jonathan Edwards did not create terrifying visions of torture in order to hurl his people into despair. The congregation, unwilling to accept any responsibility for slavery and its trade, needed "Sinners in the Hands of an Angry God" to ease the intolerable pangs of conscience that were provoked by the events in New York. There was real evil afoot in America at the time, and Edwards was taking a necessary step towards ridding the country of it. A: Some do, some don't. Dividing lines aren't completely cut-and-dry, but it is a controversial question among reformed folk. Generally, you'll find "yeses" among cage-stage Calvinists, and also among more confessional Presbyterians, such as those in the ARP or RPCNA, thought it's probably a minority view even in those churches. You'll find more "nos" in mainline and evangelical churches, as well as the less confessional or more baptistic churches. "Yes" is definitely a minority view in general. In the following I will endeavor to provide quotes that accurately represent both sides, including the theological or Biblical basis for their answer. Yes Paul Washer says in "The Cross of Christ" (see a related question): It is not an exaggeration to say that the last thing that the accursed sinner should and will hear when he takes his first step into hell is all of creation standing to its feet and applauding God because He has rid the earth of him. Such is the vileness of those who break God’s law, and such is the disdain of the holy towards the unholy. C. Matthew McMahon says on page 349 of The Two Wills of God: The saints should delight in the reprobation of the wicked, thought that be a most difficult statement to make. Augustine, as a result of Paul's exquisite explanations of election and reprobation in Romans 9, came to the same conclusion. ... We come to understand and praise God concerning the damnation of other people. We understand that we could have been what they are. We contemplate their eternal destiny, and bow before the throne to praise the Creator and the Father we have. How awesome is that grace which He bestowed upon us in His Son! McMahon's reference to Augustine is this quote from Against Two Letters of the Pelagians, Book IV, chapter 16: And hence, let the vessels of mercy understand how freely mercy is afforded to them, because to the vessels of wrath with whom they have common cause and measure of perdition, is repaid wrath, righteous and due. No The great reformed theologian Herman Bavinck says in Reformed Dogmatics: God is removed from all wickedness and does not will sin and punishment as such and for its own sake nor delight as such in reprobation. Wayne Grudem, a reformed baptist, says in his Systematic Theology: Reprobation is viewed as something that brings God sorrow, not delight (see Ezek. 33:11). ... The sorrow of God at the death of the wicked ... helps us understand how appropriate it was that Paul himself felt great sorrow when he thought about the unbelieving Jews who had rejected Christ [referring to Romans 9:1-4]. John Piper says in his sermon Palm Sunday Tears of Sovereign Mercy: I appeal to you here: pray that God would give you tears. There is so much pain in the world. So much suffering far from you and near you. Pray that God would help you be tenderly moved. When you die and stand before the Judge, Jesus Christ, and he asks you, "How did you feel about the suffering around you?" what will you say? I promise you, you will not feel good about saying, "I saw through to how a lot of people brought their suffering upon themselves by sin or foolishness." You know what I think the Lord will say to that? I think he will say, "I didn't ask you what you saw through. I asked you what you felt?" Jesus felt enough compassion for Jerusalem to weep. If you haven’t shed any tears for somebody's losses but your own, it probably means you’re pretty wrapped up in yourself. So let's repent of our hardness and ask God to give us a heart that is tenderly moved. Herman Hoeksema says in "The Place of Reprobation in the Preaching of the Gospel": God does not desire the destruction of the reprobate in the same way in which He delights in the salvation and glory of His chosen people. ... It is also evident that, when preaching on election and reprobation, we must not place them dualistically over against each other. They are not on the same level. They are not corresponding halves of the same thing, but together they form a unity. Reprobation should always be presented as subordinate to election, as serving the latter according to God's counsel. From this it follows that reprobation should not be preached with a certain delight in the doctrine. He who is forever preaching reprobation shows not only that he is harsh and cruel, but also that he has not understood the work of the Lord God. God's love remains the central thought. He has chosen in His eternal love; and, for the sake of this love, He has also reprobated. Thus all God's work becomes a beautiful organic unity. In this way He is and remains God, and He alone. Thus, at the conclusion of all this, we exclaim in adoration with the apostle, "Oh, the depth of the riches both of the wisdom and knowledge of God; for of him and through him and to him are all things! To him be glory forever!"
{ "pile_set_name": "StackExchange" }
Q: Creating a database view from a dynamic string (EXECUTE IMMEDIATE) in a PL/SQL package - Questions? I want to create a dynamic view at runtime made up of string of columns and a where clause using EXECUTE IMMEDIATE on one database which will be queried on a second database using a db_link. My question are the following. The view will be queried on another database using a database_link do I need to also GRANT privileges to the view (i.e. PUBLIC) and the SYNONYM (as PUBLIC) at the same time (if at all)? or does this only need to be created once? Can a package be INVALID if in the PL/SQL package there is a reference to an object on another database via a database link that doesn't exist, is INVALID or has changed in structure? Or does it compile regardless? I'm assuming I would need "CREATE OR REPLACE VIEW" in the the EXECUTE IMMEDIATE string as the second time I run this process the view will already exist on the database? Thanks Guys in advance for any feedback on this. A: First of all, I'd suggest you not to do that. In Oracle, objects are created once and used any time you want. What benefit do you expect from creating a view dynamically? (I'm not saying that you must not do it, just suggesting to think it over). Now, to answer your questions: You don't need GRANT because - in order to create a database link, you already know remote database's username and password If object in another database is invalid, then executing or compiling your procedure will fail Yes, as without or replace Oracle will complain that object with that name already exists.
{ "pile_set_name": "StackExchange" }
Q: Find and replace string in folder name using command line How can I replace a string in all my folder names in one directory. For example if I have these folders hellojoe hellomary hellosusan I want to change these to worldjoe worldmary worldsusan A: Using this command works find . -name 'hello*' -exec bash -c 'mv "$1" "${1/hello/world}"' -- {} \;
{ "pile_set_name": "StackExchange" }
Q: What is the solr dynamic field one should use for a large base64 string? What is the best solr dynamic field type to use for a long base64 string? In my case, I am wanting a solr field with a base64 representation of an image. We use dynamic fields in schema so I'm looking for the right one to use. I was going to use _txt but am really unsure of my choice here. What is the best choice of dynamic field to use for long base64 strings? Note: I am referring to the default built-in dynamic field mappings. A: Binary field is the best bet otherwise. You want a non-analyzed field that just stores the data - so using something that maps to the string type is a good choice. Depending on which schema you're using, they might be mapped to *_s as a dynamic field entry. You do not want to use any text field, as they're analyzed and split into separate tokens. You also want to set stored="true" indexed="false" and probably disable docValues - this field isn't going to be used for anything other than retrieval. I don't think there's any "built-in" dynamic field mappings any longer, as most examples have their own definitions.
{ "pile_set_name": "StackExchange" }
Q: How can I get the data transfered data from jQuery.getJSON within the PHP file? I have a Javascript variable whatToRefresh which is defined in this way: var whatToRefresh = { "online" : true, "running" : false, "detail" : 0 }; This variable is used within a getJSON to tell the php file what data are requested: $.getJSON("scripts/php/RequestData.php", whatToRefresh, function(data) { PopulateData(data); }); Now I need the data within the PHP file but this returns all the time null: $requestData = json_decode(($_GET['data']), true); How can I access this data within php? A: just access $_GET['online'], $_GET['running'], $_GET['detail']. try to see that - var_dump($_GET); A: Where you're getting confused is, the $.getJSON method. JSON is not being sent to the server, so you do not need to decode it with json_decode. This jQuery method is just sending an HTTP get request, with a query string that has your variables in it. The $.getJSON method expects to see a JSON response from the server, hence the json in the name.
{ "pile_set_name": "StackExchange" }
Q: Is Portable.BouncyCastle cross-platform? Will Portable.BouncyCastle works on Linux & MacOS if I reference it from an ASP.NET Core 2 web application? Will my ASP.NET Core 2 app still be cross-platform compatible? A: Yes, Portable.BouncyCastle targets .NET Standard, which represents a common set of functionality between .NET implementations, including .NET Core on different platforms. From the .NET Standard FAQ: .NET Standard is a specification that represents a set of APIs that all .NET platforms have to implement. This unifies the .NET platforms and prevents future fragmentation. Think of .NET Standard as POSIX for .NET. See Microsoft's .NET Standard Guide for more details.
{ "pile_set_name": "StackExchange" }
Q: In Javafx, does mouseReleased event always happen before mouseClicked? Which event is fired first? Does it depend on initialization order? Does it depend on something else? What is the principle behind this? pane.setOnMouseClicked(e -> { doSomething(); }); pane.setOnMouseReleased(e -> { doSomething(); }); A: You are actually adding an event handler to your Node, which handles a specific type of a MouseEvent. ( Have a look at Handling JavaFX Events as well ) If you take a look at MouseEvent documentation you will see : MOUSE_PRESSED public static final EventType<MouseEvent> MOUSE_PRESSED This event occurs when mouse button is pressed. This activates a press-drag-release gesture, so all subsequent mouse events until the button is released are delivered to the same node. MOUSE_RELEASED public static final EventType<MouseEvent> MOUSE_RELEASED This event occurs when mouse button is released. It is delivered to the same node where the button has been pressed which activated a press-drag-release gesture. MOUSE_CLICKED public static final EventType<MouseEvent> MOUSE_CLICKED This event occurs when mouse button has been clicked (pressed and released on the same node). This event provides a button-like behavior to any node. Note that even long drags can generate click event (it is delivered to the top-most node on which the mouse was both pressed and released). So to answer your question yes, the order of events is always : MOUSE_PRESSED -> MOUSE_RELEASED -> MOUSE_CLICKED
{ "pile_set_name": "StackExchange" }
Q: Is there any way to return a single image for every images call in a folder use Codeigniter? I am working on a social media project where I have a huge amount of images which I don't want to move it to my beta development server. For every profile picture I want to include from e.g images/profile folder I want php to return a single image e.g images/profile/nophoto.jpg as there is no photos for the profile pictures in this folder. I have a helper class where I have a function profileicon() which will return me the profile images from the folder specified but that can't be used every where. In most cases I have used simply base_url and path to images. if(ENVIRONMENT == 'development') { //some code to do the magic } I think we can do something in routes folder to do this magic or may be the uploads folder it self? Thank you, all A: I think you've made different folders for different user. But you don't want to show folders which are empty. Good practice is , You will have to check condition before showing image. if(file_exist('path/'.$image)){ //then show image . } You can also show a default image if image is not exist in database. I hope this will give an option to handle your several folders for users. if(file_exist('path/'.$image)){ //then show image . }else{ //show image }
{ "pile_set_name": "StackExchange" }
Q: Task synchronization without a UI thread In the code below I want to syncronize the reporting of the results of a list of tasks. This is working now because task.Result blocks until the task completes. However, task id = 3 takes a long time to complete and blocks all of the other finished tasks from reporting their status. I think that I can do this by moving the reporting (Console.Write) into a .ContinueWith instruction but I don't have a UI thread so how do I get a TaskScheduler to syncronize the .ContinueWith tasks? What I have now: static void Main(string[] args) { Console.WriteLine("Starting on {0}", Thread.CurrentThread.ManagedThreadId); var tasks = new List<Task<int>>(); for (var i = 0; i < 10; i++) { var num = i; var t = Task<int>.Factory.StartNew(() => { if (num == 3) { Thread.Sleep(20000); } Thread.Sleep(new Random(num).Next(1000, 5000)); Console.WriteLine("Done {0} on {1}", num, Thread.CurrentThread.ManagedThreadId); return num; }); tasks.Add(t); } foreach (var task in tasks) { Console.WriteLine("Completed {0} on {1}", task.Result, Thread.CurrentThread.ManagedThreadId); } Console.WriteLine("End of Main"); Console.ReadKey(); } I would like to move to this or something similar but I need the Console.Write("Completed...") to all happen on the same thread: static void Main(string[] args) { Console.WriteLine("Starting on {0}", Thread.CurrentThread.ManagedThreadId); for (var i = 0; i < 10; i++) { var num = i; Task<int>.Factory.StartNew(() => { if (num == 3) { Thread.Sleep(20000); } Thread.Sleep(new Random(num).Next(1000, 10000)); Console.WriteLine("Done {0} on {1}", num, Thread.CurrentThread.ManagedThreadId); return num; }).ContinueWith(value => { Console.WriteLine("Completed {0} on {1}", value.Result, Thread.CurrentThread.ManagedThreadId); } /* need syncronization context */); } Console.WriteLine("End of Main"); Console.ReadKey(); } -- SOLUTION -- After getting some comments and reading some of the solutions this is the complete solution that does what I want. The goal here is to process severl long running tasks as fast as possible and then do something with the results of each task one at a time. static void Main(string[] args) { Console.WriteLine("Starting on {0}", Thread.CurrentThread.ManagedThreadId); var results = new BlockingCollection<int>(); Task.Factory.StartNew(() => { while (!results.IsCompleted) { try { var x = results.Take(); Console.WriteLine("Completed {0} on {1}", x, Thread.CurrentThread.ManagedThreadId); } catch (InvalidOperationException) { } } Console.WriteLine("\r\nNo more items to take."); }); var tasks = new List<Task>(); for (var i = 0; i < 10; i++) { var num = i; var t = Task.Factory.StartNew(() => { if (num == 3) { Thread.Sleep(20000); } Thread.Sleep(new Random(num).Next(1000, 10000)); Console.WriteLine("Done {0} on {1}", num, Thread.CurrentThread.ManagedThreadId); results.Add(num); }); tasks.Add(t); } Task.Factory.ContinueWhenAll(tasks.ToArray(), _ => results.CompleteAdding()); Console.WriteLine("End of Main"); Console.ReadKey(); } A: You'll have to create a writer task of some sort, however, keep in mind even this task can be rescheduled onto another native or managed thread! Using the default scheduler in TPL you have no control over which managed thread receives the work. public class ConcurrentConsole { private static BlockingCollection<string> output = new BlockingCollection<string>(); public static Task CreateWriterTask(CancellationToken token) { return new Task( () => { while (!token.IsCancellationRequested) { string nextLine = output.Take(token); Console.WriteLine(nextLine); } }, token); } public static void WriteLine(Func<string> writeLine) { output.Add(writeLine()); } } When I switched your code to use this I received the following output: End of Main Done 1 on 6 Completed 1 on 6 Done 5 on 9 Completed 5 on 9 Done 0 on 4 Completed 0 on 4 Done 2 on 5 Completed 2 on 13 Done 7 on 10 Completed 7 on 10 Done 4 on 8 Completed 4 on 5 Done 9 on 12 Completed 9 on 9 Done 6 on 6 Completed 6 on 5 Done 8 on 11 Completed 8 on 4 Done 3 on 7 Completed 3 on 7 Even with your code sending () => String.Format("Completed {0} on {1}"... to ConcurrentConsole.WriteLine, ensuring the ManagedThreadId would be picked up on the ConcurrentConsole Task, it still would alter which thread it ran on. Although with less variability than the executing tasks.
{ "pile_set_name": "StackExchange" }
Q: Python Turtle how to draw a marker inside a cell in a 7x7 grid I'm new to using Turtle graphics in Python 3, and I'm at a loss on what to do. One of my problems is that I have no idea where to begin with creating a function that will draw a marker inside of a grid cell based on a data set called 'path' containing 3 variables. The grid map itself is 7x7 and there's 5 markers in total (ranging from 0 to 4). Each marker draws its own social media logo and are completely different from each other. grid_cell_size = 100 # px num_squares = 7 # this for creating the 7x7 grid map # for clarification: path = ['Start', location, marker_value] path = [['Start', 'Centre', 4], ['North', 2, 3], ['East', 2, 2], ['South', 4, 1], ['West', 2, 0]] My main goal is to be able to draw all 5 markers at once in their own location coordinates using the above data set. I'm not sure how should I approach with assigning these markers to their own marker_value. Would an if/elif/else statement work for this? Trying to implement 5 markers at once is too overwhelming for me so I've tried using this very simple data set called 'path_var_3' that will only draw 1 marker. path_var_3 = [['Start', 'Bottom left', 3]] def follow_path(path_selection): # Draws YouTube logo marker if 3 in path_var_3[0]: penup() # !!! goto(0, -32) setheading(90) # Variables youtube_red = '#ff0000' youtube_white = 'White' radius = 10 diameter = radius * 2 # Prep to draw the superellipse pencolor(youtube_red) fillcolor(youtube_red) # Drawing the superellipse begin_fill() pendown() for superellipse in range(2): circle(radius, 90) forward(80) circle(radius, 90) forward(60 - diameter) # Finish up end_fill() penup() # Move turtle position towards the centre of the superellipse # !!! goto(-59) backward(16) setheading(90) fillcolor(youtube_white) # Drawing the white 'play icon' triangle begin_fill() pendown() for play_triangle in range(2): right(120) forward(28) right(120) forward(28) # Finish up endfill() penup() else: return print('ERROR') follow_path(path_var_3) So far I was able to draw the marker in the program, but immediately I've encountered my first problem: I've realised that I've hardcoded the coordinates of where the superellipse and the triangle will begin to draw at, as indicated with the '!!!' comments. So when I run the program the marker is drawn outside of the grid cell. How do I get the marker to be drawn INSIDE a cell, regardless of where the cell is located within the 7x7 grid map? If anyone has any ideas or is able to help I will greatly appreciate it. TL;DR: How do I draw a marker, consisting of various shapes, inside the 100x100 cell within the 7x7 grid map? How do I draw a marker in any cell based on the location variable from a data set? How should I approach with assigning markers to integers ranging 0-4? If/elif/else statements? A: The code you provided isn't runnable due to goto(-59) and endfill() not being valid function calls. In the large, your code is lacking a layer to organize the problem you're trying to solve. (E.g. you need to define code-wise what 'Bottom left' or 'East' mean.) In the small, your YouTube logo drawing is using absolute coordinates instead of relative, preventing it from being drawn anywhere. Below is a skeletal implementation of what you describe. It draws a grid for debugging purposes to show that logos are ending up in the correct locations. It substitutes colored circles for all but the YouTube logo: from turtle import Turtle, Screen path = [('Start', 'Centre', 4), ('North', 2, 3), ('East', 2, 2), ('South', 4, 1), ('West', 2, 0)] GRID_CELL_SIZE = 100 # pixels NUMBER_SQUARES = 7 # this for creating the 7x7 grid map ABSOLUTE_OFFSETS = { 'Centre': (NUMBER_SQUARES // 2, NUMBER_SQUARES // 2), 'Bottom left': (0, NUMBER_SQUARES - 1), # etc. } COMPASS_OFFSETS = { 'North': (0, 1), 'East': (1, 0), 'South': (0, -1), 'West': (-1, 0), 'Start': (1, 1), # Special case, assumes absolute offset } # YouTube Variables YOUTUBE_RED = '#ff0000' YOUTUBE_WHITE = 'White' YOUTUBE_RADIUS = 10 YOUTUBE_WIDTH = 80 YOUTUBE_HEIGHT = 60 YOUTUBE_TRIANGLE_EDGE = 28 def draw_grid(): # for debugging grid = Turtle(visible=False) grid.speed('fastest') grid.dot() # visualize origin grid.penup() grid.goto(-GRID_CELL_SIZE * NUMBER_SQUARES / 2, GRID_CELL_SIZE * (NUMBER_SQUARES / 2 - 1)) for _ in range(NUMBER_SQUARES - 1): grid.pendown() grid.forward(NUMBER_SQUARES * GRID_CELL_SIZE) grid.penup() grid.goto(-GRID_CELL_SIZE * NUMBER_SQUARES / 2, grid.ycor() - GRID_CELL_SIZE) grid.goto(-GRID_CELL_SIZE * (NUMBER_SQUARES / 2 - 1), GRID_CELL_SIZE * NUMBER_SQUARES / 2) grid.setheading(270) for _ in range(NUMBER_SQUARES - 1): grid.pendown() grid.forward(NUMBER_SQUARES * GRID_CELL_SIZE) grid.penup() grid.goto(grid.xcor() + GRID_CELL_SIZE, GRID_CELL_SIZE * NUMBER_SQUARES / 2) def follow_path(path_selection): turtle = Turtle(visible=False) x, y = ABSOLUTE_OFFSETS['Centre'] # relative to grid, not screen! for direction, offset, marker in path_selection: if direction in COMPASS_OFFSETS: dx, dy = COMPASS_OFFSETS[direction] if offset in ABSOLUTE_OFFSETS: x, y = ABSOLUTE_OFFSETS[offset] else: x += dx * offset y += dy * offset turtle.penup() # new virtual drawing origin, convert to screen coordinates turtle.goto((x - NUMBER_SQUARES // 2) * GRID_CELL_SIZE, (y - NUMBER_SQUARES // 2) * GRID_CELL_SIZE) MARKERS[marker](turtle) turtle.penup() def YouTube(turtle): diameter = YOUTUBE_RADIUS * 2 x, y = turtle.position() # Draws YouTube logo marker turtle.goto(x + YOUTUBE_WIDTH/2 + YOUTUBE_RADIUS, y + YOUTUBE_HEIGHT/2 - YOUTUBE_RADIUS) turtle.setheading(90) # Draw the rounded rectangle (should really be a superellipse) turtle.color(YOUTUBE_RED) turtle.begin_fill() for _ in range(2): turtle.circle(YOUTUBE_RADIUS, 90) turtle.forward(YOUTUBE_WIDTH) turtle.circle(YOUTUBE_RADIUS, 90) turtle.forward(YOUTUBE_HEIGHT - diameter) # Finish up turtle.end_fill() # Return turtle position towards the centre of the rounded rectangle turtle.goto(x - YOUTUBE_TRIANGLE_EDGE/4, y + YOUTUBE_TRIANGLE_EDGE/2) turtle.setheading(90) # Drawing the white 'play icon' triangle turtle.fillcolor(YOUTUBE_WHITE) turtle.begin_fill() for _ in range(2): turtle.right(120) turtle.forward(YOUTUBE_TRIANGLE_EDGE) # Finish up turtle.end_fill() def RedDot(turtle): turtle.dot(GRID_CELL_SIZE / 2, 'Red') def BlueDot(turtle): turtle.dot(GRID_CELL_SIZE / 2, 'Blue') def GreenDot(turtle): turtle.dot(GRID_CELL_SIZE / 2, 'Green') def OrangeDot(turtle): turtle.dot(GRID_CELL_SIZE / 2, 'Orange') MARKERS = [RedDot, BlueDot, GreenDot, YouTube, OrangeDot] screen = Screen() draw_grid() # for debugging follow_path(path) screen.mainloop()
{ "pile_set_name": "StackExchange" }
Q: How to change Build Numbering format in Visual Studio I've inherited a .NET application that automatically updates it's version number with each release. The problem, as I see it, is the length and number of digits in the version number. An example of the current version number format is 3.5.3167.26981 which is a mouthful for the users to say when they are reporting bugs. What I would like is something more like this: 3.5 (build 3198). I would prefer to manually update the major and minor versions, but have the build number update automatically. Even better, I don't want the build number to increment unless I am compiling in RELEASE mode. Anyone know if there is a way to do this -- and how? A: In one of the project files, probably AssemblyInfo.cs, the assembly version attribute is set to [assembly: AssemblyVersion("3.5.*")] or something similar. The * basically means it lets Visual Studio automatically set the build and revision number. You can change this to a hard coded value in the format <major version>.<minor version>.<build number>.<revision> You are allowed to use any or all of the precision. For instance 3.5 or 3.5.3167 or 3.5.3167.10000. You can also use compiler conditions to change the versioning based on whether you're doing a debug build or release build.
{ "pile_set_name": "StackExchange" }
Q: How do I access an array in an array of class instances? I'm trying to practice making list apps with models by making a class to represent each list item. I have a Category class which contains three properties - two strings and one array of strings. Here is the class: class Category { var name: String var emoji: String var topics: [String] // (the getCategories method listed below goes here) // init(name: String, emoji: String, topics: [String]) { self.name = name self.emoji = emoji self.topics = topics } In my Category class I have a method to assign values to the categories so I can keep them out of the view controller. This method is listed below: class func getCategories() -> [Category] { let categories = [Category(name:"cat", emoji:"", topics: ["paws","tails", "fur", "pussyfoot","purr", "kitten", "meow"]) ] return categories } In one of my tableview controller files I am trying to get the number of rows in section by setting it to the count of the topics from the topics in the getCategories method. Nothing I do seems to work, although I am able to get the count of the categories in the getCategories method...I just seem to be unable to access the topics array specifically. Here's what I did to get the categories count... var categories = Category.getCategories() .... override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories.count } I need to do this except I need to get the count of the topics that I set in the getCategories method. Thanks so much! :) A: The piece I think you are missing is that you need to know which section you want to get the topic count from. This should be provided to you in some why by the table view datasource callback. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories[section].topics.count } In addition, when you need to access a specific topic, you will be passed an indexPath. func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let topic = categories[indexPath.section].topics[indexPath.row] let cell = … … return cell }
{ "pile_set_name": "StackExchange" }
Q: How to get a cat to stop chewing on cords? Title says it all. Is there some way to get a cat to stop chewing on cords. I have a lot of corded things lying around and my cat likes to play with them. He crawls under my computer desk and bats my phone charger cord out of my phone and I even catch him chewing on my snake thermostats sometimes. Is there some way to discourage or outright prevent this behavior? A: I rubbed lemon juice on my cat's favorite cords and that seems to have deterred the behavior, but I'm not sure if it's due to the lemon or that he's just moved on. Supposedly, cats hate citrus. "Critter cords" may help in the meantime (plastic cord covers that slip over chargers, etc. and prevent the cat's teeth from doing damage). If there's a certain area he likes, maybe try a Sssscat. (It's a motion-activated can of compressed air that usually scares the life out of the cat). Has worked to keep my cat off of the counter, it may work to keep yours away from the thermostat area.
{ "pile_set_name": "StackExchange" }
Q: OpenLayers 3 show/hide layers I am creating an application which utilises a map created and managed by the OpenLayers 3 library. I want to be able to switch which layer is visible using the zoom level (i.e. zoom out to get an overview of countries, zoom in to get an overview of cities). There are three categories of layers (3 different zoom levels), and within each category there are 3 colours which the pins I am using could be (which are all separate layers as well) so in total there are 9 layers. What I want is to develop the ability to filter which layers are displayed, which means showing/hiding the existing layers depending on which zoom level we are at. There is some code to demonstrate how the map is generated and how one type of layer is generated but if there is more detail required please let me know. I don't believe there will be an issue with this, however. function setUpMap(vectorLayers, $scope){ var view = new ol.View({ center: ol.proj.fromLonLat([2.808981, 46.609599]), zoom: 4 }); map = new ol.Map({ target: 'map', layers: vectorLayers, overlays: [overlay], view: view }); view.on("change:resolution", function(e){ var oldValue = e.oldValue; var newValue = e.target.get(e.key); if (newValue > 35000){ if (oldValue < 35000) //This is where I will show group 1 } else if (newValue > 10000){ if (oldValue < 10000 || oldValue > 35000) //This is where I will show group 2 } else { if (oldValue > 10000) //This is where I will show group 3 } }); addClickEventsToMapItems($scope); } I tried something like this and got no success: function showLayer(whichLayer){ vectorLayers[1].setVisibility(false); vectorLayers[2].setVisibility(false); vectorLayers[3].setVisibility(false); vectorLayers[whichLayer].setVisibility(true); } I am open to suggestions. Please let me know! :) A: You can listen to the resolution:change event on your ol.Map instance: map.getView().on('change:resolution', function (e) { if (map.getView().getZoom() > 0) { vector.setVisible(true); } if (map.getView().getZoom() > 1) { vector.setVisible(false); } }); Example on Plunker: http://plnkr.co/edit/szSCMh6raZfHi9s6vzQX?p=preview It's also worth to take a look at the minResolution and maxResolution options of ol.layer which can switch automaticly for you. But it works by using the view's resolution, not the zoomfactor: http://openlayers.org/en/v3.2.1/examples/min-max-resolution.html
{ "pile_set_name": "StackExchange" }
Q: How can I install a go package with MinGW which depends on libiconv I am currently trying to set up a Go project, and considering I am running Windows, while the other 2 developers are working on a Mac, I have some trouble with installing a few packages. After trying to install the packages with cmd, I was only able to install 2 out of 4. The other two needed gcc. Therefore, I installed MinGW. I was able to install a third package that way, but now I am stuck on https://github.com/mikkyang/id3-go. It seems to depend on another underlying project, https://github.com/djimenez/iconv-go. The moment I try to go install id3-go, I am always left with this error: src\github.com\djimenez\iconv-go\converter.go:8:19: fatal error: iconv.h: No such file or directory Somehow, I need to use libiconv with MinGW, but I have no idea how to connect both parts. I'm not really an expert in that field, so any help would be appreciated a lot. I already downloaded libiconv for Windows. Related issue for additional information I found on the github project: https://github.com/mikkyang/id3-go/issues/21 EDIT: I made some progress on the whole problem. I now got all the files I need, but now I am stuck with this warning: # github.com/djimenez/iconv-go E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -liconv collect2.exe: error: ld returned 1 exit status I tried to add the libiconv2.a from my libiconv installation to the mingw32 lib folder, but then this is what I end up with: # github.com/djimenez/iconv-go E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/../lib\libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib\libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/lib/libiconv.a when searching for -liconv E:/Tools/TDM-GCC/bin/../lib/gcc/x86_64-w64-mingw32/5.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -liconv collect2.exe: error: ld returned 1 exit status I have no idea how to proceed from here. A: I've met the same problem when I want to go install github.com/google/gopacket which need CGO. It's because your libiconv2.a is generated by other compiler, so it's incompatible with mingw32 compiler as the error message says. We need generate the static lib with the mingw32 toolset: find libiconv-2.dll(the coresonding dynamic library) in your PC run gendef(located in C:\TDM-GCC-64\x86_64-w64-mingw32\bin in my 64-bit Windows ) on those files gendef libiconv-2.dll, this will generate libiconv2.def file Then generate the static library: dlltool --as-flags=--64 -m i386:x86-64 -k --output-lib libiconv2.a --input-def libiconv2.def copy libiconv2.a to proper location.
{ "pile_set_name": "StackExchange" }
Q: LINQPad Query Error Problem: Can't properly setup LINQPad connection to my Entity Framework dll. I downloaded LINQPad (v4.42.01) I started to create a new connection using the Entity Framework DbContext POCO driver At the setup dialog I pointed to my C# project's dll and it found the appropriate DbContext class. Next I pointed the config file to the app.config of my C# project When I hit the Test Button I get this error: Error: The type initializer for 'System.Data.Entity.Internal.AppConfig' thre an exception. An error occurred creating the configuration section handler for entityFramework: Could not load file or assembly 'EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' on one of its dependencies. The system cannot find the file specified. (C:\Code\NET\FTI_Opp_Model\App.Config line 5) So I tried doing what @Sorax did in this related question and moved my EntityFramework.dll from the one I got from NuGet in my project into the LINQPad.exe folder. This got me a little further along and the Test now worked. I was encouraged because my connection in the LINQPad panel showed all my entities underneath it. But when I right click on my Borrower entity and chose "Borrower.Take(100)" I received this error from LINQPad: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. With an inner exception message: [A]System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection cannot be cast to [B]System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection. Type A originates from 'EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'Default' at location 'C:\MarkSisson\LinqPad\EntityFramework.dll'. Type B originates from 'EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadFrom' at location 'C:\Users\msisson\AppData\Local\Temp\LINQPad\vlnebssu\shadow_ujjvzp\EntityFramework.dll'. Any ideas? A: Download the latest beta - this problem was fixed in 4.42.05.
{ "pile_set_name": "StackExchange" }
Q: Tab collapse in bootstrap 4 In my code i have bootstrap 4 Tab .I want first all the tab-content will be hide when i click tab li then the tab-contents will be shown. For that i've removed the active class from tab-pane div so now at first contents are not showing and when i click on the tab li it is showing then but after i click on that li again it does not closing . I want when again i click the tab li button the tab contents should be closed again. <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#home" role="tab">Home</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#profile" role="tab">Profile</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#messages" role="tab">Messages</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#settings" role="tab">Settings</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane" id="home" role="tabpanel">A</div> <div class="tab-pane" id="profile" role="tabpanel">B</div> <div class="tab-pane" id="messages" role="tabpanel">C</div> <div class="tab-pane" id="settings" role="tabpanel">D</div> </div> Just want when click the menu it will show the content and when click again the menu it should close. Help me A: Updated Add this extra code to remove the active class on click again. $(document).on('click','.nav-link.active', function(){ var href = $(this).attr('href').substring(1); $(this).removeClass('active'); $('.tab-pane[id="'+ href +'"]').removeClass('active'); }) $(document).on('click','.nav-link.active', function(){ var href = $(this).attr('href').substring(1); //alert(href); $(this).removeClass('active'); $('.tab-pane[id="'+ href +'"]').removeClass('active'); }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" > <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#home" role="tab">Home</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#profile" role="tab">Profile</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#messages" role="tab">Messages</a> </li> <li class="nav-item"> <a class="nav-link" data-toggle="tab" href="#settings" role="tab">Settings</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane" id="home" role="tabpanel">A</div> <div class="tab-pane" id="profile" role="tabpanel">B</div> <div class="tab-pane" id="messages" role="tabpanel">C</div> <div class="tab-pane" id="settings" role="tabpanel">D</div> </div>
{ "pile_set_name": "StackExchange" }
Q: Debug rails app inside docker use Intellij/Rubymine I'm start working rails development with Docker. Currently, I follow some tutorial to setup development environment. Everything work well. (for build, run). But now, I want to setup Ruby Remote SDK for Rubymine, so I installed SSH on docker container (the ruby container; I INSTALLED SSH BECAUSE IT'S NEEDED FOR SETTING REMOTE SDK). Here is Dockerfile FROM ruby:2.2.0 # Install package RUN apt-get update -qq && apt-get install -y \ build-essential \ libpq-dev \ nodejs \ openssh-server # Setting sshd RUN mkdir /var/run/sshd RUN echo 'root:root' | chpasswd RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config RUN sed -ri 's/UsePAM yes/#UsePAM yes/g' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile EXPOSE 22 CMD ["/usr/sbin/sshd", "-D"] RUN mkdir /myapp WORKDIR /myapp ADD Gemfile /myapp/Gemfile ADD Gemfile.lock /myapp/Gemfile.lock RUN bundle install ADD . /myapp And docker-compose.yml version: '2' services: db: image: postgres web: build: . command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: - .:/myapp ports: - "3000:3000" - "22" depends_on: - db (For ssh -> in flow this link https://docs.docker.com/engine/examples/running_ssh_service/) Then I connect ssh to the container. Here is my steps: Get port of ssh: docker port demorailsdocker_web_1 # Here is result 22/tcp -> 0.0.0.0:32768 3000/tcp -> 0.0.0.0:3000 Connect ssh to container ssh root@localhost -p 32768 # Result ssh_exchange_identification: Connection closed by remote host I figure out the problem is related to setup in Dockerfile. Because when I remove those lines in docker file: RUN mkdir /myapp WORKDIR /myapp ADD Gemfile /myapp/Gemfile ADD Gemfile.lock /myapp/Gemfile.lock RUN bundle install ADD . /myapp And remove those lines in docker-compose.yml volumes: - .:/myapp Then I can connect to SSH. I think the problem is about setting work dir. I can connect SSH well to the container by removed this line in docker-compose.yml command: bundle exec rails s -p 3000 -b '0.0.0.0' So I think the problem is about rails. But I don't know how to fix it. A: I've managed to use RubyMine to remote debug rails running inside a docker, without using SSH. Versions of software in my environment are as follows RubyMine 2017.2.4 (Build #RM-172.4155.44, built on September 26, 2017) Ruby inside docker (ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-linux]) Ruby SDK and Gems used by RubyMine (ruby-2.4.2-p198) Note: for Ruby SDK, I am just using a local Ruby interpreter /usr/bin/ruby, not a remote one. Below are the detailed steps as a demo 1. Start the docker docker run --name rails-demo -p 1234:1234 -p 3080:3000 -it ruby bash 2. Steps inside the docker Be sure you have the following gems in your Gemfile, and better to comment out gem pry-byebug if it's there, to avoid possible interference. # gem 'pry-byebug' gem 'debase', '0.2.2.beta10' gem 'ruby-debug-ide' Update the dependencies of your application if necessary bundle install Start your rails server /home/hello_rails# rdebug-ide --host 0.0.0.0 --port 1234 --dispatcher-port 26162 -- bin/rails s 3. Remote debug from RubyMine Now start RubyMine, Run -> Debug... -> Edit Configurations... Click plus sign '+' to add new configuration, and choose Ruby remote debug. Fill the form as shown above and click the Debug button. Now you'll see in the docker the Rails server gets started: /home/hello_rails# rdebug-ide --host 0.0.0.0 --port 1234 --dispatcher-port 26162 -- bin/rails s Fast Debugger (ruby-debug-ide 0.6.0, debase 0.2.2.beta10, file filtering is supported) listens on 0.0.0.0:1234 => Booting Puma => Rails 5.1.4 application starting in development => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.10.0 (ruby 2.4.2-p198), codename: Russell's Teapot * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://0.0.0.0:3000 Use Ctrl-C to stop Now, you can set breakpoints in RubyMine, and start remote debugging it :-) Go to browser with URL: http://localhost:3080/say/hi (Note port 3080 is mapped from 3000, see the command of starting docker) The breakpoint is hit as shown below, where you can inspect variables, etc. One more caveat worth mentioning is that be sure the web server puma starts in single mode. For me the cluster mode does not work for remote debugging, where you'll have errors like "terminating timed out worker". For development, single mode should be good enough.
{ "pile_set_name": "StackExchange" }
Q: How to specify a range of RGB values in C# On a form I have a PictureBox, a button to load image in the picturebox and couple of more buttons to do some operations on the image loaded into the picturebox. I load a bitmap image into the picturebox and then I want to perform some operation on pixel ranges rgb(150,150,150) to rgb(192,222,255) of the loaded image. Is it possible to do this using SetPixel method? Is there any way to specify a range of RGB values in C#? A: Simple way would be something like this: for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { Color c = bitmap.GetPixel(i, j); if (ColorWithinRange(c)) { // do stuff } } With ColorWithinRange defined like this: private readonly Color _from = Color.FromRgb(150, 150, 150); private readonly Color _to = Color.FromRgb(192, 222, 255); bool ColorWithinRange(Color c) { return (_from.R <= c.R && c.R <= _to.R) && (_from.G <= c.G && c.G <= _to.G) && (_from.B <= c.B && c.B <= _to.B); } For large bitmap sizes, however, GetPixel and SetPixel become very slow. So, after you have implemented your algorithm, if it feels slow, you can use the Bitmap.LockBits method to pin the bitmap (prevent GC from moving it around memory) and allow yourself fast unsafe access to individual bytes.
{ "pile_set_name": "StackExchange" }
Q: Horizontal UIScrollView and bunch of UIButtons I need help with the application I am trying to create, in which I have a UIScrollView and three pages. The problem is that buttons 'FOO' and 'BAR' are loaded in the first page, instead it should be loaded in the second page only. So, the project should be like this: \--View (The underlying UIView) \--scrollView (The UIScrollView) \--button (The buttons) and - (void)createButton { float xButton = 10.0; NSArray *buttonTitles = @[@"foo", @"bar"]; for (int i = 0; i < 2; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(xButton, 10.0, 100.0, 50.0); [button setTitle:buttonTitles[i] forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown]; [scrollView addSubview:button]; [button setTag:i]; xButton += 200; } } I have a UIView with three horizontal UIScrollViews. What I want to do is, the buttons are to be displayed in the second view. But every time I launch the application, the buttons are already loaded in the first view, and not in the second view. __________ __________ __________ | | | | | | | 1st | <--- | 2nd | <--- | 3rd | | page | scroll | page | scroll | page | | | | | | | |________| |________| |________| How will I load the buttons in the second page, and won't reappear in the first and third page? It seems that by checking the currentPage of UIPageControl won't work. In addition, what are needed to be done in order for my second page to be displayed first whenever I launch the application? A: A few things here: I have a UIView with three horizontal UIScrollViews You should only have one UIScrollView. It may have 3 pages of content, but there should only be one, paging-enabled scroll view. How will I load the buttons in the second view, and not in the first view? Don't you really want to load all three pages of buttons? That way, if the user starts on page 2 and scrolls left, page 1 will have its buttons loaded. If they scroll right, page 3 will already have its buttons loaded. If you really, really feel you need to defer loading of the next page's buttons until the user starts scrolling, you could implement the UIScrollViewDelegate protocol, and detect scrolling in scrollViewDidScroll:. When the scroll starts, you're then going to have to load new buttons. But, I wouldn't recommend this. Loading on demand like this may make your scrolling more laggy (if you aren't careful about performance), and buttons normally aren't big memory users, so I would think that you could easily keep all 3 pages of buttons loaded at all times. - (void)createButton { float xButton = 10.0; NSArray *buttonTitles = @[@"foo", @"bar"]; for (int i = 0; i < 2; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(xButton, 10.0, 100.0, 50.0); /* button setup here */ xButton += 200; } } I don't think you want to increment xButton by 200 points every iteration. SpringBoard doesn't space its buttons like that. I once built something that sort of imitated SpringBoard's layout, and the code to initialize the buttons was something like this: const int PADDING = 4; const int SCREEN_WIDTH = 320; const int SCREEN_HEIGHT = 411; const int SPACING = (SCREEN_WIDTH - (4 * 57)) / 5; // 5 spaces between 4 columns float x = SPACING; float y = SPACING; int index = 0; int page = 0; for (NSString* title in buttonTitles) { UILabel* btnLabel = [[UILabel alloc] initWithFrame: CGRectMake(x, y + 57 + PADDING, 57, 20)]; btnLabel.text = title; btnLabel.font = [UIFont boldSystemFontOfSize: 12.0]; btnLabel.shadowColor = [UIColor darkGrayColor]; btnLabel.shadowOffset = CGSizeMake(1, 1); btnLabel.textColor = [UIColor whiteColor]; btnLabel.opaque = NO; btnLabel.backgroundColor = [UIColor clearColor]; btnLabel.textAlignment = UITextAlignmentCenter; [self.scrollView addSubview: btnLabel]; UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(x, y, 57, 57); // NOTE: my code uses labels beneath buttons, not button titles //[button setTitle:title forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.scrollView addSubview:button]; // index tag helps us determine which button was pressed later [button setTag:index]; // I keep a NSMutableSet of all the buttons [self.buttons addObject: button]; if ((x + (2 * 57) + SPACING) > (SCREEN_WIDTH * (page + 1))) { // new row x = SCREEN_WIDTH * page + SPACING; if ((y + (2 * 57) + SPACING) > SCREEN_HEIGHT) { // new page (to the right of the last one) page++; y = SPACING; x = SCREEN_WIDTH * page + SPACING; } else { y += 57 + PADDING + 20 + SPACING; } } else { x += 57 + SPACING; } index++; } // set the virtual scrollView size to allow paging/scrolling horizontally self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * (page + 1), SCREEN_HEIGHT); In my code, I trigger the button click callback on the Touch Up Inside event, as I think that makes for a better user experience. I also added labels below my buttons, not as part of the buttons (again, imitating SpringBoard itself). You can delete that code (btnLabel) if you like. In addition, what are needed to be done in order for my second view to be displayed first whenever I launch the application? If you have one scroll view, and want to start on page 2, use currentPage from your UIPageControl: - (void)viewWillAppear: (BOOL) animated { [super viewWillAppear: animated]; self.pageControl.currentPage = 1; // for page '2' } Note: I seem to remember that 57 points isn't actually the size SpringBoard displays icons at. It's something like the size, ignoring the shadow/edge effects, which I think brings the total size to 60 points. Anyway, you can play with that.
{ "pile_set_name": "StackExchange" }
Q: Contact Us button/smtplib forward details (Resolved) I am using pythonanywhere to make a website. I have set up a contact us page, and I am attempting to take whatever a user submits as feedback and then forward the information to myself with smtplib. I asked about this on their forums, but they for some reason just deleted my post. Here is my HTML code: <title>Contact us!</title> <link rel="stylesheet" href="{{ url_for('static', filename='css/contact.css') }}"> <div class="container"> <form action="contact"> <label for="report">Reason</label> <select id="report" name="report"> <option value="Bug">Bug</option> <option value="Suggestion">Suggestion</option> <option value="Other">Other</option> </select> <label for="Subject">Subject</label> <textarea id="Subject" name="Subject" placeholder="Write something.." style="height:200px"></textarea> <input type="submit" value="Submit"> </form> </div> And here is the python code: @app.route("/contact", methods=["GET", "POST"]) def feedback(): if request.method == 'GET': return render_template("contact.html") else: result = "Thanks for the feedback!" report = request.form['report'] Subject = request.form['Subject'] from email.mime.text import MIMEText import smtplib gmail_user = '[email protected]' gmail_password = 'password' message = MIMEText(report) message["Subject"] = Subject message["From"] = gmail_user message["To"] = gmail_user server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.sendmail(gmail_user, gmail_user, message.as_string()) server.close() return render_template('settlement_return.html',result = result) EDIT: If I manually set report and subject to some misc text string it sends fine. But trying to get the information that someone submits is not giving any results. A: As discussed in the comments above -- it looks like the problem was that you were missing the method="POST" in your form tag. That meant that the form was being submitted with the GET method, so the code in the first branch of the if statement in your view was being executed, which meant that no email was being sent.
{ "pile_set_name": "StackExchange" }
Q: Load only visible cells in UITableView So I have an application that reads records from a database and basically fills out a UITableView with the information from the DB. Some of the information includes an image, which it brings from an online server I have. Everything works fine, but the program is a little slow and scrolling is a little laggy/ jumpy, as its bringing all the images at once, instead of bringing them as I scroll. Is there a way to change it so that as I scroll it brings the next few visible records? -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { static NSString *CellIdentifier = @"VersionCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } STSneakerInfo *info = [_versionInfo objectAtIndex:indexPath.row]; cell.textLabel.font = [UIFont boldSystemFontOfSize:14.1]; [[cell textLabel] setNumberOfLines:2]; cell.textLabel.text = [[_uniqueBrand stringByAppendingString:@" "] stringByAppendingString: info.version]; cell.detailTextLabel.textColor = [UIColor grayColor]; cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:14.1]; cell.detailTextLabel.text = info.initialReleaseDate; NSString *brandVersion = [[_uniqueBrand stringByAppendingString:@" "] stringByAppendingString:info.version]; NSString *underscoredBrandVersion = [brandVersion stringByReplacingOccurrencesOfString:@" " withString:@"_"]; NSString *underscoredBrandName = [_uniqueBrand stringByReplacingOccurrencesOfString:@" " withString:@"_"]; NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: ([[[[[@"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:@"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:@"/"] stringByAppendingString:@"default.jpg"])]]; cell.imageView.image = [UIImage imageWithData: imageData]; return cell; } A: you can use (https://github.com/rs/SDWebImage) to download image async. its easy and fast. i prefered this library because it will handle your cache. just write below code [cell.imageView sd_setImageWithURL: [NSURL URLWithString: ([[[[[@"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:@"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:@"/"] stringByAppendingString:@"default.jpg"])]]; you can also download image in background thread as per wenchenHuang answer above. using below code. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: ([[[[[@"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:@"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:@"/"] stringByAppendingString:@"default.jpg"])]; if (data) { UIImage *img = [UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ if (img) cell.imageView.image = img; }); } }); Maybe this will help you.
{ "pile_set_name": "StackExchange" }
Q: LINQ for extracting N bottom items (async streams) source.Bottom(n, x => x) should be the same as well known LINQ source.OrderBy(x => x).Take(n) but is more memory/run-time efficient as it does not keep all items in memory as OrderBy does: public static class BottomN { public static async IAsyncEnumerable<T> Bottom<T, TValue>( this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector) where TValue : IComparable<TValue> { var list = new List<T>(); await foreach(var item in source) { list.Insert(list.BestIndex(item, selector), item); if (list.Count > number) list.RemoveAt(number); } foreach (var item in list) yield return item; } static int BestIndex<T, TValue>(this IList<T> list, T value, Func<T, TValue> selector) where TValue : IComparable<TValue> { return bestIndex(0, list.Count); int bestIndex(int s, int e) => s == e ? s : selector(list[(s + e) / 2]).CompareTo(selector(value)) > 0 ? bestIndex(s, (s + e) / 2) : bestIndex((s + e) / 2 + 1, e); } } To test: [TestMethod] public async Task Keep_Three() { var values = new[] { 10, 22, 3, 55, 66, 100, 200, 2 }; var bottom = await values.ToAsyncEnumerable().Bottom(3, v => v).ToArrayAsync(); CollectionAssert.AreEqual(new int[] { 2, 3, 10 }, bottom); } A: where TValue : IComparable<TValue> Don't do this. OrderBy doesn't require its type parameters to implement this interface like this either. Instead it uses the IComparer<T> interface. What's the difference? With IComparable<T>, the implementation of the comparison logic is sitting on the class T itself. This means that there is one and only one way of ordering elements of T. If I wanted to sort them using some customized logic, I would be out of luck. Instead, IComparer<T> is a separate class that compares Ts. Providing an instance of that interface to the method allows me to use whatever logic I want to order T. But what if I don't want to implement an entire class, but instead want to use IComparable<T>? This is where Comparer<T>.Default comes to play. This static property provides a default implementation for IComparer<T> for T, which, if T implements IComparable<T>, will default to call that logic. So how would your interface look? We have an overload with the IComparer<TValue> argument, and an overload without: public static async IAsyncEnumerable<T> Bottom<T, TValue>( this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer) { return Bottom(source, number, selector, Comparer<TValue>.Default); } public static async IAsyncEnumerable<T> Bottom<T, TValue>( this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer) { // Actual implementation. } Binary tree I think this problem would call for a binary tree, instead of a list that's sorted/ranked continuously. This would you can quickly check whether the item you are iterating would even be in the top-number of items in the collection, without having to add and subsequently having to remove it again. The downside is that C# doesn't have a built-in Binary Tree that isn't hidden within the SortedX collection set. These classes sadly require unique values in their collections, which isn't guaranteed here. Alternatively, if you can handle adding another few lines to your solution, you can check if the index returned by BestIndex is equal to number, and skip adding and removing it from the list if this is the case. Code style This needs to be said. Your code is really compact. It took me multiple reads to figure out what on earth BestIndex was actually doing. Docstrings, comments and/or intermediate variables with clear names please. Something as simple as "Returns the rank of value in the list by performing a merge-sort style algorithm." is enough to understand its role in Bottom.
{ "pile_set_name": "StackExchange" }
Q: java - String to Date Format I have a problem with String conversion to Date Format. Please help me. Below is my code: String strDate = "23/05/2012"; // Here the format of date is MM/dd/yyyy Now i want to convert the above String to Date Format like "23 May, 2012". I am using below code but i am getting value as "Wed May 23 00:00:00 BOT 2012" String string = "23/05/2012"; Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string); System.out.println(date); // Wed May 23 00:00:00 BOT 2012 How can i get the value as "23 May, 2012". Please help me friends.... A: You must render the date again. You have the string and you parse it correctly back to a Date object. Now, you have to render that Date object the way you want. You can use SimpleDateFormat again, changing the pattern. Your code should then look like String string = "23/05/2012"; Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(string); String newFormat = new SimpleDateFormat("dd MMMM, yyyy").format(date); System.out.println(newFormat); // 23 May, 2012 A: Use the method format() from the class SimpleDateFormat with the correct pattern. Simple use: SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy"); System.out.println(df.format(date));
{ "pile_set_name": "StackExchange" }
Q: gRPC+Go+React+TypeScript における Connect error 概要 現在、勉強の為にgRPC+Go+React+TypeScriptを用いた個人開発を行っています。 ReactとGoの間にはEnvoy Proxyを置いています。 gRPCは初めてということもあり、新規会員登録機能においてgRPCの接続テストを行っています。 具体的には、新規会員登録機能にアクセスするとgRPCでリクエストを送り、それに対するレスポンスをReact側でconsole.logするというものです。 しかし、そこで下記の内容のエラーが発生しました。 自分なりに色々調べてみましたが、解決せず…。 このままだと一向に次のフェーズに進めそうにないです…。 どなたか解決方法のご教授お願い致します。 エラーの内容 Error: upstream connect error or disconnect/reset before headers. reset reason: connection termination 該当のソースコード // client FROM node:latest WORKDIR /HEW2020/client COPY . . RUN yarn install --ignore-engines --network-timeout 1000000 CMD ["yarn", "start"] EXPOSE 3000 // server FROM golang:1.12 ENV GO111MODULE=on WORKDIR /go/src/HEW2020/server COPY . . RUN go get github.com/pilu/fresh CMD ["fresh"] EXPOSE 49200 49201 // envoy FROM envoyproxy/envoy:v1.12.2 WORKDIR /HEW2020/proxy COPY ./envoy.yaml . CMD /usr/local/bin/envoy -c /HEW2020/proxy/envoy.yaml EXPOSE 8080 // docker-compose.yml version: "3" services: proxy: build: ./proxy volumes: - ./proxy:/HEW2020/proxy ports: - "8080:8080" links: - "server" container_name: "hew2020-proxy" server: build: ./server volumes: - ./server:/go/src/HEW2020/server ports: - "49200:49200" container_name: "hew2020-server" client: build: ./client volumes: - ./client:/HEW2020/client ports: - "3000:3000" container_name: "hew2020-client" db: image: mysql:5.7 restart: always volumes: - ../mysql/data:/var/lib/mysql - ../mysql/conf:/etc/mysql/conf.d - ../mysql/initdb.d:/docker-entrypoint-initdb.d environment: MYSQL_ROOT_PASSWORD: secret MYSQL_DATABASE: hew2020 MYSQL_USER: root MYSQL_PASSWORD: secret # TZ: 'Asia/Tokyo' ports: - "13306:3306" container_name: hew2020-db // envoy.yaml admin: access_log_path: /tmp/admin_access.log address: socket_address: { address: 0.0.0.0, port_value: 9901 } static_resources: listeners: - name: listener_0 address: # 全IPの8080PortでListen socket_address: { address: 0.0.0.0, port_value: 8080 } filter_chains: - filters: - name: envoy.http_connection_manager config: codec_type: auto stat_prefix: ingress_http route_config: name: local_route virtual_hosts: - name: local_service domains: ["*"] routes: - match: { prefix: "/" } route: cluster: web_app_service max_grpc_timeout: 0s cors: allow_origin: - "*" allow_methods: GET, PUT, DELETE, POST, OPTIONS allow_headers: keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout max_age: "1728000" expose_headers: custom-header-1,grpc-status,grpc-message http_filters: - name: envoy.grpc_web - name: envoy.cors - name: envoy.router clusters: - name: web_app_service connect_timeout: 0.25s type: logical_dns http2_protocol_options: {} upstream_connection_options: tcp_keepalive: keepalive_time: 300 lb_policy: round_robin # win/mac hosts: Use address: host.docker.internal instead of address: localhost in the line below hosts: [ { socket_address: { address: host.docker.internal, port_value: 49200 }, }, ] // Signup.tsx import { SexTypes } from "../../proto/enums_pb" import { SignUpRequest } from "../../proto/messages_pb" import { WebAppServiceClient } from "../../proto/web_app_service_pb_service" const Signup: React.FC = () => { const classes = useStyles() useEffect(() => { const req = new SignUpRequest() req.setName("MyName") req.setSex(SexTypes.SEX_MALE) req.setAge(22) req.setUserId("abcdefg") req.setUserPw("password") const client = new WebAppServiceClient("http://localhost:8080", {}) client.signUp(req, (err, res) => { if (err || res === null) { throw err } console.log(res.getMessage()) }) }) return ( <Root> <div className={classes.toolbar} /> <h1>Signup</h1> <h1>Signup</h1> <h1>Signup</h1> </Root> ) } // web_app_service.proto web_app_service_proto service WebAppService { rpc SignUp (messages.SignUpRequest) returns (messages.AuthResponse) {} } // messages.proto message AuthResponse { bool status = 1; enums.StatusCodes status_code = 2; string token = 3; } message SignUpRequest { string name = 1; enums.SexTypes sex = 2; uint32 age = 3; string user_id = 4; string user_pw = 5; } 追記 公式サイト(該当ページ)をチェックしてみたところ下記の様な記述がありました。 Two quick definitions, used by Envoy: Upstream connections are the service Envoy is initiating the connection to. Downstream connections are the client that is initiating a request through Envoy. Upstream Connection Closed What it is: When the upstream closes the connection before the response is finished sending, Envoy cannot send a complete response to the downstream. Result: This depends on whether the downstream has started receiving data. If it has not (i.e. the upstream disconnects quickly), the downstream connection is reset. If it has, the downstream receives an HTTP 503 and the body text “upstream connect error or disconnect/reset before headers” これはUpstream(つまりGo)側に問題があるということでしょうか? A: Go側でエラーが発生していました…。修正したところ無事解決いたしました。 ありがとうございました!
{ "pile_set_name": "StackExchange" }
Q: Defining a string type to be a certain format I was wondering if there's a way to define a type of string or similar in delphi 7 which is intended to be in a particular format, or matching certain specifications? For example, I'd like to define a TSizeString type which accepts values such as 4x6 or 9x12 or maybe even 2.5x10.75. It should require the x as the only deliminator between two numbers. So there should never be anything like x9 or 65 or 2-4 or 4-6x6-2 and not even 4 x 6. Just INTEGER + 'x' + INTEGER or SINGLE + 'x' + SINGLE. Similar I guess to how like a TFilename works, standard filenames may look like C:\MyPath\MyFile.txt or \\Storage\SomeDir\SomeFile.doc A: In newer versions of Delphi, advanced records and operator overloading are very handy in this case: type TSizeString = record x, y: single; public class operator Implicit(const S: string): TSizeString; class operator Implicit(const S: TSizeString): string; end; implementation class operator TSizeString.Implicit(const S: string): TSizeString; var DelimPos: integer; begin DelimPos := Pos('x', S); if (DelimPos = 0) or (not TryStrToFloat(Copy(S, 1, DelimPos-1), result.X)) or (not TryStrToFloat(Copy(S, DelimPos + 1), result.y)) then raise Exception.CreateFmt('Invalid format of size string "%s".', [S]); end; class operator TSizeString.Implicit(const S: TSizeString): string; begin result := FloatToStr(S.x) + 'x' + FloatToStr(S.y); end; Now you can do procedure TForm1.Button1Click(Sender: TObject); var S: TSizeString; begin S := '20x30'; // works ShowMessage(S); S := 'Hello World!'; // exception raised ShowMessage(S); end; In older versions of Delphi, you simply have to write a class, or create a basic record to hold your size (and then, of course, you can create functions that convert between such records and formatted strings). A: Special types, like TFileName and TCaption are nothing special, like Andreas mentioned, but they can be used to register a specific property editor in the IDE. This will help entering such values through the object inspector. To really enforce such a value, if your string is a property of an object, you can write a setter for it. Otherwise, I should make a TSize class that has properties for the two integers, and an AsString property that combines its properties to a string. type TSize = class private FLeftInt, FRightInt: Integer; function GetString: string; procedure SetString(Value: string); public property LeftInt: Integer read FLeftInt write FLeftInt; property RightInt: Integer read FRightInt write FRightInt; property AsString: string read GetString write SetString; end; function TSize.GetString: string; begin Result := Format('%dx%d', [FLeftInt, FRightInt]); end; function TSize.SetString(Value: string); begin // Validate and parse Value. Set LeftInt and RightInt. end;
{ "pile_set_name": "StackExchange" }
Q: Why did I fail this audit review? I was in the Low-Quality review queue and I came upon an answer that even though it lacks explanation I thought it could still pass as an ok answer. However, after clicking "Looks OK" I received the following message: Any idea why that is? Especially considering that the justification was for "Spam/offensive content". Here's the link of the audit A: Let's unpack how we got to this point. The original answer was not spam (and the user has plenty of decent answers). Apparently an anonymous user edited in spam and people asleep at the wheel approved it. A moderator then came back and disapproved the edit (and probably handed out review bans). What's weird here is that on May 4, 2020 (some 3 years after the spam edit) the question was red-flagged by a moderator (one downvote and deleted by Community without a user destroy). The user is suspended for a year so it might be related somehow. It's been used as an audit one other time (and I can only assume that reviewer clicked into the answer to see it was deleted since they passed). I've raised a mod flag to see if they can shed any light, but it's a bad audit because it's a bad red flag. A: While the actions of the user may be spammy in nature, this particular post should not have been spam-flagged since that causes it to be eligible as an (incorrect) audit and only cause confusion. I've re-deleted it manually so it should no longer be an audit.
{ "pile_set_name": "StackExchange" }
Q: Reassigning an array frees the memory used by it? My class has a member variable array, items. Periodically I reassign the array to be the value of another, temporary array, like this: $temp = array(); $temp[] = new Object(); $temp[] = new Object(); $temp[] = new Object(); ... etc. $this->items = $temp; So, could I have a memory leak? By reassigning the value of $this->temp to a new value, $temp, would all the items (the items are objects) originally in $this->temp still linger around, or would they be freed? A: This will not cause a memory leak. $temp and $this->items are just references to the same array. Since PHP is a garbage collected language, the array will be deleted (garbage collected) when there are no more references to the array.
{ "pile_set_name": "StackExchange" }
Q: How to match a string with a value in a database I think value would be the correct word. Please edit if not. Contents: Problem 1(String not staying permanently in database) Problem 2(Idea for problem 1) I'm creating a program which adds a string into a table in a database using Sqlite3 in Python3. I am using a function which asks you for the password. Later, wanting to recall the function if the inputted string equals something in the database.(If it does not equal anything in the database, then we insert it into the passwords table.) Problem 1: The problem is that when I stop running the program and run it again, the string does not stay in the database which leads it to allowing me to retype previous passwords. What I want the program to do is to make the string stay in the database after stopping it. Here is the program for the paragraph above:(SCROLL DOWN for an idea for problem 1 ) import sqlite3 import hashlib db = sqlite3.connect( "users.db" ) cur = db.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS passwords( pwd TEXT, UNIQUE( pwd ))" ) def password(): pwd = input( "password: " ) sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest() cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, )) while True: try: password() #break except KeyboardInterrupt: print( "aborted" ) break except sqlite3.IntegrityError: print( "cannot reuse that password" ) db.commit() db.close() ====================================================================== Problem 2: (Idea for Problem 1) Here is an updated version. What I am doing here is trying to add the string into the database's table if it does or doesn't match with any of the strings. the error I am having here is that pwd is not a variable on line 13 although I do have it as one and had set it as a global variable. If wanting to help on this problem, i'd like to know why pwd isn't a variable and how to make it one. import sqlite3 import hashlib db = sqlite3.connect( "used_passwords.db" ) cur = db.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS passwords( pwd TEXT, UNIQUE( pwd ))" ) def password(): global pwd pwd = input( "password: " ) #turn this into a global variable sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest() cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, )) while True: #take pwd from password and put it here sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest() try: password() #break except KeyboardInterrupt: print( "aborted" ) break except sqlite3.IntegrityError: print( "cannot reuse that password" ) cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, )) db.commit() db.close() A: For problem 1 move your db.commit() into the loop, either into an else for your try-except or into the password() function directly. try: password() except KeyboardInterrupt: print( "aborted" ) break except sqlite3.IntegrityError: print( "cannot reuse that password" ) else: db.commit() or def password(): pwd = input( "password: " ) sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest() cur.execute( "INSERT INTO passwords VALUES( ? )", ( sha, )) db.commit() Commit your inserts individually after they succeed or you risk losing all of them in an unhandled error. I do not see any other reason for your passwords to "not stay in the database" than uncommitted inserts. As for problem 2: when the program enters the loop, password() has not yet been called, hence pwd does not yet exist when you try to use it. while True: #take pwd from password and put it here sha = hashlib.sha256( pwd.encode( 'utf-8' )).hexdigest() # <-- pwd is undefined here ... try: password() # ... because it needs this to be executed at least once Why even do the hashlib.sha256 for a second time in the loop? You already do it in password; you can remove that line from the loop and get rid of the NameError immedietaly. Also, the second INSERT in the loop's except block does not make sense. If the INSERT violates the UNIQUE constraint and raises the IntegrityError you attempt that very same INSERT again? This will raise the same error, which is unhandled this time and will make your programm crash. Stick with your first approach, it is a lot better. Don't use global variables unless you really really REALLY have to.
{ "pile_set_name": "StackExchange" }
Q: When does God respond? To attain god people do a lot of meditation, some worship god by doing rituals with discipline, some do vedic sacrifices. Consider the case of seeing him (not a material desire). Some people have to do a lot of meditation, but for some people he responds without doing much meditation. Does it depend on karma of when he has to respond? Even the rakshasas do meditate to see Lord Siva, they will be with strict discipline in doing their meditation. But how will Lord Siva decide that it is the time to respond. He knows that the desire of Rakshasas will be evil. Why can't he just test more, the patience of them by taking a very long time? So that they get vexed and stop meditating? A: When Yogi's heart is in Sattva mode and his heart is clean GOD responds. GOD is your lover only. You need to call him with Love. Who says God doesn't respond? You do not call him like Mirabai, Narasimha Mehta, Radha and Prahlada. Achutam Keshavam, Krishna Damodaram, Ram Narayanam, Janaki Vallabham Kaun kehte he bhagawan aate nahi, tum Mira ke jaise bulate nahi.. Even Rakshasa also become very innocent when they sit in meditation. This is power of God's name only. You must have love when you call anybody. For GOD every body is equal. Even Rakshasa or devata are equal. Just check yourself. If someone calls you with pure love, can you stop yourself from going to him? Love is GOD. Love calls GOD. Sattva calls Love.
{ "pile_set_name": "StackExchange" }
Q: Graph not $k$-colorable, without $k$-cliques I am looking for a simple example of a graph without $k$-cliques that is not $k$-colorable. $k=3$ would be great but perhaps a larger $k$ is required for this to be possible? A: The Grotzsch graph is the smallest example of a triangle-free graph with chromatic number $4$. It is the Mycelskian of $C_5$. By considering the Mycelskian of the Grotzsch graph you have a triangle-free graph with $23$ vertices and chromatic number $5$. This procedure can be iterated. I would point out some fancy ways for proving that there are triangle-free graphs with arbitrary chromatic number: for instance the existence of an infinite triangle-free difference graph with chromatic number $+\infty$, namely the graph whose vertices are the elements of $\mathbb{Z}$ and whose arcs join integers which differ by a cube.
{ "pile_set_name": "StackExchange" }
Q: Output values from Textbox using Constructor - Prototype i am trying to output the inserted values in the textboxes when the button(John) is click. At the moment i have just added default values in here ( John= new Player(30,"England",3)); but i would like these value to be picked from the textboxes. Please advise how would i go about doing it. I tried getting the values from textboxes and assigning to variables (x,y,z commented out in script)and passing here ( John= new Player(x,y,z)); but it didn't seem to work. Age : <input type = "text" id = "test1" /><br> County : <input type = "text" id = "test2" /><br> Rank: <input type = "text" id = "test3" /><br> <button type="button" onclick="John.myPlayer()">John</button> <br> <br> <div id = "box"></div> <br> <script type="text/javascript"> // var x = document.getElementById('test1').value; // var y = document.getElementById('test2').value; // var z = document.getElementById('test3').value); function Player(a,c,r){ this.age=a; this.country=c; this.rank=r; } Player.prototype.myPlayer = function(){ document.getElementById('box').innerHTML = "John is from " + this.country + " he is " + this.age + " years old and his rank is " + this.rank; } John= new Player(30,"England",3); John.myPlayer() </script> A: My suggestion is to create a function that is called on the onclick event, and read the values from the textboxes there, after which you create a new instance of Player. <button type="button" onclick="createNewPlayer()">John</button> and in javascript: function createNewPlayer() { var x = document.getElementById('test1').value; var y = document.getElementById('test2').value; var z = document.getElementById('test3').value); John= new Player(x, y, z); John.myPlayer() }
{ "pile_set_name": "StackExchange" }
Q: Are real numbers complex conjugates of one another? I'm just stuck with a technical part of my proof that might just be a triviality: if two different numbers are both real, are they complex conjugates of each other? Thanks, A: No - the complex conjugate of any given real number $a$ is itself: $$a=a+0i=a-0i=\overline{a}$$ Thus, if you have two different real numbers, they are not complex conjugates of each other.
{ "pile_set_name": "StackExchange" }
Q: How to make SCP on Linux output "success" to stdout instead of stderr? We have a cron job that sends stuff to another company using SCP. The command look like this: 10 0 * * * ssh USER@LOCAL-SERVER 'scp -q ~/some/dir/* REMOTE_SERVER:/other/dir/' >> ~/log/some.log This was setup by someone else. Now my problem is that my boss is on the cron mailing list, and despite the ">> ~/log/some.log" cron still sends an email every day, because even if the transfer was successful, it still outputs: Connection to REMOTE_SERVER 12345 port [tcp/*] succeeded! And my boss doesn't want to get that email unless an error happens. The command is really inside a script, which I have omitted to make the make the question simpler. It runs on a RHEL 6 server. But since it's the only line where we talk to REMOTE_SERVER, then it must come from there. And the reason we perform the command on LOCAL-SERVER (Ubuntu 10.04.4 LTS) is because we are on the DB server, which cannot cross the firewall, so we first copy the data to another local server, and upload it from there. When used without the -q, I also get the following output: SSH Server supporting SFTP and SCP I don't want to redirect all stderr output, because I still want to get an email when there is an error. A: I don't think you can redirect STDERR output selectively without rewriting the program to write those particular messages to STDOUT instead of STDERR. What you can do, however, is write a wrapper script that filters out the unwanted message, and run that script in the cron job. #!/bin/bash (ssh USER@LOCAL-SERVER ... 3>&1 1>&2- 2>&3-) 2>> ~/log/some.log \ | grep -v "Connection .* succeeded" 1>&2 exit $? Out of curiosity, why aren't you running a cron job with the scp command directly on LOCAL-SERVER? Edit: You want to filter out some of the STDERR output while redirecting all STDOUT output to a file, but the pipe can connect STDOUT of one process to STDIN of another process. |& or 2>&1 | won't work, because STDOUT is already is redirected to ~/log/some.log, so there'd be nothing going into the pipe, and a lot of unwanted output in your log file. However, it's possible to swap the descriptors, so that STDOUT actually goes to STDERR and STDERR actually goes to STDOUT. Then you can redirect all STDERR output to your log file and filter the STDOUT output via grep. Someone over at stackoverflow posted this neat little trick. The 1>&2 returns the filtered output back to STDERR.
{ "pile_set_name": "StackExchange" }
Q: PHP request handler script and SEO Would using a central "page handler" affect SEO negatively? eg A page request comes in for www.mysite.com/index.php, which mod_rewrite passes on as www.mysite.com/handler.php?page=index. Handler.php gathers the page-specific includes, language files and templates, and outputs the resultant html. My understanding is that the page handler method won't be any different SEO-wise than serving index.php directly, as the content and publicly visible url remain the same regardless of the monkey-business going on behind-the-scenes, but I've been wrong before... :) A: Search engines can only see the end HTML result. They have no idea if you're using a central page handler - how would they without hacking into your site's FTP? Also, as many frameworks and CMSes use this technique - Drupal and WordPress come to mind immediately - Google et. al. would be lunatics to penalise it, even if they could detect it.
{ "pile_set_name": "StackExchange" }
Q: What types of kayaks are suitable for occasional class 1 and 2 rapids According to the scale on this Wikipedia page (the International Scale of River Difficulty), what are the types of kayaks in the following list that are suitable to occasionally handle class 1 and 2 rapids ? whitewater sea recreational sit on top By occasionally I mean, no more than 20% of the time spent kayaking. A: I understand your goal in asking this question, but I think you're approaching it wrong: you should choose a kayak based on your skill and expected use. Each type of kayak will have benefits and drawbacks in each type of water, and some are completely unsuited for it -- choose one that fits your uses best. A well-known example: a recreational kayak is the wrong choice for kayaking on the ocean. Class 1 and 2 rapids are fantastic. I think it's probably fair to say that anybody with no skill and the right boat can make it through class 1 rapids with no concern. I think class 2 rapids should probably be handled by somebody with at least a little experience on the water, and the less experienced should always be accompanied by somebody more experienced. So, I am confident that you could do some class 1 rapids with any of those types of kayaks. For class two rapids, I would first be concerned with your skill level -- both on the water in general, and with the type of kayak being used (and maybe even the specific model). While class two rapids may not require much maneuvering, spinning a 20' sea/touring kayak is going to be practically impossible and therefore impractical; a 14-16' sea kayak is probably manageable for any experienced paddler. A whitewater or completely flat-bottomed rec kayak provide the maneuverability required, however a less experienced paddler will find themselves spinning with each stroke and out of control -- and therefore perhaps in a dangerous situation. In my opinion, the right choice for a new paddler is a rec kayak. They're fun, easy to use, and relatively cheap to buy/rent. Getting some experience with an eye towards determining what you ultimately want to do will help you make an informed decision. Rent a few times and take a lesson or two and you'll have gained a huge amount of experience to help you know what kind of kayak you really want and will lead you to the best choice. Experience is king. An experienced paddler will be able to take anything through class 1 or 2 rapids, no doubt. An inexperienced paddler could end up in a dangerous situation. I think it's essential to start out on calm flat water to learn strokes, practice technique, and gain some confidence. On that flat water you can learn to maneuver the kayak around strainers, rocks, or buoys. You can learn how a sweep differs from a front stroke, and what you can make the kayak do with each of those. Also on flat water, try working in windy conditions -- it'll do a surprisingly good job of mimicking how a river and rapids can push your boat around and teach you how to handle it. Once confident, go out on a slow river to put your skills to the test. Eventually move up to some faster moving water, and throw in a class 1 rapid. Try a short class 2 next. Then if you can find it, go through a long class 2 -- you'll get splashed quite a bit and get a solid workout. After working through class 2 you might want to step up to class 3. While gaining all of this experience you're going to learn how a kayak handles and what it does well and poorly, and more importantly you're going to see how your skill grows with it. As you do this stuff you'll be able to recognize where each type of boat is the right choice. Trying to more directly answer your question: IMO, a whitewater kayak is only useful for whitewater/surfing waves. A sit on top is good for jumping in and out of the water. A rec kayak is a good choice for many. A short touring/sea kayak is a good choice for many. A long touring/sea kayak is the right choice for racers and travelers. A: I think your answer makes sense, but I would caution boaters who use recreational kayaks on class 2 rivers because I've need to rescue recreational kayakers attempting this. Recreational kayaks are usually fine for class 1 rivers and for easy class 2 rivers. I wouldn't recommend one for long class 2 rapids, and not for a class 2+ rapid (and many class 2 rivers contain class 2+ when the water gets higher from a some rain or snowmelt). And please wear a PFD (life jacket). Most of those I've had to rescue in recreational kayaks have no PFD. I think you should have a helmet anywhere there are rocks, as well. You need to absolutely step up to a whitewater craft of some sort when you hit class 3. You'll find that whitewater kayaks will spin more on flatwater when you first start with one, and that after you learn to keep them going straight, that they will be slower and require more work to cover the same distance on flatwater. A: There's a specific class of boat designed to do exactly what you want - "crossover" kayaks. Here's some examples: In general they.. are much longer than a whitewater boat but are still short enough to be usable on a river are very stable and forgiving have proper whitewater outfitting (means they can be controlled properly) have hatches for storage often have skegs All the major manufacturers have their own models, often a range. There are different designs, some are a bit more focused on whitewater, some a bit more on sea, touring etc. As another poster said, skills are the most important thing. Going from flat to moving water isn't hard, but there's very important differences in safety, rescue, and skills. It's not about the boat - a paddler with the right ability will paddle a river more safely in an inflatable rubber duck than someone else in the right boat. If you have a club nearby, join up.
{ "pile_set_name": "StackExchange" }
Q: Matlab- Reading irregular textfile How can I read a textfile containing the following text in matlab? B4070IC05.tif,11 B4070IC06.tif,11,15,16,6,7 B4070IC07.tif,13,14,4,18,9 B4070IC08.tif,10,7 B4070IC09.tif,4,22,7 B4070IC10.tif,14,15,19,20,24,29,9 B4070IC11.tif,10,11,20,21 B4070IC12.tif,13,14,5,9 I don't know the number of columns of text. Is there a way to put these data in a cell matrix? how can I print the cell matrix after the data load? A: You can use textscan for this. Make sure that the number of %f-s is long enough to cover the longest series of values in your file. If all numeric values are integer, you could also use for instance `%d' (see textscan for more details). fid = fopen(filename); A = textscan(fid,'%s %f %f %f %f %f %f %f','delimiter',','); fclose(fid); The result is a cell array, with the first column the strings 'blabla.tif' and the second up to last column the numeric values. If a value is not present in the file, it equals NaN. Accessing the j-th value of the i-th column is done by A{i}(j). By the way, the last line in the file is not appended with NaNs, like the other lines. This means that combining the result into a cell array is not directly possible: the last few arrays are (might be) shorter than the first. I did not find an obvious fix for that, so we have to do that manually: idx = find(diff(arrayfun(@(idx)numel(A{idx}),1:numel(A)))); cA = [A{1} num2cell([horzcat(A{2:idx}) [horzcat(A{idx+1:end});nan(1,numel(A)-idx)]])];
{ "pile_set_name": "StackExchange" }
Q: Booting multiple Ubuntu's in a system I having Ubuntu 11.10, Windows7 and Windows8 installed for now. I also want to install UbuntuStudio. I have tried installing it into a separate partition. But, that did not load. Only the Ubuntu 11.10(with WindowsLoader[windows7 & windows8]) loads. The newly installed UbuntuStudio(based on Ubuntu 12.04) doesn't load up. The installation went successful. How am I supposed to load that also? A: That depends on how many (primary) partitions you already have. AFAIK only 4 primary partitions or 3 primary partitions and 1 extended partition, which can be subdivided into multiple logical partitions, are possible to be created on any hard drive. Many operating systems need to be running on an active primary partition to be bootable. So if you already have 3 operating systems (probably on 3 primary partitions) and maybe one SWAP or data partition, you cannot create an additional primary partition (see Wikipedia for more information). Nevertheless you actually don't need to seperately install Ubuntu Studio, as all the additional packages are available though the official packet sources. You can find a list of the packages here.
{ "pile_set_name": "StackExchange" }
Q: Are there collaborative drawing software? I was reflecting on Google Docs today and wondering if there are any graphic design software that include some real-time collaborative features? I'm talking about creating per se, not project management. I could see this being potentially useful for remote working or teamwork. I've never seen anything like this in the Adobe suite but I'm not knowledgeable of open source/online/or mobile graphic design oriented software. Does such a thing exist? A: You might want to chek out Figma which emphasizes its real-time collaboration features. It is geared towards interface design, bit since it's a vector editor, it could potentially be used for anything else. There is also vectr, which seems to have collaboration features (but I have not tested that)
{ "pile_set_name": "StackExchange" }
Q: Expect doesn't recognize output on Cisco router I'm writing a script with expect to configure cisco routers automatically via ssh. A part of this script is to copy an image into flash if it doesn't exist: For this expect sends a copy and waits for Destination filename then sends a return. cisco#copy tftp://10.xx.xx.3/name_of_image.bin flash: Destination filename [name_of_image.bin]? Now there're two options: The File doesn't exist and gets copied into flash: The File exists and the script skips this part. If the file already exists it looks like this: %Warning:There is a file already existing with this name Do you want to over write? [confirm] Now to my problem: The scripts waits for Do you want to over write? [confirm] and then should exit since the image is already in flash. But currently it seems like expect can't recognize that line and gets stuck at the confirmation. It've tried several patterns like [confirm], *[confirm]*, Do, *write* and some more. My code for that job looks like this at the moment: expect "*#" send "copy tftp://10.$ip_local.3/name_of_image.bin flash:\r" expect "Destination filename" send "\r" expect { "Do you want to over write? [confirm]"{ interact abort } expect "*#" send "exit\r" What am I doing wrong? A: A couple of things wrong: in a double-quoted string [confirm] will attempt to call the expect command "confirm" -- square brackets in expect are like backticks in the shell expect needs to have arguments separated by whitespace. Therefore it's critical to put a space before the opening curly brace your script does not expect the overwrite prompt conditionally. You need to use the multi-pattern form of the expect command, where the first one matched wins. Try this: expect { -exact {Do you want to over write? [confirm]} { send "\r" exp_continue } "*#" } send "exit\r" expect eof Notes I'm using "exact" matching since you have glob wildcards ? and [...] that would interfere. I'm using expect's no-interpolation quotes (curly braces) to prevent [confirm] from attempting command substitution I expect either the overwrite prompt or the command prompt I use exp_continue to remain within this expect command if the overwrite prompt appears. That means that I can still look for the command prompt. the above 2 bullets are how to implement conditional matching. I assume you just want to hit enter at the overwrite prompt. after you exit, wait for eof to allow the ssh session to end normally
{ "pile_set_name": "StackExchange" }
Q: Understand decorators on Flask-HTTPAuth I want to understand how and when @auth.verify_password decorator is used on this program. If i navigate to route http://127.0.0.1:5000, I understand that I need to passed in a username and a password and @auth.login_required will verify it, but where does @auth.verify_password comes in? Does @auth.login_required calls it? #!/usr/bin/env python from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users: return check_password_hash(users.get(username), password) return False @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.username() if __name__ == '__main__': app.run() A: From the documentation: verify_password(verify_password_callback) If defined, this callback function will be called by the framework to verify that the username and password combination provided by the client are valid. The callback function takes two arguments, the username and the password and must return True or False. So you basically provide the function so your program is able to verify the credentials supplied by the user. The login_required decorator protects the route by reading the authentication credentials provided by the user and passing them to your verify_password function to be verified.
{ "pile_set_name": "StackExchange" }
Q: Capture Flash Player Event in Javascript I need to capture the event raised when a flash video ends. If possible, I'd like to distinguish this from a user clicking the stop button. One thing to be made perfectly clear: I DON'T HAVE CONTROL OVER THE PRESENTATIONS OR THE SWF FILES. What I'm looking for is simple (I thought) js automation of the client player object, not more complex interactivity with the presentation itself. I thought this would be really simple stuff, but a dozen Google and Bing searches later, I can't find anything about it. TIA. A: No can do. The SWF doesn't make anything available to the JavaScript layer unless it's specifically programmed to do so. Without access to the source, you're out of luck.
{ "pile_set_name": "StackExchange" }
Q: Why is "Dawn" translated "Mediodía"? Me parece que "mediodía" significa "noon" y "dawn" debe ser "amanecer," pero: In "The Outcasts of Poker Flat / Los Desterrados de Poker Flat" (por Bret Harte) the original English has this: "...waited for the dawn." Whereas the Spanish translation puts it this way: "...esperó la luz del mediodía,..." Why would dawn be translated "mediodía" instead of "amanecer" here? It makes no sense, at any rate - the protagonist has been sleeping; it would naturally be the dawn he awaits, not noon. Is there any possible sensible reason why "dawn" would be translated "mediodía" here? A: Indeed, dawn should be translated as "amanecer" or "alba" ... esperó al amanecer. ... esperó a las primeras luces del alba Seeing that you already found a really blatant example of bad translation in the version of that book you are working with, it should not be surprising this is another oner.
{ "pile_set_name": "StackExchange" }
Q: PHP table values I have a question and I will try to explain the best way that I can I have a table that show me names of accounts and each one of that accounts has it own information. and I'm getting that information like this On the page "verpersonagem.php" I have this: $idaccount = $_GET['accountId']; but the url comes like this ../verpersonagem.php?account= Why it's not getting the value? Thanks in advance A: you don't have yo use all this echo statement try this <?php while ($row = mysqli_fetch_row($result)) { echo '<tr> <th><a href="verpersonagem.php?account='. $row[0] .'"> '. $row[0] .' </a></th> <td>'. $row[2] .' </td> <td>'. $row[1] .'</td> <td>'. $row[3] .'</td> <td>'. $row[4] .'</td> </tr>'; } ?>
{ "pile_set_name": "StackExchange" }
Q: Opinions on NetCDF vs HDF5 for storing scientific data? Anyone out there have enough experience w/ NetCDF and HDF5 to give some pluses / minuses about them as a way of storing scientific data? I've used HDF5 and would like to read/write via Java but the interface is essentially a wrapper around the C libraries, which I have found confusing, so NetCDF seems intriguing but I know almost nothing about it. edit: my application is "only" for datalogging, so that I get a file that has a self-describing format. Important features for me are being able to add arbitrary metadata, having fast write access for appending to byte arrays, and having single-writer / multiple-reader concurrency (strongly preferred but not a must-have. NetCDF docs say they have SWMR but don't say whether they support any mechanism for ensuring that two writers can't open the same file at once with disastrous results). I like the hierarchical aspect of HDF5 (in particular I love the directed-acyclic-graph hierarchy, much more flexible than a "regular" filesystem-like hierarchy), am reading the NetCDF docs now... if it only allows one dataset per file then it probably won't work for me. :( update — looks like NetCDF-Java reads from netCDF-4 files but only writes from netCDF-3 files which don't support hierarchical groups. darn. update 2009-Jul-14: I am starting to get really upset with HDF5 in Java. The library available isn't that great and it has some major stumbling blocks that have to do with Java's abstraction layers (compound data types). A great file format for C but looks like I just lose. >:( A: I strongly suggest you HDF5 instead of NetCDF. NetCDF is flat, and it gets very dirty after a while if you are not able to classify stuff. Of course classification is also a matter of debate, but at least you have this flexibility. We performed an accurate evaluation of HDF5 vs. NetCDF when I wrote Q5Cost, and the final result was for HDF5 hands down. A: I'll have to admit using HDF5 is very much easier in the long run. It's not hard to get simple data structures into NetCDF format, but manipulating them down the road is kind of a pain. The "H" in HDF5 stands for "heirarchical", which translated (for me anyway) into a REALLY easy way to manipulate data, by just moving nodes around and referencing nodes from other places. Can I ask what kind of project this is? I use these both for a lot of HPC scientific modeling tasks. Can I assume you're doing the same? If so, the trend I'm seeing is people moving to HDF5, but that might be different in your particular domain. However you end up going, best of luck! A: NetCDF, starting with version 4.0 (2008) can read and write most HDF5 files, and provides access to the hierarchical features of HDF5 via the enhanced data model. HDF5 is extremely feature-rich, and has some great performance features. NetCDF has a simpler API, and a much wider tool base. There are many tools that handle netCDF data.
{ "pile_set_name": "StackExchange" }
Q: How we can use mysql_affected_rows() in stored procedure How we can use mysql_affected_rows() in stored procedure.. A: Use the ROW_COUNT() information function. ROW_COUNT() returns the number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT. For other statements, the value may not be meaningful. The ROW_COUNT() value is the same as the value from the mysql_affected_rows() C API function and the row count that the mysql client displays following statement execution. A: example BEGIN DECLARE countRow INT; DECLARE roomTypeId INT; INSERT INTO room_type (room_type) SELECT * FROM (SELECT paramRoomType) AS tmp WHERE NOT EXISTS ( SELECT room_type_id FROM room_type WHERE room_type = paramRoomType ) LIMIT 1; SET countRow = ROW_COUNT(); IF(countRow > 0) THEN SET roomTypeId = LAST_INSERT_ID(); INSERT hotel_has_room_type (hotel_id,room_type_id) VALUES (paramHotelId,roomTypeId); END IF; END A: You cannot use mysql_affected_rows() in a stored procedure since it's a C API function. You can use FOUND_ROWS() function which gives a similar functionality. Refer this link for more details.
{ "pile_set_name": "StackExchange" }
Q: how to send json header via python tornado in a websocket? #!C:/Python27/python.exe -u import tornado import tornado.websocket import tornado.wsgi import tornado.web import tornado.httpserver import tornado.tcpserver import json from py2neo import neo4j, cypher graph_db = neo4j.GraphDatabaseService() class request(tornado.web.RequestHandler): def sr(): self.set_header('Content-type','application/json') class ChatWebSocket(tornado.websocket.WebSocketHandler): clients = [] def open(self): ChatWebSocket.clients.append(self) def on_message(self, message): query = "START a=node:node_auto_index(uid='twitter') CREATE a-[:ch]-(t{con:'"+message+"'}) RETURN a" data, metadata = cypher.execute(graph_db, query) for client in ChatWebSocket.clients: print(client) t=json.loads(message) client.write_message('Content-type:application/json\n') client.write_message(json.dumps({'a':t['b']})) print(t['b']) def on_close(self): ChatWebSocket.clients.remove(self) tornado_app = tornado.web.Application([ (r'/websocket', ChatWebSocket), (r'.*', tornado.web.FallbackHandler) ]) tornado_app.listen(5094) tornado.ioloop.IOLoop.instance().start() here is my code sample i am accepting json in the message getting its instance b and send json again to the client.but client is treating header as normal string. A: Websockets does not require headers. Just send your json as string.
{ "pile_set_name": "StackExchange" }
Q: Photos won't load and links are dead So I hosted my website on netlify with my github repo. All of my photos and files used in the site are there but they will not load. Only my index.html and style.css that is outside of all of the folders will load. I have a link to my github repo. Github Repo html{ background-color:#abb2bc; } body{ margin:0; } h1 { margin:0; background-color: #363b42; } img{ width:250px; } .navbar{ text-align:center; } .blogpost{ background-color:white; padding:5%; margin:3% } #blogheader{ margin-top:15px; } .blogimage{ margin-top:25px; } <!DOCTYPE html> <html> <head> <title>GamingCoachBlog</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <header> <div class="navbar"> <h1>GamingCoach</h1> </div> </header> <main> <div class="blogpost"> <h2 id="blogheader">Recent Blog Posts</h2> <a href="/Users/david/Desktop/Blog/Articles/Ten Fortnite Tips For Season 8/index.html"><img class="blogimage" src="C:/Users/david/Desktop/Blog/Images/How to get more wins in Fortnite.png" alt="How to get more wins in Fortnite"></a> </div> </main> </body> </html> A: 'C://' refrences, or local refrences, do not work online. Aside from this, using spaces in your webpage name and file name is not recommended, as some browsers may not support spaces or will convert them to the web standard, a '+', or the unicode standard for space (U+0020) so that more actions can be performed on them. FIX: Swap src="C:/Users/david/Desktop/Blog/Images/How to get more wins in Fortnite.png" with src="Images/How to get more wins in Fortnite.png" to fix your problem and render the photo correctly, assuming your browser doesn't object to the spaces.
{ "pile_set_name": "StackExchange" }
Q: Extend Object and Change Method Parameter I create ImageViewProduct class which is extending ImageView class so i can store some variables in my ImageViewProduct object. But i can't get the ImageViewProduct's variable inside setOnClickListener method.. ImageViewProduct class : public class ImageViewProduct extends ImageView { boolean toUpload = false; public ImageViewProduct(Context context) { super(context); } public void setToUpload(boolean toUpload) { this.toUpload = toUpload; } public boolean isToUpload() { return toUpload; } } MainActivity class : ImageViewProduct ivProduct = new ImageViewProduct(this); ivProduct.setToUpload(true) ivProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { Log.i("zihad", "is to upload : "+v.isToUpload()); } }; The log inside onClickListener is error cannot resolve method 'isToUpload()'. I've try to change the onClick(final View v) to onClick(final ImageViewProduct v) but error. How to fix it? A: If you only ever apply this to an ImageViewProduct then you could cast v to an ImageViewProduct. public void onClick(final View v) { ImageViewProduct productView = (ImageViewProduct) v; Log.i("zihad", "is to upload : "+productView.isToUpload()); } More info on casting at this QnA.
{ "pile_set_name": "StackExchange" }
Q: iPhone UI controls for WinForms Does anybody know where I could find WinForms controls that mimic those on the iPhone? I am interested in doing some iPhone prototyping using Visual Studio and it would be handy if I could make the controls look like the native iPhone controls. I know that I could just use Interface Builder on a Mac, but I do not want to do this. I just want to play around with various ideas and I will be much faster in Visual Studio. A: Balsamiq Mockups has some iPhone-like controls, and you get a mock up done faster than in Visual Studio. A: I've had a look around for windows forms iPhone controls for mocking and positioning items and couldn't find any. However it's quite easy to do yourself with a few screenshots from the iPhone Simulator. Below is what I've done - I'll update with a download link to the project a bit later. As mentioned Apple probably won't like, nor let you release a product using their UI style. However for mocking there is nothing to stop you doing it in Visual Studio - they still get their $99 and appstore cut. I use Visual Studio as I do XIB-less Monotouch development in it, and want to avoid switching back and forth. For XIB-less apps, designing with interface Builder isn't much faster in my view - but that's a Monotouch-centric viewpoint.
{ "pile_set_name": "StackExchange" }
Q: Eclipse freeze on opening declaration in long file I am using Eclipse CDT on linux. I have a long header file with 5k lines of code. When I try to open declaration of some variable in this file by pressing F3, Eclipse freezes for about 20 seconds and then opens declaration. This issue makes code navigation unusable in a long file. In shorter files declaration opens almost instantly. I tried to restart Eclipse and rebuild the index but this did not help. My Eclipse version is: Version: Neon.1 (4.6.1) Build id: Z20161111-1340 How can I workaround this issue ? A: Looks like this is Eclipse bug 455467. The reason of freeze is high cpu usage when opening declaration. I applied workaround from Comment 5 and freeze dropped to 1-5 seconds: Changing all settings in .metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.cdt.codan.core.prefs from RUN_AS_YOU_TYPE\=>true to RUN_AS_YOU_TYPE\=>false seems to help us out of this but this is not really what we want. As I understand this workaround partially disables Codan - CDT static analysis framework.
{ "pile_set_name": "StackExchange" }
Q: MySql group by two columns i am just begin learning mysql for php! i have a problem with query mysql to get data team from table i have a table with the fields table name (team) id, OPPONENT, COMPETITION data table (team) like this **id** **OPPONENT** **COMPETITION** 1 barcelona real madrid 2 barcelona Villarreal 3 real madrid ruby i want write query to get table like this **team** barcelona Villarreal real madrid ruby A: This table should have foreign key of your teams and you would simply select teams name in teams table. Anyway, if you want to do it that way, try this: SELECT DISTINCT opponent AS team FROM table UNION SELECT DISTINCT competition AS team FROM table
{ "pile_set_name": "StackExchange" }
Q: Symfony 3: Error message of embedded form with contraint on class property If a class has a property of another class, validation can be cascaded by using the Valid() annotation, as shown in the documentation. I've built an embedded form for that example and it correctly cascades errors when I put incorrect data into the form fields of the Address class. However, if I leave all form fields of the class Address empty, no error is displayed. That seems to be ok. I need to specify NotBlank() or NotNull besides Valid() on the address property. Here is the complete example: // src/AppBundle/Entity/Address.php namespace AppBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; class Address { /** * @Assert\NotBlank() */ protected $street; /** * @Assert\NotBlank * @Assert\Length(max = 5) */ protected $zipCode; } // src/AppBundle/Entity/Author.php namespace AppBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; class Author { /** * @Assert\NotBlank() * @Assert\Length(min = 4) */ protected $firstName; /** * @Assert\NotBlank() */ protected $lastName; /** * @Assert\NotNull() * @Assert\Valid() */ protected $address; } With this code, leaving all fields of address empty makes the form submission invalid. This is what I want. But: No error message is displayed on the form after submission. I think it has something to do with the fact that the error message for NotNull() is not associated to a single form field. How can I display the error? Form type code: // src/AppBundle/Form/Type/AddressType.php namespace AppBundle\Form\Type; use AppBundle\Entity\Address; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; class AddressType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('street', TextType::class) ->add('zipCode', TextType::class) } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => Address::class, )); } } // src/AppBundle/Form/Type/AuthorType.php namespace AppBundle\Form\Type; use AppBundle\Form\Type\AddressType; use AppBundle\Entity\Author; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextType; class AddressType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('firstName', TextType::class) ->add('lastName', TextType::class) ->add('address', AddressType::class) } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => Author::class, )); } } Output of dump($form->getErrors(true,true));: AuthorController.php on line 33: FormErrorIterator {#538 ▼ -form: Form {#363 ▶} -errors: array:1 [▼ 0 => FormError {#748 ▼ -message: "This value should not be null." #messageTemplate: "This value should not be null." #messageParameters: array:1 [▼ "{{ value }}" => "null" ] #messagePluralization: null -cause: ConstraintViolation {#682 ▼ -message: "This value should not be null." -messageTemplate: "This value should not be null." -parameters: array:1 [▶] -plural: null -root: Form {#363} -propertyPath: "data.author.address" -invalidValue: null -constraint: NotNull {#674 ▶} -code: "ad32d13f-c3d4-423b-909a-857b961eb720" -cause: null } -origin: Form {#489 ▶} } ] } A: In your controller you need to create an instance of the related object. This way the object is not null and you can have its field validation public function myAction() { $formObject = new Author(); $formObject->setAddress(new Address()) $this->createForm(AuthorType::class, $formObject)
{ "pile_set_name": "StackExchange" }
Q: Continuous image loading/processing & display on button click (in Swing) I have trouble with continuous image loading&processing&display in Swing: Below there is simple case where clicking a button causes my program to grab frame from webcam and then display this picture in jlabel. It works as it should, but i have to consecutively click this "Start" button in order to get new image(frame) shown. private void StartActionPerformed(java.awt.event.ActionEvent evt) { displayed_img = this.getPIC_COLOR(player); img_field.setIcon(new ImageIcon(displayed_img)); } Im more demanding and i would like to make some image processing during live video stream, therefore i need to "grab" & "show" my frames continuously. You might say that i can just launch webcam stream, but it is not what i want to achieve since i'm about to implement some threshholding/etc. functions which will modify my image on-fly. Therefore i need to perform this grabbing&processin&display as fast as possible (delay is a no-no since i want to achieve something like 10 fps including image processing). Despite the fact that i delay is utterly undesirable i tried to make some Thread.sleep however it didnt work. Simple while(true) /* presented below */ does not work, my program "hangs" and not even single frame is displayed, although in debugger it keeps working over and over. private void StartActionPerformed(java.awt.event.ActionEvent evt) { while(true){ displayed_img = this.getPIC_COLOR(player); //threshholding & further processing... img_field.setIcon(new ImageIcon(displayed_img)); } } just in case getPIC_COLOR() was required, i paste it below: public BufferedImage getPIC_COLOR(Player player){ FrameGrabbingControl frameGrabber = (FrameGrabbingControl)player.getControl("javax.media.control.FrameGrabbingControl"); Buffer buf = frameGrabber.grabFrame(); Image img = (new BufferToImage((VideoFormat)buf.getFormat()).createImage(buf)); BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics(); g.drawImage(img, null, null); return buffImg; } Any help greatly appreciated. Ok, after some reading i managed to write some SwingWorker Code: private void SingleFrameActionPerformed(java.awt.event.ActionEvent evt) { SwingWorker<Void, BufferedImage> worker = new SwingWorker<Void, BufferedImage>() { @Override protected Void doInBackground() { while (!isCancelled()) { displayed_img = getPIC_COLOR(player); publish(displayed_img); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } } return null; } @Override protected void process(List mystuff) { Iterator it = mystuff.iterator(); while (it.hasNext()) { img_field.setIcon(new ImageIcon(displayed_img)); try { ImageIO.write(displayed_img, "png", new File("c:\\testimg.jpg")); } catch (IOException ex) { Logger.getLogger(TestCAMGUI.class.getName()).log(Level.SEVERE, null, ex); } } } @Override protected void done() { infoBAR.setText("FINISHED"); } }; worker.execute(); } Now what seriously bothers me is the fact that my img_field is not updated in swing, although ImageIO.write present in process works, and image is "redrawn" on C:\ with MAD speed ("mad speed" is highly desirable). Moreover my GUI is still frozen even though i created this swing worker thread... btw i also tried to "sleep" this saving thread for a second, however my GUI hangs even with this additional sleep Now some explanations about my code: doInBackground() returns void, as i dont need to return anything, since i assume this process will run till cancelled (which is unlikely to happen, unless program is closed). inside process() i've included try/catch block with ImageIO.write just to make sure my thread launched and works i didnt use 'SwingUtilities.invokeLater' due to fact that browsing guides/tutorials i've read that it is better to use SwingWorker in my case What bothers me furthermore: in process i operate on list which enlarges... i dont need that, i just need a single element and thats all. So is there a way to collect single object from doInBackground()? making list seems memory waste for me. Or maybe i should clear() the list at the end of process()? (in order to reduce memory allocated) Any further hints are appreciated. A: You must not run any kind of infinite loop of that form in a method that is called from an event (unless you explicitly intend to hang your user interface, which would be odd to say the least). You should run your frame grab in a separate thread, and then use something like SwingUtilities.invokeLater to display it.
{ "pile_set_name": "StackExchange" }
Q: How to inject click event with Android UiAutomation.injectInputEvent I'm automating the testing of a flow in my app where I install a device administrator. To activate a device administrator on most devices (let's assume here I don't have some enterprise API that lets me do this like what Samsung offers) the system displays a popup to the user who then has to click the "Activate" button. I'm using Robotium and Android JUnit to drive my tests. In a normal testing case one can only interact with the app and process under test and not any system activities that come up. The UiAutomation claims to allow you to interact with other applications by leveraging the Accessibility Framework, and then allowing one to inject arbitrary input events. So - here's what I'm trying to do: public class AbcTests extends ActivityInstrumentationTestCase2<AbcActivity> { private Solo mSolo @Override public void setUp() { mSolo = new Solo(getInstrumentation(), getActivity()); } ... public void testAbc(){ final UiAutomation automation = getInstrumentation().getUiAutomation(); MotionEvent motionDown = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN, 100, 100, 0); // This line was added in to give a complete solution motionDown.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionDown, true) MotionEvent motionUp = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, 100, 100, 0); // This line was added in to give a complete solution motionUp.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionUp, true) motionUp.recycle(); motionDown.recycle(); } } When this test is run the System popup to "Activate" the device administrator is active, and I want to just click on the screen. I've hardcoded in 100,100 as the position for clicks for the purposes of this question but realistically I'll click in the bottom right corner of the screen so I can hit the button. I do not get any click events occurring on the screen. Does anyone have experience with this? Are there any alternatives to do what I want to do? From my understanding there are very few tools that do this. Thanks. Update Added setSource for right answer A: Finally figured this out. I compared my MotionEvents to the two events that get dispatched when I clicked on a button and the only difference was the source. So, I set the source on the two motionEvents and it worked. .... motionDown.setSource(InputDevice.SOURCE_TOUCHSCREEN); .... motionUp.setSource(InputDevice.SOURCE_TOUCHSCREEN); And here's a full version of the method //========================================================================= //== Utility Methods === //========================================================================= /** * Helper method injects a click event at a point on the active screen via the UiAutomation object. * @param x the x position on the screen to inject the click event * @param y the y position on the screen to inject the click event * @param automation a UiAutomation object rtreived through the current Instrumentation */ static void injectClickEvent(float x, float y, UiAutomation automation){ //A MotionEvent is a type of InputEvent. //The event time must be the current uptime. final long eventTime = SystemClock.uptimeMillis(); //A typical click event triggered by a user click on the touchscreen creates two MotionEvents, //first one with the action KeyEvent.ACTION_DOWN and the 2nd with the action KeyEvent.ACTION_UP MotionEvent motionDown = MotionEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_DOWN, x, y, 0); //We must set the source of the MotionEvent or the click doesn't work. motionDown.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionDown, true); MotionEvent motionUp = MotionEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_UP, x, y, 0); motionUp.setSource(InputDevice.SOURCE_TOUCHSCREEN); automation.injectInputEvent(motionUp, true); //Recycle our events back to the system pool. motionUp.recycle(); motionDown.recycle(); }
{ "pile_set_name": "StackExchange" }
Q: Finding $P(X<2Y)$ given joint pdf $f(x, y) = \frac {1}{2\pi} e^{-\sqrt{x^2 + y^2}}$ for $x,y\in\mathbb R$ The joint pdf of $X$ and $Y$ is $$f(x, y) = \frac {1}{2\pi} e^{-\sqrt{x^2 + y^2}}\,; \quad x,y\in \mathbb{R}$$ Find $P(X<2Y)$. I have tried this: $$\int_{-\infty}^{\infty}\int_{-\infty}^{2y} f(x, y)\, dx\,dy$$ @StubbornAtom suggested polar transformations. So here it goes, Let $X = r \cos\theta, \, Y = r \sin\theta$. Then The integral gets transformed as $\int \int re^{-r}d\theta$. Could some one help find the new limits. A: The joint distribution of $(X,Y)$ is rotationally symmetric, since the density depends only on the distance from the origin. This means that the conditional distribution of $(X,Y)$ given $X^2+Y^2$ is uniformly distributed on the circle of radius $r=\sqrt{X^2+Y^2}$. Writing $X=r\cos\Theta$ and $Y=r\sin\Theta$ with $\Theta\in [0,2\pi)$ uniformly random, we have $$ \mathbb P(X<2Y\mid X^2+Y^2)=\mathbb P(\cos\Theta<2\sin \Theta)$$$$=\mathbb P\Bigl(\tan\Theta>\frac{1}{2}, \cos\theta > 0\Bigr)+\mathbb P\Bigl(\tan\Theta<\frac{1}{2}, \cos\theta < 0\Bigr),$$ which can be seen to equal $$\mathbb P\Bigl(\tan^{-1}\frac{1}{2}<\Theta<\pi+\tan^{-1}\frac{1}{2}\Bigr)=\frac12. $$ Since the conditional probability is $\tfrac12$ independent of $X^2+Y^2$, it follows that the unconditional probability is also $\tfrac12$. A: Draw the set $M = \{(x,y)\in\mathbb R^2 \mid x<2y\}$. What you should get is the half-plane above the line $y=\frac{x}{2}$. Since the given pdf $f$ is radially symmetric, you get the result $$ P(X<2Y) = \int_M f(x,y) \, \mathrm dx\, \mathrm dy = \frac{1}{2} $$ without any calculations.
{ "pile_set_name": "StackExchange" }
Q: shell script filter question I am trying to store the resulting list from "ls -la" into a variable then filter out some files name, after that print out only the filtered file names (along with the date and stuff like how ls -la does it" again, but when I do that everything is in one line, is there a way to make sure every file name are on different lines? thanks in advance A: Use a pipe instead of storing it in a variable. ls -la | filter Where filter is whatever you're using to filter. That's about as good an answer as I can give unless you can provide some more details on exactly what you're trying to do. A: if you want to filter file names, eg , don't list all txt files shopt -s extglob ls !(*.txt)
{ "pile_set_name": "StackExchange" }
Q: How to make a div appear when clicking on an element with jQuery I have an invisible div which I want to make visible by clicking an element. It doesn't seem to work. What am I missing here? I've tried targeting <a class=".demo"> with jQuery and using the click function to add a class .open to <div class="demo-div"> to make it visible $(".demo").click(function() { $(".demo-div").addClass("open"); }); $(".demo").click(function() { $(".demo-div").removeClass("open"); }); .demo-div { background: #3AB0E0; color: #18191D; position: fixed; left: 0; top: 0; width: 100%; height: 100%; padding: 3.75rem; z-index: 99; opacity: 0; visibility: hidden; overflow-x: hidden; overflow-y: hidden; transform: tranlateY(-100%); transition: all 0.5s ease-in-out; } .demo-div.open { opacity: 1; z-index: 99; visibility: visible; transform: translateY(0); transition: all 0.5s ease-in-out; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="javascript:void(0);" class="demo">click here</a></li> </ul> </nav> <div class="demo-div"></div> And it doesn't seem to add class open to class demo-div if you delete this class demo-div you can see it appear opacity: 0; visibility: hidden; ***Update I understood what I did wrong, when adding the new class it should contain a closing button such as .demo-close-btn $(".demo").click(function() { $(".demo-div").addClass("open"); }); $(".demo-close-btn").click(function() { $(".demo-div").removeClass("open"); }); A: Use toggleClass() instead of add or remove. $(".demo").on('click', function() { $(".demo-div").toggleClass("open"); }); A: The problem is because you've attached two event handlers to the same element, and both of them are conflicting with each other in that they add then remove the class. To fix this you should use a single event handler and add/remove the class based on its current state. You can do that using toggleClass(): $(".demo").click(function() { $(".demo-div").toggleClass("open"); }); It's worth noting, however that when the open class is applied to .demo-div the .demo element is no longer clickable, as it's occluded. To fix this you could add another click handler to .demo-div which removes the open class, like this: $(".demo").click(function() { $(".demo-div").addClass("open"); }); $('.demo-div').click(function() { $(this).removeClass('open'); }); .demo-div { background: #3AB0E0; color: #18191D; position: fixed; left: 0; top: 0; width: 100%; height: 100%; padding: 3.75rem; z-index: 99; opacity: 0; visibility: hidden; overflow-x: hidden; overflow-y: hidden; transform: tranlateY(-100%); transition: all 0.5s ease-in-out; } .demo-div.open { opacity: 1; z-index: 99; visibility: visible; transform: translateY(0); transition: all 0.5s ease-in-out; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li><a href="javascript:void(0);" class="demo">click here</a></li> </ul> </nav> <div class="demo-div"></div>
{ "pile_set_name": "StackExchange" }
Q: Opening figure in a specific order When the script run is over, all my figure appears in the opposite order. I mean I see the figure 3, then the figure 2 and the figure 1. But I would like to see figure 1 first and etc... Is it possible ? thank you. A: If you have something like: y=rand([1,100]; x=1:100; figure(1) plot(x,y,'b') figure(2) plot(x,y,'r') figure(3) plot(x,y,'g') % ... % figure(N) then in the end just do N=3; for ii=N-1:-1:1 figure(ii) end Basically, calling figure(existing_number) will bring that figure upfront.
{ "pile_set_name": "StackExchange" }
Q: Change site name SEO impacts My site is merging with my friends one so the domain and the site title will change, currently my page title's are structured <title>Contact Us | Example Industries</title> But when we change the name of the company I was thinking of changing it to <title>Contact Us | Cool New Site Name</title> I have a sitemap.xml file which I can add in Google Webmaster Tools to reindex my pages, but is there anything I need to be aware of when changing names, should I still reference the old name initially maybe in the title or meta description. What is the best approach here? A: My site is merging with my friends one so the domain and the site title will change If your site is moving to a new domain, you should let search engines know using the steps listed here: Tell Google when your site moves Bing - Site Move Also, be sure to avoid duplicate content issues by using 301 redirects if your previous site is still accessible. But when we change the name of the company I was thinking of changing it...should I still reference the old name initially maybe in the title or meta description. You should change the name in the title and description and no longer reference the old name because it will confuse visitors when they see it in your SERP and browser tabs/bookmarks, as well as possibly result in search engines indexing the old name. If you want to let visitors know your site has moved, you could add a statement to your page's content instead. Lastly, you should add the new site to Google Webmaster Tools and submit the sitemap for it under that, making sure you no longer have URL's to the old site in it.
{ "pile_set_name": "StackExchange" }
Q: How to create hashmap which will hold 528 bit record in binary I need to create a hash map which will hold 528 bit binary data. How would the binary data be stored in the hashmap? Example: 0000000001000000100000000... this is 25 bits. Similarly, I need to store 528 bits. Do I need to convert this value into some byte array, or can I directly store the data in memory? An example would be of great help. A: Do not complicate your life. Assuming value is of String type, then if you: Store key as String Probably easiest and most readable. String value = "some data", key = "0101101010101010101011010110101010010101"; HashMap<String, String> map = new java.util.HashMap<String, String>(); map.put(key, value); Additional: To convert a key of type byte[] to String, you can use BigInteger class, for example: byte[] keyb = { 90, -86, -83, 106, -107 }; String keys = new BigInteger(keyb).toString(2); Element keys will have a value: 101101010101010101011010110101010010101. Store key as byte[] Personally I would like to avoid this. Simple default hash function in this case hashes the reference to the array as key, but we want deep hash (all elements must be equal). Following will not work as described: HashMap<byte[], String> map = new HashMap<byte[], String>(); map.put(new BigInteger(key1, 2).toByteArray(), value); One way to fix this, is to put the array in the class or extend collection called ArrayList and rewrite the equals and hash method. It is not as trivial as it seems - you really need to know what you are doing. Store key as BitSet Extracting, adding or manipulating bits is not most efficient - it's even rather slow. So this seems only good option if it impacts the memory size very noticeably and that's a problem. String value = "some data", key = "0101101010101010101011010110101010010101"; HashMap<BitSet, String> map = new HashMap<BitSet, String>(); map.put(getBitSet(key), value); You can create a makeshift BitSet class converter like: public static int keySize = 41; public static BitSet getBitSet(String key) { char[] cs = new StringBuilder(key).reverse().toString().toCharArray(); BitSet result = new BitSet(keySize); int m = Math.min(keySize, cs.length); for (int i = 0; i < m; i++) if (cs[i] == '1') result.set(i); return result; } public static String getBitSet(BitSet key) { StringBuilder sb = new StringBuilder(); int m = Math.min(keySize, key.size()); for (int i = 0; i < m; i++) sb.append(key.get(i) ? '1' : '0'); return sb.reverse().toString(); }
{ "pile_set_name": "StackExchange" }
Q: Worklight WL.Client.getUserName I have a Worklight 6.2 app. I am modifying the android java code to subscribe to a notification sent via Bluemix. After the user logs in, I would like to register the device using the userid that gets created. Is there an API call that I can use within the android code that is the equivalent to WL.Client.getUserName, or should I be calling the java code from my javascript and passing the userName to the java code? Thanks for any suggestions. JT A: There is no Java equivalent to this. This is a Worklight API. What you can do is use the new WL.App.sendActionToNative method in Worklight 6.2 for to send a value to your native code and from there do what you need with it. WL.App.sendActionToNative(“doSomething”, { customData: 12345} ); Where customdData is the WL.Client.getUserName. On the native side you then need to use WLActionReciever (see What's New). You could also opt to implement a basic Cordova plug-in that will move data from the web to native view. The tutorial in the Getting Started page is doing exactly that.
{ "pile_set_name": "StackExchange" }
Q: Best way of storing a pair of values that need to be updated frequently in Python? I have a use case where I need to be storing a pair of values in Python where both values will need to be updated frequently. Do I use a list or a tuple or something else? On one hand, a list is easier to update, since tuples are immutable and I will need to create a new tuple every time I update any one of the values. However, since I will not be appending anything to the list, and the size is fixed at 2, it feels like a tuple may be a better representation of what the object actually is. Any insight? Thanks! A: Make a pair class? class pair(object): def __init__(self,first,second): self.update(first,second) def update(self,first,second): self.first = first self.second = second This clarifies it's only two objects, and that updates are welcome. If you want basic arithmetic with other pairs/lists/tuples you can implement that easily enough.
{ "pile_set_name": "StackExchange" }
Q: Application is opening on notification creation using Alarm Manager Here is what I am trying to do : I am trying to trigger a notification everyday at a specific time which the user can select in settings screen. The issue I am currently facing is, whenever the alarm triggers and displays the notification, the application opens and closes. Please find below the code that I have used : MainActivity.java @Override protected void onRestart() { Util.handleNotificationPreferences(this); super.onResume(); } Util.java public static void handleNotificationPreferences(Activity activity) { SharedPreferences notificationPreferences = activity.getSharedPreferences("com.xyz.abc_prefs, Context.MODE_PRIVATE); boolean notificationEnabled = notificationPreferences.getBoolean("currencyNotificationOnOff", false); if(notificationEnabled) { String time = notificationPreferences.getString("scheduleNotificationTime", ""); String hour = time.split(":")[0]; String minutes = time.split(":")[1]; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour)); calendar.set(Calendar.MINUTE, Integer.parseInt(minutes)); calendar.set(Calendar.SECOND, 0); Calendar now = Calendar.getInstance(); if(calendar.getTimeInMillis() < now.getTimeInMillis()) { calendar.setTimeInMillis(calendar.getTimeInMillis() + 86400000L); } AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE); //---PendingIntent to launch activity when the alarm triggers--- Intent i = new Intent(activity, NotificationActivity.class); //---assign an ID of 1--- i.putExtra("notificationId", 1); PendingIntent displayIntent = PendingIntent.getActivity( activity.getBaseContext(), 0, i, 0); //---sets the alarm to trigger--- alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), displayIntent); } } NotificationActivity.Java public class NotificationActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int notificationId = getIntent().getExtras().getInt("notificationId"); Intent resultIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , resultIntent,0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(getResources().getString(R.string.notification_title)) .setContentText(getResources().getString(R.string.notification_text)) .setContentIntent(pendingIntent) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); } // Gets an instance of the NotificationManager service NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Builds the notification and issues it. mNotifyMgr.notify(notificationId, mBuilder.build()); finish(); } } A: Intent i = new Intent(activity, NotificationActivity.class); you're giving to the system the instruction to open the Activity. You should use instead create a BroadcastReceiver, register it on the AndroidManifest.xml and create a intent to it new Intent(activity, NotificationBroadcast.class); then inside the onReceive call back you generate and show the notification.
{ "pile_set_name": "StackExchange" }
Q: passing arguments in the URL on POST method I'm trying to pass arguments in the URL example: // client side URL: index.pl?action=view_user METHOD: GET #perl side my $Q = CGI->new; print $Q->param('action'); return me view_user but when try post by example on a form: // client side URL: index.pl?action=save_user METHOD: POST FORM: username: test #perl side my $Q = CGI->new; print $Q->param('action'), "-", $Q->param('username'); return me -test. why the param on url is blank? A: Use ->url_param instead of ->param to get parameters from the URL when handling a POST request.
{ "pile_set_name": "StackExchange" }
Q: Customize Spring Oauth Error I've to customize my Spring OAuth 2 response. Now is like : { "error": "invalid_token", "error_description": "Invalid access token: INVALID" } but i need additional data like: { "status": -5, "error": "invalid_token", "error_description": "Invalid access token: INVALID", "errors":[ {"message":"clear message for customer"} ] } How to customize it to get the requested message? I tried this: my spring servlet xml: <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" > <property name="exceptionTranslator" ref="OauthErrorHandler" /> </bean> <bean id="OauthErrorHandler" class="com.mypath.handler.OauthErrorHandler"/> My Translator: import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator; import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; public class OauthErrorHandler extends DefaultWebResponseExceptionTranslator implements WebResponseExceptionTranslator { @Override public ResponseEntity<OAuth2Exception> translate(Exception e){ ResponseEntity<OAuth2Exception> responseEntity = null; try { responseEntity = super.translate(e); } catch (Exception e1) { e1.printStackTrace(); } OAuth2Exception body = responseEntity.getBody(); body.addAdditionalInformation("status", "-5"); body.addAdditionalInformation("errors", "[{\"message\":\""+body.getLocalizedMessage()+"\"}]"); HttpHeaders headers = new HttpHeaders(); headers.setAll(responseEntity.getHeaders().toSingleValueMap()); return new ResponseEntity<>(body, headers, responseEntity.getStatusCode()); } } But the response still the same A: I've solved doing extending OAuth2Exception and using a custom JSON serializer and deserializer @org.codehaus.jackson.map.annotate.JsonSerialize(using = OAuth2ExceptionJackson1Serializer.class) @org.codehaus.jackson.map.annotate.JsonDeserialize(using = OAuth2ExceptionJackson1Deserializer.class) @com.fasterxml.jackson.databind.annotation.JsonSerialize(using = OAuth2ExceptionJackson2Serializer.class) @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2ExceptionJackson2Deserializer.class) public class CustomOauthException extends OAuth2Exception { private static final long serialVersionUID = 124661L; public CustomOauthException(String msg) { super(msg); } private String oaut_error_code; private int http_error_code; public CustomOauthException(String msg, Throwable t) { super(msg, t); } @Override public int getHttpErrorCode() { return this.http_error_code; } public int getHttp_error_code() { return http_error_code; } public void setHttp_error_code(int http_error_code) { this.http_error_code = http_error_code; } @Override public String getOAuth2ErrorCode() { return oaut_error_code; } public void setOaut_error_code(String oaut_error_code) { this.oaut_error_code = oaut_error_code; } }
{ "pile_set_name": "StackExchange" }
Q: Second order central difference = first order central difference applied twice? Approximating the 1st order derivative via central differences can be written as $ \delta_{2h}u(x) =\frac{u(x+h) - u(x-h)}{2h} \approx u'(x) .$ What is the main issue with applying again a central difference to compute $u''(x)$? In this case, $\delta_{2h}u'(x) = \frac{u'(x+h) - u'(x-h)}{2h} \approx \frac{u(x+2h) + u(x-2h) - 2u(h)}{4h^2}.$ This is actually different from what most sources on finite differences consider the second order approximation using central differences, i.e. $ u''(x) \approx \frac{u(x+h)+u(x-h)-2u(x)}{h^2},$ which is achieved for a step-size of $\frac{1}{2}h$. What is the problem with the first interpretation and why do most sources require that one uses the half step size (apart from the obvious loss of numerical accuracy, is there any logical fallacy)? A: $$u(x+h)= u(x)+u'(x)h+\frac{1}{2}u''(x)h^2+\mathcal{O}(h^2)$$ $$u(x-h)= u(x)-u'(x)h+\frac{1}{2}u''(x)h^2+\mathcal{O}(h^2)$$ The common formula is obtained not assuming "half step size" , but by adding the above formula together. Your result is similar to looking at the below formula, the steps are larger. $$u(x+2h)= u(x)+u'(x)2h+\frac{1}{2}u''(x)(2h)^2+\mathcal{O}((2h)^2)$$ $$u(x-2h)= u(x)-u'(x)2h+\frac{1}{2}u''(x)(2h)^2+\mathcal{O}((2h)^2)$$
{ "pile_set_name": "StackExchange" }
Q: Twitter Bootstrap Table of Dropdowns Say you have a generic table as such: <table> <tr> <td class="box">ABC</td> <td class="box">DEF</td> </tr> <tr> <td class="box">GHI</td> <td class="box">JKL</td> </tr> </table> <ul id="menu" class="dropdown-menu"> <li>One</li> <li>Two</li> </ul> Is it possible, using bootstrap, to open a dropdown menu above a .box when clicked. (I'm assuming the easiest would be to use the bootstrap .dropdown() method.) $('.box').click -> ... make dropdown appear over $(this) Libraries currently being used: Bootstrap v2.1.1 jQuery v1.8.3 A: I found a sufficient jQuery plugin that will do exactly what I'm trying to achieve. http://labs.abeautifulsite.net/jquery-dropdown/
{ "pile_set_name": "StackExchange" }
Q: How can I host the Ulympics? I really would like to host the Ulympics. I suspect I need a lot of money and possibly certain buildings, as I failed getting to host them this time. I have four years to sort myself out and make my city awesome enough to host. What do I need to do or have to be able to host the Ulypmics? A: It seems that there's still some research going on to find the exact formula used to determine if you host the Ulympics. However, the minimum successful configuration found so far is: Jobs: 1 Athelete 1 Entrepreneur 1 Politician Buildings: 1 TV Station 1 Sports Combo 1 Security Company Source
{ "pile_set_name": "StackExchange" }
Q: Postgres join tables with certain requirements I've been trying to create a certain query through flask for a project needed at work. The idea is to create a client management system whereupon providing the name of the client the code returns a table with all the information. What I did was create one table called clients where I store name, address, etc, and another table called maintenance where there I store issues dates and name, just these three columns. what I am hoping to achieve is to return upon input of the client's name one row with has the client's information and another row hat displays only issues and date. SELECT clients.name, clients.vat, clients.address, clients.phone, clients.plate, clients.year, clients.vin, clients.engine, clients.email, maintenance.issue, maintenance.date FROM clients INNER JOIN maintenance ON clients.plate = maintenance.plate where clients.name = 'PETROS' this code works ok inside pgadmin4 screenshot but when I run it in flask and display it with an HTML table I get as expected multiple tables also. the idea was something like this. omit all the duplicate info and just keep the issues And this is the HTML code for displaying the info <div id="sectionE" class="tab-pane fade"> <h3>Καρτέλα</h3> <form name = "search" form method="post" action="/client_card"> <p><label for="search">Αναζητηση Πελατη</label></p> <p><input type="search" id="search" placeholder="Ονοματεπωνυμο.." name = "NAME" onkeyup="var start = this.selectionStart;var end = this.selectionEnd;this.value= this.value.toUpperCase();this.setSelectionRange(start, end);"></p> <input type="submit" value="Αναζητηση"> </form> <br> <table id="results_customer"> <tr> {% for row in data4 %} <h3>Στοιχεια</h3> <th>Ονομα</th> <th>ΑΦΜ</th> <th>Διευθηνση</th> <th>Τηλεφωνο</th> <th>e-mail</th> </tr> <tr> <td>{{row[0]}}</td> <td>{{row[1]}}</td> <td>{{row[2]}}</td> <td>{{row[3]}}</td> <td>{{row[8]}}</td> </tr> </table> <table id="results_customer"> <h3>Στοιχεια Οχηματος</h3> <tr> <th>Πινακιδα </th> <th>Μοντελο</th> <th>Χρονολογια</th> <th>Πλαισιο</th> </tr> <tr> <td>{{row[4]}}</td> <td>{{row[5]}}</td> <td>{{row[6]}}</td> <td>{{row[7]}}</td> </tr> </table> <table id="results_customer"> <h3>Εργασιες και Σχολια</h3> <tr> <th>Εργασιες</th> <th>Ημερομηνια</th> </tr> <td style="word-wrap: break-word"></tdstyle>>{{row[9]}}</td> <td>{{row[10]}}</td> </tr> {% endfor %} </table> </div> The way things are i just get three times the same table. and if i add more issues it will just keep multiplying. Sorry for the long post ive been trying with anything i can find but no luck.The other option is to make two separate queries through python or join then through sql. any idea would be greatly appreciated! A: So i tried out a few things and well I quess that works to my liking. although I would still want to find out if there is a proper way to do it through postgres def client_card(): NAME = request.form["NAME"] query = ('''SELECT * from clients where NAME = %s ''') cur.execute(query,(NAME,)) results_customer = cur.fetchall() conn.commit() query_1 = ('''select maintenance.issue,maintenance.date from maintenance, clients where maintenance.plate = clients.plate AND clients.name= %s''') cur.execute(query_1,(NAME,)) results_is = cur.fetchall() conn.commit() return render_template("choices.html", data4 = results_customer,data5 = results_list) so basically one way is to query another table and view its output but that only works through python select maintenance.issue,maintenance.date from maintenance, clients where maintenance.plate = clients.plate AND clients.name= %s and I just created another table in the HTML form to view these results below the first query <table style="table-layout: fixed; width: 100%" id="results_is"> <h3>Εργασιες και Σχολια</h3> <tr> <th>Εργασιες</th> <th>Ημερομηνια</th> </tr> {% for row in data5 %} <tr> <td style="word-wrap: break-word">{{row[0]}}</td> <td>{{row[1]}}</td> </tr> {% endfor %} </table>
{ "pile_set_name": "StackExchange" }
Q: Adding custom actions to facebook comment plugin I am currently using the normal facebook comments plugin as such: <p class="fb-comments"></p> <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js#appId=API_ID&amp;xfbml=1"></script> <fb:comments href="URL_OF_PAGE" num_posts="10" style="max-width:480px" width="300"></fb:comments> I have a custom login section. but I want to be able to see who posts a comment on the website if they are logged in. In other words this is exactly what I want to accomplish. if the user is logged in, and they post a comment, I want to be able to store the ID (or username, email, etc) of the user thats logged in - into my DB. if they are not logged in then i dont care to track it. any one have any thoughts? A: Subscribe to the comment.create method in javascript and then the check values in the response variable. FB.Event.subscribe('comment.create', function(response) { alert(JSON.stringify(response); });
{ "pile_set_name": "StackExchange" }
Q: Function that asks a ~special~ something and returns an answer I want to do it, but so far all I have is: print("Will you go out with me?") I want the code to work so that one can answer yes/no and if answer is yes then a message would return saying like the time, place, etc. The person I am asking is an R guru so it would mean a lot to them ~~(: Would love some help. Trying to get that date! A: Put the following into a file and then ask your friend to source the file. r <- readline("Will you go out with me? (respond 'yes' or 'no'): ") if(grepl("[Yy]es", r)) { cat("Date: 3/10/2018", "Time: 7pm", "Place: McDonalds", sep = "\n") } else { cat("Too bad, I'm a catch.") } Now your friend sources the file and BOOM, date! > source('~/.active-rstudio-document') Will you go out with me?: yes Date: 3/10/2018 Time: 7pm Place: McDonalds ... or BOOM, rejected! > source('~/.active-rstudio-document') Will you go out with me?: no Too bad, I'm a catch.
{ "pile_set_name": "StackExchange" }
Q: Traducción de la etiqueta [burninate-request] Los que ya sean familiares con la administración de etiquetas en enSO Meta conocen la etiqueta burninate-request, ¿cuál sería una buena traducción para nuestro sitio? De acuerdo a la descripción del sitio en inglés Requests to have a tag "burninated" (or deleted) from the system. En mi opinión, una traducción sería solicitud-de-borrado A: Personalmente solicitud-de-borrado me parece demasiado formal. En la versión en inglés se intenta mantener un espíritu desenfadado en el proceso de borrado de etiquetas porque es un proceso tedioso y aburrido, y es común ver solicitudes con títulos divertidos y con juegos de palabras. De hecho, burninate es una palabra inventada en Internet (mezcla de burn e incinerate si no me equivoco) que viene de la serie Homestar Runners, inspirada por el personaje Trogdor the Burninator: Creo que sería interesante mantener ese espíritu desenfadado de la versión en inglés, buscar alguna palabra (inventada o no) en la misma línea que burninate y utilizarla de manera paralela. Quizás podríamos buscar inspiración en alguna serie que haya influido en nuestra comunidad o en la sociedad en general, por ejemplo Bola de Dragón, el Chapulín Colorado, o el Cálico Electrónico (por mencionar algunas). Y si eligieramos una palabra relacionada con el fuego, quemar o tostar cosas (¿solicitud-de-quemado?¿solicitud-de-requemado?, lo siento no soy muy original) siempre podríamos mantener a Trogdor como mascota :)
{ "pile_set_name": "StackExchange" }
Q: ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name when I tried to create a new user it's says ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name from c:/RubyOnRails/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/ activemodel-3.2.3/lib/active_model/mass_assignment_security/ sanitizer.rb:48:in `process_removed_attri butes' A: A couple things: Mass Assignment usually means passing attributes into the call that creates an object as part of an attributes hash. That is, you pass a bunch of attributes in a hash into the call that creates the new object. For example: @user = User.create({:name => "My name", :user_type => "nice_user"}) However, Rails includes some basic security rules that mean not all attributes can be assigned that way by default. You have to specify which ones can beforehand. You do so like this: class user < ActiveRecord::Base attr_accessible :name, :user_type end If you don't specify an attribute is attr_accessible, and you pass it in to create the object, you get the error you posted. Here are more details: http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html The alternative is to set some of the attributes when you first create the record, and set others after -- like so: # In this example `user_type` is not attr_accessible so it needs to be set specifically @user = User.create({:name => "My name"}) @user.user_type = "nice_user" @user.save
{ "pile_set_name": "StackExchange" }
Q: Breeze.js getEntities returns no entity Using Breeze.js coupled with an Asp.net Web Api (with Entity Framework 6 Code First) I am unabled to get entities after a call to executeQuery(query). More specifically here is my call in javascript: entityManager.executeQuery(query) .then(function(data){ alert(data.results.length); // length > 0 --> has data !! alert(entityManager.getEntities().length); // == 0 has no data WHY?!! }); while executeQuery(query) does hit my api controller on the server and returns data to client because data.results.length > 0, it looks like data is not not cached because entityManager.getEntities().length == 0. How then can I track changes if data is not cached? Am I missing something? After googling around I found this post http://forum.ideablade.com/forum_posts.asp?TID=3739&title=entity-manager-cache-not-working where it is said that Simply put, Breeze requires that the models and dbcontext be in the same namespace. Is this the issue in play here? since I cannot change my namespaces (dbcontext and api controllers come from an external library I do not have control hover) what workaround could be used in this case? A: The most likely cause is that the objects returned by the server are not entity data ... at least not from the point of view of the Breeze client. Perhaps you can show us your query. Check out the "Query Result Debugging" topic in the Breeze documentation.
{ "pile_set_name": "StackExchange" }
Q: using startsWith and replaceFirst not working for me. I print all my phone contacts in the Android Monitor with the code below. Where a phone number begins with 00 I want to change the 00 to + . But it is not working. Can you tell me what is wrong please ? protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString( cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex( ContactsContract.Contacts.DISPLAY_NAME)); if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (pCur.moveToNext()) { String phoneNo = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); if (phoneNo.startsWith("00")) { System.out.println(phoneNo.replaceFirst("00", "+")); } System.out.println("Name: " + name); System.out.println("Phone No: " + phoneNo); } pCur.close(); } } } A: replaceFirst() returns a String, it doesn't mutate the object. You should perform assignment: phoneNo = phoneNo.replaceFirst("00", "+")
{ "pile_set_name": "StackExchange" }