qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
148,118
I am trying to make a little wireless-connected gizmo to attach to my grandfather's walking cane. The idea is that when it senses the cane has fallen down, it would alert/call one of us so that we can rush to him if we're not nearby. The question is: What sensor or combination of sensors could I use to reliably differentiate between these two scenarios? **NORMAL situation**: The cane is being held upright (or at only a slight angle from vertical) and used normally. *versus* **CRITICAL situation**: The cane has been let go of, falls down and continues to lie on the floor/ground Obviously, occasional false positives would be fine, but detection misses (false negatives) should be minimized. --- I am thinking a combination of two things might help: --sense whether my grandpa's hand is holding the cane or not (perhaps a light sensor that is blocked when the hand is on it?) --sense whether the cane is upright or has taken a fall (perhaps an accelerometer+gyroscope+vibration sensor to determine orientation and shock events?)
2015/01/08
[ "https://electronics.stackexchange.com/questions/148118", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/11636/" ]
The most reliable way would be a gyro+accel combo (like the mpu6050 from invensense). You can just use their DMP stuff to get a roll/pitch/yaw angle for the sensor, or do the work yourself by running the data through a kalman filter. You don't need a vibration sensor, as you can get that from the accelerometer data too (just look for impact events).
Seems like an accelerometer and a small microcontroller (a PIC for example) could do this quite easily. You could then set the angle at which the alarm goes off in the code. With the light sensor approach you'd need to be careful that the area stayed clean. Otherwise if he covers the sensor with crud it will always indicate that the cane is vertical even when it is not. With a vibration sensor you'd have to get creative about detecting the impulse event (when the cane falls) and then latch the output so it continues to sound the alarm even after the can has come to a rest.
148,118
I am trying to make a little wireless-connected gizmo to attach to my grandfather's walking cane. The idea is that when it senses the cane has fallen down, it would alert/call one of us so that we can rush to him if we're not nearby. The question is: What sensor or combination of sensors could I use to reliably differentiate between these two scenarios? **NORMAL situation**: The cane is being held upright (or at only a slight angle from vertical) and used normally. *versus* **CRITICAL situation**: The cane has been let go of, falls down and continues to lie on the floor/ground Obviously, occasional false positives would be fine, but detection misses (false negatives) should be minimized. --- I am thinking a combination of two things might help: --sense whether my grandpa's hand is holding the cane or not (perhaps a light sensor that is blocked when the hand is on it?) --sense whether the cane is upright or has taken a fall (perhaps an accelerometer+gyroscope+vibration sensor to determine orientation and shock events?)
2015/01/08
[ "https://electronics.stackexchange.com/questions/148118", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/11636/" ]
I agree with one of the above replies in that you need something (probably two accelerometers) to detect the angle at which the cane stands (calibrated at the factory if you are industrializing this). This way you have a continuum of what angle the cane is at, relative to upright. This gives a distinct advantage over a simple tilt switch for the following reasons. 1. You can calculate the angle with two accelerometers. With a tilt (on/off) switch, you cannot 2. Not only can you calculate the angle with two accelerometers, you can detect **the rate at which the angle changes** relative to the cane standing up straight. **This is key** as you can then at least have the information to characterize what the rate of fall looks like by a simple drop test and base your fall detection algorithm model on that.
A very simple solution is a tilt sensor such as the AT-407 from Sparkfun. It consists of 2 steel balls inside a small tube and 2 leads. When the tube is tilted, the balls separate and continuity is lost between the 2 leads. It costs only $1.95.
148,118
I am trying to make a little wireless-connected gizmo to attach to my grandfather's walking cane. The idea is that when it senses the cane has fallen down, it would alert/call one of us so that we can rush to him if we're not nearby. The question is: What sensor or combination of sensors could I use to reliably differentiate between these two scenarios? **NORMAL situation**: The cane is being held upright (or at only a slight angle from vertical) and used normally. *versus* **CRITICAL situation**: The cane has been let go of, falls down and continues to lie on the floor/ground Obviously, occasional false positives would be fine, but detection misses (false negatives) should be minimized. --- I am thinking a combination of two things might help: --sense whether my grandpa's hand is holding the cane or not (perhaps a light sensor that is blocked when the hand is on it?) --sense whether the cane is upright or has taken a fall (perhaps an accelerometer+gyroscope+vibration sensor to determine orientation and shock events?)
2015/01/08
[ "https://electronics.stackexchange.com/questions/148118", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/11636/" ]
I agree with one of the above replies in that you need something (probably two accelerometers) to detect the angle at which the cane stands (calibrated at the factory if you are industrializing this). This way you have a continuum of what angle the cane is at, relative to upright. This gives a distinct advantage over a simple tilt switch for the following reasons. 1. You can calculate the angle with two accelerometers. With a tilt (on/off) switch, you cannot 2. Not only can you calculate the angle with two accelerometers, you can detect **the rate at which the angle changes** relative to the cane standing up straight. **This is key** as you can then at least have the information to characterize what the rate of fall looks like by a simple drop test and base your fall detection algorithm model on that.
The most reliable way would be a gyro+accel combo (like the mpu6050 from invensense). You can just use their DMP stuff to get a roll/pitch/yaw angle for the sensor, or do the work yourself by running the data through a kalman filter. You don't need a vibration sensor, as you can get that from the accelerometer data too (just look for impact events).
12,744,622
I want to know index of current scrolled page in UIScrollView. I have searched through many sites by none helps. Any suggestions are welcome.
2012/10/05
[ "https://Stackoverflow.com/questions/12744622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564754/" ]
Try this ``` //Horizontal NSInteger pagenumber = scrollView.contentOffset.x / scrollView.bounds.size.width; //Vertical NSInteger pagenumber = scrollView.contentOffset.y / scrollView.bounds.size.height; ```
Use the `contentOffset` property, which returns a `CGSize` that is the offset of the content in the `UIScrollView`.
12,744,622
I want to know index of current scrolled page in UIScrollView. I have searched through many sites by none helps. Any suggestions are welcome.
2012/10/05
[ "https://Stackoverflow.com/questions/12744622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564754/" ]
For those needing code (swift) , the UIScrollViewDelegate provides the method, this uses the horizontal example from above ``` func scrollViewDidEndDecelerating(scrollView: UIScrollView) { print("END Scrolling \(scrollView.contentOffset.x / scrollView.bounds.size.width)") index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width) } ```
Use the `contentOffset` property, which returns a `CGSize` that is the offset of the content in the `UIScrollView`.
12,744,622
I want to know index of current scrolled page in UIScrollView. I have searched through many sites by none helps. Any suggestions are welcome.
2012/10/05
[ "https://Stackoverflow.com/questions/12744622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564754/" ]
Try this ``` //Horizontal NSInteger pagenumber = scrollView.contentOffset.x / scrollView.bounds.size.width; //Vertical NSInteger pagenumber = scrollView.contentOffset.y / scrollView.bounds.size.height; ```
with the help of some mathematical calculation you can get index number of page I am sending code for reference only . I have done. ``` -(void)KinarafindingSelectedCategory:(UIScrollView*)scrollView{ for (UIView *v in scrollView.subviews) { if ([v isKindOfClass:[UIButton class]]) { UIButton *btn=(UIButton*)v; float x1=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)-(btn.frame.size.width/2)); float x2=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)+(btn.frame.size.width/2)); float BtnMidPoint=btn.frame.origin.x+(btn.frame.size.width/2); if(BtnMidPoint >= x1 && BtnMidPoint <= x2) { if(scrollView==KinaraCategory) { KinaraSelectedCategoryName=btn.titleLabel.text; KinaraSelectedCategoryID=btn.tag; NSLog(@"Selected Category Tag : %d",KinaraSelectedCategoryID); NSLog(@"Selected Category Name : %@",KinaraSelectedCategoryName); } else if(scrollView==KinaraSubCategory) { KinaraSelectedSubCategoryID=btn.tag; KinaraSelectedSubCategoryName=btn.titleLabel.text; NSLog(@"Selected SubCategory Tag : %d",KinaraSelectedSubCategoryID); NSLog(@"Selected SubCategory Name : %@",KinaraSelectedSubCategoryName); } break; } } } } ```
12,744,622
I want to know index of current scrolled page in UIScrollView. I have searched through many sites by none helps. Any suggestions are welcome.
2012/10/05
[ "https://Stackoverflow.com/questions/12744622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564754/" ]
For those needing code (swift) , the UIScrollViewDelegate provides the method, this uses the horizontal example from above ``` func scrollViewDidEndDecelerating(scrollView: UIScrollView) { print("END Scrolling \(scrollView.contentOffset.x / scrollView.bounds.size.width)") index = Int(scrollView.contentOffset.x / scrollView.bounds.size.width) } ```
with the help of some mathematical calculation you can get index number of page I am sending code for reference only . I have done. ``` -(void)KinarafindingSelectedCategory:(UIScrollView*)scrollView{ for (UIView *v in scrollView.subviews) { if ([v isKindOfClass:[UIButton class]]) { UIButton *btn=(UIButton*)v; float x1=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)-(btn.frame.size.width/2)); float x2=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)+(btn.frame.size.width/2)); float BtnMidPoint=btn.frame.origin.x+(btn.frame.size.width/2); if(BtnMidPoint >= x1 && BtnMidPoint <= x2) { if(scrollView==KinaraCategory) { KinaraSelectedCategoryName=btn.titleLabel.text; KinaraSelectedCategoryID=btn.tag; NSLog(@"Selected Category Tag : %d",KinaraSelectedCategoryID); NSLog(@"Selected Category Name : %@",KinaraSelectedCategoryName); } else if(scrollView==KinaraSubCategory) { KinaraSelectedSubCategoryID=btn.tag; KinaraSelectedSubCategoryName=btn.titleLabel.text; NSLog(@"Selected SubCategory Tag : %d",KinaraSelectedSubCategoryID); NSLog(@"Selected SubCategory Name : %@",KinaraSelectedSubCategoryName); } break; } } } } ```
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
0bxxxx notation is for bit-wise representation of integers, which can be cast to byte if they fit, but this is not special byte-only notation. 0b1000000 is positive +128, which is more than can fit into byte. You would need to do something like -0b111111 (-127) to achieve byte pattern 0b1000000, but it is probably better to do explicit cast. What you are really looking for is unsigned byte type, which java lacks.
You may want to declare your flag as ``` private static final unsigned byte ``` I guess the compiler thinks the 255 is not fitting in to an signed byte (which only holdes -128 to 127)
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
Taking it from where [@Artur Biesiadowski](https://stackoverflow.com/users/4210615/artur-biesiadowski) left off, you are in essence attempting to store more than a byte can handle. ``` 1 0 0 0 0 0 0 0 7th 6th 5th 4th 3rd 2nd 1st 0th ``` This value is +128; Java byte range is -128 to +127 [[read further here](https://stackoverflow.com/questions/3621067/why-is-the-range-of-bytes-128-to-127-in-java)]. A cleaner and more readable way could be to use hex instead of the 0bxxx. Now, since you are asking to store +128 in a datatype that can store a maximum of +127, it is automatically using a datatype that can store a greater range, i.e., `int` via a process of type promotion. [[JLS 5.x](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html)] explains this in great detail.
You may want to declare your flag as ``` private static final unsigned byte ``` I guess the compiler thinks the 255 is not fitting in to an signed byte (which only holdes -128 to 127)
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
An alternative solution is to use a `BitSet` with its more human readable methods. You can still use flags for the individual bits, but they'd be indexes instead of bitmasks. Then you can just retrieve the resulting byte with `BitSet.toByteArray()[0]`.
You may want to declare your flag as ``` private static final unsigned byte ``` I guess the compiler thinks the 255 is not fitting in to an signed byte (which only holdes -128 to 127)
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
0bxxxx notation is for bit-wise representation of integers, which can be cast to byte if they fit, but this is not special byte-only notation. 0b1000000 is positive +128, which is more than can fit into byte. You would need to do something like -0b111111 (-127) to achieve byte pattern 0b1000000, but it is probably better to do explicit cast. What you are really looking for is unsigned byte type, which java lacks.
Taking it from where [@Artur Biesiadowski](https://stackoverflow.com/users/4210615/artur-biesiadowski) left off, you are in essence attempting to store more than a byte can handle. ``` 1 0 0 0 0 0 0 0 7th 6th 5th 4th 3rd 2nd 1st 0th ``` This value is +128; Java byte range is -128 to +127 [[read further here](https://stackoverflow.com/questions/3621067/why-is-the-range-of-bytes-128-to-127-in-java)]. A cleaner and more readable way could be to use hex instead of the 0bxxx. Now, since you are asking to store +128 in a datatype that can store a maximum of +127, it is automatically using a datatype that can store a greater range, i.e., `int` via a process of type promotion. [[JLS 5.x](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html)] explains this in great detail.
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
0bxxxx notation is for bit-wise representation of integers, which can be cast to byte if they fit, but this is not special byte-only notation. 0b1000000 is positive +128, which is more than can fit into byte. You would need to do something like -0b111111 (-127) to achieve byte pattern 0b1000000, but it is probably better to do explicit cast. What you are really looking for is unsigned byte type, which java lacks.
An alternative solution is to use a `BitSet` with its more human readable methods. You can still use flags for the individual bits, but they'd be indexes instead of bitmasks. Then you can just retrieve the resulting byte with `BitSet.toByteArray()[0]`.
37,155,592
I'm interacting with a legacy system that takes a lot of input on the bit level. It requires me to pass in octets (bytes really) with specific bits set. To keep this readable, I declare some flags like this: ``` private static final byte FLAG_A = 0b00010000; private static final byte FLAG_B = 0b00100000; private static final byte FLAG_C = 0b00011000; ``` That works perfectly. The strange thing is that when I set the highest bit (like shown below), the compiler starts complaining that is finds an int. I could cast it down, but this seems strange to me. It's still 8 bits, so I would expect it to fit in a byte (even if the two-complement notation causes it to be interpreted as negative, which is of no consequence to me) ``` private static final byte FLAG_D = 0b10000000; ``` Any idea what's going on?
2016/05/11
[ "https://Stackoverflow.com/questions/37155592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396618/" ]
Taking it from where [@Artur Biesiadowski](https://stackoverflow.com/users/4210615/artur-biesiadowski) left off, you are in essence attempting to store more than a byte can handle. ``` 1 0 0 0 0 0 0 0 7th 6th 5th 4th 3rd 2nd 1st 0th ``` This value is +128; Java byte range is -128 to +127 [[read further here](https://stackoverflow.com/questions/3621067/why-is-the-range-of-bytes-128-to-127-in-java)]. A cleaner and more readable way could be to use hex instead of the 0bxxx. Now, since you are asking to store +128 in a datatype that can store a maximum of +127, it is automatically using a datatype that can store a greater range, i.e., `int` via a process of type promotion. [[JLS 5.x](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html)] explains this in great detail.
An alternative solution is to use a `BitSet` with its more human readable methods. You can still use flags for the individual bits, but they'd be indexes instead of bitmasks. Then you can just retrieve the resulting byte with `BitSet.toByteArray()[0]`.
105,496
A friend and I will be flying separately from the USA into Heathrow. I am arriving in T5 and she arrives in T2. I arrive about an hour earlier than she does. We will then be taking the underground into London. What is our best way to connect? Should I go to arrivals in T2 after going through border control, baggage and customs? If yes -- how do I get to T2 arrivals from T5? I appreciate any help you may offer.
2017/11/19
[ "https://travel.stackexchange.com/questions/105496", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/70491/" ]
The most convenient meeting point is indeed the T2 public arrivals area. It offers comfort, access to food and drink, wifi, immediate updates if your friend's flight is delayed, the ability to make enquiries about any delay and page her if you don't manage to meet. Arrivals areas are accessible to anyone, so make your way to T2 by any of the advertized means and simply wait with everyone else who is waiting for a passenger. There is a page on the Heathrow website dedicated to [getting from one terminal to another](http://www.heathrow.com/airport-guide/getting-around-heathrow/travel-between-terminals). In short you can use the free Heathrow Express train, or the Underground, which is free if you have an Oyster card.
Provided your friend is also a comfortable traveler, the easiest thing for you to do is take the Underground (Piccadilly Line, one stop) from T5 to T2&3 and wait for them on the platform. Or, if they manage to arrive first, they can wait for you there. Basically, the T2 platform is your rendezvous point. If you have a mobiles that works in the UK, you can check each others flights. Heathrow has free WiFi if your plan does't cover text or data. T-Mobile is likely included, depending on you plan, and the other carriers make it easy to add. You really should do this anyway.
45,727
I see that 但 means "only" besides its typical meaning "but". So what is the difference between 但 and 只 and when do you use 但 with the meaning "only"?
2021/07/27
[ "https://chinese.stackexchange.com/questions/45727", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/28802/" ]
When delivering sad or bad news, a common phrase to say is 很不幸,很遺憾,or 很抱歉 Example: **很不幸**, 我心愛的寵物積克已經去世了 - **unfortunately/ sadly**, my beloved pet Jack has passed away. (He was such a good boy) **很遺憾**, 你這次測試你失敗了 - **regretfully**, you have failed this test **很抱歉**, 我對你一點好感也沒有 - **Sorry**, I don't have any good feelings for you > > I am sorry to say my grandmother passed away on X date > > > 很不幸, 我的祖母在 X月X日 去世了
"I am sorry to say". This type of expression is not in the Chinese's blood for the described event - the pass away of a family member. Rather the news is usually announced as a family matter: "家中不幸". 我的祖母在前天晚間過逝了, 她走的很突然但是很安祥. "家中不幸" will be dropped for a person without any attachment/tie to his family or have any living closely related family members around, that who is considered no home/family. "很不幸", 我的祖母在前天過逝了. This will be an answer to another person, who is asking the whereabout/condition of the grandmother without knowing her death.
71,022,493
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error. ``` import React, {useState, useEffect} from 'react' import ReactDOM from 'react-dom' import axios from 'axios' const App = () => { const url = 'https://api.tvmaze.com/search/shows?q=avengers' const [data, setData] = useState([]) useEffect(() => { axios.get(url).then((json) => setData(json.data)) }, []) const renderTable = () => { return data.map((user) => { return ( <tr> <td>{user.show.name}</td> <td>{user.show.language}</td> <td>{user.show.genres}</td> <td>{user.show.runtime}</td> <td>{user.show.premiered}</td> <td>{user.show.rating}</td> <td>{user.show.country.name}</td> <td>{user.image.medium}</td> </tr> ) }) } return ( <div> <h1 id="title">API Table</h1> <table id="users"> <thead> <tr> <th>Name</th> <th>language</th> <th>genres</th> <th>runtime</th> <th>premiered</th> <th>Rating</th> <th>country name</th> <th>image</th> </tr> </thead> <tbody>{renderTable()}</tbody> </table> </div> ) } export default App ```
2022/02/07
[ "https://Stackoverflow.com/questions/71022493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18036567/" ]
As mentioned in the comments, the example with `mstsc` only works because there's a 1-to-1 relationship between closing the main window it produces and *exiting the process*. This relationship does not exist with `explorer` - it'll detect on launch that the desktop session already has a shell, notify it of the request, and then exit immediately. Instead, use `Read-Host` to block further execution of the script until the user hits enter: ``` # launch folder window Invoke-Item $networkfolderpath # block the runtime from doing anything further by prompting the user (then discard the input) $null = Read-Host "Edit the files, then hit enter to continue..." ```
Here is some proof-of-concept code that opens the given folder and waits until the new shell (Explorer) window has been closed. This is made possible by the [Shell.Application](https://learn.microsoft.com/en-us/windows/win32/shell/shell) COM object. Its [`Windows()`](https://learn.microsoft.com/en-us/windows/win32/shell/shell-windows) method returns a list of currently open shell windows. We can query the `LocationURL` property of each shell window to find the window for a given folder path. Since there could already be a shell window that shows the folder we want to open, I check the number of shell windows to be sure a new window has been opened. Alternatively you could choose to [bring an existing shell window to front](https://stackoverflow.com/a/11369696/7571258). Then just loop until the `Visible` property of the shell window equals `$False` to wait until the Window has been closed. ``` Function Start-Explorer { [CmdletBinding()] param ( [Parameter(Mandatory)] [String] $Path, [Parameter()] [Switch] $Wait ) $shell = New-Object -ComObject Shell.Application $shellWndCountBefore = $shell.Windows().Count Invoke-Item $Path if( $wait ) { Write-Verbose 'Waiting for new shell window...' $pathUri = ([System.Uri] (Convert-Path $Path)).AbsoluteUri $explorerWnd = $null # Loop until the new shell window is found or timeout (30 s) is exceeded. foreach( $i in 0..300 ) { if( $shell.Windows().Count -gt $shellWndCountBefore ) { if( $explorerWnd = $shell.Windows() | Where-Object { $_.Visible -and $_.LocationURL -eq $pathUri }) { break } } Start-Sleep -Milliseconds 100 } if( -not $explorerWnd ) { $PSCmdlet.WriteError( [Management.Automation.ErrorRecord]::new( [Exception]::new( 'Could not find shell window' ), 'Start-Explorer', [Management.Automation.ErrorCategory]::OperationTimeout, $Path ) ) return } Write-Verbose "Found $($explorerWnd.Count) matching explorer window(s)" #Write-Verbose ($explorerWnd | Out-String) Write-Verbose 'Waiting for user to close explorer window(s)...' try { while( $explorerWnd.Visible -eq $true ) { Start-Sleep -Milliseconds 100 } } catch { # There might be an exception when the COM object dies before we see Visible = false Write-Verbose "Catched exception: $($_.Exception.Message)" } Write-Verbose 'Explorer window(s) closed' } } Start-Explorer 'c:\' -Wait -Verbose -EA Stop ```
185,867
I configured hardfail SPF for my domain and DKIM message signing on my SMTP server. Since this is the only SMTP server that should be used for outgoing mail from my domain, I didn't foresee any complications. However, consider the following situation: I sent an e-mail message via my SMTP server to my colleague's university e-mail. The problem is that my colleague forwards his university e-mail to his GMail account. These are the headers of the message after it reaches his GMail mailbox: ``` Received-SPF: fail (google.com: domain of me@example.com does not designate 192.168.128.100 as permitted sender) client-ip=192.168.128.100; Authentication-Results: mx.google.com; spf=hardfail (google.com: domain of me@example.com does not designate 192.168.128.100 as permitted sender) smtp.mail=me@example.com; dkim=hardfail (test mode) header.i=@example.com ``` (Headers have been sanitized to protect the domains and IP addresses of the non-Google parties) GMail checks the last SMTP server in the delivery chain against my SPF and DKIM records (rightfully so). Since the last STMP server in the delivery chain was the university's server and not my server, the check results in an SPF hardfail and DKIM failure. Fortunately, GMail did not mark the message as spam but I'm concerned that this might cause a problem in the future. Is my implementation of SPF hardfail perhaps too strict? Any other recommendations or potential issues that I should be aware of? Or maybe there is a more ideal configuration for the university's e-mail forwarding procedure? I know that the forwarding server could possibly change the envelope sender but I see that getting messy.
2010/09/29
[ "https://serverfault.com/questions/185867", "https://serverfault.com", "https://serverfault.com/users/53736/" ]
The forwarding server needs to setup SRS in order not to break your SPF <http://www.open-spf.org/srs/>
While forwarding does break SPF (without SRS), it typically does not break DKIM. It looks like (based on `dkim=hardfail (test mode)` in GMail's authentication results) the problem is that your SPF key record has the `t=y` flag, indicating it is only for [testing purposes](https://www.rfc-editor.org/rfc/rfc4871#section-3.6.1).
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
Please, no. I spend so much time fixing things that students believe that they heard in lectures on the German Wikipedia. Excellent points have been made above. I suggest installing <https://bitnami.com/stack/mediawiki> on a machine under your control and keep your notes there.
The lecture material was provided for you and your classmates. You haven't been authorized to share it with the world. Until you have permission to do so, you should not post your notes on Wikipedia.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
This is not what Wikipedia is for but you can use a [*personal* Wiki](https://en.wikipedia.org/wiki/Personal_wiki). There are several ways to do this. You can actually run a personal webserver on your own machine and access it like any Wiki. There are several open source projects that provide source code for such websites. You can also use applications that are standalone. Lots and lots available out there. I sometimes use [Zim](https://zim-wiki.org/) for this kind of thing (everyone has different ways of working and it's worth trying out all the options to get what works best for their own needs). > > I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well. > > > Wikipedia aims to be an *authoritative* source of information just like any major encyclopedia. Whether you consider it successful in that regard is neither here nor there. You have to be writing articles that you have a good faith reason to think your material is accurate and precise. Your notes will unlikely to be that. You could even end up banned as the site is moderated and they don't like people abusing the site.
**tl;dr**: In theory this could be useful for all concerned. If you have bags of time and patience, including patience with people, you are more likely to succeed, but there's no guarantee. Is it "advisable"? Well I wouldn't *advise* it, for several reasons, which I will come to in a moment. But there is benefit if done properly. * Firstly in ensuring that the content is covered you are improving Wikipedia. * Secondly in the process you are revising your knowledge from the lectures and getting supporting information from both Wikipedia, and the references you need (which won't be *just* the course text book) - and other reading you will do to make your edits good. As to the negative reasons: * It's important that each article is reasonably balanced, your professor may have an idiosyncratic approach, or be on one side of an academic dispute, or just be plain biased * You may have to deal with gatekeeping behaviour from Wikipedians. In particular you may need to go through the [Articles For Creation process](https://en.wikipedia.org/wiki/Wikipedia:Articles_for_creation) which was designed to make it easier (or at least less traumatic) for new users to create articles, but arguably sometimes has the opposite effect * You may risk being drawn off into side-tracks that are not relevant to your course * The articles you edit or create may change (or even be deleted) leaving you without your "notes" (though you can keep copies, or links to specific versions of pages that still exist) * Wikipedia is not keen on single-source articles, so you would need to spend time on other sources (which is a good idea anyway). * Special sourcing requirements apply to [medical claims](https://en.wikipedia.org/wiki/Wikipedia:Identifying_reliable_sources_(medicine)), essentially requiring recent high-standard review articles as sources where feasible. Another comment, somewhat neutral, perhaps: if a section of an article expands out of proportion this is called [undue weight](https://en.wikipedia.org/wiki/Wikipedia:Neutral_point_of_view#Due_and_undue_weight) - provided the matter is sufficiently well sourced it should be split off into a separate article, leaving a summary behind. There is, however, no guarantee that this will happen. Good luck, whichever path you take.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
Other have already pointed out many valid reasons why to not abuse Wikipedia for personal note making. However, one more reason comes to mind: *You have no guarantee that someday somebody will alter your notes.* Wikipedia is written by everybody. Granted, there is a review process, which incidentely might also prevent you yourself from making you notes. Reviewers might question the relevant/quality/ and opt to delete your notes
**tl;dr**: In theory this could be useful for all concerned. If you have bags of time and patience, including patience with people, you are more likely to succeed, but there's no guarantee. Is it "advisable"? Well I wouldn't *advise* it, for several reasons, which I will come to in a moment. But there is benefit if done properly. * Firstly in ensuring that the content is covered you are improving Wikipedia. * Secondly in the process you are revising your knowledge from the lectures and getting supporting information from both Wikipedia, and the references you need (which won't be *just* the course text book) - and other reading you will do to make your edits good. As to the negative reasons: * It's important that each article is reasonably balanced, your professor may have an idiosyncratic approach, or be on one side of an academic dispute, or just be plain biased * You may have to deal with gatekeeping behaviour from Wikipedians. In particular you may need to go through the [Articles For Creation process](https://en.wikipedia.org/wiki/Wikipedia:Articles_for_creation) which was designed to make it easier (or at least less traumatic) for new users to create articles, but arguably sometimes has the opposite effect * You may risk being drawn off into side-tracks that are not relevant to your course * The articles you edit or create may change (or even be deleted) leaving you without your "notes" (though you can keep copies, or links to specific versions of pages that still exist) * Wikipedia is not keen on single-source articles, so you would need to spend time on other sources (which is a good idea anyway). * Special sourcing requirements apply to [medical claims](https://en.wikipedia.org/wiki/Wikipedia:Identifying_reliable_sources_(medicine)), essentially requiring recent high-standard review articles as sources where feasible. Another comment, somewhat neutral, perhaps: if a section of an article expands out of proportion this is called [undue weight](https://en.wikipedia.org/wiki/Wikipedia:Neutral_point_of_view#Due_and_undue_weight) - provided the matter is sufficiently well sourced it should be split off into a separate article, leaving a summary behind. There is, however, no guarantee that this will happen. Good luck, whichever path you take.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
This is not what Wikipedia is for but you can use a [*personal* Wiki](https://en.wikipedia.org/wiki/Personal_wiki). There are several ways to do this. You can actually run a personal webserver on your own machine and access it like any Wiki. There are several open source projects that provide source code for such websites. You can also use applications that are standalone. Lots and lots available out there. I sometimes use [Zim](https://zim-wiki.org/) for this kind of thing (everyone has different ways of working and it's worth trying out all the options to get what works best for their own needs). > > I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well. > > > Wikipedia aims to be an *authoritative* source of information just like any major encyclopedia. Whether you consider it successful in that regard is neither here nor there. You have to be writing articles that you have a good faith reason to think your material is accurate and precise. Your notes will unlikely to be that. You could even end up banned as the site is moderated and they don't like people abusing the site.
I used to do this to some extent, that is, adding new things I learned from books and articles to the relevant wikipedia entries (the [Schur polynomial entry](https://www.wikiwand.com/en/Schur_polynomial) is perhaps my main victim). However, I quickly realized that I wanted to add information which is of interest for people in my field, but is perhaps somewhat too specific for wikipedia. Moreover, I wanted to be able to use LaTeX syntax for more general things (tables, etc). So, I did what StephenG suggested, and made [my own web-page about symmetric functions](https://www.symmetricfunctions.com/) which is publicly available (but not editable by anyone but me). I occasionally get emails from researchers suggesting edits (where I have made some typo), or other inquiries.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
I used to do this to some extent, that is, adding new things I learned from books and articles to the relevant wikipedia entries (the [Schur polynomial entry](https://www.wikiwand.com/en/Schur_polynomial) is perhaps my main victim). However, I quickly realized that I wanted to add information which is of interest for people in my field, but is perhaps somewhat too specific for wikipedia. Moreover, I wanted to be able to use LaTeX syntax for more general things (tables, etc). So, I did what StephenG suggested, and made [my own web-page about symmetric functions](https://www.symmetricfunctions.com/) which is publicly available (but not editable by anyone but me). I occasionally get emails from researchers suggesting edits (where I have made some typo), or other inquiries.
The lecture material was provided for you and your classmates. You haven't been authorized to share it with the world. Until you have permission to do so, you should not post your notes on Wikipedia.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
No, this is not a good idea. Wikipedia articles and the kind of notes you'd write while following a lecture are very different types of text. Audience: A Wikipedia article should be written for a general public, your notes are written for future-you. Context: A Wikipedia article would start much more with a blank slate for context, your notes fit into the surrounding lecture materials. Level of detail: Your notes may often be so specific that the corresponding Wikipedia article would get deleted/heavily abridged for lack of notability. Expert-level of the author: You write notes at the beginning of your journey through new material. The appropriate time to consider writing a Wikipedia article would be once you have actually mastered it. This is not to say that writing/editing Wikipedia articles cannot be a great way to solidify your topic-mastery in a university course while simultaneously doing some good for the general public. But this cannot replace the role of note-taking.
The lecture material was provided for you and your classmates. You haven't been authorized to share it with the world. Until you have permission to do so, you should not post your notes on Wikipedia.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
No, this is not a good idea. Wikipedia articles and the kind of notes you'd write while following a lecture are very different types of text. Audience: A Wikipedia article should be written for a general public, your notes are written for future-you. Context: A Wikipedia article would start much more with a blank slate for context, your notes fit into the surrounding lecture materials. Level of detail: Your notes may often be so specific that the corresponding Wikipedia article would get deleted/heavily abridged for lack of notability. Expert-level of the author: You write notes at the beginning of your journey through new material. The appropriate time to consider writing a Wikipedia article would be once you have actually mastered it. This is not to say that writing/editing Wikipedia articles cannot be a great way to solidify your topic-mastery in a university course while simultaneously doing some good for the general public. But this cannot replace the role of note-taking.
This is not what Wikipedia is for but you can use a [*personal* Wiki](https://en.wikipedia.org/wiki/Personal_wiki). There are several ways to do this. You can actually run a personal webserver on your own machine and access it like any Wiki. There are several open source projects that provide source code for such websites. You can also use applications that are standalone. Lots and lots available out there. I sometimes use [Zim](https://zim-wiki.org/) for this kind of thing (everyone has different ways of working and it's worth trying out all the options to get what works best for their own needs). > > I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well. > > > Wikipedia aims to be an *authoritative* source of information just like any major encyclopedia. Whether you consider it successful in that regard is neither here nor there. You have to be writing articles that you have a good faith reason to think your material is accurate and precise. Your notes will unlikely to be that. You could even end up banned as the site is moderated and they don't like people abusing the site.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
Other have already pointed out many valid reasons why to not abuse Wikipedia for personal note making. However, one more reason comes to mind: *You have no guarantee that someday somebody will alter your notes.* Wikipedia is written by everybody. Granted, there is a review process, which incidentely might also prevent you yourself from making you notes. Reviewers might question the relevant/quality/ and opt to delete your notes
Please, no. I spend so much time fixing things that students believe that they heard in lectures on the German Wikipedia. Excellent points have been made above. I suggest installing <https://bitnami.com/stack/mediawiki> on a machine under your control and keep your notes there.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
No, this is not a good idea. Wikipedia articles and the kind of notes you'd write while following a lecture are very different types of text. Audience: A Wikipedia article should be written for a general public, your notes are written for future-you. Context: A Wikipedia article would start much more with a blank slate for context, your notes fit into the surrounding lecture materials. Level of detail: Your notes may often be so specific that the corresponding Wikipedia article would get deleted/heavily abridged for lack of notability. Expert-level of the author: You write notes at the beginning of your journey through new material. The appropriate time to consider writing a Wikipedia article would be once you have actually mastered it. This is not to say that writing/editing Wikipedia articles cannot be a great way to solidify your topic-mastery in a university course while simultaneously doing some good for the general public. But this cannot replace the role of note-taking.
I used to do this to some extent, that is, adding new things I learned from books and articles to the relevant wikipedia entries (the [Schur polynomial entry](https://www.wikiwand.com/en/Schur_polynomial) is perhaps my main victim). However, I quickly realized that I wanted to add information which is of interest for people in my field, but is perhaps somewhat too specific for wikipedia. Moreover, I wanted to be able to use LaTeX syntax for more general things (tables, etc). So, I did what StephenG suggested, and made [my own web-page about symmetric functions](https://www.symmetricfunctions.com/) which is publicly available (but not editable by anyone but me). I occasionally get emails from researchers suggesting edits (where I have made some typo), or other inquiries.
182,330
Some people summarize the content of a lecture to deepen their understanding, but I am thinking about using Wikipedia instead. Specifically, I mean finding the Wikipedia article (in my primary, non-English language) that covers the lecture material and adding any suitable content that the article does not already have. In some cases, this may mean making a new article from scratch. I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well: * It will be more durable to write on Wikipedia than to keep it in a paper notebook. Even more, it could be get even better by someone adding to it, or correcting errors. * Wikipedia is usually found at the top of a google search, so it's easy to find. You don't have to flip through your notes to find it. * Wikipedia requires references, but you can use the textbook you used in the lecture as a reference. Of course, I will be careful not to reprint the textbook or lectures as is. While it has all these advantages, I think the only disadvantage is that it takes a lot of time. Or is there some other reason for not recommending it?
2022/02/13
[ "https://academia.stackexchange.com/questions/182330", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/153356/" ]
This is not what Wikipedia is for but you can use a [*personal* Wiki](https://en.wikipedia.org/wiki/Personal_wiki). There are several ways to do this. You can actually run a personal webserver on your own machine and access it like any Wiki. There are several open source projects that provide source code for such websites. You can also use applications that are standalone. Lots and lots available out there. I sometimes use [Zim](https://zim-wiki.org/) for this kind of thing (everyone has different ways of working and it's worth trying out all the options to get what works best for their own needs). > > I thought of several reasons that writing and editing a Wikipedia article on what you learned would be beneficial not only to other readers, but to yourself as well. > > > Wikipedia aims to be an *authoritative* source of information just like any major encyclopedia. Whether you consider it successful in that regard is neither here nor there. You have to be writing articles that you have a good faith reason to think your material is accurate and precise. Your notes will unlikely to be that. You could even end up banned as the site is moderated and they don't like people abusing the site.
The lecture material was provided for you and your classmates. You haven't been authorized to share it with the world. Until you have permission to do so, you should not post your notes on Wikipedia.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
What you're talking about is a 'push' notification, where the server would pass a notification to the client (a browser) without the client requesting anything. This isnt something which HTTP is naturally capable of, however have a read about [Comet](http://en.wikipedia.org/wiki/Comet_%28programming%29) - this will let you know the current state of what is possible. You may opt for creating a 'heartbeat' on the client side - a polling mechanism which requests from the server every x seconds, and updates the page when new content is found.
When a user submit requests I assume that his request is first stored in the database. So on the admin & user part you use ajax which periodically update data from database (for un-approved data), do some google search on ajax auto-update or Javascript's timeout or similar function. The same process will be involved in user part.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
> > I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. > > > **Instantly** is a very strong term and isn't usually very scalable. For some ideas on how you might implement this I'd recommend you take a look at [Wikipedia's Comet Programming page](http://en.wikipedia.org/wiki/Comet_%28programming%29)
When a user submit requests I assume that his request is first stored in the database. So on the admin & user part you use ajax which periodically update data from database (for un-approved data), do some google search on ajax auto-update or Javascript's timeout or similar function. The same process will be involved in user part.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
I will suggest you take a look at SignalR (<https://github.com/SignalR/SignalR>). It is a framework developed by a few MS developers for doing long polling/notifications from the server. Link for webforms walkthrough - <http://www.infinitelooping.com/blog/2011/10/17/using-signalr/>.
When a user submit requests I assume that his request is first stored in the database. So on the admin & user part you use ajax which periodically update data from database (for un-approved data), do some google search on ajax auto-update or Javascript's timeout or similar function. The same process will be involved in user part.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
You could also look into using a Timer control. It's a client side control that will cause a postback for ASP.NET AJAX applications. Here's a simple tutorial <http://ajax.net-tutorials.com/controls/timer-control/>
When a user submit requests I assume that his request is first stored in the database. So on the admin & user part you use ajax which periodically update data from database (for un-approved data), do some google search on ajax auto-update or Javascript's timeout or similar function. The same process will be involved in user part.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
I will suggest you take a look at SignalR (<https://github.com/SignalR/SignalR>). It is a framework developed by a few MS developers for doing long polling/notifications from the server. Link for webforms walkthrough - <http://www.infinitelooping.com/blog/2011/10/17/using-signalr/>.
What you're talking about is a 'push' notification, where the server would pass a notification to the client (a browser) without the client requesting anything. This isnt something which HTTP is naturally capable of, however have a read about [Comet](http://en.wikipedia.org/wiki/Comet_%28programming%29) - this will let you know the current state of what is possible. You may opt for creating a 'heartbeat' on the client side - a polling mechanism which requests from the server every x seconds, and updates the page when new content is found.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
You could also look into using a Timer control. It's a client side control that will cause a postback for ASP.NET AJAX applications. Here's a simple tutorial <http://ajax.net-tutorials.com/controls/timer-control/>
What you're talking about is a 'push' notification, where the server would pass a notification to the client (a browser) without the client requesting anything. This isnt something which HTTP is naturally capable of, however have a read about [Comet](http://en.wikipedia.org/wiki/Comet_%28programming%29) - this will let you know the current state of what is possible. You may opt for creating a 'heartbeat' on the client side - a polling mechanism which requests from the server every x seconds, and updates the page when new content is found.
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
I will suggest you take a look at SignalR (<https://github.com/SignalR/SignalR>). It is a framework developed by a few MS developers for doing long polling/notifications from the server. Link for webforms walkthrough - <http://www.infinitelooping.com/blog/2011/10/17/using-signalr/>.
> > I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. > > > **Instantly** is a very strong term and isn't usually very scalable. For some ideas on how you might implement this I'd recommend you take a look at [Wikipedia's Comet Programming page](http://en.wikipedia.org/wiki/Comet_%28programming%29)
7,759,095
I know the question sounds too vague so let me explain exactly what I want to implement. I have a WebApplication that many users log into to submit a request, Request in my project is a form that accepts some information from the user and when he click submit, it reflects on the administrator page. then the admin can grant or decline this request. and of course the result need to be sent to the user's 'Pending Requests' page. this process is all about time so I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. (kind of like facebook notification system). I hope my problem is know clear. I understand that there are many ways to implement this and I have a very small knowledge about them. But I just want you guys to recommend an effecient way because I'm sure that the good ways to do this is limited. Thanks in advance everybody :)
2011/10/13
[ "https://Stackoverflow.com/questions/7759095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315625/" ]
You could also look into using a Timer control. It's a client side control that will cause a postback for ASP.NET AJAX applications. Here's a simple tutorial <http://ajax.net-tutorials.com/controls/timer-control/>
> > I need a clean and efficient way to show the admin the requests instantly and for the user to see the admin's response instantly. > > > **Instantly** is a very strong term and isn't usually very scalable. For some ideas on how you might implement this I'd recommend you take a look at [Wikipedia's Comet Programming page](http://en.wikipedia.org/wiki/Comet_%28programming%29)
9,777,206
I have a text file which contains following ``` Name address phone salary Jack Boston 923-433-666 10000 ``` all the fields are delimited by the spaces. I am trying to write a C# program, this program should read a this text file and then store it in the formatted array. My Array is as follows: ``` address salary ``` When ever I am trying to look in google I get is how to read and write a text file in C#. Thank you very much for your time.
2012/03/19
[ "https://Stackoverflow.com/questions/9777206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278465/" ]
You can use File.ReadAllLines method to load the file into an array. You can then use a for loop to loop through the lines, and the string type's Split method to separate each line into another array, and store the values in your formatted array. Something like: ``` static void Main(string[] args) { var lines = File.ReadAllLines("filename.txt"); for (int i = 0; i < lines.Length; i++) { var fields = lines[i].Split(' '); } } ```
Do not reinvent the wheel. Can use for example [fast csv reader](http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader) where you can specify a `delimeter` you need. There are plenty others on internet like that, just search and pick that one which fits your needs.
9,777,206
I have a text file which contains following ``` Name address phone salary Jack Boston 923-433-666 10000 ``` all the fields are delimited by the spaces. I am trying to write a C# program, this program should read a this text file and then store it in the formatted array. My Array is as follows: ``` address salary ``` When ever I am trying to look in google I get is how to read and write a text file in C#. Thank you very much for your time.
2012/03/19
[ "https://Stackoverflow.com/questions/9777206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278465/" ]
Do not reinvent the wheel. Can use for example [fast csv reader](http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader) where you can specify a `delimeter` you need. There are plenty others on internet like that, just search and pick that one which fits your needs.
This answer assumes you don't know how much whitespace is between each string in a given line. ``` // Method to split a line into a string array separated by whitespace private string[] Splitter(string input) { return Regex.Split(intput, @"\W+"); } // Another code snippet to read the file and break the lines into arrays // of strings and store the arrays in a list. List<String[]> arrayList = new List<String[]>(); using (FileStream fStream = File.OpenRead(@"C:\SomeDirectory\SomeFile.txt")) { using(TextReader reader = new StreamReader(fStream)) { string line = ""; while(!String.IsNullOrEmpty(line = reader.ReadLine())) { arrayList.Add(Splitter(line)); } } } ```
9,777,206
I have a text file which contains following ``` Name address phone salary Jack Boston 923-433-666 10000 ``` all the fields are delimited by the spaces. I am trying to write a C# program, this program should read a this text file and then store it in the formatted array. My Array is as follows: ``` address salary ``` When ever I am trying to look in google I get is how to read and write a text file in C#. Thank you very much for your time.
2012/03/19
[ "https://Stackoverflow.com/questions/9777206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1278465/" ]
You can use File.ReadAllLines method to load the file into an array. You can then use a for loop to loop through the lines, and the string type's Split method to separate each line into another array, and store the values in your formatted array. Something like: ``` static void Main(string[] args) { var lines = File.ReadAllLines("filename.txt"); for (int i = 0; i < lines.Length; i++) { var fields = lines[i].Split(' '); } } ```
This answer assumes you don't know how much whitespace is between each string in a given line. ``` // Method to split a line into a string array separated by whitespace private string[] Splitter(string input) { return Regex.Split(intput, @"\W+"); } // Another code snippet to read the file and break the lines into arrays // of strings and store the arrays in a list. List<String[]> arrayList = new List<String[]>(); using (FileStream fStream = File.OpenRead(@"C:\SomeDirectory\SomeFile.txt")) { using(TextReader reader = new StreamReader(fStream)) { string line = ""; while(!String.IsNullOrEmpty(line = reader.ReadLine())) { arrayList.Add(Splitter(line)); } } } ```
17,202,066
The code bellow is a part of an activity of an Android app. I am using Jena(Androjena) to query rdf files. That part works fine. The problem is that i am trying to iterate through the results and store the in a two-dimensional array. Where the columns and rows should be like: ``` ///////////////// Adam /Sandler/43 Kate /Sandler/22 Mike /Jasonss/13 ///////////////// ``` Code: ``` enter code here // Query uses an external SPARQL endpoint for processing // This is the syntax for that type of query QueryExecution qe = QueryExecutionFactory.sparqlService(sparqlEndpointUri, query); // Execute the query and obtain results ResultSet resultSet = qe.execSelect(); // Setup a place to house results for output StringBuffer results = new StringBuffer(); // Get the column names (the aliases supplied in the SELECT clause) List<String> columnNames = resultSet.getResultVars(); int i=0; int j=0; String results1[][] = new String[i][j]; // Iterate through all resulting rows while (resultSet.hasNext()) { // Get the next result row QuerySolution solution = resultSet.next(); results1 = new String[i][columnNames.size()]; // Iterate through the columns for (String var : columnNames) { // Add the column label to the StringBuffer results.append(var + ": "); // Add the returned row/column data to the StringBuffer // Data value will be null if optional and not present if (solution.get(var) == null) { results.append("{null}"); // Test whether the returned value is a literal value } else if (solution.get(var).isLiteral()) { results.append(solution.getLiteral(var).toString()); results1[resultSet.getRowNumber()][j]=solution.getLiteral(var).toString(); j++; // Otherwise the returned value is a URI } else { results.append(solution.getResource(var).getURI().toString()); results1[resultSet.getRowNumber()][j]=solution.getResource(var).getURI().toString(); j++; } results.append('\n'); } results.append("-----------------\n"); i++; } ``` PS. Ignore the string buffer.
2013/06/19
[ "https://Stackoverflow.com/questions/17202066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146142/" ]
Since you do not know in advance the size of the result set, you cannot use an array. Use an `ArrayList<String[]>` instead and add `String[]` elements to the list as you read rows from the resultSet. ``` ArrayList<String[]> results1 = new ArrayList<>(); ``` When you have read all the rows you can still refer to the rows and columns by index if you want, using ``` results1.get(index)[colIndex] ```
The problem is that the array that you create is actually `String results1[][] = new String[i][j];` which is `String results1[][] = new String[0][columnNames.size()];` Then in the `for (String var : columnNames)` loop you increment the value of i and try to set an element to `results1[resultSet.getRowNumber()][j]`. Above you say its a `0,columnNames.size()` array and in the loop you try to access `resultSet.getRowNumber(), j`. `j` is legal here however `resultSet.getRowNumber()` is not.
2,687,931
Is there a closed form for: $$\sum\_{n=0}^\infty \frac{\cos(n)}{(2n+1)(2n+2)} $$ I know it converges through the direct comparison test, and I'm pretty sure there is a closed form, but I'm not entirely certain what it is. Here's what I've done so far: $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1}-\sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} $$ $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n}\cos(n)dx = \Re \int\_{0}^1 \sum\_{n=0}^\infty(x^2e^i)^n dx = \Re \int\_{0}^1 \frac{1}{1-e^ix^2}dx = \Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}}))} $$ $$ \sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n+1}\cos(n)dx=\Re\int\_{0}^1 x\sum\_{n=0}^\infty (x^2e^i)^ndx = \Re \int\_{0}^1 \frac{x}{1-e^ix^2}dx=\Re(-\frac{e^{-i}}{2} \ln|1-e^i|)$$ $$\Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}})}+\frac{e^{-i}}{2} \ln|1-e^i|)$$ After plugging all of this in into Wolfram Alpha, I don't get the right answer, however. Where is the mistake? There could be a lot of things wrong. Edit: I more want to see where my mistake in my work is, rather how to do the problem.
2018/03/12
[ "https://math.stackexchange.com/questions/2687931", "https://math.stackexchange.com", "https://math.stackexchange.com/users/457359/" ]
First, we evaluate $\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1}$. To do so, we note that for $|z|<1$ $$\sum\_{n=0}^\infty \frac{z^{2n+1}}{2n+1}=\text{arctanh}(z)\tag 1$$ In fact, the series in $(1)$ converges for all $|z|\le 1$, $z\ne 1$. Therefore, letting $z=e^{ix}$, $x\ne 2k\pi$, reveals $$\sum\_{n=0}^\infty \frac{e^{i(2n+1)x}}{2n+1}=\text {arctanh}(e^{ix})\tag 2$$ for $x\ne 2k\pi$. Setting $x=1/2$ in $(2)$ yields $$\text{arctanh}(e^{i/2})=e^{i/2}\sum\_{n=0}^\infty \frac{e^{in}}{2n+1}\tag3$$ whence we find $$\begin{align} \sum\_{n=0}\frac{\cos(n)}{2n+1}&=\text{Re}\left(e^{-i/2}\text{arctanh}(e^{i/2})\right)\\\\ &=\text{Re}\left(e^{-i/2}\frac12\log\left(\frac{1+e^{i/2}}{1-e^{i/2}}\right)\right)\\\\ &=\frac12\text{Re}\left(e^{-i/2}\log\left(i\cot(1/4)\right)\right)\\\\ &=\frac12 \cos(1/2)\log(\cot(1/4))+\frac\pi4 \sin(1/2) \end{align}$$ --- --- Next, we evaluate $\sum\_{n=0}^\infty \frac{\cos(n)}{2n+2}=\frac12 \sum\_{n=0}^\infty \frac{\cos(n)}{n+1}$. To do so, we note that for $|z|\le 1$, $z\ne1$ $$\begin{align} \sum\_{n=0}^\infty \frac{z^n}{n+1}&=\frac1z \sum\_{n=1}^\infty \frac{z^n}{n}\\\\ &=-\frac{\log(1-z)}{z}\tag4 \end{align}$$ Using $(4)$, we find $$\begin{align} \sum\_{n=0}^\infty \frac{\cos(n)}{2n+2}&=-\frac12\text{Re}\left(\frac{\log(1-e^{i})}{e^i}\right)\\\\ &=-\frac14 \cos(1)\log(2-2\cos(1))+\frac12\sin(1)\arctan\left(\frac{\sin(1)}{1-\cos(1)}\right)\\\\ &=-\frac12\cos(1)\log(2)-\frac12\cos(1)\log(\sin(1/2))+\sin(1)\left(\frac{\pi-1}{4}\right) \end{align}$$
Hint: $$\sum\_{n=0}^\infty\dfrac{\cos n}{n+2}=$$ Real part of $$e^{-2i}\sum\_{n=0}^\infty\dfrac{(e^i)^{n+2}}{n+2}$$ $$=e^{-2i}\left(-\ln(1-e^i)-\dfrac{e^i}{1}\right)$$ Use [How to prove Euler's formula: $e^{i\varphi}=\cos(\varphi) +i\sin(\varphi)$?](https://math.stackexchange.com/questions/3510/how-to-prove-eulers-formula-ei-varphi-cos-varphi-i-sin-varphi) and $$\ln(1-e^{2it})=\ln(-i)+it+\ln(2\sin t)$$
2,687,931
Is there a closed form for: $$\sum\_{n=0}^\infty \frac{\cos(n)}{(2n+1)(2n+2)} $$ I know it converges through the direct comparison test, and I'm pretty sure there is a closed form, but I'm not entirely certain what it is. Here's what I've done so far: $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1}-\sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} $$ $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n}\cos(n)dx = \Re \int\_{0}^1 \sum\_{n=0}^\infty(x^2e^i)^n dx = \Re \int\_{0}^1 \frac{1}{1-e^ix^2}dx = \Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}}))} $$ $$ \sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n+1}\cos(n)dx=\Re\int\_{0}^1 x\sum\_{n=0}^\infty (x^2e^i)^ndx = \Re \int\_{0}^1 \frac{x}{1-e^ix^2}dx=\Re(-\frac{e^{-i}}{2} \ln|1-e^i|)$$ $$\Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}})}+\frac{e^{-i}}{2} \ln|1-e^i|)$$ After plugging all of this in into Wolfram Alpha, I don't get the right answer, however. Where is the mistake? There could be a lot of things wrong. Edit: I more want to see where my mistake in my work is, rather how to do the problem.
2018/03/12
[ "https://math.stackexchange.com/questions/2687931", "https://math.stackexchange.com", "https://math.stackexchange.com/users/457359/" ]
For any $z\in\mathbb{C}$ such that $\|z\|\leq 1$ the series $\sum\_{n\geq 1}\frac{z^n}{(2n+1)(2n+2)}$ is absolutely convergent. We may notice that $$ f(w)=\sum\_{n\geq 0}\frac{w^{2n+2}}{(2n+1)(2n+2)}=\int\_{0}^{w}\int\_{0}^{v}\sum\_{n\geq 1}u^{2n}\,du\,dv=\int\_{0}^{w}\int\_{0}^{v}\frac{du}{1-u^2}\,dv $$ is a holomorphic function in the region $\|w\|<1$, where it equals $w\,\text{arctanh}(w)+\frac{1}{2}\log(1-w^2)$. From $$ \sum\_{n\geq 0}\frac{w^{2n}}{(2n+1)(2n+2)}=\frac{(1+w)\log(1+w)+(1-w)\log(1-w)}{2w^2} $$ we get $$\sum\_{n\geq 0}\frac{\rho^{2n} \cos(n)}{(2n+1)(2n+2)}=\text{Re}\frac{(1+\rho e^{i/2})\log(1+\rho e^{i/2})+(1-\rho e^{i/2})\log(1-\rho e^{i/2})}{2\rho^2 e^{i}} $$ for any $\rho\in(0,1)$. By considering the limit of the RHS as $\rho\to 1^-$ and by invoking the dominated convergence theorem we get $$ \sum\_{n\geq 0}\frac{\cos(n)}{(2n+1)(2n+2)}=\tfrac{1}{2}\cos\tfrac{1}{2}\log\cot\tfrac14+\tfrac12 \cos 1\log\left(2\sin\tfrac12\right)+\tfrac{\pi}{4}\sin\tfrac12+\tfrac{1-\pi}{4}\sin 1. $$ The RHS is approximately $0.513683$.
Hint: $$\sum\_{n=0}^\infty\dfrac{\cos n}{n+2}=$$ Real part of $$e^{-2i}\sum\_{n=0}^\infty\dfrac{(e^i)^{n+2}}{n+2}$$ $$=e^{-2i}\left(-\ln(1-e^i)-\dfrac{e^i}{1}\right)$$ Use [How to prove Euler's formula: $e^{i\varphi}=\cos(\varphi) +i\sin(\varphi)$?](https://math.stackexchange.com/questions/3510/how-to-prove-eulers-formula-ei-varphi-cos-varphi-i-sin-varphi) and $$\ln(1-e^{2it})=\ln(-i)+it+\ln(2\sin t)$$
2,687,931
Is there a closed form for: $$\sum\_{n=0}^\infty \frac{\cos(n)}{(2n+1)(2n+2)} $$ I know it converges through the direct comparison test, and I'm pretty sure there is a closed form, but I'm not entirely certain what it is. Here's what I've done so far: $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1}-\sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} $$ $$\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n}\cos(n)dx = \Re \int\_{0}^1 \sum\_{n=0}^\infty(x^2e^i)^n dx = \Re \int\_{0}^1 \frac{1}{1-e^ix^2}dx = \Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}}))} $$ $$ \sum\_{n=0}^\infty \frac{\cos(n)}{2n+2} = \int\_{0}^1\sum\_{n=0}^\infty x^{2n+1}\cos(n)dx=\Re\int\_{0}^1 x\sum\_{n=0}^\infty (x^2e^i)^ndx = \Re \int\_{0}^1 \frac{x}{1-e^ix^2}dx=\Re(-\frac{e^{-i}}{2} \ln|1-e^i|)$$ $$\Re({e^{-\frac{i}{2}}\operatorname{arctanh(e^\frac{i}{2}})}+\frac{e^{-i}}{2} \ln|1-e^i|)$$ After plugging all of this in into Wolfram Alpha, I don't get the right answer, however. Where is the mistake? There could be a lot of things wrong. Edit: I more want to see where my mistake in my work is, rather how to do the problem.
2018/03/12
[ "https://math.stackexchange.com/questions/2687931", "https://math.stackexchange.com", "https://math.stackexchange.com/users/457359/" ]
First, we evaluate $\sum\_{n=0}^\infty \frac{\cos(n)}{2n+1}$. To do so, we note that for $|z|<1$ $$\sum\_{n=0}^\infty \frac{z^{2n+1}}{2n+1}=\text{arctanh}(z)\tag 1$$ In fact, the series in $(1)$ converges for all $|z|\le 1$, $z\ne 1$. Therefore, letting $z=e^{ix}$, $x\ne 2k\pi$, reveals $$\sum\_{n=0}^\infty \frac{e^{i(2n+1)x}}{2n+1}=\text {arctanh}(e^{ix})\tag 2$$ for $x\ne 2k\pi$. Setting $x=1/2$ in $(2)$ yields $$\text{arctanh}(e^{i/2})=e^{i/2}\sum\_{n=0}^\infty \frac{e^{in}}{2n+1}\tag3$$ whence we find $$\begin{align} \sum\_{n=0}\frac{\cos(n)}{2n+1}&=\text{Re}\left(e^{-i/2}\text{arctanh}(e^{i/2})\right)\\\\ &=\text{Re}\left(e^{-i/2}\frac12\log\left(\frac{1+e^{i/2}}{1-e^{i/2}}\right)\right)\\\\ &=\frac12\text{Re}\left(e^{-i/2}\log\left(i\cot(1/4)\right)\right)\\\\ &=\frac12 \cos(1/2)\log(\cot(1/4))+\frac\pi4 \sin(1/2) \end{align}$$ --- --- Next, we evaluate $\sum\_{n=0}^\infty \frac{\cos(n)}{2n+2}=\frac12 \sum\_{n=0}^\infty \frac{\cos(n)}{n+1}$. To do so, we note that for $|z|\le 1$, $z\ne1$ $$\begin{align} \sum\_{n=0}^\infty \frac{z^n}{n+1}&=\frac1z \sum\_{n=1}^\infty \frac{z^n}{n}\\\\ &=-\frac{\log(1-z)}{z}\tag4 \end{align}$$ Using $(4)$, we find $$\begin{align} \sum\_{n=0}^\infty \frac{\cos(n)}{2n+2}&=-\frac12\text{Re}\left(\frac{\log(1-e^{i})}{e^i}\right)\\\\ &=-\frac14 \cos(1)\log(2-2\cos(1))+\frac12\sin(1)\arctan\left(\frac{\sin(1)}{1-\cos(1)}\right)\\\\ &=-\frac12\cos(1)\log(2)-\frac12\cos(1)\log(\sin(1/2))+\sin(1)\left(\frac{\pi-1}{4}\right) \end{align}$$
For any $z\in\mathbb{C}$ such that $\|z\|\leq 1$ the series $\sum\_{n\geq 1}\frac{z^n}{(2n+1)(2n+2)}$ is absolutely convergent. We may notice that $$ f(w)=\sum\_{n\geq 0}\frac{w^{2n+2}}{(2n+1)(2n+2)}=\int\_{0}^{w}\int\_{0}^{v}\sum\_{n\geq 1}u^{2n}\,du\,dv=\int\_{0}^{w}\int\_{0}^{v}\frac{du}{1-u^2}\,dv $$ is a holomorphic function in the region $\|w\|<1$, where it equals $w\,\text{arctanh}(w)+\frac{1}{2}\log(1-w^2)$. From $$ \sum\_{n\geq 0}\frac{w^{2n}}{(2n+1)(2n+2)}=\frac{(1+w)\log(1+w)+(1-w)\log(1-w)}{2w^2} $$ we get $$\sum\_{n\geq 0}\frac{\rho^{2n} \cos(n)}{(2n+1)(2n+2)}=\text{Re}\frac{(1+\rho e^{i/2})\log(1+\rho e^{i/2})+(1-\rho e^{i/2})\log(1-\rho e^{i/2})}{2\rho^2 e^{i}} $$ for any $\rho\in(0,1)$. By considering the limit of the RHS as $\rho\to 1^-$ and by invoking the dominated convergence theorem we get $$ \sum\_{n\geq 0}\frac{\cos(n)}{(2n+1)(2n+2)}=\tfrac{1}{2}\cos\tfrac{1}{2}\log\cot\tfrac14+\tfrac12 \cos 1\log\left(2\sin\tfrac12\right)+\tfrac{\pi}{4}\sin\tfrac12+\tfrac{1-\pi}{4}\sin 1. $$ The RHS is approximately $0.513683$.
40,516,055
I need to create 4 output files. I currently obtain a single file. ``` String url1 = "www.xxxx.com"; String url2 = "www.xxxx.com"; String url3 = "www.xxxx.com"; String url4 = "www.xxxx.com"; String tableaurl[] = {url1,url2,url3,url4}; for(String url : tableaurl) { String encodedString = UrlUtils.encodeAnchor(url); System.out.format("%s\n", encodedString); URL myURL = new URL(encodedString); String userpass = "username" + ":" + "password"; String basicAuth = "Basic " + Base64.encode(userpass.getBytes("UTF-8")); URLConnection myURLConnection = myURL.openConnection(proxy); myURLConnection.setRequestProperty("Authorization", basicAuth); myURLConnection.connect(); InputStream is = myURLConnection.getInputStream(); BufferedReader br = null; File dir = new File(home + File.separator + "collected" + File.separator +"test"); dir.mkdirs(); File file = new File(dir + File.separator + date.getTime()); FileOutputStream fos = new FileOutputStream(file); StringBuilder sb = new StringBuilder(); ```
2016/11/09
[ "https://Stackoverflow.com/questions/40516055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5909095/" ]
If you want 4 files, then use 4 distinct names. ``` int i = 0; // Some number counter for(String url : tableaurl) { // other code... i++; File file = new File(dir + File.separator + i + "_" + date.getTime()); ```
You should use different date object to create different file name. Currently you are using a single object which returns the same time each time you call get time(). You can use new Date().get time().
32,836,103
I am working on Adobe CQ. I created 2-3 versions(1.2,1.2,1.3) for a particular page in my author instance. Now I tried to package my content page and installed it in another instance. I couldn't see the versions of the page which I installed in another instance. Can anyone help me out doing this?? I want to migrate my content pages along with their versions from one CQ instance to another??
2015/09/29
[ "https://Stackoverflow.com/questions/32836103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5387245/" ]
We are in the same situation. You can extract prior version details using the packaging approach, but you will be precluded from reloading them in due to the new Oak security model. The next issue is that you would need to extract and transform the data, and then reinsert due to the node ID's potentially differing, especially if you are using partial data sets to extract. Where we have gotten to, and are proving now, is to use the new migration tool to move content from instance to instance, which purportedly has a version extract tool. I will update details here when we get our results back. --- UPDATE: We have tested the CRX2OAK migration tool, and it indeed does move versions across. Using the tool, you can specify filters to only migrate a subset of content, which will then drag the version details across as well. It seems this approach works quite well for both single tenancy and multi tenancy approaches as it used to using a package for content. Unfortunately, it can't be used as a portable backup system, as it is an instance to instance solution. It does, however, work well for blue/green deployment strategies.
Versions are stored by path '/jcr:system/jcr:versionStorage' in AEM. To transfer pages with their versions just create a package with filters for content which you want to move and the version storage path as well, download package and install in other AEM.
32,836,103
I am working on Adobe CQ. I created 2-3 versions(1.2,1.2,1.3) for a particular page in my author instance. Now I tried to package my content page and installed it in another instance. I couldn't see the versions of the page which I installed in another instance. Can anyone help me out doing this?? I want to migrate my content pages along with their versions from one CQ instance to another??
2015/09/29
[ "https://Stackoverflow.com/questions/32836103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5387245/" ]
We are in the same situation. You can extract prior version details using the packaging approach, but you will be precluded from reloading them in due to the new Oak security model. The next issue is that you would need to extract and transform the data, and then reinsert due to the node ID's potentially differing, especially if you are using partial data sets to extract. Where we have gotten to, and are proving now, is to use the new migration tool to move content from instance to instance, which purportedly has a version extract tool. I will update details here when we get our results back. --- UPDATE: We have tested the CRX2OAK migration tool, and it indeed does move versions across. Using the tool, you can specify filters to only migrate a subset of content, which will then drag the version details across as well. It seems this approach works quite well for both single tenancy and multi tenancy approaches as it used to using a package for content. Unfortunately, it can't be used as a portable backup system, as it is an instance to instance solution. It does, however, work well for blue/green deployment strategies.
If anyone comes across this question like me, here is the summarised answer: You can use crx2oak utility available from link below to migrate pages and page version across instances: <https://repo.adobe.com/nexus/content/groups/public/com/adobe/granite/crx2oak/> This is a powerful utility with multiple uses (especially in upgrades) as documented in links below: <https://docs.adobe.com/docs/en/aem/6-2/deploy/upgrade/using-crx2oak.html> <https://jackrabbit.apache.org/oak/docs/migration.html> The source and destination repositories need to be offline while running this utility so best to plan ahead for this type of migration. HTH
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
* `InputLayer` is a layer. * `Input` is a tensor. You can only call layers passing tensors to them. **The idea is:** ``` outputTensor = SomeLayer(inputTensor) ``` So, only `Input` can be passed because it's a tensor. Honestly, I have no idea about the reason for the existence of `InputLayer`. Maybe it's supposed to be used internally. I never used it, and it seems I'll never need it.
According to tensorflow website, "It is generally recommend to use the functional layer API via Input, (which creates an InputLayer) without directly using InputLayer." Know more at this page [here](https://www.tensorflow.org/api_docs/python/tf/keras/layers/InputLayer)
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
* `InputLayer` is a layer. * `Input` is a tensor. You can only call layers passing tensors to them. **The idea is:** ``` outputTensor = SomeLayer(inputTensor) ``` So, only `Input` can be passed because it's a tensor. Honestly, I have no idea about the reason for the existence of `InputLayer`. Maybe it's supposed to be used internally. I never used it, and it seems I'll never need it.
Input: Used for creating a functional model ``` inp=tf.keras.Input(shape=[?,?,?]) x=layers.Conv2D(.....)(inp) ``` Input Layer: used for creating a sequential model ``` x=tf.keras.Sequential() x.add(tf.keras.layers.InputLayer(shape=[?,?,?])) ``` And the other difference is that > > When using InputLayer with the Keras Sequential model, it can be skipped by moving the input\_shape parameter to the first layer after the InputLayer. > > > That is in sequential model you can skip the InputLayer and specify the shape directly in the first layer. i.e From this ``` model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(4,)), tf.keras.layers.Dense(8)]) ``` To this ``` model = tf.keras.Sequential([ tf.keras.layers.Dense(8, input_shape=(4,))]) ```
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
* `InputLayer` is a layer. * `Input` is a tensor. You can only call layers passing tensors to them. **The idea is:** ``` outputTensor = SomeLayer(inputTensor) ``` So, only `Input` can be passed because it's a tensor. Honestly, I have no idea about the reason for the existence of `InputLayer`. Maybe it's supposed to be used internally. I never used it, and it seems I'll never need it.
To define it in simple words: `keras.layers.Input` is used to instantiate a Keras Tensor. In this case, your data is probably not a tf tensor, maybe an `np` array. On the other hand, `keras.layers.InputLayer` is a layer where your data is already defined as one of the tf tensor types, i.e., can be a ragged tensor or constant or other types. I hope this helps!
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
According to tensorflow website, "It is generally recommend to use the functional layer API via Input, (which creates an InputLayer) without directly using InputLayer." Know more at this page [here](https://www.tensorflow.org/api_docs/python/tf/keras/layers/InputLayer)
Input: Used for creating a functional model ``` inp=tf.keras.Input(shape=[?,?,?]) x=layers.Conv2D(.....)(inp) ``` Input Layer: used for creating a sequential model ``` x=tf.keras.Sequential() x.add(tf.keras.layers.InputLayer(shape=[?,?,?])) ``` And the other difference is that > > When using InputLayer with the Keras Sequential model, it can be skipped by moving the input\_shape parameter to the first layer after the InputLayer. > > > That is in sequential model you can skip the InputLayer and specify the shape directly in the first layer. i.e From this ``` model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(4,)), tf.keras.layers.Dense(8)]) ``` To this ``` model = tf.keras.Sequential([ tf.keras.layers.Dense(8, input_shape=(4,))]) ```
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
According to tensorflow website, "It is generally recommend to use the functional layer API via Input, (which creates an InputLayer) without directly using InputLayer." Know more at this page [here](https://www.tensorflow.org/api_docs/python/tf/keras/layers/InputLayer)
To define it in simple words: `keras.layers.Input` is used to instantiate a Keras Tensor. In this case, your data is probably not a tf tensor, maybe an `np` array. On the other hand, `keras.layers.InputLayer` is a layer where your data is already defined as one of the tf tensor types, i.e., can be a ragged tensor or constant or other types. I hope this helps!
46,147,019
I made a model using Keras with Tensorflow. I use `Inputlayer` with these lines of code: ``` img1 = tf.placeholder(tf.float32, shape=(None, img_width, img_heigh, img_ch)) first_input = InputLayer(input_tensor=img1, input_shape=(img_width, img_heigh, img_ch)) first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` But I get this error: ``` ValueError: Layer 1st_conv1 was called with an input that isn't a symbolic tensor. Received type: <class 'keras.engine.topology.InputLayer'>. Full input: [<keras.engine.topology.InputLayer object at 0x00000000112170F0>]. All inputs to the layer should be tensors. ``` When I use `Input` like this, it works fine: ``` first_input = Input(tensor=img1, shape=(224, 224, 3), name='1st_input') first_dense = Conv2D(16, 3, 3, activation='relu', border_mode='same', name='1st_conv1')(first_input) ``` What is the difference between `Inputlayer` and `Input`?
2017/09/11
[ "https://Stackoverflow.com/questions/46147019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7148586/" ]
Input: Used for creating a functional model ``` inp=tf.keras.Input(shape=[?,?,?]) x=layers.Conv2D(.....)(inp) ``` Input Layer: used for creating a sequential model ``` x=tf.keras.Sequential() x.add(tf.keras.layers.InputLayer(shape=[?,?,?])) ``` And the other difference is that > > When using InputLayer with the Keras Sequential model, it can be skipped by moving the input\_shape parameter to the first layer after the InputLayer. > > > That is in sequential model you can skip the InputLayer and specify the shape directly in the first layer. i.e From this ``` model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(4,)), tf.keras.layers.Dense(8)]) ``` To this ``` model = tf.keras.Sequential([ tf.keras.layers.Dense(8, input_shape=(4,))]) ```
To define it in simple words: `keras.layers.Input` is used to instantiate a Keras Tensor. In this case, your data is probably not a tf tensor, maybe an `np` array. On the other hand, `keras.layers.InputLayer` is a layer where your data is already defined as one of the tf tensor types, i.e., can be a ragged tensor or constant or other types. I hope this helps!
36,338,261
How can I make my Footer width cover the entire width of the browser window? **Note:** I'm using Bootstrap, the Footer uses 'container-fluid' but the page content uses 'container'. **Live link:** <http://185.123.96.102/~kidsdrum/moneynest.co.uk/blog.html> **HTML** ``` <footer class="container-fluid" style="margin-top: 30px;"> <div class="row"> <div class="col-sm-7 footercta"> <h4 class="bottomoffer">Sign up to access your free Jumpstart your Finances email course:</h4> <div id="mc_embed_signup2"> <div id="mc_embed_signup_scroll"> <div id="mlb2-2024903" class="ml-subscribe-form ml-subscribe-form-2024903"> <div class="ml-vertical-align-center"> <div class="subscribe-form ml-block-success" style="display:none"> <div class="form-section"> <h4></h4> <p>Success!</p> </div> </div> <form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/i4m1h1" data-code="i4m1h1" method="POST" target="_blank"> <div class="subscribe-form"> <div class="form-section"> <h4></h4> <p></p> </div> <div class="form-section"> <div class="form-group ml-field-email ml-validate-required ml-validate-email"> <input type="email" name="fields[email]" class="form-control" placeholder="Email*" value="" id="footer-cta-input"> </div> </div> <input type="hidden" name="ml-submit" value="1" /> <button type="submit" class="text-uppercase btn btn-primary btn-lg btn-bottom primary gradient-on"> Start Class Now </button> <button disabled="disabled" style="display: none;" type="button" class="loading gradient-on"> <img src="//static.mailerlite.com/images/rolling.gif" width="20" height="20" style="width: 20px; height: 20px;"> </button> </div> </form> <script> function ml_webform_success_2024903() { jQuery('.ml-subscribe-form-2024903 .ml-block-success').show(); jQuery('.ml-subscribe-form-2024903 .ml-block-form').hide(); }; </script> </div> </div></div> <script type="text/javascript" src="//static.mailerlite.com/js/w/webforms.js?v25"></script> </div> </div> <div class="col-sm-5 footerlinks"> <br> <ul class="mylist"> <li><a href="/">Home</a></li> <li><a href="/blog.html">Blog</a></li> <li><a href="/about.html">About</a></li> <li><a href="/contact.html">Contact</a></li> </ul> <ul class="mylist2"> <li><a href="https://www.facebook.com/ukmoneynest/">Facebook</a></li> <li><a href="https://twitter.com/ukmoneynest">Twitter</a></li> </ul> </div> </div> <br> <br> <div class="finalfooterlinks"><p> <a href="/privacy-policy.html">Privacy Policy</a> | <a href="/terms-and-conditions.html">Terms of Service</a></p> <p>&copy; Copyright 2015 - <script type="text/javascript"> now = new Date theYear=now.getYear() if (theYear < 1900) theYear=theYear+1900 document.write(theYear) </script></div> <br> </footer> ```
2016/03/31
[ "https://Stackoverflow.com/questions/36338261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872557/" ]
Your `footer` is inside a `.container` which has a `1170px` `width`. So you just need to get it out of here.
If you move your footer outside of, and directly after div.container, it will span the full-width of the browser window.
36,338,261
How can I make my Footer width cover the entire width of the browser window? **Note:** I'm using Bootstrap, the Footer uses 'container-fluid' but the page content uses 'container'. **Live link:** <http://185.123.96.102/~kidsdrum/moneynest.co.uk/blog.html> **HTML** ``` <footer class="container-fluid" style="margin-top: 30px;"> <div class="row"> <div class="col-sm-7 footercta"> <h4 class="bottomoffer">Sign up to access your free Jumpstart your Finances email course:</h4> <div id="mc_embed_signup2"> <div id="mc_embed_signup_scroll"> <div id="mlb2-2024903" class="ml-subscribe-form ml-subscribe-form-2024903"> <div class="ml-vertical-align-center"> <div class="subscribe-form ml-block-success" style="display:none"> <div class="form-section"> <h4></h4> <p>Success!</p> </div> </div> <form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/i4m1h1" data-code="i4m1h1" method="POST" target="_blank"> <div class="subscribe-form"> <div class="form-section"> <h4></h4> <p></p> </div> <div class="form-section"> <div class="form-group ml-field-email ml-validate-required ml-validate-email"> <input type="email" name="fields[email]" class="form-control" placeholder="Email*" value="" id="footer-cta-input"> </div> </div> <input type="hidden" name="ml-submit" value="1" /> <button type="submit" class="text-uppercase btn btn-primary btn-lg btn-bottom primary gradient-on"> Start Class Now </button> <button disabled="disabled" style="display: none;" type="button" class="loading gradient-on"> <img src="//static.mailerlite.com/images/rolling.gif" width="20" height="20" style="width: 20px; height: 20px;"> </button> </div> </form> <script> function ml_webform_success_2024903() { jQuery('.ml-subscribe-form-2024903 .ml-block-success').show(); jQuery('.ml-subscribe-form-2024903 .ml-block-form').hide(); }; </script> </div> </div></div> <script type="text/javascript" src="//static.mailerlite.com/js/w/webforms.js?v25"></script> </div> </div> <div class="col-sm-5 footerlinks"> <br> <ul class="mylist"> <li><a href="/">Home</a></li> <li><a href="/blog.html">Blog</a></li> <li><a href="/about.html">About</a></li> <li><a href="/contact.html">Contact</a></li> </ul> <ul class="mylist2"> <li><a href="https://www.facebook.com/ukmoneynest/">Facebook</a></li> <li><a href="https://twitter.com/ukmoneynest">Twitter</a></li> </ul> </div> </div> <br> <br> <div class="finalfooterlinks"><p> <a href="/privacy-policy.html">Privacy Policy</a> | <a href="/terms-and-conditions.html">Terms of Service</a></p> <p>&copy; Copyright 2015 - <script type="text/javascript"> now = new Date theYear=now.getYear() if (theYear < 1900) theYear=theYear+1900 document.write(theYear) </script></div> <br> </footer> ```
2016/03/31
[ "https://Stackoverflow.com/questions/36338261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872557/" ]
Is it what you want? ``` <div class="container"> <p>Your content goes here</p> </div> <footer class="footer"> <div class="container"> <p>Your footer content here.</p> </div> </footer> ```
If you move your footer outside of, and directly after div.container, it will span the full-width of the browser window.
36,338,261
How can I make my Footer width cover the entire width of the browser window? **Note:** I'm using Bootstrap, the Footer uses 'container-fluid' but the page content uses 'container'. **Live link:** <http://185.123.96.102/~kidsdrum/moneynest.co.uk/blog.html> **HTML** ``` <footer class="container-fluid" style="margin-top: 30px;"> <div class="row"> <div class="col-sm-7 footercta"> <h4 class="bottomoffer">Sign up to access your free Jumpstart your Finances email course:</h4> <div id="mc_embed_signup2"> <div id="mc_embed_signup_scroll"> <div id="mlb2-2024903" class="ml-subscribe-form ml-subscribe-form-2024903"> <div class="ml-vertical-align-center"> <div class="subscribe-form ml-block-success" style="display:none"> <div class="form-section"> <h4></h4> <p>Success!</p> </div> </div> <form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/i4m1h1" data-code="i4m1h1" method="POST" target="_blank"> <div class="subscribe-form"> <div class="form-section"> <h4></h4> <p></p> </div> <div class="form-section"> <div class="form-group ml-field-email ml-validate-required ml-validate-email"> <input type="email" name="fields[email]" class="form-control" placeholder="Email*" value="" id="footer-cta-input"> </div> </div> <input type="hidden" name="ml-submit" value="1" /> <button type="submit" class="text-uppercase btn btn-primary btn-lg btn-bottom primary gradient-on"> Start Class Now </button> <button disabled="disabled" style="display: none;" type="button" class="loading gradient-on"> <img src="//static.mailerlite.com/images/rolling.gif" width="20" height="20" style="width: 20px; height: 20px;"> </button> </div> </form> <script> function ml_webform_success_2024903() { jQuery('.ml-subscribe-form-2024903 .ml-block-success').show(); jQuery('.ml-subscribe-form-2024903 .ml-block-form').hide(); }; </script> </div> </div></div> <script type="text/javascript" src="//static.mailerlite.com/js/w/webforms.js?v25"></script> </div> </div> <div class="col-sm-5 footerlinks"> <br> <ul class="mylist"> <li><a href="/">Home</a></li> <li><a href="/blog.html">Blog</a></li> <li><a href="/about.html">About</a></li> <li><a href="/contact.html">Contact</a></li> </ul> <ul class="mylist2"> <li><a href="https://www.facebook.com/ukmoneynest/">Facebook</a></li> <li><a href="https://twitter.com/ukmoneynest">Twitter</a></li> </ul> </div> </div> <br> <br> <div class="finalfooterlinks"><p> <a href="/privacy-policy.html">Privacy Policy</a> | <a href="/terms-and-conditions.html">Terms of Service</a></p> <p>&copy; Copyright 2015 - <script type="text/javascript"> now = new Date theYear=now.getYear() if (theYear < 1900) theYear=theYear+1900 document.write(theYear) </script></div> <br> </footer> ```
2016/03/31
[ "https://Stackoverflow.com/questions/36338261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872557/" ]
Another solution if you don't want to move the footer outside of container, just add this css to your code: ``` footer { position: relative; width: 100vw; left: calc(-50vw + 50%);} ``` This will make footer have 100% of the viewport width, and move the child element 50% of the viewport width – minus 50% of the parent element's width – to the left to make it meet the edge of the screen. I found this answer here: [Is there are way to make a child DIV's width wider than the parent DIV using CSS?](https://stackoverflow.com/questions/5581034/is-there-are-way-to-make-a-child-divs-width-wider-than-the-parent-div-using-css). Hope this help.
If you move your footer outside of, and directly after div.container, it will span the full-width of the browser window.
36,338,261
How can I make my Footer width cover the entire width of the browser window? **Note:** I'm using Bootstrap, the Footer uses 'container-fluid' but the page content uses 'container'. **Live link:** <http://185.123.96.102/~kidsdrum/moneynest.co.uk/blog.html> **HTML** ``` <footer class="container-fluid" style="margin-top: 30px;"> <div class="row"> <div class="col-sm-7 footercta"> <h4 class="bottomoffer">Sign up to access your free Jumpstart your Finances email course:</h4> <div id="mc_embed_signup2"> <div id="mc_embed_signup_scroll"> <div id="mlb2-2024903" class="ml-subscribe-form ml-subscribe-form-2024903"> <div class="ml-vertical-align-center"> <div class="subscribe-form ml-block-success" style="display:none"> <div class="form-section"> <h4></h4> <p>Success!</p> </div> </div> <form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/i4m1h1" data-code="i4m1h1" method="POST" target="_blank"> <div class="subscribe-form"> <div class="form-section"> <h4></h4> <p></p> </div> <div class="form-section"> <div class="form-group ml-field-email ml-validate-required ml-validate-email"> <input type="email" name="fields[email]" class="form-control" placeholder="Email*" value="" id="footer-cta-input"> </div> </div> <input type="hidden" name="ml-submit" value="1" /> <button type="submit" class="text-uppercase btn btn-primary btn-lg btn-bottom primary gradient-on"> Start Class Now </button> <button disabled="disabled" style="display: none;" type="button" class="loading gradient-on"> <img src="//static.mailerlite.com/images/rolling.gif" width="20" height="20" style="width: 20px; height: 20px;"> </button> </div> </form> <script> function ml_webform_success_2024903() { jQuery('.ml-subscribe-form-2024903 .ml-block-success').show(); jQuery('.ml-subscribe-form-2024903 .ml-block-form').hide(); }; </script> </div> </div></div> <script type="text/javascript" src="//static.mailerlite.com/js/w/webforms.js?v25"></script> </div> </div> <div class="col-sm-5 footerlinks"> <br> <ul class="mylist"> <li><a href="/">Home</a></li> <li><a href="/blog.html">Blog</a></li> <li><a href="/about.html">About</a></li> <li><a href="/contact.html">Contact</a></li> </ul> <ul class="mylist2"> <li><a href="https://www.facebook.com/ukmoneynest/">Facebook</a></li> <li><a href="https://twitter.com/ukmoneynest">Twitter</a></li> </ul> </div> </div> <br> <br> <div class="finalfooterlinks"><p> <a href="/privacy-policy.html">Privacy Policy</a> | <a href="/terms-and-conditions.html">Terms of Service</a></p> <p>&copy; Copyright 2015 - <script type="text/javascript"> now = new Date theYear=now.getYear() if (theYear < 1900) theYear=theYear+1900 document.write(theYear) </script></div> <br> </footer> ```
2016/03/31
[ "https://Stackoverflow.com/questions/36338261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872557/" ]
Your `footer` is inside a `.container` which has a `1170px` `width`. So you just need to get it out of here.
Is it what you want? ``` <div class="container"> <p>Your content goes here</p> </div> <footer class="footer"> <div class="container"> <p>Your footer content here.</p> </div> </footer> ```
36,338,261
How can I make my Footer width cover the entire width of the browser window? **Note:** I'm using Bootstrap, the Footer uses 'container-fluid' but the page content uses 'container'. **Live link:** <http://185.123.96.102/~kidsdrum/moneynest.co.uk/blog.html> **HTML** ``` <footer class="container-fluid" style="margin-top: 30px;"> <div class="row"> <div class="col-sm-7 footercta"> <h4 class="bottomoffer">Sign up to access your free Jumpstart your Finances email course:</h4> <div id="mc_embed_signup2"> <div id="mc_embed_signup_scroll"> <div id="mlb2-2024903" class="ml-subscribe-form ml-subscribe-form-2024903"> <div class="ml-vertical-align-center"> <div class="subscribe-form ml-block-success" style="display:none"> <div class="form-section"> <h4></h4> <p>Success!</p> </div> </div> <form class="ml-block-form" action="//app.mailerlite.com/webforms/submit/i4m1h1" data-code="i4m1h1" method="POST" target="_blank"> <div class="subscribe-form"> <div class="form-section"> <h4></h4> <p></p> </div> <div class="form-section"> <div class="form-group ml-field-email ml-validate-required ml-validate-email"> <input type="email" name="fields[email]" class="form-control" placeholder="Email*" value="" id="footer-cta-input"> </div> </div> <input type="hidden" name="ml-submit" value="1" /> <button type="submit" class="text-uppercase btn btn-primary btn-lg btn-bottom primary gradient-on"> Start Class Now </button> <button disabled="disabled" style="display: none;" type="button" class="loading gradient-on"> <img src="//static.mailerlite.com/images/rolling.gif" width="20" height="20" style="width: 20px; height: 20px;"> </button> </div> </form> <script> function ml_webform_success_2024903() { jQuery('.ml-subscribe-form-2024903 .ml-block-success').show(); jQuery('.ml-subscribe-form-2024903 .ml-block-form').hide(); }; </script> </div> </div></div> <script type="text/javascript" src="//static.mailerlite.com/js/w/webforms.js?v25"></script> </div> </div> <div class="col-sm-5 footerlinks"> <br> <ul class="mylist"> <li><a href="/">Home</a></li> <li><a href="/blog.html">Blog</a></li> <li><a href="/about.html">About</a></li> <li><a href="/contact.html">Contact</a></li> </ul> <ul class="mylist2"> <li><a href="https://www.facebook.com/ukmoneynest/">Facebook</a></li> <li><a href="https://twitter.com/ukmoneynest">Twitter</a></li> </ul> </div> </div> <br> <br> <div class="finalfooterlinks"><p> <a href="/privacy-policy.html">Privacy Policy</a> | <a href="/terms-and-conditions.html">Terms of Service</a></p> <p>&copy; Copyright 2015 - <script type="text/javascript"> now = new Date theYear=now.getYear() if (theYear < 1900) theYear=theYear+1900 document.write(theYear) </script></div> <br> </footer> ```
2016/03/31
[ "https://Stackoverflow.com/questions/36338261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3872557/" ]
Your `footer` is inside a `.container` which has a `1170px` `width`. So you just need to get it out of here.
Another solution if you don't want to move the footer outside of container, just add this css to your code: ``` footer { position: relative; width: 100vw; left: calc(-50vw + 50%);} ``` This will make footer have 100% of the viewport width, and move the child element 50% of the viewport width – minus 50% of the parent element's width – to the left to make it meet the edge of the screen. I found this answer here: [Is there are way to make a child DIV's width wider than the parent DIV using CSS?](https://stackoverflow.com/questions/5581034/is-there-are-way-to-make-a-child-divs-width-wider-than-the-parent-div-using-css). Hope this help.
6,461,492
I've got several tables that I want to merge for one big query. The criteria for the search are based on two tables: `section_types` and `sections`. I want to pull all `section_types` and their associated `sections` where the `sections` match certain criteria, PLUS any `section_types` that are active but don't have any `sections` associated. It seems like a basic `LEFT JOIN`, but I think because some of my filter criteria are based on `sections`, I can't get `section_types` that have no associated `sections` ``` `section_types` id | name | active ---+------+------- 1 | a | 1 2 | b | 0 3 | c | 1 `sections` type | issue | location -----+-------+---------- 1 | 0611 | 1 2 | 0611 | 1 1 | 0511 | 1 ``` Say I want to pull all sections for issue 0611 at location 1, plus any empty section types. Like so: (edited. see below) But I'm only getting `section_types` that have corresponding `sections`. So in this query, `section_types` row 3 would not show up. What am I doing wrong? EDIT: I'm getting all the `section_types` now, but not all the `sections` I need. I guess `LEFT JOIN` will do that. There can be many `sections` for each `section_type`, or none. My query is at this point now: ``` SELECT * FROM `section_types` st RIGHT JOIN `sections` s ON s.type=st.id AND s.issue='0611' AND s.location=1 WHERE st.active OR s.issue IS NOT NULL ORDER BY st.id ``` which gets me: ``` id | name | active | issue | location ---+------+--------+-------+--------- 1 | a | 1 | 0611 | 1 2 | b | 0 | 0611 | 1 3 | c | 1 | | ``` but I still need that second type-1 `section`
2011/06/23
[ "https://Stackoverflow.com/questions/6461492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323677/" ]
**EDIT** I deleted this, but based on the conversation, I think it accomplishes what you're looking for. **ORIGINAL** Feels like a hack... but I think it works. ``` Declare @tmp TABLE( id int, name varchar(50), active int, type int, issue int, location int ) Insert Into @tmp SELECT * FROM section_types st LEFT JOIN sections s ON st.id=s.type AND s.issue='0611' AND s.location=1 WHERE st.active = 1 OR s.issue IS NOT NULL ORDER BY st.id Select * FROM @tmp UNION Select *, NULL, NULL, NULL From section_types WHERE id NOT IN ( SELECT id FROM @tmp) AND active = 0 ```
You just have your tables reversed. `LEFT OUTER JOIN` requires the *left* table to have a row for the `ON` condition. Use a `RIGHT OUTER JOIN` or swap the tables.
6,461,492
I've got several tables that I want to merge for one big query. The criteria for the search are based on two tables: `section_types` and `sections`. I want to pull all `section_types` and their associated `sections` where the `sections` match certain criteria, PLUS any `section_types` that are active but don't have any `sections` associated. It seems like a basic `LEFT JOIN`, but I think because some of my filter criteria are based on `sections`, I can't get `section_types` that have no associated `sections` ``` `section_types` id | name | active ---+------+------- 1 | a | 1 2 | b | 0 3 | c | 1 `sections` type | issue | location -----+-------+---------- 1 | 0611 | 1 2 | 0611 | 1 1 | 0511 | 1 ``` Say I want to pull all sections for issue 0611 at location 1, plus any empty section types. Like so: (edited. see below) But I'm only getting `section_types` that have corresponding `sections`. So in this query, `section_types` row 3 would not show up. What am I doing wrong? EDIT: I'm getting all the `section_types` now, but not all the `sections` I need. I guess `LEFT JOIN` will do that. There can be many `sections` for each `section_type`, or none. My query is at this point now: ``` SELECT * FROM `section_types` st RIGHT JOIN `sections` s ON s.type=st.id AND s.issue='0611' AND s.location=1 WHERE st.active OR s.issue IS NOT NULL ORDER BY st.id ``` which gets me: ``` id | name | active | issue | location ---+------+--------+-------+--------- 1 | a | 1 | 0611 | 1 2 | b | 0 | 0611 | 1 3 | c | 1 | | ``` but I still need that second type-1 `section`
2011/06/23
[ "https://Stackoverflow.com/questions/6461492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323677/" ]
Is this what you need? All section\_types and ALL their related sections where at least one section has issue `'0611'` and location `1`. Plus all the rest section\_types that are active: ``` SELECT * FROM section_types st JOIN sections s ON s.type = st.id WHERE EXISTS ( SELECT * FROM sections s2 WHERE s2.type = st.id AND s2.issue = '0611' AND s2.location = 1 ) UNION ALL SELECT *, NULL, NULL, NULL FROM section_types st WHERE st.active AND NOT EXISTS ( SELECT * FROM sections s2 WHERE s2.type = st.id AND s2.issue = '0611' AND s2.location = 1 ) ORDER BY id ```
You just have your tables reversed. `LEFT OUTER JOIN` requires the *left* table to have a row for the `ON` condition. Use a `RIGHT OUTER JOIN` or swap the tables.
486
Some ideas: * Rename the [install](https://unix.stackexchange.com/questions/tagged/install "show questions tagged 'install'") tag, to something like [installation](https://unix.stackexchange.com/questions/tagged/installation "show questions tagged 'installation'")? * If applicable, get rid of it in favor of [package-management](https://unix.stackexchange.com/questions/tagged/package-management "show questions tagged 'package-management'") or something more specific ([apt](https://unix.stackexchange.com/questions/tagged/apt "show questions tagged 'apt'") or [yum](https://unix.stackexchange.com/questions/tagged/yum "show questions tagged 'yum'"))? * If not, limit it to OS installation and installations not involving a package manager?
2011/03/02
[ "https://unix.meta.stackexchange.com/questions/486", "https://unix.meta.stackexchange.com", "https://unix.meta.stackexchange.com/users/688/" ]
How about replacing it with [system-installation](https://unix.stackexchange.com/questions/tagged/system-installation "show questions tagged 'system-installation'"), to distinguish it from already-existing [software-installation](https://unix.stackexchange.com/questions/tagged/software-installation "show questions tagged 'software-installation'")?
Given the lack of opposition, I've declared [install](https://unix.stackexchange.com/questions/tagged/install "show questions tagged 'install'") a tag to be removed in the tag wiki. We can wear it off a little at a time. It would be good to ban [install](https://unix.stackexchange.com/questions/tagged/install "show questions tagged 'install'"), as well.
29,948,131
Questions from an angularjs newbie. This is a two part problem. I have a page which has a drop down (populated using web service), a text box and button 'Go'. Button ng-click causes the value of drop down and text box to hit a web service which returns JSON which I use to display the grid (Id, name). Grid also has delete button for each row. All this is inside one controller say controllerA. When delete button is clicked, I open a modal <http://angular-ui.github.io/bootstrap/> which has Yes and No button. This modal is in a different controller say controllerB. Q1. How can I get the value of id (row users want to delete) in controllerB? I am using a global var variable which I set in controllerA and get in controllerB but I don't think that is the correct way? Q2. When users click Yes on modal (controllerB), how can I reload the page and display the refreshed grid (controllerA) - how can I get the value of dropdown and textbox in controllerB and how can I call controllerA's ng-click function in controllerB?
2015/04/29
[ "https://Stackoverflow.com/questions/29948131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700747/" ]
Q1: Check out [this page for an example](https://angular-ui.github.io/bootstrap/#/modal) on how to pass information to a modal dialog. Basically you need to specify the **resolve** property when calling $modal.open. Q2: See the example again. In ControllerA, you can call **modalInstance.result.then(...)** and provide a function which will get called when the model dialog is dismissed. Inside that function, you can make whatever web service call you wish, and when the web service call returns, your success function can update your $scope array variable which populates the data grid.
Use an AngularJS **factory** or **service** to use methods across different controllers. You shouldn't be using global variables, you can look into using **$rootScope** to make things available in a broader scope. Documentation here: <https://docs.angularjs.org/guide/services> & <https://docs.angularjs.org/api/ng/service/>$rootScope One method to reload the page would be to call a re-render function on the ng-click from the controller so that it makes a call to the server for the most updated information (if you don't already have function/method that initially renders the page, otherwise call that in the ng-click again to re-render), that way you are executing multiple functions on the click, including the re-render.
20,832,048
Im trying to use innerhtml and html() but html() does not work on the browser. what could be the reason... when I replace innerHTML to html() in the fiddle, I dont get any result. <http://jsfiddle.net/7RCyX/> html ``` <ul> <li>First</li> <li>Second</li> </ul> ``` jquery: ``` var listitems = $('li') var firstitem = listitems[1] var x = firstitem.innerHTML alert(x) ```
2013/12/30
[ "https://Stackoverflow.com/questions/20832048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
`x` is not being set since firstitem is only the `li` element. You need to add `$()`. ``` var listitems = $('li'); var firstitem = listitems[1]; var x = $(firstitem).html(); alert(x); ``` The above code works as intended.
when you `html()` does not work do you mean `firstitem.html()`, it never do that because it s html node not jQuery object to convert it to jQuery try `$(firstitem)` or `$("li:nth-child(2)")`.
20,832,048
Im trying to use innerhtml and html() but html() does not work on the browser. what could be the reason... when I replace innerHTML to html() in the fiddle, I dont get any result. <http://jsfiddle.net/7RCyX/> html ``` <ul> <li>First</li> <li>Second</li> </ul> ``` jquery: ``` var listitems = $('li') var firstitem = listitems[1] var x = firstitem.innerHTML alert(x) ```
2013/12/30
[ "https://Stackoverflow.com/questions/20832048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
``` var firstitem = listitems[1] ``` by specifying this it means it will give you back dom element (see image), so you can access properties of object like `li.className` ![enter image description here](https://i.stack.imgur.com/ma0iS.png) you can change it to ``` var firstitem = listitems.eq(1); // or use nth:child selector ``` <http://jsfiddle.net/7RCyX/4/>
when you `html()` does not work do you mean `firstitem.html()`, it never do that because it s html node not jQuery object to convert it to jQuery try `$(firstitem)` or `$("li:nth-child(2)")`.
20,832,048
Im trying to use innerhtml and html() but html() does not work on the browser. what could be the reason... when I replace innerHTML to html() in the fiddle, I dont get any result. <http://jsfiddle.net/7RCyX/> html ``` <ul> <li>First</li> <li>Second</li> </ul> ``` jquery: ``` var listitems = $('li') var firstitem = listitems[1] var x = firstitem.innerHTML alert(x) ```
2013/12/30
[ "https://Stackoverflow.com/questions/20832048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
``` var firstitem = listitems[1] ``` by specifying this it means it will give you back dom element (see image), so you can access properties of object like `li.className` ![enter image description here](https://i.stack.imgur.com/ma0iS.png) you can change it to ``` var firstitem = listitems.eq(1); // or use nth:child selector ``` <http://jsfiddle.net/7RCyX/4/>
`x` is not being set since firstitem is only the `li` element. You need to add `$()`. ``` var listitems = $('li'); var firstitem = listitems[1]; var x = $(firstitem).html(); alert(x); ``` The above code works as intended.
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Ok after digging through the [source code](https://github.com/apache/spark) I found how to add my own custom metrics. It requires 3 things: 1. Create my own custom [source](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/core/src/main/scala/org/apache/spark/metrics/source/Source.scala). Sort of like [this](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/streaming/src/main/scala/org/apache/spark/streaming/StreamingSource.scala) 2. Enable the Jmx sink in the spark metrics.properties file. The specific line I used is: `*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink` which enable JmxSink for all instances 3. Register my custom source in the SparkEnv metrics system. An example of how to do can be seen [here](http://mail-archives.us.apache.org/mod_mbox/spark-user/201501.mbox/%3CCAE50=dq+6tdx9VNVM3ctBMWPLDPbUAacO3aN3L8x38zg=xb6VQ@mail.gmail.com%3E) - I actually viewed this link before but missed the registration part which prevented me from actually seeing my custom metrics in the JVisualVM I'm still struggling with how to actually count the number of insertions into VoltDB because the code runs on the executors but that's a subject for a different topic :) I hope this will help others
here's an excellent tutorial which covers all the setps you need to setup Spark's MetricsSystem with Graphite. That should do the trick: <http://www.hammerlab.org/2015/02/27/monitoring-spark-with-graphite-and-grafana/>
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Groupon have a library called [`spark-metrics`](https://github.com/groupon/spark-metrics) that lets you use a simple (Codahale-like) API on your executors and have the results collated back in the driver and automatically registered in Spark's existing metrics registry. These then get automatically exported along with Spark's built-in metrics when you configure a metric sink as per the [Spark docs](https://spark.apache.org/docs/latest/monitoring.html#metrics).
here's an excellent tutorial which covers all the setps you need to setup Spark's MetricsSystem with Graphite. That should do the trick: <http://www.hammerlab.org/2015/02/27/monitoring-spark-with-graphite-and-grafana/>
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Ok after digging through the [source code](https://github.com/apache/spark) I found how to add my own custom metrics. It requires 3 things: 1. Create my own custom [source](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/core/src/main/scala/org/apache/spark/metrics/source/Source.scala). Sort of like [this](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/streaming/src/main/scala/org/apache/spark/streaming/StreamingSource.scala) 2. Enable the Jmx sink in the spark metrics.properties file. The specific line I used is: `*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink` which enable JmxSink for all instances 3. Register my custom source in the SparkEnv metrics system. An example of how to do can be seen [here](http://mail-archives.us.apache.org/mod_mbox/spark-user/201501.mbox/%3CCAE50=dq+6tdx9VNVM3ctBMWPLDPbUAacO3aN3L8x38zg=xb6VQ@mail.gmail.com%3E) - I actually viewed this link before but missed the registration part which prevented me from actually seeing my custom metrics in the JVisualVM I'm still struggling with how to actually count the number of insertions into VoltDB because the code runs on the executors but that's a subject for a different topic :) I hope this will help others
to insert rows from based on inserts from VoltDB, use accumulators - and then from your driver you can create a listener - maybe something like this to get you started ``` sparkContext.addSparkListener(new SparkListener() { override def onStageCompleted(stageCompleted: SparkListenerStageCompleted) { stageCompleted.stageInfo.accumulables.foreach { case (_, acc) => { ``` here you have access to those rows combined accumulators and then you can send to your sink..
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Ok after digging through the [source code](https://github.com/apache/spark) I found how to add my own custom metrics. It requires 3 things: 1. Create my own custom [source](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/core/src/main/scala/org/apache/spark/metrics/source/Source.scala). Sort of like [this](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/streaming/src/main/scala/org/apache/spark/streaming/StreamingSource.scala) 2. Enable the Jmx sink in the spark metrics.properties file. The specific line I used is: `*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink` which enable JmxSink for all instances 3. Register my custom source in the SparkEnv metrics system. An example of how to do can be seen [here](http://mail-archives.us.apache.org/mod_mbox/spark-user/201501.mbox/%3CCAE50=dq+6tdx9VNVM3ctBMWPLDPbUAacO3aN3L8x38zg=xb6VQ@mail.gmail.com%3E) - I actually viewed this link before but missed the registration part which prevented me from actually seeing my custom metrics in the JVisualVM I'm still struggling with how to actually count the number of insertions into VoltDB because the code runs on the executors but that's a subject for a different topic :) I hope this will help others
Groupon have a library called [`spark-metrics`](https://github.com/groupon/spark-metrics) that lets you use a simple (Codahale-like) API on your executors and have the results collated back in the driver and automatically registered in Spark's existing metrics registry. These then get automatically exported along with Spark's built-in metrics when you configure a metric sink as per the [Spark docs](https://spark.apache.org/docs/latest/monitoring.html#metrics).
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Ok after digging through the [source code](https://github.com/apache/spark) I found how to add my own custom metrics. It requires 3 things: 1. Create my own custom [source](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/core/src/main/scala/org/apache/spark/metrics/source/Source.scala). Sort of like [this](https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/streaming/src/main/scala/org/apache/spark/streaming/StreamingSource.scala) 2. Enable the Jmx sink in the spark metrics.properties file. The specific line I used is: `*.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink` which enable JmxSink for all instances 3. Register my custom source in the SparkEnv metrics system. An example of how to do can be seen [here](http://mail-archives.us.apache.org/mod_mbox/spark-user/201501.mbox/%3CCAE50=dq+6tdx9VNVM3ctBMWPLDPbUAacO3aN3L8x38zg=xb6VQ@mail.gmail.com%3E) - I actually viewed this link before but missed the registration part which prevented me from actually seeing my custom metrics in the JVisualVM I'm still struggling with how to actually count the number of insertions into VoltDB because the code runs on the executors but that's a subject for a different topic :) I hope this will help others
Below is a working example in Java. It's tested with `StreaminQuery` (Unfortunately `StreaminQuery` does not have ootb metrics like `StreamingContext` till Spark 2.3.1). **Steps:** **Define a custom source in the same package of `Source` class** ``` package org.apache.spark.metrics.source; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import lombok.Data; import lombok.experimental.Accessors; import org.apache.spark.sql.streaming.StreamingQueryProgress; /** * Metrics source for structured streaming query. */ public class StreamingQuerySource implements Source { private String appName; private MetricRegistry metricRegistry = new MetricRegistry(); private final Progress progress = new Progress(); public StreamingQuerySource(String appName) { this.appName = appName; registerGuage("batchId", () -> progress.batchId()); registerGuage("numInputRows", () -> progress.numInputRows()); registerGuage("inputRowsPerSecond", () -> progress.inputRowsPerSecond()); registerGuage("processedRowsPerSecond", () -> progress.processedRowsPerSecond()); } private <T> Gauge<T> registerGuage(String name, Gauge<T> metric) { return metricRegistry.register(MetricRegistry.name(name), metric); } @Override public String sourceName() { return String.format("%s.streaming", appName); } @Override public MetricRegistry metricRegistry() { return metricRegistry; } public void updateProgress(StreamingQueryProgress queryProgress) { progress.batchId(queryProgress.batchId()) .numInputRows(queryProgress.numInputRows()) .inputRowsPerSecond(queryProgress.inputRowsPerSecond()) .processedRowsPerSecond(queryProgress.processedRowsPerSecond()); } @Data @Accessors(fluent = true) private static class Progress { private long batchId = -1; private long numInputRows = 0; private double inputRowsPerSecond = 0; private double processedRowsPerSecond = 0; } } ``` **Register the source right after SparkContext is created** ``` querySource = new StreamingQuerySource(getSparkSession().sparkContext().appName()); SparkEnv.get().metricsSystem().registerSource(querySource); ``` **Update data in StreamingQueryListener.onProgress(event)** ``` querySource.updateProgress(event.progress()); ``` **Config metrics.properties** ``` *.sink.graphite.class=org.apache.spark.metrics.sink.GraphiteSink *.sink.graphite.host=xxx *.sink.graphite.port=9109 *.sink.graphite.period=10 *.sink.graphite.unit=seconds # Enable jvm source for instance master, worker, driver and executor master.source.jvm.class=org.apache.spark.metrics.source.JvmSource worker.source.jvm.class=org.apache.spark.metrics.source.JvmSource driver.source.jvm.class=org.apache.spark.metrics.source.JvmSource executor.source.jvm.class=org.apache.spark.metrics.source.JvmSource ``` **Sample output in graphite exporter (mapped to prometheus format)** ``` streaming_query{application="local-1538032184639",model="model1",qty="batchId"} 38 streaming_query{application="local-1538032184639",model="model1r",qty="inputRowsPerSecond"} 2.5 streaming_query{application="local-1538032184639",model="model1",qty="numInputRows"} 5 streaming_query{application="local-1538032184639",model=model1",qty="processedRowsPerSecond"} 0.81 ```
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Groupon have a library called [`spark-metrics`](https://github.com/groupon/spark-metrics) that lets you use a simple (Codahale-like) API on your executors and have the results collated back in the driver and automatically registered in Spark's existing metrics registry. These then get automatically exported along with Spark's built-in metrics when you configure a metric sink as per the [Spark docs](https://spark.apache.org/docs/latest/monitoring.html#metrics).
to insert rows from based on inserts from VoltDB, use accumulators - and then from your driver you can create a listener - maybe something like this to get you started ``` sparkContext.addSparkListener(new SparkListener() { override def onStageCompleted(stageCompleted: SparkListenerStageCompleted) { stageCompleted.stageInfo.accumulables.foreach { case (_, acc) => { ``` here you have access to those rows combined accumulators and then you can send to your sink..
32,843,832
I'm working on a Spark Streaming program which retrieves a Kafka stream, does very basic transformation on the stream and then inserts the data to a DB (voltdb if it's relevant). I'm trying to measure the rate in which I insert rows to the DB. I think [metrics](http://metrics.dropwizard.io/3.1.0/manual/) can be useful (using JMX). However I can't find how to add custom metrics to Spark. I've looked at Spark's source code and also found [this thread](http://apache-spark-developers-list.1001551.n3.nabble.com/Registering-custom-metrics-td9030.html#a9968) however it doesn't work for me. I also enabled the JMX sink in the conf.metrics file. What's not working is I don't see my custom metrics with JConsole. Could someone explain how to add custom metrics (preferably via JMX) to spark streaming? Or alternatively how to measure my insertion rate to my DB (specifically VoltDB)? I'm using spark with Java 8.
2015/09/29
[ "https://Stackoverflow.com/questions/32843832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3510671/" ]
Groupon have a library called [`spark-metrics`](https://github.com/groupon/spark-metrics) that lets you use a simple (Codahale-like) API on your executors and have the results collated back in the driver and automatically registered in Spark's existing metrics registry. These then get automatically exported along with Spark's built-in metrics when you configure a metric sink as per the [Spark docs](https://spark.apache.org/docs/latest/monitoring.html#metrics).
Below is a working example in Java. It's tested with `StreaminQuery` (Unfortunately `StreaminQuery` does not have ootb metrics like `StreamingContext` till Spark 2.3.1). **Steps:** **Define a custom source in the same package of `Source` class** ``` package org.apache.spark.metrics.source; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import lombok.Data; import lombok.experimental.Accessors; import org.apache.spark.sql.streaming.StreamingQueryProgress; /** * Metrics source for structured streaming query. */ public class StreamingQuerySource implements Source { private String appName; private MetricRegistry metricRegistry = new MetricRegistry(); private final Progress progress = new Progress(); public StreamingQuerySource(String appName) { this.appName = appName; registerGuage("batchId", () -> progress.batchId()); registerGuage("numInputRows", () -> progress.numInputRows()); registerGuage("inputRowsPerSecond", () -> progress.inputRowsPerSecond()); registerGuage("processedRowsPerSecond", () -> progress.processedRowsPerSecond()); } private <T> Gauge<T> registerGuage(String name, Gauge<T> metric) { return metricRegistry.register(MetricRegistry.name(name), metric); } @Override public String sourceName() { return String.format("%s.streaming", appName); } @Override public MetricRegistry metricRegistry() { return metricRegistry; } public void updateProgress(StreamingQueryProgress queryProgress) { progress.batchId(queryProgress.batchId()) .numInputRows(queryProgress.numInputRows()) .inputRowsPerSecond(queryProgress.inputRowsPerSecond()) .processedRowsPerSecond(queryProgress.processedRowsPerSecond()); } @Data @Accessors(fluent = true) private static class Progress { private long batchId = -1; private long numInputRows = 0; private double inputRowsPerSecond = 0; private double processedRowsPerSecond = 0; } } ``` **Register the source right after SparkContext is created** ``` querySource = new StreamingQuerySource(getSparkSession().sparkContext().appName()); SparkEnv.get().metricsSystem().registerSource(querySource); ``` **Update data in StreamingQueryListener.onProgress(event)** ``` querySource.updateProgress(event.progress()); ``` **Config metrics.properties** ``` *.sink.graphite.class=org.apache.spark.metrics.sink.GraphiteSink *.sink.graphite.host=xxx *.sink.graphite.port=9109 *.sink.graphite.period=10 *.sink.graphite.unit=seconds # Enable jvm source for instance master, worker, driver and executor master.source.jvm.class=org.apache.spark.metrics.source.JvmSource worker.source.jvm.class=org.apache.spark.metrics.source.JvmSource driver.source.jvm.class=org.apache.spark.metrics.source.JvmSource executor.source.jvm.class=org.apache.spark.metrics.source.JvmSource ``` **Sample output in graphite exporter (mapped to prometheus format)** ``` streaming_query{application="local-1538032184639",model="model1",qty="batchId"} 38 streaming_query{application="local-1538032184639",model="model1r",qty="inputRowsPerSecond"} 2.5 streaming_query{application="local-1538032184639",model="model1",qty="numInputRows"} 5 streaming_query{application="local-1538032184639",model=model1",qty="processedRowsPerSecond"} 0.81 ```
30,462,770
Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference between the associated and raw values, an example would be very helpful.
2015/05/26
[ "https://Stackoverflow.com/questions/30462770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920977/" ]
Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. ``` let A = 0 let B = 1 ``` is similar to: ``` enum E: Int { case A // if you don't specify, IntegerLiteralConvertible-based enums start at 0 case B } ``` So, `A` has a fixed raw value of `0`, `B` of `1` etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case). They can only be literal-convertible strings, characters or numbers. And they all have to be *distinct* (no two enums can have the same raw value). Associated values are more like variables, associated with *one* of the enumeration cases: ``` enum E { case A(Int) case B case C(String) } ``` Here, `A` now has an associated `Int` that can hold *any* integer value. `B` on the other hand, has no associated value. And `C` has an associated `String`. Associated types can be of any type, not just strings or numbers. Any given value of type `E` will only ever hold one of the associated types, i.e. either an `Int` if the enum is an `A`, or a `String` if the enum is a `C`. It only needs enough space for the bigger of the two. Types like this are sometimes referred to as "discriminated unions" – a union being a variable that can hold multiple different types, but you know (from the enum case) which one it is holding. They can even be generic. The most common example of which is `Optional`, which is defined like this: ``` enum Optional<T> { case .Some(T) case .None } ```
**Swift Enum raw vs associated values** [[Swift types]](https://stackoverflow.com/a/59219141/4770877) `Enumerations` or `Enum` allows you to create a finite set of values and enum variable references on a **single** value from the set ![](https://i.stack.imgur.com/9NnR3.png) In Swift, an enum cannot have both **raw values** and **associated values** at the same time. Raw Values ---------- ``` enum Color: String { case white = "#ffffff" case black = "#000000" } ``` A "raw value" is an unique identifier of a type. It means that you are able to construct your type by ID. For example: ``` XCTAssertEqual(Color.white, Color(rawValue: "#ffffff")) ``` To get raw value use ``` Color.white.rawValue ``` Associated Values ----------------- ``` enum Color { case white case black case custom(hex: String) } ``` Swift's "associated values" allows you to add additional information into enum that can be defined dynamically. Please note when we introduce "associated values", we omit the "raw values" and add a type annotation. This makes it impossible to use the "raw value" to reconstruct your type, because it is now set up dynamically. You can read the "associated value" as follows: ``` let myColor = Color.custom(hex: "#ff00ff") switch myColor { case .custom(let hex): print("custom color hex:\(hex)") //#ff00ff case .white: print("white color") case .black: print("black color") } ``` Good example of `Associated Value` enum is `Result`[[About]](https://stackoverflow.com/a/66413003/4770877) Please note that Objective-C does not support Swift's enum(except Int-bound) **Compare value in enum** raw enum ``` if case .error = someResult { //some logic } ``` associated enum ``` if case .success(let result) = someResult, result == "ok" { //some logic } ``` [[Swift change Enum associated value]](https://stackoverflow.com/a/73586527/4770877) [[Swift indirect enum]](https://stackoverflow.com/a/70317241/4770877)
30,462,770
Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference between the associated and raw values, an example would be very helpful.
2015/05/26
[ "https://Stackoverflow.com/questions/30462770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920977/" ]
Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. ``` let A = 0 let B = 1 ``` is similar to: ``` enum E: Int { case A // if you don't specify, IntegerLiteralConvertible-based enums start at 0 case B } ``` So, `A` has a fixed raw value of `0`, `B` of `1` etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case). They can only be literal-convertible strings, characters or numbers. And they all have to be *distinct* (no two enums can have the same raw value). Associated values are more like variables, associated with *one* of the enumeration cases: ``` enum E { case A(Int) case B case C(String) } ``` Here, `A` now has an associated `Int` that can hold *any* integer value. `B` on the other hand, has no associated value. And `C` has an associated `String`. Associated types can be of any type, not just strings or numbers. Any given value of type `E` will only ever hold one of the associated types, i.e. either an `Int` if the enum is an `A`, or a `String` if the enum is a `C`. It only needs enough space for the bigger of the two. Types like this are sometimes referred to as "discriminated unions" – a union being a variable that can hold multiple different types, but you know (from the enum case) which one it is holding. They can even be generic. The most common example of which is `Optional`, which is defined like this: ``` enum Optional<T> { case .Some(T) case .None } ```
Answers by @Airspeed Velocity and @yoAlex5 explain the difference well, but they state that > > enums can have **either** associated **either** raw values. > > > This is not so for Swift 4 and 5. [Here](https://stackoverflow.com/a/45954779) is a good illustration on for having them both in one enum. You'll need default values for raw value initialiser, of course.
30,462,770
Swift enumerations have both associated and raw values. But the use cases of these values is not clear to me. So I would really appreciate if anyone can explain the difference between the associated and raw values, an example would be very helpful.
2015/05/26
[ "https://Stackoverflow.com/questions/30462770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1920977/" ]
**Swift Enum raw vs associated values** [[Swift types]](https://stackoverflow.com/a/59219141/4770877) `Enumerations` or `Enum` allows you to create a finite set of values and enum variable references on a **single** value from the set ![](https://i.stack.imgur.com/9NnR3.png) In Swift, an enum cannot have both **raw values** and **associated values** at the same time. Raw Values ---------- ``` enum Color: String { case white = "#ffffff" case black = "#000000" } ``` A "raw value" is an unique identifier of a type. It means that you are able to construct your type by ID. For example: ``` XCTAssertEqual(Color.white, Color(rawValue: "#ffffff")) ``` To get raw value use ``` Color.white.rawValue ``` Associated Values ----------------- ``` enum Color { case white case black case custom(hex: String) } ``` Swift's "associated values" allows you to add additional information into enum that can be defined dynamically. Please note when we introduce "associated values", we omit the "raw values" and add a type annotation. This makes it impossible to use the "raw value" to reconstruct your type, because it is now set up dynamically. You can read the "associated value" as follows: ``` let myColor = Color.custom(hex: "#ff00ff") switch myColor { case .custom(let hex): print("custom color hex:\(hex)") //#ff00ff case .white: print("white color") case .black: print("black color") } ``` Good example of `Associated Value` enum is `Result`[[About]](https://stackoverflow.com/a/66413003/4770877) Please note that Objective-C does not support Swift's enum(except Int-bound) **Compare value in enum** raw enum ``` if case .error = someResult { //some logic } ``` associated enum ``` if case .success(let result) = someResult, result == "ok" { //some logic } ``` [[Swift change Enum associated value]](https://stackoverflow.com/a/73586527/4770877) [[Swift indirect enum]](https://stackoverflow.com/a/70317241/4770877)
Answers by @Airspeed Velocity and @yoAlex5 explain the difference well, but they state that > > enums can have **either** associated **either** raw values. > > > This is not so for Swift 4 and 5. [Here](https://stackoverflow.com/a/45954779) is a good illustration on for having them both in one enum. You'll need default values for raw value initialiser, of course.
241,552
Hey, I'm trying to learn how to program so I've installed the latest version of Python and I've been following the Byte of Python tutorial. I'm using Textwrangler I've only gotten as far as the simple "Hello World" intro and I'm already having a problem. I type out the code: ``` #!/usr/bin/python #Filename: helloworld.py print('Hello World') ``` and save it to my desktop as helloworld.py. I then go into terminal and type "python3 helloworld.py" and I get the following error message: ``` /Library/Frameworks/Python.framework/Versions/3.1/Resources/Python.app/Contents/MacOS/Python: can't open file 'helloworld.py': [Errno 2] No such file or directory ``` I was hoping someone could tell me what I'm doing wrong. If I choose to run the script from Textwrangler it operates just fine however I'm not able to access it from the Terminal. Thanks so much!
2011/02/04
[ "https://superuser.com/questions/241552", "https://superuser.com", "https://superuser.com/users/66027/" ]
You need to be in the same directory in the terminal that you saved the file in or you need to specify the full directory on the command line: ``` cd /path/to/directory python3 helloworld.py ``` or ``` python3 /path/to/directory/helloworld.py ``` What directory did you save the file to?
just save your .py file to a folder on your desktop and then you should be able to right click it and at the bottom of the options that come up just press new terminal at folder. I had the same problem as you and this worked for me.
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
Generics in extension methods aren't really anything special, they behave just like in normal methods. ``` public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } ``` As per your comment, you could do something like the following to effectively restrict the type of `T` (adding guard statements). ``` public static int GetLastIndex<T>(this T[] buffer) where T : struct { if (!(buffer is byte[] || buffer is ushort[] || buffer is uint[])) throw new InvalidOperationException( "This method does not accept the given array type."); return buffer.GetUpperBound(0); } ``` Note: As Martin Harris pointed out in a comment, you don't actually need to use generics here. The `Array` type from which all arrays derive will suffice. If you want a more elegant solution, at the cost of slightly more code, you could just create overloads of the method: ``` public static int GetLastIndex(this byte[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this ushort[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this uint[] buffer) { return GetLastIndex(buffer); } private static int GetLastIndex(Array buffer) { return buffer.GetUpperBound(0); } ```
``` public static class MyExtensions { public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } } ```
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
Generics in extension methods aren't really anything special, they behave just like in normal methods. ``` public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } ``` As per your comment, you could do something like the following to effectively restrict the type of `T` (adding guard statements). ``` public static int GetLastIndex<T>(this T[] buffer) where T : struct { if (!(buffer is byte[] || buffer is ushort[] || buffer is uint[])) throw new InvalidOperationException( "This method does not accept the given array type."); return buffer.GetUpperBound(0); } ``` Note: As Martin Harris pointed out in a comment, you don't actually need to use generics here. The `Array` type from which all arrays derive will suffice. If you want a more elegant solution, at the cost of slightly more code, you could just create overloads of the method: ``` public static int GetLastIndex(this byte[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this ushort[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this uint[] buffer) { return GetLastIndex(buffer); } private static int GetLastIndex(Array buffer) { return buffer.GetUpperBound(0); } ```
Same way you do generics in normal (non-extension) methods: Use a placeholder type name introduced in the generic syntax: ``` public static int GetLastIndex<TElement>(this TElement[] buffer) ```
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
Generics in extension methods aren't really anything special, they behave just like in normal methods. ``` public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } ``` As per your comment, you could do something like the following to effectively restrict the type of `T` (adding guard statements). ``` public static int GetLastIndex<T>(this T[] buffer) where T : struct { if (!(buffer is byte[] || buffer is ushort[] || buffer is uint[])) throw new InvalidOperationException( "This method does not accept the given array type."); return buffer.GetUpperBound(0); } ``` Note: As Martin Harris pointed out in a comment, you don't actually need to use generics here. The `Array` type from which all arrays derive will suffice. If you want a more elegant solution, at the cost of slightly more code, you could just create overloads of the method: ``` public static int GetLastIndex(this byte[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this ushort[] buffer) { return GetLastIndex(buffer); } public static int GetLastIndex(this uint[] buffer) { return GetLastIndex(buffer); } private static int GetLastIndex(Array buffer) { return buffer.GetUpperBound(0); } ```
@RHaguiuda You can make constraint like ``` public static class MyExtensions{ public static int GetLastIndex<T>(this T[] buffer) where T: Integer { return buffer.GetUpperBound(0); }} ``` But, type used as a constraint must be an interface, a non-sealed class or a type parameter
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
``` public static class MyExtensions { public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } } ```
Same way you do generics in normal (non-extension) methods: Use a placeholder type name introduced in the generic syntax: ``` public static int GetLastIndex<TElement>(this TElement[] buffer) ```
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
``` public static class MyExtensions { public static int GetLastIndex<T>(this T[] buffer) { return buffer.GetUpperBound(0); } } ```
@RHaguiuda You can make constraint like ``` public static class MyExtensions{ public static int GetLastIndex<T>(this T[] buffer) where T: Integer { return buffer.GetUpperBound(0); }} ``` But, type used as a constraint must be an interface, a non-sealed class or a type parameter
3,521,684
I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic type here. But how can I do that using arrays? Thanks!!! ``` public static class MyExtensions { public static int GetLastIndex(this byte[] buffer) { return buffer.GetUpperBound(0); } } ```
2010/08/19
[ "https://Stackoverflow.com/questions/3521684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321614/" ]
Same way you do generics in normal (non-extension) methods: Use a placeholder type name introduced in the generic syntax: ``` public static int GetLastIndex<TElement>(this TElement[] buffer) ```
@RHaguiuda You can make constraint like ``` public static class MyExtensions{ public static int GetLastIndex<T>(this T[] buffer) where T: Integer { return buffer.GetUpperBound(0); }} ``` But, type used as a constraint must be an interface, a non-sealed class or a type parameter
2,236,195
I'm having trouble as to seeing what this problem is asking. Am I supposed to create an algorithm that'll find $R^n$ for set R? If I'm just supposed to find $R^n$ for $R$, why does $n$ continue off into infinity? **Definition:** Let $R$ be a relation on the set $A$. The powers $^$, $ = 1, 2, 3, \dots$ are defined recursively by $^1 = $ and $^{+1} = ^ \circ $. The definition shows that $^2 = \circ $, $^3 = R^2 \circ = ( \circ ) \circ $ and so on. Let $ = \{(1,1), (2,1), (3,2), (4,3)\}$. Use the definition above to find $^$, $ = 2, 3, 4, \ldots$
2017/04/16
[ "https://math.stackexchange.com/questions/2236195", "https://math.stackexchange.com", "https://math.stackexchange.com/users/436188/" ]
Compute $R^2$ first. You have $1\to1,$ $2\to 1,$ $3\to 2$ and $4\to 3,$ so composing this with itself, $R^2 = \{(1,1),(2,1),(3,1),(4,2)\}.$ Now do it again, You see how this is going to go?
I think you are asking ``How am I supposed to solve an infinite number of problems?'' Without solving it for you, note that there are a finite number of relations over a finite set, so at some point $R^n$ must repeat itself with a fixed period (maybe even becoming a constant). Have you tried to solve it for some small values?
691,729
I've always known that $\emptyset$ is called an *empty set* or *null*, until recently, when I heard someone calling it *zed*. I looked it everywhere but couldn't find this naming. Is "*zed*" a valid name for the $\emptyset$ symbol?
2014/02/26
[ "https://math.stackexchange.com/questions/691729", "https://math.stackexchange.com", "https://math.stackexchange.com/users/23749/" ]
If we set $$ f(z)=\mathrm{e}^{z}-1, $$ then $$ \frac{f'(z)}{f(z)}=\frac{\mathrm{e}^{z}}{\mathrm{e}^{z}-1}, $$ and $$ \int\_\Gamma\frac{3\mathrm{e}^{z}\,dz}{1-\mathrm{e}^{z}}=-3\int\_{|z|=4\pi/3}\frac{f'(z)\,dz}{f(z)} $$ But $\frac{1}{2\pi i}\int\_{|z|=4\pi/3}\frac{f'(z)\,dz}{f(z)}$ is the number of roots of $f(z)=\mathrm{e}^z-1=0$ in the interior of $\Gamma$. (Argument Principle.) And there is exactly one root $z=0$ is that disc. Therefore, $$ \int\_\Gamma\frac{3\mathrm{e}^{z}\,dz}{1-\mathrm{e}^{z}}=-3\int\_{|z|=4\pi/3}\frac{f'(z)\,dz}{f(z)}=(-3)\cdot 2\pi i\cdot 1=-6\pi i. $$
You have to compute the residue at each $ z \in \mathbb{C} : e^z=1 $. Then take the points which are in the compact component of the complement of $\Gamma$, and sum the residue with the good sign (depends of the orientation of $\Gamma$).
10,532,448
I would like to know what happens "under the hood" with regards to C++ multithreading on Unix (specifically Linux)- particularly the involvement of the OS and semaphores etc. I have performed an initial google search but it is not throwing up. Could somebody please either describe or point me to a good resource that could help? EDIT: When I create a thread in C++, what "objects" are created/stored by the operating system to manage this thread and any associated overheads involved? Have realised this is more a Linux question than a C++ one.
2012/05/10
[ "https://Stackoverflow.com/questions/10532448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1107474/" ]
It depends on what threading library you're using. In C++11, when you use `#include <thread>` the standard C++ library for your platform can choose to use OS-specific features. In the case of Linux this usually is accessed through pthreads, or in other cases direct calls to `clone(...)` with the appropriate flags and interactions via various `ioctls`, `fcntl`, and on some architectures atomic and memory model intrinsics (fences, barriers, etc.). If you're using Boost.Thread in C++03 mode you're basically using pthreads under the hood. All of the constructs in Boost.Thread in POSIX operating systems rely on POSIX threading primitives.
Try running your program with the help of "strace". This will list all system calls made to the operating system.
32,444,728
Hello today I started to work on a project in c# that need to get all files from zip file but the pint was that I need to make it on my own . I can't use other lit or something any idea how to start or even to build something that will work ..... Thanks. Sorry that I don't provide a code but I don't have any .
2015/09/07
[ "https://Stackoverflow.com/questions/32444728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5310203/" ]
.NET Framework has ZipFile class for that. <https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile.openread%28v=vs.110%29.aspx> ``` using System; using System.IO; using System.IO.Compression; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string zipPath = @"c:\example\start.zip"; string extractPath = @"c:\example\extract"; using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) { entry.ExtractToFile(Path.Combine(extractPath, entry.FullName)); } } } } } } ```
As it sounds like you can use the classes provided in the .Net Framework, the MSDN documentation will be a good place to look - [ZipFile Class](https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) This code will extract the files from a given zip file: ``` using System; using System.IO; using System.IO.Compression; namespace ConsoleApplication { class Program { static void Main(string[] args) { string zipPath = @"c:\example\result.zip"; string extractPath = @"c:\example\extract"; ZipFile.ExtractToDirectory(zipPath, extractPath); } } } ```
32,444,728
Hello today I started to work on a project in c# that need to get all files from zip file but the pint was that I need to make it on my own . I can't use other lit or something any idea how to start or even to build something that will work ..... Thanks. Sorry that I don't provide a code but I don't have any .
2015/09/07
[ "https://Stackoverflow.com/questions/32444728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5310203/" ]
.NET Framework has ZipFile class for that. <https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile.openread%28v=vs.110%29.aspx> ``` using System; using System.IO; using System.IO.Compression; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string zipPath = @"c:\example\start.zip"; string extractPath = @"c:\example\extract"; using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) { entry.ExtractToFile(Path.Combine(extractPath, entry.FullName)); } } } } } } ```
If you'd like to do your own unzipping, then you have to understand the .zip file format and all of the technologies that go into file compression and packaging. This is a good place to start: <https://en.wikipedia.org/wiki/Zip_%28file_format%29> Good luck! Zipping and unzipping is not simple!
225,446
We have to train the client professionals on the source code for an application we developed. What shall I include in their training plan for source code? Any help would be really appreciated. regards
2008/10/22
[ "https://Stackoverflow.com/questions/225446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This may help: [What are the core elements to include in Support Documentation?](https://stackoverflow.com/questions/205374/what-are-the-core-elements-to-include-in-support-documentation)
You could highlight the important design decisions. So they understand why you have chosen which solution.
225,446
We have to train the client professionals on the source code for an application we developed. What shall I include in their training plan for source code? Any help would be really appreciated. regards
2008/10/22
[ "https://Stackoverflow.com/questions/225446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1.) If possible show them various changes/revisions the code has gone through, then that will help them to understand the code design at some higher level. (That function needs to be modified for what feature?) 2.) Extract some function Call-Graph/Function-flow diagram using some tool and let them get familiar with that. 3.) The test setup for the application should be explained to them. 4.) High level Design & Low level design document -AD
You could highlight the important design decisions. So they understand why you have chosen which solution.
28,654,003
I have a simple dataframe in pandas that has two numeric columns. I want to make a histogram out of the columns using matplotlib through pandas. The example below does not work: ``` In [6]: pandas.__version__ Out[6]: '0.14.1' In [7]: df Out[7]: a b 0 1 20 1 2 40 2 3 30 3 4 30 4 4 3 5 3 5 In [8]: df.plot(kind="hist") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-8-4f53176a4683> in <module>() ----> 1 df.plot(kind="hist") /software/lib/python2.7/site-packages/pandas/tools/plotting.pyc in plot_frame(frame, x, y, subplots, sharex, sharey, use_index, figsize, grid, legend, rot, ax, style, title, xlim, ylim, logx, logy, xticks, yticks, kind, sort_columns, fontsize, secondary_y, **kwds) 2095 klass = _plot_klass[kind] 2096 else: -> 2097 raise ValueError('Invalid chart type given %s' % kind) 2098 2099 if kind in _dataframe_kinds: ValueError: Invalid chart type given hist ``` why does it say invalid chart type? the columns are numeric and can be made into histograms.
2015/02/22
[ "https://Stackoverflow.com/questions/28654003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4572586/" ]
`DataFrame` has its own `hist` method: ``` df =pd.DataFrame({'col1':np.random.randn(100),'col2':np.random.randn(100)}) df.hist(layout=(1,2)) ``` draws a histogram for each valid column of the `dataframe`. ![enter image description here](https://i.stack.imgur.com/jXOkn.png)
I don't believe 'hist' was a supported type in 0.14.1. Try df.hist() instead
1,118,958
i created a Ext.TreePanel and i would have in the node an image, in the text of the node i have the url to the image but i can't load it in the page, i see only the text, there is the possibility to view the image? this is my code ``` var root1 = new Tree.AsyncTreeNode({ text: 'Legenda degli starti PAT', draggable:true, // disable root node dragging id:'source' }); var tree1 = new Tree.TreePanel({ renderTo : 'legend', animate:true, loader: new Tree.TreeLoader({dataUrl:'legend.php'}), containerScroll: true, root: root1, }); ``` and this is the response of the TreePanel request ``` [{"text":"comuni","id":"co","leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\ /cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1 .1&LAYER=comuni&REQUEST=GetLegendGraphic","id":"comuni","leaf":true,"cls":"file"}]},{"text":"idrografia" ,"id":"id","leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv ?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=idrografia &REQUEST=GetLegendGraphic","id":"idrografia","leaf":true,"cls":"file"}]},{"text":"viabilita","id":"via" ,"leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home \/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=viabilita&REQUEST=GetLegendGraphic" ,"id":"viabilita","leaf":true,"cls":"file"}]},{"text":"uso_suolo","id":"uso","leaf":false,"cls":"folder" ,"children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms .map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=uso_suolo&REQUEST=GetLegendGraphic","id":"uso_suolo" ,"leaf":true,"cls":"file"}]},{"text":"catasto","id":"cat","leaf":false,"cls":"folder","children":[{"text" :"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms &FORMAT=png&VERSION=1.1.1&LAYER=catasto&REQUEST=GetLegendGraphic","id":"catasto","leaf":true,"cls":"file" }]}] ``` thank's Luca
2009/07/13
[ "https://Stackoverflow.com/questions/1118958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to include an "iconCls" attribute for node in your JSON that references a CSS class defining the image you want to show up for that particular node. Per the API docs on extjs.com: // specify the property in the config for the class: ... iconCls: 'my-icon' // css class that specifies background image to be used as the icon image: .my-icon { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; } So your JSON is going to look like this: [{"text":"comuni","id":"co","leaf":false,"cls":"folder","children":[{"text":"http://localhost\ /cgi-bin/mapserv?map=/home/gis/mapserver/cartocomune\_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1 .1&LAYER=comuni&REQUEST=GetLegendGraphic","id":"comuni","leaf":true,"cls":"file", **"iconCls": "my-icon"**}]},{"text":"idrografia" ,"id":"id","leaf":false,"cls":"folder", **"iconCls": "my-icon**"} ... etc.. etc...}]
Well, it's not clear what your issue is -- do you see image placeholders? If so, you may need to double-check that [Ext.BLANK\_IMAGE\_URL](http://extjs.com/deploy/dev/docs/?class=Ext&member=BLANK_IMAGE_URL) is set correctly. If you are trying to load custom images, inspect the rendered tree nodes in Firebug -- are your image tags rendered correctly with the proper urls? Also check the Net tab in Firebug and see if you have any broken image references.
1,118,958
i created a Ext.TreePanel and i would have in the node an image, in the text of the node i have the url to the image but i can't load it in the page, i see only the text, there is the possibility to view the image? this is my code ``` var root1 = new Tree.AsyncTreeNode({ text: 'Legenda degli starti PAT', draggable:true, // disable root node dragging id:'source' }); var tree1 = new Tree.TreePanel({ renderTo : 'legend', animate:true, loader: new Tree.TreeLoader({dataUrl:'legend.php'}), containerScroll: true, root: root1, }); ``` and this is the response of the TreePanel request ``` [{"text":"comuni","id":"co","leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\ /cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1 .1&LAYER=comuni&REQUEST=GetLegendGraphic","id":"comuni","leaf":true,"cls":"file"}]},{"text":"idrografia" ,"id":"id","leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv ?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=idrografia &REQUEST=GetLegendGraphic","id":"idrografia","leaf":true,"cls":"file"}]},{"text":"viabilita","id":"via" ,"leaf":false,"cls":"folder","children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home \/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=viabilita&REQUEST=GetLegendGraphic" ,"id":"viabilita","leaf":true,"cls":"file"}]},{"text":"uso_suolo","id":"uso","leaf":false,"cls":"folder" ,"children":[{"text":"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms .map&SERVICE=wms&FORMAT=png&VERSION=1.1.1&LAYER=uso_suolo&REQUEST=GetLegendGraphic","id":"uso_suolo" ,"leaf":true,"cls":"file"}]},{"text":"catasto","id":"cat","leaf":false,"cls":"folder","children":[{"text" :"http:\/\/localhost\/cgi-bin\/mapserv?map=\/home\/gis\/mapserver\/cartocomune_wms.map&SERVICE=wms &FORMAT=png&VERSION=1.1.1&LAYER=catasto&REQUEST=GetLegendGraphic","id":"catasto","leaf":true,"cls":"file" }]}] ``` thank's Luca
2009/07/13
[ "https://Stackoverflow.com/questions/1118958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to include an "iconCls" attribute for node in your JSON that references a CSS class defining the image you want to show up for that particular node. Per the API docs on extjs.com: // specify the property in the config for the class: ... iconCls: 'my-icon' // css class that specifies background image to be used as the icon image: .my-icon { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; } So your JSON is going to look like this: [{"text":"comuni","id":"co","leaf":false,"cls":"folder","children":[{"text":"http://localhost\ /cgi-bin/mapserv?map=/home/gis/mapserver/cartocomune\_wms.map&SERVICE=wms&FORMAT=png&VERSION=1.1 .1&LAYER=comuni&REQUEST=GetLegendGraphic","id":"comuni","leaf":true,"cls":"file", **"iconCls": "my-icon"**}]},{"text":"idrografia" ,"id":"id","leaf":false,"cls":"folder", **"iconCls": "my-icon**"} ... etc.. etc...}]
Ensure your Ext.BLANK\_IMAGE\_URL is properly pointing at the s.gif
236,488
I used Address Book on Mac and I really liked the software. It's simple, easy and it has all the things I needed in an address book. Now, I recently switched to Windows 7 and I am looking for a software which works like Address Book. Light weight with Speed. Even, a Website or a Cloud App which syncs contacts from my system to the cloud is OK.
2011/01/22
[ "https://superuser.com/questions/236488", "https://superuser.com", "https://superuser.com/users/52143/" ]
Since Vista [contacts are built-in](http://windows.microsoft.com/en-US/windows-vista/Managing-your-contacts), if you have MS Office you might also want to consider MS Outlook. Another alternative is [Free Address Book](http://addressbook.gassoftwares.com/). > > Free Address Book is an address book wherewith you can note the addresses, phone numbers, mobile, fax, company name, country, city, website address and email addresses of your contacts and partners. > > > You can easy print list of contacts and details of selected contact. > Phone Book is absolutely free! > > > Organize your contacts easy and fast! > > >
[Google Contacts](https://www.google.com/contacts/). Plus Android and addressbook nirvana arrives regardless of computing platform.
236,488
I used Address Book on Mac and I really liked the software. It's simple, easy and it has all the things I needed in an address book. Now, I recently switched to Windows 7 and I am looking for a software which works like Address Book. Light weight with Speed. Even, a Website or a Cloud App which syncs contacts from my system to the cloud is OK.
2011/01/22
[ "https://superuser.com/questions/236488", "https://superuser.com", "https://superuser.com/users/52143/" ]
Since Vista [contacts are built-in](http://windows.microsoft.com/en-US/windows-vista/Managing-your-contacts), if you have MS Office you might also want to consider MS Outlook. Another alternative is [Free Address Book](http://addressbook.gassoftwares.com/). > > Free Address Book is an address book wherewith you can note the addresses, phone numbers, mobile, fax, company name, country, city, website address and email addresses of your contacts and partners. > > > You can easy print list of contacts and details of selected contact. > Phone Book is absolutely free! > > > Organize your contacts easy and fast! > > >
What do you use for email? Thunderbird and the Contacts extension work for me. And I access my contacts on my phone as well with Google.
62,174,656
I got the specific problem from [here](https://www.mathworks.com/help/stats/hidden-markov-models-hmm.html) and wanted to implement it on Cplint as Im learning now the principles of ProbLog [![using the above HMM as an example](https://i.stack.imgur.com/N0ung.png)](https://i.stack.imgur.com/N0ung.png) So from the above model we get A red die, having six sides, labeled 1 through 6. • A green die, having twelve sides, five of which are labeled 2 through 6, while the remaining seven sides are labeled 1. • A weighted red coin, for which the probability of heads is 0.9 and the probability of tails is 0.1. • A weighted green coin, for which the probability of heads is 0.95 and the probability of tails is 0.05. As a solution, I want to create a sequence of numbers from the set {1, 2, 3, 4, 5, 6} with the following rules: • Begin by rolling the red die and writing down the number that comes up, which is the emission/observation. • Toss the red coin and do one of the following: ➢ If the result is heads, roll the red die and write down the result. ➢ If the result is tails, roll the green die and write down the result. • At each subsequent step, you flip the coin that has the same color as the die you rolled in the previous step. If the coin comes up heads, roll the same die as in the previous step. If the coin comes up tails, switch to the other die. My state diagram for this model has two states, red and green, as shown in the figure. In addition, this figure shows: 1) the state-transition probability matrix A, b) the discrete emission/observation probabilities matrix B, and 3) the initial (prior) probabilities matrix π. The model is not hidden because you know the sequence of states from the colors of the coins and dice. Suppose, however, that someone else is generating the emissions/observations without showing you the dice or the coins. All you see is the sequence of emissions/observations. If you start seeing more 1s than other numbers, you might suspect that the model is in the green state, but you cannot be sure because you cannot see the color of the die being rolled. Consider the Hidden Markov Model `(HMM) M=(A, B, π)`, assuming an observation sequence `O=<1,1,2,2,3,6,1,1,1,3>` what is the probability the hidden sequence to be ``` H =<RC,GC, GC,RC, RC,GC, GC,GC,GC,GC> ``` where RC and GC stand for Read Coin and Green Coin respectively. Use the cplint or ProbLog to calculate the probability that the model M generated the sequence O. That is, calculate the probability ``` P(H|O) = P(<RC,GC, GC,RC, RC,GC, GC,GC, GC,GC>| <1,1,2,2,3,6,1,1,1,3>) ``` What I did so far are two approaches. 1) ``` :- use_module(library(pita)). :- if(current_predicate(use_rendering/1)). :- use_rendering(c3). :- use_rendering(graphviz). :- endif. :- pita. :- begin_lpad. hmm(O):-hmm1(_,O). hmm1(S,O):-hmm(q1,[],S,O). hmm(end,S,S,[]). hmm(Q,S0,S,[L|O]):- Q\= end, next_state(Q,Q1,S0), letter(Q,L,S0), hmm(Q1,[Q|S0],S,O). next_state(q1,q1,S):0.9; next_state(q1,q2,S):0.1. next_state(q2,q1,S):0.05; next_state(q2,q2,S):0.95. letter(q1,rd1,S):1/6; letter(q1,rd2,S):1/6; letter(q1,rd3,S):1/6; letter(q1,rd4,S):1/6; letter(q1,rd5,S):1/6; letter(q1,rd6,S):1/6. letter(q2,gd1,S):7/12; letter(q2,gd2,S):1/12; letter(q2,gd3,S):1/12; letter(q2,gd4,S):1/12; letter(q2,gd5,S):1/12; letter(q2,gd6,S):1/12. :- end_lpad. state_diagram(digraph(G)):- findall(edge(A -> B,[label=P]), (clause(next_state(A,B,_,_,_), (get_var_n(_,_,_,_,Probs,_),equalityc(_,_,N,_))), nth0(N,Probs,P)), G). ``` which Im creating the diagram and the 2 one is this which I just creating the two coins and dices. I dont know how to continue from this. The 1st one is specific from a example from cplint. I cannot find any other forum specified for this kind of tasks. Seems like problog is "dead" ``` :- use_module(library(pita)). :- if(current_predicate(use_rendering/1)). :- use_rendering(c3). :- endif. :- pita. :- begin_lpad. heads(RC): 0.9; tails(RC) : 0.1:- toss(RC). heads(GC): 0.95; tails(GC) : 0.05:- toss(GC). toss(rc); RD(0,1):1/6;RD(0,2):1/6;RD(0,3):1/6;RD(0,4):1/6;RD(0,5):1/6;RD(0,6):1/6. RD(0,1):1/6;RD(0,2):1/6;RD(0,3):1/6;RD(0,4):1/6;RD(0,5):1/6;RD(0,6):1/6:- X1 is X-1,X1>=0, RD(X1,_), \+ RD(X1,6) GD(0,1):1/12;GD(0,2):1/12;GD(0,3):1/12;GD(0,4):1/12;GD(0,5):1/12;GD(0,6):7/12. GD(0,1):1/12;GD(0,2):1/12;GD(0,3):1/12;GD(0,4):1/12;GD(0,5):1/12;GD(0,6):7/12:- X1 is X1-1,X1>=0, GD(X1,_), \+ GD(X1,12). toss(RC). toss(GC). :- end_lpad. ```
2020/06/03
[ "https://Stackoverflow.com/questions/62174656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12619262/" ]
Not sure if this is still useful but in ProbLog you could have tried something like this: ``` %% Probabilities 1/6::red_die(1,T) ; 1/6::red_die(2,T) ; 1/6::red_die(3,T) ; 1/6::red_die(4,T) ; 1/6::red_die(5,T) ; 1/6::red_die(6,T). 7/12::green_die(1,T) ; 1/12::green_die(2,T) ; 1/12::green_die(3,T) ; 1/12::green_die(4,T) ; 1/12::green_die(5,T) ; 1/12::green_die(6,T). 0.9::red_coin_head(T). 0.95::green_coin_head(T). %% Rules % Start with tossing red toss_red(1). % Toss red if previous toss was red, head. toss_red(T) :- T > 1, Tprev is T - 1, toss_red(Tprev), red_coin_head(Tprev). % Toss red if previous toss was green but tails. toss_red(T) :- T > 1, Tprev is T - 1, toss_green(Tprev), \+green_coin_head(Tprev). % Toss green if previous toss was green, head. toss_green(T) :- T > 1, Tprev is T - 1, toss_green(Tprev), green_coin_head(Tprev). % Toss green if previous toss was red but tails. toss_green(T) :- T > 1, Tprev is T - 1, toss_red(Tprev), \+red_coin_head(Tprev). % Writing results from red_die if next toss is red. results([X],1) :- red_die(X,1), toss_red(1). results([X|Y],T) :- T > 1, Tprev is T - 1, red_die(X,T), toss_red(T), results(Y,Tprev). % Writing results from green_die if next toss is green. results([X|Y],T) :- T > 1, Tprev is T - 1, green_die(X,T), toss_green(T), results(Y,Tprev). results(X) :- length(X, Length), results(X,Length). results(X) :- length(X, Length), results(X,Length). % Query query_state :- toss_red(1), toss_green(2), toss_green(2), toss_red(3), toss_red(4), toss_green(5), toss_green(6), toss_green(7), toss_green(8), toss_green(9). toss_green(10). evidence(results([1,1,2,2,3,6,1,1,1,3])). query(query_state). ``` Which according to [this](https://dtai.cs.kuleuven.be/problog/editor.html#task=prob&hash=c21033afd32f96e960d9f06a1eca4dca) has a probability of 0.00011567338
hmmpos.pl from [here](http://cplint.ml.unife.it/example/inference/inference_examples.swinb) seems to be usefull enough to continue
58,572,085
We have gRPC stream to share data between two micro services, an API and a Worker (both created in Golang). The intention is to listener about the status of jobs being processed by Worker service pods. So, the communication is one-directional (Worker sends updates to Api). The figure below shows it. [![enter image description here](https://i.stack.imgur.com/0eh2Z.png)](https://i.stack.imgur.com/0eh2Z.png) Our problem is, how can I managed to know when Worker's pod scales up, in order to subscribe to new Worker pod (by stream)? The figure below shows the problem. [![enter image description here](https://i.stack.imgur.com/6Vp7U.png)](https://i.stack.imgur.com/6Vp7U.png)
2019/10/26
[ "https://Stackoverflow.com/questions/58572085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2463840/" ]
I have got a simple method to resolve that: ``` struct ContentView : View { @State var isPresented = false var body: some View { NavigationView { HStack{ NavigationLink(destination: MyDetailView(message: "Detail Page #2") ,isActive: $isPresented) { Text("Go detail Page #2 >") .onTapGesture { //Do somethings here print("onTapGesture") //Navigate self.isPresented = true } } .navigationBarTitle("Index Page #1") } } } } ```
You can handle methods from lifecycle using: ``` .onAppear { print("ContentView appeared!") } ``` And: ``` .onDisappear { print("ContentView disappeared!") } ``` check this tutorial: <https://www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear> So, you can use the `.onDisappear` to perform any action you need
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
Just checking that you intend to be [reinventing-the-wheel](/questions/tagged/reinventing-the-wheel "show questions tagged 'reinventing-the-wheel'"), you can do: ``` System.out.println("happy".indexOf("app")); ``` You did know that, right? Or, if you want to reformat the 'signature' to match yours, it is: ``` public static int subStringIndex(String str, String substr) { return str.indexOf(substr); } ``` There are a number of helper methods on String which will help: * [String.indexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) - return the index of the first occurrence of substr * [String.indexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String,%20int%29) - return the index of the first occurrence of substr on or after the start position. * [String.lastIndexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String%29) - return the index of the last occurrence of substr * [String.lastIndexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String,%20int%29) - return the index of the last occurrence of substr starting **before** the start position. -
Actually there is a bug. Consider `str="aaS"` and `substr="aS"`. At first iteration `a` and `a` are equal. At second iteration `a` and `S` are not equal, and it will skip it, however `substr`'s first character is equal to it. So it should be: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; if (substrlen >= 1) { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring j++; // iterate if (j == substrlen) { // when to stop return i - (substrlen - 1); //found substring. As i is currently at the end of our substr so sub substrlen } } else { i -= j; j = 0; } } } return -1; } ``` **Edit update:** Needed to subtract 1 from the String's length in order to pass the right answer.
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
Just checking that you intend to be [reinventing-the-wheel](/questions/tagged/reinventing-the-wheel "show questions tagged 'reinventing-the-wheel'"), you can do: ``` System.out.println("happy".indexOf("app")); ``` You did know that, right? Or, if you want to reformat the 'signature' to match yours, it is: ``` public static int subStringIndex(String str, String substr) { return str.indexOf(substr); } ``` There are a number of helper methods on String which will help: * [String.indexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) - return the index of the first occurrence of substr * [String.indexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String,%20int%29) - return the index of the first occurrence of substr on or after the start position. * [String.lastIndexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String%29) - return the index of the last occurrence of substr * [String.lastIndexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String,%20int%29) - return the index of the last occurrence of substr starting **before** the start position. -
Here is another version: ``` public static int indexOf(String original, String find) { if (find.length() < 1) return -1; boolean flag = false; for (int i = 0, k = 0; i < original.length(); i++) { if (original.charAt(i) == find.charAt(k)) { k++; flag = true; if (k == find.length()) return i - k + 1; } else { k = 0; if (flag) { i--; flag = false; } } } return -1; } ```
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
Just checking that you intend to be [reinventing-the-wheel](/questions/tagged/reinventing-the-wheel "show questions tagged 'reinventing-the-wheel'"), you can do: ``` System.out.println("happy".indexOf("app")); ``` You did know that, right? Or, if you want to reformat the 'signature' to match yours, it is: ``` public static int subStringIndex(String str, String substr) { return str.indexOf(substr); } ``` There are a number of helper methods on String which will help: * [String.indexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String%29) - return the index of the first occurrence of substr * [String.indexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf%28java.lang.String,%20int%29) - return the index of the first occurrence of substr on or after the start position. * [String.lastIndexOf(substr)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String%29) - return the index of the last occurrence of substr * [String.lastIndexOf(substr, start)](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#lastIndexOf%28java.lang.String,%20int%29) - return the index of the last occurrence of substr starting **before** the start position. -
My re-writing: clear and clean, yet efficient. There is no innovation in the algorithm. Just the way of the coding in more structural re-arrangement, trying to make the thought and steps easy to read and understand (comments are welcome): ``` static int subStringIndex( String str, String substring) { if (substring.length() < 1 ) return -1; int L = str.length(); int l = substring.length(); int index = -1; for (int i = 0, j; i <= L-l; i++) { // if the remaining (L-i) is smaller than l, // there won't be no enough length to contain the substring. for (j = 0; j < l; j++) { if (substring.charAt(j) != str.charAt(i+j) ) { break; } } // has it reached the end of the shorter string? // if so, it means no non-equals encountered. if (j == l) { index = i; break; } } return index; } ```
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
You can get away without the `index` variable as you're reassigning it at each step of your loop anyway. ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; if (substrlen >= 1) { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring j++; // iterate if (j == substrlen) { // when to stop return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen } } else { j = 0; } } } return -1; } ```
Actually there is a bug. Consider `str="aaS"` and `substr="aS"`. At first iteration `a` and `a` are equal. At second iteration `a` and `S` are not equal, and it will skip it, however `substr`'s first character is equal to it. So it should be: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; if (substrlen >= 1) { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring j++; // iterate if (j == substrlen) { // when to stop return i - (substrlen - 1); //found substring. As i is currently at the end of our substr so sub substrlen } } else { i -= j; j = 0; } } } return -1; } ``` **Edit update:** Needed to subtract 1 from the String's length in order to pass the right answer.
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
You can get away without the `index` variable as you're reassigning it at each step of your loop anyway. ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; if (substrlen >= 1) { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring j++; // iterate if (j == substrlen) { // when to stop return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen } } else { j = 0; } } } return -1; } ```
Here is another version: ``` public static int indexOf(String original, String find) { if (find.length() < 1) return -1; boolean flag = false; for (int i = 0, k = 0; i < original.length(); i++) { if (original.charAt(i) == find.charAt(k)) { k++; flag = true; if (k == find.length()) return i - k + 1; } else { k = 0; if (flag) { i--; flag = false; } } } return -1; } ```
38,870
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance? Example: > > str = "happy" substr = "app" > > > index = 1 > > > My code: ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; int index = -1; if (substrlen < 1) { return index; } else { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring index = i - j; // remember index j++; // iterate if (j == substrlen) { // when to stop return index; } } else { j = 0; index = -1; } } } return index; } ```
2014/01/09
[ "https://codereview.stackexchange.com/questions/38870", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/32250/" ]
You can get away without the `index` variable as you're reassigning it at each step of your loop anyway. ``` public static int subStringIndex(String str, String substr) { int substrlen = substr.length(); int strlen = str.length(); int j = 0; if (substrlen >= 1) { for (int i = 0; i < strlen; i++) { // iterate through main string if (str.charAt(i) == substr.charAt(j)) { // check substring j++; // iterate if (j == substrlen) { // when to stop return i - substrlen; //found substring. As i is currently at the end of our substr so sub substrlen } } else { j = 0; } } } return -1; } ```
My re-writing: clear and clean, yet efficient. There is no innovation in the algorithm. Just the way of the coding in more structural re-arrangement, trying to make the thought and steps easy to read and understand (comments are welcome): ``` static int subStringIndex( String str, String substring) { if (substring.length() < 1 ) return -1; int L = str.length(); int l = substring.length(); int index = -1; for (int i = 0, j; i <= L-l; i++) { // if the remaining (L-i) is smaller than l, // there won't be no enough length to contain the substring. for (j = 0; j < l; j++) { if (substring.charAt(j) != str.charAt(i+j) ) { break; } } // has it reached the end of the shorter string? // if so, it means no non-equals encountered. if (j == l) { index = i; break; } } return index; } ```