text
stringlengths
64
89.7k
meta
dict
Q: How to use @Nullable and @Nonnull annotations more effectively? I can see that @Nullable and @Nonnull annotations could be helpful in preventing NullPointerExceptions but they do not propagate very far. The effectiveness of these annotations drop off completely after one level of indirection, so if you only add a few they don't propagate very far. Since these annotations are not well enforced there is a danger of assuming a value marked with @Nonnull is not null and consequently not performing null checks. The code below causes a parameter marked with @Nonnull to be null without raising any complaints. It throws a NullPointerException when it is run. public class Clazz { public static void main(String[] args){ Clazz clazz = new Clazz(); // this line raises a complaint with the IDE (IntelliJ 11) clazz.directPathToA(null); // this line does not clazz.indirectPathToA(null); } public void indirectPathToA(Integer y){ directPathToA(y); } public void directPathToA(@Nonnull Integer x){ x.toString(); // do stuff to x } } Is there a way to make these annotations more strictly enforced and/or propagate further? A: Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors. As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants. Another good tip is never returning null values, but using Null Object Pattern instead. A: Other than your IDE giving you hints when you pass null to methods that expect the argument to not be null, there are further advantages: Static code analysis tools can test the same as your IDE (e.g. FindBugs) You can use AOP to check these assertions This can help your code be more maintainable (since you do not need null checks) and less error-prone. A: I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link: Java 8's new Type Annotations In the above blog, it is recommended that: Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.
{ "pile_set_name": "StackExchange" }
Q: Expression regular for check phone numbers at word level I'm trying to write a RegEx to test if a number is valid and for valid I mean any number that matches country calling codes but also where the format of telephone numbers is standardized by ITU-T in the recommendation E.164. This specifies that the entire number should be 15 digits or shorter, and begin with a country prefix as said here so I did this: ^\+\d{2}|\d{3}([0-9])\d{7}$ But it's not working. In my case (VE numbers can't match the RegEx since this one are validated in another way) this input is valid: +1420XXXXXXXXXXX // Slovakia - X is a digit and could be more, tough, 5 minimum 001420XXXXXXXXXX // Slovakia - I've changed from + to 00 420XXXXXXXXXXXXX // Slovakia - I've removed the 00 o + but number still being valid +40XXXXXXXXXXXXX // Romania Invalid numbers are the one that doesn't match the RegEx and the one started with +58 since they are from VE. So, resuming, a valid number should have: +XX|+XXX plus 12|11 digits (5 minimum) where XX|XXX is the country code and then since maximum is 15 digits then should be 12 or 11 digits depending on the country format Can any help me with this? It's a one I called complex A: Few strange things going on with your regexp: \d is shorthand for [0-9] - fine to use both, but I'm wondering why they're mixed what you are searching with you OR (|) is "something that starts with +XX" i.e. plus and two numbers (^\+\d{2}) OR "something that ends with XXXXXXXXXXX" i.e. 11 numbers (\d{3}([0-9])\d{7}$) You need to group (with brackets) the OR choices, otherwise it is everything to the left or everything to the right (simplistically) ^\+(\d{2}|\d{3})([0-9])\d{7}$ There is, however, another way of giving the number of occurrences : {m,n} means occurs between m and n times. So you could say ^\+\d{7,15}$ (where 7 is your minimum 5 + the minimum country code of 2). To really do this, however, you might want to take a look here (https://code.google.com/p/libphonenumber/ 1) where there is a complete validation and formatting for all phone numbers available as javascript.
{ "pile_set_name": "StackExchange" }
Q: Best way to kill an out of process dll ('dllhost.exe' 'COM Surrogate') when an App exits? I am using the 'DllSurrogate' method to allow a 64-bit C# exe to talk to a 32-bit C# dll. The method is described in Hosting a .NET DLL as an Out-Of-Process COM Server (EXE). When the App runs an extra process called 'dllhost.exe *32' automatically shows up in Task Manager, with the description 'COM Surrogate'. This is the link between the App and the 32-bit dll. The problem I have is that this process is not killed when the App exits. Can someone suggest the recommended way of dealing with this? I could find the process and kill it as my App closes, but I would need to make sure: It is my 'COM Surrogate', not one belonging to another App. It is not being used by another running instance of my App. Is there a more direct link between my App and this process that I can check? A: A COM surrogate, which refuses to terminate, usually indicates outstanding references to a CoClass or resources, which haven't been released yet. You can enforce the release by resorting to ReleaseComObject or FinalReleaseComObject. However, when using this approach, you should be aware of the associated risks, as described here. If you're still seeing no other way than terminating the COM surrogate manually, you'll need to enumerate all dllhost.exe processes on your machine. Extract the command line of each candidate and look for the /ProcessId argument. If it matches the GUID of your CoClass, then you have found the match.
{ "pile_set_name": "StackExchange" }
Q: OLS: $E[\epsilon_{it}^T\epsilon_{it}] \not= 0$ in 1st equation biases standard errors in 2nd equation? Suppose ${X_{it}},{Y_{it}}$ are time series with $X_{it}\sim N(0.1,1)$, ($\sigma^2(Y_{it}) = 1$ and $mean(Y_{it})$ is similar to that for $X_{it}$, but changes when the dummy = 1). and $t \in \{1,2,...,200\}$, $i \in \{1,2,...,N\}$. In a real world setting this will be periodic stock market returns over $N$ firms (but you can ignore this). There is a dummy, $D_t$ that's equal to unity over $t \in \{150,151,...,200\}$ and equal to zero otherwise. The time series model to be estimated with OLS $\forall i$ is: $(1) Y_{it} = \alpha_i + \beta_i X_{it} + \gamma_i D_{t} + \epsilon_{it}$ This model generally adheres to the Gauss-Markov assumptions for each $i$. However, we have $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$ for all $i$ and $j$. The next step is to construct a vector of gammas using the $N$ estimates of model $(1)$. Call this vector $\bf{\hat{\gamma}}$. We then use this in the cross-sectional model: $(2) \hat{\gamma}_i = a + b Z_i + u_i$ where $Z_i$ is some cross-sectional variable that doesn't cause any violations in OLS assumptions and is relevant for explaining $\hat{\gamma}_i$. The claim in the applied econometrics literature is that $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$ in model $(1)$ leads to (i) No problem for the OLS coefficient estimates in $(2)$, but (ii) Biased standard errors in $(2)$. Can someone please post ideas about why this is the case? I don't understand what $\epsilon_{it}^T$ is in the expression $E[\epsilon_{it}^T \epsilon_{jt}] \not= 0$. Of course $\epsilon_{it}$ is a scalar and you can't transpose a scalar. This is seen HERE, where they apply this methodology. A: In order to be sure you need to go into the details, this implies comparing the true variance covariance matrix with the one you get in the second ols stage. The true one: This can be obtained by replacing eq.2 into eq.1, pooled OLS follows, and from it, the true $\hat a , \hat b$ variance covariance matrix: $Y_{it} = \alpha_i + \beta_i X_{it} + aD_t + bD_tZ_{i} +D_t u_{i} + \epsilon_{it}$ Using matrix notation to split the equation in $\gamma$ parameters and others leads to: $Y = X\theta + Z\gamma + \varepsilon$ where we are interested in $V(\hat \gamma)$ , $\gamma=[a \; b] $, Z is a two column vector $Z=[D_t \; D_tZ_i]_{[i=1,..,N;t=1,...,T]}$ ( a similar structure defines X but this is not of interest) and where $V(\varepsilon) =\Sigma$ has a full structure of between firms covariances that's why it's not diagonal ($\sigma^2I_{NT}$) like in the GAUSS-MARKOV assumptions. By Frish-Waugh we can express $\gamma$ ols as : $\hat \gamma = (Z'M_{X}Z)^{-1}Z'M_{X}Y$ where $M_X= I-X(X'X)^{-1}X' $ which implies the following true variance: $V(\hat \gamma) = H\Sigma H'$ where $H = (Z'M_{X}Z)^{-1}Z'M_{X}$ The other one Under the assumption of non correlated firms (and time periods but this is not the issue), $\Sigma$ has a simplier diagonal structure $\Delta$. This means that $\Delta$ triangular terms are 0. Under an even simpler specification,( the one that is estimated by default by econometric and statistical software for OLS) $\Sigma$ follows GAUSS-Markov assumptions meaning that even the diagonal terms are equal thus $\Sigma$ is downgraded to $\sigma^2I$ This implies that not considering between firms correlation would lead to $V(\hat\gamma) $as: $V(\hat \gamma) = H\Delta H'$ or $V(\hat \gamma) = H\sigma^2I H' \equiv \sigma^2(Z'M_xZ)^{-1}$ which, as it can be seen, are not equal to the true one.
{ "pile_set_name": "StackExchange" }
Q: WooCommerce - How to get shipping class of cart items in calculate_shipping function? I have created a WooCommerce plugin that enables free shipping for subscribers. It seems to have broken following a recent WooCommerce upgrade. Specifically, the problem seems that the shipping class of the cart items may not be being retrieved correctly. Here is my calculate_shipping code - can anyone advise what is wrong? /** * Add free shipping option for customers in base country with an active subscription, * but only if the cart doesn't contain an item with the 'heavy-item-shipping-class'. * * @access public * @param mixed $package * @return void */ public function calculate_shipping($package) { global $woocommerce; // Check country and subscription status if (is_user_in_base_country() && does_user_have_active_subscription()) { // This flag will be set to TRUE if cart contains heavy items $disable_free_shipping = FALSE; // Get cart items $cart_items = $package['contents']; // Check all cart items foreach ($cart_items as $cart_item) { // Get shipping class $shipping_class = $cart_item['data']->shipping_class; // *** IS THIS THE RIGHT WAY TO GET THE SHIPPING CLASS ??? *** // If heavy item, set flag so free shipping option is not made available if ($shipping_class === 'heavy-item-shipping-class') { // Set flag $disable_free_shipping = TRUE; // Enough break; } } // If appropriate, add the free shipping option if ($disable_free_shipping === FALSE) { // Create the new rate $rate = array( 'id' => $this->id, 'label' => "Free Shipping", 'cost' => '0', 'taxes' => '', 'calc_tax' => 'per_order' ); // Register the rate $this->add_rate($rate); } else { // Doesn't qualify for free shipping, so do nothing } } } UPDATE I've looked at the %package array and noticed that it now contains the shipping class under [shipping_class:protected]. (Previously, this must have been [shipping_class].) Is it possible to extract this data? If not, what is the correct way of doing it? A: I found the solution. Now, it seems the only way to get the shipping class of a product/item is to call get_shipping_class() on it. So, in my code snippet, above, I changed... $shipping_class = $cart_item['data']->shipping_class; ...to... $shipping_class = $cart_item['data']->get_shipping_class(); Hopefully, this will help someone else. :)
{ "pile_set_name": "StackExchange" }
Q: Motor Shield and HC-06 Bluetooth Module competing for pins So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time? Thanks in advance! A: The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins. You could either solder some wires to the TX and RX pins, or use something like the proto shield to sandwich in the middle of it, and connect the BT module onto this shield. You could also remove all the male headers from the motor shield, and replace them with stacking headers
{ "pile_set_name": "StackExchange" }
Q: What does "No more variables left in this MIB View" mean (Linux)? On Ubuntu 12.04 I am tring to get the subtree of management values with the following command: snmpwalk -v 2c -c public localhost with the last line of the output being iso.3.6.1.2.1.25.1.7.0 = No more variables left in this MIB View (It is past the end of the MIB tree) Is this an error? A warning? Does the subtree end there? A: There's a bit more going on here than you might suspect. I encounter this on every new Ubuntu box that I build, and I do consider it a problem (not an error, but a problem--more on this down further). Here's the technically-correct explanation (why this is not an "error"): "No more variables left in this MIB View" is not particularly an error; rather, it is a statement about your request. The request started at something simple, say ".1.3" and continued to ask for the "next" lexicographic OID. It got "next" OIDs until that last one, at which point the agent has informed you that there's nothing more to see; don't bother asking. Now, here's why I consider it a problem (in the context of this question): The point of installing "snmpd" and running it is to gather meaningful information about the box; typically, this information is performance-oriented. For example, the three general things that I need to know about are network-interface information (IF-MIB::ifHCInOctets and IF-MIB::ifHCOutOctets), disk information (UCD-SNMP-MIB::dskUsed and UCD-SNMP-MIB::dskTotal), and CPU information (UCD-SNMP-MIB::ssCpuRawIdle, UCD-SNMP-MIB::ssCpuRawWait, and so on). The default Ubuntu "snmpd" configuration specifically denies just about everything useful with this configuration (limiting access to just enough information to tell you that the box is a Linux box): view systemonly included .1.3.6.1.2.1.1 view systemonly included .1.3.6.1.2.1.25.1 rocommunity public default -V systemonly This configuration locks the box down, which may be "safe" if it will be on an insecure network with little SNMP administration knowledge available. However, the first thing that I do is remove the "-V systemonly" portion of the "rocommunity" setting; this will allow all available SNMP information to be accessed (read-only) via the community string of "public". If you do that, then you'll probably see what you're expecting, which is pages and pages of SNMP information that you can use to gauge the performance of your box.
{ "pile_set_name": "StackExchange" }
Q: InsertSort de lista doble enlazada a lista simple Tengo 2 listas (una simple y una doble), en la doble implemente el método de insertsort sin ningún problema y me gustaría implementar el mismo método de ordenamiento pero en la lista simple, el código es el siguiente. Insertar al inicio: void Listaven::insertaInicio(Vendedor dato) { Nodo * tmp = new Nodo; tmp->guardaObjeto(dato); tmp->guardaNodoSig(NULL); bool nada = vacia(); if (nada) { inicio = final = tmp; } else { tmp->sig = inicio; inicio->ant = tmp; tmp->ant = NULL; inicio = tmp; } ordenar(); int codigoVendedor = dato.damecodigoVendedor(); cout << "Has agregado un vendedor con el codigo: '" << codigoVendedor << "'" << endl; } Metodo de ordenamiento: void Listaven::ordenar() { Nodo *tmp = inicio; Nodo *aux; Vendedor recuperar; while (tmp) { recuperar = tmp->dato; aux = tmp; while (aux->ant != NULL && recuperar.damecodigoVendedor()<aux->ant->dato.damecodigoVendedor()) { aux->dato = aux->ant->dato; aux = aux->ant; } aux->dato = recuperar; tmp = tmp->sig; } } Así es como lo tengo para poder ordenarlo en la lista doblemente enlazada. Cual seria la forma para implementarlo en la lista simplemente enlazada, ya que por ende en la lista simple no hay parte ANT solo parte SIG. A: Depende del tipo de ordenación que quieras el algoritmo puede variar; podrías probar con un burbuja de toda la vida, que es más conocido por su sencillez que por su eficiencia. Por ejemplo: void ordenar() { for (Nodo *head = inicio; head; head = head->sig) { for (Nodo *tail = head->sig; tail; tail = tail->sig) { if (head->dato.damecodigoVendedor() > tail->dato.damecodigoVendedor()) { std::swap(head->dato, tail->dato); } } } } Puedes ver el código funcionando [aquí]. Evidentemente me he inventado el Vendedor y el Listaven, no se cuál es tu implementación.
{ "pile_set_name": "StackExchange" }
Q: JQuery - Scroll functions are not working I'd like to display circlefull animation on page scroll with jquery, but no one scroll function works. > $("body").scrollTop(); 0 <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'> </script> <script type="text/javascript"> $(document).ready( function (){ alert('ready'); $('#htmlbody').scroll( function (){ alert('scroll'); }); }); </script> No one works. What's problem in? Any errors are not logging in console also. A: $('#htmbody') is wrong. Use this: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(window).scroll(function(){ alert('scroll'); }); }); </script> Demo: http://jsfiddle.net/wqZ6G/ If you want to call HTML and BODY to animate scroll top use: $('html, body').animate({scrollTop:'400px'},{duration:1000}); Demo: http://jsfiddle.net/wqZ6G/1/
{ "pile_set_name": "StackExchange" }
Q: XSD attribute (Not an element) should not be an empty string What changes I need to make in below defined schema, so that attribute named code should not be an empty string/validate if code is empty? <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xsd:attribute name="code" type="xsd:string"/> <xsd:element name="Root"> <xsd:complexType> <xsd:sequence> <xsd:element name="Child" nillable="false"> <xsd:complexType> <xsd:sequence> <xsd:element name="childAge"> <xsd:simpleType> <xsd:restriction base="xsd:integer"/> </xsd:simpleType> </xsd:element> </xsd:sequence> <xsd:attribute ref="code" use="required"></xsd:attribute> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> A: Type xsd:string type includes the empty string, so using <Child code=""> Is valid according to your schema. There are several ways to restrict the type. If you just want to restrict the length you could use: <xsd:attribute name="code"> <xsd:simpleType> <xsd:restriction base="xsd:string"> <xsd:minLength value="1"/> </xsd:restriction> </xsd:simpleType> </xsd:attribute> Or you can use a type that does not include the empty string as valid, for example: <xsd:attribute name="code" type="xsd:NMTOKEN" /> which also won't allow special characters or spaces. If your code requires a specific pattern, you might want to specify that in a regular expression, for example: <xsd:restriction base="xsd:string"> <xsd:pattern value="[A-Z][0-9]{4}"/> </xsd:restriction> which will also not validate for empty strings.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to compile a standalone Fortran executable in Linux? For example, consider that I wrote a Fortran program in one computer and want to run it on another computer which may not have required libraries and/or has a different compiler (or even better, no Fortran compiler at all). Is it possible to create an executable with all its dependencies? I am using gfortran (7.2.1) in Fedora 26 and sometimes use LAPACK routines in my code. Using -static option with the program program main write (*,*) 'Hello' end I get the output gfortran -static a.f90 /usr/bin/ld: cannot find -lm /usr/bin/ld: cannot find -lm /usr/bin/ld: cannot find -lc collect2: error: ld returned 1 exit status There is no error with gfortran -static-libgfortran a.f90 A: In Fedora, gcc does not ship by default with static libraries. You need to install the package glibc-static for the -static option to work, as hinted in this related question. Note that -static-libgfortran will only do static linking of the libgfortran library and that you must have static versions of your dependencies as well.
{ "pile_set_name": "StackExchange" }
Q: Firebase Live Database Listener first-read/update distinction? For iOS, using Swift, does Firebase provide an easy way to distinguish between the first read done on all the data in a database path when the listener comes online and every update after the initial read? I could implement code to account for this, but it feels hacky. A flag or some value returned by Firebase indicating this would be convenient. A: The Firebase Realtime Database makes no distinction between the first event it fires for a listener and subsequent events. If you need this distinction, you'll have to maintain a flag in your own code.
{ "pile_set_name": "StackExchange" }
Q: Disable select list with knockout I'm trying to disable a select list using knockout disable binding. It doesn't work. The list is still enabled when the value (readOnly.IsNew) is true. I've checked that the value is correct i.e. readOnly.IsNew. It works fine for a checkbox, just not the select list. <select name="myDropDown" data-bind=" options: $parents[1].readOnly.myList, value: selectedMethod, disable: !(readOnly.isNew)"></select> A: I guess that isNew is observable, in that case you need to unwarp it when it is used in expressions: disable: !(readOnly.isNew()) If you put just observable to data-bind knockout automatically unwrap it, for example you could write and it would work: disable: readOnly.isNew However when you use expression in data-bind knockout cannot unwrap observable and you should do it by yourself. For example if you want to hide select when there are no records you should write the following: visible : $parents[1].readOnly.myList().length > 0
{ "pile_set_name": "StackExchange" }
Q: How to get high accuracy in CNNs? ML and Data Science world. I am a newbie to CNNs, but do possess a basic understanding of ML and Neural Networks. I wanted to create my own CNN that works on the Cats and Dogs Dataset. I preprocessed the data and built my network, but when I fit the model with the data, I am not able to get more than 55% accuracy, which means the model isn't learning anything. Can anybody explain what I am doing wrong here? model = Sequential() model.add(Conv2D(filters=32, kernel_size=(3,3),padding='SAME', input_shape=X[0].shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2), dim_ordering='th')) model.add(Conv2D(filters=64, kernel_size=(3,3), padding='SAME')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2), dim_ordering='th')) model.add(Dropout(rate=0.4)) model.add(Conv2D(filters=128, kernel_size=(3,3), padding='SAME')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2), dim_ordering='th')) model.add(Dropout(rate=0.35)) #model.add(Conv2D(filters=64, kernel_size=(3,3), padding='SAME')) #model.add(Activation('relu')) #model.add(MaxPooling2D(pool_size=(2,2), dim_ordering='th')) model.add(Flatten()) model.add(Dense(1024)) model.add(Activation('relu')) model.add(Dropout(rate=0.3)) model.add(Dense(2)) model.add(Activation('softmax')) And this is the optimizer part: opt = keras.optimizers.SGD(lr=0.0001, decay=0.0) model.compile(optimizer=opt, loss='binary_crossentropy', metrics['accuracy']) print(model.summary()) model.fit(X, np.array(Y), validation_data=(test_x, np.array(test_y)), epochs=30, verbose=2) I've been stuck on this for the past 2 days. Any and all help is appreciated. Thanks. A: Adding multiple layers before pooling will increase the feature extraction, softmax function is used when there are more than 2 categories/classes, try with sigmoid fuction, Also, Data Augmentation will help you with tuning hyper-parameters(tilt, width-shift, shear, rotation etc). Go through the documentation. Give a try with this code, If RMSprop yieds less accuracy try adam, model = Sequential() model.add(Conv2D(32, 3, 3, border_mode='same', input_shape=input_shape, activation='relu')) model.add(Conv2D(32, 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, 3, 3, border_mode='same', activation='relu')) model.add(Conv2D(64, 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, 3, 3, border_mode='same', activation='relu')) model.add(Conv2D(128, 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(256, 3, 3, border_mode='same', activation='relu')) model.add(Conv2D(256, 3, 3, border_mode='same', activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy',optimizer=RMSprop(lr=0.0001),metrics=['accuracy'])
{ "pile_set_name": "StackExchange" }
Q: Fabricjs function to join 2 objects with line I have a canvas where I can click to place icons and link those icons with a line, but I can't manage to get the lines to follow when moving the icon objects. I tried the following, but I can't manage to lock the ends of the lines to the icon objects. My effort so far: JSFIDDLE canvas.on('mouse:move', function (obj) { var line = canvas.getItemByName('line'); var objEl = canvas.getActiveObject(); var type = objEl.get('type'); var leftEl = objEl.left; var topEl = objEl.top; canvas.getObjects().forEach((obj) => { var lineX1 = line.get('x1'); var lineY1 = line.get('y1'); var lineX2 = line.get('x2'); var lineY2 = line.get('y2'); if (lineX1 == leftEl && lineY1 == topEl) { line.set({ x1: leftEl, y1: topEl }); canvas.renderAll(); }; }); line.set('opacity', 1); }); A: You have to keep the reference when you create your object, look at my comments: (function() { var canvas = this.__canvas = new fabric.Canvas('c', { selection: false }); fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center'; function makeCircle(left, top, line1, line2, line3, line4) { // Note: Circle has its own variable var c = new fabric.Circle({ left: left, top: top, strokeWidth: 5, radius: 12, fill: '#fff', stroke: '#666' }); // Note: properties added to the object c.hasControls = c.hasBorders = false; // Note: references the line that refers to this joint c.line1 = line1; c.line2 = line2; c.line3 = line3; c.line4 = line4; return c; } function makeLine(coords) { return new fabric.Line(coords, { fill: 'red', stroke: 'red', strokeWidth: 5, selectable: false, evented: false, }); } // Create a line and assign it to a variable var line = makeLine([ 250, 125, 250, 175 ]), line2 = makeLine([ 250, 175, 250, 250 ]), line3 = makeLine([ 250, 250, 300, 350]), line4 = makeLine([ 250, 250, 200, 350]), line5 = makeLine([ 250, 175, 175, 225 ]), line6 = makeLine([ 250, 175, 325, 225 ]); canvas.add(line, line2, line3, line4, line5, line6); canvas.add( // Here we set the references to the lines makeCircle(line.get('x1'), line.get('y1'), null, line), makeCircle(line.get('x2'), line.get('y2'), line, line2, line5, line6), makeCircle(line2.get('x2'), line2.get('y2'), line2, line3, line4), makeCircle(line3.get('x2'), line3.get('y2'), line3), makeCircle(line4.get('x2'), line4.get('y2'), line4), makeCircle(line5.get('x2'), line5.get('y2'), line5), makeCircle(line6.get('x2'), line6.get('y2'), line6) ); // Here, by reference, we move the line according to the moving object canvas.on('object:moving', function(e) { var p = e.target; p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top }); canvas.renderAll(); }); })(); A: With the help of this answer I was able to reference to any canvas object and lock the lines as I go. var canvas = new fabric.Canvas('c'); fabric.Canvas.prototype.getItemByName = function(name) { var object = null, objects = this.getObjects(); for (var i = 0, len = this.size(); i < len; i++) { if (objects[i].name && objects[i].name === name) { object = objects[i]; break; } } return object; }; var currentColor; var defaultIcon = { width: 40, height: 30, originX: 'center', originY: 'center', hasControls: false, }; var iconTriangle = new fabric.Triangle(defaultIcon); setColor('green'); canvas.add(iconTriangle); //disable icon & hide when hovering over existing icon canvas.on('mouse:over', function(obj) { iconTriangle.set('opacity', 0); canvas.renderAll(); }); //restor icon & unhide canvas.on('mouse:out', function(e) { if (document.getElementById("on").checked == true) { // if 'target' is null, means mouse is out of canvas if (e.target) { iconTriangle.set('opacity', 1); } else { iconTriangle.left = -100; iconTriangle.top = -100; } canvas.renderAll(); }; }); //move pointer icon canvas.on('mouse:move', function(obj) { iconTriangle.top = obj.e.y - 100; iconTriangle.left = obj.e.x - 10; canvas.renderAll(); }); //count each by type and place new icon canvas.on('mouse:up', function(e) { if (e.target) { return } var red = getObjectsBy((obj) => obj.fill === 'red').length; var green = getObjectsBy((obj) => obj.fill === 'green').length; var yellow = getObjectsBy((obj) => obj.fill === 'yellow').length; document.getElementById("greentally").value = green; document.getElementById("yellowtally").value = yellow; document.getElementById("redtally").value = red; addIcon(e.e.x - 10, e.e.y - 100, currentColor); }); function setColor(color) { currentColor = color; iconTriangle.setColor(currentColor); canvas.renderAll(); } function getObjectsBy(fn) { return canvas.getObjects().filter(fn) } function addIcon(x, y, color) { var icon = new fabric.Triangle(defaultIcon); if (document.getElementById("icon").checked == true) { icon.setColor(color); icon.left = x; icon.top = y; canvas.add(icon); } else if (document.getElementById("link").checked == true) { iconTriangle.set('opacity', 0); icon = null; }; canvas.renderAll(); } //set icon type $(".switch").click(function() { if (document.getElementById("green").checked == true) { setColor('green'); } else if (document.getElementById("yellow").checked == true) { setColor('yellow'); } else if (document.getElementById("red").checked == true) { setColor('red'); } }); document.getElementById("icon").checked = true; //link icons with line $("input").change(function () { mode = "draw"; canvas.on('mouse:up', function (o) { isDown = true; var icon = canvas.getItemByName('icon'); if (document.getElementById("link").checked == true) { if (canvas.getActiveObjects().length == 1) { mode = "draw"; var pointer = canvas.getActiveObject(); var points = [pointer.left, pointer.top, pointer.left, pointer.top]; if (mode == "draw") { line1 = new fabric.Line(points, { strokeWidth: 5, fill: '#39ff14', stroke: '#39ff14', originX: 'center', originY: 'center', selectable: false, hasControls: false, hasBorders: false, evented: false, targetFindTolerance: true, name: 'line1', }); canvas.add(line1); line1.sendToBack(); }; canvas.renderAll(); } else { return; }; }; }); if (document.getElementById("link").checked == true) { canvas.on('mouse:move', function (o) { line1.set('opacity', 0.4); if (o.target !== null) { var x2 = o.target.left; var y2 = o.target.top; if (mode == "draw") { line1.set({ x2: x2, y2: y2 }); canvas.renderAll(); } } else { var pointer = canvas.getPointer(o.e); if (mode == "draw") { line1.set({ x2: pointer.x, y2: pointer.y }); canvas.renderAll(); } } line1.set('opacity', 1); }); canvas.on('mouse:down', function (e) { if (document.getElementById("link").checked == true) { canvas.selection = false; var line1 = canvas.getItemByName('line1'); var objEl = e.target; var type = objEl.get('type'); if (type !== 'text') { canvas.remove(line1); } }; }); }; canvas.renderAll(); }); $("input").change(function () { if (document.getElementById("link").checked == true) { // we need this here because this is when the canvas gets initialized ['object:moving', 'object:scaling'].forEach(addChildMoveLine); function addChildLine(options) { if (document.getElementById("link").checked == true) { canvas.off('object:selected', addChildLine); // add the line var fromObject = canvas.addChild.start; var toObject = options.target; var from = fromObject.getCenterPoint(); var to = toObject.getCenterPoint(); var line = new fabric.Line([from.x, from.y, to.x, to.y], { strokeWidth: 5, fill: '#39ff14', stroke: '#39ff14', originX: 'center', originY: 'center', selectable: false, hasControls: false, hasBorders: false, evented: false, targetFindTolerance: true, name: 'line', }); canvas.add(line); // so that the line is behind the connected shapes line.sendToBack(); // add a reference to the line to each object fromObject.addChild = { // this retains the existing arrays (if there were any) from: (fromObject.addChild && fromObject.addChild.from) || [], to: (fromObject.addChild && fromObject.addChild.to) } fromObject.addChild.from.push(line); toObject.addChild = { from: (toObject.addChild && toObject.addChild.from), to: (toObject.addChild && toObject.addChild.to) || [] } toObject.addChild.to.push(line); // to remove line references when the line gets removed line.addChildRemove = function () { fromObject.addChild.from.forEach(function (e, i, arr) { if (e === line) arr.splice(i, 1); }); toObject.addChild.to.forEach(function (e, i, arr) { if (e === line) arr.splice(i, 1); }); } canvas.discardActiveObject(); }; } function addChildMoveLine(event) { if (document.getElementById("link").checked == true) { canvas.on(event, function (options) { var object = options.target; var objectCenter = object.getCenterPoint(); // udpate lines (if any) if (object.addChild) { if (object.addChild.from) object.addChild.from.forEach(function (line) { line.set({ 'x1': objectCenter.x, 'y1': objectCenter.y }); }) if (object.addChild.to) object.addChild.to.forEach(function (line) { line.set({ 'x2': objectCenter.x, 'y2': objectCenter.y }); }) } canvas.renderAll(); }); }; } function addChild(o) { if (document.getElementById("link").checked == true) { var line = canvas.getItemByName('line'); var objEl = canvas.getActiveObject(); var type = objEl.get('type'); canvas.addChild = { start: canvas.getActiveObject() } // for when addChild is clicked twice canvas.off('object:selected', addChildLine); canvas.on('object:selected', addChildLine); }; }; canvas.on('mouse:down', function (e) { if (document.getElementById("link").checked == true) { var line = canvas.getItemByName('line'); canvas.selection = false; if (e.target !== null) { addChild(); } else { canvas.discardActiveObject(); } canvas.on('mouse:over', function () { canvas.discardActiveObject(); }); canvas.on('mouse:out', function () { canvas.forEachObject(function (obj) { if (obj.get('name') !== 'cursor') { obj.set('opacity', 1); } }); }); }; }); }; }); canvas { border: 1px solid #ccc; } .tally { position: fixed; width: 50px; left: 255px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script> <b>PLACE:</b> <input class="switch" name="iconOn" type="radio" id="icon" /> <b>ICON</b> <input class="switch" name="iconOn" type="radio" id="link" /> <b>LINK</b> <br> <input class="switch" checked name="iconType" type="radio" id="green" />Green <input class="tally" disabled id="greentally" type="text" value="0"> <br> <input class="switch" name="iconType" type="radio" id="yellow" /> Yellow <input class="tally" disabled id="yellowtally" type="text" value="0"> <br> <input class="switch" name="iconType" type="radio" id="red" /> red <input class="tally" disabled id="redtally" type="text" value="0"> <canvas id="c" width="600" height="300"></canvas>
{ "pile_set_name": "StackExchange" }
Q: Adaptec 6405 RAID controller turned on red LED I have a server with an Adaptec 6405 RAID controller and 4 disks in a RAID 5 configuration. Staff in the data center called me because they noticed a red LED was turned on in one of the drive bays. I have then checked the status using 'arcconf getconfig 1' and I got the status message 'Logical devices/Failed/Degraded: 2/0/1'. The status of the logical devices was listed as 'Rebuilding'. However, I did not get any suspicious status of the affected physical device, the S.M.A.R.T. setting was 'no', the S.M.A.R.T. warnings were '0' and also 'arcconf getsmartstatus 1' returned no problems with any of the disk drives. The 'arcconf getlogs 1 events tabular' command gives lots of output (sorry, can't paste the log file here as I only have remote console access, I could post a screenshot though). Here are some sample entries: eventtype FSA_EM_EXPANDED_EVENT grouptype FSA_EXE_SCSI_GROUP subtype FSA_EXE_SCSI_SENSE_DATA subtypecode 12 cdb 28 00 17 c4 74 00 00 02 00 00 00 00 data 70 00 06 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 0 The 'arcconf getlogs 1 device tabular' command reports mediumErrors 1 for two of the disks. Today, I have checked the status of the controller again. Everything is back to normal, the controller status is now 'Logical devices/Failed/Degraded: 2/0/0', the logical devices are also all back to 'Optimal'. I was not able to check the LED status, my guess is that the red LED is off again. Now I have a lot of questions: what is a possible cause for the medium error, why it is not reported by the SMART log too? Should I replace the disk drives? They were purchased just a month ago. The rebuilding process took one or two days, is that normal? The disks are 2 TByte each and the storage system is mostly idling. the timestamp of the logs seem to show the moment of the log retrieval, not the moment of the incident. Please advise, all help is very appreciated. A: what is a possible cause for the medium error, why it is not reported by the SMART log too? COULD be a not smart related error? Depending on Cabling a SAS incompatibility. Should I replace the disk drives? They were purchased just a month ago Oh man, you ask that? They are under full warranty now - what do you gain by NOT replacing them and waiting until the warranty expires? The rebuilding process took one or two days, is that normal? The disks are 2 TByte each and the storage system is mostly idling. Well, yes. Be happy it worked. See, RAID 5, 23TB discs = no protection, RAID 5 starts failing over 1tb. Welcome to a world of pain - if you value your data, better put in Raid 6. They are big slow drives that take ages to rebuild, yes. the timestamp of the logs seem to show the moment of the log retrieval, not the moment of the incident. Possible.
{ "pile_set_name": "StackExchange" }
Q: Copy rows which corresponds to search data My project has old information on Sheet1 and I import new data onto Sheet2. Column A (on both sheets) contains a 4 digit number. What I'm trying to do is find the row on Sheet1 that has the same 4 digit number as my new information on Sheet2 (to ensure I'm updating the correct information) and overwrite the old entry with the new (I also have it highlighting if there's been a date change, but that's not critical at this point; dates are in column E). Also, if there is no corresponding entry on Sheet1, I want to be able create a new entry in the next available row. The code that I've written so far does OK for one row, but has problems that I'm having trouble getting past: The Do While loop will run forever when there is no match. I can't figure out how to loop through all of the cells I want to search on Sheet1 as well as all of my search terms on Sheet2 (I was thinking I had to check every cell with info on Sheet1 Col A for each search term on Sheet2, but from everything I've seen online, it seems there has to be a better way, but I'm too green to figure it out). Code: Private Sub DoWork() Dim billOr As Range Dim billTgt As Range Dim tgtCell As Range Dim orCell As Range Dim compareBill As Integer Dim compareDate As Integer Dim x As Integer Dim i As Integer i = 1 x = 2 Set billOr = Sheets("Sheet2").Range("A" & i) Set billTgt = Sheets("Sheet1").Range("A" & x) Set orCell = Sheets("Sheet2").Range("E" & i) compareBill = InStr(billOr.Value, billTgt.Value) Do While compareBill <> 1 compareBill = InStr(billOr.Value, billTgt.Value) Set billTgt = billTgt.Offset(1, 0) Loop Set tgtCell = Sheets("Sheet1").Range("E" & x) compareDate = InStr(orCell, tgtCell) If compareDate = 0 Then tgtCell.EntireRow.Value = orCell.EntireRow.Value tgtCell.EntireRow.Interior.ColorIndex = 6 Else tgtCell.EntireRow.Value = orCell.EntireRow.Value End If End Sub Any help would be appreciated, even if it's just pointing me in the right direction. A: Ignoring the date part: Private Sub DoWork() Dim billOr As Range Dim billTgt As Range Dim shtDest as Worksheet Set billOr = Sheets("Sheet2").Range("A1") Set shtDest = Sheets("Sheet1") Do While billOr.value <> "" Set billTgt = shtDest.columns(1).find(billOr.value, _ lookat:=xlwhole) If billTgt Is Nothing Then Set billTgt = shtDest.cells(rows.count,1) _ .End(xlUp).Offset(1,0) Debug.Print "copying new row to " & billTgt.Address() End If billOr.entirerow.copy billTgt Set billOr = billOr.Offset(1,0) Loop End Sub
{ "pile_set_name": "StackExchange" }
Q: Erlang: convert HTTP GET param to Unicode I am using connector on Erlang. It gets requests from Javascript like "controler?q=value". If I send a value in Unicode, the browser sends an encoded string. http://127.0.0.1:8001/controler?q=%D1%82%D0%B5%D1%81%D1%82 How to convert this string to UTF-8? A: I wrote a module for similar purpose some time ago: https://gist.github.com/816291 You can use it like this: io:format("~ts~n",[uri:decode_uri_component("%D1%82%D0%B5%D1%81%D1%82")]). тест ok
{ "pile_set_name": "StackExchange" }
Q: Spring Boot 2, Spring Security 5 and @WithMockUser Since I migrated to Spring Boot 2.0.5 from 1.x, with no mean to disable security, I can't get test roles to work on mock MVC tests : @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class ApplicationsControllerShould { ... @Autowired private MockMvc mockMvc; private ObjectMapper mapper = new ObjectMapper(); @Test @WithMockUser(roles = "ADMIN") public void handle_CRUD_for_applications() throws Exception { Application app = Application.builder() .code(APP_CODE).name(APP_NAME) .build(); mockMvc.perform(post("/applications") .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(mapper.writeValueAsString(app))) .andExpect(authenticated()) .andExpect(status().isOk()); // failure 403! ... My controller endpoint isn't even protected! @RestController @RequestMapping("/applications") public class ApplicationsController { ... @PostMapping public Application addApplication(@RequestBody Application application) { Assert.isTrue(!applicationsDao.existsById(application.getCode()), "Application code already exists: " + application.getCode()); return applicationsDao.save(application); } } So I have in the test a session (#authenticated fails when @WithMockUser is commented out) and a role by the way (ROLE_ADMIN is visible in traces) but my request is being rejected and I don't understand what I did wrong. Thx for any idea! A: Ok... the good old CSRF stuff, then... logging.level.org.springframework.security=DEBUG 2018-10-02 10:11:41.285 DEBUG 12992 --- [ main] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost/applications/foo Application app = Application.builder() .code(APP_CODE).name(APP_NAME) .build(); mockMvc.perform(post("/applications").with(csrf()) // oups... .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(mapper.writeValueAsString(app))) .andExpect(authenticated()) .andExpect(status().isOk()); // there we go!
{ "pile_set_name": "StackExchange" }
Q: Deformation of Sphere using Transformations I have a graphic related question. I need to have a transformation matrix that I have no idea about what it is. The problem is to create right image from the right sphere. I created those images in Maya, but I need some matrices for the graphics course. Here is the image: Our professor told us to use some sine and cosine in our transformations, but I have no idea what he meant. I thought of intersecting a plane from the grid(that is xz plane) and sphere, and then scaling down the resulting circle. Would that work? I also checked this paper, however it looks like a bit advanced for me. Another thing is I guess that paper is not about the same type of information I was looking for. It would be great if you could help me. A: This type of transformation cannot be done with a (single) matrix; those can only handle linear transformations, and the image you posted plainly shows a non-linear transformation. (A linear transformation could deform the sphere into an ellipsoid, but it couldn't produce a waist in the middle like that.) I'm going to assume that what your professor meant here was to apply a different matrix to each vertex of the sphere, where the matrix depends on the vertex's position. So to apply it, you'd iterate over the vertices, calculate the matrix for each vertex according to some formula that you can make up, and then transform that vertex by the resulting matrix. For example, to suck in the middle of the sphere like that shown, you might want to use a scaling in the xz plane, where the amount of scaling depends on the vertex's y-coordinate. You'd make up a function that would give you a scale factor less than 1.0 when y = 0, but increases toward 1.0 as y goes up to +1 or down to -1. You could make such a function by taking a sin or cos function and scaling/translating it appropriately. Actually, just a quadratic function like (y^2 + 1) / 2 would do as well.
{ "pile_set_name": "StackExchange" }
Q: XMPPFramework - "" when logging into Openfire server I installed Openfire server in my mac and did all the configuration. When i trying to connect it thro XMPP Protocol in the sense am getting bellow error log. RECV: <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure> and also i note that in login response am getting username as null check bellow log decoded response: username="(null)",realm="172.16.0.162",nonce="EFYJmP/oVfVKnhvuenmxVEBwH7VzYMET5j1cUqJ/",cnonce="DE5E4A14-3B6E-4239-B6AB-0B8BC1D75539",nc=00000001,qop=auth,digest-uri="xmpp/nivas",response=a64dcc45fef55811788d8784546baf29,charset=utf-8 Can any one tell me am i doing anything wrong here and any suggestion.?? Thanks A: For users using iOS's XMPPFramework, and receiving this message: <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure> Append your server domain name to the back of each user IDs, like so: keithoys@openfire
{ "pile_set_name": "StackExchange" }
Q: How to determine whether a timer id is exists? I could create a new timer with SetTimer(hwnd, id, elpase, proc), but i cannot assure that the timer for the id does not exist. Is there a way to know whether a timer for the id exist? A: I presume you mean SetTimer (Win32 doesn't have a CreateTimer). http://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx From the published Win32 API there is no way to find out if a timer for a particular window already exists. Bear in mind that each Window (hwnd) can have an independent timer with the same id. I presume you are not in control of the window and therefore don't know which (if any) other timer ids are in use? If you are really concerned about overwriting someone else's timer, why not just create a child window within the parent hwnd and create a timer in there?
{ "pile_set_name": "StackExchange" }
Q: How can I count occurrences of elements that are bigger than a given number in an list? Let's say I have this list: a = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1] I want to know how many elements are there bigger than 7. The result should be 3. Is there an elegant way to do this in Python? I tried with count but it won't work. A: >>> a = [1.1 , 2 , 3.1 , 4 , 5 , 6 , 7.2 , 8.5 , 9.1] >>> sum(x > 7 for x in a) 3 This uses the fact that bools are ints too. (If you oppose this because you think it isn't clear or pythonic then read this link)
{ "pile_set_name": "StackExchange" }
Q: replacing/overwriting standard-output in lisp i'm writing a chronometer in common lisp, output is being displayed in standard-output. what i'm trying to do is replace the output without printing a newline and without printing side-by-side but by overwriting the previous output so there is an illusion of continuity. is there anyway to do this in common lisp? A: OK, after reading the comments, I understand your intentions much better. From you original question, I assumed you wanted to replace/augment the output of some other code. But now I understand, what you actually want is to update the screen. This cannot be done with stream-based IO alone, you need some other kind of IO library like ncurses. A Common Lisp binding for ncurses is the system cl-charms (available in QuickLisp). There is no cl-charms specific documentation, but the documentation for using ncurses in C can be applied almost unchanged. Here is a simple implementation for the task you're describing, ie. it displays (for 10 seconds) a clock in the left upper corner of the screen: (defun clock () (charms:initscr) (charms:clear) (charms:curs-set 0) (loop with start = (get-universal-time) do (multiple-value-bind (s m h) (get-decoded-time) (charms:mvaddstr 0 0 (format nil "~2,'0d:~2,'0d:~2,'0d" h m s))) (charms:refresh) until (>= (- (get-universal-time) start) 10)) (charms:endwin)) Two problems I've experienced with this: This worked only in a terminal, not in the Emacs slime-repl buffer. cl-charms couldn't find my installation of the curses library by itself. It was looking for a library named "libcurses.so" or "libncurses.so", but on my system, the library was only present with versioned names. So I had to use the USE-VALUE restart during loading the library and provide the alternative value ("libncurses.so.5") for the list of library names. For using the library often, you should probably want to change the library source code and maybe suggest a patch to the developers. The cl-charms homepage linked from CLiki is not available, but the repository at http://gitorious.org/cl-charms is. Here's a short explanation of the ncurses/cl-charms functions I used in the example: initscr initializes ncurses. clear clears the screen. curs-set sets cursor visibility, 0 means invisible. mvaddstr moves the cursor to the coordinates y, x and writes a string there, replacing what was there on the screen previously. refresh makes the changes to the screen actually visible. endwin is the clean-up function to call when you're finished with ncurses. If I understand correctly what you're trying to do, the best approach seems to be to create a new output stream class (i.e. a subclass of fundamental-character-output-stream, assuming your implementation supports Gray Streams). You should probably provide methods specialised for your class at least for stream-write-charand stream-write-string. Then you could wrap code with a redefinition of *standard-output* to an instance of your class, somewhat like this: (let ((*standard-output* (make-instance 'your-stream-class :target *standard-output*))) (function-to-be-called-with-wrapped-standard-output))
{ "pile_set_name": "StackExchange" }
Q: Sitecore 7 Custom Experience Buttons Missing Not sure why but I am not seeing the 'Applications' folder under 'Content'. All the tutorials out there mention editing the (/sitecore/content/Applications/WebEdit/Custom Experience Button) items to accomplish what I need. My guess is I don't have view access to the core database in order to see these items or folders? If this isn't the case, how would I go about finding these buttons? Any help appreciated and I apologize if I didn't provide enough info but my goal is to add features to the page editor component toolbars. A: To make this a formal answer... First, login to desktop mode (on login screen, select "Desktop" from "Options" expander below form). Next, change database to core at bottom right: Finally, re-open your content manager and you should see the /sitecore/content/Applications node.
{ "pile_set_name": "StackExchange" }
Q: Building Python from source as a framework on Mac OS X Mountain Lion: error in headers I was building Python (3.4 dev version) from source as a framework on OS X 10.8. I'm a relative newbie to Mac OS X internals and couldn't figure out why the OS X framework headers caused these errors. Can someone please give me some pointers? I use the latest version of GNU gcc on my mac instead of the Apple supplied LLVM compiler. Perhaps, that's causing a compatibility problem. gcc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -o FileSettings.o -c ./FileSettings.m In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:123:0, from ./FileSettings.h:9, from ./FileSettings.m:9: /System/Library/Frameworks/Foundation.framework/Headers/NSTask.h:69:24: error: expected identifier or ‘(’ before ‘^’ token @property (copy) void (^terminationHandler)(NSTask *) NS_AVAILABLE(10_7, NA); ^ /System/Library/Frameworks/Foundation.framework/Headers/NSTask.h:72:1: error: expected identifier before ‘end’ @end ^ In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:159:0, from ./FileSettings.h:9, from ./FileSettings.m:9: /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:36:15: error: expected identifier or ‘(’ before ‘^’ token typedef void (^NSUserScriptTaskCompletionHandler)(NSError *error); ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:37:1: error: unknown type name ‘NSUserScriptTaskCompletionHandler’ - (void)executeWithCompletionHandler:(NSUserScriptTaskCompletionHandler)handler; ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:53:15: error: expected identifier or ‘(’ before ‘^’ token typedef void (^NSUserUnixTaskCompletionHandler)(NSError *error); ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:54:1: error: unknown type name ‘NSUserUnixTaskCompletionHandler’ - (void)executeWithArguments:(NSArray *)arguments completionHandler:(NSUserUnixTaskCompletionHandler)handler; ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:68:15: error: expected identifier or ‘(’ before ‘^’ token typedef void (^NSUserAppleScriptTaskCompletionHandler)(NSAppleEventDescriptor *result, NSError *error); ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:69:1: error: unknown type name ‘NSUserAppleScriptTaskCompletionHandler’ - (void)executeWithAppleEvent:(NSAppleEventDescriptor *)event completionHandler:(NSUserAppleScriptTaskCompletionHandler)handler; ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:86:15: error: expected identifier or ‘(’ before ‘^’ token typedef void (^NSUserAutomatorTaskCompletionHandler)(id result, NSError *error); ^ /System/Library/Frameworks/Foundation.framework/Headers/NSUserScriptTask.h:87:1: error: unknown type name ‘NSUserAutomatorTaskCompletionHandler’ - (void)executeWithInput:(id <NSSecureCoding>)input completionHandler:(NSUserAutomatorTaskCompletionHandler)handler; ^ In file included from /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:160:0, from ./FileSettings.h:9, from ./FileSettings.m:9: /System/Library/Frameworks/Foundation.framework/Headers/NSXPCConnection.h:46:11: error: expected identifier or ‘(’ before ‘^’ token void (^_interruptionHandler)(); ^ make[2]: *** [FileSettings.o] Error 1 make[1]: *** [install_PythonLauncher] Error 2 make: *** [frameworkinstallapps] Error 2 A: The errors correspond precisely to the 'block' extension Apple developed for C, C++ and Objective-C languages. GCC (the GNU version) doesn't recognize the block occurences and complains.
{ "pile_set_name": "StackExchange" }
Q: Branch not taken on Linux The below code works as expected on Windows but when built with Clang 6.0 and running on an Ubuntu server it does not work. The CurAnimIndex is an int32 and has the value 2147483647 (max int). I would expect it to enter the branch since the value of CurAnimIndex after the increment should be a negative number, however it does not. CurAnimIndex++; if (CurAnimIndex >= AnimSelectorDatas.Num() || CurAnimIndex < 0) { CurAnimIndex = 0; } 0x000000000411a12f mov 0x0(%r13),%eax 0x000000000411a133 lea 0x1(%rax),%ecx 0x000000000411a136 movslq 0x10(%r13),%r15 0x000000000411a13a xor %ebp,%ebp 0x000000000411a13c cmp %r15d,%ecx 0x000000000411a13f cmovge %ebp,%ecx 0x000000000411a142 cmp $0xffffffff,%eax 0x000000000411a145 cmovl %ebp,%ecx 0x000000000411a148 mov %ecx,0x0(%r13) 0x000000000411a14c mov 0x8(%r13),%r12 enter code here A: CurAnimIndex++ The CurAnimIndex is an int32 and has the value 2147483647 (max int). I would expect it to enter the branch since the value of CurAnimIndex after the increment should be a negative number 2147483647 is a positive number. Why would you expect that incrementing a positive number would yield a negative one? That doesn't happen in normal arithmetic. The compiler knows this and optimises according to that knowledge. If the initial value of CurAnimIndex has been proven to be at least -1, then the check CurAnimIndex < 0 is known always to be false and can be optimised away. Maybe your expectation is related to the fact that the operation overflows the maximum representable value. That expectation is misplaced because signed overflow isn't guaranteed to have such behaviour. In fact, signed overflow isn't guaranteed to have any particular behaviour. The behaviour of the program is undefined. A correct way to do this is to first check whether the number is equal to maximum representable value and only increment if it isn't.
{ "pile_set_name": "StackExchange" }
Q: How do you get the IP address of a Loki Service Node on the network? Is there a way to see the IP address of a Loki service node that is on the network? A: On any loki node regardless if its a service node or not, you can run the following command: curl -sX POST http://localhost:22023/json_rpc -d '{"jsonrpc":"2.0","id":"0","method":"get_service_nodes"}' -H 'Content-Type: application/json' | grep -B 4 SERVICE_NODE_ID_HERE Change localhost if your connecting to a remote loki node and change SERVICE NODE ID to the id you are looking for.
{ "pile_set_name": "StackExchange" }
Q: Left-clicking a text input in IE8 and Firefox This seems like a silly question since it doesn't have anything to do with programming, so I expect a few silly answers. But this is making me crazy. I develop in FF but I'm forced to test in IE8 since that's the only officially-supported browser here (way better than when I had to support IE6!!!). In testing, I have to fill out the same forms over and over. In FF this is much faster since I just left-click in a text input box and get a list of old values. In IE8, it always seems like I have to start from scratch. The only input that seems to keep old values is a username. Is there some feature in IE8 that I don't have turned on? I'd like to use it before carpal-tunnel sets in! A: Nope, there isn't. That's why newer browsers are better. Why not pre-populate your forms for testing purposes.
{ "pile_set_name": "StackExchange" }
Q: Accumulate values into an array with Postgres Currently I have this query: select sum(case when my_table.property_type = 'FLAT' then my_table.price else 0 end) as Flat_Current_Asking_Price, sum(case when my_table.property_type_mapped = 'SEMIDETACHED' then my_table.price else 0 end) as Semidetached_Current_Asking_Price from my_table; So if my_table has the values: property_type | price --------------+------- FLAT | 5000 SEMIDETACHED | 9000 FLAT | 6000 the query will return: Flat_Current_Asking_Price | Semidetached_Current_Asking_Price --------------------------+----------------------------------- 11000 | 9000 How can I replace the sum to accumulate the values into arrays to get? Flat_Current_Asking_Price | Semidetached_Current_Asking_Price --------------------------+----------------------------------- {5000, 6000} | {9000} A: If your PostggreSQL version is 9.4 or later use FILTER clause: select array_agg(my_table.price) filter(where my_table.property_type = 'FLAT' ) as Flat_Current_Asking_Price, array_agg(my_table.price) filter(where my_table.property_type = 'SEMIDETACHED') as Semidetached_Current_Asking_Price from my_table;
{ "pile_set_name": "StackExchange" }
Q: Query data for the last day of previous month into SSRS Report Cell I'm in the process of building a report and I'm stuck with one requirement. two of the columns in the output of my stored procedure are Accomplishments and UpdateDate. Now I have to write an expression for the accomplishment field such that it takes the Accomplishments values corresponding to the latest date in previous month in the UpdateDate column.. There are multiple Accomplishment values for every month and all of them are updated at different dates.. please help.. A: This is what I did: ' SELECT * FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY ProjectID ORDER BY UpdateDate DESC) AS RN, * FROM TableName WHERE UpdateDate BETWEEN DateAdd(mm, DateDiff(mm, 31, GetDate()), 0) AND DateAdd(mm, DateDiff(mm, 0, GetDate()), 0)' ) AS x WHERE RN = 1 Courtesy Naomi N from MSDN Forums..
{ "pile_set_name": "StackExchange" }
Q: sending sms in j2me i wrote a sending sms program through wireless messaging in j2me..but whenever i am sending message they are asking permission for sending mssg. A: You need to sign your midlet otherwise you will get these security prompts whenever you use an API such as network connection or SMS.
{ "pile_set_name": "StackExchange" }
Q: Diagnosing why WebResource.axd requests are empty I'm finding that for one particular web application requests to WebResource.axd are returning a completely empty page. (Copying and pasting the link into a new browser window results in a completley empty response document) IIS logs showing that the requests to WebResource.axd are successful (HTTP status code 200) The application itself is complex and so it seems likely that it is something that the application is doing which is causing this, however I don't know what. What additional debugging steps can I take to work out why these requests are failing, and where should I look for places where application specific behaviour might affect WebResource.axd in this way? Things I have tried so far: Creating a new virtual directory in IIS pointing towards the same directory gives the same results (empty WebResource.axd document) Creating a completely new indepdent blank page and placing it in this directory gives the same results. If I create a new virtual directory in IIS pointing towards a different folder then the blank page works as expected. Swapping the web.config files between the working / broken directories appears to have no impact. This is on a Windows XP machine running IIS 5.1 A: It turns out that the problem was a HttpResponse filter that I was applying in the Application_PreRequestHandlerExecute method in Global.asax. I was applying the filter generically to all requests - even though the filter left the content unchanged for WebResouce.axd, this still caused problems. The following links helped me out and describe this in more detail: HttpResponse filter returns nothing http://daniel-richardson.blogspot.com/2008/11/how-to-apply-filter-to-content-returned.html The solution was to skip applying the filter for WebResouce.axd.
{ "pile_set_name": "StackExchange" }
Q: Find the quotient using synthetic division with imaginary number $\frac{x+1}{x-i}$ I am to find the quotient using synthetic division: $\frac{x+1}{x-i}$ The solution is provided as $1+\frac{1+i}{x-i}$ I get $2+i$. My working: $$\begin{array} & i & | & 1 & 1 \end{array}$$ Pull down the 1 then multiply by i sum 1 and i $1+(1+i)$ = $2+i$ How can I arrive at $1+\frac{1+i}{x-i}$? A: Your work is already correct (except for the step where you did $1+(1+i)$). Remember that the $(1+i)$ at the end of the synthetic division is the remainder, so what you ended up with is indeed $1+\frac{1+i}{x-i}$. You should not have added $(1+i)$ and $1$ together.
{ "pile_set_name": "StackExchange" }
Q: Is it true that finishing the registration to the Android Market can take up to 4 days? I just registered my dev account in the Android Market and there is the message: Your Registration to the Android Market is still being processed . I googled and read around and I read that this phase can take up to 3-4 days! Is it true? How much time did it require for you? A: It took me a minute. But please, ask such questions on the Android stackexchange: https://android.stackexchange.com/
{ "pile_set_name": "StackExchange" }
Q: C Program crashes when adding an extra int I am new to C and using Eclipse IDE The following code works fine: #include <stdio.h> #include <stdlib.h> #include <String.h> int main() { char *lineName; int stationNo; int i; while (scanf("%s (%d)", lineName, &stationNo)!=EOF) { for (i=0; i<5 ; i++ ){ printf("%d %d",i); } } return 0; } Input: Green (21) Red (38) Output: Green (21) Red (38) 0123401234 However, when simply add a new int: #include <stdio.h> #include <stdlib.h> #include <String.h> int main() { char *lineName; int stationNo; int i,b=0; while (scanf("%s (%d)", lineName, &stationNo)!=EOF) { printf("%d",b); for (i=0; i<5 ; i++ ){ printf("%d",i); } } return 0; } The program will crash with the same input. Can anybody tell me why? A: You said your first program "works", but it works only by accident. It's like a car zooming down the road with no lugnuts holding on the front wheels, only by some miracle they haven't fallen off -- yet. You said char *lineName; This gives you a pointer variable that can point to some characters, but it doesn't point anywhere yet. The value of this pointer is undefined. It's sort of like saying "int i" and asking what the value of i is. Next you said scanf("%s (%d)", lineName, &stationNo) You're asking scanf to read a line name and store the string in the memory pointed to by lineName. But where is that memory? We have no idea whatsoever! The situation with uninitialized pointers is a little trickier to think about because, as always, with pointers we have to distinguish between the value of the pointer as opposed to the data at the memory which the pointer points to. Earlier I mentioned saying int i and asking what the value of i is. Now, there's going to be some bit pattern in i -- it might be 0, or 1, or -23, or 8675309. Similarly, there's going to be some bit pattern in lineName -- it might "point at" memory location 0x00000000, or 0xffe01234, or 0xdeadbeef. But then the questions are: is there actually any memory at that location, and do we have permission to write to it, and is it being used for anything else? If there is memory and we do have permission and it's not being used for anything else, the program might seem to work -- for now. But those are three pretty big ifs! If the memory doesn't exist, or if we don't have permission to write to it, the program is probably going to crash when it tries. And if the memory is being used for something else, something's going to go wrong when we ask scanf to write a string there. And, really, if what we care about is writing programs that work (and that work for the right reasons), we don't have to ask any of these questions. We don't have to ask where lineName points when we don't initialize it, or whether there's any memory there, or if we have permission to write to it, or if it's being used for something else. Instead, we should simply initialize lineName! We should explicitly make it point to memory that we do own and that we are allowed to write to and that isn't being used for anything else! There are several ways to do this. The easiest is to use an array for lineName, not a pointer: char lineName[20]; Or, if we have our hearts set on using a pointer, we can call malloc: char *lineName = malloc(20); However, if we do that, we have to check to make sure malloc succeeded: if(lineName == NULL) { fprintf(stderr, "out of memory!\n"); exit(1); } If you make either of those changes, your program will work. ...Well, actually, we're still in a situation where your program will seem to work, even though it still has another, pretty serious, lurking problem. We've allocated 20 characters for lineName, which gives us 19 actual characters, plus the trailing '\0'. But we don't know what the user is going to type. What if the user types 20 or more characters? That will cause scanf to write 20 or more characters to lineName, off past the end of what lineName's memory is allowed to hold, and we're back in the situation of writing to memory that we don't own and that might be in use for something else. One solution is to make lineName bigger -- declare it as char lineName[100], or call malloc(100). But that just moves the problem around -- now we have to worry about the (perhaps smaller) chance that the user will type 100 or more characters. So the next thing to do is to tell scanf not to write more to lineName than we've arranged for it to hold. This is actually pretty simple: if lineName is still set up to hold 20 characters, just call scanf("%19s (%d)", lineName, &stationNo) That format specifier %19s tells scanf that it's only allowed to read and store a string of up to 19 characters long. Now, I've said a lot here, but I realize I haven't actually gotten around to answering the question of why your program went from working to crashing when you made that seemingly trivial, seemingly unrelated change. This ends up being a hard question to answer satisfactorily. Going back to the analogy I started with, it's like asking why you were able to drive the car with no lugnuts to the store with no problem, but when you tried to drive to grandma's house, the wheels fell off and you crashed into a ditch. There are a million possible factors that might have come into play, but none of them change the underlying fact that driving a car with the wheels not fastened on is a crazy idea, that's not guaranteed to work at all. In your case, the variables you're talking about -- lineName, stationNo, i, and then b -- are all local variables, typically allocated on the stack. Now, one of the characteristics of the stack is that it gets used for all sorts of stuff, and it never gets cleared between uses. So if you have an uninitialized local variable, the particular random bits that it ends up containing depend on whatever was using that piece of the stack last time. If you change your program slightly so that different functions get called, those different functions may leave different random values lying around on the stack. Or if you change your function to allocate different local variables, the compiler may place them in different spots on the stack, meaning that they'll end up picking up different random values from whatever was there last time. Anyway, somehow, with the first version of your program, lineName ended up containing a random value that corresponded to a pointer that pointed to actual memory which you could get away with writing to. But when you added that fourth variable b, things moved around just enough that lineName ended up being a pointer to memory that didn't exist or that you didn't have permission to write to, and your program crashed. Make sense? And now, one more thing, if you're still with me. If you stop and think, this whole thing might be kind of unsettling. You had a program (your first program) that seemed to work just fine, but actually had a decently horrible bug. It wrote to random, unallocated memory. But when you compiled it you got no fatal error messages, and when you ran it there was no indication that anything was amiss. What's up with that? The answer, as a couple of the comments alluded to, involves what we call undefined behavior. It turns out that there are three kinds of C programs, which we might call the good, the bad, and the ugly. Good programs work for the right reasons. They don't break any rules, they don't do anything illegal. They don't get any warnings or error messages when you compile them, and when you run them, they just work. Bad programs break some rule, and the compiler catches this, and issues a fatal error message, and declines to produce a broken program for you to try to run. But then there are the ugly programs, that engage in undefined behavior. These are the ones that break a different set of rules, the ones that, for various reasons, the compiler is not obliged to complain about. (Indeed the compiler may or may not even be able to detect them). And programs that engage in undefined behavior can do anything. Let's think about those last two points a little more. The compiler is not obligated to generate error messages when you write a program that uses undefined behavior, so you might not realize you've done it. And the program is allowed to do anything, including work as you expect. But then, since it's allowed to do anything, it might stop working tomorrow, seemingly for no reason at all, either because you made some seemingly innocuous change to it, or merely because you're not around to defend it, as it quietly runs amok and deletes all your customer's data. So what are you supposed to do about this? One thing is to use a modern compiler if you can, and turn on its warnings, and pay attention to them. (Good compilers even have an option called "treat warnings as errors", and programmers who care about correct programs usually turn this option on.) Even though, as I said, they're not required to, compilers are getting better and better at detecting undefined behavior and warning you about it, if you ask them to. And then the other thing, if you're going to be doing a lot of C programming, is to take care to learn the language, what you're allowed to do, what you're not supposed to do. Make a point of writing programs that work for the right reasons. Don't settle for a program that merely seems to work. And if someone points out that you're depending on undefined behavior, don't say, "But my program works -- why should I care?" (You didn't say this, but some people do.)
{ "pile_set_name": "StackExchange" }
Q: Delete confirmation for html form I would like to add a delete confirmation to my form button Possible javascript to use?? <script type="text/javascript"> function confirmDelete() { return confirm("Are you sure you want to delete?"); } </script> This is currently working inside my form. <input type="button" onclick="parent.location='<?php echo "delete.php?id=" . $people['id'] ?>'" value='Delete'> How can I integrate the javascript into the onclick event? Either using the above javascript or any other way that may be better A: It's possible :) On the tag, use the attribute onsubmit like this : <form onsubmit="return confirm('Are you sure?');"> or using a method <form onsubmit="return myMethod"> The same for a button on onclick event. If it return false, it will be not clicked. Remember, if the method return false, the form will not be submited A: Bind your event handler in javascript. <input type="button" id="delete" value='Delete' /> document.getElementById('delete').onclick = function () { if (confirm('Are you sure?')) { parent.location='<?php echo "delete.php?id=" . $people['id'] ?>'; } };
{ "pile_set_name": "StackExchange" }
Q: Is there a difference in memory allocation when declaring a new array in a class? Is there a difference in memory usage / allocation for the class myObjectA and myObjectB? For example if I don't want to add a velocity to every object of that class will is use more memory having new float[2] in the class? Also whats the memory usage of "itemA" if I create a new "myObjectA" object but I don't add a new ItemA aka its at null, does it still use memory? and how much memory would it use if I create an new "ItemA" (myItem) and then create a new "myObjectA" (myObject), myObject.item = myItem;I assume it' a pointer pointing at (myItem)as reference but how much memory would that pointer use? and is there a difference between leaving it at null? Example C# public class itemA { Color color = Color.FromArgb(255,0,0); //3byte } itemA myItem = new itemA(); public class myObjectA { float[] pos; // ?byte float[] velocity; // ?byte itemA item; // ?byte } myObjectA myObject0 = new myObjectA(); public class myObjectB { float[] pos = new float[2]; // 8byte float[] velocity = new float[2];// 8byte itemA item; //?byte } myObjectB myObject1 = new myObjectB(); A: There is a difference in memory usage between the two classes at the time creation. As you point out, myObjectA will have unassigned variables, while myObjectB will assign arrays to these variables. As soon as you assign objects to the variables in myObjectA, the pointers will be set to those objects, and the memory use will be determined by how large these arrays are. Assuming that you intend to create them exactly as in myObjectB - as float[2], then myObjectA and myObjectB will use the same amount of memory. As for the size of an unassigned variable, while the pointer will not point to an object in memory, the pointer itself will still exist, and will have the default pointer size for your OS. See How big is an object reference in .NET? for pointer sizes. For the final question, it depends. What are you trying to accomplish by making this class generic? I would suggest asking a separate question for this.
{ "pile_set_name": "StackExchange" }
Q: Eliminate duplicate rows from query output I have a large SELECT query with multiple JOINS and WHERE clauses. Despite specifying DISTINCT (also have tried GROUP BY) - there are duplicate rows returned. I am assuming this is because the query selects several IDs from several tables. At any rate, I would like to know if there is a way to remove duplicate rows from a result set, based on a condition. I am looking to remove duplicates from results if x.ID appears more than once. The duplicate rows all appear grouped together with the same IDs. Query: SELECT e.Employee_ID, ce.CC_ID as CCID, e.Manager_ID, e.First_Name, e.Last_Name,,e.Last_Login, e.Date_Created AS Date_Created, e.Employee_Password AS Password,e.EmpLogin ISNULL((SELECT TOP 1 1 FROM Gift g JOIN Type t ON g.TypeID = t.TypeID AND t.Code = 'Reb' WHERE g.Manager_ID = e.Manager_ID),0) RebGift, i.DateCreated as ImportDate FROM @EmployeeTemp ct JOIN dbo.Employee c ON ct.Employee_ID = e.Employee_ID INNER JOIN dbo.Manager p ON e.Manager_ID = m.Manager_ID LEFT JOIN EmployeeImp i ON e.Employee_ID = i.Employee_ID AND i.Active = 1 INNER JOIN CreditCard_Updates cc ON m.Manager_ID = ce.Manager_ID LEFT JOIN Manager m2 ON m2.Manager_ID = ce.Modified_By WHERE ce.CCType ='R' AND m.isT4L = 1 AND CHARINDEX(e.first_name, Selected_Emp) > 0 AND ce.Processed_Flag = @isProcessed A: I don't have enough reputation to add a comment, so I'll just try to help you in an answer proper (even though this is more of a comment). It seems like what you want to do is select distinctly on just one column. Here are some answers which look like that: SELECT DISTINCT on one column How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
{ "pile_set_name": "StackExchange" }
Q: How to avoid/prevent infinite recursive call in Node.js? I have a javascript function in my Node.js application which calls itself to find its level in parent-child hierarchy in MongoDB. A document will try to find its parent and if found will increase the level and goes on till there is no parent found. It looks like the following, function findLevel(doc, level, callback){ if(!doc) return callback(null, level); var query = { id: doc.parentID }; model.findOne(query, function(err, parentDoc){ if(err){ return callback(err, level) }; return findLevel(parentDoc, level+1, callback); }) } This has high chance of producing infinite recursive calls. One of the scenario is parentID is same as the current doc's id. That can be avoided by including another condition in find query, but still I am worried about I may miss something and it can cause the entire application to crash/kill. Is there a recommended way to avoid/prevent this kind of situation in Node.js? Or can we restrict the level of recursive calls and stop it gracefully like saying the recursive call should go only till this n level? A: You could implement cycle detection by making note of all the IDs you encounter during recursion and stopping as soon as an ID has been handled before. function findLevel(doc, callback) { var level = 0, seen = {}; (function getParent(doc) { // proper termination if(!doc || !doc.parentID) return callback(null, level); // cycle detection if (seen.hasOwnProperty(doc.parentID)) return callback(new Error("cycle detected")); seen[doc.parentID] = true; // recursion model.findOne({id: doc.parentID}, function (err, parentDoc) { if (err) return callback(err); level++; getParent(parentDoc); }); })(doc); }
{ "pile_set_name": "StackExchange" }
Q: Good Reference for Spanier-Whitehead duality? Does anyone know of a good book that explains Spanier-Whitehead duality (other than Adams)? Thanks Jon A: Well, one classic source is some exercises in Spanier's book on algebraic topology (alas, I don't have my copy at hand so I can't give a more precise reference, but it is towards the end). There is also a chapter on it in MR0273608 (42 #8486) Cohen, Joel M. Stable homotopy. Lecture Notes in Mathematics, Vol. 165 Springer-Verlag, Berlin-New York 1970 v+194 pp. However, I have to admit that I find Adams's book very clear and beautiful. Is there a reason you don't like it? A: You might find the following interesting: http://www.math.purdue.edu/~gottlieb/Bibliography/53.pdf even though it is not quite what you asked for.
{ "pile_set_name": "StackExchange" }
Q: How to get children type in react I'm trying to make my own Tabs component, so that I can use tabs in my app. However I seem to be having issues trying to extract the child components I need by type. import React from 'react' export class Tabs extends React.Component { render() { let children = this.props.children let tablinks = React.Children.map(children, x => { console.log(x.type.displayName) // Always undefined if (x.type.displayName == 'Tab Link') { return x } }) return ( <div className="tabs"></div> ) } } export class TabLink extends React.Component { constructor(props) { super(props) this.displayName = 'Tab Link' } render() { return ( <div className="tab-link"></div> ) } } <Tabs> <TabLink path="tab1">Test</TabLink> <TabLink path="tab2">Test2</TabLink> </Tabs> My console.log never returns "Tab Link", it always returns undefined, why? A: As an alternative you could use console.log(x.type.name) // this would be 'TabLink' You don't need to explicitly define displayName in this case. https://jsfiddle.net/lustoykov/u1twznw7/1/ A: It's undefined because displayName should be a static property. class TabLink extends React.Component { constructor(props) { super(props) } render() { return ( <div className="tab-link"></div> ) } } TabLink.displayName = 'Tab Link' jsfiddle (check the console)
{ "pile_set_name": "StackExchange" }
Q: Asynchronous Client/Server pattern in Python ZeroMQ I have 3 programs written in Python, which need to be connected. 2 programs X and Y gather some information, which are sent by them to program Z. Program Z analyzes the data and send to program X and Y some decisions. Number of programs similar to X and Y will be expanded in the future. Initially I used named pipe to allow communication from X, Y to Z. But as you can see, I need bidirectional relation. My boss told me to use ZeroMQ. I have just found pattern for my use case, which is called Asynchronous Client/Server. Please see code from ZMQ book (http://zguide.zeromq.org/py:all) below. The problem is my boss does not want to use any threads, forks etc. I moved client and server tasks to separate programs, but I am not sure what to do with ServerWorker class. Can this be somehow used without threads? Also, I am wondering, how to establish optimal workers amount. import zmq import sys import threading import time from random import randint, random __author__ = "Felipe Cruz <[email protected]>" __license__ = "MIT/X11" def tprint(msg): """like print, but won't get newlines confused with multiple threads""" sys.stdout.write(msg + '\n') sys.stdout.flush() class ClientTask(threading.Thread): """ClientTask""" def __init__(self, id): self.id = id threading.Thread.__init__ (self) def run(self): context = zmq.Context() socket = context.socket(zmq.DEALER) identity = u'worker-%d' % self.id socket.identity = identity.encode('ascii') socket.connect('tcp://localhost:5570') print('Client %s started' % (identity)) poll = zmq.Poller() poll.register(socket, zmq.POLLIN) reqs = 0 while True: reqs = reqs + 1 print('Req #%d sent..' % (reqs)) socket.send_string(u'request #%d' % (reqs)) for i in range(5): sockets = dict(poll.poll(1000)) if socket in sockets: msg = socket.recv() tprint('Client %s received: %s' % (identity, msg)) socket.close() context.term() class ServerTask(threading.Thread): """ServerTask""" def __init__(self): threading.Thread.__init__ (self) def run(self): context = zmq.Context() frontend = context.socket(zmq.ROUTER) frontend.bind('tcp://*:5570') backend = context.socket(zmq.DEALER) backend.bind('inproc://backend') workers = [] for i in range(5): worker = ServerWorker(context) worker.start() workers.append(worker) poll = zmq.Poller() poll.register(frontend, zmq.POLLIN) poll.register(backend, zmq.POLLIN) while True: sockets = dict(poll.poll()) if frontend in sockets: ident, msg = frontend.recv_multipart() tprint('Server received %s id %s' % (msg, ident)) backend.send_multipart([ident, msg]) if backend in sockets: ident, msg = backend.recv_multipart() tprint('Sending to frontend %s id %s' % (msg, ident)) frontend.send_multipart([ident, msg]) frontend.close() backend.close() context.term() class ServerWorker(threading.Thread): """ServerWorker""" def __init__(self, context): threading.Thread.__init__ (self) self.context = context def run(self): worker = self.context.socket(zmq.DEALER) worker.connect('inproc://backend') tprint('Worker started') while True: ident, msg = worker.recv_multipart() tprint('Worker received %s from %s' % (msg, ident)) replies = randint(0,4) for i in range(replies): time.sleep(1. / (randint(1,10))) worker.send_multipart([ident, msg]) worker.close() def main(): """main function""" server = ServerTask() server.start() for i in range(3): client = ClientTask(i) client.start() server.join() if __name__ == "__main__": main() A: So, you grabbed the code from here: Asynchronous Client/Server Pattern Pay close attention to the images that show you the model this code is targeted to. In particular, look at "Figure 38 - Detail of Asynchronous Server". The ServerWorker class is spinning up 5 "Worker" nodes. In the code, those nodes are threads, but you could make them completely separate programs. In that case, your server program (probably) wouldn't be responsible for spinning them up, they'd spin up separately and just communicate to your server that they are ready to receive work. You'll see this often in ZMQ examples, a multi-node topology mimicked in threads in a single executable. It's just to make reading the whole thing easy, it's not always intended to be used that way. For your particular case, it could make sense to have the workers be threads or to break them out into separate programs... but if it's a business requirement from your boss, then just break them out into separate programs. Of course, to answer your second question, there's no way to know how many workers would be optimal without understanding the work load they'll be performing and how quickly they'll need to respond... your goal is to have the worker complete the work faster than new work is received. There's a fair chance, in many cases, that that can be accomplished with a single worker. If so, you can have your server itself be the worker, and just skip the entire "worker tier" of the architecture. You should start there, for the sake of simplicity, and just do some load testing to see if it will actually cope with your workload effectively. If not, get a sense of how long it takes to complete a task, and how quickly tasks are coming in. Let's say a worker can complete a task in 15 seconds. That's 4 tasks a minute. If tasks are coming in 5 tasks a minute, you need 2 workers, and you'll have a little headroom to grow. If things are wildly variable, then you'll have to make a decision about resources vs. reliability. Before you get too much farther down the trail, make sure you read Chapter 4, Reliable Request/Reply Patterns, it will provide some insight for handling exceptions, and might give you a better pattern to follow.
{ "pile_set_name": "StackExchange" }
Q: When parse xml via c# get "\ / " or so on I parse config file via Linq. File like this: <?xml version="1.0" encoding="utf-8" ?> <Path Name="Config file"> <PathToHelpTopic>"/Files/HelpTopics.xml"</PathToHelpTopic> <PathToFiles>"http://system-help"</PathToFiles> And try to parse: XDocument doc = XDocument.Load(helpTopicPath); var path = from item in doc.Descendants("PathToHelpTopic") select item.Value; foreach (var p in path) { Console.WriteLine(p); return p; } But p= "\"/Files/HelpTopics.xml\"" . How get result string like /Files/HelpTopics.xml ? Thank you! A: In fact, you want to trim off all the double quotes from the value: var path = from item in doc.Descendants("PathToHelpTopic") select item.Value.Trim('"');
{ "pile_set_name": "StackExchange" }
Q: How can I have a host and container read/write the same files with Docker? I would like to volume mount a directory from a Docker container to my work station, so when I edit the content in the volume mount from my work station it updated in the container as well. It would be very useful for testing and develop web applications in general. However I get a permission denied in the container, because the UID's in the container and host isn't the same. Isn't the original purpose of Docker that it should make development faster and easier? This answer works around the issue I am facing when volume mounting a Docker container to my work station. But by doing this, I make changes to the container that I won't want in production, and that defeats the purpose of using Docker during development. The container is Alpine Linux, work station Fedora 29, and editor Atom. Question Is there another way, so both my work station and container can read/write the same files? A: There are multiple ways to do this, but the central issue is that bind mounts do not include any UID mapping capability, the UID on the host is what appears inside the container and vice versa. If those two UID's do not match, you will read/write files with different UID's and likely experience permission issues. Option 1: get a Mac or deploy docker inside of VirtualBox. Both of these environments have a filesystem integration that dynamically updates the UID's. For Mac, that is implemented with OSXFS. Be aware that this convenience comes with a performance penalty. Option 2: Change your host. If the UID on the host matches the UID inside the container, you won't experience any issues. You'd just run a usermod on your user on the host to change your UID there, and things will happen to work, at least until you run a different image with a different UID inside the container. Option 3: Change your image. Some will modify the image to a static UID that matches their environment, often to match a UID in production. Others will pass a build arg with something like --build-arg UID=$(id -u) as part of the build command, and then the Dockerfile with something like: FROM alpine ARG UID=1000 RUN adduser -u ${UID} app The downside of this is each developer may need a different image, so they are either building locally on each workstation, or you centrally build multiple images, one for each UID that exists among your developers. Neither of these are ideal. Option 4: Change the container UID. This can be done in the compose file, or on a one off container with something like docker run -u $(id -u) your_image. The container will now be running with the new UID, and files in the volume will be accessible. However, the username inside the container will not necessarily map to your UID which may look strange to any commands you run inside the container. More importantly, any files own by the user inside the container that you have not hidden with your volume will have the original UID and may not be accessible. Option 5: Give up, run everything as root, or change permissions to 777 allowing everyone to access the directory with no restrictions. This won't map to how you should run things in production, and the container may still write new files with limited permissions making them inaccessible to you outside the container. This also creates security risks of running code as root or leaving filesystems open to both read and write from any user on the host. Option 6: Setup an entrypoint that dynamically updates your container. Despite not wanting to change your image, this is my preferred solution for completeness. Your container does need to start as root, but only in development, and the app will still be run as the user, matching the production environment. However, the first step of that entrypoint will be to change the user's UID/GID inside the container to match your volume's UID/GID. This is similar to option 4, but now files inside the image that were not replaced by the volume have the right UID's, and the user inside the container will now show with the changed UID so commands like ls show the username inside the container, not a UID to may map to another user or no one at all. While this is a change to your image, the code only runs in development, and only as a brief entrypoint to setup the container for that developer, after which the process inside the container will look identical to that in a production environment. To implement this I make the following changes. First the Dockerfile now includes a fix-perms script and gosu from a base image I've pushed to the hub (this is a Java example, but the changes are portable to other environments): FROM openjdk:jdk as build # add this copy to include fix-perms and gosu or install them directly COPY --from=sudobmitch/base:scratch / / RUN apt-get update \ && apt-get install -y maven \ && useradd -m app COPY code /code RUN mvn build # add an entrypoint to call fix-perms COPY entrypoint.sh /usr/bin/ ENTRYPOINT ["/usr/bin/entrypoint.sh"] CMD ["java", "-jar", "/code/app.jar"] USER app The entrypoint.sh script calls fix-perms and then exec and gosu to drop from root to the app user: #!/bin/sh if [ "$(id -u)" = "0" ]; then # running on a developer laptop as root fix-perms -r -u app -g app /code exec gosu app "$@" else # running in production as a user exec "$@" fi The developer compose file mounts the volume and starts as root: version: '3.7' volumes: m2: services: app: build: context: . target: build image: registry:5000/app/app:dev command: "/bin/sh -c 'mvn build && java -jar /code/app.jar'" user: "0:0" volumes: - m2:/home/app/.m2 - ./code:/code This example is taken from my presentation available here: https://sudo-bmitch.github.io/presentations/dc2019/tips-and-tricks-of-the-captains.html#fix-perms Code for fix-perms and other examples are available in my base image repo: https://github.com/sudo-bmitch/docker-base
{ "pile_set_name": "StackExchange" }
Q: Can't debug Excel 2003 Addin (XLL) My problem: I'm currently working on both an XLL (written in C++) and VSTO development. I'm using Visual Studio 2008 and Excel 2003. My VSTO addin doesn't do anything exciting. My XLL provides UDFs to the end-user (mostly calculations) I've only recently started on the VSTO addin, and noticed that now when I attempt to debug my XLL I can't attach to an existing Excel process. If I disable the VSTO addin then this problem goes away and I can debug the XLL by attaching to the process. When I launch "debug" from my XLL project and have VS launch Excel and it loads both my XLL and VSTO I can debug the XLL. This isn't exactly ideal as it would be nice to be able to attach to an existing session. This problem appears to be envirnomental, does anyone know why this is happening? A: When you attach, there's an option in the dialog that lets you choose the kind of debugger you want. Click the Select button, ensure you have "Native" ticked.
{ "pile_set_name": "StackExchange" }
Q: Ionic 2 - Adding a background image to a page I have just installed a new Ionic project - Ionic v2.0.0-beta.32 Im looking to add a background image to the home page of the fresh install, is there anyone that could show me how i go about this? All i can find is information for Ionic 1 and things seems quite different. From what ive found, the image needs to be the following dimensions 2800px x 2800px But apart from that i cant find any other tutorials. This is my first Ionic project so be gentle Thanks you guys A: The image can be any size. go to app/theme/app.core.scss and add the following code ion-content{ background-image: url('img/background.jpg'); } This is assuming that the name of your image file is background.jpg and is stored in www/img/ folder. Hope this helps UPDATE Ionic 3.x Go to app/app.scss and add the following code ion-content { background-image: url('assets/img/background.jpg'); } This is assuming that the name of your image file is background.jpg and is stored in assets/img folder. A: For Ionic V4 they use some new switch in the scss file. This worked for me: ion-content { --background: url('../../assets/Welcome-screen.png') no-repeat 50% 10%; }
{ "pile_set_name": "StackExchange" }
Q: Lithium Li3 "Inner Join" I need to do a "Inner Join" between two MySQL Tabels via the Li3 Lithium3 framework. My model relationships are ok for "Left Joins". But I don't know how to perform an inner join to do some more filtering via sql. Manually it works (with a custom finder): Posts::finder ('popular', function($self, $params, $chain) { $db = Connections::get ($self::meta ('connection')); $records = $db->read ( "SELECT * FROM `posts` p INNER JOIN `post_metas` pm ON (pm.`post_id` = p.`id` AND pm.`meta_key`='views') ORDER BY pm.`int_value` DESC", array('return' => 'object')); return $records; }); But this is not really dynamic. Does anyone know how to do this with lithium relationships? thx in advise. A: Just create a normal model relationship and 'mode' => 'INNER'.
{ "pile_set_name": "StackExchange" }
Q: Can't draw with glDrawTexfOES I can't draw a texture with glDrawTextOES in my Android app. I've tried the SpriteMethodTest code and I can't get it to work... However, here's the code: Code for cropping when loading texture: GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); int[] mCropWorkspace = new int[4]; mCropWorkspace[0] = 0; mCropWorkspace[1] = bitmap.getHeight(); mCropWorkspace[2] = bitmap.getWidth(); mCropWorkspace[3] = -bitmap.getHeight(); bitmap.recycle(); ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0); Code for drawing: gl.glBindTexture(GL10.GL_TEXTURE_2D, texture); ((GL11Ext) gl).glDrawTexfOES(x, y, 0.0f, width, height); Any ideas? I got it to work with Vertex Arrays and Vertex Buffer Objects, but not with this... Thanks in advance! A: You need to have properly height and width for your image, e.g: 512x512 or 512x1024 so it fills a quad/rectangle, specified by your GL_TEXTURE_CROP_RECT_OES.
{ "pile_set_name": "StackExchange" }
Q: Publicar App en Google Play Quisiera publicar una aplicación en Play store como empresa, pero a la hora de crear una cuenta se debe hacer como una cuenta personal ya que pide nombre, apellido, fecha de nacimiento, etc... Mi duda es si como empresa debería hacerlo de forma diferente o ¿cuál sería la recomendación? ¿Legalmente existe algún problema si creo una cuenta y en campos de nombre y apellido pongo el nombre de la empresa? No quisiera que saliera mi nombre sino el de la empresa a la hora que visitan una App nuestra. A: No quisiera que saliera mi nombre sino el de la empresa a la hora que visitan una App nuestra. Lo que saldrá en la PlayStore sería lo que configures como "Developer name": En cambio los datos que introduces al registrarte como desarrollador son principalmente para facturación.
{ "pile_set_name": "StackExchange" }
Q: Append to an environment variable without overwriting values from .env file Assuming the .env file is loaded before execution, how can you append to it without overriding it? DEBUG=True FOO=BAR PYTHONPATH="/Users/James/project/" The above file would (?) override it, and that would be bad. I could put it in .bash_profile or .profile, but that's not consistent with what I have now, and I only want to set it for the current virtualenv too. I don't think this makes any difference, but I'm using Mac OS X (the tutorial I was using was multi-platform) A: What you most likely want to do is export the variables you are interested in. The following will make the variable available to the current shell and any sub-processes it creates: export PYTHONPATH=$PYTHONPATH:/Users/James/project Here a process that uses PYTHONPATH will first search the existing path for its target and if not found, try the /Users/James/project. If you wanted to overide some existing path, you could add the new path first: export PYTHONPATH=/Users/James/project:$PYTHONPATH In either case, other shells will not see the variable (and obviously closing the shell will make the variable unaccessible).
{ "pile_set_name": "StackExchange" }
Q: Displaying Subnode content on parent node in Umbraco I've been having a lot of trouble figuring this out. What I want is a FAQ page that displays all the questions and answers on the same page. It gets the content from the questions and answers from subnode content. So for example my tree looks like this: FAQ Question1 Question2 Question3 I want the template on FAQList to list the question and answer data from Question1...2... and 3 on the same page. Every time I try to find examples of this being done I can only find examples that list the subpages as links. I don't want to link to the subpages. I want to actually print the content from them onto the parent page. Is that possible? This is my attempt at it: <xsl:for-each select="$currentPage/node"> Question: <xsl:value-of select="data [@alias = 'question']"/><br/> Answer: <xsl:value-of select="data [@alias = 'answer']"/><br/> </xsl:for-each> But I had no results. Help me out here. I'm banging my head on this. A: It all depends on the version of Umbraco you're running. There's a lot of documentation out there that refers to a much earlier version of Umbraco and simply won't work on more recent versions. Assuming the document type alias of your questions is called 'FaqItem' and assuming that this XSLT is run on the respective content node (i.e. $currentPage is your FAQ parent node), you can use the following: If you're using < Umbraco 4.5.1 <xsl:for-each select="$currentPage/child::node[@nodeTypeAlias='FaqItem']"> Question: <xsl:value-of select="./data[@alias='question']"/><br/> Answer: <xsl:value-of select="./data[@alias='answer']"/><br/> </xsl:for-each> If you're using >= Umbraco 4.5.1 <xsl:for-each select="$currentPage/FaqItem"> Question: <xsl:value-of select="./question"/><br/> Answer: <xsl:value-of select="./answer"/><br/> </xsl:for-each> For future reference If you're familiar with XPath and want to figure out how Umbraco has stored the data, or to help with debugging. Look for a file called Umbraco.config (typically found in ~/App_Data/). This is the cached XML that all XSLTs will read from. Posting the relevant snippet from this file into your [Stack Overflow] question will increase the speed and chances of getting a response, as XSLT contributors will be able to help and not just Umbraco contributors.
{ "pile_set_name": "StackExchange" }
Q: C# compiler: CS0121: The call is ambiguous between the following methods or properties This is the craziest what I've seen since a Fody plugin ruined my assembly by emitting invalid code and control flow varied random at runtime... No Fody this time. Facts: The whole story is within one project. The GetMessage extension method is there since weeks... The issue is started since 2 hours, and I can not figure out what it is. There is only one GetMessage extension method. The error message (see the pic) lists two identical method specification Error CS0121 The call is ambiguous between the following methods or properties: 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' and 'ComiCalc.Data.ExceptionExtensions.GetMessage2(System.Exception)' ComiCalc.Data D:\2014Develop\.vsonline\ComiCalc\src\ComiCalc.Data\Services\UserService.cs 61 If I change both the call, both the method definition (only 2 edits in 2 places) to GetMessage2, then I got exactly the same error message just referring to the GetMessage2. Using VS 2015 Any ideas? and here is the single one method: namespace ComiCalc.Data { using System; using System.Data.Entity.Validation; using PluralTouch.DataAccess; // TODO: Move to PluralTouch public static class ExceptionExtensions { public static string GetMessage2(this Exception exception) { var message = exception.Message; if (exception is DbEntityValidationException) { message = ((DbEntityValidationException) exception).DbEntityValidationResultToString(); } return message; } } } A: Make sure you don't reference the output binary in your project references (i.e., the project references itself). This has happened to me in the past with Resharper (the addition of the output binary to the project references), so the extension method is both in the source and in the binary reference. A: Delete bin folder > open project > build solution.
{ "pile_set_name": "StackExchange" }
Q: Make JsonServiceClient process requests with empty (not null) request objects How can I configure ServiceStack v3.x JsonServiceClient to serialize an empty request object and call the service? I want to get an exception, but instead the JsonServiceClient returns null. I put a breakpoint at the top of the service, and it's never hit. But when the name property is not blank, it gets hit. Result Message: Expected: <ServiceStack.ServiceClient.Web.WebServiceException> But was: null Here's the failing test, it doesn't raise any ex. [Test] public void TestPortfolioBlankNameE2E() { JsConfig.IncludeNullValues = true; var client = TestHelpers.ISWJsonServiceClient(); GetPortfolio request = "{\"name\":\"\"}".FromJson<GetPortfolio>(); WebServiceException ex = (WebServiceException)Assert.Throws(typeof(WebServiceException), delegate { client.Get(request); }); Assert.AreEqual(400, ex.StatusCode); Assert.AreEqual("Bad Request", ex.StatusDescription); StringAssert.Contains("Required parameter missing: name", ex.Message); } The equivalent test, calling the service directly, passes. [Test] public void TestPortfolioBlankName() { PortfolioService service = TestHelpers.MockServer<PortfolioService>(); GetPortfolio request = "{\"name\":\"\"}".FromJson<GetPortfolio>(); HttpError ex = (HttpError)Assert.Throws(typeof(HttpError), delegate { service.get(request); }); Assert.AreEqual(400, ex.Status); Assert.AreEqual(HttpStatusCode.BadRequest, ex.StatusCode); StringAssert.Contains("Required parameter missing: name", ex.Message); } The DTO: [Route("/portfolio/{name}", "GET")] public class GetPortfolio : IReturn<GetPortfolioResponse> { public String name { get; set; } } As Doug points out, that explains it. It fails to create a valid route without a value for name. Too bad it doesn't raise an exception when it can't create a valid route. Returning null doesn't suggest the source of the problem. A: I don't think your problem lies in serialization. Setting JsConfig.IncludeNullValues = true won't affect whether your request DTO transfers from client to server correctly. It affects the efficiency of the wire protocol. That configuration only affects the payload size of the serialized JSON. Rather than sending {"name":null} (13 UTF-8 bytes), serializing with JsConfig.IncludeNullValues = false will send {} (2 UTF-8 bytes). But the deserialized DTO received by the server will be identical to the DTO on the client in both cases. (Also, your example code is sending an empty string "" not null. So it will be completely unaffected by the JsConfig.IncludeNullValues setting.) I'm guessing your problem lies in the routing of your request DTO. There's probably something ambiguous about it (or it conflicts with other request DTOs) such that ServiceStack can't figure out how to route it to your PortfolioService class. Calling the service directly is bypassing all the ServiceStack routing logic. Can you include the source for your GetPortfolio request DTO class, so we can see if there is anything obviously wrong?
{ "pile_set_name": "StackExchange" }
Q: $("#id").click(function(){calculation()}); What is wrong with the line in the header? The below example is supposed to make a button which will increment a counter each time it is clicked. However, I enforce a delay of 2000 ms between button clicks. The version below works, however, if I use the commented out line instead of document.getElementById("rollButton").onclick=function(){calculation()}; (both in function afterWaiting()) I get various odd results, for instance that the counter starts incrementing by a lot more than 1, and the waiting time disappears? <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script> function afterWaiting() { $("#rollButton").css("color","black"); //$("#rollButton").click(function(){calculation()}); document.getElementById("rollButton").onclick=function(){calculation()}; } var counter=0; function calculation() { ////Enforcing wait: document.getElementById("rollButton").style.color="red"; document.getElementById("rollButton").onclick=""; window.setTimeout("afterWaiting()",2000); counter=counter+1; document.getElementById("test").innerHTML=counter; } </script> </head> <body> <button type="button" onclick="calculation()" id="rollButton"> Roll! </button> <p id="test"> </p> </body> </html> What have I misunderstood? thanks in advance :) JSFiddle: http://jsfiddle.net/Bwxb9/ A: The difference is that when you apply event handlers through onclick as you do in your original version, you can only bind one handler to the element. And using onclick="" kind of clears it. When using jQuery .click(handler) you bind a new handler each time you call it (and you can unbind it with unbind('click') (and not with onclick=""). So after a couple of calls to afterWaiting you have applied mulitple click handlers on your element, and on each click the calculation function runs multiple times.. So, one way to correct it is to replace document.getElementById("rollButton").onclick=""; with $('#rollButton').unbind('click'); A: The only code required is <button type="button" id="rollButton"> Roll! </button> <p id="test"> </p> var counter = 0; var $test = $('#test'); var $rollButton = $('#rollButton'); function increment(){ $test.html(counter++); $rollButton.off('click', increment); setTimeout(function(){ $rollButton.on('click', increment); }, 2000); } $rollButton.on('click', increment); Demo: Fiddle Updated: as suggested by Andy, but I would recommend Andy's answer as it involves no additional event manipulation var counter = 0; var $test = $('#test'); var $rollButton = $('#rollButton'); function increment(){ $test.html(counter++); setTimeout(function(){ $rollButton.one('click', increment); }, 2000); } $rollButton.one('click', increment); Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: Open Source Java PDF Viewers that can play embedded media I'm trying to find a open source pdf viewer that I can embed in a java swing application. The PDFs will have embedded media in them so I will need the viewer to be able to play the media. Does anyone know of any good pdf viewers? I've tried ICEpdf, JPedal and Pdf Renderer but playing the embedded media in all of them was unsuccessful. A: Have a look at this blog Open source Java projects: SwingLabs PDF Renderer
{ "pile_set_name": "StackExchange" }
Q: Is there any sample code to access the user's Facebook Profile details in iphone sdk? I want to access my own account user details in facebook like Messages,friend requests,Notifications,my profile pic and my profile details. Is there any sample code or any way to do so?? Anyone's help will be deeply appreciated. Thanks to all, Monish. A: Nice introduction to the Facebook SDK, including sample code for iOS: http://developers.facebook.com/docs/guides/mobile/
{ "pile_set_name": "StackExchange" }
Q: How do you implement UI for the non computer savvy? I have been support a web app that is used by a user base who's age range if from 40-65. The app is very good and has the latest ajaxy stuff etc. What we would now call very user friendly and responsive. I am amazed as to how this app is not so userfriendly for that user base. I was told that some autocomplete features make them disoriented!! Also, a lot of accidental clicks happen, they sometimes say "its not going thru!" then I realize that one of required check boxes were not clicked. I hope I made the scenario clear. Could someone provice me resources/tips for this? Is not so much as an accessibility issue. A: Don't make me think is like a bible, a must read lecture A: I had similar trouble with an application used by a workforce with a good proportion in their 50s. I learnt an amazing amount just by sitting with them while they used the application. If they tried to do something I thought was daft or missed something I thought was obvious, I'd ask them what they were trying to do, and what made them think that was the way to solve it. It's very true, lots of things more experienced users would think are benefits and useful features can just be distractions. Be sure to take the users feedback very seriously. If you have also got savvy users, they could have an advanced mode that turns on auto-complete etc. But don't ever try to think you know best because a certain way of working allows you to work more efficiently when you use the UI. Also. Remember to use big plain fonts, high contrast, and big buttons that are easy to hit with a mouse. I know you say you haven't got accessibility problems, but your users might appreciate these things and see it as an improvement to the UI. One issue I had was that the users didn't seem to understand the meanings of icons, text seemed to work better. Or if you've got space, include text next to existing icons. Be very careful when you come to add new features... these can confuse this type of user massively. It's taken them a long time to work out how to do something and now its changed! So ensure new features don't upset old ones too much or at all if possible. Another good thing to consider is the workflow. If you can organize screen elements so that users can work from top to bottom in a linear manner to achieve a task, this may improve the usability. A: If you want an awesome UI book, try The Design of Everyday Things by Donald Norman. It is not about computer interfaces, but is applicable to nearly all UI work. My two cents: Make the interface consistent with something that the age group is already familiar with (probably Microsoft Office).
{ "pile_set_name": "StackExchange" }
Q: SVG Polygon Shape with Image I am trying to make polygon shape for Mozilla with the help of clip path. but I am not able to make it, Below are my code for the circle shape how to change the circle into polygon. <style> img {clip-path: url(#clipping);} </style> <svg> <defs> <clipPath id="clipping"> <circle cx="284" cy="213" r="213" /> </clipPath> </defs> </svg> <img src="img/1.jpg" width="568"> {Updated my Question} Now I have created a polygon but Chrome is not supporting it... how to resolve that... below are my code for polygon it's working on Mozilla. <style> #img {clip-path: url(#clipping); -webkit-clip-path: url(#clipping); -webkit-shape-outside: url(#clipping); shape-outside: url(#clipping); } </style> <svg> <defs> <clipPath id="clipping"> <!-- <circle cx="284" cy="213" r="213" />--> <path d="M188 0 L1 0 L1 188 L188 0 Z"> </clipPath> </defs> </svg> <div id="img"> <img src="img/1.jpg" width="568"> </div> A: you can't change cirle into polygon, for polygon, use path tag and its d attribute. Here's a link that can help.
{ "pile_set_name": "StackExchange" }
Q: How to create solution in asp.net I have to create website with business layer and data access layer. I want to have a structure like this. Complete project inside a solution. So that to open a website and other projects, I have to open only the solution. I tried like this, first I created on website and than added the projects to the website. but it is not coming as a solution. Please help A: From MSDN: In Visual Studio, click File, point to New, and then click Project. In the New Project dialog box, in the Project types pane, click Other Project Types, and then click Visual Studio Solutions. In the Templates pane, click Blank Solution. Enter the name of your project in the Name field, and then click OK.
{ "pile_set_name": "StackExchange" }
Q: Is there any way to connect a record player (RCA outputs) to AirPlay speakers? I've got a very simple situation, which is: I have a generic record player with a preamp and RCA outputs (red/white). I have a pair of speakers connected to an old Airport Express, one connected to a new Airport Express, and an Apple TV. Can I make the record player Do A Sound in the AirPlay-connected speakers? Options I've considered are: A Raspberry Pi, but the software side of it may be more trouble than it's worth Connecting the record player, using an adapter, to my iMac, and then using Rogue Amoeba's LineIn to capture input, and transmit all audio, using Soundflower and Porthole, to AirPlay. This worked, but the lag between different speakers is considerable. Also, I'm using three separate apps for a task I should be able to do with a small box. This doesn't seem like that maddeningly difficult an ask, but so far I've come up with nothing that works as an AirPlay transmitter in the same way as, say, iTunes. I can get this amp for cheap: http://www.pioneer.eu/uk/products/42/98/405/VSX-529-K/page.html but I don't understand if it can transmit as well as receive AirPlay streams. Halp? A: Now I have figured out a simple and reasonably cheap solution for Airplay that does not require a computer, paid apps and similar, only a cable, that have multiple other uses, and an iOS device not in use while listening (depending on the circumstances I use either my iPhone or my iPad), see this http://davidbo.livejournal.com/795.html (It is added to the Wayback Machine so it won't disappear). Some non-dealbreaking minor issues remains, I will update that article when I find solutions to them.
{ "pile_set_name": "StackExchange" }
Q: Overwrite an Array I am new at Java and I am trying to overwrite an array like the following: {2,7,6,1,9} to {9,13,7,10,9}. So I am trying to add up neighbouring numbers in an array and overwrite the first number with the sum. My code looks like this: int add = numbers[i] + numbers[i+1]; int[] numbersAdd = new int[numbers.length]; i = 1; int j = 1; while(j < numbers.length) { numbersAdd[j] = add; i++; j++; } I get always an IndexOutofBoundException. Can you help me with that? Thank you! A: You should move add inside the while loop, and change the starting and ending indexes of i and j, like: int[] numbersAdd = new int[numbers.length]; int i = 0; int j = 0; while(j < numbers.length - 1) { int add = numbers[i] + numbers[i+1]; numbersAdd[j] = add; i++; j++; } numbersAdd[numbers.length - 1] = numbers[numbers.length - 1]; or it can be done using a for-loop: int[] numbersAdd = new int[numbers.length]; for(int i = 0; i < numbers.length - 1; i++) { numbersAdd[i] = numbers[i] + numbers[i + 1]; } numbersAdd[numbers.length - 1] = numbers[numbers.length - 1];
{ "pile_set_name": "StackExchange" }
Q: The frame of the UIView is changed after be flipped I used UIView.transition method to flip between 2 views, but after that, the frame of both views was changed. if isFront { UIView.transition(from: frontView, to: behindView, duration: 0.5, options: .transitionFlipFromRight,completion: { (finished) in if finished { self.isFront = false } }) } else { UIView .transition(from: behindView, to: frontView, duration: 0.5, options: .transitionFlipFromLeft, completion: { (finished) in if finished { self.isFront = true } }) } What is my wrong? Thanks for your helps. A: I solved the same issue. The problem is that when we use flip transition from view A to view B we lose its constraints. Solution: Put both views (i.e frontView and behindView) into a parentView and use: UIView.transition(with: scroller, duration: 0.5, options: .transitionFlipFromLeft,animations: { () -> Void in}, completion: { _ in }) Example: @IBAction func FlipButtonAction(_ sender: Any) { if(front){ frontView.isHidden = true behindView.isHidden = false UIView.transition(with: parentView, duration: 0.5, options: .transitionFlipFromLeft,animations: { () -> Void in}, completion: { _ in }) print("1") }else{ frontView.isHidden = false behindView.isHidden = true UIView.transition(with: parentView, duration: 0.5, options: .transitionFlipFromLeft,animations: { () -> Void in}, completion: { _ in }) print("2") } front = !front }
{ "pile_set_name": "StackExchange" }
Q: add Perl Modules' Directory to include path using .htaccess for CGI scripts I've used Cpanel to install per modules on my host server running lightspeed. It gave an "Installation Successful" message too. But it shows: Location of Your Perl Module(s) Path: /home/username/perl Using Your Perl Module(s): You will need to add /home/username/perl to the include path. Is it possible to add it using only .htaccess? Because it's my only access to the server. A: It should be possible using the SetEnv directive. Try putting this in your .htaccess: SetEnv PERL5LIB /home/username/perl If you want to add more than one path, separate them with :, like this: SetEnv PERL5LIB /home/username/perl:/some/other/path You can (of course) also use this to set other environment variables. Another option would be adding it to the include path from inside Perl itself. You will have to add the line use lib "/home/username/perl"; to the CGI script(s), somewhere before it loads the module(s) installed there.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to invert colors on a randomize position? I want to take the colors on my screen and invert them, then print them back to the screen using the BitBlt function, as I know the function takes a picture, copies it and pastes it It back to the screen. Basically what I want is to invert the colors with DSTINVERT, what it does it take the colors on the screen, invert them and print back to the screen. So I used that, and I wanted to do the random position on the screen, I took the screen pixels with the GetSystemMetrics function and did a random print on the screen. But it doesn't work for me, doesn't print anything and doesn't do anything, if I put my randomness resolution (1920x1080), it works and prints randomly, but I want the program to work as well on all screens. Would appreciate help. #include <iostream> #include <Windows.h> #include <time.h> using namespace std; int main() { srand(time(0)); HDC desktop = GetDC(GetDesktopWindow()); int width = GetSystemMetrics(SM_CXSCREEN); int height = GetSystemMetrics(SM_CYSCREEN); for (int i = 0; i < 1000; i++) { // Position on the screen int x = rand() % width; int y = rand() % height; Sleep(3000); BitBlt(desktop, width, height, 250, 250, desktop, width, height, DSTINVERT); } return 0; } And I would also love if someone explain the two parameters (7, 8) because I did not understand so much about doing so I did the same randomness. A: Sorry! my fault. I have used the width and height as parameters. I was need to use the x and y. My program is now working well. But i still want please explain about the parameters (8, 7). Thanks! #include <iostream> #include <Windows.h> #include <time.h> using namespace std; int main() { srand(time(0)); HDC desktop = GetDC(GetDesktopWindow()); int width = GetSystemMetrics(SM_CXSCREEN); int height = GetSystemMetrics(SM_CYSCREEN); for (int i = 0; i < 1000; i++) { // Size int size1 = rand() % 500; int size2 = rand() % 500; // Position on the screen int x = rand() % width; int y = rand() % height; Sleep(3000); BitBlt(desktop, x, y, size1, size2, desktop, x, y, DSTINVERT); } return 0; }
{ "pile_set_name": "StackExchange" }
Q: $\text{proj} _{u_1}v + \text{proj} _{u_2}v = \text{proj} _{U}v$ Let $U = $span$\{u_1,u_2\}$ , $u_1,u_2$ are orthogonal and $v$ be a vector. Does the following holds true? $$\text{proj} _{u_1}v + \text{proj} _{u_2}v = \text{proj} _{U}v$$ A: Yes, this is true. It is enough to verify that the equation holds for $v$ of the form $au_1+bu_2$ and the equation holds for this $v$ because $proj_{u_1} (au_1+bu_2)=au_1$ (in view of orthogonality) and $proj_{u_2} (au_1+bu_2)=bu_2$
{ "pile_set_name": "StackExchange" }
Q: Finding the distance of coordinates from the beginning of a route in Shapely I have a list of coordinates (lat/lon) representing a route. Given a certain radius and another coordinate I need to check if the coord is in the route (within the given radius from any point) and its distance from the beginning of the route. I looked at Shapely and it looks like a good solution. I started off by creating a StringLine from shapely.geometry import LineString route = LineString[(x, y), (x1, y1), ...] Then to check if the point is near the route I've added a buffer and checked for intersection from shapely.geometry import Point p = Point(x, y) r = 0.5 intersection = p.buffer(r).intersection(route) if intersection.is_empty: print "Point not on route" else: # Calculate P distance from the begning of route I'm stuck calculating the distance. I thought of splitting the route at p and measuring the length of the first half but the intersection result I get is a HeterogeneousGeometrySequence which I'm not sure what I can do with. I believe I found a solution: if p.buffer(r).intersects(route): return route.project(p) A: Rather than buffering a geometry, which is expensive and imperfect (since buffering requires a number of segments and many other options), just see if the point is within a distance threshold: if route.distance(p) <= r: return route.project(p) Also, you probably realised by now that your distance units are in degrees. If you want linear distances, like meters, you would need to make it much more complicated using different libraries.
{ "pile_set_name": "StackExchange" }
Q: What Easter Eggs are in Hearthstone? Lets keep it simple. I have not been able to find any forums with facts about Easter Eggs in Hearthstone, so I would love to know the following. Are there any Easter Eggs in Hearthstone? And if so, which Easter Eggs are there in Hearthstone? NOTE: That I am not interested in knowing the definition on Easter Eggs. (look here for a discription of an Easter Egg in a video game: http://www.gamesradar.com/100-best-easter-eggs-all-time/) A: So from the looks of things, there aren't actually many Easter Eggs in Hearthstone, at least not many discovered yet. It is indeed a little surprising, but to be fair, Hearthstone isn't exactly the largest of games. The closest things to Easter Eggs are actually more like hidden references to the lore of Warcraft. If Cairne Bloodhoof is played against a warrior, he says the line "Garrosh, you are not fit to rule the horde" rather than his usual line. If Illidan Stormrage is played against a druid, he says the line "Hello, brother" rather than his usual line. Millhouse Manastorm, the hero in the tutorial, says a line "Just you wait until I have 10 mana!" This is a reference to the old Millhouse Manastorm card, which had "Battlecry: Put a 'Mega-Blast' card in your hand." Megablast is a 10 mana card that deals 5 damage to all enemies. Reference In the Hearthstone credits, there are personalized cards for team members of Hearthstone, many of which seem to reference aspects of the individual person. Reference The opening video has an 8 cost Pyroblast; it's now 10. If you click on the vegetables long enough you can get a boot. If you play Dire Wolf Alpha against the Big Bad Wolf, your wolf whimpers after the Big Bad Wolf scared him. Reference Video There are of course individual cards that are references to things in World of Warcraft rather than the actual lore, one of the most obvious being Leeroy Jenkins, but I wouldn't necessarily define these kinds of things as Easter Eggs. If individual unlisted extras are discovered, feel free to edit this question and tack them on here, so they can be easily organized. However, from what my research could find, these are pretty much the only ones discovered thusfar.
{ "pile_set_name": "StackExchange" }
Q: Repeat some action every x minutes between "A" a.m. and "B" p.m How can I run for example local notifications? In UNUserNotificationCenter there is not repeat feature. Maybe using NSTimer or something like this? Why my code does not work as I expected let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] for hour in hours { for minute in stride(from: 0, to: 60, by: 5){ let content = UNMutableNotificationContent() content.title = "Title" content.body = "Body" var dateComponents = DateComponents() dateComponents.hour = hour dateComponents.minute = minute let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request) { (error : Error?) in if let theError = error { print(theError.localizedDescription) } } } } A: There is a repeat feature. From Apple's documentation: let content = UNMutableNotificationContent() content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil) content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil) // Deliver the notification in five seconds and repeat it content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true) // Schedule the notification. let request = UNNotificationRequest(identifier: "60_seconds", content: content, trigger: trigger) let center = UNUserNotificationCenter.current() center.add(request, withCompletionHandler: nil) Edit: As also written in the documentation, you certainly have to have user permissions to post notifications: let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in // Enable or disable features based on authorization } Result: Notification is posted every minute:
{ "pile_set_name": "StackExchange" }
Q: How to set different color to each row How can I set different color to each row? The data are get from SQLite to table layout and the number of rows are not fixed. I want to set the first row to green, second to red, third row to red again...I have declared the color on color.xml, but they are not working... DisplayData.java // outer for loop for (int i = 0; i < rows; i++) { TableRow row = new TableRow(this); row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); // inner for loop for (int j = 0; j < cols; j++) { TextView tv = new TextView(this); tv.setLayoutParams(new TableRow.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT )); // tv.setBackgroundResource(R.drawable.cell_shape); tv.setGravity(Gravity.CENTER); tv.setTextSize(18); tv.setPadding(0, 5, 0, 5); tv.setText(c.getString(j)); row.addView(tv); row.setBackgroundResource(R.drawable.color); row.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(DisplayData.this, UpdatePage.class); intent.putExtra("name", name2); intent.putExtra("date",date2); startActivity(intent); } }); } c.moveToNext(); table_layout.addView(row); } sqlcon.close(); } } color.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <color android:name="green">#00ff00</color> <color android:name="red">#FF0000</color> </resources> </LinearLayout> A: There's probably a much nicer solution, but I guess this could work: // outer for loop int colorIndex = 0; for (int i = 0; i < rows; i++) { if (index == 0) { //set background row.setBackgroundColor(getResources().getColor(R.color.some_color)); index++; } else if (index == 1) { //set background row.setBackgroundColor(getResources().getColor(R.color.some_other_color)); index++; } if (index == 2) { //set background row.setBackgroundColor(getResources().getColor(R.color.yet_another_color)); index = 0; } }
{ "pile_set_name": "StackExchange" }
Q: Video mute/unmute button javaScript JavaScript beginner here! I am trying to make a video player in javaScript for a school project but I am having trouble with my mute button. I want the button to mute the video when clicked and unmute if the button is pressed again. So far I have only been able to mute the video and keep it muted. Here is my current mute button. var button = document.getElementById('mute'); button.onclick = function (){ video.muted = true; }; I tried an if else statement but it was unsuccessful var button = document.getElementById('mute'); button.onclick = function (){ if (video.muted = false) { video.muted = true; } else { video.muted = false; } }; Thanks for your help. A: if (video.muted = false) { video.muted = true; } This should be if (video.muted === false) { video.muted = true; } Or else the else statement will never run, since you are setting video.muted to false every time in the if statement itself.
{ "pile_set_name": "StackExchange" }
Q: WPF margins don't add up I just started working with WPF and I am trying to set up a grid with four rows that have a height of 150. That would take up 600 of my 800 pixels that I set for the height. I then set my top margin to 30 and my bottom margin to 170 to give myself some room for controls at the bottom. Everything looks great in design view but when I run my applications the bottom row has some area cut off. Design View Running View I don't understand what is causing this discrepancy between these views. <Page x:Class="EzTargetProject.HomePage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="800" d:DesignWidth="1280" Title="HomePage"> <Grid Margin="20,30,20, 170" Grid.Column="4" Grid.Row="4" Background="Gray" ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="150"/> <RowDefinition Height="150"/> <RowDefinition Height="150"/> <RowDefinition Height="150"/> </Grid.RowDefinitions> <!-- Name --> <StackPanel Grid.Column="0" Grid.Row="0" Orientation="Vertical" /> </Grid> A: You can avoid the bottom margin if you want to set the height of your grid. If you always want to have a 600px height grid, just set it. I'd use a ScrollViewer as a parent to let the user see the controls you are going to set under the grid (if the user wants to have a little window forexample): Enabling Scrollbar in WPF
{ "pile_set_name": "StackExchange" }
Q: ViaCEP não preenche dados de endereço do usuário (Website na plataforma .NET) Estou desenvolvendo uma aplicação web na plataforma .NET e pensei em fazer com que o usuário digite o cep de seu endereço e automaticamente ele preencheria os textboxs com dados de logradouro, bairro, cidade e estado. Mas no meu código ele não funciona, não sei porque. Aqui está o meu código: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Novo Registro</title> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script> <script src="https://fiddle.jshell.net/js/lib/dummy.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("#txtCPF").keydown(function(){ try { $("#txtCPF").unmask(); } catch (e) {} var tamanho = $("#txtCPF").val().length; if(tamanho < 11){ $("#txtCPF").mask("999.999.999-99"); } else if(tamanho >= 11){ $("#txtCPF").mask("99.999.999/9999-99"); } }); }//]]> </script> <!-- Adicionando Javascript --> <script type="text/javascript"> function limpa_formulario_cep() { //Limpa valores do formulário de cep. document.getElementById("#txtRua").value=(""); document.getElementById('#txtBairro').value=(""); document.getElementById('#txtCidade').value=(""); document.getElementById('#txtEstado').value=(""); } function meu_callback(conteudo) { if (!("erro" in conteudo)) { //Atualiza os campos com os valores. document.getElementById('#txtRua').value=(conteudo.logradouro); document.getElementById('#txtBairro').value = (conteudo.bairro); document.getElementById('#txtCidade').value = (conteudo.localidade); document.getElementById('#txtEstado').value = (conteudo.uf); } //end if. else { //CEP não Encontrado. limpa_formulario_cep(); alert("CEP não encontrado."); } } function pesquisacep(valor) { //Nova variável "cep" somente com dígitos. var cep = valor.replace(/\D/g, ''); //Verifica se campo cep possui valor informado. if (cep != "") { //Expressão regular para validar o CEP. var validacep = /^[0-9]{8}$/; //Valida o formato do CEP. if(validacep.test(cep)) { //Preenche os campos com "..." enquanto consulta webservice. document.getElementById('#txtRua').value = "..."; document.getElementById('#txtBairro').value = "..."; document.getElementById('#txtCidade').value = "..."; document.getElementById('#txtEstado').value = "..."; //Cria um elemento javascript. var script = document.createElement('script'); //Sincroniza com o callback. script.src = '//viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback'; //Insere script no documento e carrega o conteúdo. document.body.appendChild(script); } //end if. else { //cep é inválido. limpa_formulario_cep(); alert("Formato de CEP inválido."); } } //end if. else { //cep sem valor, limpa formulário. limpa_formulario_cep(); } }; </script> </head> <body> <form id="form1" runat="server"> <div> <h3>Cadastro de Clientes - Novo Registro</h3> <h5>Obs.: Campos sinalizados com *(asterisco) são de preenchimento obrigatório!</h5> <asp:TextBox ID="txtNome" runat="server" Width="384px" placeholder="Nome*"></asp:TextBox> <asp:RequiredFieldValidator ID="txtNomeValidator" runat="server" ControlToValidate="txtNome" Display="Dynamic" ForeColor="Red" ErrorMessage="*"></asp:RequiredFieldValidator> <asp:TextBox ID="txtFantasia" runat="server" Width="384px" placeholder="Fantasia"></asp:TextBox><br /> <asp:TextBox ID="txtCPF" runat="server" Width="384px" placeholder="CPF ou CNPJ"></asp:TextBox><br /> <asp:TextBox ID="txtCEP" runat="server" Width="70px" placeholder="CEP*" AutopostBack="true"></asp:TextBox><br /> <asp:TextBox ID="txtLogradouro" runat="server" Width="305px" placeholder="Logradouro"></asp:TextBox><br /> <asp:TextBox ID="txtNumero" runat="server" Width="80px" placeholder="Número"></asp:TextBox><br /> <asp:TextBox ID="txtComplemento" runat="server" Width="100px" placeholder="Complemento"></asp:TextBox><br /> <asp:TextBox ID="txtBairro" runat="server" Width="200px" placeholder="Bairro"></asp:TextBox><br /> <asp:TextBox ID="txtCidade" runat="server" Width="200px" placeholder="Cidade"></asp:TextBox><br /> <asp:TextBox ID="txtEstado" runat="server" Width="50px" placeholder="Estado"></asp:TextBox><br /> <asp:Button ID="btnSalvar" runat="server" Text="Salvar"/> </div> </form> </body> </html> meu code-behind: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class insert : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { txtCEP.Attributes.Add("onblur", "pesquisacep(this.value);"); } } Ele funciona no JSBIN: http://output.jsbin.com/baxuyumace Alguém poderia me ajudar nessa, por favor? A: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Novo Registro</title> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script> <script src="https://fiddle.jshell.net/js/lib/dummy.js"></script> <script type='text/javascript'>//<![CDATA[ window.onload=function(){ $("#txtCPF").keydown(function(){ try { $("#txtCPF").unmask(); } catch (e) {} var tamanho = $("#txtCPF").val().length; if(tamanho < 11){ $("#txtCPF").mask("999.999.999-99"); } else if(tamanho >= 11){ $("#txtCPF").mask("99.999.999/9999-99"); } }); }//]]> </script> <!-- Adicionando Javascript --> <script type="text/javascript" > $(document).ready(function() { function limpa_formulario_cep() { // Limpa valores do formulário de cep. $("#txtLogradouro").val(""); $("#txtBairro").val(""); $("#txtCidade").val(""); $("#txtEstado").val(""); } //Quando o campo cep perde o foco. $("#txtCEP").blur(function() { //Nova variável "cep" somente com dígitos. var cep = $(this).val().replace(/\D/g, ''); //Verifica se campo cep possui valor informado. if (cep != "") { //Expressão regular para validar o CEP. var validacep = /^[0-9]{8}$/; //Valida o formato do CEP. if(validacep.test(cep)) { //Preenche os campos com "..." enquanto consulta webservice. $("#txtLogradouro").val("...") $("#txtBairro").val("...") $("#txtCidade").val("...") $("#txtEstado").val("...") //Consulta o webservice viacep.com.br/ $.getJSON("//viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) { if (!("erro" in dados)) { //Atualiza os campos com os valores da consulta. $("#txtLogradouro").val(dados.logradouro); $("#txtBairro").val(dados.bairro); $("#txtCidade").val(dados.localidade); $("#txtEstado").val(dados.uf); } //end if. else { //CEP pesquisado não foi encontrado. limpa_formulario_cep(); alert("CEP não encontrado."); } }); } //end if. else { //cep é inválido. limpa_formulario_cep(); alert("Formato de CEP inválido."); } } //end if. else { //cep sem valor, limpa formulário. limpa_formulario_cep(); } }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <h3>Cadastro de Clientes - Novo Registro</h3> <h5>Obs.: Campos sinalizados com *(asterisco) são de preenchimento obrigatório!</h5> <asp:TextBox ID="txtNome" runat="server" Width="384px" placeholder="Nome*"></asp:TextBox> <asp:RequiredFieldValidator ID="txtNomeValidator" runat="server" ControlToValidate="txtNome" Display="Dynamic" ForeColor="Red" ErrorMessage="*"></asp:RequiredFieldValidator> <asp:TextBox ID="txtFantasia" runat="server" Width="384px" placeholder="Fantasia"></asp:TextBox><br /> <asp:TextBox ID="txtCPF" runat="server" Width="384px" placeholder="CPF ou CNPJ"></asp:TextBox><br /> <asp:TextBox ID="txtCEP" runat="server" Width="70px" placeholder="CEP*" AutopostBack="true" AcceptsTab="True"></asp:TextBox><br /> <asp:TextBox ID="txtLogradouro" runat="server" Width="305px" placeholder="Logradouro"></asp:TextBox><br /> <asp:TextBox ID="txtNumero" runat="server" Width="80px" placeholder="Número"></asp:TextBox><br /> <asp:TextBox ID="txtComplemento" runat="server" Width="100px" placeholder="Complemento" AutopostBack="true"></asp:TextBox><br /> <asp:TextBox ID="txtBairro" runat="server" Width="200px" placeholder="Bairro"></asp:TextBox><br /> <asp:TextBox ID="txtCidade" runat="server" Width="200px" placeholder="Cidade"></asp:TextBox><br /> <asp:TextBox ID="txtEstado" runat="server" Width="50px" placeholder="Estado"></asp:TextBox><br /> <asp:Button ID="btnSalvar" runat="server" Text="Salvar"/> </div> </form> </body> </html> Consegui resolver. Pra quem tiver interesse, o código está aí.
{ "pile_set_name": "StackExchange" }
Q: How to input a model instance in a form field I have a simple model with 2 classes: class Company(models.Model): company_name = models.CharField(default='', max_length=128, blank=True, null=True) class Visitor(models.Model): visitor_company = models.ForeignKey(Company) visitor_name = models.CharField(default='', max_length=128, blank=False, null=False) I also have a simple form: class VisitorForm(forms.ModelForm): visitor_company = forms.CharField() class Meta: model = Visitor fields = "__all__" And here is the view.py code: def home(request): form = Visitor() if request.method == "POST": form = Visitor(request.POST) if form.is_valid(): obj, created = Visitor.objects.get_or_create(**form.cleaned_data) if created: messages.add_message(request, messages.SUCCESS, 'Visitor added.') else: messages.add_message(request, messages.INFO, 'Visitor exists : %s' % obj.visitor_name) return redirect('visitors') context = { 'form': form } return render(request, "visitors/home.html", context) I have set visitor_company as a CharField as I want to use Typeahead for users to specify the ForeignKey, rather than Django's built in dropdown (which would appear if I did not set the input type). However, when I use this method, even if I input a valid company_name in the visitor_company field, I get Cannot assign "XXX": "Visitor.visitor_company" must be a "Company" instance. How do I input a Company instance? Is it also possible to use get_or_create on a ForeignKey like this if the Company record doesn't exist? A: This is untested code, so consider this a starting point, no real solution: forms.py class VisitorForm(forms.ModelForm): visitor_company = forms.CharField() def clean_visitor_company(self): vc = self.cleanded_data['visitor_company'] try: vc_object = Company.objects.get(company_name=vc) except Company.DoesNotExist: vc_object = Company.objects.create(company_name=vc) return vc_object class Meta: model = Visitor fields = "__all__" views.py def home(request): form = VisitorForm(request.POST or None) if form.is_valid(): form.save() return redirect('visitors') return render(request, "visitors/home.html", { 'form': form })
{ "pile_set_name": "StackExchange" }
Q: Add html to jquery text function I am editing the wordpress js and was unable to do so as I am not a jquery expert so i decided to post question here i am wondering to set the font size of AM or PM to small but in js the html is not working i know that would be possible as when i place html tags it is not converting just showing as html output $time.text(hours + ":" + minutes + ampm); at the place of ampm i would like to wrap it up with si i tried to do like this $time.text(hours + ":" + minutes +"<p class='small'>" + ampm + "</p>"); the output is coming as 03:25 <p class='small'> PM </p> so the html is harcoded not converting can anyone help me out with this concern ? A: change .text to .html:- $time.html(hours + ":" + minutes +"<p class='small'>" + ampm + "</p>"); jQuery Docmentation .text = Set the content of each element in the set of matched elements to the specified text. .html = Set the HTML contents of each element in the set of matched elements. A: .html() treats/interpret the string as HTML whereas .text() treats the content as text Thus you need to use.html() instead of .text(): $time.html(hours + ":" + minutes +"<p class='small'>" + ampm + "</p>");
{ "pile_set_name": "StackExchange" }
Q: SQL [Hard query - to make or to avoid] SELECT Name, ( NOT (ID_ListGroupParIzm IN (SELECT ID_Param FROM TbUserParam WHERE ID_User=:ID_User ) ) ) Visi FROM CfgListParIzm WHERE ID_ListGroupParIzm=:ID_ListGroupParIzm Errors : Message 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword "NOT". Message 102, Level 15, State 1, Line 2 Incorrect syntax near the construction ":". added : I'll try to explain what I want with it. I need a name from one table and a BOOL value for each Node wich will be false if ID_ListGroupParIzm IN (SELECT ID_Param FROM TbUserParam WHERE ID_User=:ID_User And ID_ListGroupParIzm (from CfgListParIzm ) = ID_Param (from TbUserParam) forget to say :( btw : looking like select can't return logics value . . . How to get my purpose then :( added a try : SELECT Name, COALESCE( ( SELECT TOP 1 0 FROM TbUserParam WHERE TbUserParam.ID_User = :ID_User AND TbUserParam.ID_Param = CfgListParIzm.ID_ListParIzm ), 1) Visi FROM CfgListParIzm WHERE CfgListParIzm.ID_ListGroupParIzm = :ID_ListGroupParIzm error : Message 102, Level 15, State 1, line 6 Incorrect syntax near the construction ":". But ... sure >_< I need to remake it as a Procedure, Thank you. A: SELECT Name, COALESCE( ( SELECT TOP 1 0 FROM TbUserParam WHERE ID_User = :ID_User AND ID_ListGroupParIzm = :ID_ListGroupParIzm ), 1) Visi FROM CfgListParIzm WHERE ID_ListGroupParIzm = :ID_ListGroupParIzm
{ "pile_set_name": "StackExchange" }
Q: c++ virtual inheritance: Implementation difference I know the usage of virtual inheritance: class A { public: void Foo() {} }; class B : public virtual A {}; class C : public virtual A {}; class D : public B, public C {}; What I want to know is the difference between class X { public: void Bar() {} }; class Y : public virtual X {}; and class X { public: void Bar() {} }; class Y : public X {}; mainly from the implementation perspective. I mean when would I not want to use virtual inheritance? A: Firstly, virtual inheritance will "merge" all identically-typed virtual bases into a single base subobject, shared by all derived types in the complete object. Do you want that to happen? If you want such bases to be represented by separate base subobjects, then you can't use virtual inheritance. So, there is an obvious matter of your intent. In your first example, the same single A subobject will be shared by classes B, C and D within a complete object of type D. If inheritance was non-virtual, then B would have its own separate A and C would have its own separate A. This would obviously affect the behavior of any code that relies on As object identity. So, from this point of view it is really a question to you: what do you want to implement? A single shared base subobject? Or multiple independent base subobjects? (Your X and Y example is non-representative. The above properties of virtual inheritance only reveal itself in multiple-inheritance configurations. In single-inheritance situation virtual inheritance achieves nothing, besides imposing potential performance/space overhead.) Secondly, in order to provide access from all derived classes to a single shared base class subobject (in case of virtual inheritance) the compiler will use run-time implementation structures. Typically derived classes will access their virtual bases through pointers embedded into each object with virtual base. This imposes a performance penalty and requires additional space in object's layout. Meanwhile, "normal" (non-virtual) inheritance produces a fixed compile-time layout, which means that all conversions between classes are performed by adding or subtracting a fixed offset, immediately known to the compiler. This is faster and requires no additional run-time information.
{ "pile_set_name": "StackExchange" }
Q: WinCE 6.0, work with GPRS/WiFi I'm working on a project, which should connect to servers through wifi/gprs. Project is an application for Windows CE 6.0 device, I'm writing in Visual Studio 2008 on C#. I have two severs to work with. The first I have to connect via wifi, second - via gprs. So I need to know, how can I change the method of connecting between wifi and gprs? I found and tried this way: I turn on both wifi and gprs on my device. So I work via wifi because it has a higher priority. When I need to work via gprs, I turn off wifi (SetDevicePower function). But when I turn wifi on, it doesn't connect back to my Preferred Network. Also I heard about the way to change priority between gprs/wifi in OS priority table programmatically, but I didn't find any information about how to do this. I hope you can help me. A: I would use the route command from a shell. lets assume server1 ip: 123.123.123.1 server2 ip: 123.123.123.2 wifi ip : 192.168.1.101 gateway: 192.168.1.1 gprs ip : 10.1.2.3 gateway: 10.1.1.1 Now you can excute in a command prompt route add 123.123.123.1 MASK 255.255.255.255 192.168.1.1 and route add: 123.123.123.2 MASK 255.255.255.255 10.1.1.1 This should route all trafic to server 1 over wifi and to server 2 over gprs, without changing a single line of code in your app. You can verify it worked with tracert 123.123.123.1 tracert 123.123.123.2 However, you could use your app to periodically perform this task (I assume gprs ip could change from time to time) with Process.Start(...) - delete route 1 - add route 1 - delete route 2 - add route 2 You even could specify the interface with the IF 2 switch (route list prints the interface id for your network cards). Another interesting post to read is this one: http://ce4all.blogspot.com/2007/05/routing-ip-traffic-via-specified.html The author uses the GetAdapterAddresses() and CreateIpForwardEntry() P/Invokes: http://msdn.microsoft.com/en-us/library/ms927384.aspx http://msdn.microsoft.com/en-us/library/ee495149%28v=winembedded.60%29.aspx
{ "pile_set_name": "StackExchange" }
Q: Powershell 3D WinForms 3D Charts I'm having some trouble making my charts appear in 3D, here's my code [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") $WeekTable = @{ "Week1" = 50 "Week2" = 50 } $WeekChart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart $WeekChart.Width = 1200 $WeekChart.Height = 768 $WeekChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea3DStyle $WeekChartArea.Enable3D = $true $WeekChart.ChartAreas.Add($WeekChartArea) $WeekChart.Series.Add("Data") $WeekChart.Series["Data"].Points.DataBindXY($WeekTable.Keys, $WeekTable.Values) #$WeekChart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie # Display chart on form $WeekChart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = "Escape Windows XP statistics" $Form.Width = 1024 $Form.Height = 820 $Form.controls.add($WeekChart) $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog() The chart shows up fine on my form but it is not displayed in 3D. The Enable3D property is true as it should be?? if i check when the script has finished A: The problem you're seeing is that the ChartArea3DStyle is not a ChartArea, because it does not inherit from the ChartArea class. However, you are using it like it is a ChartArea when you call $WeekChart.ChartAreas.Add($WeekChartArea). I don't know why that isn't throwing an exception, but it sure seems to me like it should. Instead, you need to simply create a ChartArea, then change its Area3DStyle property to the value of your ChartArea3DStyle instance. Don't treat the ChartArea3DStyle object like a ChartArea, because it isn't one. $Area3DStyle = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea3DStyle; $Area3DStyle.Enable3D = $true; $ChartArea = $WeekChart.ChartAreas.Add('ChartArea'); $ChartArea.Area3DStyle = $WeekChartArea; The final script would look like this: [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") $WeekTable = @{ "Week1" = 50 "Week2" = 50 } $WeekChart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart $WeekChart.Width = 1200 $WeekChart.Height = 768 $Area3DStyle = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea3DStyle; $Area3DStyle.Enable3D = $true; $ChartArea = $WeekChart.ChartAreas.Add('ChartArea'); $ChartArea.Area3DStyle = $Area3DStyle; $ChartSeries = $WeekChart.Series.Add("Data") $WeekChart.Series["Data"].Points.DataBindXY($WeekTable.Keys, $WeekTable.Values) #$WeekChart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie # Display chart on form $WeekChart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = "Escape Windows XP statistics" $Form.Width = 1024 $Form.Height = 820 $Form.controls.add($WeekChart) $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog()
{ "pile_set_name": "StackExchange" }
Q: "Whisky prices" in Italian I am looking for the correct translation of "whisky prices". It looks like prezzo is singular and prezzi is plural. Now I am wondering if one needs an article or a declension to form this phrase in Italian. I translated it as whisky prezzi or prezzi del whisky. Which one of these two forms is correct? Or is there another form perhaps? A: Prezzi del whisky is the correct form, whisky prezzi is surely an error. This type of preposition (del) is a preposition combined with an article (preposizione articolata) and is built by a simple preposition + definite article. http://www.oneworlditaliano.com/english/italian-grammar/articulated-prepositions-in-italian.htm Take care in Italian the word whisky is used for both singular and plural.
{ "pile_set_name": "StackExchange" }
Q: How to optimise master-slave query with count by max? I have a query to get games with current number of players for each of game ordered by the measure of what percent of player slots are filled by players. It goes like this: SELECT g.* , COUNT( p.ID ) NUM_OF_PLAYERS FROM games g, players p WHERE g.ID = p.GAME_ID GROUP BY g.ID ORDER BY COUNT( p.ID ) / g.MAX_NUM_OF_PLAYERS DESC And it takes like 4 seconds. And Explain gives me this mainly: How to make it faster? A: Try this query. Is it faster? select g.*,p.NUM_OF_PLAYERS NUM_OF_PLAYERS from games g left join ( select GAME_ID, COUNT( ID ) NUM_OF_PLAYERS from players group by GAME_ID ) p on (g.ID = p.GAME_ID) ORDER BY p.NUM_OF_PLAYERS/g.MAX_NUM_OF_PLAYERS DESC
{ "pile_set_name": "StackExchange" }
Q: How to direct subdomains to the correct JBoss App? new to JBoss and am configuring some applications. I know how to do this in apache webserver, but not using Jboss. I have successfully deployed 3 applications on a redhat box, JBoss 4.2. If my server is called fruit.mycompany.com, I can access the three apps this way: http://fruit.mycompany.com:8080/quince http://fruit.mycompany.com:8080/pineapple http://fruit.mycompany.com:8080/lime Next, I created three subdomains, which are aliases of the server fruit. http://quince.mycompany.com http://pineapple.mycompany.com http://lime.mycompany.com How can I get each subdomain to point at it's corresponding application? I want http://quince.mycompany.com to actually open http://fruit.mycompany.com:8080/quince. In apache, I would use the VirtualHost tag to point each subdomain to the correct Document Root. How do I do it with JBoss or Tomcat? Can I do it with redirection ( does Tomcat have something like mod_rewrite )? A: Tomcat supports virtual hosts. You'll basically have to: 1) Change tomcat's "listen" port to 80 instead of 8080. 2) Modify tomcat's server.xml to list your servers: <Engine name="Catalina" defaultHost="quince"> <Host name="quince" appBase="quince_apps"/> <Host name="pineapple" appBase="pineapple_apps"/> <Host name="lime" appBase="lime_apps"/> </Engine> 3) Move each application to 'ROOT' folder of corresponding "_apps" folder. When I was in a similar situation, I chose to use Apache redirection instead; however I had Apache already serving static pages (public website). A: I gave up with Tomcat. The situation became too complicated. I have a web site running on port 80 already (on a separate instance of JBoss). I have these three applications, quince, pineapple and lime running on their own JBoss instance on port 8080. To solve my problem, I just wrote a javascript function on the index page of the website running on port 80. I check location to see which domain is being called and then redirect to the appropriate website on port 8080. The script looks something like this: var whois=location+" "; if (whois.indexOf("quince.mycompany.com") > -1) { setTimeout('window.location.replace("http://quince.mycompany.com:8080/quince/");', 10); exit; } if (whois.indexOf("lime.mycompany.com") > -1) { setTimeout('window.location.replace("http://lime.mycompany.com:8080/lime/");', 10); exit; } ... // otherwise redirect to the app running on port 80 setTimeout('window.location.replace("http://fruit.mycompany.com/otherapp/");', 10); It's not exactly what I wanted, but at least my users now have a shortcut URL, and they don't have to remember port numbers: http://lime.mycompany.com redirects to -> http://lime.langara.bc.ca:8080/lime
{ "pile_set_name": "StackExchange" }
Q: How can I test if my font is rendered correctly in pdf? When using different fonts in jasper report, you need to use font-extensions. However if the font is not rendered correctly is there a way that I can test if the font is supported by pdf so that I can understand if the problem is related to my font-extensions or to my .ttf font? The incorrect rendering of font when exporting to pdf from jasper reports is a common problem example Jasper Reports PDF doesn't export cyrillic values, as seen in checklist point 1 using font-extensions are not always enough, the font need's also to be supported by pdf generating library and able to render the actual character. This is why I have decided to pass this Q-A style questions, so that future user when hitting checklist 1 can have a reference on how to quickly test the font. A: Since jasper report use the itext library the easiest way to test if your font will be rendered correctly in pdf is to test it directly with itext. Example program*, adapted from iText: Chapter 11: Choosing the right font import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfWriter; public class FontTest { /** The resulting PDF file. */ public static final String RESULT = "fontTest.pdf"; /** the text to render. */ public static final String TEST = "Test to render this text with the turkish lira character \u20BA"; public void createPdf(String filename) throws IOException, DocumentException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename)); document.open(); BaseFont bf = BaseFont.createFont( "pathToMyFont/myFont.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf, 20); ColumnText column = new ColumnText(writer.getDirectContent()); column.setSimpleColumn(36, 730, 569, 36); column.addElement(new Paragraph(TEST, font)); column.go(); document.close(); } public static void main(String[] args) throws IOException, DocumentException { new FontTest().createPdf(RESULT); } } Some notes (seen in example): To render special characters use it's encoded value example \u20BA to avoid problems of encoding type on your file. Consider to always use Unicode encoding, this is recommended approach in the newer PDF standard (PDF/A, PDF/UA) and gives you the possibility to mix different encoding types, with the only dis-advantage of slightly larger file size. Conclusion: If your font is rendered correctly in the "fontTest.pdf", you have a problem with your font-extensions in jasper report. If you font is not rendered correctly in the "fontTest.pdf", there is nothing you can do in jasper reports, you need to find another font. *Latest jasper-reports distribution use a special version itext-2.1.7, the imports in this version is com.lowagie.text, if you are using later version the imports are com.itextpdf.text as in adapted example.
{ "pile_set_name": "StackExchange" }
Q: Division of Array into parts based upon a 2nd Array Two arrays one with objects and other with string values, based on second arrays values looking to dive first one to multiple. In my case it is two. let arr1= [{"key": "English","code": "en"}, {"key": "Arabic","code": "ar"}, {"key": "Chinese (traditional)","code": "zh"}, {"key": "Czech", "code": "cs"}, {"key": "Dutch","code": "nl"},{"key": "Finnish","code": "fi"}] let arr2 = ["English", "Dutch", "Finnish"]; let completed =[]; let optional =[]; for (let i = 0; i < arr2.length; i++) { for (let j = 0; j < arr1.length; j++) { if (arr1[j].key === arr1[i]) { completed.push(arr1[j]) }else{ optional.push(arr1[j]) } } } Aiming for output like this completed=[{"key": "English","code": "en"},{"key": "Dutch","code": "nl"}, {"key": "Finnish","code": "fi"}] optional=[{"key": "Arabic","code": "ar"},{"key": "Chinese (traditional)","code": "zh"}, {"key": "Czech", "code": "cs"} ] A: Some of the problems with your code are: Comparing the same array elements if (arr1[j].key === arr1[i]). Not breaking the loop on finding a matching element and inserting next element immediately into optional array. Fixing these issues, your code would look like: let arr1 = [{ "key": "English", "code": "en" }, { "key": "Arabic", "code": "ar" }, { "key": "Chinese (traditional)", "code": "zh" }, { "key": "Czech", "code": "cs" }, { "key": "Dutch", "code": "nl" }, { "key": "Finnish", "code": "fi" } ] ; let arr2 = ["English", "Dutch", "Finnish"]; let completed = []; let optional = []; for (let i = 0; i < arr1.length; i++) { let found = false; for (let j = 0; j < arr2.length; j++) { if (arr1[i].key === arr2[j]) { completed.push(arr1[i]); found = true; break; } } if (!found) { optional.push(arr1[i]); } } console.log("Completed: ", completed); console.log("Optional: ", optional); Another easier approach is to use Array.filter() and Array.includes(). let arr1 = [{ "key": "English", "code": "en" }, { "key": "Arabic", "code": "ar" }, { "key": "Chinese (traditional)", "code": "zh" }, { "key": "Czech", "code": "cs" }, { "key": "Dutch", "code": "nl" }, { "key": "Finnish", "code": "fi" } ] ; let arr2 = ["English", "Dutch", "Finnish"]; let completed = arr1.filter(item => arr2.includes(item.key)); let optional = arr1.filter(item => !arr2.includes(item.key)); console.log("Completed: ", completed); console.log("Optional: ", optional);
{ "pile_set_name": "StackExchange" }
Q: Is there a way to only play audio from a video? I want to play a downloaded talk show, but I only want to play audio. Whenever I do MediaPlayer.media().play("video.mp4"), it opens the video in a pop-up window. Is there a way to hide that window, or to disable video track if needed? I've tried setting renderer to null, but it doesn't do anything mediaPlayer.setRenderer(null); String url = "video.mp4"; mediaPlayer.media().play(url); I'd like to only play Audio from a video, but I always get a pop-up playing video track. A: You can do this with custom VLC switches passed as media player factory arguments: MediaPlayerFactory factory = new MediaPlayerFactory("--novideo"); AudioMediaPlayerComponent mediaPlayer = new AudioMediaPlayerComponent(factory); You don't need to use AudioMediaPlayerComponent, it just happens to be the most convenient.
{ "pile_set_name": "StackExchange" }
Q: Separating NaClO from its aqueous form in bleach I was wondering, can I separate the $\ce{NaClO}$ from the $\ce{H2O}$ in bleach. The decomposition point for $\ce{NaClO}$ is $374.14\ \mathrm{K}$, so I'm risking decomposing the compound if I do simple distillation. What should I do? PS: I don't have a vacuum pump. A: Sodium hypochlorite, $\ce{NaClO}$, is unstable and can't be separated from the water in which you usually find it without it decomposing. That's the short answer. To learn more about it check Wikipedia for sodium hypochlorite.
{ "pile_set_name": "StackExchange" }
Q: Select the last row and then format it in excel with VB I am trying to create a user form that inserts data into the last row of a spreadsheet in a logical fashion, but the data is not formatted once I drop it in to the cells. My first thought would be to simply select the last row and format it before I drop the data in. The '.Rows.Autofit' property works with this code, but the other settings, such as text that is left aligned, which is what I really need, do not work. What am I missing? (I replaced all userform text things and variables with "Stuff" for NDA reasons. I know this creates duplicates) Private Sub StuffUpload_Click() Dim ws As Worksheet ' Grabs the worksheet that the user is currently looking at, making this ' form work on all sheets Set ws = ActiveSheet ' Make sure all required fields have been entered If Stuff.Text = "" Then MsgBox "You must enter Stuff." Stuff.SetFocus Exit Sub End If ' Add a dash of formatting to the last row so the stuff we put into it will ' look nice ws.Range("B" & Rows.Count).End(xlUp).Offset(1).Select With Selection .HorizontalAlignment = xlLeft .VerticalAlignment = xlBottom .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False .Rows.AutoFit End With ' Adds the Stuff info into Col B at the Last Blank Row ws.Range("B" & Rows.Count).End(xlUp).Offset(1).Value = Me.Stuff.Value ' Add date and time stamp for the moment the comment was entered ws.Range("C" & Rows.Count).End(xlUp).Offset(1).Value = Date + Time ' Adds the Stuff info into Col D at the last Blank Row ws.Range("D" & Rows.Count).End(xlUp).Offset(1).Value = Me.Stuff.Value Unload Me End Sub A: Try replacing your code with the code below: Private Sub StuffUpload_Click() Dim ws As Worksheet Dim LastRow As Long Dim RngAnchor As Range ' Grabs the worksheet that the user is currently looking at, ' making this form work on all sheets Set ws = ActiveSheet ' Make sure all required fields have been entered If Stuff.Text = "" Then MsgBox "You must enter Stuff." Stuff.SetFocus Exit Sub End If ' Add a dash of formatting to the last row so the stuff we put into it will ' look nice With ws LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row ' get the last row in column "B" ' set the anchor point of the range in column "B" Set RngAnchor = .Range("B" & LastRow + 1) ' Adds the Stuff info into Col B at the Last Blank Row RngAnchor.Value = Me.Stuff.Value ' Add date and time stamp for the moment the comment was entered RngAnchor.Offset(, 1).Value = Now ' Adds the Stuff info into Col D at the last Blank Row RngAnchor.Offset(, 2).Value = Me.Stuff.Value '<-- already added this on Column "B" ' now format last row, cells "B:D" With RngAnchor.Resize(1, 3) .HorizontalAlignment = xlLeft .VerticalAlignment = xlBottom .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False .Rows.AutoFit End With End With Unload Me End Sub
{ "pile_set_name": "StackExchange" }
Q: How to count blank lines from file in C? So what I'm trying to do is to count blank lines, which means not only just containing '\n'but space and tab symbols as well. Any help is appreciated! :) char line[300]; int emptyline = 0; FILE *fp; fp = fopen("test.txt", "r"); if(fp == NULL) { perror("Error while opening the file. \n"); system("pause"); } else { while (fgets(line, sizeof line, fp)) { int i = 0; if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') { i++; } emptyline++; } printf("\n The number of empty lines is: %d\n", emptyline); } fclose(fp); A: Before getting into the line loop increment the emptyLine counter and if an non whitespace character is encountred decrement the emptyLine counter then break the loop. #include <stdio.h> #include <string.h> int getEmptyLines(const char *fileName) { char line[300]; int emptyLine = 0; FILE *fp = fopen("text.txt", "r"); if (fp == NULL) { printf("Error: Could not open specified file!\n"); return -1; } else { while(fgets(line, 300, fp)) { int i = 0; int len = strlen(line); emptyLine++; for (i = 0; i < len; i++) { if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') { emptyLine--; break; } } } return emptyLine; } } int main(void) { const char fileName[] = "text.txt"; int emptyLines = getEmptyLines(fileName); if (emptyLines >= 0) { printf("The number of empty lines is %d", emptyLines); } return 0; }
{ "pile_set_name": "StackExchange" }
Q: Creating Riak bucket over cURL I would like to be able to create a Riak bucket over cURL. I have been searching online and cant seem to find a way to do it. I know there are ways to do it easily with the drivers but need to be able to do it with cURL for the Saas application I am working on. A: You would do a PUT passing the bucket properties you want as a json object, e.g. curl -v http://riak3.local:8098/riak/newBucket -X PUT -H Content-Type:application/json --data-binary '{"props":{"n_val":5}}' The docs has more complete details. A: One other thing - the important thing to remember is that, there is no way to 'create' a bucket explicitly, with a call (via CURL or a client api). You can only create custom buckets via the call above. The reason for that is -- buckets are simply just a prefix to the keys. There is no object anywhere in the Riak system that keeps track of buckets. There is no file somewhere, no variable in memory, or anything like that. That is why the simple "list buckets" commands is so expensive: Riak literally has to go through every key in the cluster, and assemble a list of buckets by looking at the key prefixes. The only thing that exists as actual objects are buckets with non-default settings, ie, custom buckets. That's what that curl command above does -- it keeps track of some non-default settings for Riak to consult if a call ever comes in to that bucket. Anyways, the moral of the story is: you don't need to create buckets in the normal course of operations. You can just start writing to them, and they will come into being (again, in the sense of, keys with bucket prefixes will come into being, which means they can now be iterated over by the expensive 'list buckets' call). You only have to issue the call for custom buckets (and also, you don't want to do that too much, either, as there is a practical limit to the number of custom buckets created in a cluster, somewhere around 9000). A: I also found that if you add a new object to an non existing bucket it will create that bucket on the fly. Remember, buckets are automatically created when you add keys to them. There is no need to explicitly “create” a bucket (more on buckets and their properties further down the page.) Bucket Properties and Operations
{ "pile_set_name": "StackExchange" }
Q: can I cache page in nginx rewrite rules? nginx conf: location / { rewrite ^/cache.html$ /cache.jsp last; } location ~ \.jsp { proxy_pass http://127.0.0.1:85; #if I add proxy_cache here,will be cache every JSP file,I don't want it } #location ~ \.html { #I want cache all ".html" page,but it's not work. #proxy_cache cache; #.... #} I using a rewrite rule to mapping /cache.html to /cache.jsp I want to access http//localhost/cache.html to cache page, but access http//localhost/cache.jsp with out cache, how to do? thanks for help :) A: That is not possibly simply using rewrite rules. The only way you could make it work is by proxying back to the page and enabling proxy caching. You could write custom locations to have it only cache specific page extensions and you can use if statements to set one-off cache keys to make it appear like a page is uncached, even though it is actually cached for 1 view. If you're thinking of stepping in to the realms of real rule-based caching I'd recommend using Varnish instead.
{ "pile_set_name": "StackExchange" }
Q: Stirling's Formula for n! A group of $2N$ boys and $2N$ girls is divided into two equal groups. find the probability $p$ that each group will be equally divided into boys and girls. Estimate $p$ using Stirling's formula. The author's solution is $$p=\frac{\binom{2N}{N}^2}{\binom{4N}{2N}}.$$ The author's estimate using Stirling's formula is $(\frac{2}{(N\pi)})^{0.5}$. I don't understand how it is calculated? Stirling's formula is $n!\sim(2\pi)^{0.5}n^{n+0.5}e^{-n}$ where the sign $\sim$ is used to indicate the ratio of two sides tends to unity as $n\rightarrow \infty$. A: People have given hints, but sometimes it's good to see these things worked out explicitly. Write $p$ in terms of factorials: $$ p = \left( {(2n)! \over (n!)^2} \right)^2 \left( (4n)! \over (2n)!^2 \right)^{-1} = {(2n)!^4 \over (4n)! (n!)^4 }$$ Then replace each of those factorials with its Stirling approximation: $$ p \sim {\left(\sqrt{4\pi n} \left( {2n \over e} \right) ^{2n}\right)^4 \over\sqrt{8\pi n} \left( {4n \over e} \right)^{4n} \left(\sqrt{2\pi n} \left( {n \over e} \right) ^{n}\right)^4}. $$ Now a good general strategy for dealing with these quotients of Stirling approximations is to group all the constants together, all the factors of $\pi n$ to a constant power together, terms together, all the things like $(an)^{bn}$ together, and all the powers of $e$ together. This gives $$ p \sim {4^2 \over 8^{1/2} 2^2} {(\pi n)^2 \over (\pi n)^{1/2} (\pi n)^2} {(2n)^{8n} \over (4n)^{4n} n^{4n}} {e^{-8n} \over e^{-4n} e^{-4n}} $$ Then we can factor a bit more: $$ p \sim {4^2 \over 8^{1/2} 2^2} {(\pi n)^2 \over (\pi n)^{1/2} (\pi n)^2}{2^8 \over 4^4} \left( {n^8 \over n^4 n^4} \right)^n \left( {e^{-8} \over e^{-4} e^{-4}} \right)^n $$ And you can easily see that this is $$ p \sim 2^{1/2} \cdot (\pi n)^{-1/2} \cdot 1 \cdot 1^n \cdot 1^n $$ or, after dropping the trivial factors, $2/\sqrt{\pi n}$ like you're looking for.
{ "pile_set_name": "StackExchange" }
Q: How to catch the play.api.libs.openid.Errors$AUTH_CANCEL$ exception? Using Play Framework 2.1 with OpenID, if I cancel my authentication from the OpenID Provider, I get this exception : [RuntimeException: play.api.libs.openid.Errors$AUTH_CANCEL$] Here's my code : Promise<UserInfo> userInfoPromise = OpenID.verifiedId(); UserInfo userInfo = userInfoPromise.get(); // Exception thrown here But since it's a Runtime exception, I can't catch it with a try/catch so I'm stuck on how to avoid exception and returns something nicer than a server error to the client. How can I do that? A: A Promise is success biased, for all its operations, it assumes it actually contains a value and not an error. You get the exception because you try to call get on a promise which contains an untransformed error. What you want is to determine if the Promise is a success or an error, you can do that with pattern matching for instance. try this code: AsyncResult( OpenID.verifiedId.extend1( _ match { case Redeemed(info) => Ok(info.attributes.get("email").getOrElse("no email in valid response")) case Thrown(throwable) => { Logger.error("openid callback error",throwable) Unauthorized } } ) ) You may want to read more on future and promises, I recommend this excellent article : http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html edit : checking the documentation (http://www.playframework.com/documentation/2.1.0/JavaOpenID) in java it seems you are supposed to catch and handle exceptions yourself. In any case, you should catch exceptions and if one is thrown redirect back the user to the login page with relevant information. something like this should work : public class Application extends Controller { public static Result index() { return ok("welcome"); } public static Result auth() { Map<String, String> attributes = new HashMap<String, String>(); attributes.put("email", "http://schema.openid.net/contact/email"); final Promise<String> stringPromise = OpenID.redirectURL("https://www.google.com/accounts/o8/id", "http://localhost:9000/auth/callback",attributes); return redirect(stringPromise.get()); } public static Result callback() { try{ Promise<UserInfo> userInfoPromise = OpenID.verifiedId(); final UserInfo userInfo = userInfoPromise.get(); System.out.println("id:"+userInfo.id); System.out.println("email:"+userInfo.attributes.get("email")); return ok(userInfo.attributes.toString()); } catch (Throwable e) { System.out.println(e.getMessage()); e.printStackTrace(); return unauthorized(); } } }
{ "pile_set_name": "StackExchange" }
Q: Sitecore 8: Items Duplicated in Web Index After Publish In only our Staging/Production environment, items are being duplicated in our web index after a publish is performed. The only distinction between the duplicate items (via Luke) is that any indexed images are prefixed with "/sitecore/shell" If I perform a manual index rebuild from Indexing Manager, the results are as expected. The index uses a copy of the default IndexConfiguration with some slight modifications (edited), renamed to be newsIndexConfiguration and it is referenced properly on the index implementation <index id="$(News.Index.Name.Web)" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider"> <param desc="name">$(id)</param> <param desc="folder">$(id)</param> <!-- This initializes index property store. Id has to be set to the index id --> <param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" /> <configuration ref="contentSearch/indexConfigurations/newsIndexConfiguration" /> <strategies hint="list:AddStrategy"> <strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync" /> </strategies> <commitPolicyExecutor type="Sitecore.ContentSearch.CommitPolicyExecutor, Sitecore.ContentSearch"> <policies hint="list:AddCommitPolicy"> <policy type="Sitecore.ContentSearch.TimeIntervalCommitPolicy, Sitecore.ContentSearch" /> </policies> </commitPolicyExecutor> <locations hint="list:AddCrawler"> <crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch"> <Database>web</Database> <Root>/sitecore/content/Global/News/Articles</Root> </crawler> </locations> </index> It goes without saying that there is custom code all over this implementation at this point. However, this is a new feature that started with the default configuration. I cannot figure out what might be causing the duplicates to be added on publish. It was erring without the <indexAllFields> element set to true, which I can live with, but certainly isn't ideal. I should note, when I perform a Republish (including all children) at the newsroom root, it adds these multiple values, not just 1 additional duplicate, but 5 or even more sometimes, it feels quite arbitrary. In the past, in this instance, I've gotten around this by filtering out results that contain "/sitecore/shell" in the image field, but this is merely a Band-Aid. Any help to solve this would be greatly appreciated. A: This looks like a bug with the OnPublishEndAsync strategy. It becomes apparent when authors start creating new versions of content each time they lock and edit an item. It has been fixed in 8.1 but still resides in the version you are using. See this knowledge base article https://kb.sitecore.net/articles/992608 A: The issue was that in my efforts to trim the index of waste, i.e. remove fields that I'm not accessing, I removed a certain special field (though it is not marked in any way as being important, though by name it makes sense in hindsight). I removed the "_uniqueid" field from the index configuration. Specifically here: <fieldMap> ... <field fieldName="_uniqueid" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"> <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" /> </field> ... I had created a new IndexConfiguration.config file unique to my index. I tested and I was able to remove all other fields from the index. Toggling this field on or off reproduced the issue. EDIT: With the _uniqueid field omitted from the index configuration, the field will still appear in the index (via Luke or other means). Including it in the index configuration will solve this problem. A: It may depend on what version of Sitecore you are running, from this SO post (https://stackoverflow.com/questions/27272832/urllink-in-sitecore-indexs-returns-media-url-with-sitecore-shell-media) it looks like there may be a known bug. Accepted answer from link above: Just to give an update for this. Confirmed by Sitecore it's a bug. They are finding a workaround, I'll update here when they do. Thanks. -------------updated on 15/12/2014---------------------- Ticket's closed now. Sitecore's solution is to remove this "urlLink" field from the index in the future(They said they will request this). Reason being that url should be generated by LinkManager based on current site context. However site context doesn't exist while indexing(For content item you can check the path, but for media item you cannot). Of course there's another solution is to create your own computeredField to override the logic for media item. However I agree with Sitecore, it feels more right to remove this field from the index. On top of all that, the initial reason for using the urlLink field was to drop the need for querying Sitecore completely while doing a Search. All the content are coming from Index's stored fields value. But on the other hand, pagination is normally being used for search results, so even there're requests to Sitecore, it shouldn't be a lot. That'd be all for now, happy to see more opinions and to discuss, thanks!
{ "pile_set_name": "StackExchange" }
Q: How to have Query Pull Weekly Data I have a a query like so that ONLY shows data for the specific day. But how can I modify this to show data for the previous 7 days? So when I run the query this week show data for the date range of 01/24/2014 - 01/30/2014 then next week shows data for 01/31/2014 - 02/06/2014 SELECT * FROM SalesInformation WHERE (datename(dw, getdate()) = 'Monday' AND CONVERT(VARCHAR(10), DateSold, 101) = DATEADD (Day,DATEDIFF(Day,0,GetDate()),0)) OR (datename(dw, getdate()) = 'Tuesday' AND CONVERT(VARCHAR(10), DateSold, 101) = DATEADD(Day,DATEDIFF(Day,0,GetDate()),0)) OR (datename(dw, getdate()) = 'Wednesday' AND CONVERT(VARCHAR(10), DateSold, 101) = DATEADD(Day,DATEDIFF(Day,0,GetDate()),0)) OR (datename(dw, getdate()) = 'Thursday' AND CONVERT(VARCHAR(10), DateSold, 101) = DATEADD(Day,DATEDIFF(Day,0,GetDate()),0)) OR (datename(dw, getdate()) = 'Friday' AND CONVERT(VARCHAR(10), DateSold, 101) = DATEADD(Day,DATEDIFF(Day,0,GetDate()),0)) A: This will be seven days including time. So 01/23/2014 10:06 AM to 1/30/2014 10:06 AM. If you want the whole day of 01/23, cast to a DATE. Here is a complete working example for 2012. I changed to getdate() just in case you are using a older version of the engine. -- Just playing use tempdb; go -- drop existing if object_id ('sales') > 0 drop table sales go -- create new create table sales ( id int identity (1,1) primary key, sold smalldatetime, amt smallmoney ); go -- clear data truncate table sales; go -- insert data declare @dte date = '20131231'; declare @amt int; while (@dte < '20140201') begin set @amt = floor(rand(checksum(newid())) * 50000); set @dte = dateadd(d, 1, @dte); insert into sales values (@dte, @amt); end go -- Show 7 * 24 hrs worth of data select * from sales where sold >= dateadd(d, -7, getdate()) and sold < getdate() go Check out Aarons Blog on dates. It goes over the good, bad, and ugly practices. For instance, do not use BETWEEN. Bad habits to kick : mis-handling date / range queries
{ "pile_set_name": "StackExchange" }
Q: Yet another Java generics question Can someone explain why the following doesn't work? It complains that: The method add(C) in the type List is not applicable for the arguments (Generics.Person) import java.util.ArrayList; import java.util.List; public class Generics<C extends Comparable<C>> { static class Person implements Comparable<Person> { public final String name, city; public Person(String name, String city) { this.name = name; this.city = city; } @Override public int compareTo(Person that) { return 0; } } public Generics() { List<C> persons = new ArrayList<C>(); persons.add(new Person(null, null)); } // however, this one works, but it gives a warning // about Comparable being a raw type public Generics() { List<Comparable> persons = new ArrayList<Comparable>(); persons.add(new Person(null, null)); } } So, basically, what I want is a generic List of Comparables, to which I can add any type that implements Comparable. A: To be allowed to do what you need to do you should specify the type parameter of the Generics class from outside: Generics<Person> generic = new Generics<Person>(); Otherwise you are just adding a Person to a list which has an unbound type variable, this is not allowed. While using the Generics class with a free type variable you must not make any assumption on the type of C. To see a clear example think about having a second class Place extends Comparable<Place>. According to what you are trying to do you should be allowed to do the following: public Generics() { List<C> persons = new ArrayList<C>(); persons.add(new Person(null, null)); persons.add(new Place()); } since also Place is a valid candidate. Then which would be the type of type variable C? Mind that there is no unification process that tries to guess the right type of C according to what you are adding to the list, and finally you should see C not as a "whatever type as long as it fulfills the constraints" but as a "specified type that fulfills the constraints",
{ "pile_set_name": "StackExchange" }
Q: Select multiple tables in related database in vb Need help with to select 3 related databasetables in one query. The result is supposed to be copied to my viewmodel. Byt i cant find how to write the query. I have like this: Dim l = db.myEntity.Where(Function(m) m.regnr.Contains(regnr) And m.ExtLok = True).Select(Function(m) m.Customer).tolist() This query only select the one-to-on-related table "Customer", so my question is, how do i select more tables? Ive tried this Dim l = db.myEntity.Where(Function(m) m.regnr.Contains(regnr) And m.ExtLok = True).Select(Function(m) m.Customer, m.Cars).tolist() A: Dim item As myEntity = (from e in db.MyEntities.Include("MoreEntities").Include("OtherEntity") where m.field.contains("criteria") select e) The key here is calling the Include method on the collection in the In clause. Take a look at MSDN or Intelisense - Include() has several overloads.
{ "pile_set_name": "StackExchange" }
Q: Ubuntu vm shows Floppy disk I set up a qemu virtual machine on my Ubuntu 15.04. I installed Ubuntu 15.04 in it and the virtualized Ubuntu shows a Floppy Disk. What does it mean and how do I remove it? A: I've never used QEMU, but from what I'm seeing on their documentation, it looks like it will create floppy support by default for an x86 architecture machine, even if you don't have a floppy drive in your physical machine. VMWare and VirtualBox do the same thing. It shouldn't affect performance of the VM unless you're really worried about the VENOM vulnerability. As far as disabling it goes, it looks like the easiest way to disable the floppy drive is to use -nodefaults when opening QEMU. Otherwise, you should be able to patch the VM to avoid the VENOM vulnerability, but I don't think it will disable the floppy. Here's a link with more information on the vulnerability.
{ "pile_set_name": "StackExchange" }
Q: PDF generation in XCode I am a newbie in iPhone development. I am planning to do a PDF application for iPhone. The functionality is: User will type their input in a text field (which is going to be the content of the PDF file). I have to modify the PDF file through code while saving (paragraphs, tables, bullets etc). User can save it in their own name. User can send the PDF file as attachment of MFMailComposer. So I have searched and got many links. However I didn't find any leading details to create and modify a PDF file in iPhone/iPad. Can anyone please provide me a good reference to do this. Are there any alternatives to do this? A: I've used this reference: https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html It contains theoretical explanations and source code examples
{ "pile_set_name": "StackExchange" }
Q: Tree List View In Android I am trying to do a tree list in android using this project library. First: I cannot import it in Eclipse. I am getting the following error: [2014-01-15 14:58:18 - tree-view-list-android] Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties. even if I try go to the project properties I am getting the same error and I cannot open it. Second: I found different version on the project HERE but there is no documentation at all. I was wondering if there is another approach to complete the task. I checked that I can accomplish it using so called ExpandableListView but they can handle only up to two levels and I want more. Any suggestions??? Thank you in advance!!! A: I've implemented it with Custom ListView, here's a link where I've posted example of my implementation: Link: https://stackoverflow.com/a/20518117/2219052 Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Rendering a local HTML file with a local image in WebView I am trying to render a local html file with a local image in a WebView where the WebView is in a Dialog Box and not an Activity. The image is not being rendered, but the remainder of the info is displayed just fine. There are countless solutions to this problem suggested in Stack Overflow, many with green check marks. None that I have tried have worked. What I am doing is placing the html file and the image in res/raw The html file has a line referencing the image; I have tried different options all which have been stated somewhere in stack overflow as working, for example: <img src="file:///android_res/raw/main_screen_crop.png" alt="Main Screen" width="525" height="290"> and <img src="main_screen_crop.png" alt="Main Screen" width="525" height="290"> The text part of the html renders fine, but for the image I get just the 'alt' text inside an empty box with a thumbnail picture icon. So the questions I have are: Is accessing an image when the html of a WebView is rendered inside a Dialog Box different than an Activity making the suggested solutions invalid? Some answers said "place the image in the assets directory and use the file:///..." to reference the image AND they indicated that this was required which contradicts other solutions. Is the use of the assets directory required? Android has a 2018 tutorial https://www.youtube.com/watch?v=HGZYtDZhOEQ stating that many of the StackOverflow answers on how to handle WebView are just plain wrong but admit it is partly their fault due to out of date documentation ... Here is my render code which works just fine for everything else! LayoutInflater inflater = ((Activity)context).getLayoutInflater(); @SuppressLint("InflateParams") // Okay on dialog final View helpContent = inflater.inflate(R.layout.help_screen, null); // Get the Alert Dialog Builder android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context); TextView customTitle = new TextView(context); // Customise Title here customTitle.setText(title); customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground)); customTitle.setPadding(10, 10, 10, 10); customTitle.setGravity(Gravity.CENTER); customTitle.setTextColor(Color.WHITE); customTitle.setTextSize(20); builder.setCustomTitle(customTitle) WebView help = helpContent.findViewById(R.id.helpView); help.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); String helpText = readRawTextFile(htmlpage); // reads the html file help.getSettings().setAllowFileAccess(true); // This did not help ... help.loadData(helpText, "text/html; charset=utf-8", "utf-8"); builder.setView(helpContent); // put view in Dialog box Any help, clarification, etc. as to what is correct will be greatly appreciated! Should add that the html file, when clicked on in Windows, renders fine in a browser. A: Following CommonWare's suggestion, I will answer this question and state what worked for me. I was also able to scale the image independently of the text. I was unable to get the image to render when my image and html file were in the res/raw directory. I tried many combinations and failed. I will not state that it is impossible. What DID work was creating an assets directory at the same level as the src directory and placing BOTH my image file and html file in that directory. As CommonWare pointed out, the URL for the files is "file://android_asset/main_screen_crop.png" even though the directory name is 'assets'. The code simplifies to LayoutInflater inflater = ((Activity)context).getLayoutInflater(); @SuppressLint("InflateParams") // Okay on dialog final View helpContent = inflater.inflate(R.layout.help_screen, null); // Get the Alert Dialog Builder android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context); TextView customTitle = new TextView(context); // Customise Title here customTitle.setText(title); customTitle.setBackgroundColor(context.getResources().getColor(R.color.colorToolbarBackground)); customTitle.setPadding(10, 10, 10, 10); customTitle.setGravity(Gravity.CENTER); customTitle.setTextColor(Color.WHITE); customTitle.setTextSize(20); builder.setCustomTitle(customTitle); WebView help = helpContent.findViewById(R.id.helpView); help.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); help.getSettings().setAllowFileAccess(true); help.loadUrl(htmlpage); builder.setView(helpContent); where 'htmlpage' is, for example, "file:///android_asset/layout_help.html" The html file itself (with independent scaling of text and image) becomes: <html> <head> <style> .gfg { width:auto; text-align:center; padding:2px; } img { max-width:100%; height:auto; } </style> </head> <body> <h3>Running the Application</h3> After pressing start you will see a screen as follows: <div class="gfg"> <p id="my-image"> <img src="file:///android_asset/main_screen_crop.png" alt="Main Screen"/> </p> </div> </html> Hope this saves someone the 7 hrs it took me to get it to work.
{ "pile_set_name": "StackExchange" }