Help! Need To Recover Partitions

Question: Ok, I will describe each & every step I performed.
First the problem:
A few days ago, my laptop refused to boot. It showed me automatic repair, but the repair was unable to solve the problem. So I checked the log file. The log file said that the bootloader was not found.
Since I was in a hurry for my work. I booted an Ubuntu live CD & tried to write the bootloader
I ran a command in ubuntu
Sudo dd if=/usr/syslinux/mbr.bin of=/dev/sda
What it did is make situations worse.
This command deleted my system_drv partition which was the boot partition.
So I ran testdisk & recovered that partition.
In testdisk I selected Intel type partitions for recovery.
Though the partition was recovered it wiped data from the rest of my partitions. Now in my laptop there is a LENOVO partition containing the lenovo drivers, SYSTEM_DRV (boot) & some other recovery partitions. Two partitions remain one was Data & other is Windows8_OS.
When I did my first recovery should I have selected efi/gpt instead of Intel? & if yes is it possible to recover now or I have lost my data?
My final questions are:
Should I try to recover those partitions using testdisk?
Or Is There Any Other Reliable Software?
Or Is There Any Alternate Way?
Or should I just handover to Lenovo for repairing the drive.
Though the data is gone I have checked in Gpart & confirmed that the partitions are still intact & I assume the partition table is also intact. The partitions still showup in Gpart but with an red exclamation & no used space just the size of the partition.
Please suggest a solution I am very worried coz my data is too important & want to restore my laptop as it was. Please I am in need of help.
Comment: You/we need to really know if system was UEFI with gpt partitioning or BIOS boot with MBR(msdos) partitioning. The syslinux install is a Windows only boot loader for BIOS boot of Windows. It should not have caused any issued with UEFI boot, but BIOS or UEFI is controled by settings in UEFI/BIOS. You may be able to convert back to gpt if it was gpt, but may make it a lot worse if it really was MBR. What does gdisk show: http://www.rodsbooks.com/gdisk/mbr2gpt.html Do not press w or write the new partition table unless you are sure it is gpt.
Comment: @oldfred Hey, here is gdisk & a gparted screenshot https://www.dropbox.com/sh/904rnyc5bwfpfwi/AACiCaRk4wSIIUEOHpFdpgAga?dl=0. Please can you tell me how to proceed.
Comment: It is gpt and Windows partition look like a typical UEFI boot. Windows only boots from gpt partitioned drives with gpt partitioning, so cannot be MBR. Did gdisk show any error or issue with partition table. The only issue shown seem to be every NTFS partition with gparted. What does right click on red error icon show in gparted? You may need to run chkdsk from a Windows repair disk or whatever else the error may be. You cannot run chkdsk from Linux, only Windows or perhaps some third party Windows tools. It looks like sda2 needs boot flag to make it the efi partition. Then you may boot UEFI.
Comment: It may have been installing syslinux moved boot flag from sda2 and that was entire issue. Errors on NTFS may be because you left it hibernated.
Comment: @oldfred The error on right click say ERROR(5): Failed to check '/dev/sda1' mount state: Input/output error. Probably /etc/mtab is missing. It's too risky to continue. You might retry an another Linux distro. There was no error from gdisk on execution of sudo gdisk -l /dev/sda. It says found valid gpt with protective MBR; using GPT & then lists all partitions. So should I recover partitons first? & then set SYSTEM_DRV boot flag & then I would be able to boot in windows?
Comment: Also if it possible tell me the other flags to set as it is not showing any other flags.
Comment: Partition table then sounds ok. With UEFI and using gparted you must have boot flag on efi partition. If using gdisk it is code ef00 (see gdisk instructions on that site). No other flags are normally required. Once boot flag is set and system sees efi partition you may be able to boot Windows from UEFI (not grub menu), if issue is just that you left it hibernated or fast boot still on.
Comment: What do you think about the bootloader problem? The system_drv has the EFI files to boot but previously it had an entry in BIOS under EFI now there is no such entry. Do I have to fix the bootloader? If yes what tool I should use since I tried boot repair but it didn't work previously.
Comment: Did you set boot flag. Until that is done UEFI will not show much. You also should have UEFI on, secure boot off, and CSM/BIOS off.
Comment: @oldfred Ok I tried setting the boot flag, keeping UEFI on, secure boot off. But it is still not detecting it.
Comment: No Boot options in UEFI? Or one time boot key?  Run Boot-Repair and post link to summary report in first post. Be sure to boot Ubuntu installer in UEFI boot mode and install Boot-Repair to that live version. https://help.ubuntu.com/community/Boot-Repair
Comment: @oldfred I booted in ubuntu in UEFI mode by which I came to know that there is no operating system in my Windows8_OS partition. What should I do now?
Comment: You have to restore from the backups you made before you make major system changes. If you did not backup Windows or make the recovery disks (which restore as purchased without your data) then you have to contact vendor and see if you can get the recovery set of DVDs. Some charge just a nominal amount, others do not offer anything and you have to purchase a full new copy of Windows.
Comment: @oldfred I am planning to recover from the OneKey Recovery Backup. I guess the WINRE_DRV has the setup of OneKey Recovery so will boot from it & try to restore it to factory default OS.
Answer: Atlast I went to Lenovo Service Center for re-installing my OS. Which they did. I am not happy at all with the Lenovo Service Center at Impact Infotech Pvt. Ltd., Goregaon (East). While they did install my Operating System they deleted all partitions including the Lenovo partition which had the Drivers of my laptop, they don't have any knowledge regarding any issues related to an Operating System. Plus they charged me Rs. 800 for installing a pirated Operating System.
I recommend DO NOT GO TO THIS Lenovo Service center they will install a pirated OS on your laptop instead of installing from a recovery disc & laptops nowadays show "Media Test Failed" when they are switched from UEFI to Legacy Support. They will trick you that your Hard Disk is damaged & will charge you extra bucks for it.
Now I am having a working laptop with Windows 8.1 Pro which he installed.
Thanks to @oldfred for helping me solve my problem. I learned a great deal of knowledge from you. Keep up the good work.

Help! Need To Recover Partitions


call a method in the main Activity. From a Custom View class

Question: i am using the following method in a new application i'm developing.
there is a main activity, which instantiates different classes that extends RelativeLayout, and i'm using setContentView to switch between the different modules of the application.
i wonder if this is a good approach or necesarily i have to use different activities to the several screens the app haves.
Answer: I'd recommend using different activities, then you automatically get navigation between them via the back button.  Plus, there will be subtle things that won't work right if you do it the way you're describing -- for example, Android automatically saves the focused control when you switch activities.  It won't do this for your content views; you would have to save/restore focus yourself.
Alternatively, if it doesn't make sense for a user to go "back and forth" between the screens of your application, then you could still implement the application with multiple activities, using android.app.TabHost.  This is what the Contact app uses, for example.  Then each screen is just a sub-activity, and the whole app is really treated as a single activity.  And if you want, you can use TabHost without actually having tabs.  You can hide the tabs and enable navigation via buttons or menu items instead.
Comment: thanks for the answer. in this case the app is a little game so the navigation through controls is not as standard. however, i understand that android haves some automatic handling of things when using activities, as the focused-control capability that you mentioned.


Apache Virtualhost keeps pointing to default directory

Question: I have been trying to set an Apache name based Virtual host(http://test.local) to the directory /var/www/test, but it keps on pointing to the default /var/www directory.
My test.local configuration file looks like this-
http://paste.ubuntu.com/827328/
My hosts file looks like this-
http://paste.ubuntu.com/827338/
And the ports.conf file looks like this-
http://paste.ubuntu.com/827332/
As per suggestion form IRC chat I disabled the default Virtualhost, then something wierd happened. Now http://test.local, http://127.0.0.1 loads contents of /var/www. But http://localhost shows the contents inside /var/www/test.
I'm using likewise-ope to connect to windows domian based network, it has created an entry in hosts file(the first line, also included is the next two lines))-
127.0.0.1 asset11.domain.com asset11 localhost
127.0.0.1 artis.local
127.0.0.1 test.local

How can I make http://test.local to point to /var/www/test correctly
Answer: Your local.test file you put on pastebin looks good, just uncomment the directory part.
The <Directory ...> - by the way - must point to the same path as the DocumentRoot (/var/www/test/ in your case).
Then you need to activate that file through sudo a2ensite test.local and reload your apache with sudo /etc/init.d/apache2 reload.
Comment: Thanks for the answer, But as far as I know  directives are not absolutely necessary, but can be used where we need some directory specific directives.
Comment: I counsel always to use the directory directives, because it happened too often to me that a .htaccess didn't worked. Of course it is not absolutely necessary.


Constant propagation library for .NET

Question: Whether any open source .NET (C#/F#) library for abstract static analysis exists? Currently I'm interested in constant propagation algorithm.
It should be abstract (language independed) and open source because I want to use it as base for custom algorithm implementation.
Thanks.
Comment: You insist on open source?
Answer: The library Mono.Cecil is almost what you want. It is open-source, language abstracted and as a bonus it is super polished, fast and stable.
But it is not exactly what you want because Cecil doesn't analyze C#, VB.NET or F# source code, but it analyzes assemblies files (dll and exe) and IL code contained in assemblies. For many static analysis areas it'd be enough, but for constant propagation (I guess you mean literal constant like const string STR = "MyString"; or const int INT = 12345;) there is a loss of information at compile time since the constant value is hardcoded in place of the constant usage. Cecil is also not suited for Abstract Syntax Tree analysis.
You can also look at Microsoft Roslyn. Contrary to Cecil, Roslyn parses C# and VB.NET source code, is very well suited for Abstract Syntax Tree analysis, but it is not open source, doesn't support F#, and is certainly subject to change until it will become RTM, I'd say next year with Visual Studio 2014, (but this is just my guess).
Comment: Thank you for answer. All libraries are very interesting. But I find more high-level abstraction.
Comment: What you mean by "I find more high-level abstraction"?
Comment: Sorry. Part of answer was lost. I means that I try to found somethink like pranlib for ocaml (https://code.google.com/p/ocaml-pranlib/): the set of analysis implemented for abstract, language-independed data structures.
Answer: You should take a look at the Common Compiler Infrastructure: Code and AST components project. It provides an object model for doing static analysis on .NET assemblies in a language-independent form.
Update
The CCI projects are designed more as libraries for compiler and tooling authors rather than out-of-the-box usage.
Perhaps you are looking for something more like Mono.Gendarme which is an open source static analysis engine, similar to FxCop. It is maintained as part of the Mono-Tools collection of projects.
Comment: Thanks. It is a good idea. Are any analysis implemented or planned?
Comment: @gsv I don't think there are although I would ask the project maintainer on plans for the project. Actually I don't think the CCI project is good fit for you, I think you are looking for something like the Mono.Gendarme project. See my edit.

Constant propagation library for .NET


Basement toilet drainage

Question: Will a basement toilet suck dry if sitting directly over the sewer line when the upstairs toilet is flushed or does it need to be offset?
Answer: It needs to be properly vented. Over the line or offset sideways is not the issue.

Basement toilet drainage


Increase wood fireplace efficiency

Question: We have a large fireplace and plenty of free or cheap wood and love having fires for warmth and entertainment. An open fireplace is not an ideal source of heat, but I wanted to know if there's a relatively simple way of increasing the amount of usable heat we get from the fire.
We're in a rental property, so a permanent installation such as a wood stove or fireplace insert is not possible.
I've seen a couple commercial solutions, such as this Texas Fireframe or fireplace heat exchangers, but I have no idea if these actually make a difference. I've also heard that just putting a cast iron plate at the back might reflect some heat back. Is there something I can put together myself with some Home Depot supplies?
Comment: If you really want to increase the heat and efficiency, then a wood stove insert is going to be the way to go.
Answer: I almost passed on this question, but couldn't resist.
I have been involved in a lot of home energy audits lately. Having spent a lot of time with some very qualified experts, i've learned a lot.
The one thing about a conventional fireplace is that they are for looks only. Even if the wood is free, it is costing you heating costs every time you light it. The real story is that for the chimney to draft properly and not fill the house with smoke, it has to pull tons, yes really tons, of air from the house to feed the flue. Only about 40% of the heat generated by the burning wood is actually sent into the house. The majority is sent up the chimney, as flue temps can reach 600 to 700. In order for this hot air to escape, it pulls the warm heated air from your home. So in essence, you are trading 40% efficient heat for the paid for heat at maybe 80% to 90%, depending on your heating system. Not a good trade, huh?
My advice is not waste your money on gimmicky promises of high efficiency gadgets. Just enjoy the fire as a romantic mood setting with a glass of wine, but don't forget to close the damper as soon as the fire is out to save your heating bills!
Comment: And please, please, dispose of the ashes carefully.   There have been several homes burned to the ground in our area due to improper disposal of fireplace ashes.
Comment: I'll never forget when my brother sucked up a hot ember off the hearth with a Kirby vacuum cleaner and the bag exploded!!!!!  WOW, what a mess.
Comment: Ash disposal: put the fresh ashes in a metal container. Let it sit on a non-combustible surface until completely cooled. It could be days, as ashes insulate coals well. (My mom once put ashes in a plastic bucket on the carpet. Burned a hole to the subfloor, but no fire, *whew*)
Comment: I once vacuumed some thought-they-were-cooled ashes. It was a very old-fashioned canister vacuum, i.e. all metal parts except the bag. My mom ended up sewing a new bag for the vacuum, but it still smelled like smoke for many years after that. Needless to say, it was relegated to shop or outdoor use.
Comment: Thanks for weighing in. I know a conventional fireplace is a totally impractical source of heat, and I've heard that it can actually be a net loss, as you say. But the wood is free and I love having a fire, so my question is really this: given that I am going to have a fire 3 times a week, is it worth it to spend a little money to buy a fireback or a grate to recoup some of my heat losses?
Answer: The item called a "fireplace heater" is the best option. I have seen them used, and have actually built one myself. I have experience as a welder so it was not a real chore to do.
Several steel pipe are bent to conform to the dimensions of your fireplace, with the bottom of the "C" lying flat against the bottom of the FP. The top of the "C" should fit along the top of the fireplace, and should extend out the front of the FP a few inches.
As the heat in the FP increases, air along the floor, cold air, is drawn into the pipes, heated and forced out the top openings, putting heated air into the room. There is not need for electrical, or power of any type.
Adding a "blower" can increase the heat output significantly. Manufacturers of these type units actually measure the output, in ranges of BTU/hr in the 40,000 to 90,000 Btu range. That is a lot of heat and will warm a large area. 'Fireplace heaters" can be seen online and on the appropriate web sites.
Answer: My in-laws picked up something similar to this grate a while back for their fireplace. The theory behind it is that by properly structuring the burning logs and embers, you can help direct the output of the heat more into the house than up the chimney.
I haven't tried it myself (as I have a woodstove), but they've noted an increase in heat in their living room since getting theirs.
Comment: I've seen these grates in action (in a person's house) and definately outputs more heat.
Answer: If your fireplace has a chimney that pokes into the room, try to figure out if it gets warm when the fire is lit.  If so, you can blow air onto the chimney breastwork with a fan to distribute that heat into the room.
Alternately you can run a ceiling fan to try and move heat down from the ceiling area which is space that people generally aren't occupying.   Warmed air moving gently is different to the radiant IR heat from a fire, so you can be warmed twice.
For an enclosed wood burner, a fan can blow across the top to help spread heat around the room.

Separately, consider the quality of your wood.  If its manufactured wood, high in glue then don't even bother burning it.  You're just releasing glue compounds and asking for a chimney fire.   Resinous wood can do similar, albeit slower.   "free" wood may not be worth burning at all if it is rubbish.
Answer: If you make one, use 2 inch tubes 4 inches apart, welded to a flat plate across the back and at the bottom for the grate to sit on with the upper part of the tubes angled at 30 to 45 degrees upwards and extending forward towards the front of the fireplace. You can remove it and sell it if you leave the house

Increase wood fireplace efficiency


Swift: Dynamic App Icon Not Displaying Correctly

Question: I'm new to Swift, and I'm trying to let the user change the app icon dinamically.
The problem is that when I change the icon theoretically the icon gets changed (since I see the model popping up), but the actual icon image is not displayed and I get the icon to be the "undefined" app icon.
All the images are 1024 × 1024 and added to the Assets
This is my code:
import SwiftUI
import Foundation

class IconViewModel: ObservableObject {
    @Published var currentIconName: String? = UIApplication.shared.alternateIconName

    func changeIcon(to icon: AppIcon) {
        UIApplication.shared.setAlternateIconName(icon.iconName) { error in
            DispatchQueue.main.async {
                if let error = error {
                    print("Error changing app icon: \(error.localizedDescription)")
                } else {
                    print("App icon changed successfully to!", icon.iconName)
                    self.currentIconName = icon.iconName
                }
            }
        }
    }
}

struct AppIcon: Identifiable {
    let id = UUID()
    let iconName: String?
    let displayName: String
    let image: Image
}

let appIcons = [
    AppIcon(iconName: nil, displayName: "Default", image: Image("icon")),
    AppIcon(iconName: "BlackBlue", displayName: "Blue & Black", image: Image("blueblack")),
    AppIcon(iconName: "Dune", displayName: "Dune", image: Image("dune")),
    AppIcon(iconName: "Elegant", displayName: "Classy", image: Image("elegant")),
    AppIcon(iconName: "Minimal", displayName: "Minimal", image: Image("minimal"))
]

struct IconSelectionView: View {
    @ObservedObject var viewModel: IconViewModel
    var icons: [AppIcon]
    let columns: [GridItem] = Array(repeating: .init(.flexible()), count: 3) // Set the number of columns you want

    var body: some View {
        ScrollView {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(icons) { icon in
                    Button(action: {
                        viewModel.changeIcon(to: icon)
                    }) {
                        VStack {
                            icon.image
                                .resizable()
                                .scaledToFit()
                                .frame(width: 60, height: 60) // Set the size as needed
                                .overlay(
                                    RoundedRectangle(cornerRadius: 12)
                                        .stroke(Color.blue, lineWidth: viewModel.currentIconName == icon.iconName ? 3 : 0)
                                )

                            Text(icon.displayName)
                                .font(.caption)
                                .foregroundColor(.primary)
                        }
                        .padding()
                        .background(Color.secondary.opacity(0.1))
                        .cornerRadius(12)
                    }
                }
            }
            .padding()
        }
    }
}

Video:
video: current app icon switching problem
Comment: Hi Edoardo! I answered your question. Are you italian? :)
Answer: Maybe you did not added those assets as iOS app icons. The way I add new icons to an iOS app is the following:
1. Add the assets to the assets catalog. Maybe create a folder called AppIcons for the sake of order:

2. Then add your new icon dragging it in the 1024x1024 box like you normally would with a modern project.
3. Go to settings and search for icon and add all of the alternate app icon names to the Alternate App Icons Sets

4. In your code then you can as you are already doing:
UIApplication.shared.setAlternateIconName(icon) {error in
    if error != nil {
        print("Failed to request icon \(icon)")
        return
    }
    print("Icon changed to \(icon)")
}

Let me know if this solved your problem!


Android Callback Method

Question: When I read Android Training , I saw a description for the activity-lifecycle:

When your activity is stopped, the Activity object is kept resident in
  memory and is recalled when the activity resumes. You don't need to
  re-initialize components that were created during any of the callback
  methods leading up to the Resumed state. The system also keeps track
  of the current state for each View in the layout, so if the user
  entered text into an EditText widget, that content is retained so you
  don't need to save and restore it.

I'm confused, if I don't need to re-initialize any components, why do I have to handle data or any something on callback method?
Answer: Just take Camera as an example.
You don't need to reinitialize any component, but you need to reinitialize the camera when the activity resumed. Component arne't the only part of an activity. Most applications also need to access system resources. You release these resources when your application gets paused or stopped, so you must reinitialize them again when your application is resumed. And Android may destroy your application in some circumstances (memory not enough, etc.) So you have to release and reinitialize resources again.
Moreover, there might be some internal state of your application. For example a book reader. You need to record the progress. This internal state are not components but you have to save them when your activity get paused.
The following code is sourced from Android documentation. Old mirror available here:

<code>@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

    // Release the Camera because we don't need it when paused
    // and other activities might need to use it.
    if (mCamera != null) {
        mCamera.release()
        mCamera = null;
    }
}

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    // Get the Camera instance as the activity achieves full user focus
    if (mCamera == null) {
        initializeCamera(); // Local method to handle camera init
    }
}
</code>
Answer: That description applies only to the stopped state. A stopped activity can also be destroyed, so the idea is that you save your data in onStop() in case the activity is subsequently destroyed. While there is an onDestroy() callback, it is not guaranteed to be called. onStop() can be relied upon to be called when your activity transitions from paused to stopped.
Note that in pre-Honeycomb versions of Android even onStop() can't necessarily be relied on, and onPause() should be used to save state. Honeycomb and subsequent versions will not kill an activity until the onStop() method has returned.
Answer: If your activity is stopped (ie the user presses home OR he handles an incoming call), the process (and the contained activity) of your application is not destroyed.
In this scenario, your components are already initialized (that means, they are showing what they were showing before your activity was stopped) and when the activity is brought to front again (the user reopens your app), you don't have to restore any sort of data.
However, after a while, the os may decide to reclame your app's resources and decide to kill the process (or the user may press back button from your home activity). In this other scenario, you are supposed to save the state of your activity in order to restore it whenever the user gets back to your app.
You can use onSaveInstanceState
or just store to preferences on onStop()

Android Callback Method


Output the current PATH to text file using BASH script

Question: I am trying to output the PATH used by the computer to a simple text file.
Something like echo PATH >PATH.TXT or >>PATH.TXT
With the double >>, it works but gives each on a different line and if I use the single of course it overwrites the previous line with the next. Using %~dpo >PATH.TXT, or %~fo >>PATH.TXT, or even %~nx0 >>PATH.TXT does not give me the output I want.  Simply put I want to put the PATH into a text file for backup using a BATCH file incase I do something stupid like HELP PATH, which would change PATH completely.
Thanks in advance for any help.
Comment: This is almost certainly a Windows' cmd.exe question.
Comment: I'm not sure I understand the question correctly. Are you trying to echo the output of the current $PATH or working directory to a text file? If so then you are nearly there, from the command line you would do `echo $PATH > file.txt` assuming you wanted to overwrite the contents of that file, use >> to append. Or do you want to find the current working directory of the script you are running? In other words when you execute you script are you looking to find the scripts current PATH or working directory from within the bash script?
Answer: You change your PATH with command:
PATH=/new-path:$PATH

For example here is how to correctly expand the PATH:
$ PATH=/newpath:$PATH
$ echo $PATH
/newpath:/home/rick/bin:/home/rick/.local/bin:/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin

Here is just one way to break your PATH (by omitting $ prefix):
$ PATH=/brokenpath:PATH
$ echo $PATH
/brokenpath:PATH

If you mess up your PATH usually you can simply close your terminal and reopen it.
Omitting the $ is the mistake made in your question as well. The method to capture PATH to text file is:
echo $PATH > PATH.TXT

To keep a running log of PATH changes you can use:
echo $PATH >> PATH.TXT

PATH is an environmental variable. To set the variable we use "PATH=" but to reference it's contents we need to use "$PATH".

The PATH variable can be set in many places as outlined in this Q&A: Where is my PATH variable being set?. To discover which files are setting the PATH one of the answers recommends using:
grep --color -H 'PATH=' ~/.bashrc ~/.profile ~/.bash_profile ~/bash.login \
                     ~/.bash_aliases /etc/bash.bashrc /etc/profile \
                     /etc/profile.d/* /etc/environment 2> /dev/null

On my machine the command returns:
/home/rick/.profile:PATH="$HOME/bin:$HOME/.local/bin:$PATH"
/etc/profile.d/apps-bin-path.sh:    export PATH=$PATH:${snap_bin_path}
/etc/profile.d/jdk.sh:export PATH=$PATH:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
/etc/environment:PATH="/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

Answer: You can print your PATH to a text file with the following code:
echo $PATH >> PATH.txt

If you want to run a file to do this, be sure to add a shebang to the top:
#!/bin/bash
echo $PATH >> PATH.txt


Hello,I have 3 collections how to make a join to select the data with a single request?

Question: I have three collections in mongodb i want to join them to get some datas.
this is my Schema:

//user collection
{
    "_id": "616b429e0de99f6f74f911b9",
    "name": {
        "firstname": "Kisko",
        "lastName": "Barrisson"
    }
}
//Devices collection
{
    _id:"616b52453dcacbf8a3f989a8",
    user:"616b429e0de99f6f74f911b9",
    name:"driver",
    data:[{X:123,Y:200},{X:124,Y:300}]
}

//locations collection
{
    "_id": {
        "$oid": "6193b7a7751212e5358b481a"
    },
    "X": 123,
    "Y":200,
    "adresse":"My current adresse"
}

I would like to do something like: "Select l.adresse,d.name,u.name from user u LEFT JOIN devices d ON u._id=d.user LEFT JOIN locations l ON l.X = d.X AND L.Y=d.Y WHERE u._id=616b429e0de99f6f74f911b9".
How can i do that using mongoose.
Help me please!
Answer: Query

start from devices, match the user
unwind data
(to make join easier, having the join fields inside arrays make things harder)
join with users(SQL like join)
join with locations

*you can avoid the replace roots, but they make the results of each stage looking simpler
*for performance make an index on devices.user, and on X,Y on the locations, also you need MongoDB 5, for index to be used in the second pipeline lookup
Test code here
devices.aggregate(
[{"$match": {"user": "616b429e0de99f6f74f911b9"}},
  {"$unwind": {"path": "$data"}},
  {"$lookup":
    {"from": "users",
      "localField": "user",
      "foreignField": "_id",
      "as": "joined__"}},
  {"$unwind": {"path": "$joined__"}},
  {"$replaceRoot":
    {"newRoot": {"$mergeObjects": ["$joined__", "$$ROOT"]}}},
  {"$lookup":
    {"from": "locations",
      "let": {"x": "$data.X", "y": "$data.Y"},
      "pipeline":
      [{"$match":
          {"$expr":
            {"$and": [{"$eq": ["$$x", "$X"]}, {"$eq": ["$$y", "$Y"]}]}}}],
      "as": "joined"}},
  {"$unwind": {"path": "$joined"}},
  {"$replaceRoot": {"newRoot": {"$mergeObjects": ["$joined", "$$ROOT"]}}},
  {"$group":
    {"_id": "$user",
      "data":
      {"$push":
        {"adresse": "$adresse", "X": "$X", "Y": "$Y", "name": "$data.name"}},
      "userName": {"$first": "$name"}}}])

Comment: Hi, thanks for the answer I tried your two queries but it doesn't work with mongoose. I get an empty array. Please help me find a solution.
Comment: in the first i forgot to remove something before sending it to you, can you retry, with the new code(the second was ok) ?Mongoose allows MQL to be written directly, so you can use the code without any change.Can you also check the Match? in the above match is made with string, in your database you have ObjectId, so you will need something like `new ObjectID("616b429e0de99f6f74f911b9")`. If you can run it stage by stage to find when data become empty, if you find an example that query doesn't work, post it if you can
Comment: try run it also in mongo-shell so we are sure that its about mongoose, but i cant see a reason that mongoose causes the problem because it allows you to use the query without any change.
Comment: Hi thanks for the corrections. Some of the code is working. I'll give you the code that doesn't work. As soon as I add it I get an empty array:
        ` // {"$unwind": {"path": "$joined__"}}, {"$replaceRoot":
          //   {"newRoot": {"$mergeObjects": ["$joined__", "$$ROOT"]}}},
          // {"$project": {"joined__": 0}},
          // {"$project": {"adresse": 1, "deviceName": "$name", "userName": 1}}`
Comment: @Tekis for the id i do that for convert the id: mongoose.Types.ObjectId("616b429e0de99f6f74f911b9").
Comment: if you have small sample data that the code doesn't work,send it if you can, for example on mongoplayground
Comment: locations collection:   {
    "_id": {
        "$oid": "6193b7a7751212e5358b481a"
    },
    "X": 123,
    "Y": 200,
    "adresse": "ffffffffff"
}
Comment: devices collection :  {
    "_id": {
        "$oid": "6193b7a7751212e5358b481a"
    },
    "data":[ {
        "X": 123,
        "Y": 200,name:"name data1"
    }, {
        "X": 124,
        "Y": 300,name:"name data2"
    }],"alarm":22,
    "user":"616b429e0de99f6f74f911b9"
}
Comment: user collection : {
    "_id": {
        "$oid": "616b429e0de99f6f74f911b9"
    },
    "name": {
        "prenom": "Kisko",
        "nom": "Barrisson"
    },
    "created": {
        "$date": "2021-10-22T13:13:30.000Z"
    },
}
Comment: In mongoose i am using your code.
Comment: its not mongoose is the difference in schema, in new schema data don't have only X,Y but name field also, but its small change i updated them both. also in the new data there is no name in the devices, there is a new field "alarm". hope this time it helps
Comment: Hi yes it works very well. Thank you so much. But unfortunately I have the wrong data format in the result. I get: [{"_id":"616b429e0de99f6f74f911b9","adresse":"ffffffffff","userName":{"prenom":"Kisko","nom":"Barrisson"}}]. while I wanted the format: [{"_id":"616b429e0de99f6f74f911b9","data":[ { "X": 123, "Y": 200,name:"name data1",adresse:"adresse1 from locations" }, { "X": 124, "Y": 300,name:"name data2",adresse:"adresse2 from locations" }],"userName":{"prenom":"Kisko","nom":"Barrisson"}}].In summary the address must be added in data of the column of the devices collection.
Comment: Wow. that's some hideous looking code!
Comment: i deleted the previous queries, i kept only the one that i think its ok for what you need.
Comment: thank you so much. it works exactly as I wanted. You helped me a lot. I started using mongoDb a few days ago but the joining part of the collections is a problem for me I hope with the code you gave me I will understand step by step step how to make joins between different collections.If you have complete documentation on mongodb joins, you can send them to me. Thank you @Takis_


Do kills by healed / boosted teammates count as assists for the Field Medic?

Question: I'm wondering if the Killing Floor 2 Field Medic has a similar mechanic to the Team Fortress 2 medic, where enemies killed by those that are being healed or boosted by the medic count as assists for the medic.
I'm curious because the Field Medic has the 'Focus Injection' ability where teammates shot with healing darts have their damage inflicted temporarily boosted for a few seconds. Do boosted teammates' kills count as assists for the medics?
Answer: This mechanic is something from games like Team Fortress 2.
As far as I know, medic healing has no effect on kills/assists. The skills

Adrenaline shot
Focus injection
Coagulant booster

are merely buffs, and unlike TF2 (etc), do not make assists etc count. Damaging Zeds is the only way to get kills/assists


Refrigerator Keeps Tripping Breaker

Question: Read the whole story before responding.  Refrigerator started tripping the circuit after being in our new house for 5 years now.  Nothing new has been added to the outlets on that circuit breaker(20 amp).  Ran an extension cord to another set of outlets on another circuit breaker(also an 20 amp) and had the same problem.  Then decided to try a 3rd outlet on a 3rd circuit breaker(this one a 15 amp which also runs the TV/Box) and have had no issues.
The trip seems to happen after multiple opening and closing of the fridge in a short period of time.
I am not an electrician but this seems wrong to me?
Comment: Does this answer your question? [Why would a GFCI trip on refrigerator circuit?](https://diy.stackexchange.com/questions/53252/why-would-a-gfci-trip-on-refrigerator-circuit)
Comment: LG LFX25974ST, yes they have a test button.  They also have a red light that blinks 5 times.  Eaton Breakers, looked on their site and 5 blinks means "Ground fault detected."
Comment: What make and model is the fridge, and do the breakers in question have TEST buttons on them?
Answer: You answered your own question. This is a ground fault. Your TV circuit isn't in a wet or unfinished area, so it doesn't have or need ground fault protection, so it doesn't have a problem. Since the problem happens on two different GFCI-protected circuits and didn't happen when the refrigerator was brand new, there likely really is a problem. Multiple opening and closing as a trigger would indicate either some sort of interference that happens (e.g., perhaps there are fans/motors that stop when you open the door and start again when you close it and repeated action causes the ground fault) or maybe some part that has an insulation breakdown and repeated opening/closing of the doors allows condensation to drip down to just the wrong place.
Bottom line: GFCI with refrigerator is generally not a good combination, because if this happened while you were out and didn't find out until the next day, your food would all be spoiled. Or potentially worse, you had the problem and didn't know it and reset the breaker because of something else, you might not realize the refrigerator had been off for several hours.
The ideal solution is to fix or replace the refrigerator. Realistically, the problem is probably not a true safety hazard, but we can't be sure. In many cases, a refrigerator can be plugged into a non-GFCI circuit, but normally the exception is based on the circuit not powering any countertop kitchen receptacles, which typically requires running a separate circuit exclusively for the refrigerator. Extension cords are only a temporary solution.
Comment: Thank you!  I hope that it is a simple repair and not needing an new refrigerator.  there is not sign that there is a leak anywhere.  Bummer!!
Comment: Refrigerators tripping GFCIs doesn't necessarily mean a fault, [this question](https://diy.stackexchange.com/questions/53252/why-would-a-gfci-trip-on-refrigerator-circuit) has a pretty good breakdown on why. Motors produce an inductive load, and when turned off return a small amount of current the GFCI does not expect, which trips it.

Refrigerator Keeps Tripping Breaker


Getting rid of ants in exterior wall

Question: While doing maintenance on an exterior wall near an inside corner, I pulled off rotted cedar shingles and the backing underneath to find scurrying black ants. They were small, not like I imagine carpenter ants. Although I do suspect they are some variant of worker carpenter ants, etc.
I chipped away at where they ate tunnels in the wood. The picture shows a 1 3/4" piece of ceder timber. Behind that is another piece of 1 3/4". I don't believe that second piece had been penetrated.
I intend to coat the area with Abatron's Liquid Wood, a wood-penetrating epoxy. Then to patch the wood, I will use Wood Epox, a dough-like wood fill by the same company.
Before I do any of that, I want to be sure the ants are gone and not simply retreating their nest deeper into the walls.  My question is how can I remove them if they've gone deeper? Please note in the picture, the area where the concrete meets the wood. I have chipped away a significant amount there. There is a gap between the wood and the concrete running deep. If the ants are inside, that's where they are getting in.
The remaining wood is not moist or rotted in any way. In fact, the only damage was their tunnels. The only moisture was in the backer between the ceder shingle and the wood. That was the first thing removed. I cut that off 1 1/2' up from the ground all around.
Answer: I believe you will find that these are carpenter ants and they are quite destructive.  Not as bad as termites but close.
Your best bet is to hire a pest control company who can exterminate them and give you advice on how to prevent them from re-entering your property.
Then you can repair the damage.
While this is a DIY forum, extermination of insects is generally not a DIY project because the needed chemicals are not available to unlicensed persons.

Getting rid of ants in exterior wall


refresh on screen data when database gets updated

Question: I have this table:
http://puu.sh/drvIK/62086e6be8.png
When clicking the Edit button, the user gets moved to this page:
http://puu.sh/drvML/4a2652e48d.png
When they select aanpassen (Accept in English) the database gets updated:
$sql="UPDATE IGNORE `personen`
        SET gebruikersnaam = :gn,
            wachtwoord = :ww,
            voornaam = :vn,
            tussenvoegsel = :tv,
            achternaam = :an,
            telnummer = :tn,
            opmerking = :op,
            email = :email,
            adres  = :adres,
            foto = :foto
       WHERE id = '".$_REQUEST['id']."' ";

When this finishes I forward the user back to the table in the first screenshot:
$this->forward('docentenOverzicht','directeur');

My problem is that this table still looks the same, the new data isn't in this table until the user refreshes his page, yet I want it to be updated as soon as they get forwarded to this page.
I'm sure it's a fairly simple fix, I just can't find anything on it.
Comment: Use AJAX to query databases without refreshing page.
Answer: You can set id for table row. ( 23 can be id of record )

Name

And after update from database, you can refresh only table tr with ajax.
$.ajax({
        url: 'getData.php',
        method: 'GET',
        data: 'recordId=' + recordId,
        success: function(updatedData){
             $("#t23").html(updatedData);

        }
    });


If $g(y)=3\int_0^yxf(x)dx+2\int_{\ln\frac1y}^{\ln y}x^3f(|x|)dx-3f(y),y\in(0,3)$ then $18-g(y)=?$ where f(x) is as given in the question.

Question: If $$f(x)=\lim_{t\to0}\int_0^x\left(\frac{tx^2+x\left(\left(t+1\right)^{2t+2}-1\right)}{e^{-x}t}\right)dx$$
and:
$$g(y)=3\int_0^yxf(x)dx+2\int_{\ln\frac1y}^{\ln y}x^3f(|x|)dx-3f(y),y\in(0,3)$$
then minimum value of $18-g(y)$ is?

I tried:
$$f(x)=x^2e^x$$
then:
$$g(y)=3\int_0^yx^3e^xdx+2\int_{-\ln y}^{\ln y}\underbrace{x^5e^{|x|}}_{\text{odd function}}dx-3y^2e^y$$
So:
$$g(y)=3e^y(y^3-3y^2+6x-6)-3y^2e^y$$
How to solve further?
Comment: In $f$ you have $x$ as both a limit and the variable you integrate with respect to. Are you sure this is what you want? If so, it is regarded as confusing, and you should change one of them.
Comment: @slo no it's perfectly fine
Comment: Technically it is not wrong, but it $x$ is both a free and a bound variable which can lead to confusion.
Comment: @slo limit is taken wrt "t" and integration wrt "x".
Comment: I was not talking about the limit $\lim$, but about the upper limit of the integral. Anyway, assuming your $g$ is correct, a global minimum does not exists as $\lim\limits_{y\to\infty}g(y)=-\infty$.
Comment: I've tried to make the title more specific. Also upvoted to counter the downvote.
Answer: Actually $$g(y)=3\int_0^yx^3e^xdx+2\int_{-\ln y}^{\ln y}x^3f(|x|)dx-3y^2e^y\\=3 e^y y^3-12 e^y y^2+18 e^y y-18 e^y+18\\g'(y)=3 e^y y (y^2-y-2)$$
$g'(y)=0$ at $y=-1,0,2$; also $g(-1)=18-51/e,g(0)=0,g(2)=18-6e^2,$


Embed local jar files in maven project

Question: I have some local jar files from a non-maven project which I wish to include in my maven-based eclipse project.
These jar files are undergoing a lot of change as me and my project buddy attempt to 'fix' them, so I'd prefer not to upload them to a repository to avoid making a maven version of this non-maven project if this is possible.
Of course, the jar files need to be embedded in the resulting deployment jar. We did this before using Ant which let us specify that those jar files should be included.
How do you do the same thing in maven? Take into consideration that we do have maven dependencies too which all work fine and aren't required in the deployment. Some answers I've seen don't allow for this requirement.
Here's one of my attempts - the problem is that the jar does not get embedded:
<dependency>
    <groupId>se.krka.kahlua</groupId>
    <artifactId>kahlua-core</artifactId>
    <version>5.1_2.1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/lib/kahlua-5.1_2.1.0-core.jar</systemPath>
</dependency>

Comment: The maven [assembly plugin](http://maven.apache.org/plugins/maven-assembly-plugin/) might be the way to go.
Comment: See http://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them
Comment: How do you build those jars? With Ant? Consider automating uploading them to your shared/corporate repository as SNAPSHOT (if you have one). It would save you a lot of time, specially considering that they are "undergoing a lot of change".
Comment: I would have to rent a server for this!
Answer: System paths are a very bad idea. When anybody else checks out your projects, he cannot build it anymore. (I always see such crap in many companies). The right solution would be to install the jar into the local repository:

$ mvn install:install-file -Dfile=[JAR NAME] -DgroupId=[GROUPID OF
  JAR] -DartifactId=[ARTIFACT OF JAR] -Dversion=[VERSION OF JAR]
  -Dpackaging=jar

In your project, you just add the dependency as usual after you installed the jar into the local repository.
<dependency>
    <groupId>[GROUPID OF JAR]</groupId>
    <artifactId>[ARTIFACT OF JAR]</artifactId>
    <version>[VERSION OF JAR]</version>
</dependency>

Comment: Something happened around about the install part. I was doing it from the eclipse Build Configurations menu, and it seemed to go through okay, but maven complains it cant find `se.krka.kahlua:kahlua-core:jar:5.1_2.1.0` when it compiles. I had a look, and while the directories have been created, there are no jar files in the local repository. Is this supposed to happen or am I doing it wrong?
Comment: @CJxD I'm not sure if Eclipse is doing this right. Please try it to execute the command in the console. I'm sure it will work then.
Comment: It still doesn't work =[ I'm tempted just to give up and use Ant again
Comment: I did add it relatively I suppose. It knew where it was supposed to look though when it added it in. I'll try again absolutely.
Comment: I always do it relatively, I always change into the jar directory and never had problems. What exactly doesn't work? Here is one example of mine:
`mvn install:install-file -Dfile=GoogleAdMobAdsSdk-6.4.1.jar -DgroupId=com.google.ads -DartifactId=googleadmobadssdk -Dversion=6.4.1 -Dpackaging=jar`
Comment: Do I need to panic? Here's one I did: `mvn install:install-file -Dfile=lib\kahlua-5.1_2.1.0-core.jar -DgroupId=se.krka.kahlua -DartifactId=kahlua-core -Dversion=5.1_2.1.0 -Dpackaging=jar`. The files in `.m2\repository\se\krka\kahlua\kahlua-core\5.1_2.1.0` are `_maven.repositories`, `kahlua-core-5.1_2.1.0.jar.lastUpdated` and `kahlua-core-5.1_2.1.0.pom`, but there is no 105KB jar file in sight.
Comment: Does Maven tell you "BUILD SUCCESS" after you execute this command or "BUILD ERROR"? If error, what is the error message?
Comment: BUILD SUCCESS. Okay, I just semi-fixed it as I realised I didn't put `.jar` on the end of the `file` flag. Now I have jar files in the repository! Now the project compiles successfully, but m2eclipse is still complaining `Missing artifact se.krka.kahlua:kahlua-core:jar:5.1_2.1.0`. Furthermore, the library is not embedded in the deployment!
Comment: Right click on the project: Maven -> Update Project should do it. Maybe you have to hit F5 on the project too (not sure atm).
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32329/discussion-between-cjxd-and-bevor)
Comment: Eclipse Users: You can create a new Run Configuration with the goal set as `install:install-file`, and add the rest of the flags as 'parameters'.
Answer: You can use maven-install-plugin to install kahlua-5.1_2.1.0-core.jar into the local repository then this dependency will behave as any other, see http://maven.apache.org/plugins/maven-install-plugin/usage.html. Or make a remote repository in a location shared with your buddy and let him upload his jar there with maven-deploy-plugin:deploy-file (http://maven.apache.org/guides/mini/guide-3rd-party-jars-remote.html) each time he changes it and add this repository to your pom. You can use SNAPSHOT version if this jar changes often

Embed local jar files in maven project


Is 150 CFM ventilation fan right choice for bathroom in my older condo?

Question: My bathroom ventilation fan broke up and I am shopping for a new better one. I noticed the newer fans are higher CFM through-put and are quieter, I have narrowed down my choice to this one.
My question is that my condo was built in 1980 so its older, will this fan still do a good job and be quiter? I have read in some product reviews/youtube installation that high CFM fans require bigger ducts. I live in 3 floor condo building. I only have access to the bathroom and nothing outside.
Will this 150 CFM be still a good option for me or I just need to go with the lower ranking basic fan?
The bathroom size is 7 ft by 5 ft. I have no idea of about the ducts size.
Update
I end up asking my condo management and I am told the duct is 6 inches which is great. Now I am gonna go with 150 CFM and I am buying this from Amazon which is way cheaper than others but I worry if this will fit? I took my current one dimensions (from outside) and is 12 by 10.5 inches. The one at amazon shows bigger but I think all new ones will be standard sizes. Should I be worrying about physical dimensions? Thanks!
Comment: Some info that would be helpful for someone to answer your question are the size of the ducts and the size of the bathroom in cubic feet.
Comment: I added that to question but I don't have any of current ducts size, is that something I can find out from under? Needless to say there is no way I can replace them so maybe assume standard size or perhaps if anyone has knowledge what were they using in late 70s!?
Answer: Calculate the CFM Needed.   (Length X Width X Height)/7.5  (7 x 5 x 8)/7.5 = 37.3 CFM   Did the 7x5 include a Shower/tub area too? If so, the 50 CFM should be fine.
That Fan is a bit overkill for your bathroom, that said Mine is a 190CFM for the same size.  The issue you are going to run into is that the fan you chose has a 6" Duct coming from it.
Typically fans from a Bathroom are 3" or 4" for something that size. It would be Similar to your Dryer Vent where it Exits the house, so that should give you an Idea.   If you can get the Part number of the Existing Fan and look it up you should be able to google it to determine its Duct Size.   There are Downsize collars that would downsize the 6" to 3 or 4" though that is not recommended as you will cause back pressure on the Fan as it can't push the required CFM out the smaller hole. If your Duct run was less than 2' you might get away with it, but if not you would probably void the fan warranty.
Find the Duct you have and then get a Fan that Supports its.
Comment: Thanks my last one (NuTone but don't know the rating) was quite useless so I do want to go with high CFM. They have 110 CFM in the same model but I think it also has 6 inch duct.
Comment: @zadane, the size of the duct is going to be a fairly important factor. Using a reducing bushing could result in reduced motor life and overheating of the motor causing the thermal break to be replaced. @ 6" you're probably looking at a 50% size reduction; too much.
Comment: @zadane, a 110cfm fan, regardless of make will NOT have a 6" duct fitting.
Comment: Old school Nutone fans were absolute garbage, and are still available today. You cannot compare them to a mid-grade or better fan of today.  As stated, a 50cfm will meet the minimum recommended size. An 80cfm will be much better. A 110 will also be fine and do a good job, but is overkill IMO.
Comment: @SpeedyPetey thanks for comment, I updated the post with additional info. I am so bitten by the junk Nutone that I just wanna go with 150 CFM in hope it will really work.
Comment: IMO the quality of the fan is just as important as the CFM rating.
Answer: It's very difficult to determine what type of ducting was used and if that ducting was properly installed or has an obstructions just by the era the building was built. Since the fan is broken you can try removing it to see what size ducting is currently in place.
If your current fan was doing a good job before it broke... meaning you didn't have moisture or mold issues, fogged mirrors, etc... then sticking with the same CFM fan would be a good idea. The new fans should generally be quieter and more energy efficient.
The Home Ventilating Institute recommends a minimum 1 CFM per sq foot in bathrooms smaller than 100 sq ft. That will give you the minimum 8 air changes per hour in a bathroom with standard 8' ceilings with a 50CFM minimum.
For your bathroom you'd need a minimum of 35 CFM. Panasonic makes those WhisperCeiling Fans in various sizes. Larger CFM fans will have a 6" duct and smaller fans have a 4" duct. The WhisperGreen fans use less energy and the smaller sized ones come with the option of connecting to 4" or 6" ducts. Larger CFM fans have a 6" duct. The larger duct size is recommended if the ducting is very long. The ducts create resistance so a larger duct mitigates that. If you have 4" ducts and the ducting isn't very long you should be fine but I don't think you need the 150 CFM fan.
If you can take the old fan out you might be able to tell if the duct is a short straight run if you can see daylight through the duct.
Comment: My current one was horrible, I am glad its toast. It was noisy and I never felt it ever did anything good so going with same model or power is nearly not an option for me.
Comment: Panasonic fans up to 110cfm use 4" duct, and come with a 4"-3" adapter. 150cfm and up use 6".
Comment: @SpeedyPetey Mixed up the ceiling with the WhisperGreen fans. Made the changes, thanks.
Answer: A 50 cfm should be sufficient for a 35 sf bathroom.  1 cfm per 1 sf is a good rule of thumb.


How to change the language of whole application from the dropdown in Navbar component in vue

Question: I created a language selection dropdown in my Navbar component. So here is my navbar component:

{{ translate("welcomeMsg")}}

                <select name="lang" v-model="lang">
                    <option value="en">English</option>
                    <option value="de">Deutsch</option>
                </select>

So the parent of this component is an Index.vue which is main component in my application.

        <Topnav/>
        <Navbar/>
        <router-view></router-view>

Currently, I am able to change the language in my Navbar component. So according to the selected value in the dropdown in Navbar component, welcomeMsg is changing. What I am trying to do is I want to put this pieve of code to TopBar "{{ translate("welcomeMsg")}} ", and according to the value of the dropdown in Navbar component, I want to change this value.
Can you help me with this or can you give me an idea how to do it?
Answer: If I understand you correctly, you want to use translate method inside Topnav component.
This method is however defined in Navbar, so it's not accessible in Topnav.
To use it elsewhere you could create a mixin with this method to import it to any component. I don't recommend this solution though as mixins are making the code messy.
Another solution is to create a component with translate method defined inside. Let this component do just that: translate a message passed by prop and render it inside some div:

  {{ translatedMessage }}

You can reuse this component anywhere in the application. You would still need to pass a language prop somehow, possibly the solution would be to use vuex store to do this, since language is probably global for entire application.
For easier and more robust solutions I would use vue-i18n, which @Abregre has already suggested in his comment: https://stackoverflow.com/a/70694821/9463070
Comment: Thanks for your reply. I want to use this method for everything in the application. So do you think your method will help me with this regard? In effeciency also
Answer: If you want a quick solution for a full-scale application and you don't have a problem with dependencies, you could try to use vue-i18n.
It's a plugin for vue that does exactly this for multi-locale websites/apps in Vue.
https://www.npmjs.com/package/vue-i18n
EDIT
Then in order to use it globally in your app, you should use vuex.
Keep the language selection state there and then wherever you want to use it, you make a computed function with the state.language getter.
The translate function should be a global registered filter
https://v2.vuejs.org/v2/guide/filters.html
Comment: Yes, I checked this one but I dont want to use any plugins


Cypress gets stuck in Jenkins

Question: I have a problem with Jenkins and Cypress. I'm using the docker to run my specs inside it and it gets stuck at this step: cypress:cli piping child STDERR to process STDERR
What should I do? Locally is working as expected. Thank you!
This is how it looks a part of my script, after cloning project.
stage('Test') {
        docker.image("cypress/included:4.11.0").inside('-e "HOME=." -e "npm_config_cache=npm-cache" --entrypoint=""'){ c ->
            sh 'npm i'
            // sh 'npm run tests-headless'
            sh 'DEBUG=cypress:* cypress run --browser chrome --headless'
        }
    }

Comment: I have the same problem, have you solved it?
Comment: @CarlosNasser nope. reported also to Cypress and nothing.
Comment: thanks, I let you know if find a workaround.
Answer: I just found a way to make it work. You need to run the docker container as root.
withDockerContainer(args: '--cpus="1.0" --entrypoint="" -e DEBUG=cypress:* -u root', image:'cypress/included:5.0.0') {
     //Your code
}

Comment: Tried to run with ".inside('-e "HOME=." -e "npm_config_cache=npm-cache" --entrypoint="" -u root')" and it didn't fix. Am I missing something?
Comment: Is ".inside()" equivalent to my args? I am not sure if that is injecting the args for the docker run.
Comment: Yes, is acting like args. I didn't find a way to fix this.

Cypress gets stuck in Jenkins


Connect function in raw socket?

Question: I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me that connect may already be establishing such a connection or in some way interfering. Does connect automatically establish a TCP connection whenever the socket it's called on has the IPPROTO_TCP option set?
Comment: What else would it do? Strange question.
Answer: Yes, IPPROTO_TCP creates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to the socket function.
Comment: @ArthurJames, because `connect` would require one of the higher level socket types, like 'SOCK_STREAM' or 'SOCK_DGRAM' type, not `SOCK_RAW`. Does it work in your experiment?
Comment: Well see, I have the second parameter as `SOCK_RAW` but it's coupled with `IPPROTO_TCP` as the third parameter. In retrospect I should have clarified, I apologize. I am wondering how the two together would effect the behavior of `connect`.
Comment: In this case, I would not expect connect to actually succeed. Never tried it myself, but I would expect it to fail.
Comment: Why would you expect it not to succeed?
Answer: Per MSDN documentation:
TCP/IP Raw Sockets

Once an application creates a socket of type SOCK_RAW, this socket may be used to send and receive data. All packets sent or received on a socket of type SOCK_RAW are treated as datagrams on an unconnected socket.
The following rules apply to the operations over SOCK_RAW sockets:
...
Received datagrams are copied into all SOCK_RAW sockets that satisfy the following conditions:
...

If a foreign address is defined for the socket, it should correspond to the source address as specified in the IP header of the received datagram. An application may specify the foreign IP address by calling the connect or WSAConnect function. If no foreign IP address is specified for the socket, the datagrams are copied into the socket regardless of the source IP address in the IP header of the received datagram.

This implies that RAW sockets are essentially connection-less sockets, and thus connect() does not perform a 3-way TCP handshake on a RAW socket. It simply associates a remote address with the socket, similar to how connect() works with a UDP (SOCK_DGRAM) socket.
More importantly:

Limitations on Raw Sockets
...

TCP data cannot be sent over raw sockets.
  ...
A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed.

So you can't use IPPROTO_TCP with a RAW socket to begin with, so the matter of connect() behavior on a RAW TCP socket is moot. IPPROTO_TCP can only be used with a real TCP (SOCK_STREAM) socket:

IPPROTO_TCP
  6
The Transmission Control Protocol (TCP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type parameter is SOCK_STREAM.

Connect function in raw socket?


Responsive CSS issues

Question: I am using @media to have certain styles for devices. However, it is having issue for tablets and phones. I am currently using a S3 and a hd 7 memo pad tablet to test the responsive aspect of my website. when I am on landscape mode on the S3, the content is not stacked on each other. This feature I would like to have for the tablet but however it does not do it when the tablet is on landscape mode. I would like to know what I am doing wrong. Another issue I am having is the footer. When I am on my tablet, phone, or laptop, there is weird spacing when browser shrinks. I would like to know how to fix the issue. Thank You
<code>                       /***********************
 GENERAL
 ***********************/
 a {
 text-decoration: underline;
 }

 a:hover {
 text-decoration: underline;
 }

 img {

max-width: 100%;
}

 body {
/*font-family: 'Fabrica', 'Courier New';*/
font-family: 'Open Sans', sans-serif;
background-color:#e6e9ed;
color: #434a54;
}

#wrapper{
max-width:960px;
margin: 0 auto;
background-color: #f5f7fa;
overflow: auto; /*This fixed the wrapper background color problem that happened bc floating content*/
line-height: 1.8em;
}
#wrapper img {
border-radius:5px 20px 5px;
}

#wrapper p {
text-indent: 2.5em;
}

#banner {
margin-left: auto;
margin-right:auto;
padding: 0;
display:block;
clear:both;
}

#content {
padding:20px 40px;
padding-bottom:50px;
}

h1, h2, h3 {
font-family: 'Droid Serif', serif;
}

.selected {
 color:#0B108C;
text-decoration: none;
}

  /***********************
  HEADER - Top image strip above banner
  ***********************/
 #logo {
 text-align:right;
max-height:100%;
max-width:100%;
padding: 10px 0px 10px 30px;
}

#header {
background-image: url(../img/header.jpg);
background-repeat: no-repeat;
background-position: top;
margin: 0 auto;
max-width:960px;
}

/*Commented out for testing new header technique
#header {
margin-left: auto;
margin-right: auto;
padding: 0;
display: block;
clear: both;
font-family: 'Fabrica', Arial;
}

*******/

/***********************
NAVIGATION - Main site navigation
***********************/
nav{
 background-color:#4888dc;
text-align:center;
color:blue;
max-width:960px;
margin: 0 auto;
text-align:center;
font-size:1.2em;
}
nav ul{
list-style:none;
margin:0 10px; /*Can be change later on in the design if it doesn't work*/
}
nav li{
/*Inline, mostly text. Appears in the same line, inline as the rest of the text. Block
  pushes other items out of the page. Inline block maintains width and
  height but is in line with other images*/
display:inline-block;
list-style:none;
padding: .4em 1.5em;
}
nav a {
font-weight: 800;
}

nav a:visited, nav a:link {
color:#f5f7fa;
text-decoration: none;
}

nav a:hover {
color:#0B108C;
text-decoration: none;
}

nav ul li a.selected { /*Highlights current page for users*/
color:#0B108C;
}

 /**********************
 FOOTER
 **********************/
footer {
font-family: 'Open Sans', sans-serif;
max-width:950px;
background-color:#434a54;
font-size:0.75em;
clear:both;
color:#e6e9ed; overflow:auto;
margin: 0 auto;
padding:5px;
}
footer h3{
padding-left: .9em;
font-family: 'Open Sans', sans-serif;
}
footer ul {
display:inline-block;
list-style-type: none;
}
footer ul li{
list-style:none;
text-decoration:none;
margin-left: 1em;
}
footer ul li a{
color:#e6e9ed;
text-decoration:none;
}

footer a:hover {
color:#FFFFFF; /*Change hover color to make it more prominent*/
 }

 /**********************
 RIGHT SIDE OF FOOTER
 **********************/
#footer-right {
float:right;
margin-right:15px;
}

 .social-icon {
  display:inline-block;
  width:24px;
  height:24px;
  margin-bottom:22.7px; /*controls height of "follow us" in footer*/
  padding:1px;
  border-radius: 20%;
  }

/**********************
LEFT SIDE OF FOOTER
**********************/
#footer-left {
float:left;
padding-left: 2em;
text-align:left;
font-size: 1.35em;
display:inline-block;
line-height: 1.5em;
}

#footer-slogan {
font-family: 'Georgia', 'Droid Serif', sans-serif;
}

#copyright{
font-size: .75em;
text-align:left;
margin-top: 5px;
display:inline-block;
font-family: 'Open Sans', sans-serif;
}

 /***********************
 CONTENT TEMPLATE - Content template for all other pages
 ***********************/

 /*Responsive.css*/

 /*This is the placeholder for responsive CSS that we will implement for mobile design*/

/* Smartphones ----------- */
@media screen and (max-width: 519px){
/* Styles */

#content{
float:none;
padding:0;
width: auto;
}

img{
max-width: 100%;
height: auto;
width:auto\9; /*for ie8*/
}

body{
float:left;
font-family: 'Fabrica';
}

 #logo {
 margin-right:auto;
 max-width: 100%;
 height: auto;
 padding: 0;
 }

#wrapper{
margin: 0 auto;
}
#wrapper p{
text-indent: 0;
}

h1, h2, h3 {
font-family: 'Fabrica';
}

nav{
position: relative;
min-height: 40px;
}

nav ul{
position:absolute;
width: 180px;
padding: 5px,0;
top: 0;
left: 0;
border: solid 1px #aaa;
background: #fff url(../img/menu-bar-mobile.jpg) no-repeat 10px 11px;
border-radius: 5px;
box-shadow: 0 1px 2px rgba(0,0,0,.3);
}

nav ul:hover li{
display: block;
margin: 0 0 5px;
}

nav a:hover {
display:block;
}

nav li{
display:none;
margin:none;
}

#banner{
display: none;
}

footer{
font-family: 'Fabrica';
float:left;
}
}

/*Ipads and Tablets*/
@media screen and (min-width:520px) and (max-width: 959px) and (orientation: landscape){
footer{
font-family: 'Fabrica';
float: left;
}

body{
font-family: 'Fabrica';
}

#primary {
width: 55%;
float: left;
padding:10px;
}

#secondary {
width: 30%;
float: right;
padding:10px;
}
}

/* Desktops and laptops ----------- */
@media screen and (min-width: 1200px){
/* Styles */
#primary {
width: 55%;
float: left;
padding:10px;
}

#secondary {
width: 30%;
float: right;
padding:10px;
 }
}

/*************************************
TWO COLUMN LAYOUT

Will target anything larger than average smartphone.
This is helpful for normal sized tablets, very large smartphones, and very small desktop windows.
***************************************/
@font-face {
font-family: 'Fabrica';
font-style: normal;
font-weight: 100;
src: local('Fabrica'), local('Fabrica'), url(path/Fabrica.otf) format('otf');
}
</code>
Comment: What width in pixels is the tablet in landscape?
Comment: This is may deserve to have close flag. That is better if you attach some JSFiddle and more explain your problem. Anyway if I understood your question well maybe you need to care about pixel ratio in those devices.
Comment: You need to simplify your question to make it easier to read and debug. Only include the parts of the code that are relevant to your specific problem, and include them in a live website, [JSFiddle](http://jsfiddle.net), [CodePen](http://codepen.io), or similar whenever possible. It makes it far easier for us to help you. By the way, iPads have a screen width of 1024px when in landscape. You are setting the max to 959px.
Comment: Here is the link JSFiddle link
Comment: My question is, simplify terms is that the style I do for Ipads and tablets is not recognize but rather recognize in landscape mode for phones, like the S3
Comment: Also thank you for the comments, I will keep this in mind
Answer: Looking at the media query that targets the landscape orientation, the only two elements it mentions (other than the footer), are the ones with id=primary and id=secondary. One of these is floated right, the other floated left, so they won't stack - this will cause them to float to opposite sides of the screen.
In your media query remove the floating and make sure they are both display:block - then they will stack one above the other. (Note: I assume you only have one each of the #primary and #secondary elements, since an id can only be used once on a page).
Comment: Not sure what I am doing wrong? When I do what you said, it alters the look on laptop/desktop view.
Comment: I don't suppose anyone can give you much further help as you don't say exactly what you want to achieve other than "stack on each other". I could only point out what was stopping that happening. I suggest your best option now is to raise a new question showing your HTML (not all of it, just the bits round the #primary and #secondary items), the CSS (again, as others have said above, just the bits relevant to the primary and secondary items), and put them on jsfiddle.net so everyone can see it in action. I hope and expect you will get several people answering then.

Responsive CSS issues


Convexity of $y\geqslant\frac{1}{x}$ and $xy\geqslant 1$

Question: I would like to ask the convexity of $y\geqslant\frac{1}{x}$ and $xy\geqslant1$.
We know that $y\geqslant\frac{1}{x}$ is convex for $x>0$. But if we transform the inequality into $$xy\geqslant1(x,y>0)$$ or $$1-xy\leqslant0(x,y>0)$$
The inequality becomes nonconvex as the Hessian of the inequality is:
$$
\begin{bmatrix}
0 & -1\\
-1 & 0\\
\end{bmatrix}
$$
which has eigenvalues of 1 and -1.
So is it correct that  $y\geqslant\frac{1}{x}$ is convex and $xy\geqslant1$ is nonconvex?
Thank you.
Dylan
Comment: You are confusing the *convexity of sets* and the  *convexity of functions*. Don't. They are two different, but closely related, things.
Answer: You are confusing the convexity of sets and the convexity of functions.
Don't.
They're closely related, tightly linked, but are by no means identical.
The fundamental link between convex functions and convex sets is this: a function $f$ is convex if and only if its epigraph $\{(x,y)\,|\,f(x)\leq y\}$ is a convex set.
So if you have a convex function---and $f(x) = 1/x$ is indeed convex for $x>0$---then its epigraph $\{(x,y)\,|\,x>0,~1/x\leq y\}$ is a convex set.
The important thing to note is that above if-and-only-if relationship starts with a function. It doesn't start with a set. You can't necessarily extract a convex function from a convex set.
For instance, there are lots of ways to represent the set, including $\{(x,y)\,|\,x,y\geq 0,~xy\geq 1\}$. But just because this is a convex set doesn't mean that $f(x,y)=xy$ is a convex function.
In fact, not every convex set is the epigraph of a convex function; for instance, $C=\{x\in\mathbb{R}^2\,|\,\|x\|\leq 1\}$. Is there a convex function in there? Sure is; $f(x)=\|x\|$ is convex. But the set is not the epigraph of $f$.
So again: don't confuse convex sets and convex functions.
Answer: Hint
The epigraph is convex $\iff$ the boundary is convex. Notice that they ask you the convexity of $$\left\{(x,y)\mid xy\geq 1\text{ and }y\geq \frac{1}{x}\right\}=\left\{(x,y)\mid x>0\text{ and }y\geq \frac{1}{x}\right\}.$$
Comment: Thank you for your reply. I understand that the set is convex. But for the function $1-xy$ on the left hand side, when $x,y>0$ is it nonconvex?
Comment: They don't give you two different curve ! But a set with two conditions.
Answer: If I am not wrong, then your question is how to show that-
$$\left\{(x,y)\mid xy\geq 1\text{ and } x,y> 0 \right\}=\left\{(x,y)\mid x>0\text{ and }y\geq \frac{1}{x}\right\}$$.
Hint:

The difference between function and its sublevel set.
Check $f(x,y)=xy-1$ and $f(x,y)=1-xy$ when $x,y > 0$.
Use the defination of convex set.


How can I tell if a civilian is a Faceless?

Question: Faceless are dangerous to deal with, moreso when they are concealed as civilians. An outcome of a Dark Event is to have Faceless in missions as civilians, and it's known that even "fleeing" civilians can be Faceless.  How do I detect these guys before its too late for my squad?
Comment: There's always the option to just end every one of the visible ADVENT buggers, Faceless will reveal themselves if there are no other enemies left
Answer: Some tricks I've learned so far:

Battle Scanners (can be built after ADVENT Trooper Autopsy) deployed in range of civilians will reveal a Faceless if they are one (and will force them to transform)
Specialist ability 'Scanning Protocol' will allow you to scan an area an reveal enemies and Faceless
Firing grenades at a civilian works as well; if you fire at one and DO NOT receive a Friendly Fire warning, it's safe to say the civilian is a Faceless unit (real civilians will always trigger a friendly fire warning)

Sidenote on firing grenades. When the FF warning comes up you have a choice to cancel your shot. If you don't get it, you will fire a grenade.  Watch out if you are on Ironman as all actions are final.

On civilian rescue missions, ADVENT troops will kill civilians every turn. Civilians cannot take more than 3 damage or they will die. However, ADVENT AI will sometimes shoot a civilian that does not die (meaning it is a Faceless unit).
Faceless units will automatically reveal themselves if no other enemy troops are alive (ADVENT, sneks, robos, mutons, etc.)
Comment: @Philipp Battle Scanners are deployables you can build after completing an ADVENT Trooper autopsy. It's like the Battle Scanner from XCOM:EU, you deploy it, it has a range and it detects enemies in hiding or concealed by fog of war
Comment: I've never seen a Faceless getting shot by ADVENT. Has this possibly been patched?
Comment: With "battle scanners" do you mean the "scan protocol" of the specialist class or is that some utility item I haven't unlocked yet? Regarding scanning civilians with grenades: Do you get the warning before throwing the grenade or afterwards? I would rather prefer to avoid wasting grenades and injuring civilians.
Answer: If a civilian is on fire, but still alive, it's a Faceless.  Civilians have few enough health that they can't survive being on fire.  I suspect the same is true of a civilian that's fallen from a height, but I'm not sure about that one.
Comment: Are you suggesting putting all civilians on fire? ahahah
Comment: @J.C.Leitão No one said it wasn't a *flawed* approach, just that its results were accurate. ;)
Comment: I've never heard of this game before today but this answer makes me very interested....
Comment: Time for a spy check?
Answer: IME it's generally pretty simple to tell: you don't know the difference, but the aliens do!  If you see a civilian surrounded by active, heavily-armed aliens, and they haven't shot him yet despite having had plenty of turns to do so, shoot him yourself because he's one of theirs.  (By "active" I mean that you've discovered a group of aliens in the area and they've done their silly "war cry and then run for cover" thing.  If they have a "civilian" in their midst, he's almost certainly not a civilian.)
So far, I've never had one of the "low-hanging fruit" (the civilians that start off right by your starting point with no real chance of the aliens reaching them before you do) be a Faceless.  Not sure if that's just luck or if it's deliberately set up that way, though.
Comment: I had a "low hanging fruit" turn out to be a faceless today.
Comment: Sometimes, for ex on civilian rescue missions, you get 5 civilians all clustered together, with a few faceless civs thrown in so it's not so "obvious" which one's which
Answer: Another strategy I use is to approach the civilian. If the civilian is a faceless it will always reveal. At least I've never seen one to not reveal upon me approaching.
Now of course this is risky business and if you are not close enough with a soldier to approach the civilian from the first move then you're in for a treat.
That's why I almost always use a ranger that has both Run&Gun and Implacable. I kill the faceless with a good shotgun and retreat :)


How to use TimeSeriesSplit in cv as mentioned in the documentation of scikit-learn

Question: Trying to use 10 fold TimeSeriesSplit(), but in the documentation of cross_val_score, it is given that we need to pass a cross-validation generator or an iterable.
tss = TimeSeriesSplit(max_train_size=None, n_splits=10)
l =[]
neighb = [1,3,5,7,9,11,13,12,23,19,18]
for k in neighb:
    knn = KNeighborsClassifier(n_neighbors=k, algorithm='brute')
    sc = cross_val_score(knn, X1, y1, cv=tss, scoring='accuracy')
    l.append(sc.mean())

How should I pass it after the time-series split into train and test data to cv?
TypeError
 Traceback (most recent call last)
<ipython-input-44-acf06bc7340e> in <module>()
     14 for k in neighb:
     15     knn = KNeighborsClassifier(n_neighbors=k, algorithm='brute')
---> 16     sc = cross_val_score(knn, X1, y1, cv=tss, scoring='accuracy')
     17     l.append(sc.mean())
     18 ~\Anaconda3\lib\site-packages\sklearn\cross_validation.py in cross_val_score(estimator, X, y, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch)
   1579                                               train, test, verbose, None,
   1580                                               fit_params)
-> 1581                       for train, test in cv)
   1582     return np.array(scores)[:, 0]
   1583
TypeError: 'TimeSeriesSplit' object is not iterable

Comment: Trying to use 10 fold TimeSeries Split, but in the documentation of cross_val_score, it is given that we need to pass a cross-validation generator or an iterable. How should I pass it after time series split into train and test data to cv
Comment: I have updated the answer, see the Edit2. Thats why I was asking for full code.
Comment: It works after removing the deprecated class.
Comment: @VivekKumar would you check this related [post](https://stackoverflow.com/q/75818230/10452700)?
Answer: Just pass tss to cv.
scores = cross_val_score(knn, X_train, y_train, cv=tss , scoring='accuracy')

No need to call tss.split().
Update:
The above method is tested on scikit-learn v0.19.1 . So make sure you have the latest version. Also I am using TimeSeriesSplit from model_selection module.
Edit 1:
You are using this now:
tss = TimeSeriesSplit(n_splits=10).split(X_1)
kn = KNeighborsClassifier(n_neighbors=5, algorithm='brute')
sc = cross_val_score(kn, X1, y1, cv=tss, scoring='accuracy')

But in the question you posted you did this:
tss = TimeSeriesSplit(n_splits=10)

See the difference between them (split() is not present). I am using this tss in the cross_val_score() without the split() as you posted in the question.
Edit 2:
Dude you are using the deprecated class.
Currently you are doing this:
from sklearn.cross_validation import cross_val_score

This is wrong. You should get a warning like this:

DeprecationWarning: This module was deprecated in version 0.18 in favor
  of the model_selection module into which all the refactored classes
  and functions are moved. Also note that the interface of the new CV
  iterators are different from that of this module. This module will be
  removed in 0.20.

Pay attention to that, and use the model_selection module like this:
from sklearn.model_selection import cross_val_score

Then you will not get error with my code.
Comment: Ok, I'll try using this.
Comment: This will not work as TimeSeriesSplit is not iterable
Comment: @DhruvBhardwaj. I have checked this code before posting and its working as intented. Please share more details of your current error. Also please read the updated answer
Comment: tss = TimeSeriesSplit(n_splits=10).split(X_1)
kn = KNeighborsClassifier(n_neighbors=5, algorithm='brute')
sc = cross_val_score(kn, X1, y1, cv=tss, scoring='accuracy')
Comment: I have the latest version of scikit-learn installed as you mentioned
Comment: @DhruvBhardwaj You are doing it wrong and different from the code you gave in question. I have updated the answer to correct your code.
Comment: Oh, I was just trying to make my code look cleaner. So, how to resolve this too many indices error as far as I know the split() function will return the indices of the train and test data after Time-based Splitting
Comment: @DhruvBhardwaj Dont use the `split()` function. Just send the `TimeseriesSplit()`  without calling `split` to `cross_val_score`, as I am doing. `cross_val_score` will do that automatically
Comment: TypeError: 'TimeSeriesSplit' object is not iterable @Vivek Kumar
Comment: How can you iterate the time series object just like that As far as I Know something is wrong
Comment: @DhruvBhardwaj As I said, cross_val_score will iterate by calling the `split()` method inside automatically, no need for you to do it. Just try my code and if still not clear, please edit the question with the exact code and data.
Comment: @DhruvBhardwaj Is it not working? What error are you getting?
Comment: @DhruvBhardwaj Post the full stack trace of error.I am not getting any error on your code with my data
Comment: @VivekKumar Would you consider this related [question](https://stackoverflow.com/questions/75818230/what-is-the-best-practice-to-apply-cross-validation-using-timeseriessplit-over)? Thanks in advance.


Calling InputMethodManager.setInputMethod(IBinder token, String id) outside the InputMethodService. Where to find token?

Question: I want to show Google Voice Typing IME on my EditText by clicking on Button. So, according to this article and source code I should write this code
inputMethodManager.setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype)

The problem is: where to find appropriate token. In the source code I saw this
mInputMethodService.getWindow().getWindow().getAttributes().token

It works great, but this code located in InputMetodService superclass, so it has access to InputMethodService instance. But i don't (unfortunately :) ).
Please tell me if you have any suggestions. Thanks.
NOT WORKS: EditText.getWindowToken()
Answer: Due to security reasons android doesn't allows application to change the inputMethod type. The article you mentioned is for integrating the google IME in custom implemented IME, it is not applicable for applications.
you can check documentation of InputMethodManager here
A client application can ask that the system let the user pick a new IME, but can not programmatically switch to one itself. This avoids malicious applications from switching the user to their own IME, which remains running when the user navigates away to another application. An IME, on the other hand, is allowed to programmatically switch the system to another IME, since it already has full control of user input.
you can prompt the user to switch to new IME in your onClick Callback like this:
InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showInputMethodPicker();


Why does my A/C "bump" and cycle super fast at night?

Question: I've got an ancient Armstrong Concept 1000 air conditioner (it was old when we bought the house 11 years ago) hooked up to a Nest thermostat. The furnance and blower is much more modern; it's an Aire-Flow model from 2014.
The A/C cools the house fine during the day, but in the evening, the unit in the basement will suddenly start making "bump" sounds, and the house blower will stop working. It seems to start doing it reliably just after sundown; we joke that it's "bump o'clock" at about 9 PM. If I go downstairs, I can hear a relay repeatedly tripping while it bumps. The unit outside appears to be operating normally.
The house's blower motor works fine if I turn off the A/C and just run the fan.
If I turn the A/C off for a half hour or so and let it come back on, sometimes it'll start working again. Sometimes not.
We installed the Nest probably three years ago; the bump sound has been happening for the last year or so.
Any idea what might be happening? Is this a thing where the coils are freezing up? It seems like it's still pretty warm out for that to be what's going on...
Comment: What model AC is it?
Comment: Did you have this issue prior to Nest installation?
Comment: Added info in original post.
Comment: Here's a guess, which I offer in the hope it might be useful but without much confidence. You have an electrical problem. Because the problem occurs at a consistent time it is more likely due to something outdoors than indoors. The "bump" sound is your blower turning on briefly, then losing power, then turning on again (i.e. the loudest and highest-current-draw part of running a motor). Perhaps the electronics in your condenser have a short, and this is interfering with the startup of your blower.
Answer: Okay. I've finally figured this out after two fruitless visits from the HVAC service people, a new logic board, and new blower motor capacitor. Warranty jobs, fortunately.
It turns out the culprit was our Nest thermostat. It was hooked up without a C wire. In this configuration, to charge its battery, it periodically closes the Heat circuit for very short lengths of time. Furnaces see that short signal and generally ignore it. With our old furnace, it was no problem with either heat or AC; everything ran fine.
However, with our new furnace (an Aire-Flow, in case you're wondering), when the AC was blowing, having the Nest close the heat circuit freaked out the logic board, which responded by stopping the blower motor while leaving the AC compressor running. I'm not sure why it seemed to happen more at night — maybe something about the times the battery charged?
Anyhow, the solution was to connect the C wire (for whatever reason, the furnace installers didn't) both in the furnace and in the Nest, and everything seems to be working.
It would be nice if the Nest warned you about working without a C-wire, but hey, it is what it is.


Is there a better way to avoid if/then/else?

Question: Background
We have a request object that contains information. That specific object has a field called partnerId which determines what we are going to do with the request.
A typical approach would be a gigantic if/then/else:
function processRequest( request ){
    if( request.partnerId === 1 ){
        //code here
    }else if( request.partnerId === 23 ){
        //code here
    }
    //and so on. This would be a **huge** if then else.
}

This approach has two main problems:

This function would be huge. Huge functions are a code smell (explaining why next) but mainly they become very hard to read  and maintain very quickly.
This function would do more than one thing. This is a problem. Good coding practices recommend that 1 function should do only 1 thing.

Our solution
To bypass the previous problems, I challenged my co-worker to come up with a different solution, and he came up with a function that dynamically builds the name of the function we want to use and calls it. Sounds complicated but this code will clarify it:
const functionHolder = {
    const p1 = request => {
        //deals with request
    };

    const p23 = request => {
        //deals with request
    };

    return { p1, p23 };
};

const processRequest = request => {
    const partnerId = request.partnerId;
    const result = functionHolder[`p${partnerId}`](request);
    return result;
};

Problems
This solution has advantages over the previous one:

There is no main function with an huge gigantic if then else.
Each execution path is not a single function that does one thing only

However it also has a few problems:

We are using an object functionHolder which is in reality useless. p1 and p23 don't share anything in common, we just use this object because we don't know how else we can build the function's name dynamically and call it.
There is no else case. If we get an incorrect parameter the code blows.
Out eslint with rule non-used-vars complains that p1 and p23 are not being used and we don't know how to fix it ( https://eslint.org/docs/rules/no-unused-vars ).

The last problem, gives us the impression that perhaps this solution is not so great. Perhaps this pattern to avoid an if then else has some evil to it that we are yet to find.
Questions

Is there any other pattern we can use to avoid huge if then else statements ( or switch cases )?
Is there a way to get rid of the functionHolder object?
Should we change the pattern or fix the rule?

Looking forward to any feedback!
Comment: might try as well on `codereview.stackexchange.com`
Comment: Interesting question and factory patterns come to mind but I assume the answer is primarily opinion-based. IMHO `Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.`
Answer: You can get rid of the unused variables by never declaring them in the first place:
const functionHolder = {
    p1: request => {
        //deals with request
    },
    p23: request => {
        //deals with request
    };
};

const processRequest = request => {
    const partnerId = request.partnerId;
    const method = functionHolder[`p${partnerId}`]
    if(method)   // Is there a method for `partnerId`?
        return method(request);
    return null; // No method found. Return `null` or call your default handler here.
};

To answer your points:

Yeap, as shown above.
Not without some kind of object.
That's up to you. Whatever you prefer.
Comment: @Cerbrus your handler doesn't get `request` as argument and it doesn't match signatures of the functions inside `functionHolder`
Comment: Update `method` with `method(request)` and `return null` with call of some default handler
Comment: @Flying: Can you explain that a little more? What's wrong with how I'm doing it now?
Comment: Right, forgot to pass the `request`. That's fixed now. Any other issues?
Comment: @Cerbrus also original question contains information about requirement to have default handler (`else` statement), but your example contains simple `return null`
Answer: Perhaps I'm not understanding the question properly, but why not an object to hold the methods?
const functionHolder = {
  1: function(request) {
    // do something
  },
  23: function(request) {
    // do something
  },
  _default: function(request) {
    // do something
  }
}

function processRequest(request) {
  (functionHolder[request.partnerId] || functionHolder._default)(request)
}

Explanation:

The object functionHolder contains each of the methods used to deal with a given request.
The keys of functionHolder (e.g. 1) correspond directly to the values of request.partnerId, and the values of these members are the appropriate methods.
The function processRequest "selects" the appropriate method in functionHolder (i.e. object[key]), and calls this method with the request as the parameter (i.e. method(parameter)).
We also have a default method, under the key _default, if request.partnerId does not match any existing key. Given a || b; if a is "falsy", in this case undefined (because there is no corresponding member of the object), evaluate to b.

If you are concerned about making functionHolder "bloated", then you can separate each of the methods:
const p1 = request => {
  // do something
}

const p23 = request => {
  // do something
}

const _default = request => {
  // do something
}

And then combine them into a "summary" object of sorts.
const functionHolder = {
  1: p1,
  23: p23,
  _default: _default
}

processRequest remains the same as above.
This adds a lot of global variables though.

Another advantage is you can import / change / declare methods on the fly. e.g.
functionHolder[1] = p1b // where p1b is another request handler (function) for `request.partnerId` = 1
functionHolder[5] = p5 // where p5 is a request handler (function) that has not yet been declared for `request.partnerId` = 5

Combining the above, without having to declare many global variables while also being able to separate the declaration of each method:
const functionHolder = {}

functionHolder._default = request => {
  // do something
}

functionHolder[1] = request => {
  // do something
}

functionHolder[23] = request => {
  // do something
}

processRequest remains the same as above.
You just have to be sure that the methods are "loaded in" to functionHolder before you call processRequest.
Comment: This will crash for `partnerId`s that have no handler.


How does the happiness affect the population in Stellaris?

Question: Our empire is at a crossroads, we found an elixir that can boost our people happiness by +15%.
How will this affect our empire?
Comment: I took over a planet and the aliens living there kept objecting so I purged them.
Comment: I'm jealous. My population are all unhappy because of all the genocide.
Comment: LOL, what genocide did your empire committed? If you commit genocide does it have side effects?
Answer: This answer was made during version 1.0 and is outdated, especially after the planetary rework in 2.2 (Le Guin).
There are three benefits to a happy population.
First, a happy population is more productive. At 80% happiness and above, populations are more productive whereas below 50% there are penalties.
Second, happiness affects the ethics divergence of the population. When the population are unhappy with your rule, they are more likely to adopt ethics different from yours (which can often make them unhappier, as they will then disagree with more policies).
A table of the modifiers can be found here: http://www.stellariswiki.com/Population#Happiness_modifiers
Finally, an unhappy population is more likely to join factions and cause trouble.
The +15% bonus will be extremely effective if you want to take over planets as it helps offset the negative modifiers for conquering them. It's less useful for your content citizens unless you combine it with another happiness increase, such as the Spiritualist ethic. There is no difference between 60% (the default) and 75%- you need to somehow get to 80% for any effect.
If you do have another +5%, the +10% to all production from being happy would be a significant bonus, and probably more useful than increasing leaders' lifespans.
Comment: Additionally, keep in mind that happiness is capped by habitability. E.g. if a species colonizes a planet with 50% habitability, their happiness will never go above 50%, no matter what. You have to raise habitability to further raise happiness.
Comment: Long live the 'Tree of life' :-)
Answer: This answer is for version 2.2 "Le Guin". The main impact of pop happiness is its effect on planetary stability through a mechanic called approval rating. The approval rating of the population on a planet is a function of their happiness and their political power: in a stratified society, pops in lower strata don't matter as much as those in higher strata.
Stability has some effects that are similar to the old effects of pop happiness: high stability gives job production bonuses, low stability production penalties. High stability also increases Trade Value. High stability adds immigration to the planet (increasing pop growth) while low stability adds emigration (slowing pop growth, or making pops decay if it grows too high - this is partially good, because overpopulation is a major stability penalty). Finally, if your stability is low, it can lead to events such as unrest, riots, etc.
Compared to the previous system, the important thing to note is that stability is planet-wide. If you have a mix of happy and unhappy pops, the happy pops will suffer a production penalty as well. However, you can reduce that by having more enforcer (police) jobs on the planet.
Compared to the system at the time of the previous answer, there are no longer happiness breakpoints - that is, every increase in happiness will result in an increase in production (unless you're running up near 100%), without requiring you to hunt for specific percentages. Also, habitability is now a penalty, rather than a cap, to pop happiness. If your pop is on a 60% habitability world, it can have more than 60% happiness, but it will have to overcome a ~10% penalty to get there.
Comment: Great answer. I'm going to hold off on the bounty to give other folks a chance but this will almost certainly earn it.