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
|
---|---|---|---|---|---|
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | The Arduino is really an AVR Atmega328p. The Arduino is a fine off-the-shelf implementation of this microcontroller, but if you make many of them, you can buy the chip for less than $3 each in bulk, and it requires very little circuitry to run on its own -- a crystal and a couple of capacitors to run at 20 Mhz, or not even that if you can run at the built-in 8 MHz resonant oscillator frequency.
It's fine for generating control signals: Servo PWM, step/direction, control for H-bridges, etc.)
It's also OK for running sensors: Ultrasonic time measurement, IR voltage conversion measurement, on/off contactors, etc -- this includes whatever optical sensor you'd use for "line sensing."
There will be a little code space left over after doing these tasks, so the simple control loop of "is the line to the right, left, or center of me -> do the appropriate turn" can be built into that system. However, as soon as you want to do something bigger, like path planning, environmental awareness, memory, SLAM, etc, you will not be able to fit that into the Arduino.
Thus, the best system for your requirements probably includes tying all the physical hardware to the Arduino, and then talking to the Arduino from the Raspberry Pi. The RPi has a modicum of CPU power (700 MHz ARM) and RAM (256-512 MB RAM) and thus can run higher-level control algorithms like path planning, localization, SLAM, etc.
If you go with a bare AVR controller, there are UART outputs on the Raspberry Pi, but the problem is that the RPi is 3.3V and the Arduino Uno is 5V. Either go with a 3.3V Arduino version, or use a voltage divider to step down 5.0V output from the Arduino to the 3.3V input of the Raspberry Pi. I use a 2.2 kOhm high and 3.3 kOhm low resistor and it works fine. You can feed the 3V output from the Raspberry Pi directly into the RXD of the AVR, because it will treat anything at 1.2V or up as "high." | I would suggest using lower end Atmel AVRs for beginning robotics projects. An AVR can take a lot of abuse and can sink and source more current without burning out than the PIC microcontrollers I have used.
If you are going to be building multiple projects, you should consider investing in building your own breakout boards. You can design your own PCB with standard power circuitry, a bunch of headers for I/O and whatever microcontroller you choose. You can get your cost down to around $15 per board for the PCB and then a couple bucks worth of components. This way, you can leave your project intact, instead of having to harvest out the microcontroller for your next project. As a bonus, you will gain valuable experience in PCB design and soldering. |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | It really depends on the project.
For a line follower robot ( in your case ), using the Atmel's AVR series is the best choice. Specially ATMEGA16 or even ATMEGA32.
Because the line-follower is a small project and the Arduino is too much for it. And the other advantage of Atmega16 is that it is cheap. If it is broken or faulty then you can change it easily. and it also provides PWM for controlling the speed of motors.
So with atmega series you can build the most powerful line-follower . No need to spend money on getting prebuilt boards and ... | If you want to go further than using microcontrollers you could run ROS on you [Raspberry Pi](http://www.ros.org/wiki/ROSberryPi/Setting%20up%20ROS%20on%20RaspberryPi).
I have build several robots and a couple of other projects using a [RoboCard](http://robocard.dk/) (site in Danish, but can [be translated](http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&u=http://robocard.dk/pages/home.php&sl=da&tl=en)). The RoboCard is build around an ATMega, so that certainly is a viable route. |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | You should use an ARM. Then you can run full linux or android and have access to powerful libraries, high-level functional languages, and a package manager and community. You can use gcc or LLVM, and a modern debugger like gdb.
ARMs used to be too expensive and/or too big, but nowadays you can get an ARM for $5 that's only 13x13 mm. You have to use reflow soldering, but you will anyways if you want to make a professional-quality robot.
<http://www.eetimes.com/electronics-products/electronic-product-reviews/processors/4230227/TI-debuts--5-Sitara-AM335x-ARM-processors>
All other instructions sets have lost the competition. If you pick something like AVR, you will be forever stuck with inferior toolchains, weaker MIPS/dollar, and a much smaller community.
If you don't want to engineer the whole motherboard, then Gumstix, BeagleBone, BeagleBoard, and Raspberry Pi are all excellent pre-existing ARM-based devkits, and processor vendors also offer a devkit for every processor they make, bringing out at least a display bus and some serial busses. | If you want to go further than using microcontrollers you could run ROS on you [Raspberry Pi](http://www.ros.org/wiki/ROSberryPi/Setting%20up%20ROS%20on%20RaspberryPi).
I have build several robots and a couple of other projects using a [RoboCard](http://robocard.dk/) (site in Danish, but can [be translated](http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&u=http://robocard.dk/pages/home.php&sl=da&tl=en)). The RoboCard is build around an ATMega, so that certainly is a viable route. |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | The Arduino is really an AVR Atmega328p. The Arduino is a fine off-the-shelf implementation of this microcontroller, but if you make many of them, you can buy the chip for less than $3 each in bulk, and it requires very little circuitry to run on its own -- a crystal and a couple of capacitors to run at 20 Mhz, or not even that if you can run at the built-in 8 MHz resonant oscillator frequency.
It's fine for generating control signals: Servo PWM, step/direction, control for H-bridges, etc.)
It's also OK for running sensors: Ultrasonic time measurement, IR voltage conversion measurement, on/off contactors, etc -- this includes whatever optical sensor you'd use for "line sensing."
There will be a little code space left over after doing these tasks, so the simple control loop of "is the line to the right, left, or center of me -> do the appropriate turn" can be built into that system. However, as soon as you want to do something bigger, like path planning, environmental awareness, memory, SLAM, etc, you will not be able to fit that into the Arduino.
Thus, the best system for your requirements probably includes tying all the physical hardware to the Arduino, and then talking to the Arduino from the Raspberry Pi. The RPi has a modicum of CPU power (700 MHz ARM) and RAM (256-512 MB RAM) and thus can run higher-level control algorithms like path planning, localization, SLAM, etc.
If you go with a bare AVR controller, there are UART outputs on the Raspberry Pi, but the problem is that the RPi is 3.3V and the Arduino Uno is 5V. Either go with a 3.3V Arduino version, or use a voltage divider to step down 5.0V output from the Arduino to the 3.3V input of the Raspberry Pi. I use a 2.2 kOhm high and 3.3 kOhm low resistor and it works fine. You can feed the 3V output from the Raspberry Pi directly into the RXD of the AVR, because it will treat anything at 1.2V or up as "high." | It really depends on the project.
For a line follower robot ( in your case ), using the Atmel's AVR series is the best choice. Specially ATMEGA16 or even ATMEGA32.
Because the line-follower is a small project and the Arduino is too much for it. And the other advantage of Atmega16 is that it is cheap. If it is broken or faulty then you can change it easily. and it also provides PWM for controlling the speed of motors.
So with atmega series you can build the most powerful line-follower . No need to spend money on getting prebuilt boards and ... |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | The Arduino is really an AVR Atmega328p. The Arduino is a fine off-the-shelf implementation of this microcontroller, but if you make many of them, you can buy the chip for less than $3 each in bulk, and it requires very little circuitry to run on its own -- a crystal and a couple of capacitors to run at 20 Mhz, or not even that if you can run at the built-in 8 MHz resonant oscillator frequency.
It's fine for generating control signals: Servo PWM, step/direction, control for H-bridges, etc.)
It's also OK for running sensors: Ultrasonic time measurement, IR voltage conversion measurement, on/off contactors, etc -- this includes whatever optical sensor you'd use for "line sensing."
There will be a little code space left over after doing these tasks, so the simple control loop of "is the line to the right, left, or center of me -> do the appropriate turn" can be built into that system. However, as soon as you want to do something bigger, like path planning, environmental awareness, memory, SLAM, etc, you will not be able to fit that into the Arduino.
Thus, the best system for your requirements probably includes tying all the physical hardware to the Arduino, and then talking to the Arduino from the Raspberry Pi. The RPi has a modicum of CPU power (700 MHz ARM) and RAM (256-512 MB RAM) and thus can run higher-level control algorithms like path planning, localization, SLAM, etc.
If you go with a bare AVR controller, there are UART outputs on the Raspberry Pi, but the problem is that the RPi is 3.3V and the Arduino Uno is 5V. Either go with a 3.3V Arduino version, or use a voltage divider to step down 5.0V output from the Arduino to the 3.3V input of the Raspberry Pi. I use a 2.2 kOhm high and 3.3 kOhm low resistor and it works fine. You can feed the 3V output from the Raspberry Pi directly into the RXD of the AVR, because it will treat anything at 1.2V or up as "high." | If you want a line-following robot, then something similar to an [m3pi](http://mbed.org/cookbook/m3pi) would be achievable. Photo-transistors seem to be very effective with a black-on-white track.
As for a microcontroller, Mario Markarian is probably right, it is down to personal preference and the project you are working on. The m3pi uses an [mbed](http://mbed.org/handbook/mbed-Microcontrollers) and has a lot of IO's to play with. For more advanced robots a raspberry pi or [beagleboard](http://mbed.org/handbook/mbed-Microcontrollers) work, interfaced with slave microcontroller(s) to provide sensor data and offloading any repetitive computations that could otherwise slow down the pi. |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | I would suggest using lower end Atmel AVRs for beginning robotics projects. An AVR can take a lot of abuse and can sink and source more current without burning out than the PIC microcontrollers I have used.
If you are going to be building multiple projects, you should consider investing in building your own breakout boards. You can design your own PCB with standard power circuitry, a bunch of headers for I/O and whatever microcontroller you choose. You can get your cost down to around $15 per board for the PCB and then a couple bucks worth of components. This way, you can leave your project intact, instead of having to harvest out the microcontroller for your next project. As a bonus, you will gain valuable experience in PCB design and soldering. | If you want to go further than using microcontrollers you could run ROS on you [Raspberry Pi](http://www.ros.org/wiki/ROSberryPi/Setting%20up%20ROS%20on%20RaspberryPi).
I have build several robots and a couple of other projects using a [RoboCard](http://robocard.dk/) (site in Danish, but can [be translated](http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&u=http://robocard.dk/pages/home.php&sl=da&tl=en)). The RoboCard is build around an ATMega, so that certainly is a viable route. |
4 | I am looking for a starting point for my project, preferably using popular systems (ones there is a lot of support for). I have an Arduino Uno, a Raspberry Pi, and a lot of willpower :) Anyone here built a project using the systems above?
Observation: I'd like to start with a simple line-following vehicle and build up afterwards. | 2012/10/23 | [
"https://robotics.stackexchange.com/questions/4",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/32/"
] | I built a line following robot with an Arduino before. It was really simple to do and all we used were color sensors on the bottom inputted in the Arduino, and then of course some motors for the wheels.
But using an Arduino allowed us to have plenty of room for other components we wanted to add on to make our robot do more things.
Also, if you want to see some line following code we used just ask in a comment, but it obviously depends on your setup with the sensors and how you want it to turn at intersections and things like that. | If you want to go further than using microcontrollers you could run ROS on you [Raspberry Pi](http://www.ros.org/wiki/ROSberryPi/Setting%20up%20ROS%20on%20RaspberryPi).
I have build several robots and a couple of other projects using a [RoboCard](http://robocard.dk/) (site in Danish, but can [be translated](http://translate.google.com/translate?js=y&prev=_t&hl=en&ie=UTF-8&layout=1&eotf=1&u=http://robocard.dk/pages/home.php&sl=da&tl=en)). The RoboCard is build around an ATMega, so that certainly is a viable route. |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | Command-click the view in question and select the Make Conditional option in Beta 5. I did this on one of my views (LiftsCollectionView), and it generated the following:
```
if suggestedLayout.size.height > 150 {
LiftsCollectionView()
} else {
EmptyView()
}
``` | The following custom modifier works as .hidden() does by both hiding the view and disabling interaction with it.
ViewModifier and View extension func -
```swift
import SwiftUI
fileprivate struct HiddenIfModifier: ViewModifier {
var isHidden: Bool
init(condition: Bool) {
self.isHidden = condition
}
func body(content: Content) -> some View {
content
// Conditionally changing the parameters of modifiers
// is more efficient than conditionally applying a modifier
// (as in Cristina's ViewModifier implementation).
.opacity(isHidden ? 0 : 1)
.disabled(isHidden)
}
}
extension View {
/// Hides a view conditionally.
/// - Parameters:
/// - condition: Decides if `View` is hidden.
/// - Returns: The `View`, hidden if `condition` is `true`.
func hidden(if condition: Bool) -> some View {
modifier(HiddenIfModifier(condition: condition))
}
}
```
Use -
```swift
DatePicker($datePickerDate)
.hidden(if: !self.showDatePicker)
```
Note -
Conditionally applying a modifier is inefficient because swift sees the unmodified and modified views as different types. This causes the view (and it's state) to be destroyed and rebuilt every time the condition changes. This can become an issue for data heavy views like List. Conditionally changing the parameters of modifiers doesn't cause this issue. |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | Edit Nov 4 2021
---------------
I now prefer another approach over the one in my original answer (below):
There are two possible solutions depending on if you want to keep the original space occupied or make the other views take the space of the one that's hidden.
### Keep the space
```swift
DatePicker("Choose date", selection: $datePickerDate)
.opacity(showDatePicker ? 1 : 0)
```
Even if we are adjusting just opacity here, touching the space where the `DatePicker` should be when it's hidden doesn't open the calendar.
### Don't keep the space
```swift
if showDatePicker {
DatePicker("Choose date", selection: $datePickerDate)
}
```
---
Original answer
---------------
For whoever needs it in the future, I created a `ViewModifier` which takes a `Bool` as parameter so you can bind a boolean value to show and hide the view declaratively by just setting your `showDatePicker: Bool` variable.
*All code snippets require* `import SwiftUI`.
### The `ViewModifier`:
```
struct Show: ViewModifier {
let isVisible: Bool
@ViewBuilder
func body(content: Content) -> some View {
if isVisible {
content
} else {
content.hidden()
}
}
}
```
### The function:
```
extension View {
func show(isVisible: Bool) -> some View {
ModifiedContent(content: self, modifier: Show(isVisible: isVisible))
}
}
```
And you can use it like this:
```
var datePicker = DatePicker($datePickerDate)
.show(isVisible: showDatePicker)
``` | You also have the `opacity` modifier on any `View`:
```
ActivityIndicator(tint: .black)
.opacity(self.isLoading ? 1.0 : 0.0)
``` |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | I had the same problem, and I solved it in the following way:
Note: I use **binding** to hide and/or show dynamically.
1 - Create Modifier
```swift
struct HiddenModifier: ViewModifier{
var isHide:Binding<Bool>
func body(content: Content) -> some View {
if isHide.wrappedValue{
content
.hidden()
}
else{
content
}
}
}
```
2 - Add Modifier to view:
```swift
extension View{
func hiddenModifier(isHide:Binding<Bool>) -> some View{
return self.modifier(HiddenModifier(isHide: isHide))
}
}
```
3 - Use Modifier
```swift
struct CheckHiddenView: View {
@State var hide:Bool = false
var body: some View {
VStack(spacing: 24){
Text("Check Hidden")
.font(.title)
RoundedRectangle(cornerRadius: 20)
.fill(Color.orange)
.frame(width: 150, height: 150, alignment: .center)
.hiddenModifier(hide: $hide)
Button {
withAnimation {
hide.toggle()
}
} label: {
Text("Toggle")
}
.buttonStyle(.bordered)
}
}
}
```
**Test**
[](https://i.stack.imgur.com/vECBW.gif) | The bad part of the above solution `.isHidden(true, remove: true)` is onAppear callback will not be called when `remove = true`.
`.opacity(isHidden ? 0 : 1)` is definitely the right way. |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | ✅ The correct and Simplest Way:
===============================
You can set the alpha instead, this will preserve the layout space of the view too and does not force you to add dummy views like the other answers:
```
.opacity(isHidden ? 0 : 1)
```
### Demo
[](https://i.stack.imgur.com/7EgSY.gif)
---
Cleaner Way! - Extend original `hidden` modifier:
==================================================
Also, you can implement a custom function to get the visibility state as an argument:
```
extension View {
func hidden(_ shouldHide: Bool) -> some View {
opacity(shouldHide ? 0 : 1)
}
}
```
Now just pass the `bool` to the modifier:
```
DatePicker($datePickerDate)
.hidden(showDatePicker)
```
**Note that** unlike the original behavior of the `hidden` modifier, both of these methods preserve the frame of the hiding view.
---
⛔️ Don't use bad practices !!!
==============================
All other answers (including the accepted answer by @Jake) use branches instead of dependent code that cause a performance hit.
### Branch example:
[](https://i.stack.imgur.com/xfgzt.png)
### ✅ Dependent Code example:
[](https://i.stack.imgur.com/IpWIp.png)
Returning *logical **SAME** view* for different states causes the SwiftUI to render engine to re-render and initial a view again and cause a performance hit! (see more at **[this WWDC session](https://developer.apple.com/wwdc21/10022)**) | The bad part of the above solution `.isHidden(true, remove: true)` is onAppear callback will not be called when `remove = true`.
`.opacity(isHidden ? 0 : 1)` is definitely the right way. |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | The simplest and most common way to hide a view is like the following:
```
struct ContentView: View {
@State private var showText = true
var body: some View {
VStack {
Button("Toggle text") {
showText.toggle()
}
if showText {
Text("Hello World!")
}
}
}
}
```
This removes the `Text` view from the hierarchy when `showText` equals `false`. If you wish to have an option to preserve the space or want it as a modifier, see below.
---
I created an extension, so you can use a modifier, like so to hide the view:
```
Text("Hello World!")
.isHidden(true)
```
Or for complete removal:
```
Text("Label")
.isHidden(true, remove: true)
```
The extension below is also available on GitHub here if you want to use Swift Packages: [GeorgeElsham/HidingViews](https://github.com/GeorgeElsham/HidingViews).
---
Here is the code to create the `View` modifier:
I recommend you use this code in its own file (remember to `import SwiftUI`):
```
extension View {
/// Hide or show the view based on a boolean value.
///
/// Example for visibility:
///
/// Text("Label")
/// .isHidden(true)
///
/// Example for complete removal:
///
/// Text("Label")
/// .isHidden(true, remove: true)
///
/// - Parameters:
/// - hidden: Set to `false` to show the view. Set to `true` to hide the view.
/// - remove: Boolean value indicating whether or not to remove the view.
@ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
``` | Here is the simple way to Show/Hide view in SwiftUI.
1. Add `@State` variable:
```
@State var showLogo = false
```
2. Add condition like below:
```
VStack {
if showLogo {
Image(systemName: "house.fill")
.resizable()
.frame(width: 100, height: 100, alignment: .center)
.foregroundColor(Color("LightGreyFont"))
.padding(.bottom, 20)
}
Text("Real State App")
.font(Font.custom("Montserrat-Regular", size: 30))
}.padding(.vertical, 25)
```
3. Change state of your @State variable to Show/Hide the view like below:
```
Button(action: {
withAnimation{
self.showLogo.toggle()
}
}, label: {
Text("Login").font(.system(size: 20, weight: .medium, design: .default))
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 50)
.foregroundColor(Color("BlackFont"))
.cornerRadius(10)
})
```
[](https://i.stack.imgur.com/mgUdD.gif) |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | Edit Nov 4 2021
---------------
I now prefer another approach over the one in my original answer (below):
There are two possible solutions depending on if you want to keep the original space occupied or make the other views take the space of the one that's hidden.
### Keep the space
```swift
DatePicker("Choose date", selection: $datePickerDate)
.opacity(showDatePicker ? 1 : 0)
```
Even if we are adjusting just opacity here, touching the space where the `DatePicker` should be when it's hidden doesn't open the calendar.
### Don't keep the space
```swift
if showDatePicker {
DatePicker("Choose date", selection: $datePickerDate)
}
```
---
Original answer
---------------
For whoever needs it in the future, I created a `ViewModifier` which takes a `Bool` as parameter so you can bind a boolean value to show and hide the view declaratively by just setting your `showDatePicker: Bool` variable.
*All code snippets require* `import SwiftUI`.
### The `ViewModifier`:
```
struct Show: ViewModifier {
let isVisible: Bool
@ViewBuilder
func body(content: Content) -> some View {
if isVisible {
content
} else {
content.hidden()
}
}
}
```
### The function:
```
extension View {
func show(isVisible: Bool) -> some View {
ModifiedContent(content: self, modifier: Show(isVisible: isVisible))
}
}
```
And you can use it like this:
```
var datePicker = DatePicker($datePickerDate)
.show(isVisible: showDatePicker)
``` | I had the same problem, and I solved it in the following way:
Note: I use **binding** to hide and/or show dynamically.
1 - Create Modifier
```swift
struct HiddenModifier: ViewModifier{
var isHide:Binding<Bool>
func body(content: Content) -> some View {
if isHide.wrappedValue{
content
.hidden()
}
else{
content
}
}
}
```
2 - Add Modifier to view:
```swift
extension View{
func hiddenModifier(isHide:Binding<Bool>) -> some View{
return self.modifier(HiddenModifier(isHide: isHide))
}
}
```
3 - Use Modifier
```swift
struct CheckHiddenView: View {
@State var hide:Bool = false
var body: some View {
VStack(spacing: 24){
Text("Check Hidden")
.font(.title)
RoundedRectangle(cornerRadius: 20)
.fill(Color.orange)
.frame(width: 150, height: 150, alignment: .center)
.hiddenModifier(hide: $hide)
Button {
withAnimation {
hide.toggle()
}
} label: {
Text("Toggle")
}
.buttonStyle(.bordered)
}
}
}
```
**Test**
[](https://i.stack.imgur.com/vECBW.gif) |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | Here is the simple way to Show/Hide view in SwiftUI.
1. Add `@State` variable:
```
@State var showLogo = false
```
2. Add condition like below:
```
VStack {
if showLogo {
Image(systemName: "house.fill")
.resizable()
.frame(width: 100, height: 100, alignment: .center)
.foregroundColor(Color("LightGreyFont"))
.padding(.bottom, 20)
}
Text("Real State App")
.font(Font.custom("Montserrat-Regular", size: 30))
}.padding(.vertical, 25)
```
3. Change state of your @State variable to Show/Hide the view like below:
```
Button(action: {
withAnimation{
self.showLogo.toggle()
}
}, label: {
Text("Login").font(.system(size: 20, weight: .medium, design: .default))
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 50)
.foregroundColor(Color("BlackFont"))
.cornerRadius(10)
})
```
[](https://i.stack.imgur.com/mgUdD.gif) | Command-click the view in question and select the Make Conditional option in Beta 5. I did this on one of my views (LiftsCollectionView), and it generated the following:
```
if suggestedLayout.size.height > 150 {
LiftsCollectionView()
} else {
EmptyView()
}
``` |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | ✅ The correct and Simplest Way:
===============================
You can set the alpha instead, this will preserve the layout space of the view too and does not force you to add dummy views like the other answers:
```
.opacity(isHidden ? 0 : 1)
```
### Demo
[](https://i.stack.imgur.com/7EgSY.gif)
---
Cleaner Way! - Extend original `hidden` modifier:
==================================================
Also, you can implement a custom function to get the visibility state as an argument:
```
extension View {
func hidden(_ shouldHide: Bool) -> some View {
opacity(shouldHide ? 0 : 1)
}
}
```
Now just pass the `bool` to the modifier:
```
DatePicker($datePickerDate)
.hidden(showDatePicker)
```
**Note that** unlike the original behavior of the `hidden` modifier, both of these methods preserve the frame of the hiding view.
---
⛔️ Don't use bad practices !!!
==============================
All other answers (including the accepted answer by @Jake) use branches instead of dependent code that cause a performance hit.
### Branch example:
[](https://i.stack.imgur.com/xfgzt.png)
### ✅ Dependent Code example:
[](https://i.stack.imgur.com/IpWIp.png)
Returning *logical **SAME** view* for different states causes the SwiftUI to render engine to re-render and initial a view again and cause a performance hit! (see more at **[this WWDC session](https://developer.apple.com/wwdc21/10022)**) | Here is the simple way to Show/Hide view in SwiftUI.
1. Add `@State` variable:
```
@State var showLogo = false
```
2. Add condition like below:
```
VStack {
if showLogo {
Image(systemName: "house.fill")
.resizable()
.frame(width: 100, height: 100, alignment: .center)
.foregroundColor(Color("LightGreyFont"))
.padding(.bottom, 20)
}
Text("Real State App")
.font(Font.custom("Montserrat-Regular", size: 30))
}.padding(.vertical, 25)
```
3. Change state of your @State variable to Show/Hide the view like below:
```
Button(action: {
withAnimation{
self.showLogo.toggle()
}
}, label: {
Text("Login").font(.system(size: 20, weight: .medium, design: .default))
.frame(minWidth: 0, maxWidth: .infinity, maxHeight: 50)
.foregroundColor(Color("BlackFont"))
.cornerRadius(10)
})
```
[](https://i.stack.imgur.com/mgUdD.gif) |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | ✅ The correct and Simplest Way:
===============================
You can set the alpha instead, this will preserve the layout space of the view too and does not force you to add dummy views like the other answers:
```
.opacity(isHidden ? 0 : 1)
```
### Demo
[](https://i.stack.imgur.com/7EgSY.gif)
---
Cleaner Way! - Extend original `hidden` modifier:
==================================================
Also, you can implement a custom function to get the visibility state as an argument:
```
extension View {
func hidden(_ shouldHide: Bool) -> some View {
opacity(shouldHide ? 0 : 1)
}
}
```
Now just pass the `bool` to the modifier:
```
DatePicker($datePickerDate)
.hidden(showDatePicker)
```
**Note that** unlike the original behavior of the `hidden` modifier, both of these methods preserve the frame of the hiding view.
---
⛔️ Don't use bad practices !!!
==============================
All other answers (including the accepted answer by @Jake) use branches instead of dependent code that cause a performance hit.
### Branch example:
[](https://i.stack.imgur.com/xfgzt.png)
### ✅ Dependent Code example:
[](https://i.stack.imgur.com/IpWIp.png)
Returning *logical **SAME** view* for different states causes the SwiftUI to render engine to re-render and initial a view again and cause a performance hit! (see more at **[this WWDC session](https://developer.apple.com/wwdc21/10022)**) | The following also works even without a placeholder view or calling hidden (iOS13.1 and Swift 5)
```
struct Foo: View {
@State var condition: Bool
var body: some View {
if self.condition {
Text("Hello")
}
}
}
```
It's hard to know exactly without peeking at the `@ViewBuilder` implementation, but when evaluating a conditional, it seems that we are getting an `EmptyView` if it fails by default.
So this is equivalent to some of the answers here, but it's simpler. |
56,490,250 | I'm trying to conditionally hide a `DatePicker` in SwiftUI. However, I'm having any issue with mismatched types:
```
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
```
In this case, `datePicker` is a `DatePicker<EmptyView>` type but `datePicker.hidden()` is a `_ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>`. So I cannot assign `datePicker.hidden()` to `datePicker`. I've tried variations of this and can't seem to find a way that works. Any ideas?
**UPDATE**
You can unwrap the `_ModifiedContent` type to get the underlying type using it's `content` property. However, this doesn't solve the underlying issue. The `content` property appears to just be the original, unmodified date picker. | 2019/06/07 | [
"https://Stackoverflow.com/questions/56490250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814799/"
] | Rather than dynamically setting a variable and using it in my view, I found that I was able to hide or show the date picker this way:
```
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
} else {
DatePicker($datePickerDate).hidden()
}
}
}
}
```
Or, optionally, not including the date picker instead of hiding it:
```
struct ContentView : View {
@State var showDatePicker = true
@State var datePickerDate: Date = Date()
var body: some View {
VStack {
if self.showDatePicker {
DatePicker($datePickerDate)
}
}
}
}
``` | The bad part of the above solution `.isHidden(true, remove: true)` is onAppear callback will not be called when `remove = true`.
`.opacity(isHidden ? 0 : 1)` is definitely the right way. |
220,614 | The most basic code(i guess so) to find all the factors of a number
Note:factors include 1 and the number itself
Here's the code:
```
c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
if x%i==0:
print("factor",c+1,":",i)
c=c+1
print("Total number of factors:",c)
```
Please make this code efficient.....ie: Help to reduce the number of iterations | 2019/05/21 | [
"https://codereview.stackexchange.com/questions/220614",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/200977/"
] | Just to have a more readable (than the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin)) and complete (than the [answer](https://codereview.stackexchange.com/a/220617/98493) by [@Sedsarq](https://codereview.stackexchange.com/users/201168/sedsarq)) version of the algorithm presented in the other answers, here is a version that keeps the factors in a `set` and uses the fact that factors always come in pairs:
```
from math import sqrt
def get_factors(n):
"""Returns a sorted list of all unique factors of `n`."""
factors = set()
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
factors.update([i, n // i])
return sorted(factors)
```
Compared to your code this has the added advantage that it is encapsulated in a function, so you can call it repeatedly and give it a clear name and docstring describing what the function does.
It also follows Python's official style-guide, [PEP8](https://www.python.org/dev/peps/pep-0008/), which programmers are encouraged to follow.
With regards to which code is fastest, I'll let this graph speak for itself:
[](https://i.stack.imgur.com/aVney.png)
For the `op` function I used this code which has your checking of all factors up to `x`:
```
def op(x):
factors = []
for i in range(1,x+1):
if x%i==0:
factors.append(i)
return factors
```
And the `factors` function is from the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin).
---
If all you really want is the number of factors, the best way is probably to use the prime factor decomposition. For this you can use a list of primes together with the algorithm in the [answer](https://codereview.stackexchange.com/a/220727/98493) by [@Josay](https://codereview.stackexchange.com/users/9452/josay):
```
from math import sqrt
from functools import reduce
from operators import mul
def prime_sieve(limit):
prime = [True] * limit
prime[0] = prime[1] = False
for i, is_prime in enumerate(prime):
if is_prime:
yield i
for n in range(i * i, limit, i):
prime[n] = False
def prime_factors(n):
primes = prime_sieve(int(sqrt(n) + 1))
for p in primes:
c = 0
while n % p == 0:
n //= p
c += 1
if c > 0:
yield p, c
if n > 1:
yield n, 1
def prod(x):
return reduce(mul, x)
def number_of_factors(n)
return prod(c + 1 for _, c in prime_factors(n))
```
Comparing this with just taking the `len` of the output of the `get_factors` function and this function which implements your algorithm as `op_count`:
```
def len_get_factors(n):
return len(get_factors(n))
def op_count(n):
c = 0
for i in range(1, n + 1):
if n % i == 0:
c = c + 1
return c
```
The following timings result (note the increased range compared to the previous plot):
[](https://i.stack.imgur.com/YaTnu.png) | Divisors come in pairs. Since 2\*50 = 100, both 2 and 50 are divisors to 100. You don't need to search for both of these, because once you've found that 100 is divisible by 2, you can do 100 / 2 to find 50, which is the other divisor. So for every divisor you find, use division to find its "partner" at the same time. That way you don't need to look further than the square root of x:
```
for i in range(1, int(math.sqrt(x)) + 1):
if x % i == 0:
divisor1 = i
divisor2 = x // i
``` |
220,614 | The most basic code(i guess so) to find all the factors of a number
Note:factors include 1 and the number itself
Here's the code:
```
c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
if x%i==0:
print("factor",c+1,":",i)
c=c+1
print("Total number of factors:",c)
```
Please make this code efficient.....ie: Help to reduce the number of iterations | 2019/05/21 | [
"https://codereview.stackexchange.com/questions/220614",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/200977/"
] | Divisors come in pairs. Since 2\*50 = 100, both 2 and 50 are divisors to 100. You don't need to search for both of these, because once you've found that 100 is divisible by 2, you can do 100 / 2 to find 50, which is the other divisor. So for every divisor you find, use division to find its "partner" at the same time. That way you don't need to look further than the square root of x:
```
for i in range(1, int(math.sqrt(x)) + 1):
if x % i == 0:
divisor1 = i
divisor2 = x // i
``` | Since you say in a comment that you may need to find the divisors of a number \$n\$ up to \$10^{60}\$, trial division is not practical, even if performed only up to \$\sqrt n\$ . The only option is to find the prime factorisation and then reconstruct the divisors from the prime factorisation.
There are quite a few [algorithms to find the prime factorisation](https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms). For the size of numbers that interest you, the [quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve) is probably the best option.
Given the prime factorisation, reconstruction of the divisors is just a matter of taking some Cartesian products. Generating them in order is slightly trickier: I reproduce here some code which I wrote for an earlier answer to a similar question. It assumes that `primeFactors` gives output in the form `[(prime, power) ...]` in ascending order of primes.
```
import heapq
def divisors(n):
primes = [(1, 1)] + list(primeFactors(n))
q = [(1, 0, 1)]
while len(q) > 0:
# d is the divisor
# i is the index of its largest "prime" in primes
# a is the exponent of that "prime"
(d, i, a) = heapq.heappop(q)
yield d
if a < primes[i][1]:
heapq.heappush(q, (d * primes[i][0], i, a + 1))
if i + 1 < len(primes):
heapq.heappush(q, (d * primes[i + 1][0], i + 1, 1))
# The condition i > 0 is to avoid duplicates arising because
# d == d // primes[0][0]
if i > 0 and a == 1:
heapq.heappush(q, (d // primes[i][0] * primes[i + 1][0], i + 1, 1))
``` |
220,614 | The most basic code(i guess so) to find all the factors of a number
Note:factors include 1 and the number itself
Here's the code:
```
c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
if x%i==0:
print("factor",c+1,":",i)
c=c+1
print("Total number of factors:",c)
```
Please make this code efficient.....ie: Help to reduce the number of iterations | 2019/05/21 | [
"https://codereview.stackexchange.com/questions/220614",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/200977/"
] | Just to have a more readable (than the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin)) and complete (than the [answer](https://codereview.stackexchange.com/a/220617/98493) by [@Sedsarq](https://codereview.stackexchange.com/users/201168/sedsarq)) version of the algorithm presented in the other answers, here is a version that keeps the factors in a `set` and uses the fact that factors always come in pairs:
```
from math import sqrt
def get_factors(n):
"""Returns a sorted list of all unique factors of `n`."""
factors = set()
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
factors.update([i, n // i])
return sorted(factors)
```
Compared to your code this has the added advantage that it is encapsulated in a function, so you can call it repeatedly and give it a clear name and docstring describing what the function does.
It also follows Python's official style-guide, [PEP8](https://www.python.org/dev/peps/pep-0008/), which programmers are encouraged to follow.
With regards to which code is fastest, I'll let this graph speak for itself:
[](https://i.stack.imgur.com/aVney.png)
For the `op` function I used this code which has your checking of all factors up to `x`:
```
def op(x):
factors = []
for i in range(1,x+1):
if x%i==0:
factors.append(i)
return factors
```
And the `factors` function is from the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin).
---
If all you really want is the number of factors, the best way is probably to use the prime factor decomposition. For this you can use a list of primes together with the algorithm in the [answer](https://codereview.stackexchange.com/a/220727/98493) by [@Josay](https://codereview.stackexchange.com/users/9452/josay):
```
from math import sqrt
from functools import reduce
from operators import mul
def prime_sieve(limit):
prime = [True] * limit
prime[0] = prime[1] = False
for i, is_prime in enumerate(prime):
if is_prime:
yield i
for n in range(i * i, limit, i):
prime[n] = False
def prime_factors(n):
primes = prime_sieve(int(sqrt(n) + 1))
for p in primes:
c = 0
while n % p == 0:
n //= p
c += 1
if c > 0:
yield p, c
if n > 1:
yield n, 1
def prod(x):
return reduce(mul, x)
def number_of_factors(n)
return prod(c + 1 for _, c in prime_factors(n))
```
Comparing this with just taking the `len` of the output of the `get_factors` function and this function which implements your algorithm as `op_count`:
```
def len_get_factors(n):
return len(get_factors(n))
def op_count(n):
c = 0
for i in range(1, n + 1):
if n % i == 0:
c = c + 1
return c
```
The following timings result (note the increased range compared to the previous plot):
[](https://i.stack.imgur.com/YaTnu.png) | All answers provided are great and offer suggestions with a complexity in `O(sqrt(n))` instead of the original `O(n)` by using the trick to stop at `sqrt(n)`.
On big inputs, we can go for an even faster solution by using the decomposition in prime numbers:
* the decomposition in prime numbers can be computed in a time proportional to the square root of the biggest prime divisor if its multiplicity is one (the actually complexity is actually a bit more tricky than this)
* the decomposition can be reused to generate all possible divisors (for each prime `p` with multiplicity `n`, you take `p ^ m` with `0 <= m <= n`.
I can provide the following piece of code for the first task but I do not have a snippet for the second task (yet?)
```
def prime_factors(n):
"""Yields prime factors of a positive number."""
assert n > 0
d = 2
while d * d <= n:
while n % d == 0:
n //= d
yield d
d += 1
if n > 1: # to avoid 1 as a factor
assert d <= n
yield n
```
Edit: I tried to implement the second step and got something which is not highly tested but seems to work:
```
def mult(iterable, start=1):
"""Returns the product of an iterable - like the sum builtin."""
return functools.reduce(operator.mul, iterable, start)
def yield_divisors(n):
"""Yields distinct divisors of n."""
elements = [[p**power for power in range(c + 1)] for p, c in collections.Counter(prime_factors(n)).items()]
return [mult(it) for it in itertools.product(*elements)]
```
``` |
220,614 | The most basic code(i guess so) to find all the factors of a number
Note:factors include 1 and the number itself
Here's the code:
```
c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
if x%i==0:
print("factor",c+1,":",i)
c=c+1
print("Total number of factors:",c)
```
Please make this code efficient.....ie: Help to reduce the number of iterations | 2019/05/21 | [
"https://codereview.stackexchange.com/questions/220614",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/200977/"
] | Just to have a more readable (than the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin)) and complete (than the [answer](https://codereview.stackexchange.com/a/220617/98493) by [@Sedsarq](https://codereview.stackexchange.com/users/201168/sedsarq)) version of the algorithm presented in the other answers, here is a version that keeps the factors in a `set` and uses the fact that factors always come in pairs:
```
from math import sqrt
def get_factors(n):
"""Returns a sorted list of all unique factors of `n`."""
factors = set()
for i in range(1, int(sqrt(n)) + 1):
if n % i == 0:
factors.update([i, n // i])
return sorted(factors)
```
Compared to your code this has the added advantage that it is encapsulated in a function, so you can call it repeatedly and give it a clear name and docstring describing what the function does.
It also follows Python's official style-guide, [PEP8](https://www.python.org/dev/peps/pep-0008/), which programmers are encouraged to follow.
With regards to which code is fastest, I'll let this graph speak for itself:
[](https://i.stack.imgur.com/aVney.png)
For the `op` function I used this code which has your checking of all factors up to `x`:
```
def op(x):
factors = []
for i in range(1,x+1):
if x%i==0:
factors.append(i)
return factors
```
And the `factors` function is from the [answer](https://codereview.stackexchange.com/a/220618/98493) by [@Justin](https://codereview.stackexchange.com/users/195671/justin).
---
If all you really want is the number of factors, the best way is probably to use the prime factor decomposition. For this you can use a list of primes together with the algorithm in the [answer](https://codereview.stackexchange.com/a/220727/98493) by [@Josay](https://codereview.stackexchange.com/users/9452/josay):
```
from math import sqrt
from functools import reduce
from operators import mul
def prime_sieve(limit):
prime = [True] * limit
prime[0] = prime[1] = False
for i, is_prime in enumerate(prime):
if is_prime:
yield i
for n in range(i * i, limit, i):
prime[n] = False
def prime_factors(n):
primes = prime_sieve(int(sqrt(n) + 1))
for p in primes:
c = 0
while n % p == 0:
n //= p
c += 1
if c > 0:
yield p, c
if n > 1:
yield n, 1
def prod(x):
return reduce(mul, x)
def number_of_factors(n)
return prod(c + 1 for _, c in prime_factors(n))
```
Comparing this with just taking the `len` of the output of the `get_factors` function and this function which implements your algorithm as `op_count`:
```
def len_get_factors(n):
return len(get_factors(n))
def op_count(n):
c = 0
for i in range(1, n + 1):
if n % i == 0:
c = c + 1
return c
```
The following timings result (note the increased range compared to the previous plot):
[](https://i.stack.imgur.com/YaTnu.png) | Since you say in a comment that you may need to find the divisors of a number \$n\$ up to \$10^{60}\$, trial division is not practical, even if performed only up to \$\sqrt n\$ . The only option is to find the prime factorisation and then reconstruct the divisors from the prime factorisation.
There are quite a few [algorithms to find the prime factorisation](https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms). For the size of numbers that interest you, the [quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve) is probably the best option.
Given the prime factorisation, reconstruction of the divisors is just a matter of taking some Cartesian products. Generating them in order is slightly trickier: I reproduce here some code which I wrote for an earlier answer to a similar question. It assumes that `primeFactors` gives output in the form `[(prime, power) ...]` in ascending order of primes.
```
import heapq
def divisors(n):
primes = [(1, 1)] + list(primeFactors(n))
q = [(1, 0, 1)]
while len(q) > 0:
# d is the divisor
# i is the index of its largest "prime" in primes
# a is the exponent of that "prime"
(d, i, a) = heapq.heappop(q)
yield d
if a < primes[i][1]:
heapq.heappush(q, (d * primes[i][0], i, a + 1))
if i + 1 < len(primes):
heapq.heappush(q, (d * primes[i + 1][0], i + 1, 1))
# The condition i > 0 is to avoid duplicates arising because
# d == d // primes[0][0]
if i > 0 and a == 1:
heapq.heappush(q, (d // primes[i][0] * primes[i + 1][0], i + 1, 1))
``` |
220,614 | The most basic code(i guess so) to find all the factors of a number
Note:factors include 1 and the number itself
Here's the code:
```
c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
if x%i==0:
print("factor",c+1,":",i)
c=c+1
print("Total number of factors:",c)
```
Please make this code efficient.....ie: Help to reduce the number of iterations | 2019/05/21 | [
"https://codereview.stackexchange.com/questions/220614",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/200977/"
] | All answers provided are great and offer suggestions with a complexity in `O(sqrt(n))` instead of the original `O(n)` by using the trick to stop at `sqrt(n)`.
On big inputs, we can go for an even faster solution by using the decomposition in prime numbers:
* the decomposition in prime numbers can be computed in a time proportional to the square root of the biggest prime divisor if its multiplicity is one (the actually complexity is actually a bit more tricky than this)
* the decomposition can be reused to generate all possible divisors (for each prime `p` with multiplicity `n`, you take `p ^ m` with `0 <= m <= n`.
I can provide the following piece of code for the first task but I do not have a snippet for the second task (yet?)
```
def prime_factors(n):
"""Yields prime factors of a positive number."""
assert n > 0
d = 2
while d * d <= n:
while n % d == 0:
n //= d
yield d
d += 1
if n > 1: # to avoid 1 as a factor
assert d <= n
yield n
```
Edit: I tried to implement the second step and got something which is not highly tested but seems to work:
```
def mult(iterable, start=1):
"""Returns the product of an iterable - like the sum builtin."""
return functools.reduce(operator.mul, iterable, start)
def yield_divisors(n):
"""Yields distinct divisors of n."""
elements = [[p**power for power in range(c + 1)] for p, c in collections.Counter(prime_factors(n)).items()]
return [mult(it) for it in itertools.product(*elements)]
```
``` | Since you say in a comment that you may need to find the divisors of a number \$n\$ up to \$10^{60}\$, trial division is not practical, even if performed only up to \$\sqrt n\$ . The only option is to find the prime factorisation and then reconstruct the divisors from the prime factorisation.
There are quite a few [algorithms to find the prime factorisation](https://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms). For the size of numbers that interest you, the [quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve) is probably the best option.
Given the prime factorisation, reconstruction of the divisors is just a matter of taking some Cartesian products. Generating them in order is slightly trickier: I reproduce here some code which I wrote for an earlier answer to a similar question. It assumes that `primeFactors` gives output in the form `[(prime, power) ...]` in ascending order of primes.
```
import heapq
def divisors(n):
primes = [(1, 1)] + list(primeFactors(n))
q = [(1, 0, 1)]
while len(q) > 0:
# d is the divisor
# i is the index of its largest "prime" in primes
# a is the exponent of that "prime"
(d, i, a) = heapq.heappop(q)
yield d
if a < primes[i][1]:
heapq.heappush(q, (d * primes[i][0], i, a + 1))
if i + 1 < len(primes):
heapq.heappush(q, (d * primes[i + 1][0], i + 1, 1))
# The condition i > 0 is to avoid duplicates arising because
# d == d // primes[0][0]
if i > 0 and a == 1:
heapq.heappush(q, (d // primes[i][0] * primes[i + 1][0], i + 1, 1))
``` |
41,463 | I have an arduino Uno and nodemcu development board.[](https://i.stack.imgur.com/vsM3q.jpg)
I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the [Instructables tutorial][2] named as FromComputerNerd.ino.
Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs [shown in][2]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.
But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?
<http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/> | 2017/07/10 | [
"https://arduino.stackexchange.com/questions/41463",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/35205/"
] | Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.
NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.
see : <https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library> | I am suggesting you to buy NodeMCU because it is having inbuilt WIFI, you can connect NodeMcu to internet without much effort compare to connecting UNO to internet, and the best thing is NodeMCU is arduino compatible you can do all possible stuff that can be done with UNO. We can also program NodeMCU in 'C' language using Arduino IDE directly
**Hardware comparison**
*NodeMCU*
1. 128KB RAM
2. 4MBytes ROM(flash)
3. micro USB port
4. Small Board Size
*Arduino UNO*
1. 2kB RAM
2. 32 KB ROM
3. USB type B connector
4. Bigger in size than NodeMCU
>
> Both are having nearly same prices.
>
>
> |
69,069,482 | I am getting time in this format like startTime="1:00 am" and endTime="12:00 pm" how can to check if endTime>startTime . I'm using react-timekeeper component | 2021/09/06 | [
"https://Stackoverflow.com/questions/69069482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15682271/"
] | Well you need to check the date somehow, if you want the date to be a part of the calculation.
There might be a nicer approach, but an easy one is to just loop the range and compare the date.
```
Sub Differences()
Dim vRng As Range, r As Variant, vDate As String
Set vRng = Range("B2", Range("B2").End(xlDown))
For Each r In vRng
If r.Offset(, -1) = vDate Then
r.Offset(, 3) = r - r.Offset(-1)
Else
r.Offset(, 3) = r
End If
vDate = r.Offset(, -1)
Next r
End Sub
``` | This gets the intended results. I am assuming that the first row with data is A1, if it's not then adjust accordingly.
```
Sub test()
Dim i As Long
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lastRow
If i = 1 Then
Cells(i, 5) = Cells(i, 2)
Else
If Cells(i, 1) = Cells(i - 1, 1) Then
Cells(i, 5) = Cells(i, 2) - Cells(i - 1, 2)
Else
Cells(i, 5) = Cells(i, 2)
End If
End If
Next i
End Sub
``` |
4,173,530 | What is the best way to validate a cost/price input by a user, validation rules below:
* Examples of formats allowed .23, .2, 1.23, 0.25, 5, 6.3 (maximum of two digits after decimal point)
* Minimum value of 0.01
* Maximum value of 9.99 | 2010/11/13 | [
"https://Stackoverflow.com/questions/4173530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489978/"
] | ### Check the price and verify the format
```
#rails 3
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}
#rails 2
validates_numericality_of :price, :greater_than => 0, :less_than => 10
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/
``` | For client side validations you can use a jQuery plugin like [this one](http://docs.jquery.com/Plugins/validation) that allows you to define different valid formats for a given input.
For server side validations and according to this [question/answer](https://stackoverflow.com/questions/1019939/ruby-on-rails-best-method-of-handling-currency-money) maybe you should use a `decimal` column for `price` in which you can define values for `precision` and `scale`, `scale` solves the two digits after decimal point restriction.
Then to validate the numericality, minimum and maximum value you can use the next validation method:
```
validates_numericality_of :price, :greater_than => 0, :less_than => 10
``` |
4,173,530 | What is the best way to validate a cost/price input by a user, validation rules below:
* Examples of formats allowed .23, .2, 1.23, 0.25, 5, 6.3 (maximum of two digits after decimal point)
* Minimum value of 0.01
* Maximum value of 9.99 | 2010/11/13 | [
"https://Stackoverflow.com/questions/4173530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489978/"
] | ### Check the price and verify the format
```
#rails 3
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}
#rails 2
validates_numericality_of :price, :greater_than => 0, :less_than => 10
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/
``` | You can build custom validations.Lets say, for example the second case:
```
validate :price_has_to_be_greater_than_minimum
def price_has_to_be_greater_than_minimum
errors.add(:price, "price has to be greater than 0.01") if
!price.blank? and price > 0.01
end
```
More on this, in the Rails Guides, [here](http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods). |
23,822 | I'd like to stay in the EU for some time, maybe get a residence permit if possible. The question is what are my healthcare options. As far as I know, citizens of EU countries can get public healthcare coverage. Can I get this by paying for it? Are there any alternatives for people with a residence permit yet without citizenship? Obviously, there's an option of travel insurance but I hope that for a longer stay there might be options with better or at least cheaper coverage. | 2022/01/31 | [
"https://expatriates.stackexchange.com/questions/23822",
"https://expatriates.stackexchange.com",
"https://expatriates.stackexchange.com/users/24573/"
] | That's not exactly the way it works, health insurance is typically based on residence or (mandatory) contributions. I have varying level of familiarity with the healthcare system in half-a-dozen EU countries and I do not know a single one that would offer free coverage to citizens *qua* citizens.
In some cases, living and working in a country would in fact provide you with (statutory) health insurance coverage. In others, having independent health insurance coverage is a requirement to get a residence permit in the first place. Citizenship, however seldom makes a huge difference (save for the fact you can always come back even in situation where you wouldn't qualify for a residence permit). | Yes - you can get on local health insurance in some countries in the EU. It is managed on a country-by-country basis. I know Switzerland, for one, would require foreign nationals who get residency to purchase a local health insurance plan (<https://www.bag.admin.ch/bag/en/home/versicherungen/krankenversicherung.html>). I believe Portugal and Spain are the same. So it might be worth picking a few countries and researching if they allow foreign nationals residing in those countries to move onto their local national plans. |
14,520 | When I am pedaling hard and shift to a larger sprocket, the shift is not smooth or sometimes doesn't happen at all. Sometimes even double up-shifts don't work. There is no problem shifting when I test for it without riding. What could be the issue? | 2013/02/18 | [
"https://bicycles.stackexchange.com/questions/14520",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/3925/"
] | On ground, after shifting, look at your bike from the back. The sprocket into which you have attempted to shift, and the pulley in the derailleur should be aligned. If the pulley is more to the right than sprocket, you need to get it aligned to the sprocket, by tightening in the screw on shifter or on the rear derailleur. As you tighten the screw, you should see pulley moving horizontally.
If that does not help, other problem might be that your chain hanger is bent, but that happens much less often, and typically after some crash or hard hit on the rear derailleur. If that is the case, taking your bike to LBS sounds like a good idea. | That is perfectly normal because when you are pedaling hard the chain is under tension and resists being moved by the derailleur. Before shifting to a higher gear slow your pedaling slightly. |
14,520 | When I am pedaling hard and shift to a larger sprocket, the shift is not smooth or sometimes doesn't happen at all. Sometimes even double up-shifts don't work. There is no problem shifting when I test for it without riding. What could be the issue? | 2013/02/18 | [
"https://bicycles.stackexchange.com/questions/14520",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/3925/"
] | After a lot of tinkering and research I found the derailleur was in the need of [indexing adjustment](http://sheldonbrown.com/derailer-adjustment.html). Just twisted the barrel adjuster anticlockwise a little and the gears are shifting promptly now. The above link advises that indexing adjustment is the most frequently required adjustment for rear derailleur. | That is perfectly normal because when you are pedaling hard the chain is under tension and resists being moved by the derailleur. Before shifting to a higher gear slow your pedaling slightly. |
316,749 | >
> It is now clear that no such creatures as vampires have been seen and none \_\_\_ in the world.
>
>
> A. was found
>
>
> B. have been found
>
>
>
I chose B, but the answer is A. I don't see the necessity to use the past tense here. Besides, allowing for that "have been seen" is already mentioned, I think it should follow some kind of rules of consistency. | 2022/06/06 | [
"https://ell.stackexchange.com/questions/316749",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/152414/"
] | "Creatures" is plural, so "was" cannot be used in the sentence. Therefore the answer is B. It means that no creatures such as vampires were found from the past all the way to the present. | There are two issues here: tense and number.
The preceding clause ("that no such creatures as vampires have been seen") is in the present perfect tense, and, as Kate Bunting notes in a comment, there does not seem to be any reason to use a different tense for the current clause. Therefore, answer choice B seems better.
The subject of the current clause ("[[that]] none \_\_\_ in the world") is the pronoun "none". Some people argue that "none" (being etymologically related to "one") can only be singular. In that case, only answer choice A could be correct. However, it is common for "none" to be either singular or plural. In that case, because its antecedent is "vampires" (or perhaps "such creatures as vampires"), it would be better construed as plural, so B would be better.
I'd recommend B. Whoever created the answers might be one of those people who insist that "none" must be singular. |
22,535,102 | This is my code:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNode root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("marketingid");
```
XML that works:
```
<confirmsubmit>
<marketingid>-1</marketingid>
</confirmsubmit>
```
XML that doesn't work:
```
<confirmsubmit xmlns="http:....">
<marketingid>-1</marketingid>
</confirmsubmit>
```
What is the way to deal with the xmlns attribute and how can i parse it?
Is it has anything to do with namespace?
**EDIT:**
This is the code that works:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
XmlNode book = xmlDoc.SelectSingleNode("/ns:confirmsubmit/ns:marketingid", nsmgr);
```
This all XPath is more complicated than seems, I would recommand to begginers like my to read: <http://www.w3schools.com/xpath/xpath_syntax.asp> | 2014/03/20 | [
"https://Stackoverflow.com/questions/22535102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338687/"
] | You need to add a XmlNamespaceManager instance in the game, as shown in this example from the [documentation](https://msdn.microsoft.com/en-us/library/4bektfx9(v=vs.110).aspx):
>
>
> ```
> public class Sample
> {
> public static void Main()
> {
>
> XmlDocument doc = new XmlDocument();
> doc.Load("booksort.xml");
>
> //Create an XmlNamespaceManager for resolving namespaces.
> XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
> nsmgr.AddNamespace("bk", "urn:samples");
>
> //Select and display the value of all the ISBN attributes.
> XmlNodeList nodeList;
> XmlElement root = doc.DocumentElement;
> nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);
> foreach (XmlNode isbn in nodeList){
> Console.WriteLine(isbn.Value);
> }
>
> }
> }
>
> ```
>
> | `xmlns` attribute is used at XHTML and defines namespace for a document. You can parse it like:
```
XDocument xdoc = XDocument.Load(xmlPath);
var attrib = xdoc.Root.Attribute("xmlns").Value;
``` |
22,535,102 | This is my code:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNode root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("marketingid");
```
XML that works:
```
<confirmsubmit>
<marketingid>-1</marketingid>
</confirmsubmit>
```
XML that doesn't work:
```
<confirmsubmit xmlns="http:....">
<marketingid>-1</marketingid>
</confirmsubmit>
```
What is the way to deal with the xmlns attribute and how can i parse it?
Is it has anything to do with namespace?
**EDIT:**
This is the code that works:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
XmlNode book = xmlDoc.SelectSingleNode("/ns:confirmsubmit/ns:marketingid", nsmgr);
```
This all XPath is more complicated than seems, I would recommand to begginers like my to read: <http://www.w3schools.com/xpath/xpath_syntax.asp> | 2014/03/20 | [
"https://Stackoverflow.com/questions/22535102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338687/"
] | Here is how to do it from LINQ to XML. Short and simple
```
const string xml = @"<confirmsubmit xmlns='http:....'>
<marketingid>-1</marketingid>
</confirmsubmit>";
XElement element = XElement.Parse(xml);
var requestedElement = element.Elements().FirstOrDefault(x => x.Name.LocalName.Equals("marketingid"));
``` | `xmlns` attribute is used at XHTML and defines namespace for a document. You can parse it like:
```
XDocument xdoc = XDocument.Load(xmlPath);
var attrib = xdoc.Root.Attribute("xmlns").Value;
``` |
22,535,102 | This is my code:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNode root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("marketingid");
```
XML that works:
```
<confirmsubmit>
<marketingid>-1</marketingid>
</confirmsubmit>
```
XML that doesn't work:
```
<confirmsubmit xmlns="http:....">
<marketingid>-1</marketingid>
</confirmsubmit>
```
What is the way to deal with the xmlns attribute and how can i parse it?
Is it has anything to do with namespace?
**EDIT:**
This is the code that works:
```
XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);
XmlNode book = xmlDoc.SelectSingleNode("/ns:confirmsubmit/ns:marketingid", nsmgr);
```
This all XPath is more complicated than seems, I would recommand to begginers like my to read: <http://www.w3schools.com/xpath/xpath_syntax.asp> | 2014/03/20 | [
"https://Stackoverflow.com/questions/22535102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338687/"
] | You need to add a XmlNamespaceManager instance in the game, as shown in this example from the [documentation](https://msdn.microsoft.com/en-us/library/4bektfx9(v=vs.110).aspx):
>
>
> ```
> public class Sample
> {
> public static void Main()
> {
>
> XmlDocument doc = new XmlDocument();
> doc.Load("booksort.xml");
>
> //Create an XmlNamespaceManager for resolving namespaces.
> XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
> nsmgr.AddNamespace("bk", "urn:samples");
>
> //Select and display the value of all the ISBN attributes.
> XmlNodeList nodeList;
> XmlElement root = doc.DocumentElement;
> nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);
> foreach (XmlNode isbn in nodeList){
> Console.WriteLine(isbn.Value);
> }
>
> }
> }
>
> ```
>
> | Here is how to do it from LINQ to XML. Short and simple
```
const string xml = @"<confirmsubmit xmlns='http:....'>
<marketingid>-1</marketingid>
</confirmsubmit>";
XElement element = XElement.Parse(xml);
var requestedElement = element.Elements().FirstOrDefault(x => x.Name.LocalName.Equals("marketingid"));
``` |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | The boost\_python lib inside /usr/local/lib/ is named after libboost\_python-mt.a and libboost\_python-mt.dylib, since the default compiling is w/ multi-threads supporting enabled.
Grep boost\_lib="boost\_python" under ELSE condition in setup.py and replace it w/ boost\_lib="boost\_python-mt", will fix the "not found" issue.
Also it's OK to ln "-mt" version to libboost\_python.a: as described [here](https://stackoverflow.com/questions/2293962/boost-libraries-in-multithreading-aware-mode) for linux boost which no longer appends '-mt' suffix since 1.42.
Ignore this line ~~or you could "with-boost-python=boost\_python-mt python setup.py install".
You could probably append '--with-boost-python=boost\_python-mt' to extra\_compile\_args inside setup.py, to achieve the same goal.~~
Furthermore, you could install pgmagick through pip in managed envs. Refs <http://rohanradio.com/blog/2011/12/02/installing-pgmagick-on-os-x/> | Does setting `DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib` in the environment help before the build
e.g
```
$ export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
``` |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | According to my own reproduction of this issue in brew 0.9 and OSX 10.6.8, the problem is `--with-thread-unsafe` isn't being honored by the current brew formula file. You can verify this by checking the formula with `brew edit boost` and seeing if the option appears within the contents of the formula.
Because of this, `libboost_python-mt.a` and `libboost_python-mt.dylib` are being built instead of `libboost_python.a` and `libboost_python.dylib`.
The easiest ways to fix this are to edit your pgmagick setup.py to replace `boost_lib="boost_python"` with `boost_lib="boost_python-mt"` (as pointed out [here](https://stackoverflow.com/a/9868631/517815)) or to follow [the instructions and patch here](https://github.com/mxcl/homebrew/pull/8928). It's otherwise a known issue. | Does setting `DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib` in the environment help before the build
e.g
```
$ export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
``` |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | Note that as of July 2014 the boost Python library is a separate homebrew package called `boost-python`.
```
5254f8f510fb30484f8fac8be3d38e388a4392e2
Author: Tim D. Smith <[email protected]>
Date: Sat Jul 19 15:37:25 2014 -0700
Split out Boost.Python
```
You need to install it separately to get the `libboost_python` shared library. | Does setting `DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib` in the environment help before the build
e.g
```
$ export DYLD_FALLBACK_LIBRARY_PATH=/usr/local/lib
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
``` |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | According to my own reproduction of this issue in brew 0.9 and OSX 10.6.8, the problem is `--with-thread-unsafe` isn't being honored by the current brew formula file. You can verify this by checking the formula with `brew edit boost` and seeing if the option appears within the contents of the formula.
Because of this, `libboost_python-mt.a` and `libboost_python-mt.dylib` are being built instead of `libboost_python.a` and `libboost_python.dylib`.
The easiest ways to fix this are to edit your pgmagick setup.py to replace `boost_lib="boost_python"` with `boost_lib="boost_python-mt"` (as pointed out [here](https://stackoverflow.com/a/9868631/517815)) or to follow [the instructions and patch here](https://github.com/mxcl/homebrew/pull/8928). It's otherwise a known issue. | The boost\_python lib inside /usr/local/lib/ is named after libboost\_python-mt.a and libboost\_python-mt.dylib, since the default compiling is w/ multi-threads supporting enabled.
Grep boost\_lib="boost\_python" under ELSE condition in setup.py and replace it w/ boost\_lib="boost\_python-mt", will fix the "not found" issue.
Also it's OK to ln "-mt" version to libboost\_python.a: as described [here](https://stackoverflow.com/questions/2293962/boost-libraries-in-multithreading-aware-mode) for linux boost which no longer appends '-mt' suffix since 1.42.
Ignore this line ~~or you could "with-boost-python=boost\_python-mt python setup.py install".
You could probably append '--with-boost-python=boost\_python-mt' to extra\_compile\_args inside setup.py, to achieve the same goal.~~
Furthermore, you could install pgmagick through pip in managed envs. Refs <http://rohanradio.com/blog/2011/12/02/installing-pgmagick-on-os-x/> |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | The boost\_python lib inside /usr/local/lib/ is named after libboost\_python-mt.a and libboost\_python-mt.dylib, since the default compiling is w/ multi-threads supporting enabled.
Grep boost\_lib="boost\_python" under ELSE condition in setup.py and replace it w/ boost\_lib="boost\_python-mt", will fix the "not found" issue.
Also it's OK to ln "-mt" version to libboost\_python.a: as described [here](https://stackoverflow.com/questions/2293962/boost-libraries-in-multithreading-aware-mode) for linux boost which no longer appends '-mt' suffix since 1.42.
Ignore this line ~~or you could "with-boost-python=boost\_python-mt python setup.py install".
You could probably append '--with-boost-python=boost\_python-mt' to extra\_compile\_args inside setup.py, to achieve the same goal.~~
Furthermore, you could install pgmagick through pip in managed envs. Refs <http://rohanradio.com/blog/2011/12/02/installing-pgmagick-on-os-x/> | I've [submitted a pull request](https://github.com/mxcl/homebrew/pull/19722) to homebrew to build Boost with both mt and non mt (threaded and thread unsafe) binaries which are required to build pgmagick.
Turns out this is a rather common problem, until the patch is accepted, you can check out or use my formula for Boost to build pgmagick. |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | According to my own reproduction of this issue in brew 0.9 and OSX 10.6.8, the problem is `--with-thread-unsafe` isn't being honored by the current brew formula file. You can verify this by checking the formula with `brew edit boost` and seeing if the option appears within the contents of the formula.
Because of this, `libboost_python-mt.a` and `libboost_python-mt.dylib` are being built instead of `libboost_python.a` and `libboost_python.dylib`.
The easiest ways to fix this are to edit your pgmagick setup.py to replace `boost_lib="boost_python"` with `boost_lib="boost_python-mt"` (as pointed out [here](https://stackoverflow.com/a/9868631/517815)) or to follow [the instructions and patch here](https://github.com/mxcl/homebrew/pull/8928). It's otherwise a known issue. | I've [submitted a pull request](https://github.com/mxcl/homebrew/pull/19722) to homebrew to build Boost with both mt and non mt (threaded and thread unsafe) binaries which are required to build pgmagick.
Turns out this is a rather common problem, until the patch is accepted, you can check out or use my formula for Boost to build pgmagick. |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | According to my own reproduction of this issue in brew 0.9 and OSX 10.6.8, the problem is `--with-thread-unsafe` isn't being honored by the current brew formula file. You can verify this by checking the formula with `brew edit boost` and seeing if the option appears within the contents of the formula.
Because of this, `libboost_python-mt.a` and `libboost_python-mt.dylib` are being built instead of `libboost_python.a` and `libboost_python.dylib`.
The easiest ways to fix this are to edit your pgmagick setup.py to replace `boost_lib="boost_python"` with `boost_lib="boost_python-mt"` (as pointed out [here](https://stackoverflow.com/a/9868631/517815)) or to follow [the instructions and patch here](https://github.com/mxcl/homebrew/pull/8928). It's otherwise a known issue. | Note that as of July 2014 the boost Python library is a separate homebrew package called `boost-python`.
```
5254f8f510fb30484f8fac8be3d38e388a4392e2
Author: Tim D. Smith <[email protected]>
Date: Sat Jul 19 15:37:25 2014 -0700
Split out Boost.Python
```
You need to install it separately to get the `libboost_python` shared library. |
9,786,515 | I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1.
I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew):
```
$ brew install graphicsmagick --with-magick-plus-plus
$ brew install imagemagick --with-magick-plus-plus
$ brew install boost --with-thread-unsafe
```
then I'm cloning the repo at <https://bitbucket.org/hhatto/pgmagick>:
```
$ hg clone https://bitbucket.org/hhatto/pgmagick/src
$ cd pgmagick
$ python setup.py build
```
However I always receive the following error:
```
ld: library not found for -lboost_python
collect2: ld returned 1 exit status
```
Based on the output on stdout, setup *is* looking in the right place for the boost (`/usr/local/lib`).
I've also tried `easy_install` and `pip` but with no luck. I'm using Pythonbrew but have also disabled this and tried using the stock python install -- still no success.
Any suggestions on how I can fix the problem, or further diagnose the issue? | 2012/03/20 | [
"https://Stackoverflow.com/questions/9786515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | Note that as of July 2014 the boost Python library is a separate homebrew package called `boost-python`.
```
5254f8f510fb30484f8fac8be3d38e388a4392e2
Author: Tim D. Smith <[email protected]>
Date: Sat Jul 19 15:37:25 2014 -0700
Split out Boost.Python
```
You need to install it separately to get the `libboost_python` shared library. | I've [submitted a pull request](https://github.com/mxcl/homebrew/pull/19722) to homebrew to build Boost with both mt and non mt (threaded and thread unsafe) binaries which are required to build pgmagick.
Turns out this is a rather common problem, until the patch is accepted, you can check out or use my formula for Boost to build pgmagick. |
17,506,647 | In my custom Wordpress theme I am trying to animate all my table "nodes" in as the page loads simultaneously.
I can get this animation to work by applying the animation to each element individually but since trying to automate this process the animation fades all my nodes in at the same time and I do not understand why.
The below code generates my nodes...
```
<div class="span12 news-tiles-container">
<div class="row span12 news-tiles-inner">
<?php
$node_id = 1;
$node_size_id = 1;
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
if($node_size_id > 3) {
$node_size_id = 1;
}
?>
<a href='<?php the_permalink(); ?>'>
<div class='node node<?php echo $node_id ?> size<?php echo $node_size_id ?>'
style='background-image: url(<?php the_field( 'thumbnail' ); ?>);'>
<div id="news-caption" class="span12">
<p class="span9"><?php the_title(); ?></p>
<img class="more-arrow" src="<?php bloginfo('template_directory'); ?>/images/more-arrow.png" alt="Enraged Entertainment logo"/>
</div>
</div>
</a>
<?php
$node_size_id++;
$node_id++;
?>
<?php endwhile; endif; ?>
</div>
</div>
```
And I am using the following code to control there animate in
```
$(document).ready(function(){
// Hide all of the nodes
$('.node').hide(0);
// Local Variables
var node_id = 1;
var nodes = 10;
var i = 0;
while(i <= nodes)
{
$('.node'+node_id).hide(0).delay(500).fadeIn(1000);
node_id+=1;
nodes--;
} });
```
I assume it is something to do with my while loop, but the node counter increments successfully so it should be applying the animation to node1 then node2 then node3 and so on.
Thanks in advance
Alex. | 2013/07/06 | [
"https://Stackoverflow.com/questions/17506647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020154/"
] | Use your brandy dandy `.fadeQueue()`: [working jsFiddle](http://jsfiddle.net/rARAW/)
```
$.fn.fadeQueue = function(){
$(this).fadeIn(function(){
if(!$(this).is(':last-child')) // making sure we are not done
$(this).next().fadeQueue();
});
}
```
This will wait for the callback of `.fadeIn()` for each div before moving to the next one.. | Probably not as elegant, but still works:
```
$(document).ready(function(){
$('.node').hide();
$('.node').each(function(index,elem){
setTimeout(function(){$(elem).fadeIn(1000);},1000*index);
});
});
```
[jsFiddle here](http://jsfiddle.net/nxjg2/) |
17,506,647 | In my custom Wordpress theme I am trying to animate all my table "nodes" in as the page loads simultaneously.
I can get this animation to work by applying the animation to each element individually but since trying to automate this process the animation fades all my nodes in at the same time and I do not understand why.
The below code generates my nodes...
```
<div class="span12 news-tiles-container">
<div class="row span12 news-tiles-inner">
<?php
$node_id = 1;
$node_size_id = 1;
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
if($node_size_id > 3) {
$node_size_id = 1;
}
?>
<a href='<?php the_permalink(); ?>'>
<div class='node node<?php echo $node_id ?> size<?php echo $node_size_id ?>'
style='background-image: url(<?php the_field( 'thumbnail' ); ?>);'>
<div id="news-caption" class="span12">
<p class="span9"><?php the_title(); ?></p>
<img class="more-arrow" src="<?php bloginfo('template_directory'); ?>/images/more-arrow.png" alt="Enraged Entertainment logo"/>
</div>
</div>
</a>
<?php
$node_size_id++;
$node_id++;
?>
<?php endwhile; endif; ?>
</div>
</div>
```
And I am using the following code to control there animate in
```
$(document).ready(function(){
// Hide all of the nodes
$('.node').hide(0);
// Local Variables
var node_id = 1;
var nodes = 10;
var i = 0;
while(i <= nodes)
{
$('.node'+node_id).hide(0).delay(500).fadeIn(1000);
node_id+=1;
nodes--;
} });
```
I assume it is something to do with my while loop, but the node counter increments successfully so it should be applying the animation to node1 then node2 then node3 and so on.
Thanks in advance
Alex. | 2013/07/06 | [
"https://Stackoverflow.com/questions/17506647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020154/"
] | Here's a generic plugin that will perform any animation you want, in sequence, on a jQuery collection of elements:
```
(function ($) {
$.fn.queueEach = function (func) {
var args = [].slice.call(arguments, 1); // array of remaining args
var els = this.get(); // copy of elements
(function loop() {
var el = els.shift();
if (el) {
$.fn[func].apply($(el), args).promise().done(loop);
}
})();
return this;
}
})(jQuery);
```
Usage:
```
$('.node').queueEach('fadeIn', 'slow');
```
Working demo at <http://jsfiddle.net/alnitak/D39Cw/> | Probably not as elegant, but still works:
```
$(document).ready(function(){
$('.node').hide();
$('.node').each(function(index,elem){
setTimeout(function(){$(elem).fadeIn(1000);},1000*index);
});
});
```
[jsFiddle here](http://jsfiddle.net/nxjg2/) |
51,512 | For some months, I'm renting an apartment in the Canary Islands. It looks like the plugs are not grounded. For example, when I connect my laptop, a ThinkPad T420si, then I feel an unpleasant sensation on my bare legs when connected to mains ([220V/50Hz](http://de.wikipedia.org/wiki/L%C3%A4nder%C3%BCbersicht_Steckertypen,_Netzspannungen_und_-frequenzen#L.C3.A4nderliste)). A similar sensation I get when touching certain parts, incl. plastic parts (!), of my smartphone when connected to the laptop. *Contrary to what I wrote before:* When connected to the USB charger, I do *not* get that sensation when touching the smartphone.
My guess is that the outlets are not properly grounded. While I assume there is no risk for my health, I am a bit worried about my electronic devices. Also, I may want to do some electronics soldering, and I don't like the idea of the soldering iron's tip possibly being on a different potential than ground.
*What options do I have to remedy the problem? An isolating transformer?*
Update as of 2014-10-15 WEST
============================
After removing the Schuko ([fype F](http://www.iec.ch/worldplugs/typeF.htm)) multiplier, and upon close inspection of the outlet, I realized that the center hole is *not* a screw hole. It is ground, i.e. this outlet is of [type L](http://www.iec.ch/worldplugs/typeL.htm). So I bought an adapter, and yesterday the problem was gone:

Facepalm!
But wait, today the problem is back, and in the entire apartment! For the first time, I felt a potential when touching the washing machine in the bathroom, and this one is connected with a Schuko plug to a Schuko outlet:

Something is wrong here. Probably unrelated: Some days ago there was a power outage, I think affecting several houses, i.e. not just the one I'm living in. | 2014/10/12 | [
"https://diy.stackexchange.com/questions/51512",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/27184/"
] | This is not about grounding, or perhaps it is...
Lets start with your connectors: Do you have AC-connectors at your devices with or without grounding pin? Laptop psu may have a protective earth connection, a phone charger won't have one. I've never seen a phone charger with protective earth connection.
Both PSUs are doubly insulated, I'm pretty sure, which means primary side is galvanically separated from secondary side, which includes everything which can be touched with bare hands.
How does this sensation of 50 Hz AC come over to touchable parts? There's something calle Y-Capacitor between primary and secondary side in these PSUs. It is used to provides a stable potential for the regulating circuitry of the PSU, i.e. it prevents the secondary side from "floating". It can be described by two small capacitors in series between neutral lead and live lead on primary side with the middle node connected to the ground of the secondary side. Hence, on a 230V system, the secondary side gets a level of 115 V AC. The capacitor is designed to permit a maximum current of 0,35 mA to flow, if shorted to ground. This is a current you can sense, but which cannot harm you or your equipment.
If something with earthing in your mansion was wrong, it would not change this effect in my opinion.
In the rare case, your PSUs really have a protective earth connector you should not be able to sense that voltage as it was conducted away. In this rare case you should get an electrician soon, because if you touch your oven or washing machine there is no such limiting capacitor to protect you in case of an failure.
I have a different theory why you feel somthing you do not know at home. On canary islands it is rather warm and carpets are rare while most homes have tiled floor. If you live somewhere cold the rest of the year you probably have carpets or wooden floor which reduce capacitive coupling by orders of magnitude. You just may not feel the phenomenon while it is there, too.
Update
------
Relating to your updates: **Now you do have a problem.**
When you feel a tickling sensation when touching devices like a washing machine there is one possible conclusion: the potential of protective earth connected with the housing of your devices differs from the potential of your house. Which can mean different things.
* You have only 2-wire conduits in your house. The neutral and protective earth in your wall outlets are connected to one common wire (usually blue in EU). Some connections in your house have too high ohmic resistance. When under heavy load, voltage on N **and** PE rises, hence you can feel the influenced voltage.
* Protective Earth is somewhere broken, effectively. This is **really** bad, as all Class 1 equipment relies on working PE and a short to housing, which especially water bearing devices are prone to, will put the full voltage to touchable parts of the defective devices.
* And if PE is interrupted at the equipotential bus bar it gets even worse. Not only a faulty potential from one defective device will propagate through your complete building and be present on every Schuko (PE contact), but will also be induced by assymetric load in the 3-phase-network between the next transformer station and your house. Which means, even if all devices in your house are depowered properly, PE-conductors may conduct harmful voltages.
For the last two options, your life is at risk. You should get an electrician to prove me wrong. The first possibility can be verified by opening a wall outlet (of course after opening the circuit breaker, securing it against reconnecting, verifying all pins in the outlet are deenergised and so on). If there are two wires only and one of them connects to N and PE you have a “bootleg ground”, which renders even ground fault interruptors partially useless. | Steps to go through:
1. Turn off the power to an outlet that is causing you problems. (Fusebox/main switch)
2. Check the exterior of the outlet for presence of a metal grounding element/grounding pin/whatever you have over there.
3. Open the outlet, check to see if there's proper wiring: all three pins connected.
4. Close the outlet.
If the answer in 3 was: yup, all's well, next:
1. Connect a multimeter to the ground of one outlet, connect the other side to another outlet somewhere else in a wall (not the same box, of course).
2. Set the multimeter to "resistance" or "continuity" (the setting that beeps) and verify that the resistance is very low. (very very).
If the answer to that is: yup, low resistance:
1. Verify that the power to the outlet is still safely turned off.
2. Set the multimeter to voltage AC (high, at least 250VAC should be possible).
3. Connect one terminal to Groung, the other to one outlet power wire (phase or neutral)
4. Turn on the power to the outlet.
5. Check the multimeter without touching. Measurement One
6. Turn off the power to the outlet again
7. Get the terminal from the power carrying wire and put it in the other, leaving the other terminal connected to ground.
8. Turn on the power again.
9. Check the multimeter without touching. Measurement Two.
10. Turn off power.
11. Remove the multimeter from the outlet.
12. Turn on power.
Now, if one measurement says "230VAC" or close to it and the other says "0VAC" or something very close (no more than 1 or 2VAC), it's very likely the power ground is properly connected. It's no guarantee, but without being there myself I'm not getting any immediate other inspiration to do further verification.
If any of the earlier steps failed, obviously something is not right. |
53,520,080 | I need to encrypt user names that i receive from an external partners SSO. This needs to be done because the user names are assigned to school children. But we still need to be able to track each individual to prevent abuse of our systems, so we have decided to encrypt the user names in our logs etc.
This way, a breach of our systems will not compromise the identity of the children.
Heres my predicament. I have very limited knowledge in this area, so i am looking for advice on which algorithm to use.
I was thinking of using an asymmetrical algorithm, like PGP, and throwing away one of the keys so that we will not be able to decrypt the user name.
My questions:
* Does PGP encryption always provide the same output given the same input?
* Is PGP a good choice for this, or should we use an other algorithm?
* Does anyone have a better suggestion for achieving the same thing - anonymization of the user | 2018/11/28 | [
"https://Stackoverflow.com/questions/53520080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4149494/"
] | If you want a one-way function, you don't want encryption. You want hashing. The easiest thing to do is to use a hash like SHA-256. I recommend salting the username before hashing. In this case, I would probably pick a static salt like `edu.myschoolname:` and put that in front of the username. Then run that through SHA-256. Convert the result to Base-64 or hex encoding, and use the resulting string as the "username."
From a unix command line, this would look like:
```
$ echo -n "edu.myschoolname:[email protected]" | shasum -a 256
09356cf6df6aea20717a346668a1aad986966b192ff2d54244802ecc78f964e3 -
```
That output is unique to that input string (technically it's not "unique" but you will never find a collision, by accident or by searching). And that output is stable, in that it will always be the same for the given input. (I believe that PGP includes some randomization; if it doesn't, it should.)
---
(Regarding comments below)
Cryptographic hash algorithms are extremely secure for their purposes. Non-cryptographic hash algorithms are not secure (but also aren't meant to be). There are no major attacks I know of against SHA-2 (which includes SHA-256 and SHA-512).
You're correct that your system needs to be robust against someone with access to the code. If they know what userid they're looking for, however, no system will be resistant to them discovering the masked version of that id. If you encrypt, an attacker with access to the key can just encrypt the value themselves to figure out what it is.
But if you're protecting against the reverse: preventing attackers from determining the id when they do not already know the id they're looking for, the correct solution is a cryptographic hash, specifically SHA-256 or SHA-512. Using PGP to create a one-way function is using a cryptographic primitive for something it is not built to do, and that's always a mistake. If you want a one-way function, you want a hash. | I think that PGP is a good Idea, but risk to make usernames hard to memorize, why not simply make a list of usernames composed with `user + OrderedNumbers` where user can be wichever word you want and oredered number is a 4-5 digit number ordered by birth date of childrens?
Once you have done this you only have to keep a list where the usernames are linked wit the corresponding child abd then you can encript this "nice to have" list with a key only you know. |
206,136 | We know that a cat is able to endure, continue, or survive despite a near encounter with death or disaster because cats have nine lives (according to a common myth).
>
> Example:
> - Mr. Pickles has been missing for a few days, but I wouldn't worry about him. **He is a cat with nine lives.**
>
>
>
>
Does my bold self-made sentence work properly and idiomatically here? | 2019/04/19 | [
"https://ell.stackexchange.com/questions/206136",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/5652/"
] | It is in the past tense. This is a "[future in the past](https://www.englishpage.com/verbpage/futureinpast.html)" construction. The question is rhetorical. Leonard isn't looking for an answer, but he phrases his statement as a question. Changing it back to a statement gives:
>
> I told you I would be working nights.
>
>
>
So in the past Leonard said "I will be working nights". In the past Leonard used a future tense. When he reports this the tense of "will" is changed to the past tense. The past tense of "will" is "would".
This construction is quite rare, it is most likely to appear in reported speech, thoughts or emotions
>
> I knew it would be fun.
>
>
>
Leonard could have used a "going to" for the future with little or no change in meaning.
>
> Didn't I tell you I was going to be working nights?
>
>
> | It's not "would be doing", it's "would be sth".
`Working nights` is a idiom means the shift of working at night.
"Would" indicates that all the "L telling S about working nights thing" happened in the past, not this morning, it might be yesterday. |
3,028,475 | I'm having the following tables:
Table a
| Field | Type | Null | Key |
| --- | --- | --- | --- |
| bid | int(10) unsigned | YES | |
| cid | int(10) unsigned | YES | |
Table b
| Field | Type | Null |
| --- | --- | --- |
| bid | int(10) unsigned | NO |
| cid | int(10) unsigned | NO |
| data | int(10) unsigned | NO |
When I want to select all rows from b where there's a corresponding bid/cid-pair in a, I simply use a natural join `SELECT b.* FROM b NATURAL JOIN a;` and everything is fine.
When `a.bid` or `a.cid` is `NULL`, I want to get every row where the other column matches, *e.g.* if `a.bid` is `NULL`, I want every row where `a.cid = b.cid`, if both are `NULL` I want every column from `b`.
My naive solution was this:
```
SELECT DISTINCT b.*
FROM b
JOIN a ON (ISNULL(a.bid) OR a.bid=b.bid ) AND (ISNULL(a.cid) OR a.cid=b.cid)
```
Is there any better way to to this? | 2010/06/12 | [
"https://Stackoverflow.com/questions/3028475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73299/"
] | No, that's pretty much it.
(I'd generally rephrase `ISNULL(a.bind)` as `a.bind IS NULL` for ANSI SQL compliance FWIW.) | Too old, but here is my 2 cents, it might be useful for someone:
```
ISNULL(a.cid, 0) = ISNULL(b.cid) AND ISNULL(a.bid, 0) = ISNULL(b.bid)
``` |
3,028,475 | I'm having the following tables:
Table a
| Field | Type | Null | Key |
| --- | --- | --- | --- |
| bid | int(10) unsigned | YES | |
| cid | int(10) unsigned | YES | |
Table b
| Field | Type | Null |
| --- | --- | --- |
| bid | int(10) unsigned | NO |
| cid | int(10) unsigned | NO |
| data | int(10) unsigned | NO |
When I want to select all rows from b where there's a corresponding bid/cid-pair in a, I simply use a natural join `SELECT b.* FROM b NATURAL JOIN a;` and everything is fine.
When `a.bid` or `a.cid` is `NULL`, I want to get every row where the other column matches, *e.g.* if `a.bid` is `NULL`, I want every row where `a.cid = b.cid`, if both are `NULL` I want every column from `b`.
My naive solution was this:
```
SELECT DISTINCT b.*
FROM b
JOIN a ON (ISNULL(a.bid) OR a.bid=b.bid ) AND (ISNULL(a.cid) OR a.cid=b.cid)
```
Is there any better way to to this? | 2010/06/12 | [
"https://Stackoverflow.com/questions/3028475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73299/"
] | The ISNULL function is not actually ANSI compliant. Yes, you do need to check for nulls in both columns. Another way to write your query would be:
```
Select Distinct b.*
From b
Join a
On ( a.bid = b.bid Or ( a.bid Is Null And b.bid Is Null ) )
And ( a.cid = b.cid Or ( a.cid Is Null And b.cid Is Null ) )
```
Yet another way that avoids the use of Distinct:
```
Select b.*
From b
Where Exists (
Select 1
From a
Where ( a.bid = b.bid Or ( a.bid Is Null And b.bid Is Null ) )
And ( a.cid = b.cid Or ( a.cid Is Null And b.cid Is Null ) )
)
``` | Too old, but here is my 2 cents, it might be useful for someone:
```
ISNULL(a.cid, 0) = ISNULL(b.cid) AND ISNULL(a.bid, 0) = ISNULL(b.bid)
``` |
627,683 | I've figured out that extracting a `.zip` you need the path to the directory as well when you are recursively looking through subdirectories. So how do you store the path?
This is nearly there but doesn't work properly when there is a space in the `{zip_file}`.
```
zip_dir=$PWD/$(basename "${zip_file}")
``` | 2015/05/24 | [
"https://askubuntu.com/questions/627683",
"https://askubuntu.com",
"https://askubuntu.com/users/323574/"
] | I created this from your other question as well. It took me a bit, but this is what I was able to come up with to create the folders based on the zip file name, removing the `.zip` from the folder name, then extracting the zip file into that folder.
```
#!/bin/bash
echo "Start folder create..."
find . -type f -iname "*.zip" | while read filename
do
filename1=${filename:2}
foldername=$PWD/"${filename1%.*}"
mkdir -p "$foldername"
unzip "$filename" -d "$foldername"
echo "Created directory $foldername and extracted files to it."
done
```
The line `filename1=${filename:2}` strips off the `./` of the name. | Edit: I must not have tested this correctly.
Generally you don't need quotes when doing a variable assignment, just when dereferencing a variable. When making an assignment you don't need to put quotes around a variable being dereferenced, but since the dereferencing happens in a sub shell, quotes are needed around the `${zip_file}` part so that it's value is properly passed to basename. Quotes are *NOT* in fact needed around the entire line, because then it's back in the context of variable assignment, where quotes aren't needed as bash will do the right thing with passing the value from the subshell to the assignment line.
Thanks @janos for pointing this out. I'm not sure what I screwed up in testing the original line that took me down the path of excessive quotes. You are correct, the following is fine:
```
zip_dir=$PWD/$(basename "${zip_file}")
``` |
60,583,052 | I was trying to test my code with fixed time. so I wrote something like this:
```rust
use std::time::{SystemTime, UNIX_EPOCH};
trait Clock {
fn now(&self) -> SystemTime;
}
trait MixInClock {
type Impl;
}
struct RealClock;
impl<T: MixInClock<Impl = RealClock>> Clock for T {
fn now(&self) -> SystemTime {
SystemTime::now()
}
}
struct FakeClock;
impl <T: MixInClock<Impl = FakeClock>> Clock for T {
fn now(&self) -> SystemTime {
UNIX_EPOCH
}
}
struct DIContainer;
impl MixInClock for DIContainer {
type Impl = FakeClock;
}
```
This code gives me an error:
```
error[E0119]: conflicting implementations of trait `Clock`:
--> src/lib.rs:19:1
|
12 | impl<T: MixInClock<Impl = RealClock>> Clock for T {
| ------------------------------------------------- first implementation here
...
19 | impl <T: MixInClock<Impl = FakeClock>> Clock for T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation
```
Why? There's no possibility that `T` implements `MixInClock<Impl = RealClock>` and `MixInClock<Impl = FakeClock>` at same time. right?
<https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=95e3647b30ae0e37c45ac18da495a3c5> | 2020/03/07 | [
"https://Stackoverflow.com/questions/60583052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13025505/"
] | You ran into a [long-standing issue with Rust's coherence rules](https://github.com/rust-lang/rust/issues/20400). There are proposals how to resolve this, but the work has been postponed for now. Quoting [Jonas Schievink's most recent comment on the bug](https://github.com/rust-lang/rust/issues/20400#issuecomment-493206721):
>
> To give an update on this: In 2016, [RFC 1672](https://github.com/rust-lang/rfcs/pull/1672) was proposed to fix this, but was postponed until the Chalk integration is done. Additionally, according to [rust-lang/rfcs#1672 (comment)](https://github.com/rust-lang/rfcs/pull/1672#issuecomment-262152934), allowing these kinds of impls would allow users to express mutually exclusive traits, which is a very powerful feature that needs more in-depth consideration by the language team (hence marking as blocked on an RFC as well).
>
>
> | While Sven's answer is correct, that this is an issue with Rust's coherence rules, you can solve this problem by just generalizing your code a bit. In praticular, when you have two different types that should have different behavior but a similar interface, it's often useful to create a trait for that.
In this case, you could create a trait for `RealClock` and `FakeClock` that each can implement, and use that in your generic `Clock` implementation instead of adding the behavior of each directly:
```rust
// Common interface for RealClock and FakeClock, implemented separated for each
trait ClockImpl {
fn now() -> SystemTime;
}
impl ClockImpl for RealClock {
fn now() -> SystemTime {
SystemTime::now()
}
}
impl ClockImpl for FakeClock {
fn now() -> SystemTime {
UNIX_EPOCH
}
}
// MixInClock only needs to now that Self::Impl implements ClockImpl
trait MixInClock {
type Impl: ClockImpl;
}
// We call the T::Impl::now() method for the specific behavior of RealClock and FakeClock
impl<T: MixInClock> Clock for T {
fn now(&self) -> SystemTime {
<T::Impl as ClockImpl>::now()
}
}
```
[Code in playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4e58436d7585b60c10257522304d2d93) |
22,393,605 | how to get text from json without [" "] only text ,in android project
this is my json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
i need get text "text":["Better late than never"] without [" "] only text: Better late than never
myclass MAINACTIVITY
```
public class MainActivity extends Activity {
JSONParser jsonparser = new JSONParser();
TextView tv;
String ab;
JSONObject jobj = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
new retrievedata().execute();
}
class retrievedata extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
jobj = jsonparser.makeHttpRequest("https://translate.yandex.net/api/v1.5/tr.json/translate?key=YOURAPIKEY&text=Better%20late%20than%20never&lang=ru");
// check your log for json response
Log.d("Login attempt", jobj.toString());
ab = jobj.optString("text");
return ab;
}
protected void onPostExecute(String ab){
tv.setText(ab);
}
}
}
```
MY JSONPARSER CLASS
```
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
}
``` | 2014/03/14 | [
"https://Stackoverflow.com/questions/22393605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3413314/"
] | To uninstall the version of Typescript used by Visual Studio, use "add/remove programs" in Windows and remove "TypeScript for Visual Studio". It's installed as a program rather than an extension for VS (and as you've noticed, it doesn't use the NodeJs version). | The visual studio version of TypeScript does *not* depend on nodejs. It uses IE for compilation.
You can uninstall the nodejs version using `npm uninstall -g typescript` if you installed it previously (which you probably didn't).
And then simply install TS from : <http://www.microsoft.com/en-us/download/details.aspx?id=34790> |
20,710 | After around 15 minutes of playing Battlefield: Bad Company 2, my computer completely locks up with the game's image on screen and the last second of sound constantly looping. I have to hard restart the machine to get it to come back.
I'm not sure if this issue is isolated to BF:BC2 but it's the only game I've been playing recently. I've tried leaving a Source Engine game running and it didn't crash for the hour it was open so I'm guessing it's just because BF:BC2 is a more intensive game on the system.
Could this be a temperature issue? I've previously played BF:BC2 on the same computer during the summer (it's winter here now) without any issues so I'm guessing this is unlikely. Perhaps faulty RAM or another component?
My specs are:
* Intel Core 2 Duo E7200
* 4GB RAM
* NVIDIA GeForce 9600 GT
* Windows 7 Professional 64-bit
These are my temperatures when in Windows - are they bad?

I can try and get a picture of them while I've got a game running if that would help. | 2011/04/23 | [
"https://gaming.stackexchange.com/questions/20710",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/-1/"
] | Your temps are mostly fine, maybe the CPU is a bit hot, if these are idle temperatures.
Seems like it's the RAM or the CPU.
GPU faults don't act up like that.
So, you setup an isolated stress test for each suspect.
**RAM:**
Download memtest86+ and install it on a medium and boot your system with it. I'd suggest USB key:
<http://www.memtest.org/#downiso>
If it passes the tests, move on to CPU.
If it doesn't, find and remove the faulty RAM stick and repeat the test.
**CPU**:
Download prime95 and run it, no need to reboot:
<http://www.mersenne.org/>
It might also be that your CPU is running too hot. In that case, open your case (warranty is lost, if any) and clean the dust off from the heat sink and the fans, if any. See if the temperatures drop. If not, the heat sink might have come loose, or has not enough contact to the CPU die. You might want to re-apply the heat conducting fluid. | Here's the way that I would recommend you troubleshoot this:
1. Unplug all USB devices, with the exception of keyboard and mouse.
2. Update the video driver.
3. Update Windows via Windows update.
4. If all of the above fail, remove all the extra hardware that you aren't using from the computer (i.e. extra sound cards, modems, etc..)
Good luck. |
20,710 | After around 15 minutes of playing Battlefield: Bad Company 2, my computer completely locks up with the game's image on screen and the last second of sound constantly looping. I have to hard restart the machine to get it to come back.
I'm not sure if this issue is isolated to BF:BC2 but it's the only game I've been playing recently. I've tried leaving a Source Engine game running and it didn't crash for the hour it was open so I'm guessing it's just because BF:BC2 is a more intensive game on the system.
Could this be a temperature issue? I've previously played BF:BC2 on the same computer during the summer (it's winter here now) without any issues so I'm guessing this is unlikely. Perhaps faulty RAM or another component?
My specs are:
* Intel Core 2 Duo E7200
* 4GB RAM
* NVIDIA GeForce 9600 GT
* Windows 7 Professional 64-bit
These are my temperatures when in Windows - are they bad?

I can try and get a picture of them while I've got a game running if that would help. | 2011/04/23 | [
"https://gaming.stackexchange.com/questions/20710",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/-1/"
] | Your temps are mostly fine, maybe the CPU is a bit hot, if these are idle temperatures.
Seems like it's the RAM or the CPU.
GPU faults don't act up like that.
So, you setup an isolated stress test for each suspect.
**RAM:**
Download memtest86+ and install it on a medium and boot your system with it. I'd suggest USB key:
<http://www.memtest.org/#downiso>
If it passes the tests, move on to CPU.
If it doesn't, find and remove the faulty RAM stick and repeat the test.
**CPU**:
Download prime95 and run it, no need to reboot:
<http://www.mersenne.org/>
It might also be that your CPU is running too hot. In that case, open your case (warranty is lost, if any) and clean the dust off from the heat sink and the fans, if any. See if the temperatures drop. If not, the heat sink might have come loose, or has not enough contact to the CPU die. You might want to re-apply the heat conducting fluid. | I had this issue and resolved it by disabling my motherboards onboard realetek sound and fitting a pci soundcard (Creative Labs).
Hope this helps |
72,534,839 | I am struggling to update the interpolation of `thing`.
This simple function should change the value of the data but instead does nothing.
Chrome logs the change of thing in the console but the HTML does not update.
```
<template>
<div class="container-xl pb-5">
<button class="mb-2 btn-lg selected-dropdown" @click="dropSelect('B')">
{{ thing }}
</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
data() {
return {
thing: "A",
};
},
methods: {
dropSelect(thing: any) {
console.log(thing);
return this.thing;
},
},
});
</script>
``` | 2022/06/07 | [
"https://Stackoverflow.com/questions/72534839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939661/"
] | Since the function `getData` is `async`, it's a `Future` and you can't use a future methods inside your tree widget directly
you can use it inside your widget tree using the widget `FutureBuilder`
```
FutureBuilder(
future: getData(),
builder: (context, snapshot){
if (!snapshot.hasData) return const SizedBox();
return Text(snapshot.data?.toString() ?? '');
}
```
also, you have to modify your method to make it return something,
Ex.:
```
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
print(user?.displayName);
return user?.displayName;
}
```
---
**UPDATE:**
to access all the info you want from the `User` object, let your method return the whole object;
```
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
print(user?.displayName);
return user;
}
```
and your `FutureBuilder` will be
```
FutureBuilder(
future: getData(),
builder: (context, snapshot){
if (!snapshot.hasData) return const SizedBox();
if (snapshot.data == null) return const Text('Current user is null');
return Column(
children: [
Text('Name: ${snapshot.data?.displayName}'),
Text('Email: ${snapshot.data?.email}'),
///Add any attribute you want to show..
]
);
}
``` | ```
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
if(user!=null){
print(user.displayName);
print(user.email);}
}
```
this will wait for an async method to first complete then print |
78,579 | In one of my projects my requirement is to insert/add more than 15000 records/entries at one og in a custom list.
After searching some of the blogs i found some useful information about adding bulk entries in custom list.I tried to add by the batch files, i called processbatchdata method for bulk entries.
Referred link : <http://www.arboundy.com/code/sharepoint/bulk-add-new-items-to-a-sharepoint-list-using-processbatchdata/>
However i ended up with the performance issue,its taking more than 2 minutes for adding 5000 entries.
Can anyone help me on this issue.
Many Thanks. | 2013/10/01 | [
"https://sharepoint.stackexchange.com/questions/78579",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/19863/"
] | If you are complaining about 2 minutes being slow for 5k items, presumably this isn't a one time import - you may consider looking at [Business Connectivity Services](http://msdn.microsoft.com/en-us/library/ff798319.aspx) to connect directly to your external data source. | Is this a frequent step or just a one time task?
If it's frequent, I recommend NOT doing this in SharePoint! Sorry, I don't have a good answer. I would revisit the requirements and look at farming this high amount of data into another SQL database and use BCS to connect and manage the data.
I strongly oppose high amounts of data in SP, especially if this is a frequent task... Check out BCS |
25,653,399 | On one controller, I have a function that handles a drill down that sets that record's information on another controller's config variables.
It seems to set them fine the from first controller. When it switches to the other controller, it says those variables are undefined. What is going on?
Controller handling drill down:
```
// Set site name for Site Summary
MyApp.app.getController('otherController').setSiteId(siteId);
MyApp.app.getController('otherController').setSiteName(siteName);
console.log(MyApp.app.getController('otherController').getSiteId());
console.log(MyApp.app.getController('otherController').getSiteName());
// Prints out the correct values that are supposed to be set
```
Other controller where the values aren't sticking:
```
Ext.define('MyApp.controller.otherController', {
extend: 'Ext.app.Controller',
config: {
siteId: -1,
siteName: ''
},
init: function() {
this.listen( {
component: {
'somePnl': {
beforerender: this.onBeforeRender
},
// stuff
onBeforeRender: function() {
console.log("this.siteName = " + this.siteName);
console.log("this.siteId = " + this.siteId);
},
// Prints out 'undefined'
}
```
I can't seem to figure out why the setting of those variables aren't sticking | 2014/09/03 | [
"https://Stackoverflow.com/questions/25653399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2115016/"
] | ExtJS recommends using generated setter and getter for configs. The direct access is not documented.
Doc: <http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.Class-cfg-config>
So using
```
console.log("this.siteName = " + this.getSiteName());
console.log("this.siteId = " + this.getSiteId());
```
is best practice and should do the job. | Apparently having the underscore seems to be working...
```
console.log("this.siteName = " + this._siteName);
console.log("this.siteId = " + this._siteId);
``` |
23,794,483 | I'm just starting coding in Django and I have code that repeat itself on a lot of pages.
for example:
```
<select name="seasons" id="season-id">
{% for season in seasons %}
{% if season_id|add:0 == season.id %}
<option value="{{ season.id }}" selected="selected">{{ season.name }}</option>
{% else %}
<option value="{{ season.id }}">{{ season.name }}</option>
{% endif %}
{% endfor %}
</select>
```
In previous language I could use view helpers to make it more DRY. How can I accomplish this in Django. | 2014/05/21 | [
"https://Stackoverflow.com/questions/23794483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490570/"
] | Extract the code into a separate template file and [`include`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include) it instead of repeating:
```
{% include "seasons.html" %}
```
FYI, you can also specify that you want to pass only `seasons` variable into the context of included template:
```
{% include "seasons.html" with seasons=seasons only %}
``` | Depends on what is repeating.
1. You can nest templates. Probably not useful here.
2. You can write your own template tags and template filters. [further info](http://www.pfinn.net/custom-django-filter-tutorial.html) |
23,794,483 | I'm just starting coding in Django and I have code that repeat itself on a lot of pages.
for example:
```
<select name="seasons" id="season-id">
{% for season in seasons %}
{% if season_id|add:0 == season.id %}
<option value="{{ season.id }}" selected="selected">{{ season.name }}</option>
{% else %}
<option value="{{ season.id }}">{{ season.name }}</option>
{% endif %}
{% endfor %}
</select>
```
In previous language I could use view helpers to make it more DRY. How can I accomplish this in Django. | 2014/05/21 | [
"https://Stackoverflow.com/questions/23794483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490570/"
] | Extract the code into a separate template file and [`include`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include) it instead of repeating:
```
{% include "seasons.html" %}
```
FYI, you can also specify that you want to pass only `seasons` variable into the context of included template:
```
{% include "seasons.html" with seasons=seasons only %}
``` | You shouldn't be writing this template code at all. You should define a Django form and let that output the field. |
23,794,483 | I'm just starting coding in Django and I have code that repeat itself on a lot of pages.
for example:
```
<select name="seasons" id="season-id">
{% for season in seasons %}
{% if season_id|add:0 == season.id %}
<option value="{{ season.id }}" selected="selected">{{ season.name }}</option>
{% else %}
<option value="{{ season.id }}">{{ season.name }}</option>
{% endif %}
{% endfor %}
</select>
```
In previous language I could use view helpers to make it more DRY. How can I accomplish this in Django. | 2014/05/21 | [
"https://Stackoverflow.com/questions/23794483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490570/"
] | Depends on what is repeating.
1. You can nest templates. Probably not useful here.
2. You can write your own template tags and template filters. [further info](http://www.pfinn.net/custom-django-filter-tutorial.html) | You shouldn't be writing this template code at all. You should define a Django form and let that output the field. |
2,676,057 | Feel free to close and/or redirect if this has been asked, but here's my situation:
I've got an application that will require doing a bunch of small units of work (polling a web service until something is done, then parsing about 1MB worth of XML and putting it in a database). I want to have a simple async queueing mechanism that'll poll for work to do in a queue, execute the units of work that need to be done, and have the flexibility to allow for spawning multiple worker processes so these units of work can be done in parallel. (Bonus if there's some kind of event framework that would also me to listen for when work is complete.)
I'm sure there is stuff to do this. Am I describing Twisted? I poked through the documentation, I'm just not sure exactly how my problems maps onto their framework, but I haven't spent much time with it. Should I just look at the multiprocess libraries in Python? Something else? | 2010/04/20 | [
"https://Stackoverflow.com/questions/2676057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] | There's [celery](http://ask.github.com/celery/getting-started/introduction.html).
You could break it down into 2 different `Tasks`: one to poll the web service and queue the second task, which would be in charge of parsing the XML and persisting it. | This problem sounds like a pretty good candidate for Python's built-in (2.6+ anyway) multiprocessing module: <http://docs.python.org/library/multiprocessing.html>
A simple solution would be to create a process Pool and use your main program to poll for the XML chunks. Once it has them it can then pass them off to the pool for parsing/persisting. |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | ```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.addAll(list2);
Collections.sort(list1);
}
``` | If your input Lists aren't too long, I'd suggest just merging the lists and using the `Collections.sort()` Method to restore the order:
```
public static void mergeAndSort(List<Integer> list1, List<Integer> list2) {
List<Integer> combinedList = new ArrayList<Integer>(list1);
combinedList.addAll(list2);
Collections.sort(combinedList);
return combinedList;
}
```
As a sidenote, you should use the `List` interface instead of the `ArrayList` implementation class wherever possible. |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | After you merge the lists, call sort method as below.
```
Collections.sort(list1); // carries out natural ordering.
```
If you need a customized sorting, use Comparator object
```
Collections.sort(list1, comparatorObject);
```
Check [Comparator example](http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/) for more details.
Here is your modified code:
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.add(list2); //merges list 2 to list1
Collections.sort(list1); //natural ordering
}
``` | ```
ArrayList<Integer> a = new ArrayList();
ArrayList<Integer> b = new ArrayList();
ArrayList<Integer> c = new ArrayList();
a.add(1);
a.add(3);
a.add(5);
a.add(7);
a.add(17);
a.add(27);
a.add(37);
b.add(0);
b.add(2);
b.add(4);
while( a.size() > 0 || b.size() >0){
if( a.size() == 0 || b.size() == 0){
c.addAll(b);
c.addAll(a);
break;
}
if(a.get(0) < b.get(0)){
c.add(a.get(0));
a.remove(0);
}
else{
c.add(b.get(0));
b.remove(0);
}
}
System.out.println(c.toString());
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | ```
public list mergeAndSort(List<integer> list1, List<integer> list2){
List<integer> list3;
int list2Size = list2.size();
for(int i=0;i<list2Size;i++){
list1.add(list2(i));
}
// Here we got all the elements in 1 list i.e list1
int list1Size = list1.size();
for(i=0;i<list1Size;i++){
int small = 0;
for(int j=i;j<list1size;j++){
if(list1(i)> list2(j)){
small = list2(j;
}
}
list3.add(small); //Smallest 1 will be added to the new list
}
```
} | ```
ArrayList<Integer> a = new ArrayList();
ArrayList<Integer> b = new ArrayList();
ArrayList<Integer> c = new ArrayList();
a.add(1);
a.add(3);
a.add(5);
a.add(7);
a.add(17);
a.add(27);
a.add(37);
b.add(0);
b.add(2);
b.add(4);
while( a.size() > 0 || b.size() >0){
if( a.size() == 0 || b.size() == 0){
c.addAll(b);
c.addAll(a);
break;
}
if(a.get(0) < b.get(0)){
c.add(a.get(0));
a.remove(0);
}
else{
c.add(b.get(0));
b.remove(0);
}
}
System.out.println(c.toString());
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | ```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.addAll(list2);
Collections.sort(list1);
}
``` | After you merge the lists, call sort method as below.
```
Collections.sort(list1); // carries out natural ordering.
```
If you need a customized sorting, use Comparator object
```
Collections.sort(list1, comparatorObject);
```
Check [Comparator example](http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/) for more details.
Here is your modified code:
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.add(list2); //merges list 2 to list1
Collections.sort(list1); //natural ordering
}
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | ```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.addAll(list2);
Collections.sort(list1);
}
``` | ```
public list mergeAndSort(List<integer> list1, List<integer> list2){
List<integer> list3;
int list2Size = list2.size();
for(int i=0;i<list2Size;i++){
list1.add(list2(i));
}
// Here we got all the elements in 1 list i.e list1
int list1Size = list1.size();
for(i=0;i<list1Size;i++){
int small = 0;
for(int j=i;j<list1size;j++){
if(list1(i)> list2(j)){
small = list2(j;
}
}
list3.add(small); //Smallest 1 will be added to the new list
}
```
} |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | You only need one `for` loop assuming both lists are sorted:
```
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index1 = 0, index2 = 0; index2 < l2.size(); index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2++));
}
}
}
```
If `l2` isn't sorted, you need two loops:
```
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index2 = 0; index2 < l2.size(); index2++) {
for (int index1 = 0; ; index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2));
break;
}
}
}
}
``` | After you merge the lists, call sort method as below.
```
Collections.sort(list1); // carries out natural ordering.
```
If you need a customized sorting, use Comparator object
```
Collections.sort(list1, comparatorObject);
```
Check [Comparator example](http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/) for more details.
Here is your modified code:
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.add(list2); //merges list 2 to list1
Collections.sort(list1); //natural ordering
}
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | You only need one `for` loop assuming both lists are sorted:
```
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index1 = 0, index2 = 0; index2 < l2.size(); index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2++));
}
}
}
```
If `l2` isn't sorted, you need two loops:
```
public static void merge(List<Integer> l1, List<Integer> l2) {
for (int index2 = 0; index2 < l2.size(); index2++) {
for (int index1 = 0; ; index1++) {
if (index1 == l1.size() || l1.get(index1) > l2.get(index2)) {
l1.add(index1, l2.get(index2));
break;
}
}
}
}
``` | ```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.addAll(list2);
Collections.sort(list1);
}
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | Easy fix: sort afterwards.
```
list1.addAll(list2);
Collections.sort(list1);
```
Use sets to avoid duplicates. | After you merge the lists, call sort method as below.
```
Collections.sort(list1); // carries out natural ordering.
```
If you need a customized sorting, use Comparator object
```
Collections.sort(list1, comparatorObject);
```
Check [Comparator example](http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/) for more details.
Here is your modified code:
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
list1.add(list2); //merges list 2 to list1
Collections.sort(list1); //natural ordering
}
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | If your input Lists aren't too long, I'd suggest just merging the lists and using the `Collections.sort()` Method to restore the order:
```
public static void mergeAndSort(List<Integer> list1, List<Integer> list2) {
List<Integer> combinedList = new ArrayList<Integer>(list1);
combinedList.addAll(list2);
Collections.sort(combinedList);
return combinedList;
}
```
As a sidenote, you should use the `List` interface instead of the `ArrayList` implementation class wherever possible. | ```
ArrayList<Integer> a = new ArrayList();
ArrayList<Integer> b = new ArrayList();
ArrayList<Integer> c = new ArrayList();
a.add(1);
a.add(3);
a.add(5);
a.add(7);
a.add(17);
a.add(27);
a.add(37);
b.add(0);
b.add(2);
b.add(4);
while( a.size() > 0 || b.size() >0){
if( a.size() == 0 || b.size() == 0){
c.addAll(b);
c.addAll(a);
break;
}
if(a.get(0) < b.get(0)){
c.add(a.get(0));
a.remove(0);
}
else{
c.add(b.get(0));
b.remove(0);
}
}
System.out.println(c.toString());
``` |
13,069,605 | In my assignment the third step is to Call the method merge to merge the two lists in list1 so that the list1 **remains sorted.**
I write my code but it doesn't work well , the output show wrong because it important to be sorted
```
public static void merge (ArrayList<Integer> list1, ArrayList<Integer> list2)
{
int i;
int n=list1.size();
int pos , j=0;
for (pos =0 ;pos<n ; pos++)
{
for ( i=0 ; i<n ; i++)
if (list1.get(j)>list2.get(pos))
list1.add(pos,list2.get(pos));
else
j++;
}
}
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13069605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772461/"
] | Easy fix: sort afterwards.
```
list1.addAll(list2);
Collections.sort(list1);
```
Use sets to avoid duplicates. | ```
ArrayList<Integer> a = new ArrayList();
ArrayList<Integer> b = new ArrayList();
ArrayList<Integer> c = new ArrayList();
a.add(1);
a.add(3);
a.add(5);
a.add(7);
a.add(17);
a.add(27);
a.add(37);
b.add(0);
b.add(2);
b.add(4);
while( a.size() > 0 || b.size() >0){
if( a.size() == 0 || b.size() == 0){
c.addAll(b);
c.addAll(a);
break;
}
if(a.get(0) < b.get(0)){
c.add(a.get(0));
a.remove(0);
}
else{
c.add(b.get(0));
b.remove(0);
}
}
System.out.println(c.toString());
``` |
7,242,226 | What is the fastest way to get a list of all members/users in a given AD group and determine whether or not a user is enabled (or disabled)?
We are potentially talking about 20K users, so I would like to avoid hitting the AD for each individual user. | 2011/08/30 | [
"https://Stackoverflow.com/questions/7242226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154991/"
] | If you're on .NET 3.5 and up, you should check out the `System.DirectoryServices.AccountManagement` (S.DS.AM) namespace. Read all about it here:
* [Managing Directory Security Principals in the .NET Framework 3.5](http://msdn.microsoft.com/en-us/magazine/cc135979.aspx)
* [MSDN docs on System.DirectoryServices.AccountManagement](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx)
Basically, you can define a domain context and easily find users and/or groups in AD:
```
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
UserPrincipal theUser = p as UserPrincipal;
if(theUser != null)
{
if(theUser.IsAccountLockedOut())
{
...
}
else
{
...
}
}
}
}
```
The new S.DS.AM makes it really easy to play around with users and groups in AD! | Please can you try the following code. it use [Search Filter Syntax](http://msdn.microsoft.com/en-us/library/aa746475%28v=vs.85%29.aspx) to get what you want in one LDAP query and recursively. The interest is that the query is done on the server. I'am not sure that it faster than @marc\_s solution but it exists, and it works on framework .NET 2.0 (begining W2K3 SP2).
```
string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr";
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "test.2011");
/* To find all the users member of groups "Grp1" :
* Set the base to the groups container DN; for example root DN (dc=societe,dc=fr)
* Set the scope to subtree
* Use the following filter :
* (member:1.2.840.113556.1.4.1941:=CN=Grp1,OU=MonOu,DC=X)
* coupled with LDAP_MATCHING_RULE_BIT_AND on userAccountControl with ACCOUNTDISABLE
*/
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
dsLookFor.Filter = "(&(memberof:1.2.840.113556.1.4.1941:=CN=MonGrpSec,OU=MonOu,DC=dom,DC=fr)(userAccountControl:1.2.840.113556.1.4.803:=2))";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");
SearchResultCollection srcUsers = dsLookFor.FindAll();
/* Just to know if user is present in an other group
*/
foreach (SearchResult srcUser in srcUsers)
{
Console.WriteLine("{0}", srcUser.Path);
}
``` |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | I had this situation recently. It was so embarrassing when the saleslady told her co-workers about what I said.
I asked her to give me one half kilo (1/2 kilo) of prawns and 3 pieces of fish. She ended up giving me one and one half kilo of prawns. When she asked for the payments and I asked the amount, i freaked out. I was not expecting that she actually gave me 1 1/2 kilo of prawns.
I told her I asked for one half not one and one half kilo. She got angry and her co-workers started to laugh. They were all telling me I was wrong. They said it's half not one half.
In my understanding, "one half" and "half" are both correct it depends on how you use it with other supporting words. | You don't need the 'one' in expressions like 'give me half a cookie'. Where you do need the 'one' is in when units of measurement are involved, like "please give me one half pound of sugar". You can use 'a' instead of 'one', but leaving out any determiner is wrong.
Correct:
>
> Give me one half pound of sugar.
>
> Give me a half pound of sugar.
>
> Give me half a pound of sugar.
>
>
>
Wrong:
>
> \*Give me half pound of sugar.
>
> \*Give me one half a pound of sugar.
>
> ?Give me a half a pound of sugar.
>
>
>
(You do hear the last quite a bit in the U.S., although not in England; this came up in [another question](https://english.stackexchange.com/questions/43294/a-half-a-cup-of-something) here.) |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | It is perfectly acceptable to say "give me half of that". In English, "half" in understood on its own to mean "[one of two equal parts of something](http://www.merriam-webster.com/dictionary/half "Half - Definition, Merriam-Webster Dictionary\"")".
To put it another way:
* It would make no sense to say "give me no halves of that". You would just say "give me none of that".
* It would make no sense to say "give me two halves of that". You would just say "give me all of that".
Saying "give me one half of that" is redundant. It's equivalent to saying "give me one of one of those two equal parts of that." | You don't need the 'one' in expressions like 'give me half a cookie'. Where you do need the 'one' is in when units of measurement are involved, like "please give me one half pound of sugar". You can use 'a' instead of 'one', but leaving out any determiner is wrong.
Correct:
>
> Give me one half pound of sugar.
>
> Give me a half pound of sugar.
>
> Give me half a pound of sugar.
>
>
>
Wrong:
>
> \*Give me half pound of sugar.
>
> \*Give me one half a pound of sugar.
>
> ?Give me a half a pound of sugar.
>
>
>
(You do hear the last quite a bit in the U.S., although not in England; this came up in [another question](https://english.stackexchange.com/questions/43294/a-half-a-cup-of-something) here.) |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | *Comment posted as answer - as requested*
In idiomatic usage, you would seldom say 'one half of this'. You might say 'give me one half-pound pack of sugar' but the hyphen shows that it is a different construct. You might say 'give me one third of that' (as opposed to 'two thirds of that'), but with halves, the alternatives are none and all. However, even with thirds, it would be more usual to say 'a third' than 'one third'. So, whoever 'corrected' you was actually misleading you. | If you are discussing arithmetic, it is always correct to stipulate a numerator and a denominator. "Give me half an apple" is fine, but "what is half plus a third?" is incorrect and should be "what is one-half plus one-third?" |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | It is perfectly acceptable to say "give me half of that". In English, "half" in understood on its own to mean "[one of two equal parts of something](http://www.merriam-webster.com/dictionary/half "Half - Definition, Merriam-Webster Dictionary\"")".
To put it another way:
* It would make no sense to say "give me no halves of that". You would just say "give me none of that".
* It would make no sense to say "give me two halves of that". You would just say "give me all of that".
Saying "give me one half of that" is redundant. It's equivalent to saying "give me one of one of those two equal parts of that." | *Comment posted as answer - as requested*
In idiomatic usage, you would seldom say 'one half of this'. You might say 'give me one half-pound pack of sugar' but the hyphen shows that it is a different construct. You might say 'give me one third of that' (as opposed to 'two thirds of that'), but with halves, the alternatives are none and all. However, even with thirds, it would be more usual to say 'a third' than 'one third'. So, whoever 'corrected' you was actually misleading you. |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | *Comment posted as answer - as requested*
In idiomatic usage, you would seldom say 'one half of this'. You might say 'give me one half-pound pack of sugar' but the hyphen shows that it is a different construct. You might say 'give me one third of that' (as opposed to 'two thirds of that'), but with halves, the alternatives are none and all. However, even with thirds, it would be more usual to say 'a third' than 'one third'. So, whoever 'corrected' you was actually misleading you. | You don't need the 'one' in expressions like 'give me half a cookie'. Where you do need the 'one' is in when units of measurement are involved, like "please give me one half pound of sugar". You can use 'a' instead of 'one', but leaving out any determiner is wrong.
Correct:
>
> Give me one half pound of sugar.
>
> Give me a half pound of sugar.
>
> Give me half a pound of sugar.
>
>
>
Wrong:
>
> \*Give me half pound of sugar.
>
> \*Give me one half a pound of sugar.
>
> ?Give me a half a pound of sugar.
>
>
>
(You do hear the last quite a bit in the U.S., although not in England; this came up in [another question](https://english.stackexchange.com/questions/43294/a-half-a-cup-of-something) here.) |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | There is no need to say "one half" there. "Give me half of that" is sufficient. | You don't need the 'one' in expressions like 'give me half a cookie'. Where you do need the 'one' is in when units of measurement are involved, like "please give me one half pound of sugar". You can use 'a' instead of 'one', but leaving out any determiner is wrong.
Correct:
>
> Give me one half pound of sugar.
>
> Give me a half pound of sugar.
>
> Give me half a pound of sugar.
>
>
>
Wrong:
>
> \*Give me half pound of sugar.
>
> \*Give me one half a pound of sugar.
>
> ?Give me a half a pound of sugar.
>
>
>
(You do hear the last quite a bit in the U.S., although not in England; this came up in [another question](https://english.stackexchange.com/questions/43294/a-half-a-cup-of-something) here.) |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | I had this situation recently. It was so embarrassing when the saleslady told her co-workers about what I said.
I asked her to give me one half kilo (1/2 kilo) of prawns and 3 pieces of fish. She ended up giving me one and one half kilo of prawns. When she asked for the payments and I asked the amount, i freaked out. I was not expecting that she actually gave me 1 1/2 kilo of prawns.
I told her I asked for one half not one and one half kilo. She got angry and her co-workers started to laugh. They were all telling me I was wrong. They said it's half not one half.
In my understanding, "one half" and "half" are both correct it depends on how you use it with other supporting words. | If you are discussing arithmetic, it is always correct to stipulate a numerator and a denominator. "Give me half an apple" is fine, but "what is half plus a third?" is incorrect and should be "what is one-half plus one-third?" |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | There is no need to say "one half" there. "Give me half of that" is sufficient. | If you are discussing arithmetic, it is always correct to stipulate a numerator and a denominator. "Give me half an apple" is fine, but "what is half plus a third?" is incorrect and should be "what is one-half plus one-third?" |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | There is no need to say "one half" there. "Give me half of that" is sufficient. | I had this situation recently. It was so embarrassing when the saleslady told her co-workers about what I said.
I asked her to give me one half kilo (1/2 kilo) of prawns and 3 pieces of fish. She ended up giving me one and one half kilo of prawns. When she asked for the payments and I asked the amount, i freaked out. I was not expecting that she actually gave me 1 1/2 kilo of prawns.
I told her I asked for one half not one and one half kilo. She got angry and her co-workers started to laugh. They were all telling me I was wrong. They said it's half not one half.
In my understanding, "one half" and "half" are both correct it depends on how you use it with other supporting words. |
9,874 | I can't remember when and where I had this discussion, but I remember being corrected when I was speaking by a stranger saying that it is never correct to say *give me half of this*; instead, the grammatically correct phrase would be *give me one half of this*. I've never been a pro at where numbers fit in with the English language, so maybe someone here could shed some light on this. | 2011/01/25 | [
"https://english.stackexchange.com/questions/9874",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/4064/"
] | It is perfectly acceptable to say "give me half of that". In English, "half" in understood on its own to mean "[one of two equal parts of something](http://www.merriam-webster.com/dictionary/half "Half - Definition, Merriam-Webster Dictionary\"")".
To put it another way:
* It would make no sense to say "give me no halves of that". You would just say "give me none of that".
* It would make no sense to say "give me two halves of that". You would just say "give me all of that".
Saying "give me one half of that" is redundant. It's equivalent to saying "give me one of one of those two equal parts of that." | If you are discussing arithmetic, it is always correct to stipulate a numerator and a denominator. "Give me half an apple" is fine, but "what is half plus a third?" is incorrect and should be "what is one-half plus one-third?" |
32,082,233 | I have a dataframe with missing values. How can I write either a python or an R code to replace empty spaces with 0, a single string with 1, and multiple strings joined by "\t" with a number corresponding to how many "\t"s + 1.
my data frame:
```
col1 col2 col3
row1 5blue 2green5 white
row2 white green\twhite3\t3blue5
row3 blue3 white
row4 7blue green2
row5 3green 3white6
row6 6blue green\t6white7 green
row7 5blue5 6green white
row8 blue6
```
Output expected:
```
col1 col2 col3
row1 1 1 1
row2 0 1 3
row3 1 0 1
row4 1 1 0
row5 0 1 1
row6 1 2 1
row7 1 1 1
row8 1 0 0
```
Any ideas? Thanks | 2015/08/18 | [
"https://Stackoverflow.com/questions/32082233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2597415/"
] | [Parsing Tab Delimited](https://stackoverflow.com/questions/11059390/parsing-a-tab-separated-file-in-python)
Read this post above. It covers using python csv module to parse tab delimited. I think it will help you.
**Input File data\_frame.txt**
```
5blue 2green5 white
white green\twhite3\t3blue5
blue3 white
7blue green2
3green 3white6
6blue green\t6white7 green
5blue5 6green white
```
The code below
```
import csv
data_frame = open('data_frame.txt','r') ## create input file for dataframe
output_matrix = [] ## output matrix
reader = csv.reader(data_frame, dialect="excel-tab") ## Setup tab delimter file
for line in reader: ## Read each line in the data frame
out_line = [] ## Setup temp out-line var
for item in line:
if item == '': ## If item in line is null then put zero
out_line.append(0)
elif r"""\t""" in item: ## if item in line contains a "\t" character then put count + 1
out_line.append(item.count(r"""\t""")+1)
else: ## Else item is 1
out_line.append(1)
output_matrix.append(out_line) ## Append line into output matrix
for line in output_matrix:
print line ## Print output matrix
```
This code should work... you just have to output the output\_matrix to a csv file.
**Output**
```
[1, 1, 1]
[0, 1, 3]
[1, 0, 1]
[1, 1, 0]
[0, 1, 1]
[1, 2, 1]
[1, 1, 1]
``` | Use the `yourstring.count("\t")` function to get the number of tabs, add 1 to the value to get the number of words. If string is empty, output 0. |
32,082,233 | I have a dataframe with missing values. How can I write either a python or an R code to replace empty spaces with 0, a single string with 1, and multiple strings joined by "\t" with a number corresponding to how many "\t"s + 1.
my data frame:
```
col1 col2 col3
row1 5blue 2green5 white
row2 white green\twhite3\t3blue5
row3 blue3 white
row4 7blue green2
row5 3green 3white6
row6 6blue green\t6white7 green
row7 5blue5 6green white
row8 blue6
```
Output expected:
```
col1 col2 col3
row1 1 1 1
row2 0 1 3
row3 1 0 1
row4 1 1 0
row5 0 1 1
row6 1 2 1
row7 1 1 1
row8 1 0 0
```
Any ideas? Thanks | 2015/08/18 | [
"https://Stackoverflow.com/questions/32082233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2597415/"
] | I'm using a function that goes to each column element and checks if the element is a space (You can change that depending on what you have. It looks likes a space to me) and returns 0 if it is, otherwise it splits the string by "\t" and counts the strings that are produced.
```
# example dataset
dt = data.frame(col1 = c("green\twhite3\t3blue5","green"),
col2 = c(" ", "green\twhite3"), stringsAsFactors = F)
dt
# col1 col2
# 1 green\twhite3\t3blue5
# 2 green green\twhite3
ff = function(x)
{
res = vector() # create an empty vector to store counts for each element
for (i in 1:length(x)){ # iterate through each element
res[i] = ifelse(x[i]==" ", 0, length(unlist(strsplit(x[i],"\t")))) # if the element is space return 0, else split string by \t and count new strings
}
return(res) # return the stored values
}
data.frame(sapply(dt, function(x) ff(x))) # apply the function to all columns and save it as a data.frame
# col1 col2
# 1 3 0
# 2 1 2
``` | Use the `yourstring.count("\t")` function to get the number of tabs, add 1 to the value to get the number of words. If string is empty, output 0. |
32,082,233 | I have a dataframe with missing values. How can I write either a python or an R code to replace empty spaces with 0, a single string with 1, and multiple strings joined by "\t" with a number corresponding to how many "\t"s + 1.
my data frame:
```
col1 col2 col3
row1 5blue 2green5 white
row2 white green\twhite3\t3blue5
row3 blue3 white
row4 7blue green2
row5 3green 3white6
row6 6blue green\t6white7 green
row7 5blue5 6green white
row8 blue6
```
Output expected:
```
col1 col2 col3
row1 1 1 1
row2 0 1 3
row3 1 0 1
row4 1 1 0
row5 0 1 1
row6 1 2 1
row7 1 1 1
row8 1 0 0
```
Any ideas? Thanks | 2015/08/18 | [
"https://Stackoverflow.com/questions/32082233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2597415/"
] | I'm using a function that goes to each column element and checks if the element is a space (You can change that depending on what you have. It looks likes a space to me) and returns 0 if it is, otherwise it splits the string by "\t" and counts the strings that are produced.
```
# example dataset
dt = data.frame(col1 = c("green\twhite3\t3blue5","green"),
col2 = c(" ", "green\twhite3"), stringsAsFactors = F)
dt
# col1 col2
# 1 green\twhite3\t3blue5
# 2 green green\twhite3
ff = function(x)
{
res = vector() # create an empty vector to store counts for each element
for (i in 1:length(x)){ # iterate through each element
res[i] = ifelse(x[i]==" ", 0, length(unlist(strsplit(x[i],"\t")))) # if the element is space return 0, else split string by \t and count new strings
}
return(res) # return the stored values
}
data.frame(sapply(dt, function(x) ff(x))) # apply the function to all columns and save it as a data.frame
# col1 col2
# 1 3 0
# 2 1 2
``` | [Parsing Tab Delimited](https://stackoverflow.com/questions/11059390/parsing-a-tab-separated-file-in-python)
Read this post above. It covers using python csv module to parse tab delimited. I think it will help you.
**Input File data\_frame.txt**
```
5blue 2green5 white
white green\twhite3\t3blue5
blue3 white
7blue green2
3green 3white6
6blue green\t6white7 green
5blue5 6green white
```
The code below
```
import csv
data_frame = open('data_frame.txt','r') ## create input file for dataframe
output_matrix = [] ## output matrix
reader = csv.reader(data_frame, dialect="excel-tab") ## Setup tab delimter file
for line in reader: ## Read each line in the data frame
out_line = [] ## Setup temp out-line var
for item in line:
if item == '': ## If item in line is null then put zero
out_line.append(0)
elif r"""\t""" in item: ## if item in line contains a "\t" character then put count + 1
out_line.append(item.count(r"""\t""")+1)
else: ## Else item is 1
out_line.append(1)
output_matrix.append(out_line) ## Append line into output matrix
for line in output_matrix:
print line ## Print output matrix
```
This code should work... you just have to output the output\_matrix to a csv file.
**Output**
```
[1, 1, 1]
[0, 1, 3]
[1, 0, 1]
[1, 1, 0]
[0, 1, 1]
[1, 2, 1]
[1, 1, 1]
``` |
15,840,273 | I have an existing MVC3 application which allows users to upload files and share them with others. The current model is that if a user wants to change a file, they have to delete the one there and re-upload the new version. To improve this, we are looking into integrating WebDAV to allow the online editing of things like Word documents.
So far, I have been using the .Net server and client libraries from <http://www.webdavsystem.com/> to set the website up as a WebDAV server and to talk with it.
However, we don't want users to interact with the WebDAV server directly (we have some complicated rules on which users can do what in certain situations based on domain logic) but go through the previous controller actions we had for accessing files.
So far it is working up to the point where we can return the file and it gives the WebDAV-y type prompt for opening the file.
The problem is that it is always stuck in read-only mode. I have confirmed that it works and is editable if I use the direct WebDAV URL but not through my controller action.
Using Fiddler I think I have found the problem is that Word is trying to talk negotiate with the server about the locking with a location that isn't returning the right details. The controller action for downloading the file is "/Files/Download?filePath=bla" and so Word is trying to talk to "/Files" when it sends the OPTIONS request.
Do I simply need to have an action at that location that would know how to respond to the OPTIONS request and if so, how would I do that response? Alternatively, is there another way to do it, perhaps by adding some property to the response that could inform Word where it should be looking instead?
Here is my controller action:
```
public virtual FileResult Download(string filePath)
{
FileDetails file = _fileService.GetFile(filePath);
return File(file.Stream, file.ContentType);
}
```
And here is the file service method:
```
public FileDetails GetFile(string location)
{
var fileName = Path.GetFileName(location);
var contentType = ContentType.Get(Path.GetExtension(location));
string license ="license";
var session = new WebDavSession(license) {Credentials = CredentialCache.DefaultCredentials};
IResource resource = session.OpenResource(string.Format("{0}{1}", ConfigurationManager.AppSettings["WebDAVRoot"], location));
resource.TimeOut = 600000;
var input = resource.GetReadStream();
return new FileDetails { Filename = fileName, ContentType = contentType, Stream = input };
}
```
It is still very early days on this so I appreciate I could be doing this in entirely the wrong way and so any form of help is welcome. | 2013/04/05 | [
"https://Stackoverflow.com/questions/15840273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799403/"
] | In the end it seems that the better option was to allow users to directly talk to the WebDAV server and implement the authentication logic to control it.
The IT Hit server has extensions that allow you to authenticate against the forms authentication for the rest of the site using basic or digest authentication from Office. Using that along with some other customisations to the item request logic gave us what we needed. | This is exactly what i did for a MVC 4 project.
<https://mvc4webdav.codeplex.com/> |
51,169,227 | I have Android layout listed below, but *layout\_marginBottom* is not working - there is no any margin between *myTextView* and *myRecyclerView*.
Any ideas, what may be wrong with my layout?
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/myTextView"
android:text="*** Descritpion text"
app:layout_constraintWidth_default="spread"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@+id/myRecyclerView"
android:layout_marginBottom="300dp" />
<android.support.v7.widget.RecyclerView
android:id="@+id/myRecyclerView"
app:layout_constraintTop_toBottomOf="@+id/myTextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintVertical_bias="0"
app:layout_constraintWidth_default="spread"
app:layout_constraintHeight_default="wrap"
android:layout_width="0dp"
android:layout_height="0dp" />
</android.support.constraint.ConstraintLayout>
``` | 2018/07/04 | [
"https://Stackoverflow.com/questions/51169227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5752684/"
] | To understand your question correctly, do you meant to say telnet is not found inside the running container? If not then you can install if while building the image itself. | Why you need telnet to other container?
if you want to copy files from one container to another container then you can use
`docker cp <containerid>:<path/to/copy> <conatinerid>:<path/to/copy>`
Docker container is like lightweight os that has minimum but necessary requirements
and telnet is definitely not one of them but still if you want telnet in container and you are using ubuntu image you can install telnet in container with
`apt-get update && apt-get install telnet`
And if you are using another image you can include telnet in a docker file and from that image you can use telnet into container.
Sorry for writing this in answer. Not having reputation for comment
but i hope you can understand. |
36,144,214 | I have a vb string with this value: `c:\program\bin\files`
I need to convert this string to this value: `files`
All i need is the last folder of the path.
The path is not fixed. It can be anything like: `d:\app\win\7\sp1\update`
In this case the string must be converted to: `update`
I think that should be done by searching the string backwards for the first occurrence of `\` and removing everything before it, including the `\` itself.
But obviously i don't know how to do it. :)
Thank you!
**EDIT:**
I need to use this to fill a ComboBox...
This is what i am using:
```
ComboBox1.Items.AddRange(IO.Directory.GetDirectories(appPath & "\Updates\Version"))
```
It gives me a ComboBox like:
```
c:/program/Updates/Version/Beta1
c:/program/Updates/Version/Beta2
c:/program/Updates/Version/Beta3
c:/program/Updates/Version/Beta4
```
And i would like to have the ComboBox like:
```
Beta1
Beta2
Beta3
Beta4
``` | 2016/03/22 | [
"https://Stackoverflow.com/questions/36144214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1181161/"
] | Rather than try to pull apart the string yourself, have a look at the [System.IO.Path](https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx) class.
In your case, the GetFileName method does what you want:
```
lastFolder = System.IO.Path.GetFileName(path)
```
To fill a combo box with names you can use a LINQ query like this:
```
ComboBox1.Items.AddRange(
From path
In IO.Directory.GetDirectories(IO.Path.Combine(appPath, "Updates\Version"))
Select IO.Path.GetFileName(path))
```
Also, try to use the Path.Combine method when joining path fragments together. It's safer than just joining strings. | In VBScript, which this is tagged you have two choices. This was written before any code was edited into the question.
Use `InstrR` which is `Instr` but from back to front of string.
You also have `StrReverse` which reverses a string.
>
> **InStrRev**
>
>
> Returns the position of an occurrence of one string within another, from the end of string.
>
>
>
> ```
> InStrRev(string1, string2[, start[, compare]])
>
> ```
>
> **StrReverse**
>
>
> Returns a string in which the character order of a specified string is reversed.
>
>
>
> ```
> StrReverse(string1)
>
> ```
>
>
If using the File System Object it has a method to do specifically what you want.
>
> **GetParentFolderName** **Method**
>
>
> Returns a string containing the name of the parent folder of the last component in a specified path.
>
>
>
> ```
> Set fso = CreateObject("Scripting.FileSystemObject")
> object.GetParentFolderName(path)
>
> ```
>
> |
1,863,954 | $$\int \frac{dx}{x(x^n +1)} $$
$$t=x^n + 1$$
$${dt}=nx^{n-1}{dx}$$
$$\frac{dx}{x}=\frac{dt}{nx^n}$$
$$\int \frac{1}{n}\frac{dt}{t(t-1)} $$
I tried $t=\sin^2\theta $ but back substitution will be difficult .
How to integrate this type of integration ? | 2016/07/19 | [
"https://math.stackexchange.com/questions/1863954",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346279/"
] | Let $$I = \int\frac{1}{x(x^n+1)}dx = \int\frac{1}{\left(1+x^{-n}\right)}\cdot \frac{1}{x^{n+1}}dx$$
Now put $1+x^{-n} = t\; $ Then $\displaystyle -\frac{1}{n}\cdot \frac{1}{x^{n+1}}dx = dt$
So $$I =-n\int\frac{1}{t}dt=-n\ln |t|+\mathcal{C} = n\ln \left|\frac{x^n}{1+x^n}\right|+\mathcal{C}$$ | **Hint:**
$$\frac{1}{t(t-1)}=\frac{1}{t-1}-\frac{1}{t}.$$
Hope this helps. |
1,863,954 | $$\int \frac{dx}{x(x^n +1)} $$
$$t=x^n + 1$$
$${dt}=nx^{n-1}{dx}$$
$$\frac{dx}{x}=\frac{dt}{nx^n}$$
$$\int \frac{1}{n}\frac{dt}{t(t-1)} $$
I tried $t=\sin^2\theta $ but back substitution will be difficult .
How to integrate this type of integration ? | 2016/07/19 | [
"https://math.stackexchange.com/questions/1863954",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/346279/"
] | Let $$I = \int\frac{1}{x(x^n+1)}dx = \int\frac{1}{\left(1+x^{-n}\right)}\cdot \frac{1}{x^{n+1}}dx$$
Now put $1+x^{-n} = t\; $ Then $\displaystyle -\frac{1}{n}\cdot \frac{1}{x^{n+1}}dx = dt$
So $$I =-n\int\frac{1}{t}dt=-n\ln |t|+\mathcal{C} = n\ln \left|\frac{x^n}{1+x^n}\right|+\mathcal{C}$$ | If you insist on doing the problem solely with substitution, you should probably try substituting $t=\sec^2\theta$. Then you end up with
$$\frac1n\int\frac{2\sec^2\theta\tan\theta\,d\theta}{\sec^2\theta\tan^2\theta} = \frac2n\int\cot\theta\,d\theta,$$
which is quite straightforward. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | $$\binom{2n}n=\frac{n+1}{1}\frac{n+2}{2}\cdots\frac{2n-1}{n-1}\frac{2n}{n}\ge2^n>\frac{4n}{n+1}.$$ | The proof is correct. I particularly enjoyed how you proved the identity involving the squares of the binomial coefficients. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | We prove the stronger bound $\binom{2n}{n} \geq \frac{4^n}{2n+1}$, which is bigger than $\frac{4}{n+1}$ for all $n \geq 2$.
Note that the $2n+1$ binomial coefficients $\binom{2n}{0}$, $\binom{2n}{1}$, ..., $\binom{2n}{2n}$ have average
$$
\frac{\binom{2n}{0} + \binom{2n}{1} + \ldots + \binom{2n}{2n}}{2n+1} = \frac{2^{2n}}{2n+1} = \frac{4^n}{2n+1}.
$$
Since $\binom{2n}{n}$ is the largest of these binomial coefficients, it is surely "above average": $\binom{2n}{n} \geq \frac{4^n}{2n+1}$. | The proof is correct. I particularly enjoyed how you proved the identity involving the squares of the binomial coefficients. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | $$\binom{2n}n=\frac{n+1}{1}\frac{n+2}{2}\cdots\frac{2n-1}{n-1}\frac{2n}{n}\ge2^n>\frac{4n}{n+1}.$$ | It can probably be made shorter using induction: $$\binom{2(k+1)}{k+1)}=\binom{2k}k\cdot \frac{(2k+1)(2k+2)}{k+1}\\
>\frac{4k(2k+1)(2k+2)}{(k+1)^2}$$It isn't very hard to show that the final fraction is larger than $\frac{4k+4}{k+2}$. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | We prove the stronger bound $\binom{2n}{n} \geq \frac{4^n}{2n+1}$, which is bigger than $\frac{4}{n+1}$ for all $n \geq 2$.
Note that the $2n+1$ binomial coefficients $\binom{2n}{0}$, $\binom{2n}{1}$, ..., $\binom{2n}{2n}$ have average
$$
\frac{\binom{2n}{0} + \binom{2n}{1} + \ldots + \binom{2n}{2n}}{2n+1} = \frac{2^{2n}}{2n+1} = \frac{4^n}{2n+1}.
$$
Since $\binom{2n}{n}$ is the largest of these binomial coefficients, it is surely "above average": $\binom{2n}{n} \geq \frac{4^n}{2n+1}$. | It can probably be made shorter using induction: $$\binom{2(k+1)}{k+1)}=\binom{2k}k\cdot \frac{(2k+1)(2k+2)}{k+1}\\
>\frac{4k(2k+1)(2k+2)}{(k+1)^2}$$It isn't very hard to show that the final fraction is larger than $\frac{4k+4}{k+2}$. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | $$\binom{2n}n=\frac{n+1}{1}\frac{n+2}{2}\cdots\frac{2n-1}{n-1}\frac{2n}{n}\ge2^n>\frac{4n}{n+1}.$$ | Imagine a population, $P$, consisting of $n$ men and $n$ women. You are tasked with putting together a committee of $n$ people from $P$. There are no restriction on the make-up of the committee (for instance, it can be unisex). How many different committees can you put together?
Align the men in one row, and the women in another one. You can create a committee consisting of all the men. You can create a committee consisting of all the women. You can create a committee consisting of all the women in the odd-numbered places and all the men in the even places. You can create a committee consisting of all the men in the odd-numbered places and all the women in even places.
We have just enumerated four different possible committees. This is not necessarily an exhaustive list of all the possible committees, but it is enough for us to be able to make the statement that
$$
\binom{2n}{n} \geq 4.
$$
But
$$
4 = \frac{4n}{n} > \frac{4n}{n+1}.
$$ |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | We prove the stronger bound $\binom{2n}{n} \geq \frac{4^n}{2n+1}$, which is bigger than $\frac{4}{n+1}$ for all $n \geq 2$.
Note that the $2n+1$ binomial coefficients $\binom{2n}{0}$, $\binom{2n}{1}$, ..., $\binom{2n}{2n}$ have average
$$
\frac{\binom{2n}{0} + \binom{2n}{1} + \ldots + \binom{2n}{2n}}{2n+1} = \frac{2^{2n}}{2n+1} = \frac{4^n}{2n+1}.
$$
Since $\binom{2n}{n}$ is the largest of these binomial coefficients, it is surely "above average": $\binom{2n}{n} \geq \frac{4^n}{2n+1}$. | Imagine a population, $P$, consisting of $n$ men and $n$ women. You are tasked with putting together a committee of $n$ people from $P$. There are no restriction on the make-up of the committee (for instance, it can be unisex). How many different committees can you put together?
Align the men in one row, and the women in another one. You can create a committee consisting of all the men. You can create a committee consisting of all the women. You can create a committee consisting of all the women in the odd-numbered places and all the men in the even places. You can create a committee consisting of all the men in the odd-numbered places and all the women in even places.
We have just enumerated four different possible committees. This is not necessarily an exhaustive list of all the possible committees, but it is enough for us to be able to make the statement that
$$
\binom{2n}{n} \geq 4.
$$
But
$$
4 = \frac{4n}{n} > \frac{4n}{n+1}.
$$ |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | $$\binom{2n}n=\frac{n+1}{1}\frac{n+2}{2}\cdots\frac{2n-1}{n-1}\frac{2n}{n}\ge2^n>\frac{4n}{n+1}.$$ | Some other approaches look like sledgehammers to me, as you essentially need to show that the central binomial coefficient exceeds $4$, which is true for $2n=4$.
Is it really necessary to prove that the central coefficients are increasing ?
---
If yes,
$$\binom{2n+2}{n+1}=\frac{(2n+2)(2n+1)}{(n+1)(n+1)}\binom{2n}n$$
or simply invoke Pascal's identity that shows that the central element at least doubles on every second row.
[](https://i.stack.imgur.com/48ucK.png)
Note that the first product shows that the value is asymptotically mutiplied by $4$ on every other row. |
1,954,608 | >
> Prove that $$\binom{2n}{n}>\frac{4n}{n+1}\forall \; n\geq 2, n\in \mathbb{N}$$
>
>
>
$\bf{My\; Try::}$ Using $$(1+x)^n = \binom{n}{0}+\binom{n}{1}x+\binom{n}{2}x^2+........+\binom{n}{n}x^n$$
and $$(x+1)^n = \binom{n}{0}x^n+\binom{n}{1}x^{n-1}+\binom{n}{2}x^{n-1}+........+\binom{n}{n}$$
Now Coefficients of $x^n$ in $\displaystyle (1+x)^{2n} = \binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2$
Now Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2\right]\cdot \left[1^2+1^2+....+1^2\right]\geq \left[\binom{n}{0}+\binom{n}{1}+\binom{n}{2}+.....+\binom{n}{n}\right]^2=2^{2n}=4^n>4n\forall n\geq 2,n\in \mathbb{N}$$
So $$\binom{2n}{n} = \binom{n}{0}^2+\binom{n}{1}^2+\binom{n}{2}^2+.....+\binom{n}{n}^2>\frac{4n}{n+1}\forall n\geq 2,n\in \mathbb{N}$$
My question is , Is my proof is right, If not then how can i solve it.
Also plz explain any shorter way, Thanks | 2016/10/05 | [
"https://math.stackexchange.com/questions/1954608",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | We prove the stronger bound $\binom{2n}{n} \geq \frac{4^n}{2n+1}$, which is bigger than $\frac{4}{n+1}$ for all $n \geq 2$.
Note that the $2n+1$ binomial coefficients $\binom{2n}{0}$, $\binom{2n}{1}$, ..., $\binom{2n}{2n}$ have average
$$
\frac{\binom{2n}{0} + \binom{2n}{1} + \ldots + \binom{2n}{2n}}{2n+1} = \frac{2^{2n}}{2n+1} = \frac{4^n}{2n+1}.
$$
Since $\binom{2n}{n}$ is the largest of these binomial coefficients, it is surely "above average": $\binom{2n}{n} \geq \frac{4^n}{2n+1}$. | Some other approaches look like sledgehammers to me, as you essentially need to show that the central binomial coefficient exceeds $4$, which is true for $2n=4$.
Is it really necessary to prove that the central coefficients are increasing ?
---
If yes,
$$\binom{2n+2}{n+1}=\frac{(2n+2)(2n+1)}{(n+1)(n+1)}\binom{2n}n$$
or simply invoke Pascal's identity that shows that the central element at least doubles on every second row.
[](https://i.stack.imgur.com/48ucK.png)
Note that the first product shows that the value is asymptotically mutiplied by $4$ on every other row. |
66,921,057 | I'm new to bash scripting and trying to learn.
I have a variable $temp, that contains what I get from an API call, which is a long list of SHA1 hashes. I want to take what is in $temp and create an array that I can loop through and compare each entry to a string I have defined. Somehow, I can not seem to get it to work. The array I create always only contains only one element. It is like the rest of the string in $temp is being ignored.
I have tried multiple approaches, and can't get anything working the way I want it to.
Here's the code snippet:
```
temp=$(curl --silent --request GET "https://api.pwnedpasswords.com/range/$shortendHash")
echo "Temp is: $temp"
declare -A myArr
read myArr <<<$temp
echo ${myArr[@]}
echo ${myArr[0]}
echo ${myArr[1]}
```
When I run this, I get a full list of hashes, when I echo $temp (line 2), something like this:
"Temp is: 002C3CADF9FC86069F09961B10E0EDEFC45:1
003BE35BD9466D19258E79C8665AFB072F6:1
0075B2ADF782F9677BDDF8CC5778900D986:8
00810352C02B145FF304FCBD5BEF4F7AA9F:1
013720F40B99D6BCF6F08BD7271523EBB49:1
01C894A55EBCB6048A745B37EC2D989F102:1
030B46D53696C8889910EE0F9EB42CEAE97:4
03126B56153F0564F4A6ED6E734604C67E8:2
043196099707FCB0C01F8C2111086A92A0B:1
0452CABBEF8438F358F0BD8089108D0910E:5
0490255B206A2C0377EBD080723BF72DDAE:2
05AD1141C41237E061460DB5CA5412C1A48:4
05C1D058E4439F8F005EFB32E7553E6AA5B:1
067AF515CC712AC4ACA012311979DBC7C9A:2 ... and so on.."
But the
```
echo ${myArr[@]}
echo ${myArr[0]}
echo ${myArr[1]}
```
returns (first value is ${myArr[@]}, second is ${myArr[0]}, and last one is an empty line, indicating that there is no value at array position 1):
002C3CADF9FC86069F09961B10E0EDEFC45:1
002C3CADF9FC86069F09961B10E0EDEFC45:1
I hope someone can help with this.
Thanks a lot in advance! | 2021/04/02 | [
"https://Stackoverflow.com/questions/66921057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14851149/"
] | ```
declare -A myArr # creates an associative array (hash)
declare -a myArr # creates an array
```
Neither is necessary here. `read` can create the array for you. See `help declare` and `help read`.
---
```
temp=$(curl --silent --request GET "https://api.pwnedpasswords.com/range/$shortendHash")
# -a: assign the words read to sequential indices of the array
read -a myArr <<<"$temp"
declare -p myArr
```
Output:
>
> declare -a myArr=([0]="002C3CADF9FC86069F09961B10E0EDEFC45:1" [1]="003BE35BD9466D19258E79C8665AFB072F6:1" [2]="0075B2ADF782F9677BDDF8CC5778900D986:8" [3]="00810352C02B145FF304FCBD5BEF4F7AA9F:1" [4]="013720F40B99D6BCF6F08BD7271523EBB49:1" [5]="01C894A55EBCB6048A745B37EC2D989F102:1" [6]="030B46D53696C8889910EE0F9EB42CEAE97:4" [7]="03126B56153F0564F4A6ED6E734604C67E8:2" [8]="043196099707FCB0C01F8C2111086A92A0B:1" [9]="0452CABBEF8438F358F0BD8089108D0910E:5" [10]="0490255B206A2C0377EBD080723BF72DDAE:2" [11]="05AD1141C41237E061460DB5CA5412C1A48:4" [12]="05C1D058E4439F8F005EFB32E7553E6AA5B:1" [13]="067AF515CC712AC4ACA012311979DBC7C9A:2")
>
>
> | Assuming ...
```
$(curl --silent --request GET "https://api.pwnedpasswords.com/range/$shortendHash")
```
Returns ...
```
002C3CADF9FC86069F09961B10E0EDEFC45:1
003BE35BD9466D19258E79C8665AFB072F6:1
0075B2ADF782F9677BDDF8CC5778900D986:8
00810352C02B145FF304FCBD5BEF4F7AA9F:1
013720F40B99D6BCF6F08BD7271523EBB49:1
01C894A55EBCB6048A745B37EC2D989F102:1
030B46D53696C8889910EE0F9EB42CEAE97:4
03126B56153F0564F4A6ED6E734604C67E8:2
043196099707FCB0C01F8C2111086A92A0B:1
0452CABBEF8438F358F0BD8089108D0910E:5
0490255B206A2C0377EBD080723BF72DDAE:2
05AD1141C41237E061460DB5CA5412C1A48:4
05C1D058E4439F8F005EFB32E7553E6AA5B:1
067AF515CC712AC4ACA012311979DBC7C9A:2
```
Then assign this to an array by wrapping in a set of parens:
```
# unset current variable
$ unset myArr
# no need to issue a `declare`; the `myArr=( ... )` will automatically create `myArr` as a normal integer-indexed array
$ myArr=( $(curl --silent --request GET "https://api.pwnedpasswords.com/range/$shortendHash") )
# verify array contents:
$ typeset myArr
declare -a myarr=([0]="002C3CADF9FC86069F09961B10E0EDEFC45:1" [1]="003BE35BD9466D19258E79C8665AFB072F6:1" [2]="0075B2ADF782F9677BDDF8CC5778900D986:8" [3]="00810352C02B145FF304FCBD5BEF4F7AA9F:1" [4]="013720F40B99D6BCF6F08BD7271523EBB49:1" [5]="01C894A55EBCB6048A745B37EC2D989F102:1" [6]="030B46D53696C8889910EE0F9EB42CEAE97:4" [7]="03126B56153F0564F4A6ED6E734604C67E8:2" [8]="043196099707FCB0C01F8C2111086A92A0B:1" [9]="0452CABBEF8438F358F0BD8089108D0910E:5" [10]="0490255B206A2C0377EBD080723BF72DDAE:2" [11]="05AD1141C41237E061460DB5CA5412C1A48:4" [12]="05C1D058E4439F8F005EFB32E7553E6AA5B:1" [13]="067AF515CC712AC4ACA012311979DBC7C9A:2")
```
---
Assuming OP wants to populate the array from the variable `$temp`, and assuming the white space in `$temp` consists of linefeeds and not spaces:
```
$ mapfile -t myArr <<< "${temp}"
$ typeset -p myArr
declare -a x=([0]="002C3CADF9FC86069F09961B10E0EDEFC45:1" [1]="003BE35BD9466D19258E79C8665AFB072F6:1" [2]="0075B2ADF782F9677BDDF8CC5778900D986:8" [3]="00810352C02B145FF304FCBD5BEF4F7AA9F:1" [4]="013720F40B99D6BCF6F08BD7271523EBB49:1" [5]="01C894A55EBCB6048A745B37EC2D989F102:1" [6]="030B46D53696C8889910EE0F9EB42CEAE97:4" [7]="03126B56153F0564F4A6ED6E734604C67E8:2" [8]="043196099707FCB0C01F8C2111086A92A0B:1" [9]="0452CABBEF8438F358F0BD8089108D0910E:5" [10]="0490255B206A2C0377EBD080723BF72DDAE:2" [11]="05AD1141C41237E061460DB5CA5412C1A48:4" [12]="05C1D058E4439F8F005EFB32E7553E6AA5B:1" [13]="067AF515CC712AC4ACA012311979DBC7C9A:2")
``` |
17,696,760 | 
As show in Picture above UIView A & UIView C are Added on UIView B. for B ClipToBounds is YES so the Red area is not visible.
Is it possible to get Visible rectangle of A & C ( shown with Lines )
I need show Rectangle in visible area when I touches e.g View A. thats it.
 | 2013/07/17 | [
"https://Stackoverflow.com/questions/17696760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/355082/"
] | You can get an intersection rect of the two rects by using [CGRectIntersection()](http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/doc/uid/TP30000955-CH1g-F17157) method
```
CGRect intersectionRect = CGRectIntersection(viewA.frame, viewB.frame);
if(CGRectIsNull(intersectionRect)) {
//Rects do not intersect
}
``` | Use for this
```
[UIView convertRect:<#(CGRect)#> fromView:<#(UIView *)#>]
[UIView convertRect:<#(CGRect)#> toView:<#(UIView *)#>]
```
And CGRectIntersection function |
17,696,760 | 
As show in Picture above UIView A & UIView C are Added on UIView B. for B ClipToBounds is YES so the Red area is not visible.
Is it possible to get Visible rectangle of A & C ( shown with Lines )
I need show Rectangle in visible area when I touches e.g View A. thats it.
 | 2013/07/17 | [
"https://Stackoverflow.com/questions/17696760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/355082/"
] | You can get an intersection rect of the two rects by using [CGRectIntersection()](http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/doc/uid/TP30000955-CH1g-F17157) method
```
CGRect intersectionRect = CGRectIntersection(viewA.frame, viewB.frame);
if(CGRectIsNull(intersectionRect)) {
//Rects do not intersect
}
``` | on `touchesEnded:` method you can find it like bellow..
```
-(void) touchesEnded:(NSSet *) touches {
if(CGRectIntersectsRect([ViewA frame], [ViewB frame]) {
//Do something here
}
}
```
Read More Information about RectInterSect From [This Link](https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsPoint)
i hope its helpful to you... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.