source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0054658684.txt" ]
Q: Why is wrong bit representation got by converting byte array to BitSet in Java I tried to convert a byte array in order to use its bit representation. Input: byte[] values = new byte[]{21, 117, 41, -1}; I would like to create one BitSet object from the byte array but I splitted up it to investigate the issue and tried to create multiple BitSet objects from each element of the array. BitSet objects are created on the following way: BitSet bitSetTwentyOne = BitSet.valueOf(new byte[]{21}); BitSet bitSetOneHundredSevenTeen = BitSet.valueOf(new byte[{117}); BitSet bitSetFourtyOne = BitSet.valueOf(new byte[]{41}); BitSet bitSetMinusOne = BitSet.valueOf(new byte[]{-1}); The bits are printed out by using the following method: private String getBits(BitSet bitSet) { StringBuilder bitsBuilder = new StringBuilder(); for (int i = 0; i < bitSet.length(); i++) { bitsBuilder.append(bitSet.get(i) == true ? 1 : 0); } return bitsBuilder.toString(); } Output: bitSetTwentyOne: 10101 but expected -> 00010101 (BitSet::length = 5) bitSetOneHundredSevenTeen: 1010111 but expected -> 01110101 (BitSet::length = 7) bitSetFourtyOne: 100101 but expected -> 00101001 (BitSet::length = 6) bitSetMinusOne: 11111111 but it is as expected at least (BitSet::length = 8) I want all values 8bit width even if it is needed to fill with zeros. I do not understand why it gives wrong binary values in case of converting 117 and 41. A: length() delivers the logical length using the highest bit 1. size() would give 8. cardinality() would give the number of bit 1s. So you should have used size(). And then the bits are in little endian format, and you reversed it by outputting bit at 0 first. private String getBits(BitSet bitSet) { StringBuilder bitsBuilder = new StringBuilder(); for (int i = 0; i < bitSet.size(); ++i) { bitsBuilder.insert(0, bitSet.get(i) ? '1' : '0'); } return bitsBuilder.toString(); } A: It appears that you are printing the bits backwards. Notice how your output (except for the desired leading zeros) is a mirror image of your expected input. Using your code, passing in 4, which should be 100, I get 001. It appears that bit 0 is the least significant bit, not the most significant bit. To correct this, loop over the indices backwards. The reason that -1 and 41 are correct apart from the leading zeros is that their bitset representations are palindromes. To prepend leading zeros, subtract the length() from 8 and print that many zeros. The length() method only returns the number of bits necessary to represent the number. You need to code this yourself; there is no BitSet functionality for leading zeros.
[ "graphicdesign.stackexchange", "0000084374.txt" ]
Q: How do I export multiple SVGs from Illustrator? How do I export SVG images from multiple artboards in a batch process using Adobe Illustrator CC A: If you're using CS6 (not sure about earlier versions) then you need to save as SVG, there is no SVG export option. File → Save As → SVG (svg) In CC there is a new export option for SVG. File → Export → SVG (svg) In both cases, make sure to check "Use Artboards" to export the contents of your artboards as individual SVG files. https://helpx.adobe.com/uk/illustrator/how-to/export-svg.html A: Use: File > Export > Export for screens. Set the format to SVG. This pretty powerful and allows you to select each artboard (rather than asset) you want to export. You can also export multiple formats in one go (great for backup PNGs for example).
[ "stackoverflow", "0048511048.txt" ]
Q: Use MinMaxScaler on training data to generate std, min and max to be used on testing data How would I use the scikit-learn MinMaxScaler to standardize every column in a pandas data-frame training data set, but use the exact same standard deviation, min/max formula on my test data set? Since my testing data is unknown to the model, I dont want to standardize the whole data set, it would not be an accurate model for future unknown data. Instead I would like to standardize the data between 0 & 1 using the training set, and use the same std, min and max numbers for the formula on the test data. (Obviously I can write my own min-max scaler, but wondering if scikit-learn can do this already or if there is a library I can use for this first) A: You should be able to fit it on your training data and then transform your test data: scaler = MinMaxScaler() scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) # or: fit_transform(X_train) X_test_scaled = scaler.transform(X_test) Your approach now seems like good practice. If you were to call fit on your entire X matrix (train and test combined), you'd be causing information leakage as your training data would have "seen" the scale of your test data beforehand. Using a class-based implementation of MinMaxScaler() is how sklearn addresses this specifically, allowing the object to "remember" attributes of the data on which it was fit. However, be aware that MinMaxScaler() does not scale to ~N(0, 1). In fact, it is explicitly billed as an alternative to this scaling. In other words, it does not guarantee you unit variance or 0 mean at all. In fact, it really doesn't care about standard deviation as it's defined in the traditional sense. From the docstring: The transformation is given by: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max_ - min_) + min_ Where min_ and max_ are equal to your unpacked feature_range (default (0, 1)) from the __init__ of MinMaxScaler(). Manually this is: def scale(a): # implicit feature_range=(0,1) return (a - X_train.min(axis=0)) / (X_train.max(axis=0) - X_train.min(axis=0)) So say you had: import numpy as np from sklearn.model_selection import train_test_split np.random.seed(444) X = np.random.normal(loc=5, scale=2, size=(200, 3)) y = np.random.normal(loc=-5, scale=3, size=X.shape[0]) X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=444) If you were to call scaler = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train) Know that scaler.scale_ is not standard deviation of the data on which you did the fitting. scaler.scale_ # array([ 0.0843, 0.0852, 0.0876]) X_train.std(axis=0) # array([ 2.042 , 2.0767, 2.1285]) Instead, it is: (1 - 0) / (X_train.max(axis=0) - X_train.min(axis=0)) # array([ 0.0843, 0.0852, 0.0876])
[ "math.stackexchange", "0000738658.txt" ]
Q: existence of sequence of polynomial Is there a sequence of polynomials $P_n$ such that $\displaystyle\lim_{n \to \infty} P_n(z) = \begin{cases} 1, & \text{Im } z > 0\\ 0, & z \text{ is real,} \\ -1, & \text{Im } z < 0 \end{cases}$ I have no clue where to start from. Please provide some hints. Thanks in advance. A: What we need of Runge's theorem is that if $K \subset\mathbb{C}$ is compact such that $\mathbb{C}\setminus K$ is connected, and $f$ holomorphic on $K$ (that means that there is an open neighbourhood $U$ of $K$ and $f\colon U\to\mathbb{C}$ is holomorphic), then there is a sequence of polynomials converging uniformly on $K$ to $f$. Here, a single compact $K$ is not sufficient, we need a sequence $K_n$ of compact sets exhausting the plane. Letting $A_n = \left\{ z \in\mathbb{C} : \lvert z\rvert \leqslant n \land \operatorname{Im} z \geqslant \frac{1}{n} \right\}$, $B_n = \left\{ z \in\mathbb{C} : \lvert z\rvert \leqslant n \land \operatorname{Im} z \leqslant -\frac{1}{n} \right\}$ and $C_n = \left\{ z\in\mathbb{C} : \lvert \operatorname{Re} z\rvert \leqslant n \land \operatorname{Im} z = 0\right\}$, we obtain an increasing sequence of compact sets $K_n = A_n\cup B_n \cup C_n$ with $\bigcup K_n = \mathbb{C}$. For all $n \geqslant 1$, the complement of $K_n$ is connected, so by Runge's theorem, there is a polynomial $P_n$ with $\lvert P_n(z)-1\rvert < \frac{1}{n}$ on $A_n$, $\lvert P_n(z)+1\rvert <\frac{1}{n}$ on $B_n$ and $\lvert P_n(z)\rvert < \frac{1}{n}$ on $C_n$.
[ "stackoverflow", "0007427174.txt" ]
Q: Pointer to a member function in an inaccessible base The compilation of the next example : class A { public: void foo() { } }; class B : private A { public: using A::foo; }; int main() { typedef void (B::*mf)(); mf func = &B::foo; B b; (b.*func)(); } fails with next errors : main.cpp||In function ‘int main()’: main.cpp|18|error: ‘A’ is an inaccessible base of ‘B’ main.cpp|18|error: in pointer to member function conversion I understand that the A is not accessible base of B, but I am using the using keyword. Shouldn't it allow the access to the function foo? What are relevant paragraphs in the standard that prevents the above to be compiled? A: Since foo in B is inherited from A, &B::foo is identical to &A::foo, and has type void (A::*)(). When you write typedef void (B::*mf)(); mf func = &B::foo; you are trying to convert from void (A::*)() to void (B::*)(). Since B inherits privately fromA you cannot do that. A: Access to members of A is governed by chapter 11 "Member Access Control", but pointer-to-member conversions are covered by 4.11. In particular, 4.11/2 states that you can't convert a T A::* to an T B::* when you can't convert an B* to a A*. Here's a slight variation of the question: class A { public: void foo() { } }; class B : private A { public: using A::foo; }; int main() { typedef void (A::*amf)(); typedef void (B::*bmf)(); amf func = &A::foo; bmf f2 = static_cast<bmf>(func); } We're still talking about the same function. It's not the name lookup of B::foo that fails (using takes care of that), it's the fact that the type of B::foo is void A::*() which cannot be converted to void B::*().
[ "stackoverflow", "0042116242.txt" ]
Q: Fully optional one to one relation in MySQL workbench Fully optional one to one relation in MySQL workbench? I'm only able to create a partially optional one to one relation. My case is: A GROUP can be assigned a PROBLEM A PROBLEM can be assigned to a GROUP EDIT1: EDIT2: Maybe a better question would be if fully optional one to one relations should be avoided? A: Let's see if any of this addresses your issue. A GROUP can be assigned a PROBLEM A PROBLEM can be assigned to a GROUP Starting with a structure such as: PROBLEM id | title 1 | Prob1 2 | Prob2 GROUP id | title 1 | Group1 2 | Group2 What is also important is to know whether a GROUP can be assigned more than one problem at a time or not. And whether one same problem can be assigned to more than one GROUP. Let's say there is a strict optional 1:1 relationship. This means a group cannot have 2 problems assigned at the same time and that 1 same problem cannot be assigned to 2 groups. A strict 1:1 would be implemented by adding the PK of table A as a FK of table B. If the FK is nullable then you will notice this is already an optional 1:1, as you may leave empty cells indicating 0 problems assigned (or 0 groups assigned). PROBLEM id | title 1 | Prob1 2 | Prob2 GROUP id | title | problem 1 | Group1 | 2 2 | Group2 | null In this example Group2 has been assigned no problem. Group1 has been assigned Prob2 and Prob1 has been assigned to no group. You are not forced to assign anything but everything may have a 1:1 relationship. This structure may imply quite a few empty (null) values. This is not best practices but would do the job. If you want to avoid null values then you may have to go for a N:M implementation. PROBLEM id | title 1 | Prob1 2 | Prob2 GROUP id | title 1 | Group1 2 | Group2 GROUP_PROBLEM group | problem 1 | 2 With this implementation alone you may have 1 group be assigned more than 1 problem and have 1 same problem be assigned to more than 1 group. But if you define a UNIQUE index for each of the two fields (group and problem) then you should fix this.
[ "stackoverflow", "0019827253.txt" ]
Q: jQuery Event Callback Speed: Anonymous vs. Named Functions This is kind of a random question, but I was wondering why a named callback was performing worse, for a click event, relative to an anonymous function. Here is the link to the JSPerf tests I ran in Firefox and Chrome on Mac. I guess my assumption was that named callbacks would always perform better. For instance, when using .each the named callback is slightly faster. Thanks for your time! Edit I edited the .each JSPerf test because (a) I wasn't testing what I meant and (b) I'm trying to mimic events more so. Edit 2 My test setup was incorrect from the start as @Esailija points out below. This question is somewhat pointless but at least it might help someone with JSPerf testing. A: The jsperf is broken because you accumulate event handlers across test boundaries. In other wrods, whatever test is run first will be the "fastest". And the whole premise of the test is ridiculous, there is no difference between a function that has a name and a function that doesn't have a name if everything else is equal. You will only see a difference when you are setting up jsperf incorrectly. When you constantly get equal results for them then you know that you set it up correctly - but you would know this already from common sense :)
[ "stackoverflow", "0045702133.txt" ]
Q: Use of ctx.read() vs. ctx.channel.read() in Netty Examples Netty's pipelining (i.e. ctx.foo() vs ctx.channel.foo()) has been explained twice before on StackOverflow: Any difference between ctx.write() and ctx.channel().write() in netty? In Netty 4, what's the difference between ctx.close and ctx.channel.close? However, I don't understand the intuition behind Netty's examples of when to use the different approaches: public void channelActive(ChannelHandlerContext ctx) { ctx.read(); // <----- HERE } public void channelRead(final ChannelHandlerContext ctx, Object msg) { inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { ctx.channel().read(); // <----- HERE } else { future.channel().close(); } } }); } View source on GitHub Why use the 'from this handler down' style read in the channelActive handler of the proxy impl, but use the 'from the top' style read in channelRead? A: When using ChannelHandlerContext.read() it will start from the point in the ChannelPipeline where the ChannelHandleris located. When you use Channel.read() it will start from the tail of the ChannelPipeline and so need to traverse the whole ChannelPipeline in worse cast. The reason why this example use ctx.read() in channelActive(...) but channel.read() in the ChannelFutureListener is because the ChannelFutureListener is not part of a ChannelHandler and so it needs to start at the tail of the ChannelPipeline. Also note the the Channels are different here.
[ "askubuntu", "0000844913.txt" ]
Q: How to control IP ranges of Network Manager's hotspots? A server has two WiFi interfaces, both configured via Network Manager to be hotspots. Connected clients get IPs in ranges 10.42.0.0/24 and 10.42.1.0/24 (AFAICS via dnsmasq invoked by NM). I need to be able to assign a specific range to a specific interface. Unfortunately, Network Manager assigns them unpredictably (so wlan0 may get 10.42.0.0 today and 10.42.1.0 tomorrow; then wlan1 gets the remaining range) which messes up my iptables because the routing rules are different for these interfaces. I tried dhcp-range= option in /etc/dnsmasq.conf (which wasn't present as NM configures dnsmasq via command line) and some other ideas but can't find a workable solution. Any thoughts on how I can control which IP range gets assigned to which interface? A: After hours of trying different solutions, I was finally able to specify a subnet for a Hotspot connection using Network Manager and then set a manual ip on the client device for a sort of static ip. None of the dnsmasq/dhcp methods work with Network Manager. You have to edit the Network Manager connection file. These files are generated for each connection in the following directory: /etc/NetworkManager/system-connections I believe that when you create a Hotspot, a new connection file is created and is named Hotspot. You need to edit this file. Make sure you are editing the Hotspot connection file or this will not work! Change/add the following lines under the section [ipv4] to set a subnet. Make sure it has the line method=shared and use whatever ip address you want for address1= and NetworkManager will issue all connecting devices an ip in the same subnet. The format for this line is address1=ip/subnetmask,gateway. Gateway should be the same as the ip. Here is what the [ipv4] section should look like: [ipv4] dns-search= method=shared address1=192.168.125.1/24,192.168.125.1 Once you have this completed, save the file and run the following to restart Network Manager: sudo service network-manager restart Now your connected devices should be issued an ip address under the same subnet as the ip you entered. In this example it would be 192.168.125.x. To get a static ip, do that on the client side device. Set a manual ip for this hotspot connection under same subnet, using the same subnet mask and gateway that were entered in the Hotspot connection file. Here is my whole Hotspot connection file for reference: [connection] id=Hotspot uuid=14032jb9-43c6-41c6-8d56-8b6b0f7xcce9 type=wifi interface-name=wlan0 permissions= secondaries= timestamp=1486816539 [wifi] mac-address=7C:84:DB:62:7B:3F mac-address-blacklist= mac-address-randomization=0 mode=ap seen-bssids=7C:84:DB:62:7B:3F; ssid=yournetworkname [wifi-security] group= key-mgmt=wpa-psk pairwise= proto= psk=yourpassword [ipv4] dns-search= method=shared address1=192.168.125.1/24,192.168.125.1 [ipv6] addr-gen-mode=stable-privacy dns-search= ip6-privacy=0 method=ignore Documentation on this setting in Network Manager can be read here: https://people.freedesktop.org/~lkundrak/nm-docs/nm-settings.html Table 36. ipv4 setting Key Name: method Value Type: string Default Value: Value Description: IP configuration method. NMSettingIP4Config and NMSettingIP6Config both support "auto", "manual", and "link-local". See the subclass-specific documentation for other values. In general, for the "auto" method, properties such as "dns" and "routes" specify information that is added on to the information returned from automatic configuration. The "ignore-auto-routes" and "ignore-auto-dns" properties modify this behavior. For methods that imply no upstream network, such as "shared" or "link-local", these properties must be empty. For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. Most important part: For IPv4 method "shared", the IP subnet can be configured by adding one manual IPv4 address or otherwise 10.42.x.0/24 is chosen. A: You can determine the used IPv4 subnet by configuring one manual address, like nmcli connection modify $SHARED_NAME ipv4.addresses 192.168.2.5/24 It's documented in man nm-settings, see ipv4.method. /etc/NetworkManager/dnsmasq.d is for using dnsmasq as DNS plugin, not for your use case of connection sharing. For that, it is instead /etc/NetworkManager/dnsmasq-shared.d -- at least in recent versions of NM. But you shouldn't need that.
[ "stackoverflow", "0053855219.txt" ]
Q: MySQL not updating information_schema, unless I manually run ANALYZE TABLE `myTable` I have the need to get last id (primary key) of a table (InnoDB), and to do so I perform the following query: SELECT (SELECT `AUTO_INCREMENT` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = 'mySchema' AND `TABLE_NAME` = 'myTable') - 1; which returns the wrong AUTO_INCREMENT. The problem is the TABLES table of information_schema is not updated with the current value, unless I run the following query: ANALYZE TABLE `myTable`; Why doesn't MySQL update information_schema automatically, and how could I fix this behavior? Running MySQL Server 8.0.13 X64. A: Q: Why doesn't MySQL update information_schema automatically, and how could I fix this behavior? A: InnoDB holds the auto_increment value in memory, and doesn't persist that to disk. Behavior of metadata queries (e.g. SHOW TABLE STATUS) is influenced by setting of innodb_stats_on_metadata and innodb_stats_persistent variables. https://dev.mysql.com/doc/refman/8.0/en/innodb-parameters.html#sysvar_innodb_stats_on_metadata Forcing an ANALYZE everytime we query metadata can be a drain on performance. Other than the settings of those variables, or forcing statistics to be collected by manually executing the ANALYZE TABLE, I don't think there's a "fix" for the issue. (I think that mostly because I don't think it's a problem that needs to be fixed.) To get the highest value of an auto_increment column in a table, the normative pattern is: SELECT MAX(`ai_col`) FROM `myschema`.`mytable` What puzzles me is why we need to retrieve this particular piece of information. What are we going to use it for? Certainly, we aren't going to use that in application code to determine a value that was assigned to a row we just inserted. There's no guarantee that the highest value isn't from a row that was inserted by some other session. And we have LAST_INSERT_ID() mechanism to retrieve the value of a row our session just inserted. If we go with the ANALYZE TABLE to refresh statistics, there's still a small some time between that and a subsequent SELECT... another session could slip in another INSERT so that the value we get from the gather stats could be "out of date" by the time we retrieve it.
[ "math.stackexchange", "0002844170.txt" ]
Q: Function to create a "stepped," diagonal line First off, sorry if this is a basic question or one that has been asked before. I really don't know how to phrase it, so it's a hard question to google. I'm looking for a function that will generate a line similar to the one below __/ __/ __/ / I'm pretty good at math, but for some reason this seems to be stumping me as it seems like it should be really simple. In case it helps, I am planning on using it to drive an animation, so that it moves, pauses, moves, pauses, etc. using the current time (zero through infinity) as the input. I am using an "Absolute," system (IE: if I were to jump to frame 35, the math needs to be able to calculate frame 35 without knowing the frames before it), so I can't do anything like if (floor(sin(time)) + 1 > 0) { add 1 } A: Here is one example: $$ f(x)=\left\vert \frac{x-1}{2}-\left\lfloor\frac{x}{2}\right\rfloor\right\vert+\frac{x-1}{2}$$
[ "stackoverflow", "0005649772.txt" ]
Q: Hibernate mapping problem one-to-one/many-to-one I'm facing a problem using Hibernate. I have 3 tables: tb_user, tb_book, tb_lending. In the tb_lending, I have the following fields: id_lending - int(11) - primary key id_user - int(11) - foreign key id_book - int(11) - foreign key I have also the Beans representing the tables (tb_user and tb_book are working perfectly). My tbLending.hbm.xml mapping this field: <id name="id" type="java.lang.Integer"> <column name="id_lending" /> <generator class="identity" /> </id> <many-to-one name="userId" class="com.wa2011.beans.UserBean" not-null="true" cascade="all" unique="true" column="id_user" /> <many-to-one name="bookId" class="com.wa2011.beans.BookBean" not-null="true" cascade="all" unique="true" column="id_book" /> From the business logic the association should be one-to-one, since for each id_lending I can have 1 user and 1 book. But I read on some forums to that in this way, using many-to-one and then declaring unique="true". But then, when I execute a query.save I get the following error: GRAVE: IllegalArgumentException in class: com.wa2011.beans.UserBean, getter method of property: id I really don't know what the problem is since tb_book and tb_user as I said before work like a charm. The save method in the LendingBean.java is: public void saveLend(LendingBean lendingBean) { Session session = iniHibernate(); try { session.beginTransaction(); session.save(lendingBean); session.getTransaction().commit(); } catch (Exception e) { System.out.println("Error on registering lend:"); System.out.println(e); } } This method is called by the servlet LendingActions inside the processRequest method, the same pattern I'm following with the other beans/servlets. <class name="com.wa2011.beans.LendingBean" table="tb_lending" catalog="wa2011"> <id name="id" type="java.lang.Integer"> <column name="id_lending" /> <generator class="identity" /> </id> ... </class> In the LeandingBean.java I have: @Stateless public class LendingBean { private Integer id; private Integer bookId; private Integer userId; ... } Could you help me, please? Thanks in advance. A: Check LendingBean bean's id element to mapping. Is it same as in mapping? I think your LendingBean should be like this: @Stateless public class LendingBean { private Integer id; private BookBean bookId; private UserBean userId; ... }
[ "stackoverflow", "0009071131.txt" ]
Q: Recommended ODBC-JDBC bridge driver for Oracle Sun's JDBC-ODBC bridge driver was meant as a short term solution when JDBC drivers weren't widely available, not recommended for production, etc etc. Yet due to a conjunction of many stupid decisions made on the part of many others, we're forced to use this to connect to Oracle rather than JDBC. Are there any ODBC-JDBC bridge drivers out there, better than Sun's implementation...which are also free? A: There are some options: Easysoft JDBC-ODBC Bridge Driver Openlinksw Single-Tier JDBC to ODBC Bridge
[ "stackoverflow", "0009772125.txt" ]
Q: sort() function in IE So this code doesnt seem to work with IE, I have not found anything that says it shouldn't. What am I doing wrong? ​<ul id="cars"> <li id="2">Ford</li> <li id="1">Volvo</li> <li id="3">Fiat</li> </ul> var list = $('#cars').children('li'); list.sort(function(a,b){ return parseInt(a.id) < parseInt(b.id); }); $('#cars').append(list); ​ A: The sort function you pass in should return either a number less than zero (a comes before b), 0 (a and b are equivalent) or greater than 0 (a comes after b). If you just do this, it should work: return parseInt(a.id) - parseInt(b.id); also can't hurt to pass in the radix argument to parseInt, it's a bit safer: return parseInt(a.id, 10) - parseInt(b.id, 10);
[ "stackoverflow", "0040581512.txt" ]
Q: Error: expected unqualified-id before ‘)’ token Node() So, I keep getting an error saying I need an unqualified-id and cant figure out what is giving me the error. please help. the error occurs on the Node() part of the class. error: expected unqualified-id before ‘)’ token Node() ^ Here's the code: #include <iostream> #include <string> using namespace std; class AHuffman { public: class Node { Node* right_child; Node* left_child; Node* parent; Node* sibling; int weight; int number; string data; }; Node() { right_child = NULL; left_child = NULL; parent = NULL; sibling = NULL; weight = 0 number = 1; data = ""; } // int encode(string* msg, char** result, int rbuff_size); // int decode(string* msg, char** result, int rbuff_size); AHuffman(string* alphabet); ~AHuffman(); }; int main(int argc, const char* argv[]) { if(argc != 4){ //Invalid number of arguments cout << "invalid number of arguments" << endl; return 1; } string* alphabet = new string(argv[1]); string* message = new string(argv[2]); string* operation = new string(argv[3]); return 0; } A: Because you put the constructor of Node outside of its class: Anyway, you should initialize its members in member initializer list instead of in constructor body. class Node { Node* right_child; Node* left_child; Node* parent; Node* sibling; int weight; int number; string data; public: Node() : right_child(0), left_child(0), parent(0), sibling(0), weight(0), number(1) { } }; Another note, you don't need that much new in C++
[ "apple.stackexchange", "0000380550.txt" ]
Q: MacBook Pro shows not charging when plugged in I've got a MacBook Pro (Retina, 15-inch, Mid 2015) and as of today it says "not charging" even when it's plugged in. The MagSafe connector has an orange light, and the power menu's screenshot is attached. How can I get the battery status to charging? A: https://support.apple.com/en-us/HT201295 If you're experiencing issues with any of these, you might need to reset the SMC. Power, including the power button and power to the USB ports Battery and charging Fans and other thermal-management features Indicators or sensors such as status indicator lights (sleep status, battery charging status, and others), the sudden motion sensor, the ambient light sensor, and keyboard backlighting ... How to reset SMC: Shut down your Mac. Press and hold all of these keys: Shift (left) Control (left) Option (Alt) (left) While holding all three keys, press and hold the power button too. Keep holding all four keys for 10 seconds. Release all keys, then press the power button to turn on your Mac.
[ "stackoverflow", "0008577502.txt" ]
Q: Connection String for Oracle in OraDb11g_home1 Driver I know that connection string questions are a dime-a-dozen, but I've got a new one. I created a System DSN to talk to an Oracle database that I have locally on my machine. I put in all the info and hit the test button, and it says that it's successful. I'm using the OraDb11g_home1 driver. When I try to put together a connection string for an application that uses ODBC, of course I can't get it to work. One of the connection string attributes that they say that they require in their documentation is something called "Provider." What is this? One of the most recent strings that I've used includes the following. Driver={Oracle in OraDb11g_home1};Server=\\localhost:1521\local;Uid=mike;Pwd=password Can anyone please offer any suggestions? Thanks, mj A: I figured it out. I was trying to use an application that was using 32-bit ODBC and the DSNs that I created were 64-bit.
[ "stackoverflow", "0047184032.txt" ]
Q: Change Woocommerce Booking Label I am trying to change the woocommerce booking duration field's label which currently simply reads "Duration". It doesnt seem possible through the admin area, or i cannot find it. Is is possible to change it via functions.php does anyone know? This is the code for the label on the product page: <label for="wc_bookings_field_duration">Duration:</label> A: try this: add_filter( 'booking_form_fields', 'custom_booking_form_fields' ); function custom_booking_form_fields( $fields ) { $fields['wc_bookings_field_duration']['label'] = "The new Label"; return $fields; }
[ "stackoverflow", "0011380498.txt" ]
Q: role of code segment registers in system calls When system call is made, is previlege level checked using code segment registers or control register are used? Code segment registers in intel cpus were meant for segmentation purposes.I m not clear about how paging and intel x86 mechanisms are handled in linux. Would be great help if someone explained what happens in the cpu when system call is made with respect to change in level. A: Linux never used 286 style segmentation for separating processes, or otherwise making the virtual memory interestingly segmented, but rather used 386 style paging from the beginning. Transfer to kernel mode (syscall) used to be a simple int instruction which transfered execution according to the interrupt table and caused the CPU to enter the kernel mode (protection level 0). However, the CPU still had to reload segment descriptors to "learn" the new protection level and where the new segment is (although it was always the same dummy kernel mode segment which the CPU just "didn't know".). AMD and Intel came forward with optimized instructions to make this process faster and this is what all operating systems on this platform use in reality. Kernel code then has to do even more work to save registers on the stack and initialize them to new values, and this has not changed. But this is normally not understood to be a part of the system call process. When system call is made, is previlege level checked using code segment registers or control register are used? The privilege level is obtained, not checked, from the new code segment as referenced through the interrupt table - or, in the optimized case, as pre-loaded into a MSR (a CPU register not accessible by non-kernel code). Another way of saying the same is that the switch to level 0 happens automatically on CPU level, but the segment descriptors and/or MSRs need to be prearranged by the kernel in a way that really results in kernel executing the trap handler and not just a general protection fault.
[ "math.stackexchange", "0002962897.txt" ]
Q: If $C$ is a $m \times n$ matrix such that $Cx=b$ is consistent for all $b \in \mathbb{R^m}$, which of the statements is/are definitely correct? (I) For each $b \in \mathbb{R^m}$, there is a unique solution $x$. (II) The column space of $C$ has dimension $m$. (III) It is possible that $Cx=0$ has non trivial solutions. I have put (II) as my answer to be the only statement that is correct. However I'm unsure if (III) can also be correct or not, need some help here thanks. A: Consider \begin{align} C = \begin{pmatrix} 1 & 0 & 0\\ 0 & 1 & 0 \end{pmatrix} \end{align} then clearly \begin{align} Cx = b \end{align} has solutions for any $b \in \mathbb{R}^2$. Moreover, $(0, 0, 1)^T$ belongs in the kernel of $C$.
[ "stackoverflow", "0043051866.txt" ]
Q: Errors with"npm run dev" command on fresh Laravel 5.4 I've been struggling with this for 5 hours now. Here is the error I get when i try to run "npm run dev" on a fresh Laravel install > @ dev /var/www/html/capsule > cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js events.js:160 throw er; // Unhandled 'error' event ^ Error: spawn node_modules/webpack/bin/webpack.js ENOENT at exports._errnoException (util.js:1022:11) at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32) at onErrorNT (internal/child_process.js:359:16) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) at Module.runMain (module.js:606:11) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3 npm ERR! Linux 3.16.0-4-amd64 npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "dev" npm ERR! node v6.9.4 npm ERR! npm v2.15.11 npm ERR! code ELIFECYCLE npm ERR! @ dev: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @ dev script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'. npm ERR! This is most likely a problem with the package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm ERR! npm owner ls npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /var/www/html/capsule/npm-debug.log Here is my package.json file : { "private": true, "scripts": { "dev": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch-poll": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --watch-poll --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "axios": "^0.15.3", "bootstrap-sass": "^3.3.7", "cross-env": "^3.2.3", "jquery": "^3.1.1", "laravel-mix": "0.*", "lodash": "^4.17.4", "vue": "^2.1.10" } } As you can see I have recent versions of npm and node. I've been looking for similar issues, tried to re-install and re-build with npm several times, nothing seems to work. Thanks A: run npm install webpack --save
[ "pt.stackoverflow", "0000072659.txt" ]
Q: Como fazer setTimeout rodar "infinitamente" Preciso que uma função seja executada a cada 2 minutos. Encontrei neste link uma solução para a minha necessidade: Link O Código abaixo, chama um alert após 5 segundos ao deixar o mouse parado. Observação Coloquei 5 segundos para poupar tempo no teste. <script type="text/javascript"> $(function() { timeout = setTimeout(function() { alert('executa função'); }, 5000); }); $(document).on('mouseover', function() { if (timeout !== null) { clearTimeout(timeout); } timeout = setTimeout(function() { alert('executa função'); }, 5000); }); </script> O que eu preciso: Eu preciso que este script funcione da mesma forma só que em um loop infinito, onde a cada 5 segundos será chamado o alert. Eu tentei abraçar o código com: while(0 = 0){ } Mas não funcionou... Como faço então para que minha função seja executada infinitamente a cada 5 segundos automaticamente? A: Para que o evento ocorra infinitamente sem o mouseover, basta remove-lo. Veja: function Temporizador(initiate) { if (initiate !== true) { alert("Olá mundo"); } setTimeout(Temporizador, 5000); } $(function() { Temporizador(true); }); Se chamar o Temporizador(true); com true, ele não executa o primeiro alert, mas somente a cada 5 segundos.
[ "stackoverflow", "0018979681.txt" ]
Q: Using $# in bash loops I am trying to understand why this loop does not print a number for each arguments supplied to the script. #!/bin/bash for i in {1..$#}; do echo $i done Instead, when supplied e.g. 3 arguments, it outputs {1..3} A: The expression {} does not accept variables. To do so, you need to work with for example seq. The following will make it:: #!/bin/bash for i in $(seq 1 $#); do echo $i done Note that $() is equivalent to ``. That is, it performs a command substitution. For example: $ d=$(echo "hello") $ echo $d hello You can see more information in Shell Programming: What's the difference between $(command) and command. Tests $ ./a $ $ ./a a b c 1 2 3
[ "stackoverflow", "0022283750.txt" ]
Q: C - macro is defined based on type name I'm working on a task which has a macro of the following form. // Thread identifier type. typedef int tid_t; #define TID_ERROR ((tid_t) -1) /* Error value for tid_t. */ Then, some functions having the type tid_t will return that macro in case of failure: tid_t foo() { if(fail()) { return TID_ERROR; } } I can't understand how this makes sense: a)How can a constant be subtracted from a type name tid_t - 1? b)How can the previous result be returned? I thought types are not data, so they can't be manipulated in the same manner. And, what I need to know: c)When calling the function foo, how can I check for failure? A: It's not returning or manipulating a type, it's returning the value -1, cast to that type. To check for the error, compare with the TID_ERROR macro. tid_t result = foo(); if(result == TID_ERROR) { handle error } A: #define TID_ERROR ((tid_t) -1) It's not subtracting 1 from tid_t, it's a cast, to cast -1 to the type tid_t, which is then used as an invalid value for this type.
[ "stackoverflow", "0031394005.txt" ]
Q: Python mail script and inserting variables into the html code I tried to use templates and string formatting but nothing seemed to work. I'm trying to prompt for user input so they can set a time in the html code. Here's a snippit of the code: my_html = """\ <html> <head> <title>Something goes here</title> </head> <body> <div style="font-family: 'Segoe UI', Helvetica, Arial, sans-serif;"> <font face="Calibri,sans-serif" size="2"><span style="font-size: 14px;"><b>When: &nbsp;</b>$the_time_goes_here</span></font></div> </div> </body> </html> """ the_time_goes_here = raw_input("What's the start time?\n") I want to get "the_time_goes_here" to populate data in the html code. A: Use str.format using a placeholder {} for the string pass into raw_input : my_html = """\ <html> <head> <title>Something goes here</title> </head> <body> <div style="font-family: 'Segoe UI', Helvetica, Arial, sans-serif;"> <font face="Calibri,sans-serif" size="2"><span style="font-size: 14px;"><b>When: &nbsp;</b>{0}</span></font></div> </div> </body> </html> """.format(raw_input("What's the start time?\n"))
[ "stackoverflow", "0062930543.txt" ]
Q: Groovy + Insight (Jira) Exception on split method I'm trying to create a script with Groovy to be able to auto affect a Jira issue to a specific object in Insight (Add-on of Jira). Actually, i need to split a value. The value is "2629351(AFAW16-FS01.francois.int)", i want to have AFAW16-FS01.francois.int part only. I can do it if i apply directly the method to the text but it's not working with a string. here my code : import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.fields.CustomField import com.riadalabs.jira.plugins.insight.services.model.CommentBean; import com.atlassian.jira.issue.MutableIssue import com.atlassian.jira.event.type.EventDispatchOption import com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade import com.riadalabs.jira.plugins.insight.services.model.ObjectAttributeBean import com.riadalabs.jira.plugins.insight.services.model.ObjectBean Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade"); def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass); Class iqlFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.IQLFacade"); def iqlFacade = ComponentAccessor.getOSGiComponentInstanceOfType(iqlFacadeClass); def objects = iqlFacade.findObjectsByIQLAndSchema(10,"objectTypeId = 2443"); //def test = "AF-172738" //def ObjectInsightBean = objectFacade.loadObjectBean(test) //log.warn("ObjectInsightBean " + ObjectInsightBean) def n = 0 (objects).each { CurrentObject = objects[n] def FQDNValue = objectFacade.loadObjectAttributeBean(CurrentObject.getId(),47464).getObjectAttributeValueBeans()[0]; //Load Attribute Value //log.warn("Server " + objects[n]) //log.warn("FQDNValue " + FQDNValue) //FQDNValueSTR = FQDNValue.ToString() log.warn("FQDNValue brut" + FQDNValue) def values = '2629351(AFAW16-FS01.francois.int)'.split("\\("); //WORKS ! def FQDNSplit = FQDNValue.split("\\("); // NOT WORKS def Value1 = values[1] def Value2 = Value1.substring(0, Value1.length() - 1); //log.warn("Values " + Value2) //result = (issue.getSummary()) //Show subject //log.warn("result " + result) n ++ } FQDNSplit contain "2629351(AFAW16-FS01.francois.int)" but i have the following error: class com.riadalabs.jira.plugins.insight.common.exception.GroovyInsightException GroovyInsightException: No signature of method: com.riadalabs.jira.plugins.insight.services.model.ObjectAttributeValueBean.split() is applicable for argument types: (java.lang.String) values: [\(] Possible solutions: split(groovy.lang.Closure), wait(), wait(long), getAt(java.lang.String), print(java.lang.Object), sprintf(java.lang.String, java.lang.Object)' Any idea? Thank you!! A: The simple comman extracts the substring that you want: String res = '2629351(AFAW16-FS01.francois.int)'.replaceFirst( /\d\(([^\(\)]+)\)/, '$1' ) assert res == 'AFAW16-FS01.francois.int' Also you should stick with Java Naming Conventions, and DO NOT name variables starting with capital letters.
[ "stackoverflow", "0006550778.txt" ]
Q: How to get elements with the different value of the same attribute in javascript or jquery? I need to find elements with the different value of the same attribute... This works-> $data.find("div[data-alpha='1']"); But i need something like this-> $data.find('div[data-alpha='1']' + 'div[data-alpha='2']' .... So i want to find all elements which have the ,,data-alpha" atribute 1 or 2. Anyone have an idea how to do that? Thanks for all answers! Cheers! A: Use the multiple-selector[docs]. $data.find("div[data-alpha='1'], div[data-alpha='2']") This allows you to accumulate the results of different selectors by joining the selectors with a comma into a single selector.
[ "stackoverflow", "0047872050.txt" ]
Q: File version with VS2017 In the past I used a resource editor in VS applications to add a version number (VS_VERSION_INFO) to my program that is visible in the file properties window! Since this feature needs MFC (afxres.h) I want to get rid of it: How can I achieve same or similar results, or what is the suggested way in VS2017 C++ projects? A: I'm not sure why you think afxres.h is necessary, I have resource scripts with version resources that rely only on winres.h
[ "stackoverflow", "0049038171.txt" ]
Q: How to edit the contents of a specific row in Python SQLite3 using ROWID I have the following database (test.db): Test Database As seen in the picture,I created and populated a table ("stuffToPlot"). I want to edit a specific row (the 5th row for example), and change all the values therein. I tried the following code to do this: import sqlite3 conn = sqlite3.connect('test.db') c = conn.cursor() tableToEdit = 'stuffToPlot' rowToEdit = '5' unixVar = 5.5 dateStampVar ='feb-2018' keywordVar = 'Hello World' valueVar = 25 c.execute("""INSERT INTO """+tableToEdit+""" (unix, datestamp, keyword, value) VALUES (?,?,?,?) WHERE ROWID =""" +rowToEdit),(unixVar, dateStampVar, keywordVar, valueVar) conn.commit() c.close() conn.close() I get the following error when trying to run the code: Traceback (most recent call last): File "C:\Users\Bob\Documents\Eclipse Workspace\Python Test\SQLite3\SQLite3-3.py", line 19, in VALUES (?,?,?,?) WHERE ROWID =""" +rowToEdit),(unixVar, dateStampVar, keywordVar, valueVar) sqlite3.OperationalError: near "WHERE": syntax error I have also tried using the UPDATE/SET method, but get a different error: c.execute("""UPDATE """+tableToEdit+""" (unix, datestamp, keyword, value) SET (?,?,?,?) WHERE ROWID =""" +rowToEdit),(unixVar, dateStampVar, keywordVar, valueVar) File "C:\Users\Shaun\Documents\Eclipse Workspace\Python Test\SQLite3\SQLite3-3.py", line 24, in SET (?,?,?,?) WHERE ROWID =""" +rowToEdit),(unixVar, dateStampVar, keywordVar, valueVar) sqlite3.OperationalError: near "(": syntax error I just want to edit a specific row (using ROWID) ,any help would be greatly appreciated. A: INSERT always adds a new row, you can't use a WHERE clause when using INSERT. So yes, you have to use UPDATE here. Your UPDATE syntax is wrong however. UPDATE uses columname=value pairs, see the official documentation for UPDATE: c.execute( """UPDATE {} SET unix=?, datestamp=?, keyword=?, value=? WHERE ROWID = ?""".format(tableToEdit), (unixVar, dateStampVar, keywordVar, valueVar, int(rowToEdit))) I switched from using concatenation to str.format(), but only to put the table name in. The ROWID value can be passed in as a query parameter, so do so. Demo: >>> import sqlite3 >>> conn = sqlite3.connect(':memory:') >>> conn.execute(''' ... CREATE TABLE stuffToPlot (unix REAL, datestamp TEXT, keyword TEXT, value INTEGER) ... ''') <sqlite3.Cursor object at 0x10f049ce0> >>> with conn: ... for _ in range(10): ... c = conn.execute(''' ... INSERT INTO stuffToPlot VALUES (42.0, "mar-2010", "The quick brown fox", 81) ... ''') ... >>> tableToEdit = 'stuffToPlot' >>> rowToEdit = '5' >>> unixVar = 5.5 >>> dateStampVar ='feb-2018' >>> keywordVar = 'Hello World' >>> valueVar = 25 >>> with conn: ... conn.execute( ... """UPDATE {} SET unix=?, datestamp=?, keyword=?, value=? ... WHERE ROWID = ?""".format(tableToEdit), ... (unixVar, dateStampVar, keywordVar, valueVar, int(rowToEdit))) ... <sqlite3.Cursor object at 0x10f049ce0> >>> print(*conn.execute('SELECT * FROM stuffToPlot WHERE ROWID=5')) (5.5, 'feb-2018', 'Hello World', 25)
[ "pt.stackoverflow", "0000034683.txt" ]
Q: Selecionar Listas Específicas Tenho o seguinte código para retornar as bibliotecas do meu projeto em SharePoint: function retornarLista() { collList = website.get_lists(); context.load(collList);//, 'Include(TemplateType==109)' context.executeQueryAsync(onQuerySucceeded, onQueryFailed); } function onQuerySucceeded() { var listInfo = ''; var listEnumerator = collList.getEnumerator(); while (listEnumerator.moveNext()) { var oList = listEnumerator.get_current(); listInfo += 'Title: ' + oList.get_title() + ' ID: ' + oList.get_id().toString() + '\n'; $("#biblioteca").append("<option value='" + oList.get_id().toString() + "'>" + oList.get_title() + "</option>"); } } function onQueryFailed() { alert("Failed"); } Gostaria de retornar apenas as Bibliotecas de imagens para transferir para um dropdown de select, porém não tenho conseguido, alguém pode ajudar ? A: Você está trabalhando com a biblioteca JCOM do SharePoint. A definição do objeto lista pra essa biblioteca pode ser vista nesse link: http://msdn.microsoft.com/en-us/library/office/jj245826(v=office.15).aspx Repare que há propriedade chamada baseTemplate. Quando você cria uma lista, você está indicando o template base dela (pelo seu comentário, SP.ListTemplateType.pictureLibrary). Seu código está quase completo, só falta agora você percorrer todas as listas que obteve na consulta e verificar se o baseTemplate delas corresponde ao template de pictureLibrary que você usa para criá-las. Quando corresponder é porque a lista é uma biblioteca de imagens :) editando pra incluir código: basta ajustar seu código mais ou menos assim: /* .. snip .. */ while (listEnumerator.moveNext()) { var oList = listEnumerator.get_current(); if (oList.get_baseTemplate() == SP.ListTemplateType.pictureLibrary) { // Eis o pulo do gato. listInfo += oList.get_title() + '\n'; } /* .. snip .. */ } By the way esse SP.ListTemplateType.pictureLibrary é um valor constante, 109. Vivendo e aprendendo, eu não conhecia esse template...
[ "stackoverflow", "0026015875.txt" ]
Q: eclipse - how to create separate build configuration for multi-project workspace? My workspace contains 4 static lib projects and one executable project (which links these static libs). Now I want to create separate build configuration where TEST_GATE is set, so in c++ code this #ifdef TEST_GATE evaluates to true. So in all of my 5 projects I've copied Release configuration, named it ReleaseTest and added TEST_GATE symbol in project properties. Now all 5 projects are build into new folder ReleaseTest and my problem is that i need to link static libs in the main project properties. I do this in C/C++ Build / Settings / GCC C++ Linker / Libraries, and this configuration is NOT configuration dependent. So I should select either "Release" version of static library or "ReleaseTest" version of static library. But I need to switch this automatically depending on what confuguration i'm currently building. How can I solve/workaround this issue? A: In the Project / C/C++ General / Paths and Symbols / References you can change the configuration for every referenced project. After you change the checkboxes you can check the folder where eclipse is going to look for the libraries in the Library Paths tab.
[ "stackoverflow", "0036432759.txt" ]
Q: JMS Serializer List Polymorphic with XML Deserialization I need a little help, I have next scenario: AbtsractItem File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; /** * @JMS\Discriminator( * field = "objectType", * map = { * "part": "Com\Part", * "complement" : "Com\Complement" * }, * disabled=true * ) */ abstract class AbstractItem { protected $objectType; } Part File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; class Part extends AbstractItem { /** * @JMS\Type("string") * @JMS\XmlElement(cdata=false) */ protected $objectType = "Part"; /** * @JMS\Type("string") * @JMS\XmlElement(cdata=false) */ private $data; //getters & setters } Complement File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; class Complement extends AbstractItem { /** * @JMS\Type("string") * @JMS\XmlElement(cdata=false) */ protected $objectType = "Complemet"; /** * @JMS\Type("string") * @JMS\XmlElement(cdata=false) */ private $number; //getters & setters } MyObject File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; /** * @JMS\XmlRoot("MyObjects") */ class MyObject { /** * @JMS\Type("array<Com\AbstractItem>") * @JMS\XmlElement(cdata=false) * @JMS\XmlList(inline=false, entry="item") */ private $items; //getters & setters } So I expected something like the next XML: <MyObjects> <item> <objectType>Part</objectType> <number>1237173</number> </item> <item> <objectType>Complement</objectType> <data>loremp ipsum...</data> </item> </MyObjects> when I serialized/deserialized in JSON I have not problem, but not like that for XML. I saw the examples for arrays, for polymorphic attributes and the discriminator, but in my case, I need to have a AbstractItem collection, in this way I'm getting a message "Cannot instantiate abstract class Com\AbtsractItem", if my class it wasn't abstract I just get the attribue objectType in the xml cause is serializing a Item but no the children. A: Well, I get it, My first problem it was the version, i was using phpDocumentor so was 0.16, when I remove phpDocumentor I could update to 1.*, on the code my changes: Note: The object Part and Complement implements the new ItemInterface, removing the abstract class and extends Interface File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; /** * @JMS\Discriminator( * field = "objectType", * map = { * "part": "Com\Part", * "complement" : "Com\Complement" * }, * disabled=true * ) */ interface ItemInterface { } My Object File: <?php namespace Com; use JMS\Serializer\Annotation as JMS; /** * @JMS\XmlRoot("MyObjects") */ class MyObject { /** * @JMS\Type("array<Com\ItemInterface>") * @JMS\XmlElement(cdata=false) * @JMS\XmlList(inline=false, entry="item") */ private $items; //getters & setters }
[ "security.stackexchange", "0000054426.txt" ]
Q: Verifying integrity of text files While I was away from my home I needed to do some work on a java program so I booted a friends netbook(windows 8) I had with me and finished most of the works I needed to do there. Tho when I returned home I realized that the netbook didn't have antivirus, firewall and nothing security wise turned on which made me worry. I now want to transfer these files(.java) to my main ubuntu desktop system but I am worried that something might have hidden itself inside the files header and other places, is there a way to verify the integrity of the files or a way to safely transfer the code they contain without accidentally transferring anything malicious and since these files are actually going to be compiles and put on production I'm double worried about that. A: Because mythical imagined malware that might subtly modify your unique proprietary source code is very unlikely to exist, there are a couple of slightly more real threats you could check for. If your friend's computer was compromised by a human hacker, the hacker could have copied your code to his computer, studied it, changed it, and uploaded his changes back to your friend's computer. (This presumes an attacker who knows who you are, exactly what you are working on, how to find it, and has the means and motivation to carry out such an attack.) As the developers, you are the only people who would be in a position to know this, and a simple code review should easily satisfy you that this didn't take place. Another remote possibility might be that this mythical malware hid something in an alternate data stream inside your code. While this could theoretically be possible, there is nothing on your computer that would automatically extract the payload from the ADS and execute it, so it won't simply infect your computer to copy it in. If it's a known virus, your own computer's anti-virus would detect it. Even if the ADS contained a virus, it still wouldn't have a way to execute to compromise your system. If you want to go with full-blown movie-plot paranoia, this mythical malware could have planted some kind of "illegal" data in an ADS inside your files, as part of a complicated blackmail scheme. Frankly, the only plausible scenario of risk is that the media containing your files could have been infected by this mythical malware. Are the files now on a flash drive? Copy them off the flash drive using a Linux machine (which will be immune to Windows executable viruses and autoruns kinds of attacks.) Don't copy any files other than the valuable source files. Java source code files are fine, but PDFs, JPGs, EXEs, TTFs, DOCs, and everything else is not. After you have saved the needed files, format the flash drive. You can then use a tool like sdelete with the -z option to overwrite the bits in the drive, then sell the flash drive on eBay.
[ "stackoverflow", "0054749606.txt" ]
Q: how to group count items in SPARQL, accumulating low hit entries? How do I count grouped entries in SPARQL, merging entries whose quantity is less than a specific factor? Consider for example the Nobel Prize data. I could get a count of all family names with a query like PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name (count(*) as ?count) WHERE { ?id foaf:familyName ?name } GROUP BY $name ORDER BY DESC($count) How do I modify the query so it only returns the family names occuring at least 3 times, accumulating the other names as other. A: Just wrap your SELECT into another one. Query PREFIX foaf: <http://xmlns.com/foaf/0.1/> SELECT ?name_ (SUM(?count) AS ?count_) { { SELECT ?name (COUNT(*) AS ?count) { ?id foaf:familyName ?name } GROUP BY ?name } BIND (IF(?count > 2, ?name, "Other") AS ?name_) } GROUP BY ?name_ ORDER BY DESC(IF(?name_ = "Other", -1 , ?count_)) Results name_ count_ ----------- --------- Smith 5 Fischer 4 Wilson 4 Lee 3 Lewis 3 Müller 3 Other 878
[ "stackoverflow", "0004247361.txt" ]
Q: Display PDF as HTML Form I want display a PDF as an html page - where the user will be allowed to enter the fillable data. My problem is not how to import/fill data (I was able to do it using FDF/XML and ITextSharp). My only concern is how to show it to the user so that he/she can see the form, fill/edit data, and should be done with it. I tried saving the PDF as an image file, and showing it as an background-image - but it was very crude! - Iam hoping that there should be some elegant solution. Thanks for you help! A: PDF already has form-filling capabilities. Just display the PDF and let the user fill it in. You can add the fields using Adobe Acrobat. The form can be submitted back to your server like a Web page or just e-mailed.
[ "stackoverflow", "0044738373.txt" ]
Q: Redeclaring variables in functions Why does redeclaring output inside this if-statement not generate an error? let output = 0 if counter < message.count { let output = counter //This should throw an error, right? counter += 1 } ... The scope inside the if-statement knows about output as proven here, when trying to change the value of output instead of re-declaring it: let output = 0 if counter < message.count { output = counter //ERROR: Cannot assign to value: 'output' is a 'let' constant counter += 1 } ... A: There is no error because it is perfectly legal to declare a variable inside a closure with the same name of a variable which has been declared outside of the closure. It shadows the "outside declared variable". In case your sample code is inside a class you could still access the "outside declared variable" using self: class Foo { let output = 0 func baa() { let output = 1 print(output) print(self.output) } } Using this: let foo = Foo() foo.baa() prints: 1 0
[ "stackoverflow", "0005945968.txt" ]
Q: PHP grouping array i've got the following array: $comments = array(); $comments[] = array('member_id' => '17', 'time' => '2011-05-10 11:10:00', 'name' => 'John Smith', 'comment' => 'Test Comment 1'); $comments[] = array('member_id' => '25', 'time' => '2011-05-10 11:26:00', 'name' => 'David Jones', 'comment' => 'Test Comment 2'); $comments[] = array('member_id' => '17', 'time' => '2011-05-10 13:15:00', 'name' => 'John Smith', 'comment' => 'Test Comment 3'); How would i go about grouping it by member_id? So I'll be able to display the comments on the page with the following formatting: John Smith(2 comments) 2011-05-10 11:10:00 | Test Comment 1 2011-05-10 13:15:00 | Test Comment 3 David Jones(1 comment) 2011-05-10 11:26:00 | Test Comment 2 A: One solution is to sort them by the name field (check out usort for that), but even easier might be to just populate a new array in this way: $grouped = array(); foreach($comments as $c) { if(!isset($grouped[$c['name']]) { $grouped[$c['name']] = array(); } $grouped[$c['name']][] = $c; } //Now it's just a matter of a double foreach to print them out: foreach($grouped as $name => $group) { //print header here echo $name, "<br>\n"; foreach($group as $c) { //print each comment here } }
[ "stackoverflow", "0027120939.txt" ]
Q: Is it possible to develop an app that reads other apps' usage data? With the new app-extension kit, I'd like to know if it's possible to build an app that tracks various usage statistics of other apps. For e.g., the no of times someone uses their calculator or the no of minutes spent on Quora. A: This is a really nice idea to enhance the ability of iOS system. However, even in iOS8 this is unlike to achieve. Apple has offered so limited APIs for APPs to access other APPs. In those APIs, I cannot find any one to record other APPs' launching or closing. (Except you call that from your own APP so that you can record the time, but this is meaningless.) In the official document for App Extension Programming, manager for APP is not a type that is mentioned in the guide. I'm afraid that you have read it and it cannot give you more help. I tried to do research on the most detail list of iOS APIs to find whether this is possible. But since iOS5.0, Apple no longer provided the API diffs. Here is the search result.
[ "stackoverflow", "0010343441.txt" ]
Q: Attach data or array index to anchor tag I have some javascript/jquery code that dynamically populates an unordered list with a bunch of list items. In the list items I have a link and I want to associate some data with that link which is generated like so: var thing1 = { name: 'My Object' }; var thing2 = { name: 'My Other Object' }; var li = $('<li></li><br />'); var aSel = $('<strong>' + thing1.name + '<br /><a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>'; li.append(aSel); li.append(add); $('#sidebar').append(li); //This is in a loop so the same thing would happen with thing2, etc would generate HTML like so: <div id="results"> <ul id="sidebar"> <li> <strong>My Object</strong><br /> <a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a> </li> <li> <strong>My Other Object</strong><br /> <a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a> </li> </ul> </div> So if the user clicks the first Add Deal link, I want to work with the thing1 data elsewhere in my script. If they second link is clicked on, I want to work with the thing2 data. The path I'm going down involves an array and some code that doesn't feel quite right to me. I figure I'm missing something trivial. A: You can use the jQuery.data function to attach a "thing" to each of your links. Right after the var aSel = line: $('a', aSel).data('thing', thing1); // Select the anchor tag inside of // aSel and attach thing1 to it Then when the anchor tag is clicked, retrieve it with: var thing = $(this).data('thing');
[ "stackoverflow", "0060089560.txt" ]
Q: JAVA: Getting pause in application when Log file is going to roll over I am using wildfly 9 and slf4j(slf4j-api-1.7.21.jar)/log4j(log4j-1.2.17.jar). I am getting a pause in the application when the file is going to roll-over. My logging configuration in standalone.xml is below: <subsystem xmlns="urn:jboss:domain:logging:3.0"> <console-handler name="CONSOLE"> <level name="INFO" /> <formatter> <named-formatter name="COLOR-PATTERN" /> </formatter> </console-handler> <size-rotating-file-handler name="FILE" autoflush="true"> <formatter> <named-formatter name="PATTERN" /> </formatter> <file relative-to="jboss.server.log.dir" path="server.log" /> <rotate-size value="30m" /> <max-backup-index value="10000" /> <append value="true" /> </size-rotating-file-handler> <size-rotating-file-handler name="APPLICATION" autoflush="true"> <formatter> <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %m%n" /> </formatter> <file relative-to="jboss.server.log.dir" path="application.log" /> <rotate-size value="30m" /> <max-backup-index value="10000" /> <append value="true" /> </size-rotating-file-handler> <logger category="com.company" use-parent-handlers="true"> <level name="INFO" /> <handlers> <handler name="APPLICATION" /> </handlers> </logger> <root-logger> <level name="INFO" /> <handlers> <handler name="CONSOLE" /> <handler name="FILE" /> </handlers> </root-logger> <formatter name="PATTERN"> <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n" /> </formatter> <formatter name="COLOR-PATTERN"> <pattern-formatter pattern="%K{level}%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n" /> </formatter> </subsystem> Any suggestion/configuration for this issue? A: simple suggestion: reduce max-backup-index to a lower value. max-backup-index=10000 means that on rollover the logging framework has to: delete server-9999.log rename server-9998.log to server-9999.log rename server-9997.log to server-9998.log ... rename server.log to server-1.log and only then it can create a new server.log
[ "unix.stackexchange", "0000074721.txt" ]
Q: How do I copy directories and symlink files? I have got a directory of huge files (total ~ 1TB) and I don't want copy them around. However, I'd like to work around them, so it would be convenient to have them linked in a directory hierarchy I have access to (aka one I created). So /path/to/dirs/ foo bar baz/ tri Should be copied to ~/path/to/dirs/ foo -> /path/to/dirs/foo bar -> /path/to/dirs/bar baz/ tri -> /path/to/dirs/tri A: With GNU: cd ~/path/to/dirs || exit 1 find /path/to/dirs -type d -printf %P\\0 | xargs -0 mkdir -p find /path/to/dirs -type f -print0 | xargs -0 cp --symbolic-link --parents --target-directory=.
[ "stackoverflow", "0060648296.txt" ]
Q: How to assess even and odd numbers using the bitwise operator & I am trying to assess if the numbers inside an array are even or odd using the bitwise operator &. This is my code: arr = [1, 2, 4, 6, 9, 11, 18, 361, 5622, 5623] arr.forEach(function (el) { if (parseInt(el.toString(2)) & 1 === 0) { console.log(`${el} in binary is ${el.toString(2)} and it is an EVEN number`); } else { console.log(`${el} in binary is ${el.toString(2)} and it is an ODD number`); } }); Taking each element individually each one returns 0 or 1 which would assess if a number is even or odd, but in this case they all return ODD numbers. This is what I get as result: 1 in binary is 1 and it is an ODD number 2 in binary is 10 and it is an ODD number 4 in binary is 100 and it is an ODD number and so on... Where did I do wrong? A: The order of operations matters here (and is defined by operator precedence). The & occurs after the === comparison, so your if-statement actually evaluates like: if (parseInt(el.toString(2)) & (1 === 0)) { where 1===0 is performed first. This will result in if(<num> & false), where false is converted to the numeric value 0 as it is being used in the context of the bitwise & operator. So, <num> & 0 will always evaluate to 0, which is a falsy value (thus always causing the else-block to trigger). Instead, you can use parenthesis to enforce the order: arr = [1, 2, 4, 6, 9, 11, 18, 361, 5622, 5623] arr.forEach(function(el) { if ((el & 1) === 0) { console.log(`${el} in binary is ${el.toString(2)} and it is an EVEN number`); } else { console.log(`${el} in binary is ${el.toString(2)} and it is an ODD number`); } }); You can also use the & operator on your number directly (so no need to use toString on it)
[ "stackoverflow", "0015139562.txt" ]
Q: Error: Cannot Spawn C:\Path To\TortoiseGit\Bin: No such file or directory Trying to do a fetch from origin: git remote update Get the error Error: Cannot Spawn C:\Path To\TortoiseGit\Bin: No such file or directory fatal: unable to fork Error: Could not fetch origin Why is this happening? Also is there a fix? A: For me the answer was removing the double quotes of "c:\Program Files (x86)\PuTTY\plink.exe" from the environment variable GIT_SSH. A: This blog would seem to be the exact same problem that you have: http://www.techneiq.com/2012/08/error-cannot-spawn-cprogram.html And this issue on msysgit also points to the same error: https://code.google.com/p/msysgit/issues/detail?id=313 Find out what your GIT_SSH environmental variable is pointing to and if that path has a space in it. Maybe reinstalling TortoiseGit would solve it. (Otherwise I can really recommend GitExtensions instead) A: I faced this problem when I was required to remove and install the TortoiseGit and Git. Previously both was installed on C:\ but later I installed those on F:. So after re-installing when I tried to pull repositories it was giving me the following error while using from context menu error: cannot spawn C:\Program Files\TortoiseGit\bin\TortoisePlink.exe: No such file or directory After little bit investigation I went to Settings->Network and update the SSH Client path from C:... to F:... and then it was resolved.
[ "stackoverflow", "0057690507.txt" ]
Q: Using If statement to verify if string value is in an array of strings I have a string and an array of strings. I was wondering if it is possible to use an If statement in order to return a boolean value if the string contains a value from the array. The code below doesn't work properly. Contains can only take in one value as far as I can see. Is there a better way to do this without having to use a loop? Dim FilePath As String = "C:\Users\Downloads\Test.jpg" Dim GetExtension As String = FilePath.Substring(FilePath.Length - 3) Dim FileExtensionArray() As String = {".png", ".jpg", ".tif"} If GetExtension.Contains(FileExtension) = True Then ' Code Else ' Code End If A: Just a couple of things to note about your code: Dim GetExtension As String = FilePath.Substring(FilePath.Length - 3) Dim FileExtensionArray() As String = {".png", ".jpg", ".tif"} GetExtension now contains jpg but your arrays are .jpg. There's some built-in help already available for file extensions: IO.Path.GetExtension(FilePath) Lastly, your If .... Then test is the wrong way round. With a couple of simple adjustments I'd use this: Dim FilePath As String = "C:\Users\Downloads\Test.jpg" Dim FilePathExtension As String = IO.Path.GetExtension(FilePath) Dim FileExtensionArray As String() = {".png", ".jpg", ".tif"} If FileExtensionArray.Contains(FilePathExtension) Then 'yes Else 'no End If
[ "math.stackexchange", "0000148338.txt" ]
Q: Unbounded measurable set with different inner and outer measures I'm working on providing a counterexample to the claim that A unbounded set $A \subset \mathbb{R}$ is Lebesgue measurable if and only if its inner and outer measures are equal. Further, if $B$ is an unbounded measurable set that contains $A$, then $A$ is measurable if and only if it divides $B$ cleanly. Let me clarify which definitions I'm using. Lebesgue outer measure is $$m^*A = \inf\left\{ \sum_k |I_k| : \{I_k\} \text{ is a covering of $A$ by open intervals}\right\}$$ Lebesgue inner measure is $$m_*A = \sup\left\{ m^*C : C\text{ is closed and }C \subset A\right\}$$ A set $E$ is Lebesgue measurable if the division $E|E^c$ of $\mathbb{R}$ is so "clean" that for each "test set" $X \subset \mathbb{R}$, we have $$m^*X = m^*(X \cap E)+ m^*(X \cap E^c)$$ So far, I have thought that the best strategy to disprove the claim is to find an example of an unbounded measurable set that has unequal inner and outer measure. Does this seem like the right direction? Are there any example sets I should study? A: The counterexample is as follows. First, we define an unmeasurable set: $V \subset [0,1]$ (perhaps something like the Vitali set). Then, defining $R = (2,\infty)$, we can consider our counterexample function $C = V \sqcup R$. We know that $C$ is unmeasurable because if it were, since $[0,1]$ is measurable, we know that $C \cap [0,1]$ would be measurable. This clearly isn't the case because $C \cap [0,1] =V$. Now, we know that $m^*C = m_*C = \infty$, because $m^*R = \infty$ and both inner and outer measure are monotonic. Therefore, we have an unbounded, unmeasurable set with equal inner and outer measure, contradicting the claim.
[ "stackoverflow", "0042338288.txt" ]
Q: How to display 2 sets of data on the same axis of ASP.NET chart I want to display 2 sets of data on the same axis of a chart . On the X axis I would be displaying the UserID and on Y axis the Avg marks of all papers checked by the user. But i also want to display the number of booklets for which the avg has been derived for each user . How to go about it? I want the chart to look like this Where The numbers besides the avgs are the number of papers checked by particular user. Till now I have this: private void Bindchart() { string msg = string.Empty; try { connection.Open(); SqlCommand cmd = new SqlCommand("select Teacher_code, sum(Total_marks)/ count(*) as avgmarks , COUNT(*) as no_of_copies from " + connection.Database + "_transctn where sub_code='" + DropDown_Subjects.SelectedValue + "' and Teacher_code!='' group by Teacher_code", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DataTable ChartData = ds.Tables[0]; //storing total rows count to loop on each Record string[] XPointMember = new string[ChartData.Rows.Count]; decimal[] YPointMember = new decimal[ChartData.Rows.Count]; int totalrows = ChartData.Rows.Count; if (totalrows > 0) { for (int count = 0; count < ChartData.Rows.Count; count++) { //storing Values for X axis XPointMember[count] = ChartData.Rows[count]["Teacher_code"].ToString(); //storing values for Y Axis YPointMember[count] = Convert.ToDecimal(ChartData.Rows[count]["avgmarks"]); } //binding chart control Chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember); //Setting width of line Chart1.Series[0].BorderWidth = 5; //setting Chart type Chart1.Series[0].ChartType = SeriesChartType.Column; //Chart1.Series[0].ChartType = SeriesChartType.StackedColumn; //Hide or show chart back GridLines Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = true; Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = true; //Enabled 3D //Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true; connection.Close(); } } A: Try this: protected void Page_Load(object sender, EventArgs e) { connection.Open(); SqlCommand cmd = new SqlCommand("Your SQL here.", connection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); DataTable ChartData = ds.Tables[0]; Chart1.Series[0].Points.DataBind(ChartData.DefaultView, "Teacher_code", "avgmarks", ""); for (int i = 0; i < Chart1.Series[0].Points.Count; i++) Chart1.Series[0].Points[i].Label = string.Format("{0:0.00} ({1})", ChartData.Rows[i]["avgmarks"], ChartData.Rows[i]["no_of_copies"]); connection.Close(); }
[ "stackoverflow", "0011812426.txt" ]
Q: Java parameter validation, File exists, can be read and is a regular File I have this code to validate a java.io.Fileparameter which should not be null, should be accessible, should be a file and not a directory, etc.: private static final String EXCEPTION_FILE_CAN_NOT_BE_READ = "The file %s does not seem to readable."; private static final String EXCEPTION_PATH_DOES_NOT_EXIST = "The path %s does not seem to exist."; private static final String EXCEPTION_PATH_IS_NOT_A_FILE = "The path %s does not seem to correspond to a file."; private static final String EXCEPTION_PATH_REFERENCE_IS_NULL = "The supplied java.io.File path reference can not be null."; public static Banana fromConfigurationFile( File configurationFile) { if (configurationFile == null) { String nullPointerExceptionMessage = String.format(EXCEPTION_PATH_REFERENCE_IS_NULL, configurationFile); throw new NullPointerException(); } if (!configurationFile.exists()) { String illegalArgumentExceptionMessage = String.format(EXCEPTION_PATH_DOES_NOT_EXIST, configurationFile.getAbsolutePath()); throw new IllegalArgumentException(illegalArgumentExceptionMessage); } if (!configurationFile.isFile()) { String illegalArgumentExceptionMessage = String.format(EXCEPTION_PATH_IS_NOT_A_FILE, configurationFile.getAbsolutePath()); throw new IllegalArgumentException(illegalArgumentExceptionMessage); } if (!configurationFile.canRead()) { String illegalArgumentExceptionMessage = String.format(EXCEPTION_FILE_CAN_NOT_BE_READ, configurationFile.getAbsolutePath()); throw new IllegalArgumentException(illegalArgumentExceptionMessage); } // ... more tests, like "isEncoding(X)", "isBanana(ripe)", ... } Looks like a lot of boilerplate for something I could be "pinching" from somewhere. Especially because these are not all the checks that I need, there is more (e.g. the file is a text file and has the right encoding, ...). It seems reasonable to me that there would be a simpler way to do it than this. Perhaps a FileSpecs object to construct through a Builder and to pass to a verifyFileSpecs static helper? Question: am I doing it wrong or is there code I could reuse? Answer to the FAQ for post validity: Shows I made some research beforehand: I looked at the Java 6 SDK, that's where I got the different methods from, looked at JDK 7 and Files.isReadable, looked at Apache Commons IO, ... Shows that this question is unique: I am specifically asking if there is code that I can reuse, I am not asking "how do I check if a path corresponds to a file and not a directory?", all of which has already an answer on SO Why this could be useful to others: teams don't like boilerplate code like that submitted for code review, checked-in and versioned, potentially maintained (unit tests, etc.) So, borrowing the code from a reputable source would be very helpful, in my opinion. A: Yes, I would say above code is not DRY (Don't Repeat Yourself). Consider using Validate from Apache Commons. public static Banana fromConfigurationFile(File configurationFile) { Validate.notNull(configurationFile, String.format(EXCEPTION_PATH_REFERENCE_IS_NULL, configurationFile)); Validate.isTrue(configurationFile.exists(), String.format(EXCEPTION_PATH_DOES_NOT_EXIST, configurationFile.getAbsolutePath())); Validate.isTrue(configurationFile.isFile()), String.format(EXCEPTION_PATH_IS_NOT_A_FILE, configurationFile.getAbsolutePath())); // and more validation... }
[ "math.stackexchange", "0001861324.txt" ]
Q: minimal polynomial in Kummer extension Let $n>1$ be an integer. Let $K$ be a field such that $n$ does not divide the characteristic of $K$ and $K$ contains the $n$-th roots of unity. Let $\mu_n\subseteq K$ be the set of $n$-th roots of unity. Consider $\Phi\in\text{Hom}(K^{\times}/K^{\times n},\mu_n)$. Let $x\in K^{\times}$. Let $\Phi(xK^{\times n})=\zeta_x$ for some $\zeta_x\in\mu_n$. Let $x^{1/n}$ be any $n$-th root of $x$. I have a feeling that $x^{1/n}\zeta_x$ and $x^{1/n}$ have the same minimal polynomial over $K$. Is it correct ? A: The answer is yea, and I’ll give you an argument which I’m sure is not maximally efficient. Kummer theory gives us a perfect pairing between the discrete group $K^\times/K^{\times n}$ and the Galois group $G^{K_n}_K$, where by $K_n$ I mean the field generated by all the $n$-th roots of elements of $K$. That is, we have $\varphi:K^\times/K^{\times n}\times G^{K_n}_K\rightarrow\mu_n$, bilinear, such that if $\varphi(a,\sigma)=1$ for all $\sigma$ in the Galois group, then $a$ is an $n$-th power of an element of $K$; and if $\varphi(a,\sigma)=1$ for all $a\in K$, then $\sigma$ is identity. This means that your $\Phi$, whatever it is, can be identified with an element of the Galois group $G^{K_n}_K$, say $\tau$, which induces $\Phi$ by: for $a\in K^\times$, choose any $b$ with $b^n=a$, then $\Phi(a)=\tau(b)/b$. In particular, your $x$ has $\Phi(x)=\zeta$ and thus for an $n$-th root $y$ of $x$ we see that $\tau(y)=\zeta y$. According to your setup, $\zeta x^{1/n}=\zeta y$ is thus a Galois conjugate of $x^{1/n}=y$, and has the same minimal polynomial.
[ "stackoverflow", "0061414730.txt" ]
Q: How do I migrate an existing 20.04 ext4 installation to zfs root on different disk? I have a 20.04 ext4 installation (successful upgrade from 19.10!) and am just wondering about the above. One caveat I can think of is /etc/fstab and some other things may be somewhat different for ZFS root and so should probably not be transferred over. Is there any way to automagically avoid/resolve such conflicts, or should I just do a clean ZFS root installation and setup from scratch? A: The diet version is that to switch to ZFS root on a separate disk you will need to do the following: 1) Remove the / mount from /etc/fstab on the ZFS side after copying the rootfs across 2) Make sure that you rebuild the initramfs to include the zfs kernel module and userspace zpool and zfs binaries. 3) Change your kernel boot parameters to specify root=ZFS=poolname/rootfsname There is an excellent howto available here that covers this topic in full detail: https://github.com/openzfs/zfs/wiki/Ubuntu-18.04-Root-on-ZFS
[ "stackoverflow", "0001305838.txt" ]
Q: magento - Allow Countries - What does this mean? ok... so I feel really stupid asking this question.. but just wondering about the Allow Countries drop down in the admin panel.. What exactly does this mean? Does it mean that only certain countries are allowed to purchase from your site? if it does mean that how does it determine where you are shopping from? is it done using a IP Geo locator or is it determined when the user inputs their address on the checkout page? or does it mean that only customers from certain countries have access to the site? Regards, Fiona A: I believe it's a list of countries you are willing to ship to. Here's a reference that says this. The available list seems to be limited by locale, so no geolocating involved. No idea why this is done though.
[ "stackoverflow", "0027470900.txt" ]
Q: Size Class Issues - Also need a size class key In Xcode I am having an issue with the size classes in my app. I am unable to get the right size classes to show that seem to work for all of my different devices. I kind of would like a key to see what the size classes should really be, also the size classes don't seem to really match up. Below is an image attached of an example. I can't get anything correct. I am new to this and I know that I am doing something wrong. Also, I tried this: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LayoutandAppearance.html but it didn't match up. Maybe my controls have a layout issue? Edit: Shown below, I can't modify the leading edges and trailing edges... A: Whoo Hooo!!! I figured it out!!! @nburk, I want to give you some credit too. You said the key words trailing space and leading space so I googled more on that, and I was seeing the wrong thing. I want to recommend this to all users who are having problems with it. I didn't realize that dragging the constraints using the control button would actually do it. https://www.youtube.com/watch?v=IwSTXY0awng Bill.
[ "stackoverflow", "0049098894.txt" ]
Q: PL/SQL FIRST LAST EXISTS - (cannot show table contents) First, I have read the PL/SQL documentation repeatedly, no help. Second, I have googled for hours (usually being led here) and still cannot figure this out. I have created an index table, which seems to have been successful - at least it did not throw any errors... DECLARE CURSOR cur_emps IS SELECT employee_id, last_name, job_id, salary FROM employees ORDER BY employee_id; TYPE t_emp_rec IS TABLE OF cur_emps%ROWTYPE INDEX BY BINARY_INTEGER; v_emp_rec_tab t_emp_rec; BEGIN FOR emp_rec IN cur_emps LOOP v_emp_rec_tab(emp_rec.employee_id) := emp_rec; END LOOP; However, when I try to show what is in my index table. I fail... Documentation says do something like this... DECLARE CURSOR cur_emps IS SELECT employee_id, last_name, job_id, salary FROM employees ORDER BY employee_id; TYPE t_emp_rec IS TABLE OF cur_emps%ROWTYPE INDEX BY BINARY_INTEGER; v_emp_rec_tab t_emp_rec; BEGIN FOR emp_rec IN cur_emps LOOP v_emp_rec_tab(emp_rec.employee_id) := emp_rec; END LOOP; FOR i IN v_emp_rec_tab.FIRST..v_emp_rec_tab.LAST LOOP IF v_emp_rec_tab.EXISTS(i) THEN DBMS_OUTPUT.PUT_LINE(v_emp_rec_tab(i)); END IF; END LOOP; END; ... which gives me this... ORA-06550: line 13, column 12: PLS-00306: wrong number or types of arguments in call to 'PUT_LINE' ORA-06550: line 13, column 12: PL/SQL: Statement ignored In place of THEN DBMS_OUTPUT.PUT_LINE(v_emp_rec_tab(i)); . I have tried emp_rec.last_name, v_emp_rec.last_name, cur_emps.last name ... it has been days now trying, can anyone help? Thanks. Daniel A: You should iterate over an indexed table like this: l_idx := v_emp_rec_tab.first; while (l_idx is not null) loop dbms_output.put_line( v_emp_rec_tab(l_idx).last_name ); l_idx := v_emp_rec_tab.next(l_idx); end loop; Otherwise you will get an exception when your table indexes are not consecutive. See here
[ "stackoverflow", "0002473436.txt" ]
Q: abstract method signature, inheritance, and "Do" naming convention I'm learning about design patterns and in examples of code I've seen a convention where the abstract class declares a method, for example: public abstract class ServiceBase { ... public virtual object GetSomething(); and then protected abstract object DoGetSomething(); My question is on why these two methods exist, since they appear to serve the same purpose. Is this so that the base class GetSomething() method logic cannot be overridden by inherited classes? But then again, the method is marked virtual, so it can be overridden anyway. What is the usefulness here in requiring derived class implementers to implement the abstract method when the virtual method can be called anyway? A: One common reason is to put standard handling around the abstract method. For example, perhaps the abstract method can only be called in certain circumstance -- say, after the splines have been reticulated. In that case, it makes sense to check _areSplinesReticulated in one place -- the public GetSomething method -- rather than requiring every implementation of the abstract method to perform its own checking. Or maybe GetSomething is 90% boilerplate but requires a bit of additional logic or a crucial piece of information that only derived classes can supply. This is a form of the Template Method pattern. A non-virtual GetSomething means every derived class gets the standard handling and only gets to participate via their custom version of DoGetSomething. If GetSomething is virtual, that means derived classes can bypass the standard handling if they want to. Either of these is a viable strategy depending on whether the standard GetSomething handling is integral to the class logic (e.g. invariants) or whether the base class wants to grant maximum flexibility to derived classes.
[ "stackoverflow", "0062761565.txt" ]
Q: Reading Multiple Attribute in JSON using node js I am able to validate a single JSON object, but I want to validate an array of JSON objects like below, and console the invalid Pincode city name: var RuleEngine = require("node-rules"); var R = new RuleEngine(); var fact = [{ "name": "Person", "website": "Udemy", "transactionTotal": 400, "cardType": "Credit Card", "statuscode": 200, "details": { "city": "Kirochnaya ", "pincode": 191015 } }, { "name": "Person2", "website": "Udemy", "transactionTotal": 900, "cardType": "Credit Card", "statuscode": 200, "details": { "city": "Kirochnaya ", "pincode": 191015 } }, { "name": "Person3", "website": "Udemy", "transactionTotal": 800, "cardType": "Credit Card", "statuscode": 200, "details": { "city": "Saint Petersburg", "pincode": 191123 } }]; var rule = { "condition": function (R) { console.log(this); R.when(this.details.city != "Kirochnaya"); }, "consequence": function (R) { this.result = false; this.reason = " Failed validation bcos city name is not matched"; R.stop(); } }; R.register(rule); R.execute(fact, function (data) { if (data.result) { console.log("Valid statuscode"); } else { console.log("Blocked Reason:" + data.reason); } }); For the above code expected output is : Failed validation bcos city name is not matched: Saint Petersburg 191123 A: You can loop through the array and execute the rule for each fact: var rule = { "condition": function (R) { console.log(this); R.when(this.details.city != "Kirochnaya"); }, "consequence": function (R) { this.result = false; this.reason = " Failed validation bcos city name is not matched: " + this.details.city + " " + this.details.pincode; R.stop(); } }; R.register(rule); fact.forEach(check => { R.execute(check, function (data) { if (data.result) { console.log("Valid statuscode"); } else { console.log("Blocked Reason:" + data.reason); } }); });
[ "tex.stackexchange", "0000031199.txt" ]
Q: CVPR Style in draft mode fails to compile pstricks figure I'm new to this pstricks figures. So I apologize if my question is very basic. So this is the problem. I have a style from CVPR, cvpr.sty, and a figure that I create using a script that creates figures from MATLAB using pstricks. So I have my figure fig1.tex, which I intend to include in a document like this example: \documentclass[twocolumn]{article} \usepackage{cvpr} \usepackage[pdf]{pstricks} \usepackage{pst-node, pst-plot, pst-circ} \usepackage{moredefs} \cvprfinalcopy % Comment this line and it stop working! :( \ifcvprfinal\pagestyle{empty}\fi \begin{document} \begin{figure} \input{fig1.tex} \end{figure} \end{document} However, if I enable the draft mode by commenting the \cvprfinalcopy it stops working and I obtain the error MiKTeX GPL Ghostscript 9.00: Unrecoverable error, exit code 1 I think that there is some problem with the draft mode and the numbers it adds. Because in final mode the figure is generated and I get no error. However, I'm new to pstricks, so I have no idea where to look. Can someone point me in the right direction? PS. I paste the files in other site, I'm not sure if that is OK, or if I should paste them in this same question? A: this works: \documentclass{article} \usepackage[pdf]{pstricks} \usepackage{pst-node, pst-plot, pst-circ} \usepackage{moredefs} \usepackage{CVPR} \def\cvprPaperID{} %\cvprfinalcopy % Comment this line and it stop working! :( \ifcvprfinal\pagestyle{empty}\fi \begin{document} \begin{figure} \input{fig1.tex} \end{figure} \end{document} Change the loading order of the packages and define a paper ID if it is not a final paper!
[ "stackoverflow", "0053293923.txt" ]
Q: how to get all fields of related model in django instead of only id models.py from django.db import models class SeekerRegister(models.Model): seeker_name = models.CharField(max_length=32) seeker_email = models.CharField(max_length=32) class Social(models.Model): social_links = models.CharField(max_length=256) user = models.ForeignKey(access_models.SeekerRegister,on_delete=models.CASCADE,related_name='social',null=True,blank=True) my query: >>>obj=list(SeekerRegister.objects.values('social')) >>>[{'social': 1}, {'social': 2}, {'social': 3}] expecting: [{'social_links': 'facebook.com','user':1,'seeker_name':'a'}, {'social_links': 'twitter.com','user':2,'seeker_name':'b'}, {'social_links': 'linkedin.com','user':3,'seeker_name':'c'}] when i am writing the above query i am getting only id of social model. how can i get all fields both social_links and user instead. please have a look into my code. A: You can try like this: SeekerRegister.objects.values('social__social_link', 'id', 'seeker_name') where social__social_link is the social_link and id is user Pleas check this SO Answer for more details.
[ "stackoverflow", "0060815277.txt" ]
Q: Custom python logging handler looping continuously I'm running into some sort of looping issue attempting to implement logging in my project using a custom handler so I'm seeking for help. I do have some programming experience but I'm pretty new to python so maybe I get this all wrong. As shown below, I get a "RecursionError". I've also attached a truncated copy of the error as well as the code at the end of this post. Thanks in advance ! Error: Traceback (most recent call last): File "app.py", line 18, in <module> logger.debug('debug message!') File "/usr/lib/python3.8/logging/__init__.py", line 1422, in debug self._log(DEBUG, msg, args, **kwargs) File "/usr/lib/python3.8/logging/__init__.py", line 1577, in _log self.handle(record) File "/usr/lib/python3.8/logging/__init__.py", line 1587, in handle self.callHandlers(record) File "/usr/lib/python3.8/logging/__init__.py", line 1649, in callHandlers hdlr.handle(record) File "/usr/lib/python3.8/logging/__init__.py", line 950, in handle self.emit(record) File "/app/python/logger_handlers.py", line 27, in emit requests.post(self.url, headers = header, data = json.dumps(payload)) [...truncated...] RecursionError: maximum recursion depth exceeded in comparison # app.py import logging import my_module from logger_handlers import CustomHandler logging.getLogger("requests").disabled = True logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # Custom handler custom_handler = CustomHandler(url = 'http://some_url.com/api/1/log') custom_handler.setLevel(logging.DEBUG) custom_handler.setFormatter(formatter) logger.addHandler(custom_handler) # Log to root handler logger.debug('debug message!') # Run a function in a different module that also has a logger defined my_module.run() # my_module.py import logging log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) def run(): log.debug('A message from A Module') # logger_handlers.py import logging import requests import json from socket import gethostname, gethostbyname class CustomHandler(logging.Handler): def __init__(self, *args, **kwargs): super().__init__() self.url = kwargs['url'] def emit(self, record): message = self.format(record) header = {"content-type": "application/json"} payload = { "token":None, "client_version":"", "parameters": { "source": "Host: {} ({}), Module: {}, {}".format(gethostname(), gethostbyname(gethostname()), record.filename, record.funcName), "severity": record.levelname, "message": message } } requests.post(self.url, headers = header, data = json.dumps(payload)) UPDATE (2020-04-03): By using this snippet I was able to identify all the loggers I had to disable to avoid the loop: for key in logging.Logger.manager.loggerDict: print(key) I then use this to disable them: logging.getLogger("urllib3.util.retry").disabled = True logging.getLogger("urllib3.util").disabled = True logging.getLogger("urllib3").disabled = True logging.getLogger("urllib3.connection").disabled = True logging.getLogger("urllib3.response").disabled = True logging.getLogger("urllib3.connectionpool").disabled = True logging.getLogger("urllib3.poolmanager").disabled = True logging.getLogger("requests").disabled = True Not super pretty but it works. Please feel free to comment if you think there's a major drawback to this method. A: When doing a request with the requests module logs are created. Some from the requests logger but also some from other libraries that are used. The urllib module for example also has a logger that creates logs. These logs propagate up the log hierarchy and end up in the root logger. The root logger also has your handler, and thus will again do q request, creating more logs that end up at the root logger. Only add your handler to loggers that requests logs don't propagate to.
[ "math.stackexchange", "0001499936.txt" ]
Q: Free $\mathbb{Z}_{2}$ action on the plane Motivated by the following question we ask: Is there a free action of $\mathbb{Z}_{2}$ by homeomorphism on $\mathbb{R}^{2}$? Lie groups with no free $\mathbb{Z}/2\mathbb{Z}$ action A: We have an integer invariant of topological spaces, called the euler characteristic. This has two special properties, namely that for a covering map $X\to Y$, with fiber $F$, we have $\chi(X)=\chi(Y)|F|$. In this case, if the action is free, the map $\mathbb{R}^2\to \mathbb{R}^2/\{gx=x\}=Q$ is a covering map with fiber $\mathbb{Z}/(2)$, so that we have that $\chi(\mathbb{R}^2)=2\chi(Q)$, so that $\chi(\mathbb{R}^2)$ is even. But you can easily compute that $\chi(\mathbb{R}^2)=1$, so we have our contridiction!
[ "stackoverflow", "0033559028.txt" ]
Q: Meteor: How do I check if a collection exists I am using accounts entry, and as you may know, it doesn't allow taking you to separate pages on signup and signin. So, what I want to do is check if a field called under profile called "avatar" exists. I just want a true or false answer (or null, -1, etc). How can I do this? A: Here's a function that will return a boolean indicating if the avatar field exists in the current user's profile: var hasAvatar = function() { var user = Meteor.user(); return user && user.profile && user.profile.avatar; };
[ "stackoverflow", "0013247239.txt" ]
Q: Spring MVC Controller: Redirect without parameters being added to my url I'm trying to redirect without parameters being added to my URL. @Controller ... public class SomeController { ... @RequestMapping("save/") public String doSave(...) { ... return "redirect:/success/"; } @RequestMapping("success/") public String doSuccess(...) { ... return "success"; } After a redirect my url looks always something like this: .../success/?param1=xxx&param2=xxx. Since I want my URLs to be kind of RESTful and I never need the params after a redirect, I don't want them to be added on a redirect. Any ideas how to get rid of them? A: In Spring 3.1 a preferred way to control this behaviour is to add a RedirectAttributes parameter to your method: @RequestMapping("save/") public String doSave(..., RedirectAttributes ra) { ... return "redirect:/success/"; } It disables addition of attributes by default and allows you to control which attributes to add explicitly. In previous versions of Spring it was more complicated. A: In Spring 3.1 use option ignoreDefaultModelOnRedirect to disable automatically adding model attributes to a redirect: <mvc:annotation-driven ignoreDefaultModelOnRedirect="true" /> A: Adding RedirectAttributes parameter doesn't work for me (may be because my HandlerInterceptorAdapter adds some stuff to model), but this approach does (thanks to @reallynic's comment): @RequestMapping("save/") public View doSave(...) { ... RedirectView redirect = new RedirectView("/success/"); redirect.setExposeModelAttributes(false); return redirect; }
[ "stackoverflow", "0019661245.txt" ]
Q: Rotating child elements in wrapper + Button Navigation @j08691 answered the question How to continuously rotate children in a jQuery animation? with a nice example. However, I need to expand his example and can't see how to do it dynamically. This is a small graphic of what I have: The gray box is my banner-group, which contains the fading 4 banneritems. The green boxes are my buttons 1 to 4. Clicking on button 1 should display banneritem 1 and hide all the others. The rotating process should continue with banneritem 2 then. If I click on button 4, it should display banneritem 4. jsfiddle: http://jsfiddle.net/wxvTp/ html: <div class="col3 bannergroup"> <div class="banneritem"> <h1>Lorem Ipsum 1</h1> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <a href="#" title="Jetzt unverbindliches Angebot anfordern" class="btn orange">Wir freuen uns auf Ihr Projekt.</a> </div> <div class="banneritem"> <h1>Lorem Ipsum 2</h1> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <a href="#" title="Jetzt unverbindliches Angebot anfordern" class="btn orange">Wir freuen uns auf Ihr Projekt.</a> </div> <div class="banneritem"> <h1>Lorem Ipsum 3</h1> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <a href="#" title="Jetzt unverbindliches Angebot anfordern" class="btn orange">Wir freuen uns auf Ihr Projekt.</a> </div> <div class="banneritem"> <h1>Lorem Ipsum 4</h1> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <a href="#" title="Jetzt unverbindliches Angebot anfordern" class="btn orange">Wir freuen uns auf Ihr Projekt.</a> </div> <div class="slider-control-nav desktop"> <!-- buttons are here --> <a class="button1" href="#"> <img src="images/icon-slider-control-cs.png" alt="Grafikdesign" /> </a> <a href="#" class="button2"> <img src="images/icon-slider-control-gd.png" alt="Content Strategy" /> </a> <a class="button3" href="#"> <img src="images/icon-slider-control-wd.png" alt="Grafikdesign" /> </a> <a class="button4" href="#"> <img src="images/icon-slider-control-cs.png" alt="Content Strategy" /> </a> </div> </div> EDIT: This is what I tried, however, it is a) not working, b) would have to be done for all 4 buttons. $( ".button4" ).click(function() { $('div.bannergroup').each(function () { $('div.banneritem', this).not(':nth-child(4)').hide(); var thisDiv = this; setInterval(function () { var idx = $('div.banneritem', thisDiv).index($('div.banneritem', thisDiv).filter(':visible')); $('div.banneritem:eq(' + idx + ')', thisDiv).fadeOut(0, function () { idx++; if (idx == ($('div.text', thisDiv).length)) idx = 0; $('div.banneritem', thisDiv).eq(idx).fadeIn(600); }); }, 6000); }); }); A: Take a look at this: http://jsfiddle.net/Palpatim/TfK4J/6/ Some notes on your previous code: Set your .banneritems initial state using CSS rather than jquery. Less work for the browser, and less likely to get a "flash" of content as jquery figures out what should be hidden and shown. You were doing a lot of work in the setInterval call, but really all you wanted to do was display a new banner. Refactor your code as much as possible to reduce the work being done in the interval Good luck. [EDIT: Corrected fiddle URL to the one that has display:block on the banneritem:first-child]
[ "stackoverflow", "0014377273.txt" ]
Q: Calculating distance between two points shows wrong distance I use below two ways to calculate distance between two points in google maps using latitude and longitude. TYPE I: function CalcDistanceBetween(lat1, lon1, lat2, lon2) { //Radius of the earth in: 1.609344 miles, 6371 km | var R = (6371 / 1.609344); var R = 6371; // Radius of earth in Miles var dLat = toRad(lat2-lat1); var dLon = toRad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; alert("d==" + d); return d; } alert(CalcDistanceBetween(13.125511084202,80.029651635576,12.9898593006481,80.2497744326417)); function toRad(Value) { /** Converts numeric degrees to radians */ return Value * Math.PI / 180; } TYPE II: var p1 = new google.maps.LatLng(13.125511084202,80.029651635576); var p2 = new google.maps.LatLng(12.9898593006481,80.2497744326417); alert(calcDistance(p1, p2)); //calculates distance between two points in km's function calcDistance(p1, p2){ return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2); } Above both types gives 28 kms as distance. But when i check in google maps with same langitude and longitude it returns 36.8 kms. Sample Check in My Code & google maps Shown Below..: Do u suggest me for get accurate results?? A: The distance given by Google is from the suggested route. It's not a direct path from point A to point B. The distance you computed is the direct path, which would only be the case if you flew directly from A to B. If you want to get the result that Google outputs, look here: An elegant way to find shortest and fastest route in Google Maps API v3?
[ "stackoverflow", "0033825176.txt" ]
Q: Parallel Inserts/Updates in a SQL Server table I have a multithread environment and every thread wants to select a row (or insert it if it does not exist) in a table and increment something in it. Basically, every thread does something like this : using (var context = new Entity.DBContext()) { if(!context.MyTable.Any(...)) { var obj = new MyTable() { SomeValue = 0 }; context.MyTable.Add(obj) } var row = context.MyTable.SingleOrDefault(...); row.SomeValue += 1; context.SaveChanges(); } Problem in a example : a specific row has SomeValue = 0. Two thread select this specific row at the same time, they both see 0. -> they both increment it one time, and the final result in SomeValue will be 1, but we want it to be 2. I assume that the thread that arrives just after the other should wait (using a lock ?) for the first one to be over. But i can't make it work properly. Thanks. A: Assuming SQL Server, you can do something like this: create table T1 ( Key1 int not null, Key2 int not null, Cnt int not null ) go create procedure P1 @Key1 int, @Key2 int as merge into T1 WITH (HOLDLOCK) t using (select @Key1 k1,@Key2 k2) s on t.Key1 = s.k1 and t.Key2 = s.k2 when matched then update set Cnt = Cnt + 1 when not matched then insert (Key1,Key2,Cnt) values (s.k1,s.k2,0) output inserted.Key1,inserted.Key2,inserted.Cnt; go exec P1 1,5 go exec P1 1,5 go exec P1 1,3 go exec P1 1,5 go (Note, it doesn't have to be a procedure, and I'm just calling it from one thread to show how it works) Results: Key1 Key2 Cnt ----------- ----------- ----------- 1 5 0 Key1 Key2 Cnt ----------- ----------- ----------- 1 5 1 Key1 Key2 Cnt ----------- ----------- ----------- 1 3 0 Key1 Key2 Cnt ----------- ----------- ----------- 1 5 2 Even with multiple threads calling this, I believe that it should serialize access. I'm producing outputs just to show that each caller can also know what value they've set the counter to (here, the column Cnt), even if another caller immediately afterwards changes the value.
[ "stackoverflow", "0051429836.txt" ]
Q: RabbitMQ - Consuming messages from queue in microservices I am trying to integrate RabbitMQ as a messaging queue in my existing microservice project. I currently have a Send function written which takes a string message and publishes to a named queue. Now, I am trying to write the Receive function and here is what I have so far: public static void Receive(string queueName) { using (IConnection connection = GetConnection(LOCALHOST)) { using (IModel channel = connection.CreateModel()) { channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false, arguments: null); // Don't dispatch a new message to a consumer until it has processed and acknowledged the previous one. channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new EventingBasicConsumer(channel); // non-blocking consumer.Received += (model, e) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); // At this point, I can do something with the message. }; channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer); } } } I think that is okay but I have a few questions on parts that I am confused on. 1) I don't quite understand what the Received field is and why it is appending an anonymous function in which we do the actual work after receiving. 2) What is BasicConsume doing? Does the actual receiving happen with BasicConsume or the Received field? Does BasicConsume have to occur after the Received field assign? 3) Finally, I have, say, two microservices that need to consume from a queue. I thought that I can just call Receive in those two microservices respectively. Will it continually listen for messages or do I need to place the Receive call in a while loop? Thanks for your help and illumination. A: 1) Received is actually an event. So, calling consumer.Received += (model, e) => {}; you're subscribing to it, but it's not necesseraly an anonimous function, it can be like: consumer.Received += OnReceived; .... private static void OnReceived(object model, BasicDeliverEventArgs e) { var body = ea.Body; var message = Encoding.UTF8.GetString(body); // At this point, I can do something with the message. } It is executed each time you recieve a message. 2) BasicConsume starts a consumer of your channel, which you created before. The function in Recieved will be executed. 3) They will continually listen the channel in case of using EventingBasicConsumer. It may require a loop for another type of Consumer
[ "unix.stackexchange", "0000432971.txt" ]
Q: Error for the following command sudo apt-get update (Some errors have been excluded) Err http://ppa.launchpad.net trusty/main i386 Packages 404 Not Found Translation-en_IN Ign http://packages.linuxmint.com rebecca/upstream Translation-en Fetched 284 kB in 11s (23.9 kB/s) Reading package lists... Done W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://extra.linuxmint.com rebecca Release: The following signatures were invalid: BADSIG 3EE67F3D0FF405B2 Clement Lefebvre (Linux Mint Package Repository v1) <[email protected]> W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty/Release Unable to find expected entry 'restricted/binary-amd64/Packages' in Release file (Wrong sources.list entry or malformed file) W: Failed to fetch http://packages.linuxmint.com/dists/rebecca/main/binary-i386/Packages Hash Sum mismatch W: Failed to fetch http://ppa.launchpad.net/chris-lea/munin-plugins/ubuntu/dists/trusty/main/source/Sources 404 Not Found W: Failed to fetch http://ppa.launchpad.net/chris-lea/munin-plugins/ubuntu/dists/trusty/main/binary-amd64/Packages 404 Not Found W: Failed to fetch http://ppa.launchpad.net/chris-lea/munin-plugins/ubuntu/dists/trusty/main/binary-i386/Packages 404 Not Found W: Some index files failed to download. They have been ignored, or old ones used instead. A: Try sudo rm -rf /var/lib/apt/lists/* Then sudo apt-get update
[ "math.stackexchange", "0000461406.txt" ]
Q: Chi square proof with Exp law For an exercice in Statistics, For $ X \sim Exp(\theta)$ I have to proof that : $ (\dfrac{2} {\theta}) \sum_{i=1}^{12} X_i \sim X^2(24)$ And with this result, I have to found a best critic region with $\alpha = 0.1$ Is there anyone that can help with the proof. I can do the rest. (Sorry for English terms that not matching, my course is in french) A: I found the answer as you said @André Nicolas, With the moment generating function of the exponential and a small trick, you can have the moment generating function of the chi-square with 2n degree.
[ "math.stackexchange", "0003792778.txt" ]
Q: All nondegenerate bilinear symmetric forms on a complex vector space are isomorphic All nondegenerate bilinear symmetric forms on a complex vector space are isomorphic. Does this mean that given a nondegenerate bilinear symmetric forms on a complex vector space that you can choose a basis for the vector space such that the matrix representation of the bilinear form is the identity matrix? Can somebody help explain to me why this is? I'm thinking that a matrix with entries in $\mathbb{C}$ is going to have a characteristic equation that splits into linear factors (with multiplicities) and so will be diagonalizable, but still can't quite put these pieces together. Insights appreciated! A: The answer is yes. First, a proof that the bilinear forms are isomorphic. Note that it suffices to prove that this holds over $\Bbb C^n$. First, I claim that every invertible, complex, symmetric matrix can be written in the form $A = M^TM$ for some complex matrix $M$. This can be seen, for instance, as a consequence of the Takagi factorization. Now, let $Q$ denote a symmetric bilinear form over $\Bbb C^n$, and let $A$ denote its matrix in the sense that $Q(x_1,x_2) = x_1^TAx_2$. Let $Q_0$ denote the canonical bilinear form defined by $Q_0(x_1,x_2) = x_1^Tx_2$. We write $A = M^TM$ for some invertible complex matrix $M$. Define $\phi:(\Bbb C^n, Q) \to (\Bbb C^n, Q_0)$ by $\phi(x) = Mx$. It is easy to verify that $\phi$ is an isomormphism of bilinear product spaces, so that the two spaces are indeed isomorphic. With all that established: we can see that the change of basis $y = Mx$ is such that $Q(x_1,x_2) = y_1^Ty_2$.
[ "stackoverflow", "0037872140.txt" ]
Q: Using dpkt to parse through pcap files I'm doing an assignment where I have to parse through a pcap file and I am using dpkt to do so. I'm new to networking so I'm having a really hard time debugging the code / getting started. First set of code: import dpkt filename='test.pcap' f = open(filename) pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data f.close() Error is AttributeError: 'str' object has no attribute 'data' So from a previous Stackoverflow I found out that maybe I'm supposed to "skip the dpkt ethernet decode and jump straight to an IP decode" so I altered the code and go to: import dpkt filename='test.pcap' f = open(filename) pcap = dpkt.pcap.Reader(f) for ts,buf in pcap: ip = dpkt.ip.IP(buf) tcp = ip.data f.close() The error it is giving me now is "UnpackError: invalid header length" Don't really understand how to move forward with this, any help would be greatly appreciated A: I had this same problem for traces I took on my phone. This was due to ethernet being replaced by Linux Cooked Capture. If your traces are encapsulated similarly, you'll have to use dpkt.sll.SLL(buff) rather than dpkt.ethernet.Ethernet(buf). Here's an example: import dpkt filename='a_linux_cooked_capture.pcap' f = open(filename, 'rb') pcap = dpkt.pcap.Reader(f) for ts, buf in pcap: eth = dpkt.sll.SLL(buf) ip = eth.data tcp = ip.data f.close()
[ "stackoverflow", "0045242925.txt" ]
Q: Angular 4 Firebase Read data from database and display to browser I am learning Angular 4 and I am using firebase database.But I am completly lost on how I can make the objects apear on the browser of my application. I currently want to take all the data from users and display them on the browser. import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import * as firebase from 'firebase/app'; @Component({ selector: 'app-about', templateUrl: './about.component.html', styleUrls: ['./about.component.css'] }) export class AboutComponent implements OnInit { constructor() { var allUsers = firebase.database().ref('users/'); var db = firebase.database().ref('/users/'); // Attach an asynchronous callback to read the data at our posts reference db.on("value", function(snapshot) { console.log(snapshot.val()); }, function (errorObject) { console.log("The read failed: " + errorObject.code); }); } ngOnInit() { } } Everything works fine and I can see my data on the console.But can you help me on how I can make the data on the console apear on the browser?? A: Well there is no need to use console.log() if you want to display data on Browser.Angularfire has its own functions for this. This link focus exactly on your problem Here is an example that takes all the users name from a database and displays them as a list import { Component, OnInit } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable,FirebaseObjectObservable } from 'angularfire2/database'; import * as firebase from 'firebase/app'; @Component({ selector: 'app-about', templateUrl: './about.component.html', styleUrls: ['./about.component.css'] }) export class AboutComponent implements OnInit { users:FirebaseListObservable<any>;; constructor(db2: AngularFireDatabase) { this.users = db2.list('users'); } ngOnInit() { } And the following Html code <div class="container"> <p>Show all users</p> <ul> <li *ngFor="let user of users | async"> {{ user.name | json }} </li> </ul> </div> Hope it reduced your confusion on the matter.If you didnt understant something plz ask me again
[ "sharepoint.stackexchange", "0000013932.txt" ]
Q: Programatically add a content type to a document library I have an event-handler feature that changes the content type of an item when it is added to a document library, however this will only work if the content type is allowed for that document library. My feature needs to be able to create this content type if it does not already exist before assigning it to an item, however I most likely will also need to add it to the specific document libraries before it becomes usable. Is it is simple as just adding the content type to the list of the content types for the document library? : SPListItem listItem = properties.ListItem; SPList list = properties.ListItem.ParentList; SPContentType baseContentType = web.ContentTypes[SPBuiltInContentTypeId.Document]; SPContentType type = new SPContentType(baseContentType, web.ContentTypes, "Custom Folder"); type.Fields.Add("Users", SPFieldType.User, false); list.ContentTypes.Add(type); list.Update(); Side question (bonus points ;) - The "Users" field above should be a multi-select people-picker field. Will the above work to create this field? Thanks A: You'll need to add the field to the content type using SPContentType.FieldLinks - as SPContentType.Fields is read-only. As for creating the content type, I recommend first creating it at the RootWeb level, as a Site content type. Get the parent one from SPWeb.AvailableContentTypes. Add your field links. Then add this new content type to the SPList.ContentTypes collection (using SPList.ContentTypes.Add()).
[ "math.stackexchange", "0000377253.txt" ]
Q: The fiber $f^{-1}(a)$ is a discrete (and countable) set Let $f:ℝ→ℝ$ be a real analytic function. Then my question is: Show that for a real number $a$, the fiber $f^{-1}(a)$ is a discrete (and countable) set unless $f = a$. A: This should be trivial if you have the identity theorem for ananlytic functions, but here's how to show it directly: Assume $f^{-1}(a)$ has a limit point $c$. Then there is a strictly monotonic sequence $x_n\to c$ with $f(x_n)=a$. Hence between $x_n$ and $x_{n+1}$ there exists a $\xi_n$ with $f'(\xi_n)=0$ and by continuity $f'(c)=f'(\lim \xi_n)=\lim f'(\xi_n)=0$. That is, $c$ is a limit point of $(f')^{-1}(0)$. By induction, $c$ is limit point of $(f^{(n)})^{-1}(0)$ for all $n\ge 1$, hence $f^{(n)}(c)=0$ for all $n\ge 1$ and the Taylor expansion around $c$ is constant. Let $u=\inf\{x\in\mathbb R\colon f|_{[x,c]}=a\}$. If $u\ne-\infty$, then $u$ is a limit point of $f^{-1}(a)$ and by what we just saw, $f=a$ on an open neighbourhood of $c$, contradicting the definition of $u$ as $\inf$; we conclude $u0-\infty$. Similarly, $\sup\{x\in\mathbb R\colon f|_{[c,x]}=a\}=+\infty$ and ultimately $f=a$. Therefore, unless $f$ is constant, $f^{-1}(a)$ is discrete. As a discrete subset of $\mathbb R$, it is at most countable.
[ "stackoverflow", "0003798935.txt" ]
Q: php replace parameter $s = "{$i}<br>"; for ($i=0; $i<10; $i++) { f($s); } function f( $a ) { echo $a; } How can I replace $i with current value? A: Place $s = "{$i}<br>"; inside the loop as: for ($i=0; $i<10; $i++) { $s = "{$i}<br>"; f($s); }
[ "mathoverflow", "0000242522.txt" ]
Q: Structure of a real 3x3 positive-semidefinite matrix whose eigenvalues verify the triangle inequalities It is known that a 3 by 3 real symmetric matrix $A$ has an eigendecomposition $$ A = Q E Q^T $$ where $Q$ is an orthogonal matrix and $E$ is a diagonal matrix whose elements, $E_{11}$, $E_{22}$ and $E_{33}$, are the eigenvalues of $A$. Moreover, if those eigenvalues are non-negative then $A$ is positive-semidefinite. The question is: if those eigenvalues are not only non-negative but also verify the triangle inequalities $$ \begin{aligned} E_{11} + E_{22} &\geq E_{33}\\ E_{11} + E_{33} &\geq E_{22}\\ E_{22} + E_{33} &\geq E_{11} \end{aligned} $$ is there anything special about the structure of $A$ besides the fact that it is positive-semidefinite? Can those extra triangle inequalities constraints be written as functions of the elements of $A$, just like the positive-semidefinite constraints can be written down using the Sylvester's criterion? Can those extra constraints be somehow represented in a semidefinite programming / linear matrix inequalities framework? A: Condition $$E_{11}+E_{22}\ge E_{33}$$ is equivalent to $$E_{11}+E_{22}+E_{33}\ge 2 E_{33}$$ or $$E_{33} \le \frac12 tr\ A$$ since the sum of eigenvalues is equal to the trace. Combining with the other two conditions gives $$\lambda_{max}(A) \le \frac12 tr\ A$$ which is semidefinite representable as $$A \preceq \frac12(A_{11}+A_{22}+A_{33}) I$$
[ "stackoverflow", "0002001203.txt" ]
Q: Referencing an unmanaged C++ project within another unmanaged C++ project in Visual Studio 2008 I am working on a neural network project that requires me to work with C++. I am working with the Flood Neural Network library. I am trying to use a neural network library in an unmanaged C++ project that I am developing. My goal is to create an instance of a class object within the Flood library from within another project. There is plenty of documentation online regarding how to reference an unmanaged C++ project from within a C# project, but there is not enough information on how to reference one C++ project within another. Similar to how I would do it in C#, I added the Flood project as a reference in my other project, but I have tried all sorts of techniques to work with the object. I have attempted to use the #include directive to reference the header file, but that gives me errors stating that I need to implement the methods declared in the header file. How to add a reference in unmanaged C++ and work with the class objects? A: Yes. You need to do two things: #include the respective header files, as you did Add a reference (Visual C++ supports two types, "dependencies" which are outdated and should not be used anymore, and "references" which are the correct ones). Use them to reference the other project, which must be a part of your solution. Meaning, in this case you must be able to COMPILE the other project. Alternatively, if you do not have the source code, or you do not wish to compile the 3rd-party code for any other reason, you may also reference a compiled binary. The best way to do it is pragma comment lib. If this is what you need, please comment and I will edit my response.
[ "tex.stackexchange", "0000524372.txt" ]
Q: Include appendix figures/tables in Lof/Lot, but with some space from the last chapter I have one question about spacing in the List of Figures/Tables. My thesis has some figures and tables in the appendix; when I set the follwing code to let them be visible in the Lot/Lof, there is no spacing between, for example, the first figure of the Appendix and the last one of a chapter. But, this spacing is present when figures come from different chapters. Here is a MWE to have an idea of what I'm saying. I don't know whether it is feasible or not, I'm not that good at Latex. If anyone has any tips, please let me know, thanks! \documentclass[11pt,twoside, openright, cleardoublepage=empty]{book} \usepackage[font=small,format=hang,labelfont={sf,bf}]{caption} \usepackage{graphicx} \PassOptionsToPackage{hyphens}{url} \usepackage{hyperref} \begin{document} \frontmatter \tableofcontents\listoftables\listoffigures \mainmatter \chapter{First} \section{one} \section{two} \section{three} One image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-c} \caption[Capital letter C]{This is capital letter C} \label{fig:my_label} \end{figure} and a table: \begin{table}[ht] \centering \begin{tabular}{|c|c|} \hline 1 & 2 \\ \hline \end{tabular} \caption[1 and 2 data table]{This is a table with 1 and 2} \label{Table} \end{table} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Second} Another image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-golden} \caption[Golden]{This is golden image} \label{fig:my_label} \end{figure} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter*{Appendix} \renewcommand\thefigure{A.\arabic{figure}} \setcounter{figure}{0} \renewcommand\thetable{T.\arabic{table}} \setcounter{table}{0} Another image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-b} \caption[Capital letter B]{This is capital letter B} \label{fig:my_label} \end{figure} and another table: \begin{table}[ht] \centering \begin{tabular}{|c|c|} \hline 3 & 4 \\ \hline \end{tabular} \caption[3 and 4 data table]{This is a table with 3 and 4} \label{Table} \end{table} \end{document} A: The easiest solution is probably to add \appendix before the chapter Appendix, and to number the chapter. After that, the \titleformat command from the titlesec package can be used to format the Appendix chapter title so it will appear as if it was unnumbered. \documentclass[11pt,twoside, openright, cleardoublepage=empty]{book} \usepackage[font=small,format=hang,labelfont={sf,bf}]{caption} \usepackage{graphicx} \PassOptionsToPackage{hyphens}{url} \usepackage{titlesec} \usepackage{hyperref} \begin{document} \frontmatter \tableofcontents\listoftables\listoffigures \mainmatter \chapter{First} \section{one} \section{two} \section{three} One image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-c} \caption[Capital letter C]{This is capital letter C} \label{fig:my_label} \end{figure} and a table: \begin{table}[ht] \centering \begin{tabular}{|c|c|} \hline 1 & 2 \\ \hline \end{tabular} \caption[1 and 2 data table]{This is a table with 1 and 2} \label{Table} \end{table} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \chapter{Second} Another image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-golden} \caption[Golden]{This is golden image} \label{fig:my_label} \end{figure} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \appendix \titleformat{\chapter}[display] {\normalfont\huge\bfseries}{}{-\baselineskip}{\Huge} \chapter{Appendix} \renewcommand\thetable{T.\arabic{table}} Another image \begin{figure}[ht] \centering \includegraphics[scale=0.25]{example-image-b} \caption[Capital letter B]{This is capital letter B} \label{fig:my_label} \end{figure} and another table: \begin{table}[ht] \centering \begin{tabular}{|c|c|} \hline 3 & 4 \\ \hline \end{tabular} \caption[3 and 4 data table]{This is a table with 3 and 4} \label{Table} \end{table} \end{document}
[ "stackoverflow", "0019755102.txt" ]
Q: django-allauth change user email with/without verification I am using plain django-allauth without any social accounts. Every user should have exactly one email address associated with his account, i.e. the one that was used for registration/verification. I would like to enable my users to change this email. So my first question is, should I have the new email being verified again by sending out the verifcation email? My gut feeling says, I better have this new email being verified. But I have no real arguments for that. My second question is, if if want that to be verified, is that process somehow supported already with django-allauth? I have seen the EmailView and AddEmailForm. But those are based on the assumption that one account can have more than 1 email address (which is not what I want). Thanks A: I think the new email address should be verified. If your application sends periodic emails, you don't want to fire off loads of emails to just any email address that a user enters. What I did was allow multiple email addresses until the second email is verified. Then, listen for django-allauth's email_confirmed signal as elssar suggested. As soon as the address is verified, set the new email address as the primary email, then delete any previous EmailAddess. Here's a simplified example of what I ended up doing: models: from django.dispatch import receiver from allauth.account.models import EmailAddress from allauth.account.signals import email_confirmed class CustomUser(models.Model): ... def add_email_address(self, request, new_email): # Add a new email address for the user, and send email confirmation. # Old email will remain the primary until the new one is confirmed. return EmailAddress.objects.add_email(request, self.user, new_email, confirm=True) @receiver(email_confirmed) def update_user_email(sender, request, email_address, **kwargs): # Once the email address is confirmed, make new email_address primary. # This also sets user.email to the new email address. # email_address is an instance of allauth.account.models.EmailAddress email_address.set_as_primary() # Get rid of old email addresses stale_addresses = EmailAddress.objects.filter( user=email_address.user).exclude(primary=True).delete() views: def update_user_details(request): user = request.user new_email = request.POST.get('new_email') user.custom_user.add_email_address(request, new_email) ... A: There are a few ways you could go about doing this. Either listen to the email_confirmed signal handler, and have a function that checks whether user has two EmailAccount objects associated with his account, and if so, delete the other EmailAccount object. The other would be set EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL and EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL in your settings and have related view delete the extra email address, if it exists. Another way would be to just override the EmailView and/or AddEmailForm and have them do what you want. For changing email without confirmation, you could just have your view call the EmailAddress.change method.
[ "stackoverflow", "0063258055.txt" ]
Q: How to get a PyQt5 QPushButton to do different commands on different button clicks I wish to have the QPushButton do different things on different clicks. One the first click it should execute one command and on the next click, it should execute the other command. I've tried to make a program to do it but it only executes one command, not the other my code I: import PyQt5.QtWidgets as pyqt import sys ongoing = False class Stuff(pyqt.QWidget): def __init__(self): super().__init__() self.windows() def windows(self): w = pyqt.QWidget() layout = pyqt.QGridLayout() self.setLayout(layout) button = pyqt.QPushButton('click me', w) layout.addWidget(button) if not ongoing: button.clicked.connect(click_one) else: button.clicked.connect(click_two) self.show() w.show() def click_one(): global ongoing print('one') ongoing = not ongoing def click_two(): global ongoing print('two') ongoing = not ongoing if __name__ == '__main__': app = pyqt.QApplication(sys.argv) x = Stuff() app.exec_() What should I do to fix this? A: Since the value of ongoing is False when the class is initialized, the button's clicked signal gets connected to click_one(). Connect the button to an initial slot and then call the desired function based on the value of ongoing. class Stuff(pyqt.QWidget): def __init__(self): super().__init__() self.windows() def windows(self): w = pyqt.QWidget() layout = pyqt.QGridLayout() self.setLayout(layout) button = pyqt.QPushButton('click me', w) layout.addWidget(button) button.clicked.connect(on_click) self.show() w.show() def on_click(): global ongoing if not ongoing: click_one() else: click_two() I suggest rewriting the code with the functions and ongoing variable belonging to the class. The QWidget assigned to variable w seems redundant because the QPushButton is then added to the layout of the class, so its parent gets changed anyways. class Stuff(pyqt.QWidget): def __init__(self): super().__init__() self.ongoing = False self.windows() def windows(self): layout = pyqt.QGridLayout(self) button = pyqt.QPushButton('click me') layout.addWidget(button) button.clicked.connect(self.on_click) self.show() def on_click(self): self.click_one() if not self.ongoing else self.click_two() self.ongoing = not self.ongoing def click_one(self): print('one') def click_two(self): print('two') Also you might be interested in using a checkable button.
[ "stackoverflow", "0006221926.txt" ]
Q: Linking to my apps on the App Store I want to create button that, when pressed, takes the user into the App Store and all my apps are shown. At the moment the code is -(IBAction)goReviewTwo:(id)sender; { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.com/apps/lifevisionstudios"]]; } But that doesn't work. Any ideas on how to do it? A: Your URL isn't correct. Apple's iTunes Link Maker is the easiest and best way to get the authoritative link to your apps, including for App Stores in various countries. You can also get a link to a page with all of your company's apps the same way, which seems to be what you're looking for. In the Link Maker your company is referred to as the Artist. Lastly, rather than using http you should use itms, which will send the user directly to the App Store app rather than routing them through a blank Mobile Safari page first: itms://itunes.apple.com/us/artist/appname/id?uo=4 Edited to add As noted in Rab's answer, if you remove the /us it should automatically go to the user's local App Store. It turns out that you also need to remove the query string (?uo=4) that iTunes and the Link Maker generate: itms://itunes.apple.com/artist/appname/
[ "math.stackexchange", "0002777621.txt" ]
Q: Prove by Induction on k. using Fibonacci Numbers $$F_{k-2}+F_{k-4}+...+F_{k\,mod\,2+2}=F_{k-1}-1, \quad \quad if\: k\geq2.$$ This equation is to prove by induction on $k;$ the left-hand side is zero when $k$ is $2$ or $3$. Therefore $k_{1}$ is the greedily chosen value described earlier, and the representation must be unique. Here is my Attempt. I have attempted to solve this problem using induction, Please if anyone confirms that my attempt is true for induction step. Or If someone helps me with this answer if anything goes wrong. $$F_{k-2}+F_{k-4}+...+F_{k\,mod\,2+2}=F_{k-1}-1 \quad \quad if\,k\geq2$$ My Attempt: Base case $k=2$ $$F_{2-2}+F_{2-4}+...+F_{2\,mod \,2+2}=F_{2-1}-1$$ As $2\, mod\,2=0$ therefore, $$F_{0}+F_{-2}+...+F_{0+2}=F_{1}-1$$ $$F_{0}+F_{-2}+...+F_{2}=F_{1}-1$$ As $F_{0}=0,\,F_{-2}=-1,\,F_{2}=1,\,and\,F_{1}=1\,$therefore, $$0+(-1)+...+1=1-1$$ $$0-1+...+1=1-1$$ $$0=0 \\ which\,\,is\,\,true\,\,the\,\,left\,\,hand\,\,side\,\,is\,\,zero\,\,when\,\,k\,\,is\,\,2.$$ Now the Induction Step: $k=k+1$ on left hand side $$F_{k+1-2}+F_{k+1-4}+...+F_{k+1\,mod\,2+2}$$ $$F_{k-1}+F_{k-3}+...+F_{k+1\,mod\,2+2}$$ As we know that $F_{k-1}=F_{k+1}+F_{k}$ and $F_{k-3}=2F_{k+1}-3F_{k}$ therefore, $$F_{k+1}+F_{k}+2F_{k+1}-3F_{k}+...+F_{k+1\,mod\,2+2}$$ $$(F_{k+1}+2F_{k+1})+(F_{k}-3F_{k})+...+F_{k+1\,mod\,2+2}$$ $$(3F_{k+1})+(-2F_{k})+...+F_{k+1\,mod\,2+2}$$ $$3F_{k+1}-2F_{k}+...+F_{k+1\,mod\,2+2}$$ A: So, we agree on understanding the meaning of the dots " ... $F_{k-2}+F_{k-4}+F_{k-6}+F_{k-8}+\cdots$ and so on till $F_{k\,mod\,2+2}$". Now we shall agree on the meaning of "till". Using the dots leads to assume (as a standard interpretation) that you mean to say $$ F_{\,k - 2} + F_{\,k - 4} + \cdots + F_{\,k\bmod 2 + 2} \quad \Rightarrow \quad \sum\limits_{1\, \le \,j\, \le \,\left\lfloor {{k \over 2}} \right\rfloor - 1} {F_{\,k - 2j} } $$ and the standard interpretation of this sum is that, whenever the index does not respect the conditions imposed, then the sum is considered null, e.g. $$ \sum\limits_{a\, \le \,k\, \le \,b} {f(k)} \quad \Rightarrow \quad \sum\limits_{a\, \le \,k\, \le \,b\quad \left| {\;b\, < \,a} \right.} {f(k)} = \sum\limits_{k\, \in \;\emptyset } {f(k)} = 0 $$ There is another interpretation of the sum allowing for the bounds to be reversed, but you do not use dots to indicate it. Coming to your problem, since $$ \eqalign{ & k - 2j = k\bmod 2 + 2\quad \Rightarrow \quad \cr & \Rightarrow \quad 2j = k - k\bmod 2 - 2 = 2\left\lfloor {{k \over 2}} \right\rfloor + k\bmod 2 - k\bmod 2 - 2 \cr & \Rightarrow \quad j = \left\lfloor {{k \over 2}} \right\rfloor - 1 \cr} $$ Then we write your recurrence as $$ \bbox[lightyellow] { F_{\,k - 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,\left\lfloor {{k \over 2}} \right\rfloor - 1} {F_{\,k - 2j} } \quad \left| {\;2 \le k} \right. } \tag{1}$$ and, it seems that, the thesis you want to demonstrate is : if the $F_k$ obeys the Fibonacci recurrence $F_{k+1}=F_{k}+F_{k-1} \quad | \; 2 \le k$ then they obey to the recurrence above. The starting conditions are $$ \eqalign{ & k = 2\quad \Rightarrow \quad F_{\,1} - 1 = \sum\limits_{1\, \le \,j\, \le \,0} {F_{\,2 - 2j} } = 0\quad \Rightarrow \quad F_{\,1} = 1 \cr & k = 3\quad \Rightarrow \quad F_{\,2} - 1 = \sum\limits_{1\, \le \,j\, \le \,0} {F_{\,3 - 2j} } = 0\quad \Rightarrow \quad F_{\,2} = 1 \cr} $$ which indicates that actually $F_1 \; F_2$ equal the respective Fibonacci N.. But let's proceed apart from initial conditions because in the thesis we did not involve the initial conditions, but only the recurrence. We can put $$ k = 2m + i\quad \left| \matrix{ \;1 \le m \hfill \cr \;i = 0,1 \hfill \cr} \right. $$ and write the system $$ \bbox[lightyellow] { \left\{ \matrix{ F_{\,2m - 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right)} } \hfill \cr F_{\,2m} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 1} } \hfill \cr} \right.\quad \Leftrightarrow \quad \left\{ \matrix{ F_{\,2m} + F_{\,2m - 1} - 2 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {\left( {F_{\,2\left( {m - j} \right)} + F_{\,2\left( {m - j} \right) + 1} } \right)} \hfill \cr F_{\,2m} - F_{\,2m - 1} = \sum\limits_{1\, \le \,j\, \le \,m - 1} {\left( {F_{\,2\left( {m - j} \right) + 1} - F_{\,2\left( {m - j} \right)} } \right)} \hfill \cr} \right. } \tag{2}$$ since the validity of a system implies the validity of the system of the sum and difference of the single lines. So if the $F$ obeys the Fibonacci recurrence, then the first reads $$ \bbox[lightyellow] { \eqalign{ & F_{\,2m} + F_{\,2m - 1} - 2 = F_{\,2m + 1} - 2 = F_{\,2\left( {m + 1} \right) - 1} - 2 = \cr & = \sum\limits_{1\, \le \,j\, \le \,m - 1} {\left( {F_{\,2\left( {m - j} \right)} + F_{\,2\left( {m - j} \right) + 1} } \right)} = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 2} } = \cr & = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m + 1} \right) - 2j} } = \sum\limits_{1\, \le \,j\, \le \,m + 1 - 2} {F_{\,2\left( {m + 1} \right) - 2j} } = \cr & = \sum\limits_{\,1\, \le \,j\, \le \,\left\lfloor {{{2\left( {m + 1} \right)} \over 2}} \right\rfloor - 1 - 1} {F_{\,2\left( {m + 1} \right) - 2j} } = \sum\limits_{\,1\, \le \,j\, \le \,\left\lfloor {{{2\left( {m + 1} \right)} \over 2}} \right\rfloor - 1} {F_{\,2\left( {m + 1} \right) - 2j} } - F_{\,2\left( {m + 1} \right) - 2\left( {\left\lfloor {{{2\left( {m + 1} \right)} \over 2}} \right\rfloor - 1} \right)} = \cr & = \sum\limits_{\,1\, \le \,j\, \le \,\left\lfloor {{k \over 2}} \right\rfloor - 1} {F_{\,2\left( {m + 1} \right) - 2j} } - F_{\,2} \quad \Rightarrow \cr & \Rightarrow \quad F_{\,2\left( {m + 1} \right) - 1} - 2 = \sum\limits_{\,1\, \le \,j\, \le \,\left\lfloor {{k \over 2}} \right\rfloor - 1} {F_{\,2\left( {m + 1} \right) - 2j} } - F_{\,2} = \sum\limits_{\,1\, \le \,j\, \le \,\left\lfloor {{k \over 2}} \right\rfloor - 1} {F_{\,2\left( {m + 1} \right) - 2j} } - 1\quad TRUE \cr} } \tag{3.a}$$ while the second line reads $$ \bbox[lightyellow] { \eqalign{ & F_{\,2m} - F_{\,2m - 1} = F_{\,2m - 2} = \sum\limits_{1\, \le \,j\, \le \,m - 1} {\left( {F_{\,2\left( {m - j} \right) + 1} - F_{\,2\left( {m - j} \right)} } \right)} = \cr & = \sum\limits_{1\, \le \,j\, \le \,m - 1} {\left( {F_{\,2m - 1 - 2j} } \right)} = \sum\limits_{1\, \le \,j\, \le \,\left\lfloor {{{2m - 1} \over 2}} \right\rfloor - 1} {\left( {F_{\,2m - 1 - 2j} } \right)} \quad TRUE \cr} } \tag{3.b}$$ ----- Answer to your comment ----- If you want to restate the above in a "classical" induction process, then you can put 1) Thesis $$ {\rm Fibonacci}\;{\rm Rec}{\rm .}\quad \Leftrightarrow \quad \left( 1 \right) $$ 2) Initial Match Since the recurrence is of degree two (it involves $\Delta _{\,k} ^{\,2} F_{\,k} $) then you need to fix two initial conditions, and we saw that $$ {\rm Thesis}\;{\rm TRUE}\quad \left| {\;k = 2,3} \right. $$ 3) True for $k=2m-1,2m$ implies true for $k=2m,2m+1$ $$ \left\{ {\matrix{ {F_{\,2m - 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right)} } } & \Leftrightarrow & {F_{\,2m} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 1} } } \cr {F_{\,2m} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 1} } } & \Leftrightarrow & {F_{\,2m + 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,m} {F_{\,2\left( {m - j} \right) + 2} } } \cr } } \right. $$ i.e. $$ \left\{ {\matrix{ {F_{\,2m - 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right)} } } & \Leftrightarrow & {F_{\,2m} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 1} } } \cr {F_{\,2m} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right) + 1} } } & \Leftrightarrow & {F_{\,2m - 1} - 1 = \sum\limits_{1\, \le \,j\, \le \,m - 1} {F_{\,2\left( {m - j} \right)} } } \cr } } \right. $$ and thus $$ {\rm Thesis}\;{\rm TRUE}\quad \left| {\;k = 2,3} \right.\quad \Leftrightarrow \quad {\rm Thesis}\;{\rm TRUE}\quad \left| {\;k = 2m,2m + 1\quad \left| {\;1 \le m} \right.} \right. $$
[ "stackoverflow", "0047146659.txt" ]
Q: Will the windows app work after the certificate is expired We have a windows app that runs on Windows 8.1. We use a test certificate with sideloading to install the app. The key is expiring in a few days and we are in the process of generating a new one and deploying it. Meanwhile, I would like to know will the app stop working after the certificate expires? I tried to post date my device and test the app which worked even with a expired certificate. Is that the intended behaviour? I do understand for any future deployment of the app it does need a renewed certificate, but will the current version continue to work even after the certificate expired. I tried googling and go through various articles but could not find a relevant answer. A: Recently we faced the same issue in our windows 8.1 app. The Current installed Build works normal even after the certificate expired. But the new build will not get installed as it will look for valid certificate. Incase if you are in need to install build with expired certificate you can change the date(date before certificate expiry) and you can install the same build. After successful installation you can change the date and run the app.
[ "tex.stackexchange", "0000208402.txt" ]
Q: Reference list of figures with autoref in continuous text How can I create a reference with \autoref{} to the list of figures (or glossary, list of tables, etc.) within continuous text? Minimal Example \documentclass{article} \usepackage{caption} \usepackage{hyperref} \usepackage{bookmark} \begin{document} \begin{figure}[!htbp] \caption{Hello World} \end{figure} … bla bla bla have a look at the \autoref{??} bla bla bla … \listoffigures \end{document} A: I don't think \autoref is the easiest way to deal with this. This simplest approach is to use \hyperref combined with a \phantomsection and \label: \documentclass{article} \usepackage{caption} \usepackage{hyperref} \usepackage{bookmark} \begin{document} \begin{figure}[tbp] \centering \vrule height 1cm width 1cm \caption{Hello World} \end{figure} \dots have a look at the \hyperref[listoffigures]{\listfigurename} for\dots \phantomsection\label{listoffigures} \listoffigures \end{document} If you want the automation of autoref, the cleveref package is probably easier to customize. It uses \cref rather than \autoref. Defining a new counter gives a way to hook in to this: \documentclass{article} \usepackage{caption} \usepackage{hyperref} \usepackage{bookmark} \usepackage[capitalize]{cleveref} \newcounter{lofigs} \crefformat{lofigs}{#2\listfigurename #3} \begin{document} \begin{figure}[tbp] \centering \vrule height 1cm width 1cm \caption{Hello World} \label{fig:ex} \end{figure} \dots have a look at the \cref{listoffigures} for\dots see \cref{fig:ex}. \refstepcounter{lofigs}\label{listoffigures} \listoffigures \end{document} If you want to make this look like its completely automatic you could patch the \listoffigures command: \documentclass{article} \usepackage{caption} \usepackage{etoolbox} \usepackage{hyperref} \usepackage{bookmark} \usepackage[capitalize]{cleveref} \newcounter{lofigs} \crefformat{lofigs}{#2\listfigurename #3} \patchcmd{\listoffigures}{\@starttoc}{\refstepcounter{lofigs}\label{listoffigures}\@starttoc}{}{} \begin{document} \begin{figure}[tbp] \centering \vrule height 1cm width 1cm \caption{Hello World} \label{fig:ex} \end{figure} \dots have a look at the \cref{listoffigures} for\dots see \cref{fig:ex}. \listoffigures \end{document} In all cases you are going to have to make similar arrangements for the other lists your document may use.
[ "stackoverflow", "0009707693.txt" ]
Q: Warning: Cannot modify header information - headers already sent by ERROR I've been struggling with this error for a while now. To start with, I just thought it was white space, but after further research I think it might be a problem similar to this: Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there. I'm guessing the include header is causing the problem along with the header(), but I'm not sure how to rearrange the code to get rid of this error. How do I remove the error? <?php $username = $password = $token = $fName = ""; include_once 'header.php'; if (isset($_POST['username']) && isset($_POST['password'])) $username = sanitizeString($_POST['username']); $password = sanitizeString($_POST['password']); //Set temporary username and password variables $token = md5("$password"); //Encrypt temporary password if ($username != 'admin') { header("Location:summary.php"); } elseif($username == 'admin') { header("Location:admin.php"); } elseif($username == '') { header("Location:index.php"); } else die ("<body><div class='container'><p class='error'>Invalid username or password.</p></div></body>"); if ($username == "" || $token == "") { echo "<body><div class='container'><p class='error'>Please enter your username and password</p></div></body>"; } else { $query = "SELECT * FROM members WHERE username='$username'AND password = '$token'"; //Look in table for username entered $result = mysql_query($query); if (!$result) die ("Database access failed: " . mysql_error()); elseif (mysql_num_rows($result) > 0) { $row = mysql_fetch_row($result); $_SESSION['username'] = $username; //Set session variables $_SESSION['password'] = $token; $fName = $row[0]; } } ?> A: The long-term answer is that all output from your PHP scripts should be buffered in variables. This includes headers and body output. Then at the end of your scripts do any output you need. The very quick fix for your problem will be to add ob_start(); as the very first thing in your script, if you only need it in this one script. If you need it in all your scripts add it as the very first thing in your header.php file. This turns on PHP's output buffering feature. In PHP when you output something (do an echo or print) it has to send the HTTP headers at that time. If you turn on output buffering you can output in the script but PHP doesn't have to send the headers until the buffer is flushed. If you turn it on and don't turn it off PHP will automatically flush everything in the buffer after the script finishes running. There really is no harm in just turning it on in almost all cases and could give you a small performance increase under some configurations. If you have access to change your php.ini configuration file you can find and change or add the following output_buffering = On This will turn output buffering out without the need to call ob_start(). To find out more about output buffering check out http://php.net/manual/en/book.outcontrol.php A: Check something with echo, print() or printr() in the include file, header.php. It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem. A: There are some problems with your header() calls, one of which might be causing problems You should put an exit() after each of the header("Location: calls otherwise code execution will continue You should have a space after the : so it reads "Location: http://foo" It's not valid to use a relative URL in a Location header, you should form an absolute URL like http://www.mysite.com/some/path.php
[ "stackoverflow", "0006897160.txt" ]
Q: Configuring URL patterns for servlet filters We are trying to use spring security in our application. IN the below code, How do we configure the URL pattern to say "intercept all the URLs except the URLs of pattern '/xyz/' " ? Basically I want the filter to intercept all the URLs,but if an URL contains /xyz/ , it should not intercept it. <sec:filter-chain pattern="/**" filters="httpSessionContextFilter, filter_A, filter_B, exceptionTranslationFilter, authorizationFilter" /> </sec:filter-chain-map> A: Try: <intercept-url pattern="*/xyz/*" filters="none" /> filters="none" disables the filter chain for the given URL pattern. Also I'd recommend enabling the spring debug log if you haven't already. So you can see exactly what's going on.
[ "serverfault", "0000109339.txt" ]
Q: Slow SSD Read on Server 2008 SP2 Im using a Intel X25-M 80G with the latest firmware. on XP /w using IDE and WIN7 using AHCI I get read speeds up to 250MB/S. But when running it with Server 2008 SP1 or SP2 on AHCI, I get read speeds around 180MB/S. Ive updated drivers for 2008, tested with writecache on/off. Any input would be appreciated. thanks! A: The only operating system that shares an identical file system with server 2008 is Vista... If your results are similar on Vista then it is indicative of limitations with this file system. Server 2008/Vista were the first generation to receive self-healing NTFS but lacked TRIM and proper SSD optimizations which Windows 7 has. As for why XP is faster.. perhaps it lacks the feature which is causing the slowdown in 2008 that was remedied in windows 7. To test this theory you would have to try the drive in AHCI mode on Vista.
[ "stackoverflow", "0047984414.txt" ]
Q: Insert random string into each instance of whitespace I'm trying to insert a randomly selected string into each instance of whitespace within another string. var boom = 'hey there buddy roe'; var space = ' '; var words = ['cool','rad','tubular','woah', 'noice']; var random_words = words[Math.floor(Math.random()*words.length)]; for(var i=0; i<boom.length; i++) { boom.split(' ').join(space + random_words + space); } Output comes to: => 'hey woah there woah buddy woah roe' I am randomly selecting an item from the array, but it uses the same word for each instance of whitespace. I want a word randomly generated each time the loop encounters whitespace. What I want is more like: => 'hey cool there noice buddy tubular roe' Thanks for taking a look. (This is beta for a Boomhauer twitter bot, excuse the variables / strings ) A: Maybe you can use regex instead however, you are not seeing the result you desire because you are randomly selecting one word and then replacing all occurrences of a space with it. The regular expression below replaces occurrences of a space with a dynamic value returned by a callback. You could compare this callback to your for-loop but instead, it's iterating over the spaces found and by doing so you can replace each occurrence with a 'unique' random word. const boom = 'hey there buddy roe'; const words = ['cool', 'rad', 'tubular', 'woah', 'noice']; const random = () => Math.floor(Math.random() * words.length); let replace = boom.replace(/ /g, () => ` ${words[random()]} `); console.log(replace);
[ "electronics.stackexchange", "0000137082.txt" ]
Q: Atmel and coil close on a board - is interference an issue? I'm going to build a circuit which uses AVR uC (probably ATmega8 or some ATtiny) and a coil with iron powder ring core. The coil has 330uH and will be working under current of approx. 6A. I'd like to make the PCB as compact as possible. Is there a danger that coil would interfere with uC? Yes, I'll be doing analog measurements with the controller. A: Toroidal inductors tend to channel almost all if not all of the flux through the toroid material rather than through the surrounding air. This means that they can be placed very closely to other components (including digital ICs) while causing little to no interference. Having said that, you should still avoid routing analog connections under it, and observe proper decoupling measures.
[ "stackoverflow", "0057534062.txt" ]
Q: How to find a string within another, ignoring some characters? Background Suppose you wish to find a partial text from a formatted phone number, and you wish to mark the finding. For example, if you have this phone number: "+972 50-123-4567" , and you search for 2501 , you will be able to mark the text within it, of "2 50-1". More examples of a hashmap of queries and the expected result, if the text to search in is "+972 50-123-45678", and the allowed characters are "01234567890+*#" : val tests = hashMapOf( "" to Pair(0, 0), "9" to Pair(1, 2), "97" to Pair(1, 3), "250" to Pair(3, 7), "250123" to Pair(3, 11), "250118" to null, "++" to null, "8" to Pair(16, 17), "+" to Pair(0, 1), "+8" to null, "78" to Pair(15, 17), "5678" to Pair(13, 17), "788" to null, "+ " to Pair(0, 1), " " to Pair(0, 0), "+ 5" to null, "+ 9" to Pair(0, 2) ) The problem You might think: Why not just use "indexOf" or clean the string and find the occurrence ? But that's wrong, because I want to mark the occurrence, ignoring some characters on the way. What I've tried I actually have the answer after I worked on it for quite some time. Just wanted to share it, and optionally see if anyone can write a nicer/shorter code, that will produce the same behavior. I had a solution before, which was quite shorter, but it assumed that the query contains only allowed characters. The question Well there is no question this time, because I've found an answer myself. However, again, if you can think of a more elegant and/shorter solution, which is as efficient as what I wrote, please let me know. I'm pretty sure regular expressions could be a solution here, but they tend to be unreadable sometimes, and also very inefficient compared to exact code. Still could also be nice to know how this kind of question would work for it. Maybe I could perform a small benchmark on it too. A: OK so here's my solution, including a sample to test it: TextSearchUtil.kt object TextSearchUtil { /**@return where the query was found. First integer is the start. The second is the last, excluding. * Special cases: Pair(0,0) if query is empty or ignored, null if not found. * @param text the text to search within. Only allowed characters are searched for. Rest are ignored * @param query what to search for. Only allowed characters are searched for. Rest are ignored * @param allowedCharactersSet the only characters we should be allowed to check. Rest are ignored*/ fun findOccurrenceWhileIgnoringCharacters(text: String, query: String, allowedCharactersSet: HashSet<Char>): Pair<Int, Int>? { //get index of first char to search for var searchIndexStart = -1 for ((index, c) in query.withIndex()) if (allowedCharactersSet.contains(c)) { searchIndexStart = index break } if (searchIndexStart == -1) { //query contains only ignored characters, so it's like an empty one return Pair(0, 0) } //got index of first character to search for if (text.isEmpty()) //need to search for a character, but the text is empty, so not found return null var mainIndex = 0 while (mainIndex < text.length) { var searchIndex = searchIndexStart var isFirstCharToSearchFor = true var secondaryIndex = mainIndex var charToSearch = query[searchIndex] secondaryLoop@ while (secondaryIndex < text.length) { //skip ignored characters on query if (!isFirstCharToSearchFor) while (!allowedCharactersSet.contains(charToSearch)) { ++searchIndex if (searchIndex >= query.length) { //reached end of search while all characters were fine, so found the match return Pair(mainIndex, secondaryIndex) } charToSearch = query[searchIndex] } //skip ignored characters on text var c: Char? = null while (secondaryIndex < text.length) { c = text[secondaryIndex] if (allowedCharactersSet.contains(c)) break else { if (isFirstCharToSearchFor) break@secondaryLoop ++secondaryIndex } } //reached end of text if (secondaryIndex == text.length) { if (isFirstCharToSearchFor) //couldn't find the first character anywhere, so failed to find the query return null break@secondaryLoop } //time to compare if (c != charToSearch) break@secondaryLoop ++searchIndex isFirstCharToSearchFor = false if (searchIndex >= query.length) { //reached end of search while all characters were fine, so found the match return Pair(mainIndex, secondaryIndex + 1) } charToSearch = query[searchIndex] ++secondaryIndex } ++mainIndex } return null } } Sample usage to test it : MainActivity.kt class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // val text = "+972 50-123-45678" val allowedCharacters = "01234567890+*#" val allowedPhoneCharactersSet = HashSet<Char>(allowedCharacters.length) for (c in allowedCharacters) allowedPhoneCharactersSet.add(c) // val tests = hashMapOf( "" to Pair(0, 0), "9" to Pair(1, 2), "97" to Pair(1, 3), "250" to Pair(3, 7), "250123" to Pair(3, 11), "250118" to null, "++" to null, "8" to Pair(16, 17), "+" to Pair(0, 1), "+8" to null, "78" to Pair(15, 17), "5678" to Pair(13, 17), "788" to null, "+ " to Pair(0, 1), " " to Pair(0, 0), "+ 5" to null, "+ 9" to Pair(0, 2) ) for (test in tests) { val result = TextSearchUtil.findOccurrenceWhileIgnoringCharacters(text, test.key, allowedPhoneCharactersSet) val isResultCorrect = result == test.value val foundStr = if (result == null) null else text.substring(result.first, result.second) when { !isResultCorrect -> Log.e("AppLog", "checking query of \"${test.key}\" inside \"$text\" . Succeeded?$isResultCorrect Result: $result found String: \"$foundStr\"") foundStr == null -> Log.d("AppLog", "checking query of \"${test.key}\" inside \"$text\" . Succeeded?$isResultCorrect Result: $result") else -> Log.d("AppLog", "checking query of \"${test.key}\" inside \"$text\" . Succeeded?$isResultCorrect Result: $result found String: \"$foundStr\"") } } // Log.d("AppLog", "special cases:") Log.d("AppLog", "${TextSearchUtil.findOccurrenceWhileIgnoringCharacters("a", "c", allowedPhoneCharactersSet) == Pair(0, 0)}") Log.d("AppLog", "${TextSearchUtil.findOccurrenceWhileIgnoringCharacters("ab", "c", allowedPhoneCharactersSet) == Pair(0, 0)}") Log.d("AppLog", "${TextSearchUtil.findOccurrenceWhileIgnoringCharacters("ab", "cd", allowedPhoneCharactersSet) == Pair(0, 0)}") Log.d("AppLog", "${TextSearchUtil.findOccurrenceWhileIgnoringCharacters("a", "cd", allowedPhoneCharactersSet) == Pair(0, 0)}") } } If I want to highlight the result, I can use something like that: val pair = TextSearchUtil.findOccurrenceWhileIgnoringCharacters(text, "2501", allowedPhoneCharactersSet) if (pair == null) textView.text = text else { val wordToSpan = SpannableString(text) wordToSpan.setSpan(BackgroundColorSpan(0xFFFFFF00.toInt()), pair.first, pair.second, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) textView.setText(wordToSpan, TextView.BufferType.SPANNABLE) }
[ "stackoverflow", "0005379736.txt" ]
Q: Help improve this SQL UNION query Alright, I've got an access control list system which mimics NT DACLs. Basically, I've got users, groups, a membership mapping between them, and ACLs with any number of ACEs referencing users or groups. (For example, this lets the "Marketing Department" group access to something, but Joe who works in marketing is a problem child, so you could deny him access to that something, and he would be denied, but everyone else in the group would be allowed) I need to enumerate a list of objects which are controlled by a given ACL -- in this case, the "controlled objects" are the user objects themselves. For example, let's say user Bob (with uid=1) wants to delete another user from the system, and I want a list of users to show Bob on which he may perform that action. If a user (denoted here by the WHERE usr.id = 1 (the "1" would be cached by the PHP app this is being embedded into)) has access to the given object, I want to show it, and if (s)he does not, then it shouldn't exist in the result set. Here's the best I've come up with so far: SELECT `acelist`.id, `acelist`.first_name, `acelist`.last_name, `acelist`.acl FROM ( ( SELECT `usResult`.id, `usResult`.first_name, `usResult`.last_name, `usResult`.acl, `ace`.`allowed` FROM `user` usResult INNER JOIN access_control_list acl ON usResult.acl = acl.id INNER JOIN group_access_control_entry ace ON acl.id = ace.acl INNER JOIN `group` gp ON ace.gid = gp.id INNER JOIN group_membership ON gp.id = group_membership.gid INNER JOIN `user` usr ON group_membership.uid = usr.id WHERE usr.id = 1 ) UNION ALL ( SELECT `usResult`.id, `usResult`.first_name, `usResult`.last_name, `usResult`.acl, `ace`.`allowed` FROM `user` usResult INNER JOIN access_control_list acl ON usResult.acl = acl.id INNER JOIN user_access_control_entry ace ON acl.id = ace.acl INNER JOIN `user` usr ON ace.uid = usr.id WHERE usr.id = 1 ) ) AS acelist GROUP BY `acelist`.id HAVING COUNT(acelist.allowed) = SUM(acelist.allowed) And here's the schema I'm working with: # Generated by Propel ORM # This is a fix for InnoDB in MySQL >= 4.1.x # It "suspends judgement" for fkey relationships until are tables are set. SET FOREIGN_KEY_CHECKS = 0; -- --------------------------------------------------------------------- -- user -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` INTEGER NOT NULL, `first_name` VARCHAR(255) NOT NULL, `last_name` VARCHAR(255) NOT NULL, `direct_login` INTEGER, `acl` INTEGER NOT NULL, PRIMARY KEY (`id`), INDEX `user_FI_1` (`acl`), CONSTRAINT `user_FK_1` FOREIGN KEY (`acl`) REFERENCES `access_control_list` (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- case_id_user -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `case_id_user`; CREATE TABLE `case_id_user` ( `uid` INTEGER NOT NULL, `case_id` VARCHAR(8), PRIMARY KEY (`uid`), UNIQUE INDEX `case_id_user_U_1` (`case_id`), CONSTRAINT `case_id_user_FK_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- direct_login_user -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `direct_login_user`; CREATE TABLE `direct_login_user` ( `uid` INTEGER NOT NULL, `passhash` CHAR(60) NOT NULL, `email` VARCHAR(255) NOT NULL, `user_name` VARCHAR(45) NOT NULL, PRIMARY KEY (`uid`), UNIQUE INDEX `direct_login_user_U_1` (`user_name`), CONSTRAINT `direct_login_user_FK_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`) ON UPDATE CASCADE ON DELETE CASCADE ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- group -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `group`; CREATE TABLE `group` ( `id` INTEGER NOT NULL, `name` VARCHAR(45) NOT NULL, `description` TEXT NOT NULL, `acl` INTEGER NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `group_U_1` (`name`), INDEX `group_FI_1` (`acl`), CONSTRAINT `group_FK_1` FOREIGN KEY (`acl`) REFERENCES `access_control_list` (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- privilege -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `privilege`; CREATE TABLE `privilege` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `privilege_U_1` (`name`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- access_control_list -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `access_control_list`; CREATE TABLE `access_control_list` ( `id` INTEGER NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- user_access_control_entry -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `user_access_control_entry`; CREATE TABLE `user_access_control_entry` ( `acl` INTEGER NOT NULL, `uid` INTEGER NOT NULL, `privilege_id` INTEGER NOT NULL, `allowed` TINYINT NOT NULL, PRIMARY KEY (`acl`,`uid`,`privilege_id`,`allowed`), INDEX `user_access_control_entry_FI_1` (`privilege_id`), INDEX `user_access_control_entry_FI_2` (`uid`), CONSTRAINT `user_access_control_entry_FK_1` FOREIGN KEY (`privilege_id`) REFERENCES `privilege` (`id`) ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT `user_access_control_entry_FK_2` FOREIGN KEY (`uid`) REFERENCES `user` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE, CONSTRAINT `user_access_control_entry_FK_3` FOREIGN KEY (`acl`) REFERENCES `access_control_list` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- group_access_control_entry -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `group_access_control_entry`; CREATE TABLE `group_access_control_entry` ( `acl` INTEGER NOT NULL, `gid` INTEGER NOT NULL, `privilege_id` INTEGER NOT NULL, `allowed` TINYINT NOT NULL, PRIMARY KEY (`acl`,`gid`,`privilege_id`,`allowed`), INDEX `group_access_control_entry_FI_1` (`privilege_id`), INDEX `group_access_control_entry_FI_2` (`gid`), CONSTRAINT `group_access_control_entry_FK_1` FOREIGN KEY (`privilege_id`) REFERENCES `privilege` (`id`) ON UPDATE CASCADE ON DELETE CASCADE, CONSTRAINT `group_access_control_entry_FK_2` FOREIGN KEY (`gid`) REFERENCES `group` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE, CONSTRAINT `group_access_control_entry_FK_3` FOREIGN KEY (`acl`) REFERENCES `access_control_list` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE ) ENGINE=InnoDB; -- --------------------------------------------------------------------- -- group_membership -- --------------------------------------------------------------------- DROP TABLE IF EXISTS `group_membership`; CREATE TABLE `group_membership` ( `uid` INTEGER NOT NULL, `gid` INTEGER NOT NULL, PRIMARY KEY (`uid`,`gid`), INDEX `group_membership_FI_2` (`gid`), CONSTRAINT `group_membership_FK_1` FOREIGN KEY (`uid`) REFERENCES `user` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE, CONSTRAINT `group_membership_FK_2` FOREIGN KEY (`gid`) REFERENCES `group` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE ) ENGINE=InnoDB; # This restores the fkey checks, after having unset them earlier SET FOREIGN_KEY_CHECKS = 1; Do any of the SQL gurus here see anything I might do to either simplify the query, or to make it execute more quickly? EDIT: Ideally, I'd somehow be able to make the complicated bits of this work for any ACL'd object so that I could avoid having to write a query like this for every ACL'd object in the database.... A: Certainly not prettier but it might be faster because there's less data to juggle with. SELECT `acelist`.id, `acelist`.first_name, `acelist`.last_name, `acelist`.acl FROM `usResult` acl INNER JOIN ( SELECT `usResult`.id FROM ( SELECT `usResult`.id , SUM(`ace`.`allowed`) AS SumAllowed , COUNT(`ace`.`allowed`) AS CountAllowed FROM `user` usResult INNER JOIN access_control_list acl ON usResult.acl = acl.id INNER JOIN group_access_control_entry ace ON acl.id = ace.acl INNER JOIN `group` gp ON ace.gid = gp.id INNER JOIN group_membership ON gp.id = group_membership.gid INNER JOIN `user` usr ON group_membership.uid = usr.id WHERE usr.id = 1 GROUP BY `usResult`.id UNION ALL SELECT `usResult`.id , SUM(`ace`.`allowed`) AS SumAllowed , COUNT(`ace`.`allowed`) AS CountAllowed FROM `user` usResult INNER JOIN access_control_list acl ON usResult.acl = acl.id INNER JOIN user_access_control_entry ace ON acl.id = ace.acl INNER JOIN `user` usr ON ace.uid = usr.id WHERE usr.id = 1 GROUP BY `usResult`.id ) results GROUP BY results.id HAVING SUM(results.SumAllowed) = SUM(results.CountAllowed) ) r ON r.id = acl.id
[ "stackoverflow", "0063046782.txt" ]
Q: Asterisk MySQL CDR logs only ANSWERED calls I've been able to setup Asterisk to log CDRs to a MySQL database using the ODBC option. The challenge I am currently facing is that only calls with the disposition ANSWERED are logged. NO ANSWER, BUSY and other calls are not logged in the database though I see the status from the logs. I place the calls using ARI which connects to a stasis app when the call is answered. How do I ensure asterisk logs all calls to the database, irrespective of the call status. I am using Asterisk 16.2.1 and added a additional field to the cdr table. A: You have to configure it in your cdr.conf file please check what content inside. ad d following line in it unanswered = yes congestion = yes
[ "stackoverflow", "0029560912.txt" ]
Q: QSplitter Stretching Factors behave differnt from normal ones I want to create a flexible layout, where the User can resize Widgets, but still give a good default layout. I'm using the Qt Designer for everything. As a minimal example I used a simple Windows with a Widget and a plainTextEdit. The later one seems to cause the problems, which is why I choose it. At first I built it without the Splitter which worked just fine. The Stretching factors are 1:1 by the way. Now I put both widgets in a Splitter (by breaking the main layout, putting both widgets in a Splitter and setting a new layout to the main widget). Resizing still works but the stretching factors behave weird: The PlainTextEdit seems to take up far to much space. The Stretching Factors are still at 1:1. I found a workaournd, by changing the stretching of the upper widget to a much higher value (in this case 9:1), which looks good again: So my question is: Why do the stretching factors begin to behave weird when I put the images in a Splitter? And how can I solve this without using arbitrary guessed stretching factors? A: QSplitter::setSizes() can be used to set relative sizes. According to the documentation, "any additional/missing space is distributed amongst the widgets according to the relative weight of the sizes". In this case, it is a bit ugly, since you have to add this in your code rather than editing your layout in QDesigner (normally, you would want to define your layout only at one place), but still it is quick and works: MyWindow::MyWindow(QWidget* parent): QWidget(parent) { m_Ui.setupUi(this); m_Ui.splitter->setSizes({2000, 1000, 1000}); However, I had to use big numbers (instead of {2, 1, 1}), maybe because at this point, the window is not completely set up yet (apparently, Qt is not a big fan of RAII...). Also, this kind of notation works probably only with a recent C++ version, otherwise you can also define the QList in some extra lines.
[ "stackoverflow", "0048164986.txt" ]
Q: List size return 0 from sqlite query I tried to query a list of premise by joining three tables. However, my list return empty when I added WHERE. I tried to log everything.. it seem that without it, I was able to get a list of premise... but it's wrong. I tried running the query on DB Browser for sqlite, it manage to run and return the right list. Please help me. this is my query code.. public List<TXN_Premise> getTxnTableData(String tableName, String columnName) { ArrayList<TXN_Premise> itemList = new ArrayList<>(); String selectQuery = "SELECT " + Constants.COLUMN_PREMISE_REF + ", " + Constants.COLUMN_PREMISE_NAME + ", " + Constants.COLUMN_PREMISE_ADDRESS + ", " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_PREMISE_CATEGORY_ID + " AS " + Constants.COLUMN_FK_PREMISE_CATEGORY_ID +", " + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_PREMISE_CATEGORY_MASTER_ID + " AS " + Constants.COLUMN_FK_PREMISE_CATEGORY_MASTER_ID + ", " + Constants.COLUMN_PREMISE_REG_NO + ", " + Constants.COLUMN_PREMISE_REG_DATE + ", " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_DESCRIPTION + " AS premiseCategoryDescription, " + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_DESCRIPTION + " AS premiseCategoryMasterDescription " + " FROM " + tableName + " LEFT JOIN " + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + " ON " + Constants.TXN_PREMISE_TABLE + "." + Constants.COLUMN_FK_PREMISE_CATEGORY_MASTER_ID + " = " + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_CODE + " LEFT JOIN " + Constants.REF_PREMISE_CATEGORY_TABLE + " ON " + Constants.TXN_PREMISE_TABLE + "." + Constants.COLUMN_FK_PREMISE_CATEGORY_ID + " = " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_CODE // + " WHERE " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS'" // + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS' AND " // + Constants.COLUMN_PREMISE_NAME + " <> '-' AND " + Constants.COLUMN_PREMISE_NAME + " <> '-TIADA-'" + " ORDER BY " + columnName + " ASC LIMIT 3"; Log.d("test", "getTxnTableData: " + selectQuery); try { open(); //make sure the database is not empty if (sqLiteDatabase != null) { //get a cursor for all state in the database Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null); Log.d("test", "getTxnTableData: cursor " + cursor.toString()); Log.d("test", "getTxnTableData: outside"); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { TXN_Premise premiseColumn = new TXN_Premise(); // premiseColumn.setPremiseId(cursor.getString(0)); premiseColumn.setPremiseRef(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_REF))); premiseColumn.setPremiseName(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_NAME))); premiseColumn.setPremiseAddress(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_ADDRESS))); premiseColumn.setFk_premiseCategoryId(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_FK_PREMISE_CATEGORY_ID))); premiseColumn.setFk_premiseCategoryMasterId(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_FK_PREMISE_CATEGORY_MASTER_ID))); premiseColumn.setPremiseRegNo(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_REG_NO))); premiseColumn.setPremiseRegDate(cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_REG_DATE))); // todo: temp premise category description premiseColumn.setPremiseCategoryName(cursor.getString(cursor.getColumnIndex("premiseCategoryDescription"))); premiseColumn.setPremiseCategoryMasterName(cursor.getString(cursor.getColumnIndex("premiseCategoryMasterDescription"))); Log.d("test", "getTxnTableData: premiseName " + cursor.getString(cursor.getColumnIndex(Constants.COLUMN_PREMISE_NAME))); //add premiseColumn in the cursor itemList.add(premiseColumn); cursor.moveToNext(); } } cursor.close(); } close(); } catch (SQLException e) { e.printStackTrace(); } Log.d("test", "getTxnTableData: itemlist " + itemList.size() ); return itemList; } A: It's impossible to recreate the issue and thus determine the problem as the WHERE clause is reliant upon the underlying data. As such you need to follow simple problem determination. As you indicate that it works without the WHERE clause then 1) Remove the WHERE clause and run. 1a) If you now retrieve rows then progressively build the WHERE clause condition by condition, that would highlight the issue. 1b) If after removing the WHERE clause the issue of no rows remains then progressively build the entire SQL starting with String selectQuery = "SELECT * FROM " + tableName;, checking that the results are as expected. I would recommend changing Log.d("test", "getTxnTableData: cursor " + cursor.toString()); To Log.d("test", "getTxnTableData: cursor " + cursor.getCount()); This will then show the number of rows in the Cursor. Additionally you could take advantage of the utillities here Edit Looking at this more closely, there appears to be some issues with the WHERE clause:- For simplification, the following resolutions will be made, wherever :- Constants.REF_PREMISE_CATEGORY_TABLE appears it will be replaced with rpc Constants.REF_PREMISE_CATEGORY_MASTER_TABLE appears it will be replaced with mrpc Constants.COLUMN_LANG appears, it will be replaced with lang Constants.COLUMN_PREMISE_NAME appears, it will be replaced with name so :- " WHERE " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS'" + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS' AND " + Constants.COLUMN_PREMISE_NAME + " <> '-' AND " + Constants.COLUMN_PREMISE_NAME + " <> '-TIADA-'" becomes (????(n) being used to indicate an issue, where n identifies the specific issue, noting that it is not part of the SQL) :- " WHERE rpc.lang = 'MYS' ????(1) mrpc.lang = 'MYS' AND name <> '-' AND name <> '-TIADA-' ????(2) Issue 1 ????(1) there is no condition between the two checks e.g. perhaps it should be WHERE rpc.lang = 'MYS' AND mrpc.lang = 'MYS' ....... This may produce an error along the lines of ..... [ near "?????????": syntax error ] Exception Name: NS_ERROR_FAILURE Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) Issue 2 ????(2) This pair of condition will NEVER be met name can only be either - or -TIADA- NEVER both. Perhaps you meant OR in which case I'd enclose them in parenthesises. So perhaps the code could be :- " WHERE " + Constants.REF_PREMISE_CATEGORY_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS'" + " AND " + Constants.REF_PREMISE_CATEGORY_MASTER_TABLE + "." + Constants.COLUMN_LANG + " = 'MYS' " + " AND (" + Constants.COLUMN_PREMISE_NAME + " <> '-' " + " OR " + Constants.COLUMN_PREMISE_NAME + " <> '-TIADA-'" + ")"
[ "unix.stackexchange", "0000294742.txt" ]
Q: Build my own firewall, in Java or other high-level language? I posted a question on ServerFault about a specialized Firewall setup, but as an avid software developer I am also considering rolling my own. I am only interested in using a high-level language, preferably Java or Node.JS. Is there some system for Linux or Illumos that will take all network packets, and provide them to my application to make a determination on whether they should be allowed, dropped or refused? (or re-written) I'm only interested in ICMP, UDP and TCP packets. I'm envisioning that I would write a Java application, that would allow me to sniff the traffic to make a determination on whether it should be allowed. For example, in HTTP traffic I may wish to check the Host header to determine what website the browser is attempting to visit. I realize this is likely to lower the potential throughput, but perhaps the solution you guys recommend will have documentation that will let me clarify the impact of that caveat. It's almost like I'm asking for FUSE, except for firewalls instead of filesystems. Is there such a program out there, or would I be stuck with writing C/C++ code for the firewall? A: On Linux-based platforms there is a netlink socket that you can open from your Java program and determine whether or not to accept the packet. This socket can be included in the network stack with an iptables rule. Here of course you can also limit the types of packets to be passed to your usermode filter. Here's what the man page has to say on the matter: ULOG This target provides userspace logging of matching packets. When this target is set for a rule, the Linux kernel will multicast this packet through a netlink socket. One or more userspace processes may then subscribe to various multicast groups and receive the packets. Given the complexity and sophistication of the netfilter project, it might be worth asking for solutions to the problem you're trying to solve. (Or perhaps that's what your other SE question covered; I haven't looked yet ) A: On OpenBSD the divert(4) mechanism can be used to lob packets between the kernel and an arbitrary userland process written in an arbitrary language, assuming the language can be made to interface with the system call (either directly or possibly via the additional complication of a shim divert(4)-to-whatever-IPC-is-required proxy layer should the language suck at system calls). A: It's entirely plausible that a firewall could be built in Java, but It's very unlikely to be a tidy project that runs at the speeds that network systems require. I used to work for a company that made a network security appliance that ran on top of SecureBSD. Any changes that we made to ipchains needed to be carefully scrutinized because the traffic was filtered in realtime. Even a very marginal loss of performance can be catastrophic.
[ "stackoverflow", "0002150287.txt" ]
Q: Force an Android activity to always use landscape mode I am using the Android VNC viewer on my HTC G1. But for some reason, that application is always in landscape mode despite my G1 is in portrait mode. Since the Android VNC viewer is open source, I would like know how is it possible hard code an activity to be 'landscape'. I would like to change it to respect the phone orientation. A: Looking at the AndroidManifest.xml (link), on line 9: <activity android:screenOrientation="landscape" android:configChanges="orientation|keyboardHidden" android:name="VncCanvasActivity"> This line specifies the screenOrientation as landscape, but author goes further in overriding any screen orientation changes with configChanges="orientation|keyboardHidden". This points to a overridden function in VncCanvasActivity.java. If you look at VncCanvasActivity, on line 109 is the overrided function: @Override public void onConfigurationChanged(Configuration newConfig) { // ignore orientation/keyboard change super.onConfigurationChanged(newConfig); } The author specifically put a comment to ignore any keyboard or orientation changes. If you want to change this, you can go back to the AndroidManifest.xml file shown above, and change the line to: <activity android:screenOrientation="sensor" android:name="VncCanvasActivity"> This should change the program to switch from portrait to landscape when the user rotates the device. This may work, but might mess up how the GUI looks, depending on how the layout were created. You will have to account for that. Also, depending on how the activities are coded, you may notice that when screen orientation is changed, the values that were filled into any input boxes disappear. This also may have to be handled. A: You can set the same data in your java code as well. myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); Other values on ActivityInfo will let you set it back to sensor driven or locked portrait. Personally, I like to set it to something in the Manifest as suggested in another answer to this question and then change it later using the above call in the Android SDK if there's a need. A: In my OnCreate(Bundle), I generally do the following: this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
[ "stackoverflow", "0053167191.txt" ]
Q: How can I run one command to bundle libraries and output separately in vue-cli3.0? I have read the document of build library in VUE-CLI3.0. My directory: --src --components --componentA.vue --componentB.vue .... --componentZ.vue --build --libs.js I want to run one command with my one entry "libs.js" (Maybe there is a loop to create multiple entries in libs.js) to bundle my components separately. The destination folder maybe like the following: --dist --componentA.css --componentA.command.js --componentA.umd.js --componentA.umd.min.js ... --componentZ.css --componentZ.command.js --componentZ.umd.js --componentZ.umd.min.js Can anyone give me some suggetions? A: I add a script file. In which, I get the list of components and using 'child_process' to execute each command. The following is an example: lib.js const { execSync } = require('child_process') const glob = require('glob') // console font color const chalk = require('chalk') // loading const ora = require('ora') // 获取所有的moduleList const components = glob.sync('./src/components/*.vue') // const buildFile = path.join(__dirname, 'build.js') // const webpack = require('vuec') const spinner = ora('Packaging the components...\n').start() setTimeout(() => { spinner.stop() }, 2000) for (const component of components) { // const file = path.join(__dirname, module); const name = component.substring(component.lastIndexOf('/') + 1).slice(0, -4) const cmd = `vue build -t lib -n ${name} ${component} -d lib/components/${name}` execSync(cmd) console.log(chalk.blue(`Component ${name} is packaged.`)) } console.log(`[${new Date()}]` + chalk.green('Compeleted !')) What's more, add a script command in package.json: "build-all": "node ./src/build/lib.js" You just enter npm run build-all. That's all~
[ "puzzling.stackexchange", "0000080427.txt" ]
Q: I am the person who abides by rules, but breaks the rules. Who am I? I am the person who abides by the rules, yet sometimes breaks the rules. I discuss with everyone about their problems late at night, but I forget to give a solution in the morning. I don't compel anyone to taste me, yet when someone tastes me they want to eat me more. I am treated badly by many people, yet the same people like me when they are in distress. Who am I? A: You are: Alcohol/Beer I am the person who abides by the rules, yet some times breaks the rules. We can drink alcohol, but too much of it and it breaks the rules of driving/public I discuss with everyone about their problems late at night, but I forget to give a solution in the morning. People discuss their issues over a drink, but it never gives an answer or solves the problem I don't compel anyone to taste me, yet when someone tastes me they want to eat me more. No one is forced to drink, but people usually want more when they've had one drink I am treated badly by many people, yet the same people like me when they are in distress. Alcohol is misused by many, and people turn to it in their times of distress A: Are you: God (in Christianity)? I am the person who abides by the rules, yet some times breaks the rules. God is supposed to follow the rules they created, but sometimes had a little deal with the devil (see Book of Job) and broke the rules. I discuss with everyone about their problems late at night, but I forget to give a solution in the morning. People pray to God before going to bed but never actually get a reply. I don't compel anyone to taste me, yet when someone tastes me they want to eat me more. This might be to do with the act of communion? When Christians eat wafers and drink wine meant to symbolise the body and blood of Jesus (who was supposedly God in human form). I am treated badly by many people, yet the same people like me when they are in distress. There are a lot of atheists who do not believe, but still find themselves pleading with God when they are distressed. A: Maybe you are: A lawyer (or a politition) I am the person who abides by the rules, yet some times breaks the rules. Lawyers abide/immerse themselves in the rules, and sometimes break the rules. I discuss with everyone about their problems late at night, but I forget to give a solution in the morning. Lawyers talk a lot to people about their problems but don't always give solutions I don't compel anyone to taste me, yet when someone tastes me they want to eat me more. People who start working in the law do it more and more(?) I am treated badly by many people, yet the same people like me when they are in distress. Lawyers are joked about as being fraudulent, but when people are in financial trouble they hire lawyers.
[ "stackoverflow", "0001032357.txt" ]
Q: Comprehending 'top' CPU usage What does it exactly mean to have a 350% cpu usage (by a process) on a 4-CPU box? The process is a 'mysqld' which is currently being 'bombarded' by a simulated OLTP scenario. Any pointers appreciated. A: In *NIX land, 100% cpu usage is 100% of a SINGLE cpu. This applies to multi-core processors the same way as true multi-processor computers. So, you are using 7/8th of your total CPU cycles on mysql. A: While running top, press "1". This will toggle the view so that you can see the load per individual core/cpu. A: I've just read an interesting article on this very subject yesterday : Unix load average. It will explain all you need to know and more. Extract : The load average is the sum of the run queue length and the number of jobs currently running on the CPUs. In Solaris 2.0 and 2.2 the load average did not include the running jobs but this bug was fixed in Solaris 2.3. Consider that there are two basic modes to display load : "IRIX mode" and "Solaris mode". In IRIX mode (Linux default), a load average of 1 means that one CPU is fully loaded ( or 25% of each CPU on a 4 CPU system, etc). In Solaris mode, a load average of 1 means that all CPUs are fully loaded (so it's actually equivalent to "IRIX mode" load divided by CPU count ).
[ "stackoverflow", "0024959012.txt" ]
Q: how to change a height layout as animation (programmatically) how to change a height layout programatically as animation? first : after : A: Heey Amigo, After testing my code, i saw a small issue. Because i used "scaleY" it just "stretches" the view. That means if there is some text or something in the view, it will just stretch it and won't look nice. Try with the ValueAnimator instead, its works more smooth public void onClick(View v) { if(!isBig){ ValueAnimator va = ValueAnimator.ofInt(100, 200); va.setDuration(400); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { Integer value = (Integer) animation.getAnimatedValue(); v.getLayoutParams().height = value.intValue(); v.requestLayout(); } }); va.start(); isBig = true; } else{ ValueAnimator va = ValueAnimator.ofInt(200, 100); va.setDuration(400); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator animation) { Integer value = (Integer) animation.getAnimatedValue(); v.getLayoutParams().height = value.intValue(); v.requestLayout(); } }); va.start(); isBig = false; } } The XML: <RelativeLayout android:layout_width="150dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:background="@android:color/holo_red_dark" android:onClick="onButtonClick" android:clickable="true"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="My Layout"/> </RelativeLayout> Old Answer You can use the ObjectAnimator, just remeber to set the pivotY(0) so it only moves on the bottom. Play with it yourself to match it your needs :) private boolean isBig = false; ... public void onClick(View v) { v.setPivotY(0f); if(!isBig){ ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 2f); scaleY.setInterpolator(new DecelerateInterpolator()); scaleY.start(); isBig = true; } else{ ObjectAnimator scaleY = ObjectAnimator.ofFloat(v, "scaleY", 1f); scaleY.setInterpolator(new DecelerateInterpolator()); scaleY.start(); isBig = false; } }
[ "askubuntu", "0001212423.txt" ]
Q: usermod -d /home (user) makes a login loop on the user I am using Ubuntu 16.04 I am in the root user and typed the command: usermod -d /home test I believe this changes the default location of test's home directory to /home. But then when I log into the user, test, the screen goes black and returns to the login screen. I then go back to my account, and as root, typed the command: usermod -d /home/test test /home/test was the original default directory for test. And then I log into the user test, and I log in successfully. Why does this happen? What can I do in order to change the default directory of test but not meet a login loop? A: For GUI logins, the home directory has to be writable by the user whose directory is being changed, as steeldrivermentioned. This way, there will not be any looping logins. If you change the directory to something that is not writable by the user, you can still log in as the user without the loop if you log into tty by doing: CTRL+ALT+F1-6 (press a key from F1 to F6) and entering the credentials of the user.
[ "stackoverflow", "0055146615.txt" ]
Q: How to sort the table and re-generate it with help of pure JavaScript I need to sort the table by name. For sorting, I use the function function sortArray(index) { let arr = []; rows.forEach( elem => { arr.push(elem.children[index].textContent); }) let sort = arr.sort( (a, b) => { if ( a > b) { return 1; } if (a < b) { return -1; } return 0; }); console.log(sort); return sort; } but I don't know how to redraw the table. Table I create from JSON file dynamically. In order to start sorting, you need to click on the name of the field and then the already sorted table should be displayed. const buildHeader = data => Object.keys(data) .map(k => `<th>${k}</th>`) .join(""); const buildRow = data => Object.keys(data) .map(k => `<td>${data[k]}</td>`) .join(""); let element = document.querySelector(".people"); function showPeople(people) { let table = document.createElement("table"); table.classList.add("people__table"); let thead = document.createElement("thead"); thead.innerHTML = `<tr class="head">${buildHeader(people[0])}</tr>`; table.appendChild(thead); let tbody = document.createElement("tbody"); tbody.innerHTML = people .map(p => `<tr class="person">${buildRow(p)}</tr>`) .join(""); table.appendChild(tbody); element.appendChild(table); } const customPeople = data => data.map((p, i) => { return { name: p.name, sex: p.sex, born: p.born, died: p.died, age: p.died - p.born, mother: p.mother, father: p.father, }; }); showPeople(customPeople(ANCESTRY_FILE)); A: Something like this sortTable function would do the job: function sortTable(tbody, index, ascending) { Array.prototype.slice.call(tbody.children).sort( (tr1, tr2) => tr1.children[index].textContent.localeCompare(tr2.children[index].textContent) * (ascending ? 1 : -1) ).forEach(tr => tbody.appendChild(tr)); } // demonstration (function(){ const thead_tr = document.getElementById('thdtr'); const tbody = document.getElementById('tbd'); function makeCell() { const td = document.createElement('td'); td.appendChild(document.createTextNode(Math.round(Math.random() * 999999999).toString(36))); return td; } function makeRow() { const tr = document.createElement('tr'); for(let i = 0; i < thead_tr.children.length; i++) tr.appendChild(makeCell()); return tr; } // adds click-to-sort functionality Array.prototype.forEach.call(thead_tr.children, (th, index) => { let asc_toggle = false; // false will start off in ascending order th.addEventListener('click', event => sortTable(tbody, index, asc_toggle = !asc_toggle)); }); // fills the table with random alphanumeric data for(let i = 0; i < 100; i++) tbody.appendChild(makeRow()); }()); <table> <thead> <tr id="thdtr"> <th>col 1</th> <th>col 2</th> <th>col 3</th> </tr> </thead> <tbody id="tbd"> </tbody> <table> My sortTable function is a generic in-place table sorting function that should work on any table. It accepts 3 parameters: tbody - DOMElement - A reference to either the tbody element or the table element itself, whichever contains the tr (row) elements. index - Number - The index of the column to sort by (starts at 0). ascending - Boolean - Whether the order is ascending (true) or descending (false) Example usage for use with your current code: sortTable(document.querySelector('.people__table tbody'), 0, true);
[ "stackoverflow", "0012666003.txt" ]
Q: flex/bison parser compiles with segmentation fault I'm writing a parser with flex/bison (I could write the parser in Python, but I would always prefer the classics.) When I compile the code with this: gcc -lfl -ly chance.tab.c lex.yy.c -o chance When I run the program with a file, I get something like this: Segmentation fault (core dumped) For anyone's reference, here are the files: chance.y %{ #include <stdio.h> %} %union { char* str; } %token ASSERT BREAK CATCH CLASS CONTINUE DEL EACH ELSE ELSEIF FINALLY FROM %token FUNC IF LOAD PASS PRINT REPEAT RETURN RUN THROW TRY WHILE UNTIL %token YIELD AND OR NOT KTRUE KFALSE NONE %token MINUS EXCLAM PERCENT LAND LPAREN RPAREN STAR COMMA DOT SLASH COLON %token SEMICOLON QUESTION AT LBRACKET BACKSLASH RBRACKET CIRCUMFLEX LBRACE %token BAR RBRACE TILDE PLUS LTHAN EQUAL GTHAN INTDIV %token ADDASS SUBASS MULASS DIVASS INTDASS MODASS ANDASS ORASS LTEQ EQUALS %token GTEQ INCREMENT DECREMENT DBLSTAR %token<str> NAME STRING INTEGER FLOAT %token INDENT DEDENT NEWLINE %type<str> exprs names args kwdspec dfltarg arg arglist exprlist name namelist %type<str> funcargs parenexpr lstexpr eachspec optargs inheritance addop %type<str> expr ifs elifs elif elses trys catchs catchx finally suite stmts %type<str> stmt program %start program %% exprs: expr { $$ = $1; } | exprs COMMA expr { sprintf($$, "%s %s", $1, $3); } ; names: name { $$ = $1; } | names COMMA name { sprintf($$, "%s %s", $1, $3); } ; args: arg { $$ = $1; } | args COMMA arg { sprintf($$, "%s %s", $1, $3); } ; kwdspec: { $$ = "regular"; } | STAR { $$ = "list"; } | DBLSTAR { $$ = "keyword"; } ; dfltarg: { $$ = "null"; } | EQUAL expr { $$ = $2; } ; arg: kwdspec name dfltarg { sprintf($$, "(argument %s %s %s)", $1, $2, $3); } ; arglist: args { sprintf($$, "[%s]", $1); } ; exprlist: exprs { sprintf($$, "[%s]", $1); } ; name: NAME { sprintf($$, "(name %s)", $1); } ; namelist: names { sprintf($$, "[%s]", $1); } ; funcargs: LPAREN arglist RPAREN { $$ = $2 } ; parenexpr: LPAREN exprlist RPAREN { sprintf($$, "(tuple %s)", $2); } ; lstexpr: LBRACKET exprlist RBRACKET { sprintf($$, "(list %s)", $2); } ; eachspec: BAR namelist BAR { sprintf($$, "(each-spec %s)", $2); } ; optargs: { $$ = ""; } | funcargs { $$ = $1; } ; inheritance: { $$ = ""; } | parenexpr { $$ = $1; } ; addop: ADDASS { $$ = "add"; } | SUBASS { $$ = "sub"; } | MULASS { $$ = "mul"; } | DIVASS { $$ = "div"; } | INTDASS { $$ = "int-div"; } | MODASS { $$ = "mod"; } | ANDASS { $$ = "and"; } | ORASS { $$ = "or"; } ; expr: /* NotYetImplemented! */ NUMBER { sprintf($$, "(number %s)", $1); } | TRUE { $$ = "(true)"; } | FALSE { $$ = "(false)"; } | NONE { $$ = "(none)"; } | STRING { sprintf($$, "(string %s)", $1); } | lstexpr { $$ = $1; } ; ifs: IF expr suite { sprintf($$, "(if %s %s)", $2, $3); } ; elifs: { $$ = ""; } | elifs elif { sprintf($$, "%s %s", $1, $2); } ; elif: ELSEIF expr suite { sprintf($$, "(else-if %s %s)", $2, $3); } ; elses: { $$ = ""; } | ELSE suite { sprintf($$, "(else %s)", $2); } ; trys: TRY suite { sprintf($$, "(try %s)", $2); } ; catchs: { $$ = ""; } | catchs catchx { sprintf($$, "%s %s", $1, $2); } ; catchx: CATCH expr suite { sprintf($$, "(catch %s %s)", $2, $3); } ; finally: FINALLY suite { sprintf($$, "(finally %s)", $2); } ; suite: COLON stmts SEMICOLON { sprintf($$, "(block [%s])", $2); } ; stmts: { $$ = ""; } | stmts NEWLINE stmt { sprintf($$, "%s %s", $1, $3); } ; stmt: ASSERT expr { printf("(assert %s)", $2); } | BREAK { printf("(break)"); } | CATCH expr suite { printf("(catch %s %s)", $2, $3); } | CLASS name inheritance suite { printf("(class %s %s %s)", $2, $3, $4); } | CONTINUE { printf("(continue)"); } | DEL expr { printf("(del %s)", $2); } | expr DOT EACH eachspec suite { printf("(each %s %s %s)", $1, $4, $5); } | FROM name LOAD namelist { printf("(from %s %s)", $2, $4); } | FUNC name optargs suite { printf("(func %s %s %s)", $2, $3, $4); } | ifs elifs elses { printf("(if-block %s %s %s)", $1, $2, $3); } | LOAD namelist { printf("(load %s)", $2); } | PASS { printf("(pass)"); } | PRINT expr { printf("(print %s)", $2); } | REPEAT expr suite { printf("(repeat %s %s)", $2, $3); } | RUN expr { printf("(run %s)", $2); } | THROW expr { printf("(throw %s)", $2); } | trys catchs elses finally { printf("(try-block %s %s %s %s)", $1, $2, $3, $4); } | WHILE expr suite { printf("(while %s %s)", $2, $3); } | UNTIL expr suite { printf("(until %s %s)", $2, $3); } | YIELD expr { printf("(yield %s)", $2); } | RETURN expr { printf("(return %s)", $2); } | expr addop expr { printf("(%s-assign %s %s)", $2, $1, $3); } | expr INCREMENT { printf("(increment %s)", $1); } | expr DECREMENT { printf("(decrement %s)", $1); } | expr { printf("(expr-stmt %s)", $1); } ; program: stmts { printf("(program [%s])", $1); } ; chance.l %{ #include <assert.h> #include <stdio.h> #include "parser.tab.h" %} %option yylineno %option noyywrap %% "assert" { return ASSERT; } "break" { return BREAK; } "catch" { return CATCH; } "class" { return CLASS; } "continue" { return CONTINUE; } "del" { return DEL; } "each" { return EACH; } "else" { return ELSE; } "elseif" { return ELSEIF; } "finally" { return FINALLY; } "from" { return FROM; } "func" { return FUNC; } "if" { return IF; } "load" { return LOAD; } "pass" { return PASS; } "print" { return PRINT; } "repeat" { return REPEAT; } "return" { return RETURN; } "run" { return RUN; } "throw" { return THROW; } "try" { return TRY; } "while" { return WHILE; } "until" { return UNTIL; } "yield" { return YIELD; } "and" { return AND; } "or" { return OR; } "not" { return NOT; } "true" { return KTRUE; } "false" { return KFALSE; } "none" { return NONE; } - { return MINUS; } ! { return EXCLAM; } % { return PERCENT; } & { return LAND; } \( { return LPAREN; } \) { return RPAREN; } \* { return STAR; } , { return COMMA; } \. { return DOT; } \/ { return SLASH; } : { return COLON; } ; { return SEMICOLON; } \? { return QUESTION; } @ { return AT; } \[ { return LBRACKET; } \] { return RBRACKET; } \^ { return CIRCUMFLEX; } \{ { return LBRACE; } \} { return RBRACE; } \| { return BAR; } ~ { return TILDE; } \+ { return PLUS; } \< { return LTHAN; } = { return EQUAL; } \> { return GTHAN; } \/\/ { return INTDIV; } \+= { return ADDASS; } -= { return SUBASS; } \*= { return MULASS; } \/= { return DIVASS; } \/\/= { return INTDASS; } %= { return MODASS; } &= { return ANDASS; } \|= { return ORASS; } \<= { return LTEQ; } == { return EQUALS; } \>= { return GTEQ; } \+\+ { return INCREMENT; } -- { return DECREMENT; } \*\* { return DBLSTAR; } [[:digit:]]+([eE][+-]?[[:digit:]]+)? { yylval.str = strdup(yytext); return INTEGER; } [[:digit:]]+\.[[:digit:]]+([eE][+-]?[[:digit:]]+)? { yylval.str = strdup(yytext); return FLOAT; } [a-zA-Z_][a-zA-Z0-9_]* { yylval.str = strdup(yytext); return NAME; } \"([^\"])*\" { yylval.str = strdup(yytext); return STRING; } \'([^\'])*\' { yylval.str = strdup(yytext); return STRING; } `([^`])*` { yylval.str = strdup(yytext); return STRING; } "<INDENT>" { return INDENT; } "<DEDENT>" { return DEDENT; } "<NEWLINE>" { return NEWLINE; } #.* { } [ \\\t] {} \n { (yylineno) += 0.5; } . { yyerror(); } %% int yyerror(void) { printf("Invalid syntax on line %d: '%s'\n", yylineno, yytext); } int main() { yyparse(); printf("\n"); return 0; } And if the above program works for anyone, here is some sample code in my little programming language: test.ch from timer load x func x(f=0, **k): 5.each|x|: continue;; class OhHey: func __init__: print 5;; while true: print x; [1, 2, 3] (1, 2, 3) Thanks in advance. ~~Chance EDIT: entered new and improved code (which, unfortunately, still produces a segfault.) A: Your lexer never sets yylval, so when you parser reads the value of a token, it gets random garbage. For example, in your rule: expr: NUMBER { sprintf($$, "(number %s)", $1); } $1 refers to the token value from NUMBER, so will be random garbage. In addition, $$ is the output from a rule, so the value you pass to sprintf here will also be random garbage (as you don't set it to something first). edit One "easy" solution is to liberally use strdup/asprintf to allocate memory for strings. For example, in your .l file, you'd have something like: [+-]?[0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)? { yylval = strdup(yytext); return NUMBER; } Then your expr rule would be: expr: NUMBER { asprintf(&$$, "(number %s)", $1); free($1); } The problem is, of course, that figuring out where all the frees should go to avoid leaking memory can be tough.