Do we want a reference question about the basic rules of chess?

Question: So I noticed this question about the basic rules of chess has a (current) score of -3, but it has no close votes. I myself can't find an objective reason to close it based on the current standards.
Would it be good and on-topic to have a reference question on the essential rules of chess? How should we go about having an established question-and-answer?
Alternatively, do we expect that users coming to Chess.SE already have a basic understanding of chess rules?
Answer:
So I noticed this question about the basic rules of chess has a
  (current) score of -3, but it has no close votes. I myself can't find
  an objective reason to close it based on the current standards.

I agree. I also can't find any objective reason to close it although I see that, perhaps based off this question, 3 people have voted to close it.
The reasons for downvoting a question are not the same as those for deleting it although clearly there is some correlation. If you hover over the down button the pop-up "This question does not show any research effort; it is unclear or not useful" appears but "not useful" is not one of the reasons to delete. Nor is "does not show any research effort".

Would it be good and on-topic to have a reference question on the
  essential rules of chess?

My initial reaction was that people who come here should already know how to play chess but then after reflection I changed my mind. We should be more welcoming.
Comment: the "more welcoming" nonsense has done irreparable damage to the entire SE network over the past six months or so
Answer: Don't need one. This is not a place to teach people how to play the game from scratch. LQ questions draw in LQ users and LQ meta questions!


Overlapping Markers with AngularGM directive

Question: I have two markers that are very close to each other. When the map is zoomed out they overlap.
Problem: There is a marker event that changes the icon of one of the markers but it won't show for the marker that is behind. Is there a way to bring the marker to the front? Perhaps using CSS or some event with angularGM API ?
Answer: You can manually obtain and modify a marker's z-index using the getZIndex() and setZIndex() marker methods.
Documentation:
https://developers.google.com/maps/documentation/javascript/3.exp/reference#Marker
Comment: The only problem is I don't have access to getZIndex() marker method from the angularGM marker. Or I am unaware how to retrieve the correct marker object.
Comment: According to the documentation for `angularGM` - the `google.maps.Marker` object is passed as the second argument to any marker event callback function. That is the object that has the `getZIndex()` and `setZIndex()` methods.


How can I partially reveal and partially fill color in image

Question: In my project I'm displaying image like this,

But according to user progress I want to hide the partial image.
Example :  If user process is 75% than my image will display like this,

One idea is that I will use some variation of image and show image according to the percentage. But if I can achieve this programmatically with one image than it will be better. plz help for this problem.
Comment: I would test it with CISwipeTransition.
Answer: What you need is image masking. From apple docs -

An image mask is a bitmap that specifies an area to paint, but not the
  color. In effect, an image mask acts as a stencil to specify where to
  place color on the page. Quartz uses the current fill color to paint
  an image mask.

So as your percentage of download increases you decrease the alpha value of the uiimage below. Hope this is what you require.
Comment: Yes my second idea is to use this mask. for that i have seen this link `http://jeroendeleeuw.com/post/33638733049/how-to-mask-images-with-core-graphics-in-ios` but still not sure how to add it in my situation.
Answer: Guys i have done it using this code :
 UIImage * flagImage = [UIImage imageNamed:flagImageStr];  //this is image of the flag
    UIImage * maskImg = [UIImage imageNamed:@"mask4.png"];  //Created heart shape mask image

    UIImage *image = [self maskImage:flagImage withMask:maskImg];
    CALayer *layer = partialFlagIV.layer;  //partialFlagIV is my imageview name
    layer.shadowOpacity = .9;
    layer.shadowColor = [[UIColor blackColor] CGColor];
    layer.shadowOffset = CGSizeMake(0,0);
    layer.shadowRadius = 2;

    partialFlagIV.image = image;

    int percentage = [percentageStr integerValue];  //percentageStr value will decide how much part of image will be in other color
    int percentageValue = 100-percentage;

    int maskImgYValue = (percentageValue*80)/100;
    int imgYvalue;
    if (percentageValue<40) {
        imgYvalue = 305-(maskImgYValue*4);
    }else{
        imgYvalue = 305-(maskImgYValue*3.8);
    }

//This code is needed when i use app in iPad bcoze of size of partialFlagIV is larger in iPad
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        int baseValue = 80+(percentage*0.2);
        percentage = baseValue-percentage;
        maskImgYValue = maskImgYValue+percentage;
    }

    UIImageView *aImageView = [[UIImageView alloc] initWithFrame:CGRectMake(partialFlagIV.frame.origin.x, partialFlagIV.frame.origin.y, partialFlagIV.frame.size.width,maskImgYValue)];  //created another imageview to place it on the partialFlagIV so it will display like color field in partialFlagIV

    aImageView.backgroundColor = [UIColor clearColor];
    image = [self imageByCropping:image toRect:CGRectMake(0, 0, image.size.width, image.size.height-imgYvalue)];  //this method is used to crop my flage image

    aImageView.image = [self newImageFromMaskImage:image  inColor:[UIColor colorWithRed:(186/255.0) green:(57/255.0) blue:(38/255.0) alpha:1]];   //this method will create mask image with given color
    [self.view addSubview:aImageView];
    [self.view bringSubviewToFront:aImageView];

//this method will crop the flag imge to heart shape
-(UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropped;
}

//this method will create color image using mask image
-(UIImage *) newImageFromMaskImage:(UIImage *)mask inColor:(UIColor *) color {
    CGImageRef maskImage = mask.CGImage;
    CGFloat width = mask.size.width;
    CGFloat height = mask.size.height;
    CGRect bounds = CGRectMake(0,0,width,height);

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClipToMask(bitmapContext, bounds, maskImage);
    CGContextSetFillColorWithColor(bitmapContext, color.CGColor);
    CGContextFillRect(bitmapContext, bounds);

    CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(bitmapContext);
    CGContextRelease(bitmapContext);

    UIImage *result = [UIImage imageWithCGImage:mainViewContentBitmapContext];
    return result;
}

Added comment to explain codes.Hope it help future user.


Capistrano fails to locate assets manfiest

Question: I am trying to deploy a Rails 3.2 app to Ubuntu 13.04 with Capistrano 2.15.5. After successful cap deploy:setup, Capistrano fails during cap deploy:cold with:
failed: "sh -c 'ls /srv/www/application/shared/assets/manifest*'"
I am deploying precompiled assets with manifest.yml present in public/assets.
Full output of failing task:
triggering after callbacks for `deploy:update_code'
* 2013-11-24 23:06:43 executing `deploy:assets:precompile'
  triggering before callbacks for `deploy:assets:precompile'
* 2013-11-24 23:06:43 executing `deploy:assets:update_asset_mtimes'
* executing "[ -e /srv/www/application/shared/assets/manifest* ] && cat /srv/www/application/shared/assets/manifest* || echo"
  servers: ["18.104.22.168"]
  [188.8.131.52] executing command
  command finished in 443ms
* executing "cd -- /srv/www/application/releases/20131124190639 && RAILS_ENV=production RAILS_GROUPS=assets #<Capistrano::Configuration::Namespaces::Namespace:0x007f66b2e9a898> assets:precompile"
  servers: ["22.214.171.124"]
  [188.8.131.52] executing command
  command finished in 439ms
* executing "ls -1 /srv/www/application/shared/assets/manifest* | wc -l"
  servers: ["188.8.131.52"]
  [126.96.36.199] executing command
  command finished in 569ms
* executing "ls /srv/www/application/shared/assets/manifest*"
  servers: ["22.214.171.124"]
  [188.8.131.52] executing command
  command finished in 575ms
*** [deploy:update_code] rolling back
* executing "rm -rf /srv/www/application/releases/20131124190639; true"
  servers: ["220.127.116.11"]
  [18.104.22.168] executing command
  command finished in 458ms
failed: "sh -c 'ls /srv/www/application/shared/assets/manifest*'"

How do I fix it?
Answer: The problem was in
executing "cd -- /srv/www/application/releases/20131124190639 && RAILS_ENV=production RAILS_GROUPS=assets #<Capistrano::Configuration::Namespaces::Namespace:0x007f66b2e9a898> assets:precompile"
Here Capistrano replaced rake with a namespace object. This happened because I created a namespace :rake in my deploy file. Didn't know it could result in such a bug.
Renaming the namespace solved the issue.
Comment: wow I had this issue and it took me forever trying to figure out what the problem was. Thanks!


When sending data using MPI in Fortran, does it have to be an array?

Question: This is a pretty simple question. I'm practicing using MPI in Fortran, and as far as I can tell, the sending and receiving sources must be arrays, like this:
    do 20 i = 1, 25
    final_sum(1) = final_sum(1) + random_numbers(i)
20  continue
    print *, 'process final sum: ', final_sum(1)
    call MPI_GATHER(final_sum,1,MPI_INTEGER,sum_recv_buff,1,MPI_INTEGER,0,MPI_COMM_WORLD,ierror)

Here, I'm using the array final_sum to hold a single value. Is there a better way to do this? This is my first time using Fortran, and since I've already done some practice in C, I was trying out Fortran to see the differences and similarities.
Comment: No, you can send scalars, scalar derived-types and arrays of derived-types too.  Investigate MPI derived datatypes.
Answer: High Performance Mark is right. There is actually normally no type checking when calling MPI routines that work with buffers. The MPI routines make use of the Fortran feature that enables calling procedures with implicit interface. On machine language level just a pointer is passed (it may be a pointer to a temporary copy!). That means you can use scalars or arrays without any problem. Just use count 1 and the correct MPI type and you can pass and receive scalars.
The MPI derived types is a feature that will enable you to work with even more complicated pieces of data.


How to expand Box Composable by toggleSwitch(Android , Jetpack Compose)

Question: I am developing on dividing the composable in the box in the form of a column using Jetpack composable. I would like to know if other composable are affected by the size of the composable in the box and can be resized automatically.
The shape of the calendar changes according to the change of the custom toggle Switch in TopAppBar. According to the shape of the calendar, I would like to change the size of the box's Row-type text under the calendar, such as being pulled and pushed.
How can i fix it?
Code:
val states = listOf("월간", "주간")
    var selectedOption by remember { mutableStateOf(states[0]) }

    val onSelectionChange = { text: String -> selectedOption = text }

    var isVisible by remember { mutableStateOf(false) }
Scaffold(topBar = {
        TopAppBar(title = {
            Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
                Row(modifier = Modifier
                    .width(115.dp)
                    .height(35.dp)
                    .clip(shape = RoundedCornerShape(24.dp))
                    .background(Color(0xffe9e9ed))
                    .padding(start = 10.dp, end = 5.dp, top = 6.dp, bottom = 5.dp)) {
                    states.forEach { text ->
                        Text(text = text,
                            fontSize = 10.sp,
                            lineHeight = 16.sp,
                            color = if (text == selectedOption) {
                                Color.Black
                            } else {
                                Color.Gray
                            },
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier
                                .clip(shape = RoundedCornerShape(24.dp))
                                .clickable {
                                    onSelectionChange(text)
                                    isVisible = (text == states[1])
//                                            isVisible = !isVisible
                                }
                                .background(if (text == selectedOption) {
                                    Color.White
                                } else {
                                    Color(0xffe9e9ed)
                                })
                                .padding(
                                    vertical = 5.dp,
                                    horizontal = 16.dp,
                                ))
                    }
                }
            }
        },
            actions = {
                IconButton(onClick = {
                    goDetailProfile(NAV_ROUTE.PROFILE, routeAction)
                }) {
                    Icon(imageVector = Icons.Filled.Menu, contentDescription = "profile")
                }
            },
            colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color.White,
                titleContentColor = Color.Black))
    }) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xfff0f0f0))) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f),
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(shape = RoundedCornerShape(bottomStart = 30.dp, bottomEnd = 30.dp))) {
                    if (isVisible) {
                        Kalendar(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 45.dp)
                                .clip(shape = RoundedCornerShape(bottomStart = 30.dp,
                                    bottomEnd = 30.dp)),
                            kalendarHeaderConfig = KalendarHeaderConfig(
                                kalendarTextConfig = KalendarTextConfig(
                                    kalendarTextColor = KalendarTextColor(Color.Black),
                                    kalendarTextSize = KalendarTextSize.SubTitle)
                            ),
//                            kalendarEvents = List<KalendarDay> (
//                                size = ,
//                                init =
//                                    ),
                            kalendarType = KalendarType.Oceanic(),
                            kalendarDayColors = KalendarDayColors(Color.Black, Color.Black),
                            kalendarThemeColor = KalendarThemeColor(backgroundColor = Color.White,
                                dayBackgroundColor = Color(0xffFBE3C7),
                                headerTextColor = Color.Black),
                            onCurrentDayClick = { kalendarDay: KalendarDay, kalendarEvents: List<KalendarEvent> ->

                                year = kalendarDay.localDate.year
                                month = kalendarDay.localDate.monthNumber
                                day = kalendarDay.localDate.dayOfMonth

                                readTodo(token, year, month, day, response = {

                                    todoList.clear()
                                    for (i in it!!.data) {
                                        todoList.add(i)
                                    }
                                })
                            })
                    } else {
                        Kalendar(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 25.dp)
                                .clip(
                                    shape = RoundedCornerShape(
                                        bottomStart = 30.dp,
                                        bottomEnd = 30.dp)),
                            kalendarHeaderConfig = KalendarHeaderConfig(kalendarTextConfig = KalendarTextConfig(
                                kalendarTextColor = KalendarTextColor(Color.Black),
                                kalendarTextSize = KalendarTextSize.SubTitle)),
//                            com.himanshoe.kalendar.component.day.KalendarDay(kalendarDay =,
//                                selectedKalendarDay =,
//                                kalendarDayColors =,
//                                dotColor =,
//                                dayBackgroundColor =),
//                            kalendarEvents = List<KalendarEvent>(
//
//                            ),
                            kalendarType = KalendarType.Firey,
                            kalendarDayColors = KalendarDayColors(Color.Black, Color.Black),
                            kalendarThemeColor = KalendarThemeColor(backgroundColor = Color.White,
                                dayBackgroundColor = Color(0xffFBE3C7),
                                headerTextColor = Color.Black),
                            onCurrentDayClick = { kalendarDay: KalendarDay, kalendarEvents: List<KalendarEvent> ->

                                year = kalendarDay.localDate.year
                                month = kalendarDay.localDate.monthNumber
                                day = kalendarDay.localDate.dayOfMonth

                                readTodo(token, year, month, day, response = {

                                    todoList.clear()
                                    for (i in it!!.data) {
                                        todoList.add(i)
                                    }
                                })
                            })
                    }
                }
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .padding(top = 30.dp)
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 21.dp, end = 21.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = day.toString(),
                            fontSize = 26.sp,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.padding(end = 5.dp)
                        )

                        Divider(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(start = 5.dp),
                            color = Color(0xffD8D8D8)
                        )
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(top = 50.dp),
                        contentAlignment = Alignment.TopCenter
                    ) {
                        TodoItemList(Todo = todoList)
                    }
                }
            }
        }
}

Answer: I am developing a calendar app in Jetpack Compose, and I am using the Column composable to structure the UI. First, I compose either the MonthView or the WeekView, and then I compose the TasksList. By doing this, when the user toggles between the MonthView and the WeekView, the TasksList is automatically adjusted by the Column layout.
@Composable
fun MyCalendar() {

    Column {
        if (isMonthView) {
            MonthView()
        } else {
            WeekView()
        }
        TasksList()
    }
}

Comment: thx to advise! how can u develop toogles abt Jetpack Compose?
Comment: can you elaborate ?
Comment: yes, i made a toggleSwitch to custom. here is my code.https://gist.github.com/ParkJongJoon7128/23b3813cbc33b3b6f186c0018dc25339
I want to know how to code more effectively.


Can salt water kill bacteria in septic tank

Question: My septic tank has open bottom and as it's rainy season and the salt water from the ground (clay) is coming up to a foot, but I'm wondering whether it can kill all the bacteria (anaerobic, aerobic) which eats away the sludge?
Also I'm wondering if there are any recommended liquids or something which increases biological activity in the septic tank. (I'm finding some septic tank cleaners but there are both equal and negative reviews.)
The toilet cleaners like Harpic etc, does have to power to kill off bacteria's in septic tank.
What about hot waters impact on the biological system inside the septic tank?
It'd be good to have some insights into this.
Comment: I don't think any chemicals should be added to the septic system, as it eventually gets into the groundwater, which often is the source of your drinking water. Instead, you shall follow the good practices of septic system construction. Here is a good reference, https://www.epa.gov/septic/types-septic-systems
Comment: add sugar if you want more microbes. it does wonders for composting, giving it a jump start.
Comment: The link that you have shared is quite useful. I'm grateful for it. Thanks
Answer: Yes, many things that end up in a septic tank can harm the bacteria that break down wastes.  You've named a few such as salt water and cleaning products.  Also things like medications that you take, especially antibiotics can affect the bacteria.
Generally septic tanks rely on the sheer volume of the tank contents vs. the influx of harmful agents but at times the incoming can overwhelm the tank.  Over time the bacteria should recover but there are any number of commercial products that claim to replenish the helpful flora. You can find these are hardware stores as well as from septic tank service companies.
Comment: Pro-biotics are also a thing, they are sold OTC as a digestive aid.
Comment: Thanks , probably try some pro-biotics


Why does the borrow checker not understand that borrowing different parts of a slice is fundamentally okay?

Question: The split_at_mut function (for splitting mutable slices at an index) requires unsafe code (according to the Rust book) to be implemented. But the book also says: "Borrowing different parts of a slice is fundamentally okay because the two slices aren't overlapping".
My question: Why does the borrow checker not understand that borrowing different parts of a slice is fundamentally okay? (Is there a reason preventing the borrow checker from understanding this rule or is it just that it has not been implemented for some reason?)
Trying the suggested code with Rust 1.48 still results in the error shown in the book:
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = slice.len();

    assert!(mid <= len);

    (&mut slice[..mid], &mut slice[mid..])
}

fn main() {
    let mut vector = vec![1, 2, 3, 4, 5, 6];
    let (left, right) = split_at_mut(&mut vector, 3);
    println!("{:?}, {:?}", left, right);
}

Gives error message:
error[E0499]: cannot borrow `*slice` as mutable more than once at a time
 --> src/main.rs:6:30
  |
1 | fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
  |                        - let's call the lifetime of this reference `'1`
...
6 |     (&mut slice[..mid], &mut slice[mid..])
  |     -------------------------^^^^^--------
  |     |     |                  |
  |     |     |                  second mutable borrow occurs here
  |     |     first mutable borrow occurs here
  |     returning this value requires that `*slice` is borrowed for `'1`

Comment: I'm sure you're already aware of this and were just asking for a better understanding of the borrow checker, but for future readers it's probably worth noting that the slice primitive does of course provide a safe [`split_at_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_at_mut) method (but which, like much of the standard library, is implemented with unsafe operations to overcome this problem).
Answer:
Why does the borrow checker not understand that borrowing different parts of a slice is fundamentally okay?

Because it's impossible to do generally. Sure, in this case it's obvious that &slice[..mid] and &slice[mid..] are disjoint, but the complexity skyrockets once you escape trivial cases and it quickly becomes impossible.
These special trivial cases aren't implemented specially because:

Having a language feature that allows obviously disjoint slice borrows but not anything even slightly more complicated is unintuitive and can make beginners think they can do more things than they actually can
These special cases really only boil down to a couple patterns, most of which can be accomplished with split_at and its mutable counterpart
There's no way to reliably extend this to anything with the Index trait, which means that (&slice[..mid], &slice[mid..]) would be valid but (&vec[..mid], &vec[mid..]) wouldn't be, which is even more inconsistent. Of course this could be solved by making Vec a language intrinsic, but then what about VecDeque or user-defined data structures? It just leads to too much inconsistency that spirals into more inconsistency, which is something that Rust wants to avoid.
Comment: VecDeque still supports individual indexing, which may lead to things like `&vecdeque[0]` and `&vecdeque[1]` being disallowed despite clearly being valid. `Vec` is an entirely custom data structure, and vector slices work by [implementing the `Index` trait for ranges](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-Index%3CI%3E).
Comment: Basically the compiler would have to store which ranges of the slice are already borrowed to decide this, which could get quite complicated/impossible depending on the datatype.
Comment: Storing ranges isn't possible if the indices aren't constants known at compile time.
Comment: Could you elaborate a bit on how vector slices complicate the picture? Are string slices and vector slices not both references to array underneath the hood? VecDeque does not support slicing because of possible wrap-around, but does support turning into a pair of slices, which are again array references.
Answer: Rust's borrow checker can't understand that you're borrowing different parts of the slice; it only knows that you're borrowing from the same slice twice. What if the two slices are overlapping? There's no way to grantee that their not. (If there is, it isn't implemented yet)
That's why unsafe exists: when you know for sure that there's no way that your code will produce an unexpected behavior despite the compiler not being able to grantee that.
Comment: @IInspectable It's obvious to you, but not to the compiler, which must be able to handle arbitrarily complex slicing expressions. Proving that they don't overlap in the general case is equivalent to the halting problem i.e. theoretically impossible. For the trivial case where the slice is split by a middle element there is `split_at_mut` which removes the need to special-case this in the compiler.
Comment: *"Rust's borrow checker can't understand that you're borrowing different parts of the slice"* - I'm not sure this is accurate. With `(&mut slice[..mid], &mut slice[mid..])` it's obvious, at compile time, that the slices don't overlap. I understand, that this is not true in general, but in this specific case that reasoning isn't convincing.
Comment: This is rather special. A pure syntactic analysis would fail for this pattern `(&mut slice[..mid], dec(&mut mid), &mut slice[mid..])` (given that dec decreases the argument by 1). So a constraint solver on ranges bound to each expression used as range or index of an array is needed. But solving these constraints in general is undecidable, so `unsafe` will be needed anyway. Also an incomplete solver can get quite expensive if one incorporate intraprocedural constraints.
Comment: @use I'm not questioning that there were valid reasons. Just pointing out that this proposed answer doesn't attempt to answer the specific question. Your comment is far more useful in making a convincing argument.


How do I find the horizontal/vertical asymptotes of an equation, if any?

Question: I have the function $$f(x)=\frac{2x^2}{x^2-1}$$
and I need to find the horizontal and vertical asymptotes if any exist. The problem is I'm completely lost. The only thing I know is that the domain restrictions are $x\ne1, x\ne-1$. That only tells me there's a hole in the function though.
I know how to find asymptotes with problems like $\lim\limits_{x\to5}$ -- it would be a horizontal asymptote at $x=5$. I just don't understand how to do this problem. I think it has something to do with infinity but I'm not sure how to even figure that out.
Thanks in advanced for any help.
Comment: See my answer to [this question](https://math.stackexchange.com/questions/3366442/limit-of-polynomial-division-lim-limits-n-to-infty-fracfngn/3366457#3366457) for the horizontal asymptote.
Answer: We have that

$\lim_{x\to \pm \infty} \frac{2x^2}{x^2-1} =2$

therefore $y=2$ in an horizontal asymptote and since $x^2-1=0 \implies x=\pm 1$ and

$\lim_{x\to 1^+} \frac{2x^2}{x^2-1} =\infty$
$\lim_{x\to 1^-} \frac{2x^2}{x^2-1} =-\infty$
$\lim_{x\to -1^+} \frac{2x^2}{x^2-1} =-\infty$
$\lim_{x\to -1^-} \frac{2x^2}{x^2-1} =\infty$

therefore $x=-1$ and $x=1$ are vertical asymptotes.
Comment: I must be more lost than I thought because I'm not seeing how you get 2 in the first step. I'm also not seeing how you get +- infinity as x approaches 1/-1 just by looking at the equation.
Answer: Try sketching the curve. What happens near the "holes" in the domain? What happens when $x$ is large? When $x$ is negative and far from $0$? You can think about those things numerically or with some algebra.
When you see the picture and understand what is going on you can write things out more formally with limits, but that's not where you should begin with a question like this.
Answer: It may help to write rational functions on this form:
$\begin{cases}
f(x)=\dfrac{2x^2}{x^2-1}=2-\dfrac 1{x+1}+\dfrac 1{x-1}\\\\
g(x)=\dfrac{2x^3+9x^2+4x+10}{x^2+3x-4}=(2x+3)-\dfrac 2{x+4}+\dfrac 5{x-1}\end{cases}$

There are two types of asymptotic behaviour for a rational function:

Asymptotic behaviour in the neighbourhood of a single point or pole:

Whenever your function has a pole at $x_0$, i.e. terms with denominators $\dfrac 1{(x-x_0)^m}$ the function takes $\pm\infty$ values depending on the oddness of $m$ when $x$ becomes close to $x_0$.
In this case we say that the line whose equation is $x=x_0$ is a vertical asymptote.
$f$ has vertical asymptotes $x=1$ and $x=-1$ and $g$ has vertical asymptotes $x=-4$ and $x=1$

Asymptotic behaviour at infinity:

This time we are interested in the values of the function whenever $x\to\pm\infty$
For $f$ we have $f(x)\to 2$ and we say that the line $y=2$ is an horizontal asymptote.
But you can as well have asymptotes with any slope, for instance $g(x)$ behaves like $2x+3$ at infinity thus we say that the line $y=2x+3$ is an asymptote for $g$.

Note that asymptotic behaviour at infinity may not always be a straight line, for instance $h(x)=x^2-\frac 1x$ is asymptotic to the parabola $y=x^2$.
We just give a special preference to straight lines, because they are simple objects.


Ubuntu auto mount exfat drive allow_other non root users access

Question: Issue

I have an exfat formatted drive.
I'm able to unmount and mount it on an ubuntu 20.04 desktop.
I can read files from it, however, I can only write files as root/sudo user. I've tried a lot of different settings with no success. Saw some comments about allow_other flag using fuseblk which I couldn't get fuseblk working.

I was able to use the ubuntu graphical disks application to mount and unmount. But still had issues with non root write permission.
Some other commands:

mkdir /home/drive1 mount point
sudo umount -f -l /home/drive1 force umount drive
code /etc/fstab using visual studio code to open fstab and modify mount permissions
sudo mount -a mount all drives in /etc/fstab, used to verify that mount settings aren't broken
chown won't work for nfs and fat drives
chmod 777 also won't work although there are some comments on +x executable working

test user access

cd /home/drive1
mkdir test fails
sudo mkdir test works
touch file.txt fails
sudo touch file.txt works

mount attempts:

sudo mount /dev/sdb2 /home/drive1 -o rw,uid=yourusername,gid=yourusername, sudo still required to write files

id yourusername

sudo mount -t vfat /dev/sdb2 /home/drive1 -o rw,umask=0000 runs but root still required
sudo mount -t exfat /dev/sdb2 /home/drive1 -o uid=1000,gid=1000 same issue
sudo mount -t exfat /dev/sdb2 /home/drive1 -o rw,allow_other,umask=0000 fails to mount with allow_other

purpose

trying to use external auto mounted exfat formatted drive as a volume for a docker container, read working, but write failing (even in docker container privileged mode)

current solution

since I wasn't able to get any progress I decided to use nfs format instead which didn't have this sudo issue. I could also try fedora instead and see if it still has the sudo exfat issue.
Comment: Read `man mount` paying attention to the `Mount options for fat` section. You can specify the `uid=`, `gid=`, `umask=` and other useful parameters.
Comment: yes it's 20.04, I don't know what you mean by snap **only**, I've had to remove snaps and apt install to fix some broken apps. @waltinator I've tried all those options with no success.
Comment: The mount options waltinator mentioned should be the way to go. After that recheck with `ls -la` if the files and folders and your mount point itself are still beeing owned by root. If that is the case do a chown on that mountpoint, files and folders again.
Comment: @AlexOnLinux I think you missed the point, chown doesn't work on an exfat formatted drive. I ended up changing to nfs format instead.
Comment: @lastlink thx, i really missed that
Comment: I have the exact same issue, no matter what I use for options, it mounts it the exact same way.

/dev/sda2 on /mnt/1 type exfat (rw,relatime,fmask=0022,dmask=0022,iocharset=utf8,namecase=0,errors=remount-ro)
Answer: After days of searching and try new things I make it work.

Unmount the drive
make new mount directory
install the exFat utilities from ubuntu with sudo apt-get install exfat-fuse exfat-utils
After that sudo mount -a and I have write access as user in my exFat directory

my fstab looks like
UUID=XXXX-XXXX /media/user/hdd exfat users,exec,rw,suid,dev,atime,diratime,uid=(1000,0),umask=000 0 0
Comment: does it stay mounted and working after a machine restart? I noticed that you mount using sudo `sudo mount -a`
Comment: yes it is stay mounted


how to access a widget from another class

Question: I have two classes(MyWidget,ViewContact). In MyWidget, there is a QLineEdit and QListWidget. The contents in the QListWidget changes dynamically while changes in QLineEditt.
In ViewContact class there is many widgets.The ViewContact class is called by MyWidget class.
void MyWidget::viewbind(QListWidgetItem *item)
{
    LblNames *widget = (LblNames*)( listWidget->itemWidget(item) );
    ViewContacts *v=new ViewContacts(widget->getLabelId());
    v->show();
}

then ViewContact widget shown as a window,no problem.works fine.
while clicking an update button inside ViewContact class i need to close that window and change the text inside MyWidget .now i just close the ViewContact by this.close(); function.
I give QLineEdit as public and try to change the text. No errors occur. But no changes display in QLineEdit inside MyWidget
Answer: Add the MyWidget as a parent to your ViewContacts instance. This will allow you to call a function to update the text (and it will also fix the memory leak which you currently have in your code).
You need a constructor for your ViewContacts that takes both a parent and the labelId.
class ViewContacts : public QWidget // or whatever it is, you didn't tell
{
    Q_OBJECT
public:
    // I don't know the class of "LabelId" either
    explicit ViewContacts(LabelId id, QObject* parent = 0) : QWidget(parent)
    {
        // ...
    }

    void updateTextInParent()
    {
        MyWidget* w = qobject_cast<MyWidget*>(this->parent());
        if (NULL != w)
        {
            // w is a valid pointer to a MyWidget instance
            // you can access any public fields and function through it.
        }
    }
 };

You should also use qobject_cast or dynamic_cast in the snippet you provided because a blind cast is not safe.
Answer: This seems like a perfect time to take advantage of Qt's signals and slots. You can connect a signal that emits the value you want to update in your MyWidget object, from your ViewContacts widget.
First you'll need to create a signal that emits the changed value when the ViewContacts widget is closed.
Something like:
Q_SIGNALS:
    void value_changed_signal( QString value );

Next you'll want to add a slot, it can be private, in your MyWidget parent class
The declaration would look something like:
private Q_SLOTS:
    void update_text( QString value );

Finally, in your MyWidget class, somewhere after you have instantiated your ViewContacts object, connect the signal and slot with something like:
connect(new_view_contacts_object, SIGNAL( value_changed_signal( QString ) ),
    this, SLOT( update_text( QString ) ) );

Answer: Add a signal in the ViewContact class and emit a signal while close ViewContact Widget.The signal should contain a string to bind your list view.Before initiating ViewContact Widget from MyWidget ,should connect the signal and setText(const QString) slot.


Where is 'open in terminal'?

Question: I'm trying to figure out where is 'open in terminal' when right clicking inside a folder?
Last time I used it was in Ubuntu 10.10 and since upgrading have no luck with it.
I gave up on Unity and using Gnome but still can't find it.
Answer: you need install a package named nautilus-open-terminal :

or:
sudo apt-get install nautilus-open-terminal

and restart nautilus:
nautilus -q && sleep 1 && nautilus -n

or logout and login again.

Where is 'open in terminal'?


Icon/asset catalog for development

Question: A friend of mine currently is going through process of face-lifting existing application and it's nightmare when it comes to icons for buttons.
For example there are five different icons for "information". Similar situation is with other actions.
Is there any best practices/recomendations on creating list of assets which can be used in development for representing particular actions? Like - for "save" you use only this icon.
Answer: As far as I know, there is no such a thing.
However, you must make one yourself, specific for your application, your set of applications, or your company, depending on how far you want to be consistent. It's called a UX Style Guide. If it's just for one application you may also include it in the functional specifications of the UI for that application.
The reason why you ended up in that situation is because different developers are only looking for a solution within their own work, without caring what other developers do. If you ask 1 developer "put a button here with an information icon on it", he will just use Google to find a suitable icon. If you ask another developer to "put a button there with an information icon on it" he will do the same, and it would be a very lucky coincidence if both programmers would end up using the same icon.
A style guide, or a clear functional specification is a good way to deal with this. This will make sure you will have a consistent UI style throughout the entire application. Mind that these guidelines can describe many aspects of the UI, not just usage of icons. If you say that the icons are inconsistent within your application, I bet other things are also inconsistent.
Comment: I understand very clear, why such situation has arised :) And even have some ideas how this should be approached. Main reason why I'm asking this is to "don't invent bycicle"
Comment: Of course, this is a very legitimate question (which is why I upvoted it). But I don't think there is such a thing as a 'universal style guide'. The only thing close is the MS UX Interaction Guidelines (http://msdn.microsoft.com/en-us/library/windows/desktop/aa511258.aspx), but that will not go into the detail of giving icon-suggestions.
Answer: Guidelines
Documents similar to Microsoft's guide on creating the best user experience / Ux.stackexchange theme
How to develop an effective gui standard / PDF book by Eric M. Schaffer
Color codes

Icon design

Visual information is perceived much quicker when instead of the same objects you see distinct silhouettes.
Why Distinct Icon Outlines Help Users Scan Faster
In situations when it is impossible to create a clear mental model visualization use the text description.
For example is quite problematic to represent a condition "It is occupied" on the telephone line.
9 rules for clear and intuituve icons
Comment: Re the distinct icon outlines helping users scan faster - [it's not necessarily so](http://ux.stackexchange.com/questions/8040/do-unique-icon-contours-help-people-scan).
Comment: Very nice resources and I'll definately pass them to her. Unfortunately seems that sample **how to define asset catalog** doesn't exist. So bycicle must be invented :)
Answer: If you have the resources, ability, and buy-in...
Skip the documentation and create a reusable library of UI components that provides all the common elements developers need.
This is not easily accomplished, but it actually makes developers lives easier in the long run (and it's harder to ignore than StyleGuide.pdf on the company intranet).
Answer: Every major development platform has a corresponding style guide that fills some or all this purpose.
They are variously referred to as UX Guidelines, Human Interface Guidelines, Style Manual and Usage Guides. Exact naming varies mostly by scope. These documents usually are available as part of the platform's developer documentation.
Comment: That's how it should be. Most UI developers however have never even heard of this. Therefor it is useful to refer to such documents when handing over UI programming work to a developer.

Icon/asset catalog for development


GFCI breaker tripping to pool pump

Question: I have an in ground swimming pool.  There is an outdoor sub panel with a 20amp GFCI breaker is connected to the pump.  Today we had a bad rain storm...water coming down cats and dogs in every direction.
After the storm, I noticed my pool pump wasn't working.  The breaker had tripped.  I tried to turn it on, and it went off immediately.
So, I swapped out the breaker and the same thing happened....so it's not the breaker.  Tomorrow, I am going to disconnect and wirenut the wires from the pump (disconnect the pump).  If the breaker doesn't trip after that I will conclude there is a short in the wires running through the conduit...right?
Because it will be a pain to pull the wires and replace....which I am ok to run (temporarily, just to make sure it will work) the wires directly from the panel to the pump without putting them in the conduit right away.  When I say "not right away" I mean long enough to make sure the breaker doesn't trip.  If it doesn't trip then I would pull all the old wires and snake the new ones through.
I figured I would run this concept by the people here and get some feedback on this plan.
Thanks
Comment: Just a thought, but if you need to re-run wire, would it be possible to tie the new wire to the pump-side of the old wire, and pull the old wire out of the conduit from the not-pump-side, as opposed to pulling the old wire and then snaking the new one in separate steps? That would, in theory anyway, pull the old wire out at the same time as running the new one.
Comment: @GabeEvans -- yeah, that's a fairly common trick AIUI (using the old wire to help you get the new wire in)
Comment: We always like the "just wait" and the problem is fixed may work here.
Comment: Well you might not have the problem I once had a snake got into the motor and was causing my GFCI to trip this was just skin not the critter, after cleaning things up it worked great... Probably not the same problem but something to think about.
Comment: I hope not!  But if it fixes my issue I'll take it.  Part of me is hoping it just dries out and works in the morning without doing anything else.
Comment: Good idea.  I think that would work
Comment: I'm betting on either a water-induced short or a flood-induced clog which is stalling the motor.
Comment: Well the issue is with the pump. Disconnected the pump and the breaker worked fine.  Lucky for me there is a 2 year warranty and company is sending out someone to see what's going on.
Comment: @JonHirschman -- post an answer when the serviceman is done :)
Comment: Will do. Hopefully they will come in the next few days.
Comment: Please come back and accept one of the two answers you supplied. (Actually, merging them into one accepted answer and deleting the other would be ideal!) The SE system will automatically bump this question to the main page every now and then because it doesn't have an accepted answer.
Answer: So here is the end of the story.   After a week of hot dry weather the breaker didn't trip anymore.  On Friday morning I tired to turn it on and it stayed on.  So wherever the moisture was......was gone.  At this point not sure of this is a temporary fix or log term.  I put some electrical tape around a few of the areas that should already be water tight.  I guess I will find out if temp or perm fix next time we have a bad rain storm.  Cancelled the warrantee repair because I am sure they will fix something this is t broken when they arrive.  Thanks for all the help and advice.
Answer: Ok, the story continued.  The next rain same thing happened.  Pool guy came back and changed out the keypad on the pump.  When removing it he said whoever installed it left off some of the gaskets and it was full of water (where water is not supposed to be). So he fixed that and so far all is good.   Not sure why it took 3 years to have any issue, but glad it is now fixed!
Answer: Not the worst idea to drill a drain hole in the bottom of the keypad, if possible, and maybe stuff it with some kind of vinyl mesh or leave out a section of the gasket on the bottom. Rain seldom falls UP.
Comment: Yes, but condensation frequently "falls" up...  @JACK The keypad is mentioned in one of the self-answers. Apparently some people think SE is a discussion forum...
Answer: Was the replacement breaker also a GFI breaker? Sometimes if those GFI DEVICES even smell moisture they will trip. Change to a regular breaker without the GFI and go from there.
Comment: Hello, and welcome to Stack Exchange. The original breaker was probably GFI because it was required by code, as well as being a good idea.
Comment: It was also gfi. That was only backup I had

GFCI breaker tripping to pool pump


How to access dictionary when index is datetime?

Question: I have multiple csv-files each containing two columns. The first contains the timestamp and the second column contains a measurement value.
Lets assume the csv-file looks like this:
Date,Temperature (Celsius)
2018-07-24T20:45:31,28.86
2018-07-24T20:35:31,29.06
2018-07-24T20:25:31,29.19
2018-07-24T20:15:32,29.31
2018-07-24T20:05:31,29.48
2018-07-24T19:55:31,29.58
2018-07-24T19:45:31,29.82
2018-07-24T19:35:32,30.32
2018-07-24T19:25:31,31.00

and I import it like this:
df = pd.read_csv(csv-file, sep=',', header = 0, usecols=[0, 1], parse_dates=[0], infer_datetime_format=True)
dd = df.set_index('Date').T.to_dict()

I thought this would be convenient later, when I would search for the same key (same timestamp) in multiple files in order to merge them.
However I cannot access the dictionary. The keys are recognised as timestamp.
dd.keys()

dict_keys([Timestamp('2018-07-24 20:45:31'), Timestamp('2018-07-24 20:35:31'), Timestamp('2018-07-24 20:25:31'), Timestamp('2018-07-24 20:15:32'), Timestamp('2018-07-24 20:05:31'), Timestamp('2018-07-24 19:55:31'), Timestamp('2018-07-24 19:45:31'), Timestamp('2018-07-24 19:35:32'), Timestamp('2018-07-24 19:25:31')])

How do I access the values?
dd["2018-07-24 20:45:31"]["Temperature (Celsius)"]

does not work, so I tried
dd[Timestamp("2018-07-24 20:45:31")]["Temperature (Celsius)"]

which does not work either.
I was wondering if it might be forbidden to use a timestamp as a key, but if not, than how do I access my data?
Comment: I guess your problem is already solved.
Check this [link](https://stackoverflow.com/questions/35946387/python-dictionary-datetime-as-key-keyerror) out.
Comment: I found this question as well, but I could not figure out how I access the data. Could you help me out here? How do I read out the temperature at this (2018-07-24 20:45:31) point in time?
Answer: Each of the Timestamp keys you see are instances of pandas.Timestamp. You should pass your keys with pd.Timestamp, like so:
import pandas as pd

df = pd.read_csv(
    'file.csv', sep=',', header = 0, usecols=[0, 1], parse_dates=[0], infer_datetime_format=True
)
dd = df.set_index('Date').T.to_dict()

print(dd[pd.Timestamp('2018-07-24 20:45:31')]['Temperature (Celsius)']) # prints 28.86

Comment: Alternatively, you can add a `from pandas import Timestamp` and your code will work.
Comment: I see, I was under the impression that the "Timestamp" was somehow universal not tied to pandas. Thanks for pointing that out.
Comment:  thanks, I did check whether the conversion preserves it, but I did not think about using it when looking through a dictionary. SOLVED.


PHP iteration foreach, omitting characters from last iteration

Question: I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }

Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
    $title  = ($go['media_title'] == '') ? ' ' : $go['media_title'];
    $caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];

    $a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
    $a .= ",\n";

$i++;
return $a;
}

Many thanks for your experience,

orionrush
Comment: oh please use JSON, like json_encode
Comment: you return statement is inside the for loop. is it type?
Comment: Gaurav - typo on my part thanks for flagging that up.
Answer: $a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";

and use it by
return implode(",\n", $a);

Comment: as I am outputing directly to javascript, json isn't unfortunately an option for me. This is the solution I ended up going with.
Answer: You should really use json_encode().
$data = array();
foreach ($pages as $go) {
    $title  = ($go['media_title'] == '') ? ' ' : $go['media_title'];
    $caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];

    $data[] = array(
        'image' => BASEURL . GIMGS . '/' . $go['media_file'],
        'title' => $title . ', ' . $caption,
        'url' => BASEURL . GIMGS . '/' . $go['media_file']
    );
}

echo json_encode($data);

Comment: ThiefMaster - I can see now why folks are pushing json here - And thanks for your answer being so appropriate for my situation.
Comment: Hey  - got locked out of my own comment!
The output is on the right track, but generates a lot of extra quotes and backslashes:

{"image":"http:\/\/photolumiere.site:8888\/files\/gimgs\/1_photo-32.jpg","title":" ,  ","url":"http:\/\/photolumiere.site:8888\/files\/gimgs\/1_photo-32.jpg"},

For my needs image title etc should not be quoted at all, yet the urls need to be in single quotes. Can you quickly show me how to format the output, or point me to a good technique?
Comment: Just spend a moment looking into json - its not unfortunately going to play nice as my output is going directly to javascript, and its not really an option to rewrite the code base to accept quoted keys etc. Im not able to vote you up but thanks for your help. Im going to have to go down the implode route.
Comment: If your output is "directly going to javascript" you can simply put something like `var stuff = ;` and it will work since JSON is a subset of JavaScript.
Answer: foreach ($pages as $go){
    $return[] = json_encode($go);
}

return implode(",\n", $return);

do what you like in the foreach, the implode will comma separate the lines like you want
Answer: just chop the end off with substr:
return substr($a, 0, -3);


Compile Lib Jingle

Question: I am trying to use the Libjingle library By GYP
I follow the readme
I run the following commands
$ gclient config http://libjingle.googlecode.com/svn/trunk
$ gclient sync --force
But i do not get any libjingle libraries in the folder
Has anyone else faced the problem?.
Is there any good tutorial for Libjingle which would give me step by step instructions?
Thanks in advance
Nitesh
Answer: You have to have the depot_tools downloaded and you have to make sure that you add the depot_tools folder to your path.
<code>git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
export PATH="$PATH":path/to/depot_tools
</code>
Comment: thanks a lot. it worked.
I am trying to connect an android device and Computer for filesharing any tutorials you can point me too?

Compile Lib Jingle


Python 3 .format and List

Question: I am looking to print out results from a list built in my Python program.
I will take the results of the values in the lists and print them out separated by tabs.
I have a list called 'a' and I will just select the element to produce the final table.
But when I use the .format method, I have had to call the list four times.
a = [1,2,3,4]
print('a{[0]}\ta{[3]}\ta{[1]}\ta{[2]}'.format(a, a, a, a))

Output:
a1  a4  a2  a3

is there a better method of telling the format command to use list 'a' each time?
Answer: You can use the *(single asterisk) to unpack the list for you. See also: Unpack a list
a = [1,2,3,4]
print('a{0}\ta{3}\ta{1}\ta{2}'.format(*a))

Comment: print('a{0}\ta{3}\ta{1}\ta{2}'.format(*a)) worked. [0] wasn't necessary to select the element. Thanks.
Answer: If you're using Python 3.6 an up, you can use f-strings if you like:
a = [1, 2, 3, 4]
result = f"a{a[0]}\ta{a[3]}\ta{a[1]}\ta{a[2]}"
print(result)

but it's not very extensible if a ever changes it's dimensions.
If the order didn't matter I'd be more inclined to do something more along the lines of:
a = [1, 2, 3, 4]
result = "\t".join(f"a{x}" for x in a)
print(result)

This uses a comprehension to create a sequence of strings formatted the way you want, then join them together with tabs.
If order (or only selecting certain items) is important, but you still wanted to use something like this, you could try:
a = [1, 2, 3, 4]
indexes = [0, 3, 1, 2]
result = "\t".join(f"a{a[i]}" for i in indexes)
print(result)

That way you can change the size of a, or the order you want just by changing those lists and the code will "just work" (presuming that you don't go outside the bounds of the list). So if you wanted to just print indexes 2 and 3:
a = [1, 2, 3, 4]
indexes = [2, 3]
result = "\t".join(f"a{a[i]}" for i in indexes)
print(result)

Answer: This doesn't directly answer your question, but I'd just join the list with a tab:
"\t".join( map(str, [1, 2, 3, 4]) )

This inserts a tab between each element of the list, then joins the result together as a string.
Unfortunately, the map is required here to convert each number to a string before being given to join.
Comment: This won't work directly with the OP's code - `str.join` only works on strings. It'll fail with a `TypeError`.
Comment: @LexyStardust I know, I just realized that. Forgot Python is relatively strongly typed.
Comment: You can easily map them to strings first: `'\t'.join(map(str, [1,2,3,4]))`
Comment: @Alvra already updated. Thanks. Was fiddling with QPython on my phone. Slow going.
Comment: If you don't "like" the look of map (I'm not a fan) you could also use comprehensions (which I've provided as an example in my answer).
Comment: @LexyStardust I don't mind the map. It was just such a nice succinct bit before adding it. It's a little verbose looking now. All a comprehension would do is reduce a level of parentheses, which I suppose would make it less noisy.
Answer: You can index a list inside the format string and pass the argument by name so you can easily reuse it.
print('a{a[0]}\ta{a[3]}\ta{a[1]}\ta{a[2]}'.format(a=[1,2,3,4]))

Python 3 .format and List


ValueError: Target size (torch.Size([128])) must be the same as input size (torch.Size([112]))

Question: I have a training function, in which inside there are two vectors:
d_labels_a = torch.zeros(128)
d_labels_b = torch.ones(128)

Then I have these features:
# Compute output
features_a = nets[0](input_a)
features_b = nets[1](input_b)
features_c = nets[2](inputs)

And then a domain classifier (nets[4]) makes predictions:
d_pred_a = torch.squeeze(nets[4](features_a))
d_pred_b = torch.squeeze(nets[4](features_b))
d_pred_a = d_pred_a.float()
d_pred_b = d_pred_b.float()
print(d_pred_a.shape)

The error raises in the loss function: `            pred_a = torch.squeeze(nets3)
pred_b = torch.squeeze(nets3)
pred_c = torch.squeeze(nets3)
        loss = criterion(pred_a, labels_a) + criterion(pred_b, labels_b) + criterion(pred_c, labels) + d_criterion(d_pred_a, d_labels_a) + d_criterion(d_pred_b, d_labels_b)

The problem is that d_pred_a/b is different from d_labels_a/b, but only after a certain point. Indeed, when I print the shape of d_pred_a/b it istorch.Size([128])but then it changes totorch.Size([112])` independently.

It comes from here:
# Compute output
features_a = nets[0](input_a)
features_b = nets[1](input_b)
features_c = nets[2](inputs)

because if I print the shape of features_a is torch.Size([128, 2048]) but it changes into torch.Size([112, 2048])
nets[0] is a VGG, like this:
class VGG16(nn.Module):

  def __init__(self, input_size, batch_norm=False):
    super(VGG16, self).__init__()

    self.in_channels,self.in_width,self.in_height = input_size

    self.block_1 = VGGBlock(self.in_channels,64,batch_norm=batch_norm)
    self.block_2 = VGGBlock(64, 128,batch_norm=batch_norm)
    self.block_3 = VGGBlock(128, 256,batch_norm=batch_norm)
    self.block_4 = VGGBlock(256,512,batch_norm=batch_norm)

  @property
  def input_size(self):
      return self.in_channels,self.in_width,self.in_height

  def forward(self, x):

    x = self.block_1(x)
    x = self.block_2(x)
    x = self.block_3(x)
    x = self.block_4(x)
    # x = self.avgpool(x)
    x = torch.flatten(x,1)

    return x

Answer: I solved. The problem was the last batch. I used drop_last=True in the dataloader and It worked.


latex freezes Firefox

Question: I want to use LaTex in Xubuntu 18.04.1. But it is not possible, because after the very first installation command
$ sudo apt-get install texlive-latex-extra

Firefox does not run properly anymore. It gets permanently blocked with the message "a web page is slowing down your browser". One can click on "stop it", and then it runs again, but this happens every time and is not tolerable. The only way out seems to be, to uninstall lexlive-latex-extra again. Then Firefox runs fine again.
What to do about that?
Following the suggestions from StackOverflow of Jun 7 I have added the output of apt-cache policy firefox texlive-latex-extra:
firefox:
  Installed: 67.0.1+build1-0ubuntu0.18.04.1
  Candidate: 67.0.1+build1-0ubuntu0.18.04.1
  Version table:
 *** 67.0.1+build1-0ubuntu0.18.04.1 500
        500 http://us.archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages
        100 /var/lib/dpkg/status
     59.0.2+build1-0ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu bionic/main amd64 Packages
texlive-latex-extra:
  Installed: 2017.20180305-2
  Candidate: 2017.20180305-2
  Version table:
 *** 2017.20180305-2 500
        500 http://us.archive.ubuntu.com/ubuntu bionic/universe amd64 Packages
        500 http://us.archive.ubuntu.com/ubuntu bionic/universe i386 Packages
        100 /var/lib/dpkg/status

I have 8 GB RAM.
I have never put addons into Firefox. It is just the Firefox which came down with the latest software upgrade.
More information: Following your suggestions I played around. firefox --safe-mode does not fix it. But then I found, that this happens only, if I enter "us.yahoo.com" as internet address. If I start something else on the internet, then firefox runs fine.
But I always start firefox with "us.yahoo.com" from a launcher. That is where the international financial news is. I need that. If I start without the "us." as "yahoo.com" only, then firefox also runs ok. But since I live in the Philippines, then yahoo starts automatically as "ph.yahoo.com". I cannot use that.
I have included the output of firefox for this case:
[Parent 4357, Gecko_IOThread] WARNING: pipe error (102): Connection reset by peer: file /build/firefox-gHMaBx/firefox-67.0.1+build1/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 357
IPDL protocol error: Handler returned error code!

###!!! [Parent][DispatchAsyncMessage] Error: PLayerTransaction::Msg_ReleaseLayer Processing error: message was deserialized, but the handler returned false (indicating failure)

IPDL protocol error: Handler returned error code!

###!!! [Parent][DispatchAsyncMessage] Error: PLayerTransaction::Msg_ReleaseLayer Processing error: message was deserialized, but the handler returned false (indicating failure)

###!!! [Parent][MessageChannel] Error: (msgtype=0x1F0088,name=PBrowser::Msg_Destroy) Closed channel: cannot send/recv

###!!! [Child][MessageChannel] Error: (msgtype=0x360113,name=PContent::Msg_DetachBrowsingContext) Closed channel: cannot send/recv

[Parent 4357, Gecko_IOThread] WARNING: pipe error (132): Connection reset by peer: file /build/firefox-gHMaBx/firefox-67.0.1+build1/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 357

Comment: Do you have any addons in Firefox regarding latex after installation ? You might want to disable any latex addons.
Comment: Please add output of the command `apt-cache policy firefox texlive-latex-extra` to the question by [editing](https://askubuntu.com/posts/1149245/edit) it. I can' t reproduce this on clean upgraded 18.04 LTS and I do not see how Firefox is related to LaTeX (the [texlive filelist](https://packages.ubuntu.com/bionic/all/texlive-latex-extra/filelist) contains nothing about this). Did you tried to run Firefox in Safe Mode (`firefox --safe-mode`) with `texlive-latex-extra` installed? How much RAM do you have?
Answer: The problem is not urgent anymore. After playing around I found that the international version of yahoo can also be started with "www.yahoo.com". That has the same effect as "us.yahoo.com". But "us.yahoo.com" freezes firefox if LaTex is installed, while "www.yahoo.com" does that not. So I can work again.
Regards and thanks for the suggestions.

latex freezes Firefox


Why Thread.start() is needed?

Question: I was working on Threads when a question struck to my mind..If we can directly call run() method with the object of a class like any ordinary method then why do we need to call Thread.start() to call run() method..I tried both the methods as shown and got same result with both of them
First attempt by calling run() method directly
class Abc extends Thread
{
   public void run()
   {
      for(int i=0;i<5;i++)
      {
         System.out.println("Abc");
      }
      try
      {
          Thread.sleep(100);
      }catch(Exception e)
      {
          System.out.println("Error : "+ e);
      }
   }
}

class Xyz extends Thread
{
    public void run()
    {
       try
       {
           for(int i=0;i<5;i++)
           {
               System.out.println("Xyz");
           }
           Thread.sleep(100);
       }catch(Exception e)
       {
            System.out.println("Error : "+ e);
       }
    }
}

public class ThreadDemo
{
    public static void main(String[] args)
    {
        Abc ob=new Abc();
        Xyz oc=new Xyz();
        ob.run();
        oc.run();
    }
}

Second attempt by calling Thread.start()
public class ThreadDemo
{
    public static void main(String[] args)
    {
        Abc ob=new Abc();
        Xyz oc=new Xyz();
        Thread t1,t2;
        t1=new Thread(ob);
        t2=new Thread(oc);
        t1.start();
        t2.start();
    }
}

Comment: thread.start() starts a new call of stack however if you try invoking run directly then it will be invoked under currently executing call stack, i.e. main itself...
Answer: If you call run() directly, the code gets executed in the calling thread. By calling start(), a new Thread is created and executed in parallel.
Comment: @gau123: did you even read what multithreading is used for?
Comment: That's what I am asking..why there is a need to create new thread if the work is done by the calling thread
Comment: @gau123 It's not the same behaviour in the background. If you want multithreading, you need to create a new Thread and run it in parallel. Otherwise there's no point in creating threads. Try playing around with the sleep numbers and you'll see the difference.
Answer: If you directly call run(), then all the work will be done on the main thread.
By using Thread.start, then it will executed on a new thread other than the main thread ;)
Answer: To observe what the difference is, increase your sleep calls to something longer like 10 seconds. This will make it obvious that you need Thread.start to avoid the first task waiting on the second.
In the case where you use Thread.start, you will see that output of both threads appears immediately.
In the case where you use run, you will see that the output of the first appears, then a 10 second delay, then the output of the second.
Comment: +1 but you still need to explain the difference between both of them. There is no mention of single or multiple thread
Comment: yeah but since he didn't mention it anywhere in his question, we need to clarify the whole thing, right? Because from his question, it doesn't seem like he does know the difference
Answer: If you call run() method directly then code will run inline. To run the code in separate thread it is necessary to call Thread.start().
Answer: When you call start() method on thread reference it create span entirely context area. Then thread will have independent stack from where you are calling. More over start() invokes OS native thread to start it in separate memory context.
While run() method invocation considered as simple method call, and you won't have benefit of concurrency as its executing is current stack.
Comment: Mean you are trying to say that to maintain concurrency..i need to call start() method..right ??
Comment: Yes, That is main purpose.

Why Thread.start() is needed?


Dual wield 1H vs 1H + Quiver vs 2H + Quiver?

Question: As a demon hunter, you have three choices:

Dual Weld 1H crossbows
1H crossbow + quiver
2H crossbow/bow + quiver

Given equivalent level items of all of these types, in every single situation I have ALWAYS found the 2H crossbow/bow + quiver to be the highest dps of the three combos. Next highest is 1H crossbow + quiver and the lowest dps is dual weld 1H crossbows.
Is there ever a reason you would ever choose anything but a 2H crossbow/bow + quiver for end game dps? Are there other important factors to think about besides DPS (like attack speed)?
Answer: In general, 1H + Quiver and Dual Wield setups are only worthwhile if the itemization available to you makes them worthwhile. That is to say, if you have access to much a better 1-hander than a 2-hander, than using it instead may make sense, even with a quiver. If you have two of them, dual wielding might even be an option, as there are some stat affixes that will not appear on a Quiver.
That said, thanks to the Archery passive, 2H weapons will generally pull ahead, since a Quiver offsets the normal loss of stats that occurs when using a 2H weapon, the only thing you really give up is the opportunity to equip a shield, and the defensive benefits thereof. But at the end of the day, with items as heavily random as they are, you'll always want to evaluate every weapon individually -  don't rule out a hand xbow just because it isn't a 2 hander. With the right stats, it can still be an upgrade.
Comment: Bravo! Well spoken good sir!
Answer: The ideal 2x 1H would probably be 1000+ dps, 250+ dex, 11% att speed (ain't realy sure what the cap is), +crit dmg, socket.
Add the 15% att speed from dual-wield, and you could dish out some serious dps.
You would probably never see the big numbers you see with an 2H, but much quicker attack speed would cover for that.
2H+quiver for pure dps is the most economical choice, since you get good dps, for less money.
Answer: I do fine using 2 1-handed crossbows, can clear anything on inferno. If you choose to dual wield make sure the DPS is close, or the same, as a single 2-handed weapon.
Answer: dual wielding is actually viable if they both had sockets, and they both had increased crit dps. Archery passive gives 10% crit chance with 1h xbows, and if you put good emeralds in both the 1h.. thats a lot of bonus crit dmg. Now all you need is high base dps, and moar crit dmg/chance/aspd
Answer: You failed to note a 4th option for Demon Hunters, 1H crossbow plus shield which can add substantial defence to your take 30% more damage than barbarian or monk build :)
If your build needs to add +resist all or needs it's block increased the stats on a shield usually play in that favour.


Which is the best combination of gear and traits for a DPS champ?

Question: I am specifically interested how to combine maximum DPS output and achieve maximum morale points. Any suggestions?
Comment: Im not too familiar with this game, but i assume it is a choice. For instance maximum DPS comes at the price that you cannot achieve maximum morale and other attributes
Comment: Hey there! I'm not going to post an answer to this since I know nothing about LOTRO, but this guide may be of interest: http://lotro.mmodb.com/guides/champions-the-ins-and-outs-5.php ...I can't make heads or tails of most of the info :<
Comment: Related? http://gaming.stackexchange.com/questions/4657/best-leveling-spec-for-a-champion-in-lotro/13033#13033
Answer:
Make a Man-Champion or Dwarf-Champion
This will net you addition Might from the start, which increases your melee damage. Might is the opposite of Agility, which increases your ranged damage. Also, Race of Man gets a giant (~3000) self heal at high level. They also get a direct bonus to Morale. But now with today's 15k tanks and with your average player at 7k health, 3k isn't really that much.

However, Dwarf-Champions also get Might bonus. They also get a vitality bonus, which may also help you if you're trying to go for a balanced build. And, at high levels, through racial traits dwarves get Endurance of Stone, which adds 50% to Fire, Shadow, and Common migitations. This means that 1/2 of all Fire, Shadow, and Common will be asorbed you. Also at high levels, they get Dwarf-endurance, which gives a bonus to Vitality.
The most important stats for a build like yours are Might and Vitality
Vitality will increase your Maximum Morale (health). For every point of Vitality you have, you get three points of Morale. For instance, if you have 100 vitality, you will get 300 extra morale, in addition to your base morale (which depends on class/race) and other morale bonuses.
Might will increase your melee damage. Edit: Vitality also adds to your common migitation, and all other migitations (however, the other migitations will not receive as much bonus from just  vitality)
Get an armor set when you're at a high level
One of these will help: http://lotro-wiki.com/index.php/Comparison_of_Champion_Armour_Sets

Deathstorm's Armor is seemingly for Survivability. Blade of the West armor seems to be for Damage. You might want to earn both of them and then use whichever one you'll be using.

However, as said above in a comment, you can't have the absolute maximum health and the absolute maximum DPS at the same time. To improve DPS, try the Fervor stance. However, this will burn down your health faster. To improve survivability, try the Glory stance. However, this will increase Threat generation, decrease damage output, and increase your defense ratings. This seems to be the "Tank" stance for Champions.
I don't think I've covered everything, so tell me if there's something I should add.
Comment: Another advantage (and a quite unknown fact) to use man as race for champions is that man have a bonus to incoming heal of 5%. That helps alot while grouped and in Fervor stance.
Comment: Yes, but I just remembered that Dwarves get Dwarf-Endurance/Endurance of Stone.
Comment: Healing isn't gonna help if the Balrog is breathing fire on you.
Comment: Incoming heal increases the heal you'll recieve; so it will help if someone heals you while the Balrog breathes fire at you ;)
Comment: Migitating 75% of that damage will help more.
Comment: Not just the Balrog, but practically everything (except that ##### Frigid Squall)
Comment: Well, the Dwarf endurance is good for sure but as man you'll get a heal of 3000 whats also not bad. The point is that incoming heal is a very important stat for Champions for difficult dungeons or raids.As a Champion you should get incoming heal to the cap of ca. 4000 incoming heal; that are 20% more incoming heal reducing the malus of Ferver stance to -10%.
Comment: well, it's equal, i guess for whether you should go with Dwarf or Man. I think that Man is good for Soloing while Dwarf is good for Grouping.


htaccess regular expression help needed

Question: I'm not very good at regular expressions at the best of times, and right now I have a problem that's giving me a headache with a .htaccess file. Can anyone here help me write the right command?
I'm trying to RedirectMatch permanent for URLs that are patterned like the following:
http://www.mydomain.tld/topic000-my-name-slug.html
where 000 represents a 1, 2, or 3 digit number.
I want to rewrite these URLs to the following pattern:
http://www.mydomain.tld/my-name-slug
The phrase "my-name-slug" can vary in length and always separates words with hyphens. I don't want the .html on the end any more.
Can anyone help me with this?
Answer: Try this:
RedirectMatch 301 topic[0-9]{1,3}-([\w-]+).html /$1

Comment: RedirectMatch 301 topic[0-9]{1,3}-([\w-]+).html /$1 is the one that worked. Thanks!
Answer: Try:
RedirectMatch 301 ^/[^-]*?[0-9]+-(.+)\.html$ /$1

Or:
RedirectMatch 301 ^/topic[0-9]+-(.+)\.html$ /$1

if the original url literally starts with "topic".
Answer: This should work:
RewriteRule ^/topic[0-9]+-(.+)\.html$ /$1/ [R=301,L]

htaccess regular expression help needed


Unable To Add Second Tab Bar to Tab Controller

Question: I have two tab bars in order to have effect like the one shown in Question of Sliding UITabBarItems in UITabBarController
Instead of an arrow, I am trying to use tab bar item at last index to show another tab bar, and hiding the current tab bar. I am adding second tab bar programmatically in viewDidLoad. Problem is that my second tab bar is not showing up on when last tab bar item is tapped. What I have done is:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tabControler.view.frame = self.view.frame;
    self.tabControler.delegate = self;
    self.secondTabBarSelected = NO;

    self.secondTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, 431, 320, 49)];
    self.secondTabBar.hidden = YES;
    self.secondTabBar.delegate = self;
    self.secondTabBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.tabControler.view addSubview:secondTabBar];

    [self.view addSubview:tabControler.view];
    NSLog(@"children of tabcon: %@",[tabControler.view subviews]); //Here second tab bar added with correct frame
}

-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if (!self.secondTabBarSelected) {
        NSLog(@"first tab bar");
        if([[tabBarController viewControllers] indexOfObject:viewController] == 3)
        {
            self.firstTabBar.hidden = YES;
            self.secondTabBar.hidden = NO;

        }
    }
}

Answer: I found that my tab bar was not visible because I was allocating it explicitly while it was present in nib file. Instead I just set the frame. My corrected code is:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tabControler.view.frame = self.view.frame;
    self.tabControler.delegate = self;
    self.secondTabBarSelected = NO;

    self.secondTabBar.frame = self.firstTabBar.frame;
    self.secondTabBar.hidden = YES;
    self.secondTabBar.delegate = self;
    NSLog(@"viewdidload frame: %@",secondTabBar.frame);

    self.secondTabBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.tabControler.view addSubview:self.secondTabBar];
    NSLog(@"viewdidload frame: %@",secondTabBar.frame);

    [self.view addSubview:tabControler.view];
}

-(void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{

        NSLog(@"first tab bar - controller");
        if([[tabBarController viewControllers] indexOfObject:viewController] == 3)
        {
            self.firstTabBar.hidden = YES;
            self.secondTabBar.hidden = NO;
            self.secondTabBarSelected  = YES;
        }

}


How to run custom code(hooks) after user signup on Paid Memberships Pro

Question: i want to execute a custom code after user signup on Paid Memberships PRO
and this looks like a solution
http://www.paidmembershipspro.com/hooks-filters/

"pmpro_after_checkout" looks exactly what i am looking for, but how do i execute it? where to write the custom code???
should i write this function in my theme's function.php file??
will it be a right approach if i write a new function in functions.php
for example in the sample code here "http://www.paidmembershipspro.com/hook/pmpro_after_checkout/"
i write a new function
function my_pmpro_after_checkout($user_id){
    //my custom code here
}

and call it in this location
wp-content/paid-memberships-pro/preheaders/checkout.php
line# 929
where another one is already called:
 //hook
 do_action("pmpro_after_checkout", $user_id);

and can i call my own function like this?
do_action("my_pmpro_after_checkout", $user_id);

i apologize if i didnt understand it... any help would be appreciated
Comment: you can try it with your theme functions.php
Answer: Add this code in your theme functions.php or create a plugin and add there in plugins file:
add_action("pmpro_after_checkout", "update_user_meta_after_upgrade", 10 ,1 );

function update_user_meta_after_upgrade( $user_id ){
    // Get level details
    $membership_level_details   = pmpro_getMembershipLevelsForUser($user_id);
    $level_id           = $membership_level_details[0]->ID;
// perform action according to the level
return;
    }


Zend Framework 3 tutorial error

Question: I just started yesterday the Zend Framework 3 tutorial
But, at this step :
when I had the module 'Album' in modules.config.php I had this following error :
Zend\ServiceManager\Exception\ServiceNotFoundException
/var/www/api/vendor/zendframework/zend-servicemanager/src/AbstractPluginManager.php:133
A plugin by the name "getServiceLocator" was not found in the plugin manager Zend\Mvc\Controller\PluginManager
#0 /var/www/api/vendor/zendframework/zend-mvc/src/Controller/PluginManager.php(98): Zend\ServiceManager\AbstractPluginManager->get('getServiceLocat...', NULL)
#1 /var/www/api/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(258): Zend\Mvc\Controller\PluginManager->get('getServiceLocat...', NULL)
#2 /var/www/api/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(273): Zend\Mvc\Controller\AbstractController->plugin('getServiceLocat...')
#3 /var/www/api/module/Album/src/Album/Controller/AlbumController.php(104): Zend\Mvc\Controller\AbstractController->__call('getServiceLocat...', Array)
#4 /var/www/api/module/Album/src/Album/Controller/AlbumController.php(104): Album\Controller\AlbumController->getServiceLocator()
#5 /var/www/api/module/Album/src/Album/Controller/AlbumController.php(16): Album\Controller\AlbumController->getAlbumTable()
#6 /var/www/api/vendor/zendframework/zend-mvc/src/Controller/AbstractActionController.php(78): Album\Controller\AlbumController->indexAction()
#7 /var/www/api/vendor/zendframework/zend-eventmanager/src/EventManager.php(271): Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#8 /var/www/api/vendor/zendframework/zend-eventmanager/src/EventManager.php(151): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#9 /var/www/api/vendor/zendframework/zend-mvc/src/Controller/AbstractController.php(105): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#10 /var/www/api/vendor/zendframework/zend-mvc/src/DispatchListener.php(119): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#11 /var/www/api/vendor/zendframework/zend-eventmanager/src/EventManager.php(271): Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 /var/www/api/vendor/zendframework/zend-eventmanager/src/EventManager.php(151): Zend\EventManager\EventManager->triggerListeners(Object(Zend\Mvc\MvcEvent), Object(Closure))
#13 /var/www/api/vendor/zendframework/zend-mvc/src/Application.php(332): Zend\EventManager\EventManager->triggerEventUntil(Object(Closure), Object(Zend\Mvc\MvcEvent))
#14 /var/www/api/public/index.php(48): Zend\Mvc\Application->run()
#15 {main}

Can anyone help me please, I really don't understand, I just follow the tuto.
Thanks !
namespace Album;

use Zend\Router\Http\Segment;

return [

    'router' => [
        'routes' => [
            'album' => [
                'type'    => Segment::class,
                'options' => [
                    'route' => '/album[/:action[/:id]]',
                    'constraints' => [
                        'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'id'     => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => Controller\AlbumController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],

    'view_manager' => [
        'template_path_stack' => [
            'album' => __DIR__ . '/../view',
        ],
    ],
];

Comment: I have the same problem
Comment: @Cochou Please give your `module/Album/config/module.config.php`.
Comment: @AlFonce thanks for answering ! Here :
Comment: @AlFonce : I restart everything and It's working now, thanks !
Comment: I think you have wrong in module.php file
Answer: In your AlbumController class, you call getServiceLocator(), but you should not have to do it. Are you sure you are following the official ZF3 tutorial? There is no getServiceLocator() call in this tutorial. You should not have to retrieve the Service Manager from a controller, as you should inject the necessary services in the controller (it's the ZF3 way to do).
I strongly suggest you to remove from your code all that it is not in the tutorial. Once you'll finish it (including the In-depth tutorial), you will understand why you really should not have to call some getServiceLocator() method from your controllers...
Answer: 'view_manager' => [ // setting the views
        'display_not_found_reason' => true, // it controls whether to display the detailed info about the Page not Found error.
        'display_exceptions'       => true, //it defines whether to display info about an unhandled exception and its stack trace
    //*** the two parameters shown above MUST be set to FALSE in production systems, because you don't want the site visitors see the details about errors in you site.
    ////However, you will still be able to retrieve the detailed information from Apache's error.log file

    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',  //defines the TEMPLATE NAME for the 404 error(it will be searched on template_map)
    'exception_template'       => 'error/index', //defines the TEMPLATE NAME for the unhandled exception error
    'template_map' => [
        'layout/layout'           => __DIR__ . '/../view/layout/default.phtml',

        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'error/404'               => __DIR__ . '/../view/error/404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ],
    'template_path_stack' => [
        __DIR__ . '/../view',
    ],
],

As you can see on the lines above, you've some mistakes on your code. Your nesting as a key your Route inside the  'template_path_stack' key which belongs to the 'view_manager' key. Try to change your code and good luck.

Zend Framework 3 tutorial error


Kitchen outlet and Light

Question: I am roughing in my kitchen wiring currently and have separated the counter top outlets so that I have two per circuit.  I also have a separate general lighting circuit in the kitchen.
My question is, can I use a two receptacle gangbox for one of the counter top outlets and a light switch if they are on separate circuits?
I am in Ontario in case it matters.
Answer: As Tester said - it's quite common.  However, local ordinances (and national) can vary, so your mileage may vary.
Also, on the subject of kitchen outlets - make sure each circuit has GFCI protection - one protected outlet being the first outlet in each circuit (do not put two GFCIs on the same circuit).
May I ask why only 2 outlets per circuit?  Seems a tad light...
Comment: The way I understand the counter top outlets is that they are considered "small appliance" outlets and the most you can have on a circuit is 2.  What do you mean by my mileage may vary?  Are you saying it may not be allowed here afterall?
Comment: Different regions have different rules is all I mean.
Comment: I think you read that wrong.  You have to have two circuits.  You can put as many outlets in the kitchen and attached dining areas as you would like.
Comment: I am fairly certain that in Ontario you can only have two "small appliance receptacles per circuit".  I am not aware of any limit on the number circuits and plan on having more than two.

I appreciate the help from everyone.
Answer: Yes, there is no problem having two circuits in a single box.  In fact, it's fairly common.
Answer: There's no problem, but remember, if you have multiple circuits in there that you're likely to have 240v going on and the risk of working in there without turning everything off is increased.
Make sure you turn off ALL the appropriate breakers before you work in there.
Also, as I commented elsewhere, there is no limit for the number of receptacles you can have on your domestic 20amp small appliance circuits.  You just need to have 2 to the kitchen that aren't shared with the dishwasher or garbage disposal or any overhead lighting.
You REALLY want more than 4 duplex receptacles in your kitchen!  In fact since all your counterspace has to be no more than 2' from a receptacle for code, it's almost a requirement!

Kitchen outlet and Light


How to tension toilet handle nut without handle sticking?

Question: I have to replace toilet handle assemblies frequently. However, the frustrating part is if you tension the nut at all, the toilet handle will not return to its original position.  I'm left leaving the nut barely hanging on and in fact it often later falls off.
Is there something I'm missing? A washer or spacer I should be putting on?
Comment: Hard to say without knowing what hardware you're using. Try wrapping the threads with pipe dope or teflon tape to act as a locknut.
Answer: Buy the kind that look like this:

Notice the 'ears' that wont allow it to sink into the hole and the full length square body that would make it impossible to over tighten it (at least, not enough to inhibit functionality - you'll have broken it way before then).
If I had to guess, you're still using metal ones or you're dealing with offset (angled) toilets, the handles for which are also available in plastic.
There's lots of different kinds out there. I think you're getting the wrong replacement type for the kind of toilets you have.
Comment: +1 for nut that locks on the handle and not the tank. -1 for some really scary looking water in that tank.
Comment: +1 this is exactly right. Remember that the handle arbor and nut are likely *left-hand* thread. What's up with that nasty water BTW? I tell my kids the tank water is clean and you could drink it in an emergency... maybe not so much... LOL.
Answer: Yes, it sounds like something is missing, a bushing perhaps, or you might be missing a lock ring. Not all handles are identical, but in general, the idea is to mount a threaded pipe to the toilet.


Why is the ph of my hot water 2 points higher than my cold water?

Question: I noticed in late February that even immediately after washing my hair, it felt and looked greasy and that my bath water felt as though it had a bit of bath oil in it.  The town water department thought that it might have to do with my water heater.
Before I got around to having it flushed,  I noticed that it was leaking from the bottom.  I had it replaced on March 17, but the problem persists.
The town tested my water on March 30.  Yesterday they told me that all was normal, except that the hot water was a few points higher in Ph level.  The cold water is 7.something, while the hot is 9.something.
I can't figure out what would be causing this, and it's a nuisance!  So, I'm trying to find out what would cause the ph level to be higher and what can be done about it.  Thanks!
Comment: 9 is somewhat high (about baking soda range) and 2 points is a big difference (the pH scale is logarithmic). Perhaps a retest is in order to confirm the results? Did they say any thing about how unusual this is or do they run into it all the time?
Comment: Did you actually get the pH tested before you swapped out the HW heater or just after? I understand that the oily feeling was happening both before and after.
Comment: Ok, if you had it tested both before and after, and they used the same tester for both the cold and hot that would all but eliminate a faulty test. This is good in the sense that we can now look for other things with this troubleshooting step out of the way
Comment: Do you have hard water or scale build up? I don't know if city water systems correct this but I assume so
Comment: I've been researching this and want to make sure: do you have a water softener by chance? Or are you sure that you don't have one?
Comment: No, I don't have a water softener.  I'm erasing earlier answers, as I've been prompted to limit comments or enter chat.
Comment: Ok. The best I have right now is that water systems typically are alkaline to keep corrosion down. This typically is up to 8.5, and sometimes up to 9.0. I think you have a bit of hard water since you noted (in a deleted comment) that you've had some scale build up. I'm now very interested in the answer too but that's as far as I have the time for. What is interesting to me is not that your hot water is high, but that your cold water is low (normal when it should be higher). Also, I find it hard to believe that the water company has no clue...
Comment: From what I've read, high ph can lead to scale build up--although I don't see much.  I've asked neighbors if they've noticed the same issue and none of them have.  It seems to be localized to my house.  Thanks for your efforts!
Answer: Water testing is affected by temperature so if they tested the water hot and did not adjust for the temp the measurement was off. When I worked in a clean room the water was tested at 72 degrees if the temp was +- a couple of degrees we had to adjust the values so that is probably the reason for such a high level. But I think it went down on hot measurements, the only thing in your tank that could affect the PH is the anode , flushing the tank and or replacing the rod would be all that you can do.
Comment: Any chance that it could come from the pipe leading to the tank?
Comment: I really doubt you would see an increase if you did the pipes would not last long. If the pipes were plain pvc (not CPVC) that is required for hot water there could be some minor leaching but 2 whole points is a lot. If anything I would flush the tank it is possible a high metal count could affect the reading if the anode has crumbled and ended up in the bottom of the tank , this is really the only thing I can think of. The pipe from the city or well is usually the same right up to a few feet prior to the tank in most homes.


Error: Cannot match any routes. URL Segment: 'sockjs-node/info'

Question: I am getting this error when running angular universal on my local machine with npm run dev:ssr.
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'sockjs-node/info'
Error: Cannot match any routes. URL Segment: 'sockjs-node/info'

I am not sure if it is a local error or what.
Thanks,
J
Comment: You should not call websockets when the app is running server side
Comment: Obviously, but it gets called anyway somehow internally.
Answer: I had the same problem and realised it must be the Angular analytics getting sent. Switching analytics off using the command:
ng analytics off

solved it for me.


how to conditionally add where condition in linq

Question: I am using entity framework and i want to add a where condition only if the condition is met else i dont want that where to be executed which i want to do it in 1 query
Context.Test
                .Where(v => v.Valuation.ValuationPeriod.PeriodName == periodName && parameters.SelectedTemplateIds.Contains(v.TemplateTypeId) && fundBusinessIds.Contains(v.Fund.BusinessId))
                .Where(v =>  parameters.sortedList.Contains(v.Valuation.PortfolioCompany.DealCode))
                .Where(v => wpGroup == null || v.Valuation.PortfolioCompany.WPGroup == wpGroup)
                .Where(v => !myDeals || v.Valuation.PortfolioCompany.UserPermission.Any(up => up.UserId == userId))

so in the above query
Where(v => parameters.sortedList.Contains(v.Valuation.PortfolioCompany.DealCode))

I want to execute only if
parameters.sortedList.Count() > 0

else i dont want to include that where condition in the above query. So basically here i know we can do by seperating the query that is first get a list of values and then check this condition and if it matches then add a where on that list. But is it possible without doing that?
Answer: The filter could be added contitionally as follows by using an intermediate assignment.
var result =  Context.Test.Where(v => v.Valuation.ValuationPeriod.PeriodName == periodName && parameters.SelectedTemplateIds.Contains(v.TemplateTypeId) && fundBusinessIds.Contains(v.Fund.BusinessId));

if (parameters.sortedList.Count() > 0)
{
    result = result.Where(v =>  parameters.sortedList.Contains(v.Valuation.PortfolioCompany.DealCode));
}

result = result.Where(v => wpGroup == null || v.Valuation.PortfolioCompany.WPGroup == wpGroup)
               .Where(v => !myDeals || v.Valuation.PortfolioCompany.UserPermission.Any(up => up.UserId == userId));

Answer: You can use this
.Where(v => parameters.sortedList.Count() > 0 ?
 parameters.sortedList.Contains(v.Valuation.PortfolioCompany.DealCode) : true)

Answer: LINQ queries don't execute unless you do something that causes enumeration of the resulting IEnumerable, which means you can have a pattern of:
var x = collection.Where(...);

if(sometest)
  x = x.Where(..);

var result = x.ToList(); //enumerate, causing evaluation

If sometest is true then both the Where will apply (AND style; both where predicates would have to result in a true for a collection entity to appear in the result), if sometest is false, then only the first Where applies
Answer: You can add an extension
public static class WhereIfExtension
{
     public static IEnumerable<TCollection> WhereIf<TCollection>(this IEnumerable<TCollection> source,
            bool condition, Func<TCollection, bool> predicate)
     {
            return condition ? source.Where(predicate) : source;
     }

     public static IQueryable<TCollection> WhereIf<TCollection>(this IQueryable<TCollection> source, bool condition,
            Expression<Func<TCollection, bool>> predicate)
     {
         return condition ? source.Where(predicate) : source;
     }
}

then
Context.Test
  .Where(v => v.Valuation.ValuationPeriod.PeriodName == periodName && parameters.SelectedTemplateIds.Contains(v.TemplateTypeId) && fundBusinessIds.Contains(v.Fund.BusinessId))
  .WhereIf(parameters => parameters.sortedList.Count() > 0, parameters.sortedList.Contains(v.Valuation.PortfolioCompany.DealCode))
  .Where(v => wpGroup == null || v.Valuation.PortfolioCompany.WPGroup == wpGroup)
  .Where(v => !myDeals || v.Valuation.PortfolioCompany.UserPermission.Any(up => up.UserId == userId))