qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
6,604,459
Is there an NSNotification we can observe for when the device is on/off the phone?
2011/07/07
[ "https://Stackoverflow.com/questions/6604459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/212559/" ]
The `NotificationCenter` doesn't send out any notifications abou this, but take a look at the `CTCallCenter` class introduced in iOS 4. It has a `callEventHandler` property that you can assign a block of code to, and gets called with call state info. There is a limitation in that the handler only gets called when your app is in the foreground (or being taken out of the foreground when a call comes in), but it tells you if the user is dialing (`CTCallStateDialing`), receiving a call (`CTCallStateIncoming`), answering/connecting (`CTCallStateConnecting`) or hanging up on a call (`CTCallStateDisconnected`).
There isn't one that I'm aware of, but if the issue is that you want to know about the change in status bar then you can observe `UIApplicationWillChangeStatusBarFrameNotification` (as documented towards the bottom of the [UIApplication documentation](http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html)) and get a new rect from the relevant userInfo whenever a change occurs.
71,032
I have a Ph.D. in pure math (interested in Harmonic analysis and operator theory). I am looking forward some proper references to lead me get the foundation of discrete/signal processing more and more. Actually, I had a review of the Heppenheim's books (both signal and digital ones) and (rather) got what he is saying in these (very nice) book. Now, I am going to develop my knowledge concerning this context and do need to cover some more advanced ones. Thanks in advances for you suggestions. Probably based on my own field, I would like to read on some texts whose approaches are focused on theoretical bases. However having some (proper) references which make me feel (realize) some real applications are in priority.
2020/10/23
[ "https://dsp.stackexchange.com/questions/71032", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/50574/" ]
You have already read those Oppenheim's Signals & Systems, and Discrete-Time Signal Processing books. I'm not sure what you mean by *foundations* but in some sense these two are also the foundations on signal processing. In other words, there are no (popular & successful) graduate level DSP books that discuss at an advanced level the *same topics* that are covered on them. However the following books (or subjects) will enhance your understanding, or broaden your appreciation of the subject. First of all, the very first graduate level course on DSP, Communications, and Control is called **Linear System Theory** which brings together all the undergraduate mathematical stuff from a new, advanced, deeper, and foundational point of view of the Hilbert (linear vector) Spaces, Linear Mappings, and Matrix theory. It does not have a definite book but a bunch of books on Linear Algebra & Matrices, Measure Theory, and Diferential Equations were used. Note that there's a control theory oriented bunch of Linear System Theory books (Desoer's crew) that I do not recommend for DSP, unless you will be designing control systems on the field. Signal processing does not make much use of state-space approach, unless it's absolutely necessary. Then the second refresher/deepener is on **Probability, Statistics and Random Processes**. Fortunately it has two very strongly recomended books though: * Statistical Digital Signal Procesing \_ Monson HAYES * Discrete RaNdom Signals and Statistical Signal Processing \_ THERRIEN The first book is a must read, the second one is following the style of Oppenheim series but is harder to follow, and less practical than the first. Then the following books / subjects will be awating you : * Adaptive Filter Theory \_ HAYKIN * Multiresolution Signal Decomposition \_ AKANSU * Multirate Digital Signal Processing \_ RABINER * Estimation & Detection Theory \_ KAY * Pattern Classification \_ DUDA * Theory and Applications of Digital Signal Processing \_ RABINER & GOLD Then the following applications will make your day : * Speech and Hearing for Communication - FLETCHER * Digital Processing of Speech \_ Rabiner * Speech and Audio Signal Processing \_ GOLD * Discrete-Time Processing of Speech \_ PROAKIS * Advances in Speech Coding \_ GERSHO * Two-Dimensional Signal and Image Processing \_ LIM * Digital Image Processing \_ GONZALES * Fundamentals of Image Processing \_ JAIN * Signal Compression\_JAYANT * Introduction to Data compression \_ SAYOOD Of course the list is by no means complete...
I found these books to be very good in their respective field: [J.R. Ohm - Multimedia Communication Technology](https://rads.stackoverflow.com/amzn/click/com/3540012494) This has focus on representation and transmission of signals. It follows a practical approach hands down and features very good, informative illustrations. In general, Ohm's books are recommendable. His newest one is about feature extraction, but I have not read it yet. [Cover and Thomas - Elements of Information Theory](https://rads.stackoverflow.com/amzn/click/com/0471241954) As the title suggests, this has more of a theoretical approach. It is not about signal processing per se, but I found it very insightful. It covers the mathematical and stochastic aspects of any kind of information transmission. As I said, this is not about DSP, but more about how to get signals over a channel of some kind. As theoretical as it is, it provides extremely useful background knowledge in my everyday work as an engineer. [Vary and Martin - Digital Speech Transmission](https://rads.stackoverflow.com/amzn/click/com/0471560189) As the title says, this is all about speech communication. If you are interested in this particular field, this is a good overview. All these are quite special and not directly about DSP, but with Oppenheim you already have the basics and to dive deeper into *everything*, the field is just to broad for one book to cover it all.
15,431,025
I have published a successful app on play, but after upgrading the app when I sign and align the app and install it on an emulator/real device it force closes and gives me `ClassNotFound` Exception. ``` 03-15 16:09:08.280: E/AndroidRuntime(7122): java.lang.RuntimeException: Unable to instantiate application william.shakespeare.MyBaseClass: java.lang.ClassNotFoundException: william.shakespeare.MyBaseClass 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.LoadedApk.makeApplication(LoadedApk.java:482) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3909) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.access$1300(ActivityThread.java:122) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1184) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.os.Handler.dispatchMessage(Handler.java:99) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.os.Looper.loop(Looper.java:137) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.main(ActivityThread.java:4340) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.reflect.Method.invokeNative(Native Method) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.reflect.Method.invoke(Method.java:511) 03-15 16:09:08.280: E/AndroidRuntime(7122): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-15 16:09:08.280: E/AndroidRuntime(7122): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-15 16:09:08.280: E/AndroidRuntime(7122): at dalvik.system.NativeStart.main(Native Method) 03-15 16:09:08.280: E/AndroidRuntime(7122): Caused by: java.lang.ClassNotFoundException: william.shakespeare.MyBaseClass 03-15 16:09:08.280: E/AndroidRuntime(7122): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.Instrumentation.newApplication(Instrumentation.java:942) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.LoadedApk.makeApplication(LoadedApk.java:477) 03-15 16:09:08.280: E/AndroidRuntime(7122): ... 11 more ``` This is my Manifest file: ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="william.shakespeare" android:versionCode="2" android:versionName="1.1" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.ACTION_SEND"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.BLUETOOTH"/> <user-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.GET_TASKS"/> <application android:icon="@drawable/ic_launcher" android:theme="@android:style/Theme.Holo.NoActionBar" android:label="William Shakespeare Quotes" android:launchMode="singleInstance" android:name="william.shakespeare.MyBaseClass" > <activity android:name=".Splash_Screen" android:label="@string/title_activity_splash__screen" android:launchMode="singleInstance" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AboutUs" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Biography" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Category_List" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Favourite_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Favourite_Single_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Help" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".MainMenu" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".MyCustomActionBar" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Quote_List" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".QuotesIn_Category" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".SearchFrom" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Settings" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Single_Category" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Single_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/> <receiver android:name=".Quote_Of_Day"/> <receiver android:name=".Notification_Quote"/> <receiver android:name=".Boot_Receiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest> ```
2013/03/15
[ "https://Stackoverflow.com/questions/15431025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129047/" ]
ClassNotFound exception means that in your manifest file you have miss the Activity or may be you have not give correct name of the Activity.
Did you use ProGuard? It might have obfuscated some classes that shoudn't be obfuscated because they are referenced in an xml file (`AndroidManifest.xml` for example) or something. More on ProGuard can be found [here](http://developer.android.com/tools/help/proguard.html).
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
All the people criticizing a `LinkedList`, think about every other guy that has been using `List` in Java probably uses `ArrayList` and an `LinkedList` most of the times because they have been before Java 6 and because those are the ones being taught as a start in most books. But, that doesn't mean, I would blindly take `LinkedList`'s or `ArrayDeque`'s side. If you want to know, take a look at the below benchmark [done by Brian](https://web.archive.org/web/20191101213733/http://brianandstuff.com/2016/12/12/java-arraydeque-vs-linkedlist/) (archived). The test setup considers: > > * Each test object is a 500 character String. Each String is a different object in memory. > * The size of the test array will be varied during the tests. > * For each array size/Queue-implementation combination, 100 tests are run and average time-per-test is calculated. > * Each tests consists of filling each queue with all objects, then removing them all. > * Measure time in terms of milliseconds. > > > Test Result: > > * Below 10,000 elements, both LinkedList and ArrayDeque tests averaged at a sub 1 ms level. > * As the sets of data get larger, the differences between the ArrayDeque and LinkedList average test time gets larger. > * At the test size of 9,900,000 elements, the LinkedList approach took ~165% longer than the ArrayDeque approach. > > > Graph: [![enter image description here](https://i.stack.imgur.com/MUHdy.png)](https://i.stack.imgur.com/MUHdy.png) **Takeaway:** * If your requirement is storing 100 or 200 elements, it wouldn't make much of a difference using either of the Queues. * However, if you are developing on mobile, you may want to use an `ArrayList` or `ArrayDeque` with a good guess of maximum capacity that the list may be required to be because of strict memory constraint. * A lot of code exists, written using a `LinkedList` so tread carefully when deciding to use a `ArrayDeque` especially because it **DOESN'T implement the `List` interface**(I think that's reason big enough). It may be that your codebase talks to the List interface extensively, most probably and you decide to jump in with an `ArrayDeque`. Using it for internal implementations might be a good idea...
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
[ArrayDeque](https://docs.oracle.com/javase/9/docs/api/java/util/ArrayDeque.html) and [LinkedList](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html) are implementing [Deque](https://docs.oracle.com/javase/9/docs/api/java/util/Deque.html) interface but implementation is different. Key differences: 1. The *ArrayDeque* class is the resizable array implementation of the *Deque* interface and *LinkedList* class is the list implementation 2. NULL elements can be added to *LinkedList* but not in *ArrayDeque* 3. *ArrayDeque* is more efficient than the *LinkedList* for add and remove operation at both ends and LinkedList implementation is efficient for removing the current element during the iteration 4. The *LinkedList* implementation consumes more memory than the *ArrayDeque* So if you don't have to support NULL elements && looking for less memory && efficiency of add/remove elements at both ends, *ArrayDeque* is the best Refer to [documentation](https://docs.oracle.com/javase/tutorial/collections/implementations/deque.html) for more details.
I don't think `ArrayDeque` is better than `LinkedList`. They are different. `ArrayDeque` is faster than `LinkedList` on average. But for adding an element, `ArrayDeque` takes amortized constant time, and `LinkedList` takes constant time. For time-sensitive applications that require all operations to take constant time, only `LinkedList` should be used. `ArrayDeque`'s implementation uses arrays and requires resizing, and occasionally, when the array is full and needs to add an element, it will take linear time to resize, resulting the `add()` method taking linear time. That could be a disaster if the application is very time-sensitive. A more detailed explanation of Java's implementation of the two data structures is available in the "[Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1)" course on Coursera offered by Princeton University, taught by Wayne and Sedgewick. The course is free to the public. The details are explained in the video "Resizing Arrays" in the "Stacks and Queues" section of "Week 2".
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
I don't think `ArrayDeque` is better than `LinkedList`. They are different. `ArrayDeque` is faster than `LinkedList` on average. But for adding an element, `ArrayDeque` takes amortized constant time, and `LinkedList` takes constant time. For time-sensitive applications that require all operations to take constant time, only `LinkedList` should be used. `ArrayDeque`'s implementation uses arrays and requires resizing, and occasionally, when the array is full and needs to add an element, it will take linear time to resize, resulting the `add()` method taking linear time. That could be a disaster if the application is very time-sensitive. A more detailed explanation of Java's implementation of the two data structures is available in the "[Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1)" course on Coursera offered by Princeton University, taught by Wayne and Sedgewick. The course is free to the public. The details are explained in the video "Resizing Arrays" in the "Stacks and Queues" section of "Week 2".
Time complexity for ArrayDeque for accessing a element is O(1) and that for LinkList is is O(N) to access last element. ArrayDeque is not thread safe so manually synchronization is necessary so that you can access it through multiple threads and so they they are faster.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
Time complexity for ArrayDeque for accessing a element is O(1) and that for LinkList is is O(N) to access last element. ArrayDeque is not thread safe so manually synchronization is necessary so that you can access it through multiple threads and so they they are faster.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
[ArrayDeque](https://docs.oracle.com/javase/9/docs/api/java/util/ArrayDeque.html) and [LinkedList](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html) are implementing [Deque](https://docs.oracle.com/javase/9/docs/api/java/util/Deque.html) interface but implementation is different. Key differences: 1. The *ArrayDeque* class is the resizable array implementation of the *Deque* interface and *LinkedList* class is the list implementation 2. NULL elements can be added to *LinkedList* but not in *ArrayDeque* 3. *ArrayDeque* is more efficient than the *LinkedList* for add and remove operation at both ends and LinkedList implementation is efficient for removing the current element during the iteration 4. The *LinkedList* implementation consumes more memory than the *ArrayDeque* So if you don't have to support NULL elements && looking for less memory && efficiency of add/remove elements at both ends, *ArrayDeque* is the best Refer to [documentation](https://docs.oracle.com/javase/tutorial/collections/implementations/deque.html) for more details.
Time complexity for ArrayDeque for accessing a element is O(1) and that for LinkList is is O(N) to access last element. ArrayDeque is not thread safe so manually synchronization is necessary so that you can access it through multiple threads and so they they are faster.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
although **`ArrayDeque<E>`** and **`LinkedList<E>`** have both implemented **`Deque<E>`** Interface, but the ArrayDeque uses basically Object array **`E[]`** for keeping the elements inside its Object, so it generally uses index for locating the head and tail elements. In a word, it just works like Deque (with all Deque's method), however uses array's data structure. As regards which one is better, depends on how and where you use them.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
I believe that the main performance bottleneck in `LinkedList` is the fact that whenever you push to any end of the deque, behind the scene the implementation allocates a new linked list node, which essentially involves JVM/OS, and that's expensive. Also, whenever you pop from any end, the internal nodes of `LinkedList` become eligible for garbage collection and that's more work behind the scene. Also, since the linked list nodes are allocated here and there, usage of CPU cache won't provide much benefit. If it might be of interest, I have a proof that adding (appending) an element to `ArrayList` or `ArrayDeque` runs in amortized constant time; refer to [this](https://coderodde.wordpress.com/2015/08/01/keeping-vectors-efficient/).
`ArrayDeque` is new with Java 6, which is why a lot of code (especially projects that try to be compatible with earlier Java versions) don't use it. It's "better" in some cases because you're not allocating a node for each item to insert; instead all elements are stored in a giant array, which is resized if it gets full.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
That's not always the case. For example, in the case below `linkedlist` has better performance than `ArrayDeque` according to leetcode 103. ``` /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> rs=new ArrayList<>(); if(root==null) return rs; // here ,linkedlist works better Queue<TreeNode> queue=new LinkedList<>(); queue.add(root); boolean left2right=true; while(!queue.isEmpty()) { int size=queue.size(); LinkedList<Integer> t=new LinkedList<>(); while(size-->0) { TreeNode tree=queue.remove(); if(left2right) t.add(tree.val); else t.addFirst(tree.val); if(tree.left!=null) { queue.add(tree.left); } if(tree.right!=null) { queue.add(tree.right); } } rs.add(t); left2right=!left2right; } return rs; } } ```
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
I believe that the main performance bottleneck in `LinkedList` is the fact that whenever you push to any end of the deque, behind the scene the implementation allocates a new linked list node, which essentially involves JVM/OS, and that's expensive. Also, whenever you pop from any end, the internal nodes of `LinkedList` become eligible for garbage collection and that's more work behind the scene. Also, since the linked list nodes are allocated here and there, usage of CPU cache won't provide much benefit. If it might be of interest, I have a proof that adding (appending) an element to `ArrayList` or `ArrayDeque` runs in amortized constant time; refer to [this](https://coderodde.wordpress.com/2015/08/01/keeping-vectors-efficient/).
All the people criticizing a `LinkedList`, think about every other guy that has been using `List` in Java probably uses `ArrayList` and an `LinkedList` most of the times because they have been before Java 6 and because those are the ones being taught as a start in most books. But, that doesn't mean, I would blindly take `LinkedList`'s or `ArrayDeque`'s side. If you want to know, take a look at the below benchmark [done by Brian](https://web.archive.org/web/20191101213733/http://brianandstuff.com/2016/12/12/java-arraydeque-vs-linkedlist/) (archived). The test setup considers: > > * Each test object is a 500 character String. Each String is a different object in memory. > * The size of the test array will be varied during the tests. > * For each array size/Queue-implementation combination, 100 tests are run and average time-per-test is calculated. > * Each tests consists of filling each queue with all objects, then removing them all. > * Measure time in terms of milliseconds. > > > Test Result: > > * Below 10,000 elements, both LinkedList and ArrayDeque tests averaged at a sub 1 ms level. > * As the sets of data get larger, the differences between the ArrayDeque and LinkedList average test time gets larger. > * At the test size of 9,900,000 elements, the LinkedList approach took ~165% longer than the ArrayDeque approach. > > > Graph: [![enter image description here](https://i.stack.imgur.com/MUHdy.png)](https://i.stack.imgur.com/MUHdy.png) **Takeaway:** * If your requirement is storing 100 or 200 elements, it wouldn't make much of a difference using either of the Queues. * However, if you are developing on mobile, you may want to use an `ArrayList` or `ArrayDeque` with a good guess of maximum capacity that the list may be required to be because of strict memory constraint. * A lot of code exists, written using a `LinkedList` so tread carefully when deciding to use a `ArrayDeque` especially because it **DOESN'T implement the `List` interface**(I think that's reason big enough). It may be that your codebase talks to the List interface extensively, most probably and you decide to jump in with an `ArrayDeque`. Using it for internal implementations might be a good idea...
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
[ArrayDeque](https://docs.oracle.com/javase/9/docs/api/java/util/ArrayDeque.html) and [LinkedList](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedList.html) are implementing [Deque](https://docs.oracle.com/javase/9/docs/api/java/util/Deque.html) interface but implementation is different. Key differences: 1. The *ArrayDeque* class is the resizable array implementation of the *Deque* interface and *LinkedList* class is the list implementation 2. NULL elements can be added to *LinkedList* but not in *ArrayDeque* 3. *ArrayDeque* is more efficient than the *LinkedList* for add and remove operation at both ends and LinkedList implementation is efficient for removing the current element during the iteration 4. The *LinkedList* implementation consumes more memory than the *ArrayDeque* So if you don't have to support NULL elements && looking for less memory && efficiency of add/remove elements at both ends, *ArrayDeque* is the best Refer to [documentation](https://docs.oracle.com/javase/tutorial/collections/implementations/deque.html) for more details.
51,521,716
I have seen [this post](https://stackoverflow.com/questions/13258454/marking-specific-tiles-in-geom-tile-geom-raster), but I'm struggling to translate that to a logarithmic raster. For example: ``` library(tidyverse) a <- tibble(x = rep(10^seq(-2, 2), 5), y = rep(10^seq(-2, 2), each = 5), z = runif(25)) a %>% ggplot(aes(x, y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() ``` How do I now get for example a box around the row with `y = 0.1`? Or a box around just one tile? I know that the half-point between two points on a logarithmic scale is calculated by the geometric mean. **Update:** For the example above, the solution seems to work but not if `x` and `y` look a little different, e.g.: ``` n_x <- 10^seq(log10(6), log10(24*365), by = 0.1)/365 n_y <- 10^seq(-1, 3, by = 0.1) a <- tibble(x = rep(n_x, length(n_y)), y = rep(n_y, each = length(n_x)), z = runif(length(n_x)*length(n_y))) h <- a$y[which.min(abs(a$y - 1.14*24))] h.tb <- a %>% dplyr::filter(y == h) a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10(breaks = c(1, h, 100), labels = c('1', 'h', '100')) + geom_tile(data = h.tb, fill = NA, colour = "black", size = 2) ``` Interestingly, `h.tb` contains the correct data.
2018/07/25
[ "https://Stackoverflow.com/questions/51521716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1704801/" ]
Assuming for example that you want to mark tiles in the y = 0.1 row, for x < 10, adding `geom_tile()` like the following could work: ``` p1 <- a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() + geom_tile(data = . %>% filter(y == 0.1 & x < 10), # filter dataset for desired tiles fill = NA, # make tiles transparent colour = "black", size = 2) # aesthetic choices p1 ``` [![plot](https://i.stack.imgur.com/QPsnP.png)](https://i.stack.imgur.com/QPsnP.png) If you want the tiles to form a single rectangle, I can't think of an equally straightforward method, but it can be done. ``` # continuing from above, using the geom_tile layer from p1 to # obtain the correct tile dimensions, then transform all measures # back to the non-log form p1.data <- layer_data(p1, 2) %>% summarise(xmin = min(xmin), xmax = max(xmax), ymin = min(ymin), ymax = max(ymax)) %>% mutate_all(function(x) 10^x) > p1.data xmin xmax ymin ymax 1 0.003162278 3.162278 0.03162278 0.3162278 # replace the geom_tile() layer earlier with geom_rect() & the new data a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() + geom_rect(data = p1.data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), inherit.aes = FALSE, fill = NA, colour = "black", size = 2) ``` [![plot2](https://i.stack.imgur.com/yeuwN.png)](https://i.stack.imgur.com/yeuwN.png)
For the updated example, one just needs to add `height = 0.1` to `geom_tile` where the value of `height` needs to fit the `by` value in `n_y`. ``` n_x <- 10^seq(log10(6), log10(24*365), by = 0.1)/365 step_y <- 0.1 n_y <- 10^seq(-1, 3, by = step_y) a <- tibble(x = rep(n_x, length(n_y)), y = rep(n_y, each = length(n_x)), z = runif(length(n_x)*length(n_y))) h <- a$y[which.min(abs(a$y - 1.14*24))] h.tb <- a %>% dplyr::filter(y == h) a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10(breaks = c(1, h, 100), labels = c('1', 'h', '100')) + geom_tile(data = h.tb, fill = NA, colour = "black", size = 2, height = step_y) ```
49,290,741
We are designing a system for conducting a survey in which it askes user a about 72 questions (Multiple Choice questions) And when the user submits this will be posted to php page which will save the answer in a MySQL table. Its works fine and perfectly well when we doing the test with a small number of user But I observed the when a large amount of users are submitting not all data reaches the server only a part of some users answer (around 65 answer) only reaches the server.But i get data from my all users but some answers aren't compete. Am using MySql engine : MyISAM What would be the problem or how can i solve this. is it the problem with some php configuration or mysql (large number of insert statement) What is the best way to handle larger amount data from a form submission php Thanks in Advance
2018/03/15
[ "https://Stackoverflow.com/questions/49290741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941350/" ]
There is a limit on `POST` request size in PHP. You can adjust [`post_max_size`](http://php.net/ini.core.php#ini.post-max-size) in your `php.ini`. As for database, I don't know how you are saving them in the database, but there are character/storage limitation on the database as well. Whenever I'm dealing with large `POST` data like sending numerous field values through forms, using ajax does wonders! Try using jQuery [`$.post()`](https://api.jquery.com/jquery.post/), which is the shorthand for [`$.ajax()`](https://api.jquery.com/jQuery.ajax/). It's quite easy to use, even if you're not that familiar with jQuery :)
You should use the ajax function for post the data.. Go through bellow link,it might help you <https://www.w3schools.com/jquery/ajax_ajax.asp>
49,290,741
We are designing a system for conducting a survey in which it askes user a about 72 questions (Multiple Choice questions) And when the user submits this will be posted to php page which will save the answer in a MySQL table. Its works fine and perfectly well when we doing the test with a small number of user But I observed the when a large amount of users are submitting not all data reaches the server only a part of some users answer (around 65 answer) only reaches the server.But i get data from my all users but some answers aren't compete. Am using MySql engine : MyISAM What would be the problem or how can i solve this. is it the problem with some php configuration or mysql (large number of insert statement) What is the best way to handle larger amount data from a form submission php Thanks in Advance
2018/03/15
[ "https://Stackoverflow.com/questions/49290741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941350/" ]
You need to Increase max\_input\_vars from php.ini OR you can set the following code in your .htaccess file. ``` php_value max_input_vars 3000 ```
You should use the ajax function for post the data.. Go through bellow link,it might help you <https://www.w3schools.com/jquery/ajax_ajax.asp>
49,290,741
We are designing a system for conducting a survey in which it askes user a about 72 questions (Multiple Choice questions) And when the user submits this will be posted to php page which will save the answer in a MySQL table. Its works fine and perfectly well when we doing the test with a small number of user But I observed the when a large amount of users are submitting not all data reaches the server only a part of some users answer (around 65 answer) only reaches the server.But i get data from my all users but some answers aren't compete. Am using MySql engine : MyISAM What would be the problem or how can i solve this. is it the problem with some php configuration or mysql (large number of insert statement) What is the best way to handle larger amount data from a form submission php Thanks in Advance
2018/03/15
[ "https://Stackoverflow.com/questions/49290741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941350/" ]
There is a limit on `POST` request size in PHP. You can adjust [`post_max_size`](http://php.net/ini.core.php#ini.post-max-size) in your `php.ini`. As for database, I don't know how you are saving them in the database, but there are character/storage limitation on the database as well. Whenever I'm dealing with large `POST` data like sending numerous field values through forms, using ajax does wonders! Try using jQuery [`$.post()`](https://api.jquery.com/jquery.post/), which is the shorthand for [`$.ajax()`](https://api.jquery.com/jQuery.ajax/). It's quite easy to use, even if you're not that familiar with jQuery :)
You need to Increase max\_input\_vars from php.ini OR you can set the following code in your .htaccess file. ``` php_value max_input_vars 3000 ```
271,524
I'm building a mansion to impress my friends. I've seen pictures of armor stands with ARMS. I searched how to summon one but all of them were either 1.9 or beta. (?how?) What command do i use to summon one that works?
2016/06/27
[ "https://gaming.stackexchange.com/questions/271524", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/151855/" ]
You can watch [this tutorial](https://www.youtube.com/watch?v=LoLRLKyswTI) (by Sethbling) to see how to show arms and more But if you want to show arms, try: `/summon ArmorStand ~ ~ ~ {ShowArms:1}` If you already spawned a ArmorStand and want to add arms (show arms), you can do: `/entitydata @e[r=2,type=ArmorStand] {ShowArms:1}` (tested).
ArmorStands with the `ShowArms:1b` tag will have arms: ``` /summon ArmorStand ~ ~ ~ {ShowArms:1b} ``` You could also set this tag on the closest already-placed ArmorStands like so: ``` /entitydata @e[type=ArmorStand,c=1] {ShowArms:1b} ```
40,057,611
I'm trying to draw a set of rectangles, each with a fill color representing some value between 0 and 1. Ideally, I would like to use any standard colormap. Note that the rectangles are not placed in a nice grid, so using `imagesc`, `surf`, or similar seems unpractical. Also, the `scatter` function does not seem to allow me to assign a custom marker shape. Hence, I'm stuck to plotting a bunch of Rectangles in a for-loop and assigning a `FillColor` by hand. What's the most efficient way to compute RGB triplets from the scalar values? I've been unable to find a function along the lines of `[r,g,b] = val2rgb(value,colormap).` Right now, I've built a function which computes 'jet' values, after inspecting `rgbplot`(jet). This seems a bit silly. I could, of course, obtain values from an arbitrary colormap by interpolation, but this would be slow for large datasets. So, what would an efficient `[r,g,b] = val2rgb(value,colormap)` look like?
2016/10/15
[ "https://Stackoverflow.com/questions/40057611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7022877/" ]
You can use `complete` from package `tidyr` : ``` library("tidyr") data %>% complete(area, year, fill = list(population.served = 0)) # # A tibble: 16 × 3 # area year population.served # <fctr> <fctr> <dbl> # 1 Cambridge Year.1 200 # 2 Cambridge Year.2 202 # 3 Cambridge Year.3 204 # 4 Cambridge Year.4 207 # 5 Edinburgh Year.1 0 # 6 Edinburgh Year.2 0 # 7 Edinburgh Year.3 0 # 8 Edinburgh Year.4 210 # ..... ```
Here's one approach, using `expand.grid` from base R to fill out your table: ``` # make a dummy table with all time steps for all units DF <- with(data, expand.grid(area = unique(area), year = unique(year))) # merge the data with that table, using all.x = TRUE to keep the larger set DF <- merge(DF, data, all.x = TRUE) # replace the NAs in the expanded data frame with 0s DF[is.na(DF)] = 0 ```
40,057,611
I'm trying to draw a set of rectangles, each with a fill color representing some value between 0 and 1. Ideally, I would like to use any standard colormap. Note that the rectangles are not placed in a nice grid, so using `imagesc`, `surf`, or similar seems unpractical. Also, the `scatter` function does not seem to allow me to assign a custom marker shape. Hence, I'm stuck to plotting a bunch of Rectangles in a for-loop and assigning a `FillColor` by hand. What's the most efficient way to compute RGB triplets from the scalar values? I've been unable to find a function along the lines of `[r,g,b] = val2rgb(value,colormap).` Right now, I've built a function which computes 'jet' values, after inspecting `rgbplot`(jet). This seems a bit silly. I could, of course, obtain values from an arbitrary colormap by interpolation, but this would be slow for large datasets. So, what would an efficient `[r,g,b] = val2rgb(value,colormap)` look like?
2016/10/15
[ "https://Stackoverflow.com/questions/40057611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7022877/" ]
Here's one approach, using `expand.grid` from base R to fill out your table: ``` # make a dummy table with all time steps for all units DF <- with(data, expand.grid(area = unique(area), year = unique(year))) # merge the data with that table, using all.x = TRUE to keep the larger set DF <- merge(DF, data, all.x = TRUE) # replace the NAs in the expanded data frame with 0s DF[is.na(DF)] = 0 ```
An approach with the fast `data.table` package: ``` library(data.table) setDT(data)[CJ(area = area, year = year, unique = TRUE), on = c('area', 'year') ][is.na(population.served), population.served := 0][] ``` the result is then: ``` population.served area year 1: 200 Cambridge Year.1 2: 202 Cambridge Year.2 3: 204 Cambridge Year.3 4: 207 Cambridge Year.4 5: 0 Edinburgh Year.1 6: 0 Edinburgh Year.2 7: 0 Edinburgh Year.3 8: 210 Edinburgh Year.4 9: 0 London Year.1 10: 0 London Year.2 11: 206 London Year.3 12: 209 London Year.4 13: 201 Oxford Year.1 14: 203 Oxford Year.2 15: 205 Oxford Year.3 16: 208 Oxford Year.4 ```
40,057,611
I'm trying to draw a set of rectangles, each with a fill color representing some value between 0 and 1. Ideally, I would like to use any standard colormap. Note that the rectangles are not placed in a nice grid, so using `imagesc`, `surf`, or similar seems unpractical. Also, the `scatter` function does not seem to allow me to assign a custom marker shape. Hence, I'm stuck to plotting a bunch of Rectangles in a for-loop and assigning a `FillColor` by hand. What's the most efficient way to compute RGB triplets from the scalar values? I've been unable to find a function along the lines of `[r,g,b] = val2rgb(value,colormap).` Right now, I've built a function which computes 'jet' values, after inspecting `rgbplot`(jet). This seems a bit silly. I could, of course, obtain values from an arbitrary colormap by interpolation, but this would be slow for large datasets. So, what would an efficient `[r,g,b] = val2rgb(value,colormap)` look like?
2016/10/15
[ "https://Stackoverflow.com/questions/40057611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7022877/" ]
You can use `complete` from package `tidyr` : ``` library("tidyr") data %>% complete(area, year, fill = list(population.served = 0)) # # A tibble: 16 × 3 # area year population.served # <fctr> <fctr> <dbl> # 1 Cambridge Year.1 200 # 2 Cambridge Year.2 202 # 3 Cambridge Year.3 204 # 4 Cambridge Year.4 207 # 5 Edinburgh Year.1 0 # 6 Edinburgh Year.2 0 # 7 Edinburgh Year.3 0 # 8 Edinburgh Year.4 210 # ..... ```
An approach with the fast `data.table` package: ``` library(data.table) setDT(data)[CJ(area = area, year = year, unique = TRUE), on = c('area', 'year') ][is.na(population.served), population.served := 0][] ``` the result is then: ``` population.served area year 1: 200 Cambridge Year.1 2: 202 Cambridge Year.2 3: 204 Cambridge Year.3 4: 207 Cambridge Year.4 5: 0 Edinburgh Year.1 6: 0 Edinburgh Year.2 7: 0 Edinburgh Year.3 8: 210 Edinburgh Year.4 9: 0 London Year.1 10: 0 London Year.2 11: 206 London Year.3 12: 209 London Year.4 13: 201 Oxford Year.1 14: 203 Oxford Year.2 15: 205 Oxford Year.3 16: 208 Oxford Year.4 ```
34,523,149
I've developed app that takes screenshot. But it only takes snapshot of app. I want to take snapshot out of app. I've researched answers but I don't find answer yet. Here is my code. ``` View view = getWindow().getDecorView().getRootView(); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); saveImageToAppFolder(bitmap); ``` saveImagetoAppFolder is function that saves image to app folder. That's not problem. Is there anyway to take snapshot of screen?
2015/12/30
[ "https://Stackoverflow.com/questions/34523149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729314/" ]
To take screen shot of the device screen, **Only if you have root** call the screencap binary like: ``` Process sh = Runtime.getRuntime().exec("su", null,null); OutputStream os = sh.getOutputStream(); os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII")); os.flush(); os.close(); sh.waitFor() ``` And to load that file into a bitmap,Use ``` public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } ```
i don't know your code in saveImageToAppFolder is what but you can try this: Note: you need set background of your app/activity to transparent (100%). ``` //your code below is extractly View view = getWindow().getDecorView().getRootView(); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); //try my code for save image file to storage File imgFile = new File(imgPath); FileOutputStream os = new FileOutputStream(imageFile); int imgQuality = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, imgQuality , os); os.flush(); os.close(); ``` Code to set transparent background: //first: create theme xml below for transparent ``` <?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.Transparent" parent="android:Theme"> <item name="android:windowIsTranslucent">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:backgroundDimEnabled">false</item> </style> </resources> ``` after set by this way: ``` <activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent"> </activity> ``` note: you can red more detail from here url: [How do I create a transparent Activity on Android?](https://stackoverflow.com/questions/2176922/how-to-create-transparent-activity-in-android)
16,878,544
Want search every word in a dictionary what has the same character exactly at the second and last positon, and one times somewhere middle. examples: ``` statement - has the "t" at the second, fourth and last place severe = has "e" at 2,4,last abbxb = "b" at 2,3,last ``` wrong ``` abab = "b" only 2 times not 3 abxxxbyyybzzzzb - "b" 4 times, not 3 ``` my grep is not working ``` my @ok = grep { /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/ } @wordlist; ``` e.g. the ``` perl -nle 'print if /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/' < /usr/share/dict/words ``` prints for example the ``` zarabanda ``` what is wrong. What should be the correct regex? EDIT: And how to i can capture the enclosed groups? e.g. for the ``` statement - want cantupre: st(a)t(emen)t - for the later use my $w1 = $1; my w2 = $2; or something like... ```
2013/06/02
[ "https://Stackoverflow.com/questions/16878544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632407/" ]
This is the regex that should work for you: ``` ^.(.)(?=(?:.*?\1){2})(?!(?:.*?\1){3}).*?\1$ ``` ### Live Demo: <http://www.rubular.com/r/bEMgutE7t5>
Using lookahead: ``` /^.(.)(?!(?:.*\1){3}).*\1(.*)\1$/ ``` Meaning: ``` /^.(.)(?!(?:.*\1){3}) # capture the second character if it is not # repeated more than twice after the 2nd position .*\1(.*)\1$ # match captured char 2 times the last one at the end ```
16,878,544
Want search every word in a dictionary what has the same character exactly at the second and last positon, and one times somewhere middle. examples: ``` statement - has the "t" at the second, fourth and last place severe = has "e" at 2,4,last abbxb = "b" at 2,3,last ``` wrong ``` abab = "b" only 2 times not 3 abxxxbyyybzzzzb - "b" 4 times, not 3 ``` my grep is not working ``` my @ok = grep { /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/ } @wordlist; ``` e.g. the ``` perl -nle 'print if /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/' < /usr/share/dict/words ``` prints for example the ``` zarabanda ``` what is wrong. What should be the correct regex? EDIT: And how to i can capture the enclosed groups? e.g. for the ``` statement - want cantupre: st(a)t(emen)t - for the later use my $w1 = $1; my w2 = $2; or something like... ```
2013/06/02
[ "https://Stackoverflow.com/questions/16878544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632407/" ]
This is the regex that should work for you: ``` ^.(.)(?=(?:.*?\1){2})(?!(?:.*?\1){3}).*?\1$ ``` ### Live Demo: <http://www.rubular.com/r/bEMgutE7t5>
``` my @ok = grep {/^.(\w)/; /^.$1[^$1]*?$1[^$1]*$1$/ } @wordlist; ```
16,878,544
Want search every word in a dictionary what has the same character exactly at the second and last positon, and one times somewhere middle. examples: ``` statement - has the "t" at the second, fourth and last place severe = has "e" at 2,4,last abbxb = "b" at 2,3,last ``` wrong ``` abab = "b" only 2 times not 3 abxxxbyyybzzzzb - "b" 4 times, not 3 ``` my grep is not working ``` my @ok = grep { /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/ } @wordlist; ``` e.g. the ``` perl -nle 'print if /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/' < /usr/share/dict/words ``` prints for example the ``` zarabanda ``` what is wrong. What should be the correct regex? EDIT: And how to i can capture the enclosed groups? e.g. for the ``` statement - want cantupre: st(a)t(emen)t - for the later use my $w1 = $1; my w2 = $2; or something like... ```
2013/06/02
[ "https://Stackoverflow.com/questions/16878544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632407/" ]
`(?:(?!STRING).)*` is `STRING` as `[^CHAR]*` is to `CHAR`, so what you want is: ```none ^. # Ignore first char (.) # Capture second char (?:(?!\1).)* # Any number of chars that aren't the second char \1 # Second char (?:(?!\1).)* # Any number of chars that aren't the second char \1\z # Second char at the end of the string. ``` So you get: ``` perl -ne'print if /^. (.) (?:(?!\1).)* \1 (?:(?!\1).)* \1$/x' \ /usr/share/dict/words ``` To capture what's in between, add parens around both `(?:(?!\1).)*`. ``` perl -nle'print "$2:$3" if /^. (.) ((?:(?!\1).)*) \1 ((?:(?!\1).)*) \1\z/x' \ /usr/share/dict/words ```
Using lookahead: ``` /^.(.)(?!(?:.*\1){3}).*\1(.*)\1$/ ``` Meaning: ``` /^.(.)(?!(?:.*\1){3}) # capture the second character if it is not # repeated more than twice after the 2nd position .*\1(.*)\1$ # match captured char 2 times the last one at the end ```
16,878,544
Want search every word in a dictionary what has the same character exactly at the second and last positon, and one times somewhere middle. examples: ``` statement - has the "t" at the second, fourth and last place severe = has "e" at 2,4,last abbxb = "b" at 2,3,last ``` wrong ``` abab = "b" only 2 times not 3 abxxxbyyybzzzzb - "b" 4 times, not 3 ``` my grep is not working ``` my @ok = grep { /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/ } @wordlist; ``` e.g. the ``` perl -nle 'print if /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/' < /usr/share/dict/words ``` prints for example the ``` zarabanda ``` what is wrong. What should be the correct regex? EDIT: And how to i can capture the enclosed groups? e.g. for the ``` statement - want cantupre: st(a)t(emen)t - for the later use my $w1 = $1; my w2 = $2; or something like... ```
2013/06/02
[ "https://Stackoverflow.com/questions/16878544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632407/" ]
`(?:(?!STRING).)*` is `STRING` as `[^CHAR]*` is to `CHAR`, so what you want is: ```none ^. # Ignore first char (.) # Capture second char (?:(?!\1).)* # Any number of chars that aren't the second char \1 # Second char (?:(?!\1).)* # Any number of chars that aren't the second char \1\z # Second char at the end of the string. ``` So you get: ``` perl -ne'print if /^. (.) (?:(?!\1).)* \1 (?:(?!\1).)* \1$/x' \ /usr/share/dict/words ``` To capture what's in between, add parens around both `(?:(?!\1).)*`. ``` perl -nle'print "$2:$3" if /^. (.) ((?:(?!\1).)*) \1 ((?:(?!\1).)*) \1\z/x' \ /usr/share/dict/words ```
``` my @ok = grep {/^.(\w)/; /^.$1[^$1]*?$1[^$1]*$1$/ } @wordlist; ```
56,804,266
We are using [KubeDB](https://kubedb.com/docs/0.10.0/guides/redis/) in our cluster to manage our DB's. So Redis is deployed via a [KubeDB Redis object](https://kubedb.com/docs/0.10.0/concepts/databases/redis/) and KubeDB attaches a PVC to the Redis pod. Unfortunately KubeDB doesn't support any restoring or backing up of Redis dumps (yet). For the backup our solution is to have a CronJob running which copies the `dump.rdb` from the Redis pod into the job pod and then uploads it to S3. For the restoring of the dump I wanted to do the same, just the other way around. Have a temporary pod which downloads the S3 backup and then copies it over to the Redis pod into the `dump.rdb` location. The `redis.conf` looks like this: ``` .... # The filename where to dump the DB dbfilename dump.rdb # The working directory. # # The DB will be written inside this directory, with the filename specified # above using the 'dbfilename' configuration directive. # # The Append Only File will also be created inside this directory. # # Note that you must specify a directory here, not a file name. dir /data .... ``` The copying works. The `dump.rdb` is in the correct location with the correct permissions. I verified this by starting a second redis-server in the Redis pod using the same `redis.conf`. The `dump.rdb` is being loaded into the server without a problem. However, since I don't want to manually start a second redis-server, I restarted the Redis pod (by kubectl delete pods) for the pod to pickup the copied `dump.rdb`. Everytime I delete the pod, the `dump.rdb` is deleted and a new `dump.rdb` is being created with a much smaller size (93 bytes). I don't believe it is a PVC issue since I have created a few files to test whether they are deleted as well. They are not. Only the `dump.rdb`. Why does this happen? I am expecting Redis to just restore the DB from the `dump.rdb` and not create a new one. EDIT: Yeah, size of `dump.rdb` is around 47 GB. Redis version is 4.0.11.
2019/06/28
[ "https://Stackoverflow.com/questions/56804266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2591194/" ]
Sooo, a few hours later, my teammate remembered that Redis executes a save to dump on [shutdown](https://redis.io/commands/shutdown). Instead of deleting the pod using `kubectl delete pod` I now changed the code to run a `SHUTDOWN NOSAVE` using the `redis-cli`. ``` kubectl exec <redis-pod> -- /bin/bash -c 'redis-cli -a $(cat /usr/local/etc/redis/redis.conf | grep "requirepass " | sed -e "s/requirepass //g") SHUTDOWN NOSAVE' ```
Restore Redis on Kubernetes AOF = yes: -------------------------------------- The first thing to do is remove redis deployment from kubernetes server: ``` kubectl delete -f ./redis.yaml ``` Attach to the redis persistent storage (PVC) on mounted file system it can be GlusterFS - Volume, Azure Storage - File Share, min.io S3 bucket Then, remove the current dumb.rdb file (if there is one) or rename it to dump.rdb.old: Copy the good backup dump.rdb file in and correct its permission: ``` chown 999:999 dump.rdb chmod 644 dump.rdb ``` Next the important part is to disable AOF by editing redis.yaml file, set appendonly as "no": Verify appendonlu is set to "no": ``` containers: - name: redis image: redis:5.0.4 imagePullPolicy: Always args: ["--requirepass", "$(redis_pass)", "--appendonly", "no", "--save", "900", "1", "--save", "30", "1"] ``` Next create the Redis deployment on kubernetes: ``` kubectl apply-f ./redis.yaml ``` Run the following command to create new appendonly.aof file ``` kubectl exec redis-0 -- redis-cli -a <redis-secret> bgrewriteaof ``` Check the progress (0 - done, 1 - not yet), and if exists new appendonly.aof file on the same size like dump.rdb ``` kubectl exec redis-0 -- redis-cli -a <redis-secret> info | grep aof_rewrite_in_progress ``` You should see a new appendonly.aof file. Next, recreate redis server: After it finished, enable AOF again by changing redis.yaml file to yes ``` containers: - name: redis image: redis:5.0.4 imagePullPolicy: Always args: ["--requirepass", "$(redis_pass)", "--appendonly", "yes", "--save", "900", "1", "--save", "30", "1"] ``` Then recreate the Redis server again: ``` kubectl delete-f ./redis.yaml kubectl apply-f ./redis.yaml ``` The Restore is completed. If you have linux with installed redis as service please use this instruction: <https://community.pivotal.io/s/article/How-to-Backup-and-Restore-Open-Source-Redis?language=en_US>
38,138,478
I have a print table code fiddle [LINK](http://jsfiddle.net/9DbEP/1060/) Check my code: ``` function printData() { var divToPrint=document.getElementById("printTable"); console.log(divToPrint.outerHTML); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); newWin.print(); newWin.close(); } ``` I have added `background-color` to that as red as you can see in fiddle. I tried to print it. But in print the color not coming and all other things works fine. I have researched about `@media print` and all but unable to crack it. please guide me and an updated fiddle will be awesome you can give me. Cheers!
2016/07/01
[ "https://Stackoverflow.com/questions/38138478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4387657/" ]
Please find chrome driver here <https://sites.google.com/a/chromium.org/chromedriver/downloads>
Use this Selenium site you have drivers for all browsers even for phone's.. Check it <http://www.seleniumhq.org/download/> - You may find there chrome webdriver 2.22Version
38,138,478
I have a print table code fiddle [LINK](http://jsfiddle.net/9DbEP/1060/) Check my code: ``` function printData() { var divToPrint=document.getElementById("printTable"); console.log(divToPrint.outerHTML); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); newWin.print(); newWin.close(); } ``` I have added `background-color` to that as red as you can see in fiddle. I tried to print it. But in print the color not coming and all other things works fine. I have researched about `@media print` and all but unable to crack it. please guide me and an updated fiddle will be awesome you can give me. Cheers!
2016/07/01
[ "https://Stackoverflow.com/questions/38138478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4387657/" ]
The versions on [the chromedriver download page](http://chromedriver.storage.googleapis.com/index.html) are sorted alphabetically, not numerically or chronologically. That means that `2.9` appears at the bottom of the page, which might make it look like the "last" or "most recent" version. The actual most recent version as of this writing is, in fact, `2.22`.
Use this Selenium site you have drivers for all browsers even for phone's.. Check it <http://www.seleniumhq.org/download/> - You may find there chrome webdriver 2.22Version
43,917
I am traveling from Stockholm to Dubai and Dubai to Nairobi using two different airlines. I have Kenyan nationality and can't go through Immigration because I don't have a Dubai visa. How I will get my luggage?
2015/02/27
[ "https://travel.stackexchange.com/questions/43917", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/27260/" ]
If your luggage is not checked through, then I am afraid you will have to collect it and to do that you'll need a visa as the baggage carousels are *after* the immigration counters. The sequence is: 1. De-plane. 2. Depending on the terminal, you'll have a long walk (and then go down a few flights of stairs) or a short one, or really no walk at all (if you are at Terminal 2, as the bus will drop you right at the immigration counter). 3. The bank counter where you pay for the on-arrival visa will be on your right (Terminal 3, 2), or on your left (Terminal 1). 4. Go through immigration, then turn right to go through the metal detectors where they will scan your carryon luggage (in Terminal 3 its a straight walk). 5. Collect your baggage. 6. Go through either the Green Channel or the Red Channel (depending on what you have to declare). 7. Welcome to Dubai. I'm afraid you'll need a visa - the good news is a transit visa is available at the counter if you can show a continuing ticket/itinerary.
Do you plan to actually immigrate into Dubai (will you leave the airport)? Without a visa you will not be able to leave the transit area of the airport. It sounds like you are just passing through Dubai on a layover. You will be forced to go through arrival security check after you deplane no matter what your Nationality is. Whether or not you are flying with airlines in the same alliance, you will need to pick up your bag from the customs baggage drop, which will be after the security check but before immigration. Don't worry you'll see a lot of people in the same situation as you. Follow the crowd if in doubt. Or just ask one of the airport staff. They speak many languages. The next step will depend if your itinerary was booked with the same airline or alliance or not. If your bags are checked through, your bag should already have a tag indicating your final destination (NBO). If it already has a tag for NBO, then just drop it off at the baggage intake. If not, then you will need to go to the transfer desk (still in the "sterile" zone, within the transit area) of the airline you have your final flight on to issue your luggage documents, and then you will take your tagged bag to the baggage intake. As long as your baggage has a tag with NBO marked on it, you will be OK.
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (`objc_msgSend_stret` vs. `objc_msgSend`). Please make sure you declare `phrase` as ``` Phrase* phrase = ...; ``` so that the compiler knows `-rangeInString:…` is returning an NSRange, instead of ``` id phrase = ...; ``` (Also, since you don't show which line the compiler errors, make sure the function using `return … == -1;` is returning a BOOL not NSRange.)
> > Can a method return an NSRange? > > > Yes. > > This method is called within the Phrase object by other methods without problems. … When I call this method from outside the class I get a compile error. … The compiler says 'incompatible types in assignment'. > > > Remember to `#import` Phrase.h into the implementation file where you're talking to a Phrase object. Otherwise, the compiler doesn't know about your `rangeOfString:forString:goingForward:` method and *assumes* that it returns `id`. It needs the `@interface` in the header file to *know* that the method returns `NSRange`. Assuming that your phrase object is in an instance variable, you probably declared the Phrase class with `@class Phrase;` in the header file where you declared the ivar. That's a forward declaration; it tells the compiler that a class named “Phrase” exists (so that a declaration like `Phrase *myPhrase` will be legal), but it doesn't tell the compiler anything else about it. To do that, you need to import the header. The general rule, for instances of class A knowing about instances of class B, is for A's header (A.h) to forward-declare class B with `@class`, and A's implementation (A.m) to import B's header (B.h). A different case is when A is a subclass of B. You need the `@interface` to make a subclass, so in this case and this case only, A.h must import B.h. Since it's importing the header for B, it does not need to forward-declare B.
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (`objc_msgSend_stret` vs. `objc_msgSend`). Please make sure you declare `phrase` as ``` Phrase* phrase = ...; ``` so that the compiler knows `-rangeInString:…` is returning an NSRange, instead of ``` id phrase = ...; ``` (Also, since you don't show which line the compiler errors, make sure the function using `return … == -1;` is returning a BOOL not NSRange.)
I don't think this is the answer, but NSRange.location is declared as NSUInteger. By comparing it to -1, you are comparing an unsigned value to a signed value. The only other answer I can think of is that the .m file you are making the call from has not imported the header Phrase.h. Now, I know you believe it has, but the compiler is saying otherwise. Try running the preprocessor on the file to see what it is actually importing. (right click in an editor containing the .m file - preprocess is near the bottom of the context menu that pops up).
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (`objc_msgSend_stret` vs. `objc_msgSend`). Please make sure you declare `phrase` as ``` Phrase* phrase = ...; ``` so that the compiler knows `-rangeInString:…` is returning an NSRange, instead of ``` id phrase = ...; ``` (Also, since you don't show which line the compiler errors, make sure the function using `return … == -1;` is returning a BOOL not NSRange.)
Yes, you can return C structs in methods. That is not the problem. Also, location is an NSUInteger and will never be -1. Use NSNotFound to test for that. How is the instance of your Phrase object typed? Did you use `id` instead of `Phrase *`? Have you properly imported the Phrase header? You should give us more information about the code that's giving the compile error.
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (`objc_msgSend_stret` vs. `objc_msgSend`). Please make sure you declare `phrase` as ``` Phrase* phrase = ...; ``` so that the compiler knows `-rangeInString:…` is returning an NSRange, instead of ``` id phrase = ...; ``` (Also, since you don't show which line the compiler errors, make sure the function using `return … == -1;` is returning a BOOL not NSRange.)
In response to some questions that are coming up: ``` #import <Foundation/Foundation.h> #import "OverlayView.h" #import "Phrase.h" #import "TimerPaneView.h" ``` Is the header in the MainPane.h, the class header for where the call is being made. In the header for MainPane.h, phrase is declared: ``` Phrase *phrase; ``` And in the implementation file, which, yes, imports the MainPane header: ``` phrase = [[Phrase alloc] init]; ``` Is how the phrase class is being instantiated, in the initWithFrame method. I refer to the phrase object dozens and dozens of times, calling methods, referring to properties in this class, without problems. And no, the phrase object is never released until dealloc. -- added: I thought I had found the problem: a collapsed section of code that never is called that had a legacy return value that was BOOL. This method originally returned BOOL, but was converted. But I eliminated it, and the problem remains. I should also say that I've refactored my way around this problem, but it remains a mystery...
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
> > Can a method return an NSRange? > > > Yes. > > This method is called within the Phrase object by other methods without problems. … When I call this method from outside the class I get a compile error. … The compiler says 'incompatible types in assignment'. > > > Remember to `#import` Phrase.h into the implementation file where you're talking to a Phrase object. Otherwise, the compiler doesn't know about your `rangeOfString:forString:goingForward:` method and *assumes* that it returns `id`. It needs the `@interface` in the header file to *know* that the method returns `NSRange`. Assuming that your phrase object is in an instance variable, you probably declared the Phrase class with `@class Phrase;` in the header file where you declared the ivar. That's a forward declaration; it tells the compiler that a class named “Phrase” exists (so that a declaration like `Phrase *myPhrase` will be legal), but it doesn't tell the compiler anything else about it. To do that, you need to import the header. The general rule, for instances of class A knowing about instances of class B, is for A's header (A.h) to forward-declare class B with `@class`, and A's implementation (A.m) to import B's header (B.h). A different case is when A is a subclass of B. You need the `@interface` to make a subclass, so in this case and this case only, A.h must import B.h. Since it's importing the header for B, it does not need to forward-declare B.
I don't think this is the answer, but NSRange.location is declared as NSUInteger. By comparing it to -1, you are comparing an unsigned value to a signed value. The only other answer I can think of is that the .m file you are making the call from has not imported the header Phrase.h. Now, I know you believe it has, but the compiler is saying otherwise. Try running the preprocessor on the file to see what it is actually importing. (right click in an editor containing the .m file - preprocess is near the bottom of the context menu that pops up).
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
> > Can a method return an NSRange? > > > Yes. > > This method is called within the Phrase object by other methods without problems. … When I call this method from outside the class I get a compile error. … The compiler says 'incompatible types in assignment'. > > > Remember to `#import` Phrase.h into the implementation file where you're talking to a Phrase object. Otherwise, the compiler doesn't know about your `rangeOfString:forString:goingForward:` method and *assumes* that it returns `id`. It needs the `@interface` in the header file to *know* that the method returns `NSRange`. Assuming that your phrase object is in an instance variable, you probably declared the Phrase class with `@class Phrase;` in the header file where you declared the ivar. That's a forward declaration; it tells the compiler that a class named “Phrase” exists (so that a declaration like `Phrase *myPhrase` will be legal), but it doesn't tell the compiler anything else about it. To do that, you need to import the header. The general rule, for instances of class A knowing about instances of class B, is for A's header (A.h) to forward-declare class B with `@class`, and A's implementation (A.m) to import B's header (B.h). A different case is when A is a subclass of B. You need the `@interface` to make a subclass, so in this case and this case only, A.h must import B.h. Since it's importing the header for B, it does not need to forward-declare B.
Yes, you can return C structs in methods. That is not the problem. Also, location is an NSUInteger and will never be -1. Use NSNotFound to test for that. How is the instance of your Phrase object typed? Did you use `id` instead of `Phrase *`? Have you properly imported the Phrase header? You should give us more information about the code that's giving the compile error.
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
> > Can a method return an NSRange? > > > Yes. > > This method is called within the Phrase object by other methods without problems. … When I call this method from outside the class I get a compile error. … The compiler says 'incompatible types in assignment'. > > > Remember to `#import` Phrase.h into the implementation file where you're talking to a Phrase object. Otherwise, the compiler doesn't know about your `rangeOfString:forString:goingForward:` method and *assumes* that it returns `id`. It needs the `@interface` in the header file to *know* that the method returns `NSRange`. Assuming that your phrase object is in an instance variable, you probably declared the Phrase class with `@class Phrase;` in the header file where you declared the ivar. That's a forward declaration; it tells the compiler that a class named “Phrase” exists (so that a declaration like `Phrase *myPhrase` will be legal), but it doesn't tell the compiler anything else about it. To do that, you need to import the header. The general rule, for instances of class A knowing about instances of class B, is for A's header (A.h) to forward-declare class B with `@class`, and A's implementation (A.m) to import B's header (B.h). A different case is when A is a subclass of B. You need the `@interface` to make a subclass, so in this case and this case only, A.h must import B.h. Since it's importing the header for B, it does not need to forward-declare B.
In response to some questions that are coming up: ``` #import <Foundation/Foundation.h> #import "OverlayView.h" #import "Phrase.h" #import "TimerPaneView.h" ``` Is the header in the MainPane.h, the class header for where the call is being made. In the header for MainPane.h, phrase is declared: ``` Phrase *phrase; ``` And in the implementation file, which, yes, imports the MainPane header: ``` phrase = [[Phrase alloc] init]; ``` Is how the phrase class is being instantiated, in the initWithFrame method. I refer to the phrase object dozens and dozens of times, calling methods, referring to properties in this class, without problems. And no, the phrase object is never released until dealloc. -- added: I thought I had found the problem: a collapsed section of code that never is called that had a legacy return value that was BOOL. This method originally returned BOOL, but was converted. But I eliminated it, and the problem remains. I should also say that I've refactored my way around this problem, but it remains a mystery...
57,546,243
I have this data's is there a way to get all of these? already tried `this._data.forEach` but it is not working thanks! ``` data() { return { childData: '', credit: '', company: '', email: '', first_name: '', middle_name: '', terms: '', last_name: '', phone: '', mobile: '', fax: '', street: '', city: '', country: '', state: '', zip_code: '', as_of: '', account_number: '', website:'', open_balance: '', notes: '', files: null, } ```
2019/08/18
[ "https://Stackoverflow.com/questions/57546243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10022569/" ]
try this perhaps: ``` =QUERY(IMPORTXML(B4, "//*[@id='historical-data']/div/div[2]/table/tbody/tr/td[2]"), "limit 100", 0) ```
The `[1:100]` syntax does not work. Try `[position()<=100]` instead: ``` =importxml(B4,"//*[@id='historical-data']/div/div[2]/table/tbody/tr[position()<=100]/td[2]") ```
57,546,243
I have this data's is there a way to get all of these? already tried `this._data.forEach` but it is not working thanks! ``` data() { return { childData: '', credit: '', company: '', email: '', first_name: '', middle_name: '', terms: '', last_name: '', phone: '', mobile: '', fax: '', street: '', city: '', country: '', state: '', zip_code: '', as_of: '', account_number: '', website:'', open_balance: '', notes: '', files: null, } ```
2019/08/18
[ "https://Stackoverflow.com/questions/57546243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10022569/" ]
try this perhaps: ``` =QUERY(IMPORTXML(B4, "//*[@id='historical-data']/div/div[2]/table/tbody/tr/td[2]"), "limit 100", 0) ```
I switched IMPORTXML for IMPORTHTML to give quite an elegant solution: ``` =query(importhtml(B4,"table",1),"select Col2 limit 110 offset 1",0) ``` Shoutout to @player0 for getting me 90% there.
45,589,463
i've read a lot of blogs, tutorials & co but i don't get something about the dynamic binding in java. When i create the object called "myspecialcar" it's creates an object from the class "car" as type of the class vehicle as a dynamic binding right? So java know that when i execute the method *myspecialcar.getType()* i have a car object and it execute the method from the class car. But why i got the *type* from the class vehicle? Is that because the variable from the class vehicle (type) is a static binding? Regards, Code: ``` public class vehicle { String type = "vehicle"; public String getType(){ return type; } } ``` ``` public class car extends vehicle { String type = "car"; public String getType(){ return type; } } ``` ``` public class test { public static void main (String[] args){ vehicle myvehicle = new vehicle(); // static binding car mycar = new car(); // static binding vehicle myspecialcar = new car(); //dynamic binding System.out.println(myspecialcar.getType()); System.out.println(myspecialcar.type); System.out.println(myspecialcar.getClass()); } } ``` Output: ``` car vehicle class car ```
2017/08/09
[ "https://Stackoverflow.com/questions/45589463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747959/" ]
You faced the [fields hiding](http://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html). > > Within a class, a field that has the same name as a field in the > superclass hides the superclass's field, even if their types are > different. Within the subclass, the field in the superclass cannot be > referenced by its simple name. Instead, the field must be accessed > through super, which is covered in the next section. Generally > speaking, we don't recommend hiding fields as it makes code difficult > to read. > > >
There is a difference between `hiding` and `overriding`. You can not override class fields, but rather class methods. This means in your concrete example that ``` Vehicle mySpecialCar = new Car() // use upperCase and lowerUpperCase pls ``` You have a type of `Vehicle` which is an instance of `Car`. The over riden methods will be used while the class fields will be hidden. If you use ``` Car myCar = new Car() ``` you will get ``` myCar.type // car myCar.super.type // vehicle ```
45,589,463
i've read a lot of blogs, tutorials & co but i don't get something about the dynamic binding in java. When i create the object called "myspecialcar" it's creates an object from the class "car" as type of the class vehicle as a dynamic binding right? So java know that when i execute the method *myspecialcar.getType()* i have a car object and it execute the method from the class car. But why i got the *type* from the class vehicle? Is that because the variable from the class vehicle (type) is a static binding? Regards, Code: ``` public class vehicle { String type = "vehicle"; public String getType(){ return type; } } ``` ``` public class car extends vehicle { String type = "car"; public String getType(){ return type; } } ``` ``` public class test { public static void main (String[] args){ vehicle myvehicle = new vehicle(); // static binding car mycar = new car(); // static binding vehicle myspecialcar = new car(); //dynamic binding System.out.println(myspecialcar.getType()); System.out.println(myspecialcar.type); System.out.println(myspecialcar.getClass()); } } ``` Output: ``` car vehicle class car ```
2017/08/09
[ "https://Stackoverflow.com/questions/45589463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747959/" ]
You do not override class variables in Java you hide them. Overriding is for instance methods. Hiding is different from overriding. In your case you are hiding the member variable of super class. But after creating the object you can access the hidden member of the super class.
There is a difference between `hiding` and `overriding`. You can not override class fields, but rather class methods. This means in your concrete example that ``` Vehicle mySpecialCar = new Car() // use upperCase and lowerUpperCase pls ``` You have a type of `Vehicle` which is an instance of `Car`. The over riden methods will be used while the class fields will be hidden. If you use ``` Car myCar = new Car() ``` you will get ``` myCar.type // car myCar.super.type // vehicle ```
45,589,463
i've read a lot of blogs, tutorials & co but i don't get something about the dynamic binding in java. When i create the object called "myspecialcar" it's creates an object from the class "car" as type of the class vehicle as a dynamic binding right? So java know that when i execute the method *myspecialcar.getType()* i have a car object and it execute the method from the class car. But why i got the *type* from the class vehicle? Is that because the variable from the class vehicle (type) is a static binding? Regards, Code: ``` public class vehicle { String type = "vehicle"; public String getType(){ return type; } } ``` ``` public class car extends vehicle { String type = "car"; public String getType(){ return type; } } ``` ``` public class test { public static void main (String[] args){ vehicle myvehicle = new vehicle(); // static binding car mycar = new car(); // static binding vehicle myspecialcar = new car(); //dynamic binding System.out.println(myspecialcar.getType()); System.out.println(myspecialcar.type); System.out.println(myspecialcar.getClass()); } } ``` Output: ``` car vehicle class car ```
2017/08/09
[ "https://Stackoverflow.com/questions/45589463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747959/" ]
Instance Method Rule -------------------- When an instance method is invoked on an object using a reference, it is the *class* of the current object denoted by the reference, not the *type* of the reference, that determines which method implementation will be executed. Instance Property/Field Rule ---------------------------- When a field of an object is accessed using a reference, it is the *type* of the reference, not the *class* of the current object denoted by the reference, that determines which field will actually be accessed.
There is a difference between `hiding` and `overriding`. You can not override class fields, but rather class methods. This means in your concrete example that ``` Vehicle mySpecialCar = new Car() // use upperCase and lowerUpperCase pls ``` You have a type of `Vehicle` which is an instance of `Car`. The over riden methods will be used while the class fields will be hidden. If you use ``` Car myCar = new Car() ``` you will get ``` myCar.type // car myCar.super.type // vehicle ```
23,434
A friend of a friend has on multiple occasions aggressively asked how my self-study for software engineering interviews is going. Most recently I answered very briefly, because I find it too nosy and the person to be arrogant and presumptuous. I don't like for example that he's convinced that I seem too calm about the job interview preparation process and that I don't push myself hard enough. Initially I just listened to him rant over the phone, and after he realized he was doing all the talking he then asked for my input and I answered honestly. Then he would "check in" with me over Messenger or when I ran into him at a party it would be the first topic of conversation. Since he didn't change, one thing I did when he was doing the same to someone else right in front of me was I asked "What do you mean?" and he simply acknowledged he was rambling. I've been distancing myself from him as of late which is tricky since he's in a few of my friend groups - I have no desire to "win." How do I convey that I'm not interested in him essentially interrogating me and opining in career-related matters?
2019/11/11
[ "https://interpersonal.stackexchange.com/questions/23434", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/4886/" ]
It sounds like you have already figured out this person's *motivation* for asking you questions - they want to give you advice. "Advice-giver" is a [recognised personality trait](https://www.psychologytoday.com/gb/blog/evolution-the-self/201308/what-you-should-know-about-advice-givers), and many do it for their own ego gratification. As the opportunity to give advice is evidently what is prompting the questions, if you stop fuelling him by answering them, the advice will hopefully stop. [This article](https://www.psychologytoday.com/gb/blog/fulfillment-any-age/201506/9-ways-handle-nosy-people) on Psychology Today suggests various ways of dealing with nosy people. Two of those ways are: 1. **Tell the truth** This could be the best approach if you don't want to be rude to the person. Answer their questions, but severely limit what you tell them. If they ask how it is going, you could just say "*it's going great, thanks*". Give yes/no answers to their questions if you think that will cut him short. If he persists then you could cut it short by saying something like "*that's a lot of questions, shall we talk about something else?*" 2. **Deflection** If you are comfortable being more direct in telling them that you don't want to talk about this, this approach is about not answering any questions at all. Change the subject - perhaps say "*I'm bored with study, I'd rather talk about something else"*. Other techniques include stating your discomfort about the questions, but that may send the message that your self-study is not going too well, and that may not be the message you want to send. Ultimately though, not allowing an 'advice-giver' to give you advice is like starving them of their oxygen. They will not be interested in pursuing you for answers if they aren't getting what they want out of it.
From the way you describe it in your question, it sounds to me like you're already dealing with the situation perfectly well. As you yourself have said: you let them ramble on, you were honest with them when asked for feedback, then later you distanced yourself from them. It sounds like you have already "convey[ed] that [you're] not interested in him essentially interrogating [you] and opining in career-related matters". It also sounds like this person is just one of the many random people you'll run into in your life. This guy could be an arrogant loudmouth, or he could be clumsily and unsuccessfully trying to make friends; we can't know. In short: keep on doing what you're doing - he'll get the message and leave you alone. If you don't feel that's good enough - that you've already tried the polite approach - then you can more forcefully reiterate your disinterest, or simply ignore them and go and talk to someone else. You're not obliged to entertain every person who wants to talk at you, after all.
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
In case, if you are getting the same error in latest environment (VS 2017/.NET Framework 4.6.x) and with entityframeworks like 6.1 or 6.2, here is the solution; Downgrade your entityframework to 6.0. It'll work.
This question is now the top SO answer for this question so I figured I would answer it generally here. The `The type 'BLAH' exists in both` error often pops up in the following occassions: **1. DUPLICATE FILES** - (often very simple) This is notoriously the case with .dll files. In most cases of duplication, deletion of one of the duplicate files is the easiest and best solution **2. NON-DUPLICATE FILES** - (more complicated, such as the original poster's case) you unfortunately need to edit and often recompile/find alternate versions of the files so that conflicts like this do not arise. Luckily more often than not, qualifying the attribute with the same namespace will fix conflicts like this. *For example if your code is conflicted on something called `MaxLength` that is mentioned in several files, then qualify it on necessary files to make it very clear which MaxLength you want to use like so: `System.ComponentModel.DataAnnotations.MaxLength`. This should help to clear things up, so nothing gets conflicted when trying to run your code*
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Use using at the top of your code: ``` using MaxLength = System.ComponentModel.DataAnnotations ```
This question is now the top SO answer for this question so I figured I would answer it generally here. The `The type 'BLAH' exists in both` error often pops up in the following occassions: **1. DUPLICATE FILES** - (often very simple) This is notoriously the case with .dll files. In most cases of duplication, deletion of one of the duplicate files is the easiest and best solution **2. NON-DUPLICATE FILES** - (more complicated, such as the original poster's case) you unfortunately need to edit and often recompile/find alternate versions of the files so that conflicts like this do not arise. Luckily more often than not, qualifying the attribute with the same namespace will fix conflicts like this. *For example if your code is conflicted on something called `MaxLength` that is mentioned in several files, then qualify it on necessary files to make it very clear which MaxLength you want to use like so: `System.ComponentModel.DataAnnotations.MaxLength`. This should help to clear things up, so nothing gets conflicted when trying to run your code*
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
In case, if you are getting the same error in latest environment (VS 2017/.NET Framework 4.6.x) and with entityframeworks like 6.1 or 6.2, here is the solution; Downgrade your entityframework to 6.0. It'll work.
MaxLength is not a function, it's an Attribute. You can use the using directive in each file to specify the current correct context. Or just type the full namespace, e.g. `System.ComponentModel.DataAnnotations.MaxLength`
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Just Uninstall EntityFramework from packages and reinstall it(EntityFramework). It works for me. Just follow the steps mentioned below: [![1.Right click on reference 2.Click on manage nugetpackages](https://i.stack.imgur.com/cfYdB.png)](https://i.stack.imgur.com/cfYdB.png) 1.Right click on reference 2.Click on manage nugetpackages. [![3.Click on Uninstall ](https://i.stack.imgur.com/LfAEp.png)](https://i.stack.imgur.com/LfAEp.png) 3.Click on Uninstall 4. go in online section and type entity frame work in search box 5. Click on install button [![4. go in online section and type entity frame work in search box 5. Click on install button](https://i.stack.imgur.com/HZJUa.png)](https://i.stack.imgur.com/HZJUa.png)
MaxLength is not a function, it's an Attribute. You can use the using directive in each file to specify the current correct context. Or just type the full namespace, e.g. `System.ComponentModel.DataAnnotations.MaxLength`
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Qualify the attribute with the desired namespace ``` [System.ComponentModel.DataAnnotations.MaxLength(50)] public string LastName { get; set; } ```
This question is now the top SO answer for this question so I figured I would answer it generally here. The `The type 'BLAH' exists in both` error often pops up in the following occassions: **1. DUPLICATE FILES** - (often very simple) This is notoriously the case with .dll files. In most cases of duplication, deletion of one of the duplicate files is the easiest and best solution **2. NON-DUPLICATE FILES** - (more complicated, such as the original poster's case) you unfortunately need to edit and often recompile/find alternate versions of the files so that conflicts like this do not arise. Luckily more often than not, qualifying the attribute with the same namespace will fix conflicts like this. *For example if your code is conflicted on something called `MaxLength` that is mentioned in several files, then qualify it on necessary files to make it very clear which MaxLength you want to use like so: `System.ComponentModel.DataAnnotations.MaxLength`. This should help to clear things up, so nothing gets conflicted when trying to run your code*
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Use using at the top of your code: ``` using MaxLength = System.ComponentModel.DataAnnotations ```
Try using extern alias <http://msdn.microsoft.com/en-us/library/ms173212.aspx> to differentiate between the two assemblies Also check out <http://bartdesmet.net/blogs/bart/archive/2006/10/07/4502.aspx> near the bottom of the page is an example
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Qualify the attribute with the desired namespace ``` [System.ComponentModel.DataAnnotations.MaxLength(50)] public string LastName { get; set; } ```
MaxLength is not a function, it's an Attribute. You can use the using directive in each file to specify the current correct context. Or just type the full namespace, e.g. `System.ComponentModel.DataAnnotations.MaxLength`
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Just Uninstall EntityFramework from packages and reinstall it(EntityFramework). It works for me. Just follow the steps mentioned below: [![1.Right click on reference 2.Click on manage nugetpackages](https://i.stack.imgur.com/cfYdB.png)](https://i.stack.imgur.com/cfYdB.png) 1.Right click on reference 2.Click on manage nugetpackages. [![3.Click on Uninstall ](https://i.stack.imgur.com/LfAEp.png)](https://i.stack.imgur.com/LfAEp.png) 3.Click on Uninstall 4. go in online section and type entity frame work in search box 5. Click on install button [![4. go in online section and type entity frame work in search box 5. Click on install button](https://i.stack.imgur.com/HZJUa.png)](https://i.stack.imgur.com/HZJUa.png)
In case, if you are getting the same error in latest environment (VS 2017/.NET Framework 4.6.x) and with entityframeworks like 6.1 or 6.2, here is the solution; Downgrade your entityframework to 6.0. It'll work.
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Qualify the attribute with the desired namespace ``` [System.ComponentModel.DataAnnotations.MaxLength(50)] public string LastName { get; set; } ```
Try using extern alias <http://msdn.microsoft.com/en-us/library/ms173212.aspx> to differentiate between the two assemblies Also check out <http://bartdesmet.net/blogs/bart/archive/2006/10/07/4502.aspx> near the bottom of the page is an example
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Use using at the top of your code: ``` using MaxLength = System.ComponentModel.DataAnnotations ```
MaxLength is not a function, it's an Attribute. You can use the using directive in each file to specify the current correct context. Or just type the full namespace, e.g. `System.ComponentModel.DataAnnotations.MaxLength`
609,275
I administer a large number of ESXi hosts, and in order to do that efficiently, I pretty much need to have SSH allowed into the hosts at all times, as it's just far too burdensome to enable and disable SSH access through vCenter/vSphere on every host every time I need to log into a host and view the CLI or SCP files between hosts, or whatever else. However, the problem I'm facing is that the default behavior in vSphere is to display a warning icon and nag-banner on any host for which SSH access is enabled. [![enter image description here](https://i.stack.imgur.com/VB6W2.png)](https://i.stack.imgur.com/VB6W2.png) More than just being annoying, this makes it impossible to see from a quick visual scan if there's a warning condition I actually care about on any of my hosts, like high CPU or memory usage, or low disk space, loss of redundancy, etc. So, how do I get rid of this warning icon (and if possible, the nag banner as well)?
2014/07/01
[ "https://serverfault.com/questions/609275", "https://serverfault.com", "https://serverfault.com/users/118258/" ]
This particular alert can be controlled in the `Advanced Settings` under the `Configuration` tab for the host in question. Once there, go to the `UserVars` category and scroll down to `UserVars.SuppressShellWarning`. Change the value from `0` to `1`, and you will no longer be warned that the host in question is allowing SSH access. [![enter image description here](https://i.stack.imgur.com/fuHss.png)](https://i.stack.imgur.com/fuHss.png)
In vSphere 5.5 and greater, this is easily accomplished from the vSphere Web Client interface by clicking the **Suppress Warning** link to the right of the warning text... [![enter image description here](https://i.stack.imgur.com/IdLp5.png)](https://i.stack.imgur.com/IdLp5.png) ![enter image description here](https://i.stack.imgur.com/m6BM0.png)
609,275
I administer a large number of ESXi hosts, and in order to do that efficiently, I pretty much need to have SSH allowed into the hosts at all times, as it's just far too burdensome to enable and disable SSH access through vCenter/vSphere on every host every time I need to log into a host and view the CLI or SCP files between hosts, or whatever else. However, the problem I'm facing is that the default behavior in vSphere is to display a warning icon and nag-banner on any host for which SSH access is enabled. [![enter image description here](https://i.stack.imgur.com/VB6W2.png)](https://i.stack.imgur.com/VB6W2.png) More than just being annoying, this makes it impossible to see from a quick visual scan if there's a warning condition I actually care about on any of my hosts, like high CPU or memory usage, or low disk space, loss of redundancy, etc. So, how do I get rid of this warning icon (and if possible, the nag banner as well)?
2014/07/01
[ "https://serverfault.com/questions/609275", "https://serverfault.com", "https://serverfault.com/users/118258/" ]
There are different ways to change this option. All these solutions are listed in the `VMware KB 2003637`. About SSH, you might find useful the `esxcli` way with : `vim-cmd hostsvc/advopt/update UserVars.SuppressShellWarning long 1` The full documentation : [Cluster warning for ESXi Shell and SSH appear on an ESXi 5.x host](http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2003637)
In vSphere 5.5 and greater, this is easily accomplished from the vSphere Web Client interface by clicking the **Suppress Warning** link to the right of the warning text... [![enter image description here](https://i.stack.imgur.com/IdLp5.png)](https://i.stack.imgur.com/IdLp5.png) ![enter image description here](https://i.stack.imgur.com/m6BM0.png)
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
What do you mean to check ports on hosts remotely? Do you just want to connect to the port to see if it is open? The check\_tcp plugin will do that, if, that's what you want to do. Not quite sure what you mean.
i really like nagios. have been using it for years. i even do some oracle database management with it, but what nagios really is is an availability monitoring tool. i think what you are asking for is better fulfilled by another software like [openvas](http://www.openvas.org/) or [snort](http://www.snort.org/).
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
What do you mean to check ports on hosts remotely? Do you just want to connect to the port to see if it is open? The check\_tcp plugin will do that, if, that's what you want to do. Not quite sure what you mean.
I suppose what you want is to make sure that there is no "positive" response on any port apart from a short whitelist. I can see how you would prefer not to have 65000 check\_tcp:s on each host :) Mind you, I'm not sure nagios is really your best bet for this. Partly, it risks being a test that is always red and also, if you are serious about it, you should not limit the check to hosts that you actually know about. This sits awkwardly with Nagios which expects a host as the basic unit of configuration. Personally, I would probably have a separate tool that mailed me when something new shows up. In its most trivial form, this would be just a script that reacted to a non-zero diff of nmap output between today and yesterday and mailed me. In more complex form, such software tend to be sorted as IDSes which are not my expertise, but Google may be able to help.
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
What do you mean to check ports on hosts remotely? Do you just want to connect to the port to see if it is open? The check\_tcp plugin will do that, if, that's what you want to do. Not quite sure what you mean.
It sounds like you need a nagios check for changes/alerts in [pbnj](http://pbnj.sourceforge.net/) Use nagios to monitor the tool that tracks the changes, don't try to shim Nagios to track the changes.
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
I suppose what you want is to make sure that there is no "positive" response on any port apart from a short whitelist. I can see how you would prefer not to have 65000 check\_tcp:s on each host :) Mind you, I'm not sure nagios is really your best bet for this. Partly, it risks being a test that is always red and also, if you are serious about it, you should not limit the check to hosts that you actually know about. This sits awkwardly with Nagios which expects a host as the basic unit of configuration. Personally, I would probably have a separate tool that mailed me when something new shows up. In its most trivial form, this would be just a script that reacted to a non-zero diff of nmap output between today and yesterday and mailed me. In more complex form, such software tend to be sorted as IDSes which are not my expertise, but Google may be able to help.
i really like nagios. have been using it for years. i even do some oracle database management with it, but what nagios really is is an availability monitoring tool. i think what you are asking for is better fulfilled by another software like [openvas](http://www.openvas.org/) or [snort](http://www.snort.org/).
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
It sounds like you need a nagios check for changes/alerts in [pbnj](http://pbnj.sourceforge.net/) Use nagios to monitor the tool that tracks the changes, don't try to shim Nagios to track the changes.
i really like nagios. have been using it for years. i even do some oracle database management with it, but what nagios really is is an availability monitoring tool. i think what you are asking for is better fulfilled by another software like [openvas](http://www.openvas.org/) or [snort](http://www.snort.org/).
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
This guy has developed a nagios script for linux that does exactly what you are asking: <http://www.altsec.info/check_scan.html> I'm trying now to find a Windows equivalent Miguel
i really like nagios. have been using it for years. i even do some oracle database management with it, but what nagios really is is an availability monitoring tool. i think what you are asking for is better fulfilled by another software like [openvas](http://www.openvas.org/) or [snort](http://www.snort.org/).
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
This guy has developed a nagios script for linux that does exactly what you are asking: <http://www.altsec.info/check_scan.html> I'm trying now to find a Windows equivalent Miguel
I suppose what you want is to make sure that there is no "positive" response on any port apart from a short whitelist. I can see how you would prefer not to have 65000 check\_tcp:s on each host :) Mind you, I'm not sure nagios is really your best bet for this. Partly, it risks being a test that is always red and also, if you are serious about it, you should not limit the check to hosts that you actually know about. This sits awkwardly with Nagios which expects a host as the basic unit of configuration. Personally, I would probably have a separate tool that mailed me when something new shows up. In its most trivial form, this would be just a script that reacted to a non-zero diff of nmap output between today and yesterday and mailed me. In more complex form, such software tend to be sorted as IDSes which are not my expertise, but Google may be able to help.
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
This guy has developed a nagios script for linux that does exactly what you are asking: <http://www.altsec.info/check_scan.html> I'm trying now to find a Windows equivalent Miguel
It sounds like you need a nagios check for changes/alerts in [pbnj](http://pbnj.sourceforge.net/) Use nagios to monitor the tool that tracks the changes, don't try to shim Nagios to track the changes.
29,442,424
The following is code that I have put together with some help from SO. I am trying to be able to implement the `$select` statement, as well as the `$search` statement on the same page. The `$select` statement works fine, but I do not know how to call the `$search` statement to execute when the user searches using the form within the code. Does anyone know how to do this, or can you redirect me to a good tutorial with how forms interact with php? ``` <?php require 'db/connect.php'; $select = $db->query("SELECT * FROM customers ORDER BY id DESC"); $search = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <div id="wrapper"> <h1>Customers</h1> <p><a class="btn create" href="createcustomer.php">CREATE</a></p> <?php if (!$select->num_rows) { echo '<p>', 'No records', '</p>'; }else{ ?> <table border="1" width="100%"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone</th> <th>Alt Phone</th> <th>Job Address</th> <th>Billing Address</th> <th>Email</th> <th>Alt Email</th> </tr> </thead> <tbody> <?php while ($row = $select->fetch_object()) { ?> <tr> <td><?php echo $row->FName;?></td> <td><?php echo $row->LName;?></td> <td><?php echo $row->Phone;?></td> <td><?php echo $row->AltPhone;?></td> <td><?php echo $row->JobAddress;?></td> <td><?php echo $row->BillingAddress;?></td> <td><?php echo $row->Email;?></td> <td><?php echo $row->AltEmail;?></td> <td><a class="btn read" href="viewcustomer.php?id=<?php echo $row->id; ?>">READ</a>&nbsp;<a class="btn update" href="editcustomer.php?id=<?php echo $row->id; ?>">UPDATE</a>&nbsp;<a class="btn delete" href="deletecustomer.php?id=<?php echo $row->id; ?>">DELETE</a></td> </tr> </tbody> <tbody> <?php } ?> </table> <?php } ?> # Search form that needs tied to $search <input type="text" name="q" /> <input type="submit" name="search" /> </div> </body> </html> ```
2015/04/04
[ "https://Stackoverflow.com/questions/29442424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4564055/" ]
You can you `touchesBegan` for that. Here is example code for you: ``` override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for touch: AnyObject in touches{ let location = touch.locationInNode(self) if self.nodeAtPoint(location) == self.playButton{ //your code } } } ```
You should add the `UIButton` programatically, instead of in IB, to the `SKScene`'s `SKView` (in `didMoveToView` for example). You can then set the target for the button with `button.addTarget:action:forControlEvents:`. Just remember to call `button.removeFromSuperview()` in `willMoveFromView` otherwise you'll see the buttons in your next scene.
29,442,424
The following is code that I have put together with some help from SO. I am trying to be able to implement the `$select` statement, as well as the `$search` statement on the same page. The `$select` statement works fine, but I do not know how to call the `$search` statement to execute when the user searches using the form within the code. Does anyone know how to do this, or can you redirect me to a good tutorial with how forms interact with php? ``` <?php require 'db/connect.php'; $select = $db->query("SELECT * FROM customers ORDER BY id DESC"); $search = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <div id="wrapper"> <h1>Customers</h1> <p><a class="btn create" href="createcustomer.php">CREATE</a></p> <?php if (!$select->num_rows) { echo '<p>', 'No records', '</p>'; }else{ ?> <table border="1" width="100%"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone</th> <th>Alt Phone</th> <th>Job Address</th> <th>Billing Address</th> <th>Email</th> <th>Alt Email</th> </tr> </thead> <tbody> <?php while ($row = $select->fetch_object()) { ?> <tr> <td><?php echo $row->FName;?></td> <td><?php echo $row->LName;?></td> <td><?php echo $row->Phone;?></td> <td><?php echo $row->AltPhone;?></td> <td><?php echo $row->JobAddress;?></td> <td><?php echo $row->BillingAddress;?></td> <td><?php echo $row->Email;?></td> <td><?php echo $row->AltEmail;?></td> <td><a class="btn read" href="viewcustomer.php?id=<?php echo $row->id; ?>">READ</a>&nbsp;<a class="btn update" href="editcustomer.php?id=<?php echo $row->id; ?>">UPDATE</a>&nbsp;<a class="btn delete" href="deletecustomer.php?id=<?php echo $row->id; ?>">DELETE</a></td> </tr> </tbody> <tbody> <?php } ?> </table> <?php } ?> # Search form that needs tied to $search <input type="text" name="q" /> <input type="submit" name="search" /> </div> </body> </html> ```
2015/04/04
[ "https://Stackoverflow.com/questions/29442424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4564055/" ]
You appear to be mixing UIKit and SpriteKit here. I would personally advise against using UIButtons in conjunction with Sprite Kit. Is there a specific reason for doing so? There are two ways you can implement button behavior within a Sprite Kit scene: 1. have the SKScene object handle the touches 2. have the button itself handle the touches Dharmesh's answer uses method (1), where he implements the `-touchesBegan` method. In my current project, I am using an SKNode subclass as a button (2). I am unfamiliar with Swift syntax so I have posted Objective-C code from my project instead. The method calls are similar though and should help illustrate the point. **If you want an SKNode to receive touches, set `userInteractionEnabled` to `YES`.** Otherwise, the closest ancestor with `userInteractionEnabled = YES` (which typically is the containing SKScene) will receive a `-touchesBegan`/`-touchesMoved`/`-touchesEnded` message. ``` @interface VTObject : SKNode @end ... @implementation VTObject - (instancetype)init { if (self = [super init]) { self.userInteractionEnabled = YES; } return self; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"button touched!"); } @end ```
You should add the `UIButton` programatically, instead of in IB, to the `SKScene`'s `SKView` (in `didMoveToView` for example). You can then set the target for the button with `button.addTarget:action:forControlEvents:`. Just remember to call `button.removeFromSuperview()` in `willMoveFromView` otherwise you'll see the buttons in your next scene.
967,261
Why isn't this script working? ``` $(function() { var isbn = $('input').val(); $('button').click(function() { $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); }); ``` As you can see, I'm trying to do an extremely simple ISBN lookup field for a demo web site. The script is supposed to take the value of the input and insert it into the URL. Why isn't it working? Also, is there a better way to accomplish this end? I realize, of course, that iframes are rubbish, but I just want to keep it simple right now.
2009/06/08
[ "https://Stackoverflow.com/questions/967261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97939/" ]
It's not clear when your code gets called, but is this line: ``` var isbn = $('input').val(); ``` only called once at page-load time, whereas it should be within the click handler: ``` $('button').click(function() { var isbn = $('input').val(); $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); ```
Why not load the page you wanted to view through the ajax load technique, so fetching the html and displaying it within the element: ``` $(function() { var isbn = $('input').val(); $('button').click(function() { $("#data").load('http://books.google.com/books?vid=ISBN' + isbn); }); }); ```
967,261
Why isn't this script working? ``` $(function() { var isbn = $('input').val(); $('button').click(function() { $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); }); ``` As you can see, I'm trying to do an extremely simple ISBN lookup field for a demo web site. The script is supposed to take the value of the input and insert it into the URL. Why isn't it working? Also, is there a better way to accomplish this end? I realize, of course, that iframes are rubbish, but I just want to keep it simple right now.
2009/06/08
[ "https://Stackoverflow.com/questions/967261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97939/" ]
It's not clear when your code gets called, but is this line: ``` var isbn = $('input').val(); ``` only called once at page-load time, whereas it should be within the click handler: ``` $('button').click(function() { var isbn = $('input').val(); $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); ```
the problem is not your code but its the query string you have. please amend as follows and it should work: ``` var isbn = "1603038159"; $("#data").html('<iframe height="500" width="600" src="http://books.google.com/books?as_isbn=' + isbn); ```
55,710,561
i need some help to validate a jwt signature with a ECDSA public key. I'm reading the key from a .pem file with bouncy castle and using jjwt to do the validation. I'm getting an error while validating the signature. ``` Security.addProvider(new BouncyCastleProvider()); String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJtc2kiOiI5NzE1NTA5ODc2NTUiLCJmZWEiOiJzaWdudXAtZGF0YSIsImlzcyI6IkNEUCIsImV4cCI6MTU1NDU2NjMzNiwiaWF0IjoxNTU0MzkzNTM2LCJzaWQiOiIwNDI0MDMwMDg5NzI4MTg3QG5haS5lcGMubW5jMTMwLm1jYzMxMC4zZ3BwbmV0d29yay5vcmcifQ.RwxoGmFd1_dQPeGN-0gnWIW79xXvGHoyJKBbCKajgO75UooceS6tskxwqViEuP1gZD66UE8Bd2L0FaeI2aS_IA"; PemReader pemReader = new PemReader(new FileReader("/publickey.pem")); X509EncodedKeySpec spec = new X509EncodedKeySpec(pemReader.readPemObject().getContent()); KeyFactory kf = KeyFactory.getInstance("ECDSA","BC"); PublicKey publicKey = kf.generatePublic(spec); Jws<Claims> claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jwt); ``` I'm getting a Signature Exception with: Unable to verify Elliptic Curve signature using configured ECPublicKey. error decoding signature bytes.
2019/04/16
[ "https://Stackoverflow.com/questions/55710561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343794/" ]
This will work as well without mentioning any algorithm. ``` public boolean isTokenValid(String token) { try { String certificate = "GET_YOUR_PUBLIC_CERTIFICATE_HERE"; //Either from REST call or reading from a cert file. getPublicKeyAndParseToken(token, certificate); return true; } catch (IOException e) { log.error("", e); } catch (Exception e) { log.error("", e); log.error("JWT Not-Verified"); } return false; } private void getPublicKeyAndParseToken(String token, String certificate) throws IOException, CertificateException { log.debug("Certificate:: " + certificate); //Only for debugging purpose InputStream is = new ByteArrayInputStream(certificate.getBytes(StandardCharsets.UTF_8)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(is); PublicKey publicKey = cert.getPublicKey(); Jws parsedClaimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token); log.debug("Header:: " + parsedClaimsJws.getHeader()); //Only for debugging purpose log.debug("Body:: " + parsedClaimsJws.getBody()); //Only for debugging purpose } ``` Don't forget to use version '0.9.x' of jjwt library. I've below dependency in my build.gradle: ``` compile('io.jsonwebtoken:jjwt:0.9.1') ```
Problem found, i was using an old jjwt lib (0.6). Changed to 0.9 with the same code and it works as expected. Thanks
19,243,837
I am new to use Autolayouts, even this is my first try. Whatever I do with it, I end with a white screen as result. Here is my attempt. I have a `UIView`, let me say a `parentView` of frame `(60, 154, 200, 200)`. It is a subview to `self.view`. Then I have a dynamic view, say `dynamicView` of frame `(0, 0, 260, 100)` and a `label` of frame `(15, 25, 230, 50)` which is a subview to `dynamicView`. When I add the `dynamicView` as subview to the `parentView`, it goes out of `parentView`'s bounds. So, I'd like to adjust the size of the `dynamicView` and its child(`label`) so that its position is center to the `parentView` and `dynamicView` is inside `parentView`'s bounds. My first attempt was setting `clipsToBounds`, its not working in Xcode5, iOS7. So the next option is to achieve this using `NSLayoutConstraint`. I have no idea on it. I welcome your ideas.
2013/10/08
[ "https://Stackoverflow.com/questions/19243837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/500625/" ]
i'll just address the dyanmicView being part of the parentView issue, then let you go from there **first**: if you are creating the view dynamically, then you're good to go, but if you've created it from storyboard, you'd have to detach it from it's parent then reattach it.. that's how you get rid of it's previous NSConstraints (that usually the storyboard introduces) that may conflict with your new ones. you also gotta set it's `setTranslatesAutoresizingMaskIntoConstraints` to NO b/c that also can interfere with your nsconstraints. I usually do those last two steps like so, using [mapObjectsUsingBlock](https://github.com/abbood/NSArray-Addons) to make the whole tedious process of creating constraints a bit more pleasant and natural: ``` [@[view_1, view_2, /../, view_n] mapObjectsApplyingBlock:^(UIView *view) { [view removeFromSuperview]; [view setTranslatesAutoresizingMaskIntoConstraints:NO]; [view setHidden:NO]; [superView addSubview:view]; }]; ``` **then** before applying nsconstraints, you gotta make sure that the view you want the constraints to apply to is *already* attached to it's parent: ``` [parentView addSubview:dynamicView]; ``` **then** you want to create a bindings dictionary: ``` NSDictionary *buttonBindingsDictionary = @{ @"parentView" : parentView, @"dynamicView" : dynamicView}; ``` then you want to add the constraints using the [visual format language](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AutolayoutPG/Articles/formatLanguage.html#//apple_ref/doc/uid/TP40010853-CH3).. I also use `mapObjectsUsingBlock` here (i'll explain each constraint in english): ``` NSArray *buttonConstraints = [@[@"V:|-[dynamicView(>=200)]-|", @"|-[dynamicView(>=260)]-|", ] mapObjectsUsingBlock:^id(NSString *formatString, NSUInteger idx){ return [NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:buttonBindingsDictionary]; }]; ``` `V:|-[dynamicView(>=200)]-|` means that vertically speaking.. the upper and lower distance between `dynamicView` and it's parent should be equal.. also `dynamicView's` height should be no less than `200` `|-[dynamicView(>=260)]-|` means that horizontally speaking.. the left and right distance between `dyanmicview` and it's parent should be equal.. also `dyanmicView's` width should be no less than `260` *note:* you can do the math yourself and set exactly how much the left/right/bottom/top distance between `dyanicView` and it's parent.. this is just simpler.. but sometimes nsconstraints messes up and I gotta do it myself. in that case it would look something like this where `x` is the distance you came up with: ``` V:|-x-[dynamicView(>=200)]-x-| |-x-[dynamicView(>=260)]-x-| ``` then you gotta add the constraints to the parent view: ``` [parentView addConstraints:[buttonConstraints flattenArray]]; ``` notice here i used [flatten array](https://github.com/abbood/NSArray-Addons), again that's a method from my library b/c i want to feed it a one level array, not an array of arrays. and you're good to go! **note:** i know that this may not work perfectly.. but it gives you the idea of what to do + some helper files. It takes some practice, and you should look at some of the [tutorials](http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2) for sure.. i suggest you start with nsconstraints using storyboard (you can select a view.. then go editor>pin>.. then chose something.. get some immediate visual feedback.. also you can simulate what your views will look like in 3.5" displays vs 4.0" displays immediately on the storyboard by selecting the view controller, then going to attributes inspector and selecting different sizes under simulated metrics) take your time bud, but one thing for sure: once you go nsconstraints you will never look back! it's totally worth it! p.s. you can also [animate](https://stackoverflow.com/questions/12622424/how-do-i-animate-constraint-changes) views using nsconstraints as well.. just in case you were wondering.
Auto Layout Constraints is the best approach to what you are trying to achieve. Auto layout constraints are added automatically when you check the Use Autolayout option in the IB. Check out this tutorial which tells more about auto layouts in iOS6 <http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2> then you can check this link for the updated autolayout in iOS7 <http://www.doubleencore.com/2013/09/auto-layout-updates-in-ios-7/>
441,419
I’m curious if I have a legitimate concern or if I’m just being overly paranoid. I have a rechargeable Lithium-Polymer battery (prismatic shaped) rated for a max charging temperature of 45 °C. The battery rests against a circuit board that I know can generate some heat when charging the battery (500 mA current via an MCP73831 IC). It can get up to around 49 °C in a single location on the board (say about 1/4”x1/4” in size) and a dissipated temperature around that (I even measured 63 °C once on the hot spot but haven’t been able to reproduce it). That is for the back of the board where the battery rests (the front side can get up to 80 °C at the charger IC). Is there any legitimate concern that this will heat the battery during charging? There is nothing between the LiPo and the board. Using a thermal camera, it doesn’t seem like any heat really transfers well to the battery, so it seems like it should be okay, but I’m no expert in heat transfer, especially if it remained in the described state/position for a few hours. The battery and board would sit inside a plastic enclosure.
2019/06/01
[ "https://electronics.stackexchange.com/questions/441419", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/77406/" ]
Lithium-Polymer service life is seriously degraded at high temperatures, especially when fully charged. The cooler you can keep the battery the better. I suggest using a more efficient switch-mode charging IC such as the TP5000.
Now, the question is: How much of it do the powerful chips that generate a lot of heat ("heat" is thermal energy) transfer into the battery; that's a question of considering where the heat goes. First thing to realize is that if you have a perfectly sealed, perfectly thermally isolated box, it's going to heat up forever, and at one point break down/melt/outshine the sun in its temperature. Obviously, that's not happening, because the enclosure of your device isn't a perfect thermal isolator. Conversely, your board itself isn't a perfect thermal conductor, either: if that were the case, all spots on the board would instantly have the same temperature! So, in a first step, it'd be important to model how warm your overall device gets. Lets consider it as a black box: Inside, someone converts \$P\$ watts of electrical power to heat, and these will need to be dissipated to the environment in order to stop the infinite heating up. Now, the way we model that actually uses similar terminology as we're used from Ohm's law: There's *thermal resistance*, that tells us how much something is in the way of heat flow. Its unit is typically "K/W", or "°C/W" and tells us how much hotter something gets if a specific power is converted to heat inside. You'll often find IC datasheet specifying something like a "junction to environment thermal resistance 45 °C/W", and together with an estimate of how much power the IC uses (for example, voltage drop times current in a linear voltage regulator), you can tell how much hotter than ambient things get. So, our process goes like the following: 1. Estimate how much power is converted to heat in your system. 2. Estimate the thermal resistance of your enclosure; that times the power from 1. gives you how much hotter the inside of the enclosure is than the outside From here, I'd guess that in any typical device, improvements are minor by being more detailed: If you're already above 45 °C, then you're not colder anywhere inside the box (after a while, at least), and your device needs better cooling. If you're sufficiently below, and there are enough places heat can go without going through the battery, you honestly don't need to worry too much. Problematic would be if you're close below 45 °C inner-enclosure temperature; then you'd need to calculate further: 3. Estimate how much warmer the components in close proximity to the battery are than the in-box environment: same procedure as above, but ambient temperature is the already elevated one of the inside of the box. 4. calculate the heat transport that reaches the battery by putting all thermal resistances in parallel between the heat source and the battery and calculate how much heat will flow into the battery. Step 3. and 4. are pretty often done in simulation, because estimating how much heat a complex PCB and a battery fixation will transport is hard. Step 1. and 2. can be done pretty well by hand: For the outside of the box, you can often assume something like "well enough ventilated place" and hence assume cooling by *convection* and maybe radiation. There's ready-to-use formulas that relate horizontal and vertical surface area to the resulting thermal conductivity and resistance.
472,937
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing. Why would this be?
2009/01/23
[ "https://Stackoverflow.com/questions/472937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I use Nant to run some MSBuild tasks. Every time I use the `failonbuild` attribute of that task, it fails for me. Looking at Apache's documentation for Ant, it would appear the same attribute is there as well. Are you using this attribute?
I arrived at a solution and used `Exec`'s `failonerror`, works like a charm.
472,937
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing. Why would this be?
2009/01/23
[ "https://Stackoverflow.com/questions/472937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I use Nant to run some MSBuild tasks. Every time I use the `failonbuild` attribute of that task, it fails for me. Looking at Apache's documentation for Ant, it would appear the same attribute is there as well. Are you using this attribute?
What do you let the msbuild task do ? When I used NAnt previously, I used the task to build a VS.NET solution. Right now, I'm not using NAnt anymore, I use msbuild instead. :)
472,937
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing. Why would this be?
2009/01/23
[ "https://Stackoverflow.com/questions/472937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I arrived at a solution and used `Exec`'s `failonerror`, works like a charm.
What do you let the msbuild task do ? When I used NAnt previously, I used the task to build a VS.NET solution. Right now, I'm not using NAnt anymore, I use msbuild instead. :)
40,049,978
I'm trying to get the currently displayed `ViewController` using the following: ``` let currentViewController = UIApplication.sharedApplication().keyWindow!.rootViewController?.presentedViewController ``` This property gives me the `TabBarController`. The only property after `presentedViewController` is "`childViewControllers`". How could I use this to attain the currently displayed `ViewController`?
2016/10/14
[ "https://Stackoverflow.com/questions/40049978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6758725/" ]
I would use a computed property instead of a filter and a method. I'd go through each cast member and if any of their groups is in `selected_groups` I'd allow it through the filter. I'd so this using `Array.some`. ``` results: function() { var self = this return self.cast.filter(function(person) { return person.groups.some(function(group) { return self.selected_groups.indexOf(group) !== 1 }) }) }, ``` Here's a quick demo I set up, might be useful: <http://jsfiddle.net/crswll/df4Lnuw6/8/>
Since filters are deprecated (in `v-for`, see Bill's comment), you should get into the habit of making computeds to do filtery things. (If you're on IE, you can't use [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) without a polyfill; you can use `indexOf...>=0` instead.) ```js new Vue({ el: '#app', data: { selected_groups: [], ensemble_groups: ["Leads", "Understudies", "Children", "Ensemble"], cast: [{ actor_name: "Dave", groups: ["Leads"], }, { actor_name: "Jill", groups: ["Leads"], }, { actor_name: "Sam", groups: ["Children", "Ensemble"], }, { actor_name: "Austin", groups: ["Understudies", "Ensemble"], }, ] }, computed: { filteredCast: function() { const result = []; for (const c of this.cast) { if (this.anyMatch(c.groups, this.selected_groups)) { result.push(c); } } return result; } }, methods: { anyMatch: function(g1, g2) { for (const g of g1) { if (g2.includes(g)) { return true; } } return false; } } }); ``` ```html <script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.min.js"></script> <div id="app"> <template v-for="group in ensemble_groups"> <input name="select_group[]" id="group_@{{ $index }}" :value="group" v-model="selected_groups" type="checkbox"> <label for="group_@{{ $index }}">@{{ group }}</label> </template> <template v-for="person in filteredCast"> <div>@{{ person.actor_name }}</div> </template> </div> ```
40,049,978
I'm trying to get the currently displayed `ViewController` using the following: ``` let currentViewController = UIApplication.sharedApplication().keyWindow!.rootViewController?.presentedViewController ``` This property gives me the `TabBarController`. The only property after `presentedViewController` is "`childViewControllers`". How could I use this to attain the currently displayed `ViewController`?
2016/10/14
[ "https://Stackoverflow.com/questions/40049978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6758725/" ]
I would use a computed property instead of a filter and a method. I'd go through each cast member and if any of their groups is in `selected_groups` I'd allow it through the filter. I'd so this using `Array.some`. ``` results: function() { var self = this return self.cast.filter(function(person) { return person.groups.some(function(group) { return self.selected_groups.indexOf(group) !== 1 }) }) }, ``` Here's a quick demo I set up, might be useful: <http://jsfiddle.net/crswll/df4Lnuw6/8/>
```js var demo = new Vue({ el: '#demo', data: { search: 're', people: [ {name: 'Koos', age: 30, eyes:'red'}, {name: 'Gert', age: 20, eyes:'blue'}, {name: 'Pieter', age: 12, eyes:'green'}, {name: 'Dawid', age: 67, eyes:'dark green'}, {name: 'Johan', age: 15, eyes:'purple'}, {name: 'Hans', age: 12, eyes:'pink'} ] }, methods: { customFilter: function(person) { return person.name.indexOf(this.search) != -1 || person.eyes.indexOf(this.search) != -1 ; } }, }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script> <div id="demo"> <input type="text" class="form-control" v-model="search"/> <br/> <table class="table"> <thead> <tr> <th>name</th> <th>eyes</th> <th>age</th> </tr> </thead> <tr v-for="person in people | filterBy customFilter"> <td>{{ person.name }}</td> <td>{{ person.eyes }}</td> <td>{{ person.age }}</td> </tr> </table> </div> ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
**VB.Net: 290 chars (320 bytes)** Requires Option Strict Off, Option Explicit Off ``` Function G(i,P) i=i*2-1 F=0 M="-" Q="=" Z=P.Split(Chr(10)) While E<Z.Length L=(" "& Z(E))(i-1) R=(Z(E)&" ")(i) J=L & R=" "&" " E-=(F=2Or J) i+=If(F=1,2*((L=M)-(R=M)),If(F=2,2*((L=Q)-(R=Q)),If(J,0,2+4*(L=Q Or(L=M And R<>Q))))) F=If(F=1,2,If(F=2,0,If(J,F,2+(L=Q Or R=Q)))) End While G=(i-1)\2+1 End Function ``` **Readable form:** ``` Function G(ByVal i As Integer, ByVal P As String) As Integer i = i * 2 - 1 Dim F As Integer = 0 Const M As String = "-" Const Q As String = "=" Dim Z As String() = P.Split(Chr(10)) Dim E As Integer = 0 While E < Z.Length Dim L As Char = (" " & Z(E))(i - 1) Dim R As Char = (Z(E) & " ")(i) Dim J As Boolean = L & R = " " & " " E -= (F = 2 Or J) i += If(F = 1, 2 * ((L = M) - (R = M)), _ If(F = 2, 2 * ((L = Q) - (R = Q)), _ If(J, 0, 2 + 4 * (L = Q Or (L = M And R <> Q))))) F = If(F = 1, 2, If(F = 2, 0, If(J, F, 2 + (L = Q Or R = Q)))) End While G = (i - 1) \ 2 + 1 End Function ``` **Test cases** ``` Sub Main() Dim sb As New StringBuilder Dim LF As Char = ControlChars.Lf sb.Append("|-| |=|-|=|") sb.Append(LF) sb.Append("| |-| | |-|") sb.Append(LF) sb.Append("|=| |-| | |") sb.Append(LF) sb.Append("| | |-|=|-|") Dim pattern As String = sb.ToString For w As Integer = 1 To pattern.Split(LF)(0).Length \ 2 + 1 Console.WriteLine(w.ToString & " : " & G(w, pattern).ToString) Next Console.ReadKey() End Sub ``` **Edit:** (for those still reading this) I tried a different approach. My idea was to map the different patterns expected and act accordingly. We first need to decide if we'll turn left or right and then determine the number of columns our little [Amidar](http://en.wikipedia.org/wiki/Amidar) monkey will move (reversing the string if needed). Presenting the full solution first: ``` Function GhostLeg(ByVal i As Integer, ByVal p As String) As Integer i = i * 2 - 2 Dim LeftOrRight As New Dictionary(Of String, Integer) LeftOrRight(" | ") = 0 LeftOrRight("-| ") = -1 LeftOrRight("=| ") = -1 LeftOrRight("=|-") = -1 LeftOrRight(" |-") = 1 LeftOrRight(" |=") = 1 LeftOrRight("-|=") = 1 Dim ColumnAdd As New Dictionary(Of String, Integer) ColumnAdd("| | | ") = 0 ColumnAdd("| | |-") = 0 ColumnAdd("| |-| ") = 0 ColumnAdd("| | |=") = 0 ColumnAdd("| |=| ") = 0 ColumnAdd("| |-|=") = 0 ColumnAdd("| |=|-") = 0 ColumnAdd("|=| | ") = 0 ColumnAdd("|=| |-") = 0 ColumnAdd("|=| |=") = 0 ColumnAdd("|-| |-") = 1 ColumnAdd("|-| | ") = 1 ColumnAdd("|-| |=") = 1 ColumnAdd("|-|=|-") = 2 ColumnAdd("|-|=| ") = 2 ColumnAdd("|=|-| ") = 2 ColumnAdd("|=|-|=") = 3 Const TRIPLESPACE As String = " | | " Dim direction As Integer For Each line As String In p.Split(Chr(10)) line = TRIPLESPACE & line & TRIPLESPACE direction = LeftOrRight(line.Substring(i + 4, 3)) If direction = 1 Then line = line.Substring(i + 5, 6) i += 2 * direction * ColumnAdd(line) ElseIf direction = -1 Then line = StrReverse(line.Substring(i, 6)) i += 2 * direction * ColumnAdd(line) End If Next Return 1 + i \ 2 End Function ``` By removing the character-wise expensive Dictionary, as well as the unecessary `|`'s and after some more 'minification' we end up with: ``` Function G(i,p) D="- 0= 0=-0 -2 =2-=2" A="- -1- 1- =1-=-2-= 2=- 2=-=3" For Each l In p.Replace("|","").Split(Chr(10)) l=" "& l &" " w=InStr(D,Mid(l,i+2,2)) If w Then w=Val(D(w+1))-1 s=InStr(A,If(w=1,Mid(l,i+3,3),StrReverse(Mid(l,i,3)))) i+=If(s,w*Val(A(s+2)),0) End If Next G=i End Function ``` Not much of a gain, compared to my previous effort (282 chars, 308 bytes), but maybe this approach will prove useful to others using a different programming language.
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
Daniel's answer in C# - 173 chars ================================= After seeing Daniel Vassallo's solution, I was too ashamed of mine to post it. But here's Daniel's answer ported to C# for the heck of it. One major drawback in C# was having to do bounds checking, which cost 20 characters. ``` int G(string s,int n){var l=s.Split('\n');n*=2;for(int i=0,j,c;i<l.Length;i++) for(j=0;j<3;n+=n>2&&l[i][n-3]==c?-2:n<l[i].Length&&l[i][n-1]==c?2:0)c=j++==1?45 :61;return n/2;} ``` Formatted: ``` int G(string s, int n) { var l = s.Split('\n'); n *= 2; for (int i = 0, j, c; i < l.Length; i++) for (j = 0; j < 3; n += n > 2 && l[i][n - 3] == c ? -2 : n < l[i].Length && l[i][n - 1] == c ? 2 : 0) c = j++ == 1 ? 45 : 61; return n / 2; } ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
Perl, ~~92~~ 91 chars ===================== ``` sub g{for$s(pop=~/.+/g){map$_[0]-=1-abs(index substr(" $s",$_[0]*2-2,3),$_),qw[= - =]}pop} ``` Another approach, ~~98~~ ~~97~~ ~~95~~ ~~94~~ ~~93~~ 92 chars ------------------------------------------------------------- ``` sub g{map{for$s(qw[= - =]){pos=$_[0]*2-2;$_[0]+=/\G((?<=$s)|.$s)/&&$&cmp$"}}pop=~/.+/g;pop} ``` Test suite ---------- ``` $s=<<'__PATTERN__'; |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __PATTERN__ for $n (1..6) { print g($n,$s); } ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
AWK - 68 77 79 chars -------------------- Pretty much a translation of Daniel's solution (we love ya man ;) ``` {for(i=0;i<3;){s=++i-2?"=":"-";if(s==$x)x--;else if(s!=$++x)x--}}END{print x} ``` But we can do away with `if/else` and replace it with `?:` ``` {for(i=0;i<3;){s=++i-2?"=":"-";s==$x?x--:s!=$++x?x--:x}}END{print x} ``` Run it with the starting position defined as the x variable: ``` $ for x in `seq 6`; do echo $x\ ;awk -F\| -vx=$x -f ghost.awk<<__EOF__ |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __EOF__ done 1 6 2 1 3 3 4 5 5 4 6 2 ```
**VB.Net: 290 chars (320 bytes)** Requires Option Strict Off, Option Explicit Off ``` Function G(i,P) i=i*2-1 F=0 M="-" Q="=" Z=P.Split(Chr(10)) While E<Z.Length L=(" "& Z(E))(i-1) R=(Z(E)&" ")(i) J=L & R=" "&" " E-=(F=2Or J) i+=If(F=1,2*((L=M)-(R=M)),If(F=2,2*((L=Q)-(R=Q)),If(J,0,2+4*(L=Q Or(L=M And R<>Q))))) F=If(F=1,2,If(F=2,0,If(J,F,2+(L=Q Or R=Q)))) End While G=(i-1)\2+1 End Function ``` **Readable form:** ``` Function G(ByVal i As Integer, ByVal P As String) As Integer i = i * 2 - 1 Dim F As Integer = 0 Const M As String = "-" Const Q As String = "=" Dim Z As String() = P.Split(Chr(10)) Dim E As Integer = 0 While E < Z.Length Dim L As Char = (" " & Z(E))(i - 1) Dim R As Char = (Z(E) & " ")(i) Dim J As Boolean = L & R = " " & " " E -= (F = 2 Or J) i += If(F = 1, 2 * ((L = M) - (R = M)), _ If(F = 2, 2 * ((L = Q) - (R = Q)), _ If(J, 0, 2 + 4 * (L = Q Or (L = M And R <> Q))))) F = If(F = 1, 2, If(F = 2, 0, If(J, F, 2 + (L = Q Or R = Q)))) End While G = (i - 1) \ 2 + 1 End Function ``` **Test cases** ``` Sub Main() Dim sb As New StringBuilder Dim LF As Char = ControlChars.Lf sb.Append("|-| |=|-|=|") sb.Append(LF) sb.Append("| |-| | |-|") sb.Append(LF) sb.Append("|=| |-| | |") sb.Append(LF) sb.Append("| | |-|=|-|") Dim pattern As String = sb.ToString For w As Integer = 1 To pattern.Split(LF)(0).Length \ 2 + 1 Console.WriteLine(w.ToString & " : " & G(w, pattern).ToString) Next Console.ReadKey() End Sub ``` **Edit:** (for those still reading this) I tried a different approach. My idea was to map the different patterns expected and act accordingly. We first need to decide if we'll turn left or right and then determine the number of columns our little [Amidar](http://en.wikipedia.org/wiki/Amidar) monkey will move (reversing the string if needed). Presenting the full solution first: ``` Function GhostLeg(ByVal i As Integer, ByVal p As String) As Integer i = i * 2 - 2 Dim LeftOrRight As New Dictionary(Of String, Integer) LeftOrRight(" | ") = 0 LeftOrRight("-| ") = -1 LeftOrRight("=| ") = -1 LeftOrRight("=|-") = -1 LeftOrRight(" |-") = 1 LeftOrRight(" |=") = 1 LeftOrRight("-|=") = 1 Dim ColumnAdd As New Dictionary(Of String, Integer) ColumnAdd("| | | ") = 0 ColumnAdd("| | |-") = 0 ColumnAdd("| |-| ") = 0 ColumnAdd("| | |=") = 0 ColumnAdd("| |=| ") = 0 ColumnAdd("| |-|=") = 0 ColumnAdd("| |=|-") = 0 ColumnAdd("|=| | ") = 0 ColumnAdd("|=| |-") = 0 ColumnAdd("|=| |=") = 0 ColumnAdd("|-| |-") = 1 ColumnAdd("|-| | ") = 1 ColumnAdd("|-| |=") = 1 ColumnAdd("|-|=|-") = 2 ColumnAdd("|-|=| ") = 2 ColumnAdd("|=|-| ") = 2 ColumnAdd("|=|-|=") = 3 Const TRIPLESPACE As String = " | | " Dim direction As Integer For Each line As String In p.Split(Chr(10)) line = TRIPLESPACE & line & TRIPLESPACE direction = LeftOrRight(line.Substring(i + 4, 3)) If direction = 1 Then line = line.Substring(i + 5, 6) i += 2 * direction * ColumnAdd(line) ElseIf direction = -1 Then line = StrReverse(line.Substring(i, 6)) i += 2 * direction * ColumnAdd(line) End If Next Return 1 + i \ 2 End Function ``` By removing the character-wise expensive Dictionary, as well as the unecessary `|`'s and after some more 'minification' we end up with: ``` Function G(i,p) D="- 0= 0=-0 -2 =2-=2" A="- -1- 1- =1-=-2-= 2=- 2=-=3" For Each l In p.Replace("|","").Split(Chr(10)) l=" "& l &" " w=InStr(D,Mid(l,i+2,2)) If w Then w=Val(D(w+1))-1 s=InStr(A,If(w=1,Mid(l,i+3,3),StrReverse(Mid(l,i,3)))) i+=If(s,w*Val(A(s+2)),0) End If Next G=i End Function ``` Not much of a gain, compared to my previous effort (282 chars, 308 bytes), but maybe this approach will prove useful to others using a different programming language.
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
Ruby - 66 95 92 83 chars ======================== (Alternating rows idea from Daniel's answer) -------------------------------------------- ``` def f s,m m.each_line{|r|%w{= - =}.map{|i|s+=i==r[2*s-3]?-1:i==r[2*s-1]?1:0}} s end ``` 92 chars ``` def f s,m s=s*2-2 m.each_line{|r|%w{= - =}.each{|i|s+=i==r[s-1]?-2:i==r[s+1]?2:0}} 1+s/2 end ``` Usage ``` map="|-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-|" 1.upto(6) do |i| p f(i, map) end ``` Output ``` 6 1 3 5 4 2 ```
Daniel's answer in C# - 173 chars ================================= After seeing Daniel Vassallo's solution, I was too ashamed of mine to post it. But here's Daniel's answer ported to C# for the heck of it. One major drawback in C# was having to do bounds checking, which cost 20 characters. ``` int G(string s,int n){var l=s.Split('\n');n*=2;for(int i=0,j,c;i<l.Length;i++) for(j=0;j<3;n+=n>2&&l[i][n-3]==c?-2:n<l[i].Length&&l[i][n-1]==c?2:0)c=j++==1?45 :61;return n/2;} ``` Formatted: ``` int G(string s, int n) { var l = s.Split('\n'); n *= 2; for (int i = 0, j, c; i < l.Length; i++) for (j = 0; j < 3; n += n > 2 && l[i][n - 3] == c ? -2 : n < l[i].Length && l[i][n - 1] == c ? 2 : 0) c = j++ == 1 ? 45 : 61; return n / 2; } ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
AWK - 68 77 79 chars -------------------- Pretty much a translation of Daniel's solution (we love ya man ;) ``` {for(i=0;i<3;){s=++i-2?"=":"-";if(s==$x)x--;else if(s!=$++x)x--}}END{print x} ``` But we can do away with `if/else` and replace it with `?:` ``` {for(i=0;i<3;){s=++i-2?"=":"-";s==$x?x--:s!=$++x?x--:x}}END{print x} ``` Run it with the starting position defined as the x variable: ``` $ for x in `seq 6`; do echo $x\ ;awk -F\| -vx=$x -f ghost.awk<<__EOF__ |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __EOF__ done 1 6 2 1 3 3 4 5 5 4 6 2 ```
Perl, ~~92~~ 91 chars ===================== ``` sub g{for$s(pop=~/.+/g){map$_[0]-=1-abs(index substr(" $s",$_[0]*2-2,3),$_),qw[= - =]}pop} ``` Another approach, ~~98~~ ~~97~~ ~~95~~ ~~94~~ ~~93~~ 92 chars ------------------------------------------------------------- ``` sub g{map{for$s(qw[= - =]){pos=$_[0]*2-2;$_[0]+=/\G((?<=$s)|.$s)/&&$&cmp$"}}pop=~/.+/g;pop} ``` Test suite ---------- ``` $s=<<'__PATTERN__'; |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __PATTERN__ for $n (1..6) { print g($n,$s); } ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
Ruby - 66 95 92 83 chars ======================== (Alternating rows idea from Daniel's answer) -------------------------------------------- ``` def f s,m m.each_line{|r|%w{= - =}.map{|i|s+=i==r[2*s-3]?-1:i==r[2*s-1]?1:0}} s end ``` 92 chars ``` def f s,m s=s*2-2 m.each_line{|r|%w{= - =}.each{|i|s+=i==r[s-1]?-2:i==r[s+1]?2:0}} 1+s/2 end ``` Usage ``` map="|-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-|" 1.upto(6) do |i| p f(i, map) end ``` Output ``` 6 1 3 5 4 2 ```
Perl, ~~92~~ 91 chars ===================== ``` sub g{for$s(pop=~/.+/g){map$_[0]-=1-abs(index substr(" $s",$_[0]*2-2,3),$_),qw[= - =]}pop} ``` Another approach, ~~98~~ ~~97~~ ~~95~~ ~~94~~ ~~93~~ 92 chars ------------------------------------------------------------- ``` sub g{map{for$s(qw[= - =]){pos=$_[0]*2-2;$_[0]+=/\G((?<=$s)|.$s)/&&$&cmp$"}}pop=~/.+/g;pop} ``` Test suite ---------- ``` $s=<<'__PATTERN__'; |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __PATTERN__ for $n (1..6) { print g($n,$s); } ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
AWK - 68 77 79 chars -------------------- Pretty much a translation of Daniel's solution (we love ya man ;) ``` {for(i=0;i<3;){s=++i-2?"=":"-";if(s==$x)x--;else if(s!=$++x)x--}}END{print x} ``` But we can do away with `if/else` and replace it with `?:` ``` {for(i=0;i<3;){s=++i-2?"=":"-";s==$x?x--:s!=$++x?x--:x}}END{print x} ``` Run it with the starting position defined as the x variable: ``` $ for x in `seq 6`; do echo $x\ ;awk -F\| -vx=$x -f ghost.awk<<__EOF__ |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| __EOF__ done 1 6 2 1 3 3 4 5 5 4 6 2 ```
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
Ruby - 66 95 92 83 chars ======================== (Alternating rows idea from Daniel's answer) -------------------------------------------- ``` def f s,m m.each_line{|r|%w{= - =}.map{|i|s+=i==r[2*s-3]?-1:i==r[2*s-1]?1:0}} s end ``` 92 chars ``` def f s,m s=s*2-2 m.each_line{|r|%w{= - =}.each{|i|s+=i==r[s-1]?-2:i==r[s+1]?2:0}} 1+s/2 end ``` Usage ``` map="|-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-|" 1.upto(6) do |i| p f(i, map) end ``` Output ``` 6 1 3 5 4 2 ```
**VB.Net: 290 chars (320 bytes)** Requires Option Strict Off, Option Explicit Off ``` Function G(i,P) i=i*2-1 F=0 M="-" Q="=" Z=P.Split(Chr(10)) While E<Z.Length L=(" "& Z(E))(i-1) R=(Z(E)&" ")(i) J=L & R=" "&" " E-=(F=2Or J) i+=If(F=1,2*((L=M)-(R=M)),If(F=2,2*((L=Q)-(R=Q)),If(J,0,2+4*(L=Q Or(L=M And R<>Q))))) F=If(F=1,2,If(F=2,0,If(J,F,2+(L=Q Or R=Q)))) End While G=(i-1)\2+1 End Function ``` **Readable form:** ``` Function G(ByVal i As Integer, ByVal P As String) As Integer i = i * 2 - 1 Dim F As Integer = 0 Const M As String = "-" Const Q As String = "=" Dim Z As String() = P.Split(Chr(10)) Dim E As Integer = 0 While E < Z.Length Dim L As Char = (" " & Z(E))(i - 1) Dim R As Char = (Z(E) & " ")(i) Dim J As Boolean = L & R = " " & " " E -= (F = 2 Or J) i += If(F = 1, 2 * ((L = M) - (R = M)), _ If(F = 2, 2 * ((L = Q) - (R = Q)), _ If(J, 0, 2 + 4 * (L = Q Or (L = M And R <> Q))))) F = If(F = 1, 2, If(F = 2, 0, If(J, F, 2 + (L = Q Or R = Q)))) End While G = (i - 1) \ 2 + 1 End Function ``` **Test cases** ``` Sub Main() Dim sb As New StringBuilder Dim LF As Char = ControlChars.Lf sb.Append("|-| |=|-|=|") sb.Append(LF) sb.Append("| |-| | |-|") sb.Append(LF) sb.Append("|=| |-| | |") sb.Append(LF) sb.Append("| | |-|=|-|") Dim pattern As String = sb.ToString For w As Integer = 1 To pattern.Split(LF)(0).Length \ 2 + 1 Console.WriteLine(w.ToString & " : " & G(w, pattern).ToString) Next Console.ReadKey() End Sub ``` **Edit:** (for those still reading this) I tried a different approach. My idea was to map the different patterns expected and act accordingly. We first need to decide if we'll turn left or right and then determine the number of columns our little [Amidar](http://en.wikipedia.org/wiki/Amidar) monkey will move (reversing the string if needed). Presenting the full solution first: ``` Function GhostLeg(ByVal i As Integer, ByVal p As String) As Integer i = i * 2 - 2 Dim LeftOrRight As New Dictionary(Of String, Integer) LeftOrRight(" | ") = 0 LeftOrRight("-| ") = -1 LeftOrRight("=| ") = -1 LeftOrRight("=|-") = -1 LeftOrRight(" |-") = 1 LeftOrRight(" |=") = 1 LeftOrRight("-|=") = 1 Dim ColumnAdd As New Dictionary(Of String, Integer) ColumnAdd("| | | ") = 0 ColumnAdd("| | |-") = 0 ColumnAdd("| |-| ") = 0 ColumnAdd("| | |=") = 0 ColumnAdd("| |=| ") = 0 ColumnAdd("| |-|=") = 0 ColumnAdd("| |=|-") = 0 ColumnAdd("|=| | ") = 0 ColumnAdd("|=| |-") = 0 ColumnAdd("|=| |=") = 0 ColumnAdd("|-| |-") = 1 ColumnAdd("|-| | ") = 1 ColumnAdd("|-| |=") = 1 ColumnAdd("|-|=|-") = 2 ColumnAdd("|-|=| ") = 2 ColumnAdd("|=|-| ") = 2 ColumnAdd("|=|-|=") = 3 Const TRIPLESPACE As String = " | | " Dim direction As Integer For Each line As String In p.Split(Chr(10)) line = TRIPLESPACE & line & TRIPLESPACE direction = LeftOrRight(line.Substring(i + 4, 3)) If direction = 1 Then line = line.Substring(i + 5, 6) i += 2 * direction * ColumnAdd(line) ElseIf direction = -1 Then line = StrReverse(line.Substring(i, 6)) i += 2 * direction * ColumnAdd(line) End If Next Return 1 + i \ 2 End Function ``` By removing the character-wise expensive Dictionary, as well as the unecessary `|`'s and after some more 'minification' we end up with: ``` Function G(i,p) D="- 0= 0=-0 -2 =2-=2" A="- -1- 1- =1-=-2-= 2=- 2=-=3" For Each l In p.Replace("|","").Split(Chr(10)) l=" "& l &" " w=InStr(D,Mid(l,i+2,2)) If w Then w=Val(D(w+1))-1 s=InStr(A,If(w=1,Mid(l,i+3,3),StrReverse(Mid(l,i,3)))) i+=If(s,w*Val(A(s+2)),0) End If Next G=i End Function ``` Not much of a gain, compared to my previous effort (282 chars, 308 bytes), but maybe this approach will prove useful to others using a different programming language.
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
Ruby - 66 95 92 83 chars ======================== (Alternating rows idea from Daniel's answer) -------------------------------------------- ``` def f s,m m.each_line{|r|%w{= - =}.map{|i|s+=i==r[2*s-3]?-1:i==r[2*s-1]?1:0}} s end ``` 92 chars ``` def f s,m s=s*2-2 m.each_line{|r|%w{= - =}.each{|i|s+=i==r[s-1]?-2:i==r[s+1]?2:0}} 1+s/2 end ``` Usage ``` map="|-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-|" 1.upto(6) do |i| p f(i, map) end ``` Output ``` 6 1 3 5 4 2 ```
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
Seems like the answer is NO. While others here have helpfully suggested workarounds to try, the answer as to whether the piece of hardware I asked about exists in a single piece is NO.
The emulator that you want does exist. You are looking for an emulator that emulates a USB Floppy Drive. So the emulator connects to the computer via a USB cable, and the storage media is a USB Flash Drive. Do a Google search on "UFA1M44-100" and you will find one model of emulator that emulates a USB Floppy Drive. You can find another company that sells these if you do a Google search on "IntelliRob Systems". Look in the menu on the left side of their pages for "1.44 MB (USB) acts as USB Floppy Drive". I was trying to find a way to get a USB Flash Drive to act as a floppy without any emulator, but I finally gave up and started to look for a regular USB Floppy Drive. That is when I stumbled upon these USB Floppy Drive Emulators. I've already bought a USB Floppy Drive, but these emulators still interest me, so I may yet buy one. If you do buy one, please let us know how well it works out.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
There's no way a USB anything can transparently emulate a floppy drive without a driver being preinstalled. The traditional PC floppy drive was an ISA device and appeared on specific I/O ports (0x3F0 to 0x3F6 IIRC). Reading and writing to these ports was how you talked to the floppy drive. USB peripherals talk to a USB controller, but do not otherwise have a connection to the system bus. So they cannot appear at the x86 I/O addresses where something expecting a traditional floppy would be trying to read/write. USB keyboards and mice look like PS/2 device to DOS and BIOS by a sleight of hand called "System Management Mode" - unfortunately this is part of BIOS/UEFI firmware and not easily/publicly available to operating systems to customize. It may be possible for a device or software to hook into BIOS routines that read/write to the floppy, but by the time you get to that prompt in the Windows XP installer, Windows is already running and not using the BIOS to read/write to devices. Really doing this would at least require a direct connection to the ISA or PCI/PCI-E bus. And many motherboard chipsets already have a Super I/O chip or equivalent that acts as a floppy controller, and already appears in those locations. The HxC devices mentioned by @tofro are probably what you want. Search for "cf card floppy emulator."
You can install XP in IDE mode and install the AHCI drivers afterwards, I did this on my netbook several times. I think it goes something like: * Set disk controller to IDE mode in bios, and install XP. * In device manager go to the disk controller and manually change the driver to the AHCI one. * Reboot into bios and change disk controller to AHCI mode. * Save and reboot, XP should now load successfully. If you miss any step you will likely get the BSOD.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
I don't think anyone sells something like that in one piece. There are, however, components on the market that should allow you to build that from scratch: 1. A GoTek or HxC that behaves like a "real" floppy 2. An *old* Floppy-to-USB adapter that was used to connect "real" floppies over USB. I don't think they're still made, so you would need to source one from eBay. Newer USB floppy drives no longer have this as I have learned from answers to [this](https://retrocomputing.stackexchange.com/questions/5428/is-there-anything-useful-for-a-retro-in-these-cheap-chinese-floppy-drives) question. 3. Some sort of external power supply, as the GoTek/HxC will not be willing to live from the USB power supply. Putting it all together would end you up with something that behaves like a real floppy, connected over USB. This is, however, never going to be a full replacement for a "real" floppy disk drive. Old computer's abilities to for example boot from USB floppies have always been very limited (even if they could always boot very well from standard floppy drives). Once you find one that does this, it will most probably also boot from a standard USB flash stick. You'd probably be much better off by buying a bunch of HD disks and storing them well. Another, entirely different, but possibly long-term method to make Windows XP think it has a floppy drive would be a *[virtual floppy driver](http://vfd.sourceforge.net)*. This just emulates a floppy based on an image stored on hard disk and could be a solution for many problems. You'd obviously need to have a drive and disk first in order to pull the images from "real" disks.
You can install XP in IDE mode and install the AHCI drivers afterwards, I did this on my netbook several times. I think it goes something like: * Set disk controller to IDE mode in bios, and install XP. * In device manager go to the disk controller and manually change the driver to the AHCI one. * Reboot into bios and change disk controller to AHCI mode. * Save and reboot, XP should now load successfully. If you miss any step you will likely get the BSOD.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
I don't think anyone sells something like that in one piece. There are, however, components on the market that should allow you to build that from scratch: 1. A GoTek or HxC that behaves like a "real" floppy 2. An *old* Floppy-to-USB adapter that was used to connect "real" floppies over USB. I don't think they're still made, so you would need to source one from eBay. Newer USB floppy drives no longer have this as I have learned from answers to [this](https://retrocomputing.stackexchange.com/questions/5428/is-there-anything-useful-for-a-retro-in-these-cheap-chinese-floppy-drives) question. 3. Some sort of external power supply, as the GoTek/HxC will not be willing to live from the USB power supply. Putting it all together would end you up with something that behaves like a real floppy, connected over USB. This is, however, never going to be a full replacement for a "real" floppy disk drive. Old computer's abilities to for example boot from USB floppies have always been very limited (even if they could always boot very well from standard floppy drives). Once you find one that does this, it will most probably also boot from a standard USB flash stick. You'd probably be much better off by buying a bunch of HD disks and storing them well. Another, entirely different, but possibly long-term method to make Windows XP think it has a floppy drive would be a *[virtual floppy driver](http://vfd.sourceforge.net)*. This just emulates a floppy based on an image stored on hard disk and could be a solution for many problems. You'd obviously need to have a drive and disk first in order to pull the images from "real" disks.
The emulator that you want does exist. You are looking for an emulator that emulates a USB Floppy Drive. So the emulator connects to the computer via a USB cable, and the storage media is a USB Flash Drive. Do a Google search on "UFA1M44-100" and you will find one model of emulator that emulates a USB Floppy Drive. You can find another company that sells these if you do a Google search on "IntelliRob Systems". Look in the menu on the left side of their pages for "1.44 MB (USB) acts as USB Floppy Drive". I was trying to find a way to get a USB Flash Drive to act as a floppy without any emulator, but I finally gave up and started to look for a regular USB Floppy Drive. That is when I stumbled upon these USB Floppy Drive Emulators. I've already bought a USB Floppy Drive, but these emulators still interest me, so I may yet buy one. If you do buy one, please let us know how well it works out.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
Seems like the answer is NO. While others here have helpfully suggested workarounds to try, the answer as to whether the piece of hardware I asked about exists in a single piece is NO.
You can install XP in IDE mode and install the AHCI drivers afterwards, I did this on my netbook several times. I think it goes something like: * Set disk controller to IDE mode in bios, and install XP. * In device manager go to the disk controller and manually change the driver to the AHCI one. * Reboot into bios and change disk controller to AHCI mode. * Save and reboot, XP should now load successfully. If you miss any step you will likely get the BSOD.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
There's no way a USB anything can transparently emulate a floppy drive without a driver being preinstalled. The traditional PC floppy drive was an ISA device and appeared on specific I/O ports (0x3F0 to 0x3F6 IIRC). Reading and writing to these ports was how you talked to the floppy drive. USB peripherals talk to a USB controller, but do not otherwise have a connection to the system bus. So they cannot appear at the x86 I/O addresses where something expecting a traditional floppy would be trying to read/write. USB keyboards and mice look like PS/2 device to DOS and BIOS by a sleight of hand called "System Management Mode" - unfortunately this is part of BIOS/UEFI firmware and not easily/publicly available to operating systems to customize. It may be possible for a device or software to hook into BIOS routines that read/write to the floppy, but by the time you get to that prompt in the Windows XP installer, Windows is already running and not using the BIOS to read/write to devices. Really doing this would at least require a direct connection to the ISA or PCI/PCI-E bus. And many motherboard chipsets already have a Super I/O chip or equivalent that acts as a floppy controller, and already appears in those locations. The HxC devices mentioned by @tofro are probably what you want. Search for "cf card floppy emulator."
The emulator that you want does exist. You are looking for an emulator that emulates a USB Floppy Drive. So the emulator connects to the computer via a USB cable, and the storage media is a USB Flash Drive. Do a Google search on "UFA1M44-100" and you will find one model of emulator that emulates a USB Floppy Drive. You can find another company that sells these if you do a Google search on "IntelliRob Systems". Look in the menu on the left side of their pages for "1.44 MB (USB) acts as USB Floppy Drive". I was trying to find a way to get a USB Flash Drive to act as a floppy without any emulator, but I finally gave up and started to look for a regular USB Floppy Drive. That is when I stumbled upon these USB Floppy Drive Emulators. I've already bought a USB Floppy Drive, but these emulators still interest me, so I may yet buy one. If you do buy one, please let us know how well it works out.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
There's no way a USB anything can transparently emulate a floppy drive without a driver being preinstalled. The traditional PC floppy drive was an ISA device and appeared on specific I/O ports (0x3F0 to 0x3F6 IIRC). Reading and writing to these ports was how you talked to the floppy drive. USB peripherals talk to a USB controller, but do not otherwise have a connection to the system bus. So they cannot appear at the x86 I/O addresses where something expecting a traditional floppy would be trying to read/write. USB keyboards and mice look like PS/2 device to DOS and BIOS by a sleight of hand called "System Management Mode" - unfortunately this is part of BIOS/UEFI firmware and not easily/publicly available to operating systems to customize. It may be possible for a device or software to hook into BIOS routines that read/write to the floppy, but by the time you get to that prompt in the Windows XP installer, Windows is already running and not using the BIOS to read/write to devices. Really doing this would at least require a direct connection to the ISA or PCI/PCI-E bus. And many motherboard chipsets already have a Super I/O chip or equivalent that acts as a floppy controller, and already appears in those locations. The HxC devices mentioned by @tofro are probably what you want. Search for "cf card floppy emulator."
To boil down what others are saying: A USB device itself is incapable of *making itself appear* as a traditional floppy drive, because USB devices don't have that kind of access. However, if you're lucky, your BIOS will have support for USB floppy drives and *it* can apply the same virtualization trick that it uses to present USB keyboards and mice as PS/2 keyboards and mice for compatibility with old OSes. If your BIOS *does* support that, then the USB floppy can appear as A: or B: for anything which uses the interfaces the BIOS's compatibility mode is providing. If that isn't enough, then you need to search up how to slipstream stuff to build a custom XP install disc with the driver you need already present.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
I don't think anyone sells something like that in one piece. There are, however, components on the market that should allow you to build that from scratch: 1. A GoTek or HxC that behaves like a "real" floppy 2. An *old* Floppy-to-USB adapter that was used to connect "real" floppies over USB. I don't think they're still made, so you would need to source one from eBay. Newer USB floppy drives no longer have this as I have learned from answers to [this](https://retrocomputing.stackexchange.com/questions/5428/is-there-anything-useful-for-a-retro-in-these-cheap-chinese-floppy-drives) question. 3. Some sort of external power supply, as the GoTek/HxC will not be willing to live from the USB power supply. Putting it all together would end you up with something that behaves like a real floppy, connected over USB. This is, however, never going to be a full replacement for a "real" floppy disk drive. Old computer's abilities to for example boot from USB floppies have always been very limited (even if they could always boot very well from standard floppy drives). Once you find one that does this, it will most probably also boot from a standard USB flash stick. You'd probably be much better off by buying a bunch of HD disks and storing them well. Another, entirely different, but possibly long-term method to make Windows XP think it has a floppy drive would be a *[virtual floppy driver](http://vfd.sourceforge.net)*. This just emulates a floppy based on an image stored on hard disk and could be a solution for many problems. You'd obviously need to have a drive and disk first in order to pull the images from "real" disks.
To boil down what others are saying: A USB device itself is incapable of *making itself appear* as a traditional floppy drive, because USB devices don't have that kind of access. However, if you're lucky, your BIOS will have support for USB floppy drives and *it* can apply the same virtualization trick that it uses to present USB keyboards and mice as PS/2 keyboards and mice for compatibility with old OSes. If your BIOS *does* support that, then the USB floppy can appear as A: or B: for anything which uses the interfaces the BIOS's compatibility mode is providing. If that isn't enough, then you need to search up how to slipstream stuff to build a custom XP install disc with the driver you need already present.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
You can install XP in IDE mode and install the AHCI drivers afterwards, I did this on my netbook several times. I think it goes something like: * Set disk controller to IDE mode in bios, and install XP. * In device manager go to the disk controller and manually change the driver to the AHCI one. * Reboot into bios and change disk controller to AHCI mode. * Save and reboot, XP should now load successfully. If you miss any step you will likely get the BSOD.
To boil down what others are saying: A USB device itself is incapable of *making itself appear* as a traditional floppy drive, because USB devices don't have that kind of access. However, if you're lucky, your BIOS will have support for USB floppy drives and *it* can apply the same virtualization trick that it uses to present USB keyboards and mice as PS/2 keyboards and mice for compatibility with old OSes. If your BIOS *does* support that, then the USB floppy can appear as A: or B: for anything which uses the interfaces the BIOS's compatibility mode is providing. If that isn't enough, then you need to search up how to slipstream stuff to build a custom XP install disc with the driver you need already present.
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
Seems like the answer is NO. While others here have helpfully suggested workarounds to try, the answer as to whether the piece of hardware I asked about exists in a single piece is NO.
To boil down what others are saying: A USB device itself is incapable of *making itself appear* as a traditional floppy drive, because USB devices don't have that kind of access. However, if you're lucky, your BIOS will have support for USB floppy drives and *it* can apply the same virtualization trick that it uses to present USB keyboards and mice as PS/2 keyboards and mice for compatibility with old OSes. If your BIOS *does* support that, then the USB floppy can appear as A: or B: for anything which uses the interfaces the BIOS's compatibility mode is providing. If that isn't enough, then you need to search up how to slipstream stuff to build a custom XP install disc with the driver you need already present.
519,832
I want to write the following sentence in a compact way: "The difference between the old scheme and the new scheme lies in..." Which one of the following is correct? 1. The difference between the old and **new scheme** lies in... 2. The difference between the old and **new schemes** lies in... 3. The difference between the old and **the new scheme** lies in... 4. The difference between the old and **the new schemes** lies in... Option 1 sounds more natural to me but I cannot explain why. More important, English is not my mother tongue. In other words, I would like to know: * Is it necessary to repeat the definite article for each element of the list? * Does the common object (in this case, the scheme) become plural when it is listed multiple times with different pre-modifiers (in this case, old and new)?
2019/12/04
[ "https://english.stackexchange.com/questions/519832", "https://english.stackexchange.com", "https://english.stackexchange.com/users/368826/" ]
All are variations of parallelism, with two distinct wrinkles: * Whether the determiner or article must be repeated or not * Whether the head noun is singular or plural All four constructions are valid, but produce slight differences in emphasis. --- > > The difference between **the old and new** scheme lies in... > > > The difference between **the old** and **the new** scheme lies in... > > > In the first example, *the* is a determiner modifying "old and new scheme." Readers will generally understand that it breaks down into "the old scheme and the new scheme." The second example repeats the determiner and further emphasizes it. Generally, readers will still understand "the old scheme and the new scheme." In this case, the difference is slight because no other modifiers are interrupted when the determiner repeats. Fiction editor Beth Hill, in a post on this subject at [The Editor's Blog](https://theeditorsblog.net/2015/08/08/one-adjective-paired-with-multiple-nouns-a-readers-question/), shows how repeating the determiner can mark a further difference between two items: > > **The flat footballs and soccer balls** had been stored in the basement for a long time. (Both footballs and soccer balls are flat.) > > > **The flat footballs and the stained soccer balls** had been stored in the basement for a long time. (Only the footballs are flat—the soccer balls are stained but not flat, at least not that we know of.) > > > **The flat footballs and the soccer balls** had been stored in the basement for a long time. (We have no clues about the condition of the soccer balls. From this wording—with just the addition of the article the—we can’t assume that they’re flat.) > > > Repeating **the** is a clue that other premodifiers like "flat" may only pertain to the first noun. In your case, that is not relevant since the only premodifiers for "scheme" are already distinguished by "and." --- > > The difference between the old and new **scheme** lies in... > > > The difference between the old and new **schemes** lies in... > > > Both work, but with some caveats. Plural signals that there are *two or more* schemes, at least one is old, and at least one is new. It does not limit the potential number - there could be two old and three new schemes. If the existence of only two schemes is evident from context (you've only been discussing two schemes so far in your text), it should provide no confusion. Singular is acceptable because readers will understand that the two adjectives are mutually exclusive, such that it is not one scheme that is both old and new, but two: *the old scheme* and *the new scheme*. Take note: if the adjectives could both describe the same noun, this might be confusing: > > The difference between the hot and wet car lies in ... > > > Some readers might expect "the hot and wet car" to be followed by a second item, like "the cold and dry car," since technically a single car could be both hot and wet. In this case, adding the article avoids the issue ("the hot and the wet car"), since the duplicated determiner could only pertain to a second car. (As described above, duplicating the determiner helps mark further differences between items.) Confusion can also be avoided when using mutually exclusive adjectives (e.g. user-centric and network-centric).
Replacing the premodifiers with less esoteric ones (and assuming that that does not affect the analysis too greatly): > > 0' *The difference between the old model and the new model* ... > > > is the undeleted (part-) sentence, obviously correct for a single new model. ........................................................................... Deleting the head noun only, firstly with no adjustment to the singular-form 'model' (deletions usually leave the remaining sentence unaltered): > > 3' *The difference between the old and the new model* ... gives 319 000 hits in a Google search > > > while > > 4' *The difference between the old and the new models* ... gives 178 000 hits. > > > While there is the clear possibility that 4' refers to more than one new model (and perhaps more than one old model), and that this is thus a poorer choice when just two models are being compared, the following from a [2017 Carvoy review](https://blog.carvoy.com/28-old-vs-new-lexus-rx350/) shows that the plural-form noun *is* used in such situations: > > Although the 2017 version of the RX350 carried over all the things we > got to know and loved about the 2015 version, the main point of > difference between the old and the new models is the new safety and > technology features integrated into the new model. > > > This compares with the totally grammatical > > 4" *The difference between the two models* ... > > > So in summary, both forms are used, but there is a reasonable preference for 'model' here. ........................................................................... Going further, > > 1' *The difference between the old and new model* ... gives 269 000 hits > > > while > > 2' *The difference between the old and new models* ... gives 156 000 hits. > > > So both further-deleted forms also seem to be accepted by many. I'm surprised by the fact that 1' seems preferred to 2', as I feel 1' sounds incongruous.
519,832
I want to write the following sentence in a compact way: "The difference between the old scheme and the new scheme lies in..." Which one of the following is correct? 1. The difference between the old and **new scheme** lies in... 2. The difference between the old and **new schemes** lies in... 3. The difference between the old and **the new scheme** lies in... 4. The difference between the old and **the new schemes** lies in... Option 1 sounds more natural to me but I cannot explain why. More important, English is not my mother tongue. In other words, I would like to know: * Is it necessary to repeat the definite article for each element of the list? * Does the common object (in this case, the scheme) become plural when it is listed multiple times with different pre-modifiers (in this case, old and new)?
2019/12/04
[ "https://english.stackexchange.com/questions/519832", "https://english.stackexchange.com", "https://english.stackexchange.com/users/368826/" ]
I would say that you do not require the last two articles, as neither is the focus of identification. What is being identified is 'the' difference : > > The difference between old and new schemes lies in ... > > > --- It could be argued that this is an example of the zero article, that is to say the absent article regarding 'old' and 'new'. See elsewhere on this site for 'null' and 'zero' articles and for references to Peter Masters. For example : [Should 'one' be considered an article ?](https://english.stackexchange.com/questions/425829/should-one-be-considered-an-article)
Replacing the premodifiers with less esoteric ones (and assuming that that does not affect the analysis too greatly): > > 0' *The difference between the old model and the new model* ... > > > is the undeleted (part-) sentence, obviously correct for a single new model. ........................................................................... Deleting the head noun only, firstly with no adjustment to the singular-form 'model' (deletions usually leave the remaining sentence unaltered): > > 3' *The difference between the old and the new model* ... gives 319 000 hits in a Google search > > > while > > 4' *The difference between the old and the new models* ... gives 178 000 hits. > > > While there is the clear possibility that 4' refers to more than one new model (and perhaps more than one old model), and that this is thus a poorer choice when just two models are being compared, the following from a [2017 Carvoy review](https://blog.carvoy.com/28-old-vs-new-lexus-rx350/) shows that the plural-form noun *is* used in such situations: > > Although the 2017 version of the RX350 carried over all the things we > got to know and loved about the 2015 version, the main point of > difference between the old and the new models is the new safety and > technology features integrated into the new model. > > > This compares with the totally grammatical > > 4" *The difference between the two models* ... > > > So in summary, both forms are used, but there is a reasonable preference for 'model' here. ........................................................................... Going further, > > 1' *The difference between the old and new model* ... gives 269 000 hits > > > while > > 2' *The difference between the old and new models* ... gives 156 000 hits. > > > So both further-deleted forms also seem to be accepted by many. I'm surprised by the fact that 1' seems preferred to 2', as I feel 1' sounds incongruous.
519,832
I want to write the following sentence in a compact way: "The difference between the old scheme and the new scheme lies in..." Which one of the following is correct? 1. The difference between the old and **new scheme** lies in... 2. The difference between the old and **new schemes** lies in... 3. The difference between the old and **the new scheme** lies in... 4. The difference between the old and **the new schemes** lies in... Option 1 sounds more natural to me but I cannot explain why. More important, English is not my mother tongue. In other words, I would like to know: * Is it necessary to repeat the definite article for each element of the list? * Does the common object (in this case, the scheme) become plural when it is listed multiple times with different pre-modifiers (in this case, old and new)?
2019/12/04
[ "https://english.stackexchange.com/questions/519832", "https://english.stackexchange.com", "https://english.stackexchange.com/users/368826/" ]
All are variations of parallelism, with two distinct wrinkles: * Whether the determiner or article must be repeated or not * Whether the head noun is singular or plural All four constructions are valid, but produce slight differences in emphasis. --- > > The difference between **the old and new** scheme lies in... > > > The difference between **the old** and **the new** scheme lies in... > > > In the first example, *the* is a determiner modifying "old and new scheme." Readers will generally understand that it breaks down into "the old scheme and the new scheme." The second example repeats the determiner and further emphasizes it. Generally, readers will still understand "the old scheme and the new scheme." In this case, the difference is slight because no other modifiers are interrupted when the determiner repeats. Fiction editor Beth Hill, in a post on this subject at [The Editor's Blog](https://theeditorsblog.net/2015/08/08/one-adjective-paired-with-multiple-nouns-a-readers-question/), shows how repeating the determiner can mark a further difference between two items: > > **The flat footballs and soccer balls** had been stored in the basement for a long time. (Both footballs and soccer balls are flat.) > > > **The flat footballs and the stained soccer balls** had been stored in the basement for a long time. (Only the footballs are flat—the soccer balls are stained but not flat, at least not that we know of.) > > > **The flat footballs and the soccer balls** had been stored in the basement for a long time. (We have no clues about the condition of the soccer balls. From this wording—with just the addition of the article the—we can’t assume that they’re flat.) > > > Repeating **the** is a clue that other premodifiers like "flat" may only pertain to the first noun. In your case, that is not relevant since the only premodifiers for "scheme" are already distinguished by "and." --- > > The difference between the old and new **scheme** lies in... > > > The difference between the old and new **schemes** lies in... > > > Both work, but with some caveats. Plural signals that there are *two or more* schemes, at least one is old, and at least one is new. It does not limit the potential number - there could be two old and three new schemes. If the existence of only two schemes is evident from context (you've only been discussing two schemes so far in your text), it should provide no confusion. Singular is acceptable because readers will understand that the two adjectives are mutually exclusive, such that it is not one scheme that is both old and new, but two: *the old scheme* and *the new scheme*. Take note: if the adjectives could both describe the same noun, this might be confusing: > > The difference between the hot and wet car lies in ... > > > Some readers might expect "the hot and wet car" to be followed by a second item, like "the cold and dry car," since technically a single car could be both hot and wet. In this case, adding the article avoids the issue ("the hot and the wet car"), since the duplicated determiner could only pertain to a second car. (As described above, duplicating the determiner helps mark further differences between items.) Confusion can also be avoided when using mutually exclusive adjectives (e.g. user-centric and network-centric).
I would argue for one of the following forms, my preference being for the first. > > 1) ... the old scheme and the new scheme ... > > > 2) ... the old and the new schemes ... > > > 3) ... the two schemes, old and new, ... > > > This is because the difference is between a scheme and a scheme, not between "an old" and "a new." So this should be emphasized by the sentence structure.
519,832
I want to write the following sentence in a compact way: "The difference between the old scheme and the new scheme lies in..." Which one of the following is correct? 1. The difference between the old and **new scheme** lies in... 2. The difference between the old and **new schemes** lies in... 3. The difference between the old and **the new scheme** lies in... 4. The difference between the old and **the new schemes** lies in... Option 1 sounds more natural to me but I cannot explain why. More important, English is not my mother tongue. In other words, I would like to know: * Is it necessary to repeat the definite article for each element of the list? * Does the common object (in this case, the scheme) become plural when it is listed multiple times with different pre-modifiers (in this case, old and new)?
2019/12/04
[ "https://english.stackexchange.com/questions/519832", "https://english.stackexchange.com", "https://english.stackexchange.com/users/368826/" ]
I would say that you do not require the last two articles, as neither is the focus of identification. What is being identified is 'the' difference : > > The difference between old and new schemes lies in ... > > > --- It could be argued that this is an example of the zero article, that is to say the absent article regarding 'old' and 'new'. See elsewhere on this site for 'null' and 'zero' articles and for references to Peter Masters. For example : [Should 'one' be considered an article ?](https://english.stackexchange.com/questions/425829/should-one-be-considered-an-article)
I would argue for one of the following forms, my preference being for the first. > > 1) ... the old scheme and the new scheme ... > > > 2) ... the old and the new schemes ... > > > 3) ... the two schemes, old and new, ... > > > This is because the difference is between a scheme and a scheme, not between "an old" and "a new." So this should be emphasized by the sentence structure.
62,006,211
Having worked through a course on Pluralsight (.NET Logging Done Right: An Opinionated Approach Using Serilog by Erik Dahl) I began implementing a similar solution in my own ASP.Net Core 3.1 MVC project. As an initial proof of concept I downloaded his complete sample code from the course and integrated his logger class library into my project to see if it worked. Unfortunately, everything seems to work apart from one critical element. In the Configure method of my project's Startup.cs file rather than `app.UseExceptionHandler("/Home/Error");` I now have `app.UseCustomExceptionHandler("MyAppName", "Core MVC", "/Home/Error");` - in theory this is meant to hit some custom middleware, passing in some additional data for error logging, then behave like the normal exception handler and hit the error handling path. In practice, it doesn't hit the error handling path and users are shown the browser's error page. The comments on the middleware code say this code is: ``` // based on Microsoft's standard exception middleware found here: // https://github.com/aspnet/Diagnostics/tree/dev/src/ // Microsoft.AspNetCore.Diagnostics/ExceptionHandler ``` This link no longer works. I found the new link but it's in a GitHub archive and it didn't tell me anything useful. I am aware that there were changes to the way routing works between .Net Core 2.0 and 3.1, but I'm not sure whether these would cause the issue I am experiencing. I do not think the issue is in the code below that gets called from Startup.cs. ``` public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionHandler( this IApplicationBuilder builder, string product, string layer, string errorHandlingPath) { return builder.UseMiddleware<CustomExceptionHandlerMiddleware> (product, layer, Options.Create(new ExceptionHandlerOptions { ExceptionHandlingPath = new PathString(errorHandlingPath) })); } } ``` I believe the issue is likely to be in the Invoke method in the actual CustomExceptionMiddleware.cs below: ``` public sealed class CustomExceptionHandlerMiddleware { private readonly RequestDelegate _next; private readonly ExceptionHandlerOptions _options; private readonly Func<object, Task> _clearCacheHeadersDelegate; private string _product, _layer; public CustomExceptionHandlerMiddleware(string product, string layer, RequestDelegate next, ILoggerFactory loggerFactory, IOptions<ExceptionHandlerOptions> options, DiagnosticSource diagSource) { _product = product; _layer = layer; _next = next; _options = options.Value; _clearCacheHeadersDelegate = ClearCacheHeaders; if (_options.ExceptionHandler == null) { _options.ExceptionHandler = _next; } } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { WebHelper.LogWebError(_product, _layer, ex, context); PathString originalPath = context.Request.Path; if (_options.ExceptionHandlingPath.HasValue) { context.Request.Path = _options.ExceptionHandlingPath; } context.Response.Clear(); var exceptionHandlerFeature = new ExceptionHandlerFeature() { Error = ex, Path = originalPath.Value, }; context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature); context.Features.Set<IExceptionHandlerPathFeature>(exceptionHandlerFeature); context.Response.StatusCode = 500; context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response); await _options.ExceptionHandler(context); return; } } private Task ClearCacheHeaders(object state) { var response = (HttpResponse)state; response.Headers[HeaderNames.CacheControl] = "no-cache"; response.Headers[HeaderNames.Pragma] = "no-cache"; response.Headers[HeaderNames.Expires] = "-1"; response.Headers.Remove(HeaderNames.ETag); return Task.CompletedTask; } } ``` Any suggestions would be really appreciated, I've been down so many rabbit holes trying to get this working over the last few days to no avail, and quite aside from my own project, I'd love to be able to leave a comment on the Pluralsight course for anyone else trying to do this to save them having to go through the same struggles as I have.
2020/05/25
[ "https://Stackoverflow.com/questions/62006211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7801941/" ]
You can use `trackBy` on **\*ngFor** to deal with changes. It allows you to check each element and rerenders only the ones that are new. You can use an id or another unique elements to check them. Template : ```js <tr *ngFor="let element of objects$ | async; trackBy: trackByFunction"> </tr ``` Component : ```js trackByFunction(index: number; element: MyClass) { return element.id; // or another unique property } ``` Here is an example i made few days ago on [Stackblitz](https://stackblitz.com/edit/ng-sample-performance-trackby?file=src%2Fapp%2Fapp.component.ts) (with a message on new elements to tag them)
It is an **observable** element. So you could **subscribe** to that object and Angular do check for changes and will update your variable without reloads. Something like this: ```js this.yourWebSocketService.yourObservableObject.subscribe( data=> { this.objects$ = data } ```