What sort of contractor (if any) should I call for this ceiling crack?

Question: There is a very narrow crack in my living room ceiling, pictured below. My concern, as you can imagine, is not so much the crack itself but the discoloration on either side.

I am frankly not sure how long it's been there (possibly already when we moved in, around 8 months ago), but it was definitely like this a few months ago with no changes that I've observed.
If I'm measuring correctly there's nothing in particular on the second floor directly above the crack, but it's just a couple of feet from a rather heavy whirlpool tub.
My question is, does this need attention, and if so what kind of contractor (if any) should I be calling? (Flooring seemed right to me,  but when I look for flooring contractors, they seem mostly to specialize in installation/refinishing, and it's not clear how to tell which of them would do a credible job assessing this.)
Comment: I can get no sense of scale from that photo. How long is the crack?
Comment: Fair point! I think the discoloration (the middle third of the photo) is about a foot long. The crack itself is longer.
Comment: have you used the tub more then a few times since moving in? I would run water upstairs and see if it gets any worse. Or you can just punch a hole with a screwdriver to make sure theres no moisture still up there, and that you could repair yourself.
Comment: I'm sure it's just a handful of times that we've used the tub as a whirlpool (e.g. with more than a foot of water, and jets on), but we use it daily as a shower and/or a regular bath.
Answer: There is, or has been a leak - those come from plumbing or from the roof, or occasionally from a water spill on the floor above that was not cleaned up quickly.
If you are quite certain it's not expanding, and you never see or feel moisture near it after the tub is used, or after a rainstorm, you could hire a painter and hope that it was from a one-time spill event.
If it comes back a plumber (or a roofer) seems like a requirement, and for the plumber to see what's up you will probably need a drywall contractor to patch the holes the plumber will need to make to find out what's going on and fix it. You do not want to pay plumbers rates for drywall repair.
You'll still need a painter, but the drywall contractor might also do painting.
Answer: I don't think you are ready for a contractor yet.  I would scrape that section and add some new drywall mud with a piece of tape and see if it cracks again.  There are kits at big box stores for $10.
I would then keep track of the area and your whirlpool usage.  Filling a large whirlpool tub of water is a ton of weight - a lot more than the tub itself.  Adding two or more adults to the area and that's a lot of weight.  My point is that your crack is really straight and I would bet money it is parallel to the joists above.  I think you are getting flex on one of your joists and it is pushing off a little.  (you may have some very slight water issues but this is hard to tell - you would often see way more yellowing if there was a leak.  It could just be floor splash from bathroom though)
If your crack doesn't come back, then get a drywall guy to integrate the texture on the ceiling better.  If crack does come back I would probably reinforce the joists from below which means you will need a general contractor - someone familiar with weight bearing and framing.  He should be able to handle the drywall after reinforcing the joists.
Answer: If it is beneath the bathtub there is a fair chance that the leak is a result of a poorly sealed overflow drain. It is pretty easy to check, just run the bathwater above the overflow drain and see if you can hear a drip at the site of the crack or discoloration occurs. You can get a new overflow drain gasket at the local hardware store for somewhere in the neighborhood for around 10 dollars and the replacement is a fairly simple process.
Comment: Water is terribly good at travelling many metres from the source before you see it.  Given the proximity to the bath upstairs, its a prime suspect.
Answer: That color around the crack means moisture. Maybe from a leak, maybe from being careless with kids in the tub, etc.
What I would do, personally, is cut away the dry wall in that area, from one "beam" to the other in the ceiling, the entire length of the crack. As long as your area being cut out is less then one sheet of drywall, your not spending any "extra" money. If it's larger then a sheet of drywall then you will need to adjust, but it shouldn't be.
The reason I say cut out such a huge piece is simple. Proper repair will have you do that anyway. A patch job that is more then just Spackle, means first cutting a easy to fill shape. From beam to beam, is damn easy, you don't have to do any weird stuff to hold the patch in place. Next is the water. With that large of a section removed you can go turn on every faucet in the house, one at a time, for at least 10 mins. Then check to see if the "beams" get wet. It's really important to run "every" faucet because water can go an insanely long way. Water on one side of the house could be clear from the other side. There is no reason to run water on the first floor. Water can "go up" wood, but it wouldn't look like that and you would see the colors along walls.
With the big hole, you should be able to get a general idea where the leak is coming from. If you don't see any water, and you don't think there is a lean then apply a generous layer of flour (for cooking) to all the "beams" in that area. The flower will get wet if there is even a little water.
If you have a leak call a plumber, they will appreciate the big hole. If you don't have a leak, then check the caulking around the tub. You should be able to  pour a bucket of water on the floor  in the bathroom and it should stay on the floor, not soak into it. Don't pour a bucket. But with the flour in place maybe pour a glass. If you see water then, you probably need to re-caulk your tub. This is an easy one if you have kids. They splash water, and it goes under the tub into the floor and "leaks" to the floor below.
If you don't see water then, then just move on with the repairs.  If you do see water, then repair the leak(s), and move on with the repairs.
To repair the now gaping flour filled mess, you shop vac up the extra flour. If it didn't get wet it should be really easy. Then you give all the wood inside the area a really good spray with bleach (if there was water this will really help avoid mold). Put the new drywall in place and secure it (screws work best, but nails are ok) Then finish it like normal. Drywall tape, paint and blend.
Comment: I would put good money on that crack being at the joint between two drywall sheets. 1. Cracks are most likely at the joint between two sheets. 2. Water is most likely to find its way through at the joint between two sheets.


Vue/Vite router has /#/ which doesn't work with Oauth flow callback URL

Question: So I'm pretty sure this is easy but I'm brand new to Vite and I haven't hit upon the right combination yet. I have all of this working in Vue-Cli 3 but would like to get it working in Vite.
I'm using Vue Router 4.0.0 and Vue 3.2.25 and Vite and Okta as my Oauth provider. I have a sign-in redirect URI in Okta of http://localhost:8080/login/callback. When I initiate my login flow it redirects to http://localhost:8080/login/callback?code=PnrOH4v4_... which resolves to my Home route of "/" and not my LoginCallback route of "/login/callback". I'm pretty sure it's the hash. I've tried various combinations of things but haven't hit the right combination yet.
Here's my router.
import { createRouter, createWebHashHistory } from "vue-router";
import { LoginCallback, navigationGuard } from "@okta/okta-vue";

import Home from "../views/Home.vue";
import User from "../views/User.vue";
import Profile from "@/components/Profile.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/login/callback",
    component: LoginCallback,
  },
  {
    path: "/user",
    name: "User",
    component: User,
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: "/profile",
    component: Profile,
    meta: {
      requiresAuth: true,
    },
  },
];

console.log("base = " + import.meta.env.BASE_URL);
const router = createRouter({
  mode: "history",
  history: createWebHashHistory(import.meta.env.BASE_URL),
  hash: false,
  routes,
});

router.beforeEach(navigationGuard);

export default router;

and here's my vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  base: "http://localhost:8080/",
  server: {
    port: 3030,
  },
  preview: {
    port: 8080,
  },
  plugins: [vue()],
  resolve: {
    alias: [
      { find: "@", replacement: path.resolve(__dirname, "./src") },
      {
        // I got this from https://github.com/okta/okta-auth-js/issues/641
        find: "@okta/okta-auth-js",
        replacement: require.resolve(
          "@okta/okta-auth-js/dist/okta-auth-js.umd.js"
        ),
      },
      { find: "@config", replacement: path.resolve(__dirname, "./src/config") },
    ],
  },
});

Answer: I believe you don't need any more alias for replacing "@okta/okta-auth-js" with "@okta/okta-auth-js/dist/okta-auth-js.umd.js" since this issue was fixed in the newest version of Okta Vue SDK.
Since 5.x version you need to install @okta/okta-auth-js as dependency. Here you can find more information about migration.


Draw a dashed path using Framer Motion in React

Question: I'm trying to draw a dashed path, or at least give that illusion, using Framer Motion. Think animating a foot path on a treasure map. Animating the path length seems to be a common method, and so I've implemented it like below.
<motion.span
     initial={{ pathLength: 0 }}
     animate={{ pathLength: 1 }}
     d="...a list of coordinates"
     stroke="#000"
     strokeWidth="5"
     strokeDasharray="8"
/>

But it appears animating the path length doesn't work well with strokeDasharray. When I add the strokeDasharray value using the attribute, the path length animates but the strokeDasharray value, when inspected, reads 2000px instead of 8px. And when I add the strokeDasharray using CSS or inline styling, the path is dashed correctly, but the animation doesn't work.
From what I've read, strokeDasharray uses the path length when doing it's computations, so I'm guessing the initial "0" value is throwing things off. Might be way off. I don't know.
Is there a simple fix here? Or should I reassess how I go about the animation? Thank you!
Answer: Not a solution using Framer Motion, but found this pen by Ruskinz that does the job using some css animation. The HTML looks like this:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="340" height="333" viewBox="0 0 340 333">
  <defs>
    <path id="path1" d="M66.039,133.545c0,0-21-57,18-67s49-4,65,8s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41 C46.039,146.545,53.039,128.545,66.039,133.545z" />
    <mask id="mask1"><use class="mask" xlink:href="#path1"></mask>
  </defs>
  <use class="paths" xlink:href="#path1" mask="url(#mask1)" />
</svg>

And the CSS looks like this:
.paths {
  fill: none;
  stroke: grey;
  stroke-dasharray: 5;
  stroke-width: 5;
  stroke-linejoin: round;
}

.mask {
  fill: none;
  stroke: white;
  stroke-width: 10;
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 5s linear alternate infinite;
}

/* does not work in IE, need JS to animate there */
@keyframes dash {
  from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

See the full pen at https://codepen.io/elliz/pen/prYqwx
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: I had the same issue because i wanted to animate it with framer-motion and not in css. What i just did is i just put an exact copy of the path with the dashedArray line below the path which i'm going to animate.
It will act as an overlay. I just gave it the stroke color of the background and tweaked the stroke-width. I don't know how it would be with a linearGradient background. But in my case with a static background color it worked.

import { motion } from 'framer-motion';

export default function Path({ pathColor, bg }) {
return (
    <svg
        width="245.24878"
        height="233.49042"
        viewBox="0 0 64.888737 61.777671"
        version="1.1"
        id="svg1033">
        <defs
            id="defs1030" />
        <g
            id="layer1"
            transform="translate(-20.472293,-22.027827)">
            <g
                id="g484"
                transform="translate(11.886667,6.306109)"
            >
                <motion.path
                    initial={{ pathLength: 0 }}
                    animate={{ pathLength: 1 }}
                    transition={{
                        pathLength: { delay: 0.4, type: "tween", duration: 3, bounce: 0 }
                    }}
                    stroke={pathColor}
                    strokeDasharray='3.846, 1.282'
                    strokeDashoffset='0'
                    strokeWidth='0.641'
                    style={{ fill: 'none', fillRule: 'evenodd', strokeLinejoin: 'round' }}
                    d="m 70.258127,15.782623 c 0,0 -1.867161,10.194243 -5.854843,12.473363 -9.471023,5.413069 -22.204956,-6.41444 -32.583479,-3.054701 -9.553598,3.092694 -21.015474,9.948708 -22.6557013,19.855557 -1.7758628,10.726077 5.8258513,25.311914 16.2917403,28.255989 11.258271,3.166974 19.313188,-18.990719 30.80157,-16.800859 5.208004,0.992724 10.182339,12.218805 10.182339,12.218805"
                    id="path1154"
                />
                <path
                    stroke={bg}
                    strokeDasharray='3.846, 2.282'
                    strokeDashoffset='0'
                    strokeWidth='1.641'
                    style={{ fill: 'none', fillRule: 'evenodd', strokeLinejoin: 'round' }}
                    d="m 70.258127,15.782623 c 0,0 -1.867161,10.194243 -5.854843,12.473363 -9.471023,5.413069 -22.204956,-6.41444 -32.583479,-3.054701 -9.553598,3.092694 -21.015474,9.948708 -22.6557013,19.855557 -1.7758628,10.726077 5.8258513,25.311914 16.2917403,28.255989 11.258271,3.166974 19.313188,-18.990719 30.80157,-16.800859 5.208004,0.992724 10.182339,12.218805 10.182339,12.218805"
                    id="path1155"
                />
            </g>
        </g>
    </svg>
  );
}


Ubuntu 22.04 LTS i want to upgrade all packages

Question: sudo apt upgrade and sudo apt full-upgrade doesn't work,the following 8 packages won't upgrade:
gnome-initial-setup/jammy-updates 42.0.1-1ubuntu2.2 amd64 [upgradable from: 42.0.1-1ubuntu2]
gnome-remote-desktop/jammy-updates 42.7-0ubuntu1 amd64 [upgradable from: 42.3-0ubuntu1]
python3-software-properties/jammy-updates,jammy-updates 0.99.22.5 all [upgradable from: 0.99.22.2]
software-properties-common/jammy-updates,jammy-updates 0.99.22.5 all [upgradable from: 0.99.22.2]
software-properties-gtk/jammy-updates,jammy-updates 0.99.22.5 all [upgradable from: 0.99.22.2]
ubuntu-advantage-tools/jammy-updates 27.13.3~22.04.1 amd64 [upgradable from: 27.9~22.04.1]
update-notifier-common/jammy-updates,jammy-updates 188.8.131.52 all [upgradable from: 3.192.54]
update-notifier/jammy-updates 22.214.171.124 amd64 [upgradable from: 3.192.54]

Answer: This suggests that their is a reason these updates have been held back, either due to your apt settings, or they could conflict with another package.  To fix it, just run apt install <package name>
if you want to install all of them in one command run:
apt full-upgrade | awk -F / ' {system("apt install "$1)}'

if you are not in a root shell, you will need to add sudo to both commands
sudo apt full-upgrade | awk -F / ' {system("sudo apt install "$1)}'

*** sudo or running apt in a root shell is assumed
Comment: it denied permission
Comment: If you are not in a root shell, you need to add sudo in front of the command.  any command that is located in sbin, or other system directories but be ran form a root shell, or with sudo.
Comment: it denied even when i put in sudo in front of it and it asked if i was root instead of in root
Comment: That is strange it is only a few packages so just run :

sudo apt install gnome-initial-setup gnome-remote-desktop python3-software-properties software-properties-common software-properties-gtk ubuntu-advantage-tools update-notifier-common update-notifier

That will install the latest version of each of the packages.
Comment: that worked,thanks a lot


call a servlet's post method from another application's servlet

Question: I want  to call a servlet's POST method from another application, in which I am passing request and response. Can anyone tell me how is that possible?
Comment: How are you calling the servlet?
Answer: If your servlet is invoked in an HTTP POST then you can do an HTTP 307 redirect to another servlet and it will call it's doPost.  If you want to POST to a different page from a servlet (or any Java method) you can compose a POST with something like HttpClient like this:
<code>PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
  new NameValuePair("user", "joe"),
  new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
</code>


Turn Timer lengths

Question: The turn timer for Civilization 4 multiplayer has a number of options that are defined by descriptive words, such as  "Slow", "Blazing!!!", or "Snail."  These names are necessary since the amount of time that is given for turns on any setting is dynamic depending on the era of the game - the length gets longer as the game progresses.
What is the formula for this amount of time?  How long does each setting give you on any given turn, and how is it calculated?  Additionally, if quick combat is disabled, time is added during each combat - where is this amount controlled?
Answer: The turn length is a function of

Base timer
Maximum number of units owned by a single civilization
Maximum number of cities owned by a single civilization

Timer (seconds) = (Base + City Modifier * Max Cities + Unit Modifier * Max Units) / 4
There's also a multiplier for the first turn.
The modifiers for each setting can be found in
...Civilization 4\Assets\XML\GameInfo\CIV4TurnTimerInfo.xml
This file doesn't exist in the expansion directories, so I presume they carry over.
Summary of modifiers:
          Base    City    Unit    First Turn Multiplier
Static    240     3       1       4
Snail     360     36      12      6
Slow      180     18      6       5
Medium    120     12      4       4
Fast      100     9       3       3
Blazing   80      6       2       2

Apparently static is not actually static.
Source:
Function getMaxTurnLen() in source code file CvGame.cpp
The coefficient of 4 was verified empirically by @marshaul. The only nearby hint of this in the source is a comment stating that turn time provided by user in Pitboss mode is in hours while the code actually multiplied it by 3600 * 4 (3600 seconds in an hour). This probably would also be evident deeper in the engine code.
Comment: It sure seems like the units are 1/4 second. For instance, on blazing the first turn is 40 seconds (+ a couple units), the second turn is 20 seconds (+ units/cities).
Comment: Excellent answer!  And yes, static is not what I expected, but I can understand the name - it has very low variance.
Comment: @marshaul Thanks for pointing that out. Empirical observation wins!

Turn Timer lengths


SQL query rounding down to nearest whole number

Question: I have a field in my Access query that is directly pulled from a table in the same database. When I pull the value from my table, the value is rounded down to the nearest whole number. ie 2.999 is rounded down to 2. I don't wish for my field in my query to have any rounding, I want the number directly as is from my table. I tried using the Round([field],4) and that still doesn't work and rounds the field down to the nearest whole number. How do I fix this? My SQL code is below.
SELECT  t.Station_ID, t3.[Original_Cut_Height(m)]
FROM [Installs] AS t3 LEFT JOIN ON [Inputting Data] AS t on t.Station_ID = t3.Station_ID;

Comment: As per [the ms-access documentation](https://support.office.com/en-us/article/round-function-921ce538-c9a6-41e2-be87-28e685b59935), when not given a second argument *the function rounds to the nearest whole number.*
Comment: @carmelle . . . Nothing in your query is rounding the value.  If you are seeing "2" then either the application where you are viewing the data is converting the value to `2` or the database is storing `2`.
Comment: With the code below it is still rounding down. ```SELECT  t.Station_ID, ROUND(t3.[Original_Cut_Height(m)],4)
FROM [Installs] AS t3 LEFT JOIN ON [Inputting Data] AS t on t.Station_ID = t3.Station_ID```
Comment: @GordonLinoff okay thanks. How can I check if the value is being converted to a 2 or if the database is storing it as a 2? My other fields in my query show the value from the table directly so I'm confused why it's just this field.
Comment: @carmelle . . . I don't think you need to ask.  If you see a `2`, that's probably what is in the database.  You could multiply by 1000 and see if you get anything other than 2000.
Comment: @GordonLinoff I tried multiplying it and get 3000. When in the original table it is indeed 3.658. Is there a setting that is causing this?
Comment: @carmelle . . . You are probably loading a value into an integer.  I would recommend changing the data type to a `numeric`/`decimal` (*with decimal places*!!!) and re-load the data.
Answer: Please try this one
SELECT  t.Station_ID, CDbl (t3.[Original_Cut_Height(m)]) AS Original_Cut
FROM [Installs] AS t3 LEFT JOIN ON [Inputting Data] AS t on t.Station_ID = t3.Station_ID;

Comment: This did not quite work and the error I get is "Syntax error (missing operator) in query expression 'CAST(t3.[Original_Cut_Height(m)] AS FLOAT)'
Comment: Sorry but this was access sql query then I updated. I think CDec() function also works
Comment: The query ran but it is still showing the value rounded down to the nearest whole number.
Comment: Did u use CDec() function instead? In addition do you have any previous sql query to get the data? This can be a int/int problem there has to be like int/float or float/int or likewise.
Answer: The issue was in my Table. In the table the number was based on an IIF statement and although the number was in my table was displaying as a decimal, it was being pulled over as an integer rounded down to the nearest whole number. Putting CDbl() around the numbers of the IIF statement in the original table solved this issue.


Find duplicate files and folders and move these to a different folder

Question:
Possible Duplicate:
How to find (and delete) duplicate files

Is there a reliable duplicate file/folders utility, (with GUI) for Linux that can find duplicate files or folders and move them to different folder?
Comment: @MarcelStimberg It appears that this question only discusses duplicate files, and not duplicate folders. However, I recently found a script that can be used to detect duplicate folders: http://unix.stackexchange.com/a/58343/22020
Comment: Unrelated, but I can't stop laughing at the irony that a question on finding duplicates has been tagged as a duplicate!
Comment: I agree with @AndersonGreen that the question of finding duplicate folders / directories needs an answer.  See one option at [Find all folders in a directory with the same content - Unix & Linux Stack Exchange](http://unix.stackexchange.com/questions/58340/find-all-folders-in-a-directory-with-the-same-content)
Answer: fdupes
No GUI but fdupes  / sudo apt-get install fdupes is very fast and reliable. It uses sizes and modification dates for a preliminary analysis, then compares md5 hashes of the files and then does a bit compare if necessary. It's also dead easy to use. I strongly recommend it.
Typical usage:
fdupes -d -r /path/to/directory/

-r for walking subdirectories as opposed to walking just the contents of the specified dir.
-d to prompt the user about which file to delete (without this fdupes just compiles a list of duplicated)
-N deletes without prompt
-H normally, when two or more files point to the same disk area they are treated as non-duplicates; this option will change this behavior
-L hardlink duplicate files to the first file in each set of duplicates without prompting the user (this option was rolled back in some versions as it was found to be buggy and unsafe in rare cases. It might be reintroduced in future versions).
Edit: The hardlink options was removed as buggy for now. It might return some day. For now you have to use hardlink  / sudo apt-get install hardlink
fslint
If you insist on a graphical user interface you might want to have a look at fslint  / sudo apt-get install fslint (see website for description). It is more feature rich but also more complicated and less reliable.
Comment: How can you use fdupes to find duplicate folders (instead of duplicate files)?
Comment: I want to find folders with duplicated content (I think that's what the OP is referring to).
Comment: Sorry, didn't see your question in the notifications. What exactly do you want to achieve? Find folders with duplicated content or with the same folder name?
Comment: I don't think there's a program that does this.
Comment: That is a bit more tricky and requires you to know your bash scripting. My approach would be: 1. Run `fdupes -r folder1 fodlder2 ...` on all folders that might contain duplicate directories and save its output. Use `find folder1 -type d` etc. to find all directories in said folders and store them in array. Use `find $array[i] -type f` in a for loop over i iterating over the directories to get an individual file list for each directory. Then compare the acquired file lists with the saved output from `fdups` and see if it only consists of duplicate files. I don't think a program exists for that.
Comment: You can also compare the checksums of two different programs to see if they are duplicates - see here : http://stackoverflow.com/questions/1657232/how-can-i-calculate-an-md5-checksum-of-a-directory
Comment: Also, would it be possible to determine whether two folders are duplicates simply by converting both of those folders to to .zip or .tar files, and then comparing those zipped files?
Comment: Actually, there is a shell script that can find duplicate folders: http://unix.stackexchange.com/questions/58340/find-all-folders-in-a-directory-with-the-same-content/58343#comment80430_58343
Answer: According to the fdupes --help command, -H does not create hardlinks:
 -H --hardlinks         normally, when two or more files point to the same
                                disk area they are treated as non-duplicates; this
                                option will change this behavior

Instead, -L seems to do this:
 -L --linkhard          hardlink duplicate files to the first file in
                              each set of duplicates without prompting the user

Comment: You're right, but this information would be better added as a comment on the previous answer.
Comment: The option to create hardlinks of duplicate files was rolled back after it was found to be buggy and unsafe. It might be reintroduced in future versions.


Windows 7/8 and Ubuntu triple boot

Question: I already have windows 7 and Ubuntu 12.04 installed. Now I want to install windows 8 for a triple boot. How can I do that?
Answer:
Make sure it will not go beyond the 4 primary partitions; if so then your PC will not boot up.
You can make extra partition with GParted--up to four primary partitions, or up to three primary partitions plus an extended partition that acts as a contained for logical partitions. This way you can effectively have more than four partitions.
Make sure you have sufficient space for Windows 8.
Install Windows 8.
Now you notice that only Windows 7 and 8 are listed in Windows's boot loader.
You have 2 option to make it so you can select Ubuntu when booting your machine:

Add Ubuntu in windows boot loader by using easyBCD.
Reinstall GRUB 2 by live CD.
For this watch this video.
After this if your windows in not listed in grub 2 then type
<code>sudo update-grub2
</code>
Even if Windows is not listed retry after mounting your windows drive.
Here is a video for updating GRUB2.
Answer:
Via Gparted, reduce some partitions in order to make free space on disk
Install Windows8 in this free space
reinstall GRUB (eg via Boot-Repair)
Comment: have you tried it yourself? I just want to know that it works for sure before I mess with my system
Comment: Yes, i did. First i recommend you create a backup image of your disk via CloneZilla, so that you can revert the changes if necessary.
Comment: do you have this problem? http://askubuntu.com/questions/141640/windows-7-does-not-boot-correctly-on-a-triple-boot-system-with-windows-8consume?rq=1

Windows 7/8 and Ubuntu triple boot


How to retrofit this circuit to be able to run a bare ground splice to another appliance?

Question:
I'm adding a #8AWG bare ground in order to retrofit a 3-wire range socket into a 4-wire one. I will be splicing into an existing water heater circuit to get the "at least #10" ground that is needed. Kitchen is on the other side of this wall and to the left and that bare ground will be exposed in this garage closet.
Since there's no j-box in the closet, I will need to add one to be able to splice into this circuit.
Do I need to use a whip or a NM Schedule 80 liquid tight conduit?
If so, I would combine it with this j-box:
BUT HOW DO I RUN THE BARE COPPER OUT OF THAT BOX?

More details about tapping into existing circuit and background to this question:
Is it possible to add a retorfit ground wire to a (3-wire) Type SE, Style U cable from another branch?
Comment: That box is too small.
Answer: More like "how do I bring this up to code?"
Random $1 4x4 steel junction box. (should be $1, Home Depot is overpriced).
Cable clamp appropriate for 10/2 wire.  x2.
"10/3" wire whip. (it's like cordage, the /3 counts the ground).  I prefer the kind with a screw-down conduit nut, not a fidgety clip that is "one shot" and you can't easily correct if you do it wrong.
If you don't like the price of wire whip, then feel free to make it using either a) AC/MC cable with appropriate cable clamps for a 1/2" knockout, remember the redheads.  Or b) FMC conduit with appropriate connectors to go in a 1/2" knockout, and THHN wires inside the FMC.  If you have a quality lumberyard who cheerfully sells all that by-the-foot, that's the way to go.
Think about where the stud is.  Choose a knockout on the back of the box that will let the existing Romex come straight in the back.  Install the cable clamp "backwards" there (conduit nut side out, clamp side in, clamp oriented to give you best access to the clamp-down screws).
Bap down the conduit nut with a screwdriver and hammer (what the crowns are for) and thread the Romex through the cable clamp and slide the box down til it hits the wall.  Fasten box to stud with random 1-1/4" deck screws (I prefer Torx or Robertson, but you do you).
Cut the Romex cable so the length coming out of the box is a little less than 12 inches.  Strip at least 6" of sheath off the Romex (leave at least 1/4" past the cable clamp).  Remember to tape/re-mark the white wire as red (any color but green or gray will do, but think "red").
Little #10-32 machine screw goes onto the ground screw on the box.  Romex ground goes around that 180 degrees (little more), tighten down ground screw, leave remaining Romex ground as a pigtail.  By the way, I buy these at a good hardware store for 15 cents each either green, or just a silver one out of the screw bin. But shop where you like.
Bare ground wire comes in side knockout via a second cable clamp.
Wire whip comes in another side knockout.  Goes to water heater.
Either a nice huge tan or blue wire nut, or an "accessory ground bar intended for service panels" as a method to splice all these wires together. Crank it to the limits of human strength.
Finally, a simple blank cover and you're done.
Comment: You don't want the ground "in the sink", but otherwise shouldn't matter much. Remember, ground only carries current in a fault situation. If it were a metal sink, for example, connected to copper pipes then it would actually be connected to your ground all the time.
Comment: @Matt Yeah, a bar like that but I'm used to seeing $3-4. Prices have gone nuts, at least at box stores. Haven't talked to my electrical supplies lately because this is a bad time to do projects so I'm not doing them.  The cable clamp will close tight enough, the 3/8" figure isn't about cable opening, it refers to the size of the knockout... but but it's a weird historical artifact because the KO is actually 1/2" trade size.  Which is 7/8" LOL.
Comment: I don't think the 3/8 in. Non-Metallic (NM) Twin-Screw Cable Clamp be able to hold a bare #6 ground that is only 0.162" What type of clamp did you have in mind?
Comment: This type of ground bar? https://www.homedepot.com/p/Square-D-4-Terminal-Ground-Bar-Kit-for-QO-Homeline-Electrical-Panel-Load-Center-PK4GTACP/100207842
Comment: Is there any concern for the bare ground wire being run so close to the garage sink?
Comment: @Harper-ReinstateUkraine regarding your comment: "Cut the Romex cable so the length coming out of the box is a little less than 12 inches..." Why 12? Am I supposed to leave almost 6" of the old sheathed Romex in the box and 6" stripped?
Question 2: why are the wires out of my water heater only #12 when it gets power over #10, is it because of longer distance?
Question 3: got the 3 terminal ground bar, they didn't have a 4. What's the best way to connect all these **grounds** together: #6AWG (range) + #10 Romex (to water heater) + #10 (from panel) and the #14 pigtail for the box?
Comment: @Matt to meet Code minima for individual wire length yet Code maxima for wire length in box. You can strip as much Romex as you can reach as long as you leave 1/4" of intact Romex past the clamp. #2 because UL makes them design the appliance to tolerate the higher heat of the smaller wire.  If the hole in the bar can accept a 10-32 screw, bolt the bar directly to the box. Otherwise run one wire *through* the bar and land it on the ground screw.
Comment: Thanks @Harper-ReinstateUkraine that's super helpful!
Another question derived from this project that got upvoted: https://diy.stackexchange.com/q/248572/151179


Not able to understand func code

Question: I know what a func is, but not able to understand the following piece of code:
There's a simple property :
    public Func<DomainFacade> BusinessFacadeFactory { get; set; }

And this is how the property is set:
    this.BusinessFacadeFactory = () => new DomainFacade();

Now this way of setting the property, is it a Anonymous method or something else?
Answer: That's called a lambda expression.
It's a more-compact form of an anonymous method.
Answer: () => new DomainFacade() is a lambda expression
It is an unnamed method written in place of a delegate
The compiler converts it to a delegate instance
It's real format is
(parameter)=>expression or a statement block
Since the func requires a delegate to be assigned we can write a lambda expression instead of the delegate which would internally get converted to a delegate instance.
So,
() denotes a an empty parameter
new DomainFacade(); is the expression
that internally gets converted to delegate by the compiler
Comment: Ok, then why do we have to declare as func. If i declare func as above, i can still say new BusinessFacade or something else
Comment: @Charu you need to declare it..cuz if u dont then how are you going to  define the `target delegate` to which you want to wire up the methods..
Comment: @Charu - As this method is stored in a variable, you can use it as a parametr to any other method. Imagine some stopwatch function. You pass this lambda/Func variable as a parametr. Stowatch will execute it (whether it is web download or 3D rendering) and return you the execution time
Answer: () => new DomainFacade() is a lambda expression.
It is an inline method, returned as a delegate value.
Answer: This is a lambda expression as others have said. Here is what it would break down like this in long form:
this.BusinessFacadeFactory = () => new DomainFacade();

then
this.BusinessFacadeFactory = new delegate(){ return new DomainFacade()};

then
...
BusinessFacadeFactory = OnBusinessFacadeFactory;
...

private DomainFacade OnBusinessFacadeFactory()
{
  return new DomainFacade()
}

Answer: It is a lambda expression, which is shorthand for creating an anonymous method.
()

is the input parameters (i.e. none)
new DomainFacade();

is the method body.

Not able to understand func code


what's the function of tag '#' while using python string format option

Question: I am using python string format option, and after reading document, i am still confused by '#' cause i really don't know the meaning of this phrase 'The value conversion will use the "alternate form" (where defined below).'. Great thanks to someone that helps me.
Here is some test:
print '%#sabc' % 'ABC'

'ABCabc'

print '%#fabc' % 1.2

1.200000abc

That will be great if there are some examples of usage of '#' here.
Comment: What the alternate form is is explained a few lines later, in the first notes.
Answer: As per the notes on that document, an 'alternate form' is defined for some conversion types.
e.g. in your example with %#f

3.The alternate form causes the result to always contain a decimal point, even if no digits follow it.

There is no defined 'Alternate form' for strings so %s and %#s are equivalent
Comment: Try printing both and see what happens!  See the examples in Christian's answer
Comment: how can i see the difference between '%f' and '%#f', could you please show me an example? understanding notes is difficult for me.
Answer: The "alternative form" changes the behavior of the selected conversion slightly.
Your Example for floating point representation:

'f': Floating point decimal format.

>>> print("%.0f" % 1)
1

The alternate form causes the result to always contain a decimal point, even if no digits follow it.

>>> print("%#.0f" % 1)
1.

Example for hexadecimal representation:

'x': Signed hexadecimal (lowercase).

>>> print("%x" % -11)
-b

The alternate form causes a leading '0x' [...] to be inserted before the first digit.

>>> print("%#x" % -11)
-0xb

Comment: @chenkh Please mark as 'answered' if it answered your question.  I don't think you'll find a better answer!


How can I keep water from saturating the bottom row of siding over a metal roof?

Question: In the picture you can see water intrusion on the bottom layer of siding above the metal flashing. Was the flashing installed incorrectly? It was never sealed with caulk or anything. There is a second story roof above that picture, and that roof doesn't have a gutter. It is also metal so the water drips off the 2nd story and on to this porch roof.
Comment: Put a gutter on the roof above.
Comment: It looks like cement board siding. If it was a Hardie brand, they require a 1" gap from any surface, be it roof or sidewalk. I have seen that stuff swell up and turn to mush.
Comment: A gutter won't help. There'll be more than enough splash to soak the siding in any substantial rain. It's a matter of letting it dry out readily, which it can't do if it's sitting in a puddle and tight against the metal.
Comment: What would you fill the gap with?
Comment: The gap isn't filled. It has flashing that goes up well behind the siding.
Comment: I assume that flashing tucks behind the siding.
I would replace it with new flashing built more at an angle to give the water more speed once its down by that flashing to move away from that edge.
That headwall flashing looks to me by looking at the white wooden wall like its either flat or almost flat.
Comment: What is the slope of the tin roof on the lower left?
Comment: 1:12. PBR panels.
Comment: The gap I refer to is one that needs to be created. The siding, whether it is cement board siding or otherwise, is too close to the roof. Caulk or any kind of filler will create a problem if there isn't one already.
Comment: Thanks. As someone else mentioned, would it be possible to set the depth on a saw and take a strip off the bottom? It's composite siding, so I would then have to paint or caulk the exposed material.
Answer: Siding should always be kept well above horizontal surfaces for exactly this reason. The manufacturer will specifically call this out in their literature. I'm not sure what I'd do now, given the blind nailing strategy we seem to see here. Cutting the siding exposes a raw edge, which doesn't improve the situation much.
Assess the project yourself and decide whether it's worth pulling the wall off or taking other measures to create a gap of 2-4" while maintaining a surface finish on the bottom board.
Answer: Assuming that the flashing has a vertical leg tucked behind the siding, tip your circular saw on its side and use the flashing as a guide. Take a couple minutes to experiment with deeper and deeper cutting depths until you get just enough, then back off from there about 1/16" to avoid marring the flashing's vertical leg. Now take a utility knife and pull on the bottom piece as you work down the line to cut the last bit. By pulling on the bottom piece, you'll get constant feedback on the necessary pressure for the knife and minimally damage the flashing.
And the gutters are a good idea, too.


White stuff growing in an outside electrical outlet

Question: What is this white, pasty stuff growing in my outside electrical outlet? It has shorted our the circuit
Comment: If you haven't scraped the mold off, could you add a picture of the faceplate you've removed showing the growth on it?
Answer: It's mold, or fungus, or slime-mold. Exactly what doesn't matter.
It's an  indication that the outlet is getting wet. You need to solve that.
An "In-use" cover is one way to help that along, but this also eyeballs as a half-donkey-ed "outside outlet" with a non-weatherproof box in the wall, and who-knows what as a cover plate. Can't imagine it sealed too well against raw stucco, but that's how it appears to have been done, just as if it was an inside outlet.
A 3/4-donkey-ed approach would be to put on an in-use cover with a donkey-load of sealant to attempt to seal it against the stucco.
For the entire donkey, you'd want to replace that box with a weatherproof box and an in-use cover.
Comment: I took it as a polite form of "half-assed"....which kind of skews things about 180 degrees....
Comment: When you need a donkey, but you only bother to get half of one, the job fails. When you get the whole donkey, the job gets done.
Comment: does it not look like caulking?
Comment: Isn't 3/4-donkeyed _50% worse_ than 1/2-donkeyed?
Comment: @FreshCodemonger at first glance, yes. On a closer look, no. The left edge where it had grown past the outlet area and therefore was not ripped by having the outlet removed is the most obvious.
Comment: @Ecnerwal - I interpret the left side as flattened caulking which then discolored from a rusting cover over it. Pretty easy for the OP to determine one way or the other. Whether a slime mold or a hack caulking job, it all should be replaced properly.
Answer: I'm pretty sure that's some sort of caulk or other glop that's been spread on the outlet.  The coloring is far too uniform to be some sort of mold, and the way it's spread over that top outlet would not result from mold growth.
Of course, this doesn't change what is needed to fix things.  The outlet needs to be replaced, and a decent cover installed.  If wind-blown rain is apt to be a factor the box should be replaced with one that's weatherproof.
Comment: If you zoom in on the left side of the [image](https://i.stack.imgur.com/UIJWp.jpg) then you'll notice a thin veil of webbing which is how fungus and mold typically grow. I hesitate to believe caulk was able to achieve these finer details.
Comment: @MonkeyZeus To me, it looks like white glop with a bit of fungus growth on top and in the crevices. But yeah it needs to be weatherproofed: given the rust mark, glop-or-growth doesn't change anything.
Answer: I suspect that the installers might have used some sort of interior product to seal the outlet to whatever cover it had previously. Usually caulk or drywall. Exterior products are waterproof and will not promote mold.
I agree with Ecnerwal about water intrusion, and I suspect the source was whatever they put on for a face plate. See the dribble of rust in the lower left corner of the box? That screams that rain is hitting your stucco, running down it, and then getting into the box itself. I have a couple of suggestions here

Upgrade to a GFCI. Be sure to buy an outdoor model (with the doors on the front).
Buy an exterior extension ring and exterior caulk it up good (top and sides only to allow the box to breathe). Yes, your box will protrude more, but the new setup will better resist the water intrusion.

If you do that, any exterior cover should suffice.
Comment: Upgrade to GFCI only if this circuit is not already GFCI protected. And yes, regardless of whether you get GFCI or not, get an outdoor outlet, as the one in the picture appears to be an indoor outlet. An outdoor outlet will have the letters 'WR' for Weather Resistant stamped on it.


ReactJs re-render on state change

Question: I am trying to do a sequence of fetching some API data and manipulating it as follows:

Fetch list of string addresses via API
Convert each of this string addresses to a geocoded location via API
Displaying these geocoded addresses as markers on a map

I am having some trouble with getting the timing with all these asynchronous activities right (I am pretty new to Javascript).
Here's what I have so far:
class Map extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addresses = [],
            geocodedAddresses = []
        }
    }

    componentDidMount() {
        const geocodedAddresses = []
        fetch('.....')
            .then(result => result.json())
            .then(addresses => this.setState({ addresses }, function() {
                this.state.addresses.forEach(address => {
                    Geocode.fromAddress(address).then(geocodedAddress => {
                        geocodedAddresses.push(geocodedAddress['results'][0]['geometry']['location'])
                    })
                })
            }))
            console.log(geocodedAddresses) //Correctly contains the geocoded addresses
            this.setState({ geocodedAddresses })
        }
    }

    render() {
        this.state.addresses.map(a => console.log(a)) //Evaluates correctly
        this.state.geocodedAddresses.map(ga => console.log(ga)) //Yields nothing....
    .....
    }
}

So I don't quite understand why React does not re render when I do this.setState({ geocodedAddresses }) - Shouldn't react re render when I do setState?
Answer: There are a couple errors with your code. In the first place, the state object is being created with equals instead of colons:
this.state = {
    addresses: [],
    geocodedAddresses: []
}

In the second place, you should take into account that your code is asynchronous. Only when the promises generated by the call to Geocode.fromAddress resolve you have the data for your geocodedAddresses.
In the componentDidMount, you are console logging the geocodedAdresses and you report that you are seeing the right values. This is only because the log is update after the promises resolve. But when you do the console.log the value at that moment for geocodedAdresses is an empty array. And that is the value that is being inserted in the component state.
In order to set the correct value for the state, you should call setState when all your Geocode.fromAddress promises have resolved. In order to do that you can use Promise.all method.
So, your code would look like:
class Map extends Component {
    constructor(props) {
        super(props);

        this.state = {
            addresses: [],
            geocodedAddresses: []
        }
    }

    componentDidMount() {
        fetch('.....')
            .then(result => result.json())
            .then(addresses => {
                Promise.all(addresses.map(address => Geocode.fromAddress(address)))
                    .then(geocodedAddresses => {
                        this.setState({
                            addresses,
                            geocodedAddresses
                        })
                    });
            }))
        }
    }

    render() {
        this.state.addresses.map(a => console.log(a)) //Evaluates correctly
        this.state.geocodedAddresses.map(ga => console.log(ga)) //Yields nothing....
    .....
    }
}

Note that with this solution setState is only being called once.
Since all your state refers to addresses information, it could make sense to merge that information into a single key in the state. You could initialize your state in the constructor as:
this.state = {
    addresses: []
};

And then, you could populate the state once all the promises resolve:
componentDidMount() {
    fetch('.....')
        .then(result => result.json())
        .then(addresses => {
            Promise.all(addresses.map(address => Geocode.fromAddress(address)))
                .then(geocodedAddresses => {
                    const addressesState = addresses.map((address, i) => {
                        return {
                            address,
                            geocodedAddress: geocodedAddresses[i]
                        };
                    });
                    this.setState({ addresses: addressesState })
                });
        }))
    }
}

Comment: Works like a charm - Without the brackets "[" in the Promise.all though (I guess since Array.map itself returns a list?
Comment: Could you comment on one thing: How could I modify your code if I wanted the addresses and geocodedAddresses in the same state (i.e this.state = { addresses: [{address: "someStringAddress", geocodedAddress: {lat, lng}}....]}
Comment: @Alex5207, I updated the code to correct the typo you detected and to expand the answer to take into account your last comment. Hope it helps!
Answer: You're right it's the async is slightly off. The console.log will populate after it "appears" in the console, but when setState has been called (and also when console.log has been called) its value is still [].
if you're using async/await you can wait for the fetch chain to completely finish, or put the setState within the then. With the setState callback, it's probably better to do the latter.
componentDidMount() {
  const geocodedAddresses = []
  fetch('.....')
  .then(result => result.json())
    .then(addresses => this.setState({ addresses }, function() {
      this.state.addresses.forEach(address => {
        Geocode.fromAddress(address).then(geocodedAddress => {
          geocodedAddresses.push(geocodedAddress['results'][0]['geometry']['location'])
        })
      })
   console.log(geocodedAddresses) //Correctly contains the geocoded addresses
   this.setState({ geocodedAddresses })
}))

}}

or
componentDidMount = async () => {
      const geocodedAddresses = []
      let addresses = await fetch('.....').then(result => result.json())
      addresses.forEach(address => { // assuming this is sync
            Geocode.fromAddress(address).then(geocodedAddress => {
              geocodedAddresses.push(geocodedAddress['results'][0]['geometry']['location'])
            })
          })
       this.setState({ geocodedAddresses,addresses })

    }}

ReactJs re-render on state change


Ramanujan (LPS) graph construction

Question: In the original LPS article they mention two constructions for Ramanujan graphs, one with order $q^3$ nodes and the other in order $q$.
My question is regarding the second construction (which is described here at page 5, they call it LPS-II).
What does it mean when they say "in a linear fractional way"? I understand that for a generator $\alpha \in S$, where $S$ is the set of $\  p+1$ generators, and for some integer $z$ - $\alpha(z)$ behaves like so, but what does it mean? how do I actually connect between two vertices?
Hope I am clear enough, if not I will elaborate some more.
Thanks!
Answer: They mean that they are viewing the group as a group of permutations of the points on the projective line.
So they are constructing a Cayley graph for the linear fractional group. (This is not a group of matrices, it is the quotient of a matrix group by its centre.)
Comment: Thanks! but I am still having a hard time to understand:
1) By "viewing the group" - the group is PGL(..)?
2) What that will the graph look like, if we say $p=3$ and $q=5$ which neighbors will the node represented as "2" will have?
Comment: The vertices of the graph are elements of thr group, not points on the line.
Comment: Still don't quite get it.. I am kinda new to this area. Why are the vertices in the graph no the points of the line?
From the original [article](http://link.springer.com/article/10.1007%2FBF02126799) (bottom of page 14) "We turn $P^1(F_q)$ into a $p + 1$ regular graph by joining $p \in P^1$ to $yp$ for each generator $y \in S$."
Is the result of $yp$ an int $k \in \{0,1,...,q-1,"infinity" \}$?

Ramanujan (LPS) graph construction


Values-ldltr-v21.xml error + AAPT2 Error while trying to build in Android

Question: Long story short, I'm a complete noob in android, bought an app code from codecanyon to use for my next project, I thought it was simple to use since I already did something similar a few weeks back. Anyway while trying to build/test run the app I get the following errors:
C:\Users\username\Documents\MyApp\product\Project\proast\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-ldltr-v21\values-ldltr-v21.xml
Error: file not found.
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:mergeDebugResources'.

Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

I have no idea what's going on and I tried searching and applying some of the methods I found online and on this site but I think I'm a complete idiot because I can't make it to work.
Here's the build.gradle:
buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And the build.gradle (module app)
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.pro.ast"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 8
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:cardview-v7:26.1.0'

    //retrofit, gson
    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

    //firebase
    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-ads:11.6.0'

    //glide
    compile 'com.github.bumptech.glide:glide:4.3.1'

    //circular imageview
    compile 'de.hdodenhof:circleimageview:2.1.0'

}

apply plugin: 'com.google.gms.google-services'

I have android studio 3.0.1,
Android SDK installed: 27, 26, 25, 24, 23
java jdk: 1.8.0_144
Any ideas? Would really appreciate it, I guess I will end up refunding the app code in the end since the seller is not responding yet.
Thanks in advance,
Stephen
Answer: It is most likely related to AAPT2's limitation with paths on windows. It currently has issues with paths containing non-ascii characters and paths longer than circa 145 characters.
This has been marked as fixed in the android issue tracker, but the fix hasn't been released yet.
Comment: Path length was my problem. I moved my project very close to the filesystem's root (think: `C:\temp-app\...` and it worked instantly.
Comment: BTW the windows path issues were fixed starting android gradle plugin version 3.2.0-alpha11 (if I'm not mistaken), so if you use that version or newer there should be no more need for workarounds. :)
Comment: I'm glad that worked out for you. :) The fix should be released soon so that you won't have to use these workarounds for much longer.


How to make each method wait to complete another inside of parallel.Foreach?

Question: I have a big problem for "parallel For" by using Task Parallel. I want to make my methods and functions synchronous (wait on each other).
Parallel.For(items, item=>
{
    var a = MyClass1.Function(foo.x);
    var b = MyClass2.Function(zoo.y, b.z);  ---> Should wait "a" result...
    var c = MyClass2.Method1(a.x,b.z); -----> Should wait b result...
});

How can I do that?
Comment: It already does what you want.
Comment: What's wrong with the result? Have you tried running the code? It will run as you want.
Answer: Parallel.For will run in parallel across your collection of items. Each item it processes, will invoke the given delegate synchronously. Meaning, it will execute MyClass1.Function then MyClass2.Function then MyClass2.Method1. This is assuming your methods are synchronous, and you're not doing anything in background threads inside any of them.
Imagine it like this:
                Items
  |          |          |          |
 Item1:      Item2:     Item3:     Item4:
Function1  Function1  Function1  Function1
Function2  Function2  Function2  Function2
Method1    Method1    Method1    Method1


Unity UI - Applying mask to individual sprites instead of entire texture

Question: I am trying to apply mask to sprites cut out from a large texture (sprite mode "multiple") that are to be used in the UnityEngine.UI.Image component and so far the results are unsatisfactory.
Here is the shader that I am using, which I copied it off here.
Shader "UI/Mask"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _MaskTex ("Mask Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                #ifdef UNITY_HALF_TEXEL_OFFSET
                OUT.vertex.xy += (_ScreenParams.zw-1.0)*float2(-1,1);
                #endif
                OUT.color = IN.color * _Color;
                return OUT;
            }

            sampler2D _MainTex;
            sampler2D _MaskTex;

            fixed4 frag(v2f IN) : SV_Target
            {
                half4 color = tex2D(_MainTex, IN.texcoord) * IN.color;
                half4 mask = tex2D(_MaskTex, IN.texcoord);

                color.a *= mask.r;
                clip (color.a - 0.01);
                return color;
            }
            ENDCG
        }
    }
}

I have a strip of texture, which I cut into individual sprites. The following image shows the first two icons, stored in the same PNG.

And next, I follow the instructions on the answer of the link and prepared a mask PNG, which is simply a black bordered circle with 128 pixels in radius.

The material is then prepared...

and applied.

And here is what I've got:

I regret that I have no knowledge about shaders so I don't know if I'm describing the problem properly... but apparently, the circle mask is squashed/stretched and applied to the long strip of texture, rather than applied to the individual icons that are cut out.
In other words, the full strip looks like this:

But Unity is doing this:

And then it cuts out each icon from the incorrectly masked texture for me to use.
What can be done to the shader to make it mask properly? So I should be seeing something like this:

Or there is no simple way as this is how materials are supposed to work so I have to give Unity separate textures instead of storing all icons in one long strip?
Comment: Try ticking the preserve aspect. This will keep the circle as circle. You will probably have to fix the size and position of it. It also looks like you are using the same mask for both items since teacher seems to get the edge while students gets more of the center part. You need two instances of the mask.
Comment: Thanks for your reply, but preserve aspect doesn't seem to work. Perhaps my elaboration wasn't clear enough. I have added two more images to elaborate the problem. That should explain why the teacher button gets the edge while the student button gets more of the center part. And do you mean I need N Material instances in my Unity project for each of N icons that I use?
Comment: What it looks like is that you have your buttons under one main object and that object has the mask. The hierarchy you need is one main object then under you have N mask objects each with a mask component and Image with preserve aspect then under each of those you have your N objects with teacher/Students and so on. Each mask will cover its own child object.
Comment: Oh. I'm afraid you've misunderstood. I am not using the UI mask system, as it has aliasing problems (http://answers.unity3d.com/questions/942614/aliasing-when-using-ui-mask.html) that are not yet fixed. That's why I am resorting to using shaders to mask sprites.
Answer: Alright, here's a kind of jury-rigged solution.
Firstly, the circle image that you're using for your mask will need to have its texture wrap mode set to Repeat.
Then, find this line of code:
half4 mask = tex2D(_MaskTex, IN.texcoord);

And insert this line of code before it:
IN.texcoord.x *= 9;
half4 mask = tex2D(_MaskTex, IN.texcoord);

This will turn your one circle stretched over 9 sprites into 9 circles repeated over 9 sprites. (If you had more than 9 sprites, you would need to change this.)
Hope this helps!
Comment: This works. And for my case it is
    IN.texcoord.x *= 10;
    IN.texcoord.y *= 2;
... since I have 10 icons per row and I have 2 rows.

While it definitely works, this mask can only serve this particular 2 x 10 icon map and will draw funny shapes if used on anything else.


wpf, I create dynamically many window form at runtime, but how can I grab these window form's identity?

Question: I want to send different messages to specified window, but I do not konw how to identify a given window from all. Is the way to use the window's property of "Name"?
Comment: You want to get the title at the top of the window?
Comment: Yes, you can use Name or Title properties.
Comment: no. I want to send a message to a window, but I don't konw how to identify that window because there are many windows created dynamically.
Comment: So you're trying to get the window's handle (HWND)?
Answer: You can create your own Window class
public class MyCoolWindow : Window
{
   public string WindowKey {get;set;}
}

and on every window create add a new window to a glbal collection, for exmaple:
var windows = new List<MyCoolWindow>();

public void AddAndShowWindow(MyCoolWindow wnd)
{
    windows.Add(wnd);
    wnd.Show();
}

find window, for example
public MyCoolWindow FindWindowByKey(string windowKey)
{
    return windows.Where(w=>w.WindowKey == windowKey).SelectSingleOrDefault();
}

Just example.
Answer: Another option is to use reflection to find all the Windows in your executing assembly:
var windows = System.Reflection.Assembly.GetExecutingAssembly()
             .GetTypes().OfType<Window>();

Once you have your collection of Windows, you can find any of them by name:
Window win = windows.SingleOrDefault( x => x.Name == "MyName" );


Is x more, less or equal to the value y?

Question: What would be the most the concise way to express the following in Ruby:
Is x more, less or equal to the value y?
Answer: Do as below using spaceship operator(<=>) :

Returns 0 if obj and other are the same object or obj == other, otherwise nil.
The <=>  is used by various methods to compare objects, for example Enumerable#sort, Enumerable#max etc.
Your implementation of <=> should return one of the following values: -1, 0, 1 or nil. -1 means self is smaller than other. 0 means self is equal to other. 1 means self is bigger than other. Nil means the two values could not be compared.

x <=> y

Comment: Beat me to it :)
Check this out too: http://stackoverflow.com/questions/827649/what-is-the-ruby-spaceship-operator
Comment: It will return `-1` if x is less than y, `0` if they are equal and `1` if x is larger than y.


Integrable sequence of functions $f_n$ that converges uniformly implies that $f$ is integrable and integrals are the same

Question: Let $(f_n)$ be an integrable sequence of functions on $\Omega$ that converges uniformly $f_n \rightarrow f$.
Show that if $\mu(\Omega) < \infty$ then (1) $f$ is integrable and (2) $ \lim_{n\rightarrow\infty}\int f_n d \mu=\int f d \mu$.
So by definition $f_n$ converges uniformly if for all $\epsilon > 0$ there is an $N$ so that for all $n \geq N$:
$|f_n(x)-f(x)|<\epsilon$.
In other proofs that I have found is says that it is also less than or equal to $\epsilon/\mu(\Omega)$ which I don't quite understand?
To show (1) I need to show that $\int_{\Omega}|f| d \mu <\infty$ and for (2) $|\int f_n d \mu-\int f d \mu| \rightarrow0.$
I guess for (1) I somehow need to prove that the integral is less than the integral of $|f_n|$ which is finite by definition. I'm not sure how to prove (2).
Answer: Because $\mu (\Omega) < \infty$ the constant function $1_{\Omega}$ on $\Omega$ is integrable ($\int 1_{\Omega}d\mu = \mu(\Omega)$) and thereby also $f_n + \epsilon$ and $f_n-\epsilon$ by linearity of the integral. As the $f_n$ converge uniformly, for all $\epsilon>0$ there exists $n_0$ such that for all $n>n_0$ $|f_n-f|<\epsilon$ and so $f_n-\epsilon<f<f_n+\epsilon$, so $f$ is bounded by an integrable function and therefor integrable (This follows from the dominance convergence theorem and the fact that $\mu(\Omega)<\infty$, so every integrable function is absolutely integrable).
But now for the integral we get by monotony that:
$\int f_nd\mu - \epsilon*\mu(\Omega) =\int (f_n-\epsilon) d\mu < \int fd\mu<\int (f_n+\epsilon) d\mu<\int f_nd\mu + \epsilon*\mu(\Omega)$ for $n>n_0$
As $\epsilon>0$ is arbitrary this gives for all $\delta>0$ an $n_0$ such that for all $n>n_0$ $|\int(f_n-f)d\mu|<\delta$ if we choose $\epsilon=\delta/\mu(\Omega)$, so the integral converges.
Comment: Thank you! Could you elaborate more on why $1_\Omega$ and $f_n + \epsilon$ are integrable? I also don't understand why $\int f_nd\mu - \epsilon*\mu(\Omega) =\int (f_n-\epsilon) d\mu$?
Comment: Any scaling of integrable functions are integrable and (finite) sums of integrable functions as well, this is the linearity of the integral
Comment: So $\epsilon \mu(\Omega) = \int \epsilon d\mu$?
Comment: Yes and as you can see this is only well defined for $\mu(\Omega)<\infty$


What is the sha256sum check sum for Ubuntu studios 22.04?

Question: I'm trying to make sure the iso image is good. I'm a noob so any help is appreciated.
Answer: The SHA256SUM checksum for the ubuntustudio-22.04.1-dvd-amd64.iso file for installing Ubuntu Studio 22.04 is 3fe6fa9a17fa7a4b34b2ec7ff3b9500d354ca644aedcc37096b923f14247f504
The source of this link is Ubuntu Studio 22.04.1 LTS Release Notes.
Comment: Ty so so much. It matched appreciate it a million times over!!


What is IndexError? I keep Getting It

Question: Here is my code:
quote = input("Enter a Sentence: ")

a = len(quote)
counter = 0
counter1 = 0
reverse = a

print("The Length of the sentence is",a,"characters long!")

for x in range(0,a):
    if str.isspace(quote[x]) == True:
        counter = counter + 1

print("The Length of the sentence is",a - counter,"characters long (excluding space...)!")

for x in range(0,a):
    if str.isupper(quote[x]) == True:
        counter1 = counter1 + 1

print("The number of Upper Case Characters in the sentence is",counter1,"characters!")

print("The number of Lower Case Characters in the sentence is",a-counter1,"characters long!\n")

while reverse >= 1:
    r = reverse
    print(quote[r])
    r = r - 1

It's aim is to find everything about that sentence, but the only problem is the 'While' loop at the bottom. It doesn't seem to work, and it's aim is to 'inverse' the sentence. However, it gives my an error which looks a bit like this:
Traceback (most recent call last):
  File "C:\Documents and Settings\ususer\My Documents\Downloads\StringStuff.py", line 27, in <module>
    print(quote[r])
IndexError: string index out of range

What Am I doing wrong? Please help!
Comment: use `print(r)` to discover your problem
Answer: Python is 0-indexed, so the first character of a string is str[0] and the last is str[len(str) - 1]. So, since you start with reverse = len(quote), at the end you are doing quote[len(quote)], which is one past the end of the string.
So, you should probably start with reverse = a - 1 and your loop at the end should look something like:
while reverse >= 0:
    print(quote[reverse])
    reverse = reverse - 1

Comment: Note also that his current while loop will never exit, as he decrements `r`, not `reverse`.
Comment: Thanks, but it doesn't seem to work. It only prints the second character.
Answer: You have run into the common problem that Python starts indexing from 0, but returns the lenght of a list as a valid integer counted from 1. This results that for any list, l[len(l)] will give you IndexError, because a list of length 10 will only have indexes 0...9.
All you have to do is to initialize reverse = len(quote)-1.
You also have to descend your loop variable inside the while loop, so use reverse-=1 instead of r=r-1.

What is IndexError? I keep Getting It


Bash script with smaller scripts internally

Question: I have a sequence of small bash scripts that I need to run in a particular order.
I figured I could do this by creating a script that executes each script, one after the other, because most of the scripts take input from the output files of the previous.
However, when I try to execute the script, it tries to run each of the internal scripts at once, and returns a lot of no such file or directory errors.
I have my script formatting like this.
#!/bin/bash
bash script1.sh
bash script2.sh
bash script3.sh

And I do not want to run script2.sh until script1.sh has finished executing. Is there a simple way to do this?
Edit: I forgot to mention that I have a few python scripts in the list as well. Not sure if that changes anything.
Comment: The code you show should not start script2 until script1 completes. Unless script1 does stuff in the background. You'll need to provide more details about how the scripts are written.
Comment: @glennjackman Agreed. Executing in parallel is unexpected behavior, but that might not be the problem here and it's a "debug my code" question. I expect "script[1-3].sh" are not in the cwd, so `no such file or directory` is more likely bash saying it doesn't know what to make of `script1.sh`. Should be `bash /path/to/your/script1.sh` or simpler still without the prefix, `/path/to/your/script1.sh`.
Comment: If *most of the scripts take input from the output files of the previous*, why don't you just start `script2.sh` at the end of `script1.sh` and so forth?
Answer: The correct solution for you depends on what you want:

Combining the scripts with && will only execute the second if the first exits successfully
Combining the scripts with || will only execute the second if the first doesn't exit successfully

If you want the second command to be executed after the first no matter whether it exits successfully or not, you can use either ; or & wait:
bash script1.sh ;
bash script2.sh & wait
bash script3.sh

Comment: Semi colon worked for me and seems to be the simplest solution. Thank you!
Answer: You could try sourcing the scripts
#!/bin/bash
. script1.sh
. script2.sh
. script3.sh

If there are variables that must be removed after each script, enclose it in parentheses, i.e.
#!/bin/bash
(
    . script1.sh
)
(
    . script2.sh
)
(
    . script3.sh
)

Another possiblility is to call the scripts directly:
#!/bin/bash
./script1.sh
./script2.sh
./script3.sh

If you want all background processes spawned by the scripts to finish, add
wait to wait for them
eg.
./script1.sh
wait
./script2.sh

Your current solution is running concurrently as bash opens a new shell and executes that
Comment: I don't understand your point about braces. They only delimit a block of code. Maybe you are thinking of parentheses, which delimit a block of code *and* open a subshell?
Comment: @wjandrea I just checked. You're right. I must be thinking of C syntax
Answer: Do it as this way.
bash script1.sh && bash script2.sh && bash script3.sh

Or this way:
bash script1.sh &&
bash script2.sh &&
bash script3.sh

This will ensure if previous script exited successfully, then next script will execute.
Or use ; instead whether you need to execute next script apart of previous script is exited success or failed.
bash script1.sh ; bash script2.sh ; bash script3.sh

Comment: @dessert see update, also when user wants to execute next script once first is exited successfully or not instead of using `&&`, s/he could use `||`
Comment: @dessert correction `;` not `||` will cause execute next command if first exited success or failed
Comment: So what about when a script **doesn't** exit successfully, but one nevertheless want the next one(s) to be executed?
Comment: One long line might be ugly and unclear with long paths etc. – where can one add line breaks?
Comment: `||` will **only** execute the following command(s) if the previous doesn't exit successfully, but isn't there a way to combine both?
Comment: And same for python scripts: `script1.py; script2.py; script3.py`  or `script1.py && script2.py && script3.py` - if the scripts are marked as executable.
Comment: this is not only for scripts, it's can be any command/script
Answer: Add set -e to the beginning of all the scripts. When this option is on, any command failing will cause the whole script to fail, like what would happen if commands were separated with '&&'. the spec
"most of the scripts take input from the output files of the previous" sounds like what make is for. Consider using it.


Are there any factors that change the spawning of mobs?

Question: What I mean by the title is if you take pig's home while they're dead, does that stop them from spawning? Or does having them die from a mob or you killing them change their spawn time? If you could also post the normal respawn time that would be nice too.
Comment: I am sorry for the butcherd grammar.
Answer: According to the wiki, when a pig is killed they will always respawn in their house. They respawn the morning immediately after their death.
As far as I can tell, this is regardless of what killed them or whether you occupy their house.
Additional information can be found at the wiki page.
Comment: Do you know if destroying their house stops them from spawning?
Comment: Given that's their respawn point then yes, they wont respawn any more. You can of course build a pig house to get a new pig.
Comment: No trouble at all c:
Comment: From the video's I watched on youtube, I was told you can kill a pigman, then attack its house and it (or on of its compatriots) will immediately spawn again to protect its home.


Each request from user call a new getConnection()?

Question: The database connection is get like below
public Connection getDBConection(){
   Context context = new InitialContext();
   DataSource dataSource = (javax.sql.DataSource) context.lookup("java:myDataSource");
   Connection conn = dataSource.getConnection();
}

For a userA, is each database request should call getDBConnection() once; but no need to control all request use the same connection?
That is, if userA has three database request, then userA should call getDBConnection() three times, and call Connection.closed() after used in each request?
If the userA call getDBConnection() three times (that is, call dataSource.getConnection() three times), is three connection created? Or it is unknown and controlled by weblogic?
I feel very chaos, is it true that there should be one new connection for one database request? or just call DataSource.getConnection() for each database request and the number of new connection created is controlled by web server, no need to think how many connection is actually created.
Answer: Every time you call DataSource.getConnection, the data source will retrieve a connection for you.  It should be true that the returned connection is not being actively used by anyone else, but it is not necessarily a brand-new connection.
For example, if you use a connection pool, which is a very common practice, then when you call Connection.close, the connection is not actually closed, but instead returns to a pool of available connections.  Then, when you call DataSource.getConnection, the connection pool will see if it has any spare connections lying around that it hasn't already handed out.  If so, it will typically test that they haven't gone stale (usually by executing a very quick query against a dummy table).  If not, it will return the existing connection to the caller.  But if the connection is stale, then the connection pool will retrieve a truly new connection from the underlying database driver, and return that instead.
Typically, connection pools have a maximum number of real connections that they will keep at any one time (say, 50).  If your application tries to request more than 50 simultaneous connections, DataSource.getConnection will throw an exception.  Or in some implementations, it will block for a while until one becomes available, and then throw an exception after that time expires.  For a sample implementation, have a look at Apache Commons DBCP.
Hopefully that answers your question!
Comment: then if userA has three different database request, he should call DataSource.getConnection() three times, and call Connection.close() three times, right?
it is not good for using the same connection for serving the three database request (not good to just call DataSource.getConnection() once for three different database request, right?)
I asked this because sometimes I see the create connection time is heavy and need cache that connection, but in fact, this is already done by JDBC drvier, no need handle by application developer?
Comment: If you have three different database requests, and they should be performed one after the other (i.e. not by three different users in three different threads), then by all means, I would perform them all using the same `Connection`.  I wouldn't rely on your data source being configured in a particular way.


From an accessibility perspective, is it alright to use blue text for headings?

Question: Since most people associate blue words/phrases on a webpage with hyperlinks, I know it's a bad idea to use blue text to provide emphasis on a word or phrase within a paragraph. However, does the same issue apply when blue is used for headings?
Comment: How will users distinguish non-linked headlines from linked headlines?
Comment: The site I'm working on doesn't currently have any linked headlines. This might change, though, as not all of the content is up yet.
Answer: I definitely agree with the previous statements regarding the need to be careful to not cause confusion about what is/is not a link. However, from a strictly accessibility standpoint, you would be best to focus on the contrast of the heading more so than the blue/not blue. To check to see if you have adequate contrast in place, you should check WEB AIM's Contrast Checker.
Answer: From the Smashing Magazine article 10 Useful Usability Findings and Guidelines:

Blue Is The Best Color For Links
While giving your website a unique
design is great, when it comes to usability, doing what everyone else
is doing is best. Follow conventions, because when people visit a new
website, the first place they look for things are in the places where
they found them on most other websites; they tap into their experience
to make sense of this new content. This is known as usage patterns.
People expect certain things to be the same, such as link colors, the
location of the website's logo, the behavior of tabbed navigation and
so on.
"Google keeps all links on its websites blue for a reason: the color
is familiar to most users, which makes it easy to locate."

If its a hyperlink headline of an article I would use the blue text color since you are trying to get people to click on it.
If its just a simple headline for a page or its best to
use a non-distracting color like grey for example.

Headlines are used to get your attention but if your goal is to have the user continue reading the rest of the page it should not be the focal point and blue tends to do that.
Again it depends on what is used for and the type of site it is.
Comment: What is the source of this quote? (You should link to it in your answer.)
Comment: I've found and added in the source for your quote here but in future make sure you credit the source when using content written by someone else.


Configure subfolder in nginx server for Angular 5 app

Question: I have two angular app's published to two different subfolders "testapp1" and "testapp2".
url's -
    https://dev.testurl.org/foo -- For testapp1
    https://dev.testurl.org/bar -- For testapp2

So i build angular with basehref
For testapp1:
 ng build --prod --base-href /foo/

For testapp2:
  ng build --prod --base-href /bar/

My nginx configuration,
server {
  listen 80 default_server;
  listen [::]:80 default_server;

  client_max_body_size 1000M;
  server_name dev.testurl.org localhost;

  location /testapp1/ {
            autoindex on;
    root /testapp1/dist;
    try_files $uri $uri/ /foo/index.html;
  }
  location /testapp2/ {
            autoindex on;
    root /testapp2/dist;
    try_files $uri $uri/ /bar/index.html;
  }

When i try to hit, https://dev.testurl.org/foo or /bar - it has console error says "Unexpected Syntax Error" basically it's not loading the correct sources. Any idea? whether i am building app correctly or doing something wrong nginx configuration?
Comment: Why do you have `foo` and `bar` in your question, but `testapp1` and `testapp2` in your configuration file?
Comment: @RichardSmith Edited the original post.
Comment: So `/foo/index.html` is actually located on the server at `/testapp1/dist/index.html`?
Comment: Yes you are right
Answer: There are two problems with your configuration:
The root directive is used when the path to the file can be calculated by concatenating the document root with the requested URI. Otherwise, use alias. See this document for details.
The location directive is used to match all or part of the URI. See this document for details.
For example:
location /foo {
    autoindex on;
    alias /testapp1/dist;
    try_files $uri $uri/ /foo/index.html;
}
location /bar {
    autoindex on;
    alias /testapp2/dist;
    try_files $uri $uri/ /bar/index.html;
}

The location and alias values should either both end with / or neither end with / in order to get the correct string substitution.
Answer: Use alias for hosting local dist folder as subfolder as Richard said.
And ff you want to proxy pass to another endpoint as subfolder, see below thread~
https://stackoverflow.com/a/64112450/853509


Electrical wiring 14-2 wire connect 12-2 wire

Question: My outlets are 14-2 NM wire, wired into the attic, is it ok to connect a  12-2 NM wire to the 14-2 wires and connect them to the panel box w a 15amp breaker???
Comment: I think "not" a duplicate because in this case he has the proper breaker which is really core to the question.
Comment: Even though it may be legal, why would you do that?
Comment: multiple issues, id rather not share here...thx I have  marked the breaker and the wires in more than one place that it has both 14-2 and 12-2 wires connected....
Answer: You could use the 12 awg wire on a 15 amp circuit connecting the section that is wired in 14.
 The only problem and I have found with this in the past where part was wired in 14 but the breaker had #12 , I am guessing that at a later date someone put in a 20a breaker and cooked the 14 gauge wireing because it looked like it was wired with 12 at the panel.
Comment: that is exactly my concern. I guess there isn't actually a code prohibition to protect against this sort of future confusion.
Answer: Yes. There's no problem using larger wire (as long as it fits in any terminals/connectors), since thicker gauge wire can carry larger amounts of current.
Comment: @Adonalsium I've never had any trouble using properly sized twist-on wire connectors.
Comment: @Adonalsium never had that problem before, except when trying to re-use ratty old Scotchloks, which are not made for reuse.   And I often mix solid and stranded too.  If your nuts aren't working for you, either use modern good ones (e.g. ideal's Wingnuts) and use them correctly.
Comment: There is an issue - it is harder to make a good, solid connection between wires of different diameters, especially when using wire nuts (as opposed to a wago). The solution is to be careful, make good connections, and use a wago if you doubt your wire twisting abilities.


Group theory optimization; abstract algebra relevant?

Question: Suppose a girl, call her Alice is lost from home. Where all her geographical surroundings, including both herself and the position of her house can be modeled as particular vertices in a graph $G$ such that each edge in $G$ corresponds with a road that Alice can walk down as she attempts to find her way home. However Alice is on the phone with her friend Bob, who is trying to give her directions to get back home based on what she tells him of her current surroundings, yet Alice can only see those vertices directly adjacent to her and so Bob must try his best based on her description of where she is to help her navigate back home.
Now my goal is to optimize the graph $G$ to make it as hard as possible for Alice to get home. After rethinking this several times, I can't help but think it involves group theory which seems weird in this particular context as I've not used abstract algebra in related problems of this nature before. Though in any case my train of thought was:
Try to design a graph based on the constraints I was given, such that knowing the neighbors of any vertex gives as little structural information about that vertices positions relative to the graph as a whole, in this way since Alice can only see geographic objects adjacent to her, a graph satisfying this property would ensure Alice conveys as little information about her position as possible to Bob.
However if the graph has a large automorphism group, or is "vertex transitive" then since any vertex can be mapped to any other vertex via a bijective map. This would make the positions (vertices) essentially indistinguishable up to the objects (vertices ) adjacent to Alice's position.
So I'm thinking the more "transitive" I make the graphs automorphism group, the less information Alice will have about her geographic position relative to $G$, which means less info can be given to Bob, which means Alice will likely remain lost longer being unable to give much of a description of her surroundings based on the structure of adjacent vertices.
Though I'm not totally sure I'm interpreting transitive group actions correctly and also the fact that group theory is coming up in an optimization problem seems kind of weird to me, so I think I might be looking at the problem wrong. Is my vague intuition corerct? Or am I (probably) interpreting the relationship between a graphs automorphisms and individual vertices relative distinguish-ability based on their neighbors wrong?
Comment: What does it mean that Alice can only see the adjacent vertices? If Alice knows which vertices those are (e.g. "I am on a vertex adjacent to the Eiffel tower") then Bob can tell her to go to one of those vertices and then give directions from that vertex. This seems to trivialize the problem. Otherwise, does Alice just know how many adjacent vertices there are? (The degree of the vertex she is on.)
Comment: What does being able to distinguish the roads translate to, in graph-theoretic terms?
Comment: @MishaLavrov All vertices are unlabeled except her house. All she can distinguish is the roads. Also there is a variant of the problem where she can see down $n>1$ roads, rather then one.
Comment: @ Misha Lavrov Roads are graph edges. Anyway I just want to know if I'm on the right track, the specific constraints involved are kinda complicated and don't really help with a general approach. It just reminded me of group theory, as I remember a vertex transitive graph is one in which (I think) the vertices become "indistinguishable" in a sense from each other, "structurally".
Answer: Concepts like vertex transitivity and the automorphism group of a graph seem to address a slightly different problem. Suppose that Alice, from where she's standing, sees the entire structure of $G$, but can't tell the vertices apart in absolute terms: she can only describe them relative to her current position. (I guess we'd still want Alice to need to be sufficiently close to a vertex before she can identify it as her home; otherwise, she could just go there.)
In that case, two vertices are indistinguishable, based on this description, if there's a graph isomorphism that takes one vertex to the other. In particular, if the graph is vertex-transitive, then no two vertices are distinguishable, and Bob can't give Alice any useful advice.
In your case, Alice only has local information about the graph, and there doesn't need to be an isomorphism of the whole graph to make two vertices indistinguishable. The simplest version of the problem is when Alice can count the number of edges/roads out of her current location, but can't see what the destinations look like. (Maybe she'd be able to recognize one of them as home, maybe not; this doesn't really change the problem.)
In this case, two vertices are indistinguishable if they have the same degree. A regular graph is one in which all vertices have the same degree, and so all vertices look alike, and Bob can't help Alice find home.
Finally, we can give Alice just a bit more power. Maybe Alice can look at the adjacent vertices and be able to count their degrees. Or maybe she can see up to $k$ steps away, for some $k$.
I'm not aware of a term for the "hard case" of this problem in general, but one way we could make the problem hard is by looking at regular graphs with a minimum girth. The girth of a graph is the length of the shortest cycle. If Alice is in an $r$-regular graph with girth $2k+1$, then she will always see the same thing when standing at any vertex: "there are $r$ neighboring vertices; each one of them has $r-1$ other neighbors, and each one of those has $r-1$ other neighbors, and so on, and those are all distinct."
Regular graphs with large girth are not hard to come by. In fact, a randomly chosen $r$-regular graph on $n$ vertices will have only a constant number of cycles of lengths $3, 4, \dots, 2k$, as $n$ goes to infinity: this means that only a small fraction of the vertices in the graph look different from the boring uniform description above. With a constant probability (depending on $k$), there will be no such cycles, and all vertices will look the same to Alice.
Comment: Algorithms that test for graph isomorphism typically rely on group theory to do their job. (In general, the hard cases of graph isomorphism are graphs that have a large automorphism group.)
Comment: @MishaLavrov Thanks, also you seem to be solving all my graph theory questions. I really appreciate it.


Neo4j Cyper: Indexing numeric field

Question: I am using Neo4j with Cyper query
My requirement:
How to index a numeric field of node in optimised way.
My Person Node as,
year_month  --> 2014.1 or 2014.2 or 2014.3 and so on
desc
status

Presently indexed as,
    CREATE INDEX ON :Person(year_month)

Is there any optimised way to do index specially for numeric (Using Cyper queries) ?

i found somewhere as
new ValueContext( 1999 ).indexNumeric() for indexing

whether the above is possible to use it in Cyper queries ?
Answer: Indexes on properties and label only apply to equality comparisons in the WHERE clause in Cypher: http://docs.neo4j.org/chunked/stable/query-schema-index.html#schema-index-use-index-with-where
To make use of the index on the year_month property, you must specify an exact match for optimized lookups.
WITH 2014 as year, 5 as month
WITH ((year * 12) + month) as year_month
MATCH (p:Person { year_month: year_month })
RETURN p

Here are some tips for optimizing your Cypher queries for both range queries and exact match queries on year_month.
Instead of floating point values, convert your year and month to an integer.
Conversion to: monthIndex = (year * 12) + month
Conversion from: year = (monthIndex / 12), month = (monthIndex % 12)
Create node with a compound index for the properties month and year as year_month:
WITH 2014 as year, 5 as month
CREATE (michael:Person {
    name: "Michael",
    year_month: ((year * 12) + month),
    year: year,
    month: month })

Create your index on year_month property of the label Person:
 CREATE INDEX ON :Person(year_month)

This approach allows you to query by range.
Query the node by range between 5/2013 and 5/2014:
WITH 2013 as year_from, 5 as month_from,
     2014 as year_to, 5 as month_to
WITH ((year_from * 12) + month_from) as date_from,
     ((year_to * 12) + month_to) as date_to
MATCH (p:Person)
WHERE p.year_month >= date_from AND p.year_month <= date_to
RETURN p

Neo4j Cyper: Indexing numeric field


textView height equal to content size without viewDidLayoutSubviews

Question: I'm creating a viewController which contain 2 textViews a title and a fullText. At the moment i've created 2 textViews in the interface builder which is placed below each other and then created following code to change the height to equal to the content. However the issue is that it seem to be delayed, which gives a bad user experience. By delay i mean that it takes 0.5 or 1 sec before it resize? here is my code:
override func viewDidLayoutSubviews() {

    super.viewDidLayoutSubviews()

    setHeightToContent(self.titleText!)
    setHeightToContent(self.fullText!)

    scrollView?.contentSize = CGSizeMake(self.view.frame.width, self.fullText!.frame.origin.y + self.fullText!.frame.height)
    println(self.fullText!.frame.origin.y + self.fullText!.frame.height)

}

func setHeightToContent(theTextView: UITextView) {

    let contentSize = theTextView.sizeThatFits(theTextView.bounds.size)
    var frame = theTextView.frame
    frame.size.height = contentSize.height
    theTextView.frame = frame

    var aspectRatioTextViewConstraint = NSLayoutConstraint(item: theTextView, attribute: .Height, relatedBy: .Equal, toItem: theTextView, attribute: .Width, multiplier: theTextView.bounds.height/theTextView.bounds.width, constant: 1)
    theTextView.addConstraint(aspectRatioTextViewConstraint)
}

Answer: Make each of the text views self-sizing in accordance with its own content, and use constraints so that the scroll view's contentSize is configured automatically based on its content.
Comment: how do i make them self-sizing i thought that was what i was doing in setHeightToContent
Comment: You are, but you're calling it in `viewDidLayoutSubviews`. You want to do it at nib load time and then, if the content can change, in response to that. (Indeed, that may be in part the cause of the delay, since you are doing layout in response to layout having been done.)
Comment: Also, I'm not saying you're making this mistake, but just to be sure: don't use a text view if a label will do. A label is very, very good at sizing itself to the height of its content. So if the user does not need to type in this thing, use a label, not a text view.
Comment: Okay i think i understand, would this require me to create the UILabels programmatically in order to resize at nib load
Comment: With proper constraints and `preferredMaxLayoutWidth`, a label's height _is_ self-sizing. And the `preferredMaxLayoutWidth` is automatic by default in iOS 8. So they do not have to be "created programmatically". It just works.