Need some help with complex-analysis definitions and understanding

Question: Right, so I'm struggling proving/disproving that for functions $u,v: \mathbb R^2 \to \mathbb R$ if $v$ is a harmonic conjugate of $u$, then $u$ is a harmonic conjugate of $v$ (so the relation is symmetric)...
I've been trying to disprove it so far and I'm not having luck...
Am I correct in saying if a function is holomorphic, then it satifies Cauchy-Riemann equations and that is the best test for holomrophisms?
Also, if a function is indeed holomorphic, is that equivalent to saying it's analytic? Or is there a difference?
The definition of a harmonic function is as follows:
$u(x,y)$ is harmonic if there exists some $v(x,y) : f=u+iv$ is holomorphic, in which case, $v$ is the harmonic conjugate of $u$
If I'm trying to find a counter example to disprove my first statement, do I find 2 functions, $u , v$, substitute them into $f=u+iv$ and show that the Cauchy-Riemann equations don't hold? For some reason, I'm not believing that Cauchy-Riemann equations do test for holomorphism.
If you look at a similar question I posted, some user told me two different functions, and stated that one was holomorphic and one wasn't... but surely the fact that they're independently holomorphic is irrelevant... $f=u+iv$ has to be holomorphic right!?
And finally, if there are two holomorphic functions $u,v$, is it not the case that $f=u+iv$ will also always be holomorphic?
Any help is really really appreciated thanks
Answer: Your first claim about the harmonic conjugates is correct. In fact, both $u$ and $v$ must satisfy Laplace's equation, which is the PDE $\Delta$$u(x,y)$=$0$. (Here, $\Delta$$\phi(x,y)$ is defined as the trace of the elements in the Hessian matrix, or matrix of second partials. Holomorphic is actually another term synonymous to analytic, yes.  However, note that the Cauchy-Riemann equations only give a necessary condition for f(z) to be analytic in some neighborhood around $z_0$, not a sufficient one. For a both sufficient and necessary condition, we need to make sure that the four partial derivatives of the real and imaginary parts of $f= u + iv$ are both continuous and satisfy the Cauchy-Riemann equations themselves. If these sets of conditions are true, along with the Cauchy-Riemann equations, then yes, f is analytic. For a counter-example of this, take                                        $f(z)$ = \begin{cases} \frac{\overline{z}^2}{z} &, z\neq 0 \\ 0 &,z=0 \end{cases}
You will see that the CR equations hold, but the complex derivative does not exist at $0$. Hope this helps to point you in the right direction.


Why do I have to add a PPA twice (once to add it to the list of repo, second time to fix a BAD GPG)

Question: I notice the following:

I add a ppa using add-apt-repository, for example the wine ppa, mozilla security, nvidia drivers, etc..
When I go to the Update Manager and tell it to CHECK for updates it throws me a PPA error.
To solve the error I add the same PPA again.

Why do I have to add the PPA again (This also can be done by adding the received key alone with apt-key) but why does this problem happen anyway.
UPDATE - I have to add two small details.
First that removing the previous PPA that has the GPG problem and then adding it up again will have the same effect as adding it twice since adding it again (without removing it first) will overwrite the same PPA. But still in the end you would have to add it twice.
Second using the Update Manager (Clicking on the Settings Button and going to the Software Sources) to add the PPA has the same problem as adding it in the terminal. In both cases you have to add it twice. I can confirm this for Nvidia ppa, Mozilla Security ppa, Wine ppa and any other PPA I started trying in 11.10. I have to add that this issue was not a problem in 11.04. It started with 11.10. Somehow there is some minor details that trying to add a PPA the first time does not trigger the key for it. Doing it a second time triggers the key and you can use the Update Manager (or any other updater) without having a warning popup saying something about a PPA problem.
UPDATE 2 - I have tested several PPA. They all have the same problem adding them via the GUI Software Sources or via the terminal add-apt-repository. I have to actually add them, run the update command in terminal or via gui and then add them again to solve the problem. Does not matter from where I add them or update or add them again.
Comment: What error did it showed? and why did you not remove it first update the repos and add it back instead of adding it twice with `add-apt-repository` but shouldn't matter because it would only get overwritten you'd get something like imported:0 nothing added and what was the PPA?
Comment: @Uri - Yes as you mentioned I have also done that. Ends with the same effect, solving the GPG problem BUT in both cases I end it up adding the PPA both times. In this case at least did not have to delete the previous PPA first since it gets overwritten. But still, the question remains about why does it have to be added twice to fix this problem. I will update my question since I also have something to say about using the Update manager as mentioned by david6 below in an answer.
Answer: When you use the command line, you are the one expected to resolve issues around missing keys, or other warnings and errors.
When you instead use the Update Manager, is will attempt to hide (or resolve) many of the issues that might affect you.
Just choose whichever method you are more comfortable with ..
MORE TECHNICAL: Some application's sources (:PPA, wget http://, etc.) will give intermediary errors as you (variously): add a repository, update sources, download PGP keys, and/or resolve additional dependencies.  These are non-fatal errors, and may be reduced (or eliminated) by careful re-ordering of commands - although this is NOT technically required.
Answer: You can fix broken or bad GPG Keys by installing launchpad-getkeys from the WebUpd8 PPA.  In terminal use the following commands:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install launchpad-getkeys

Since you seem to be having problems with Update Manager recognizing new PPAs, simply do the above steps without involving the Update Manager.  Once you have installed the package, run the following command in your terminal:
sudo launchpad-getkeys

Wait for the program to finish.  Your terminal should look similar to this:

As it says, you should have no more problems with missing GPG Keys. This method of fixing your PPA's keys is preferable to adding the same PPA twice, which can cause update problems of its own.
Hope this helps!  Haha it's actually the second time today I've answered a question with this fix.
Answer: Not sure why you're getting this when using the terminal which has been the only way I've seen be successful in 11.10 (one time
Over the course of 11.10 dev probably did 100 or so installs, many times adding a ppa or 2 to test them. Software sources always would fail to add the key so stopped using & went exclusively with terminal command which always was successful.
(though i tended to use from a small group of ppa's so sampling  was small
On a fairly fresh release install took a guess at the ppa you used for wine, went fine. Did you see this on your 1st command line attempt? (& similar on others
:~$ sudo add-apt-repository ppa:ubuntu-wine/ppa
You are about to add the following PPA to your system:
 Latest official WineHQ releases
Welcome to the Wine Team PPA.  Here you can get the latest available Wine betas for every supported version of Ubuntu.
This PPA is managed by Scott Ritchie, and is a replacement for the WineHQ budgetdedicated.com repository used for Jaunty and earlier.
More info: https://launchpad.net/~ubuntu-wine/+archive/ppa
Press [ENTER] to continue or ctrl-c to cancel adding it

Executing: gpg --ignore-time-conflict --no-options --no-default-keyring --secret-keyring /tmp/tmp.zzznKxc3Hx --trustdb-name /etc/apt/trustdb.gpg --keyring  /etc/apt/trusted.gpg --primary-keyring
/etc/apt/trusted.gpg --keyserver hkp://keyserver.ubuntu.com:80/ --recv 883E8688397576B6C509DF495A9A06AEF9CB8DB0
gpg: requesting key F9CB8DB0 from hkp server keyserver.ubuntu.com
gpg: key F9CB8DB0: public key "Launchpad PPA for Ubuntu Wine Team" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

Edit: for rechecking as per comment, to start fresh
Open software sources, uncheck & then "remove" the entries. While in Software sources click on 'Authentication', find the relevant key & remove it.
To remove last traces open /etc/apt/sources.list.d/ as root & delete the relevant .list & if there .list.save files
For good measure then run a sudo apt-get update.
Comment: Correct. Exactly like that, right down to the last 1) there. After that, if I went to Update manager, did a Check on it, it would tell me "Hey man, the ppa for wine is wrong". So I would remove or readd the PPA and done. What other thoughts might you have about this problem.
Comment: Then i gather when you run the 2nd time (cli) that the last line would say "gpg:              unchanged: 1". If so then maybe this is just on update manager &   the key has actually been added correctly.  What happens if after adding thru cli if you run an update in the terminal, *sudo apt-get update, are any errors shown or is it clean. I'll edit in answer how to completely start fresh on a ppa (still using wine as Ex.
Comment: When doing it in cli it also shows an error until the PPA is added a second time.
Answer: I add this as the answer since the above 3 did not work for me. Need to make enphasis on the "did not work for me" since they might work for others so they too are correct answers for others.
Anyway, the problem was actually solved about 2 to 3 days ago from an update that landed. Do not know which one but if yo update 11.10 up to the latest version the issues will be solved.
Just tested with a PC from scratch and the issues did not occurred after updating it to the latest.


Wordpress - Menu links and dropdown does not work in frontpage home

Question: When we load site www.cligest.com made with WordPress the menu links and the dropdown options on the web initial page, the frontpage ("home") don't work. They just work in all other pages except "home".
I've tried 15 different solutions, with no luck.
Comment: can you what had been tried.
Answer: Try adding the following css:
nav ul.main-menu {

    z-index: 10;
}

Comment: Thank You Hari! It worked like a charm! After two years of development our site has finnaly gone live thanks to your finnal tip! :D
Answer: This occurs because you have a div on top of the menu. It only happens on the homepage because that div or .homepage-section only exists on the homepage.
Try adding this to your CSS sheet and see if it makes any difference. It should bring your menu on top.
.main-menu {z-index: 2}


How can a gun fire immediately after swapping?

Question: I was playing against a guy the other day who would have his knife out, use the knife crosshairs to aim, and then switch to an awp and immediately fire. Whenever I switch weapons there is always a delay for the animation before I can fire. Was I seeing some kind of exploit?
Answer: Either you played on a custom server where they really changed some parameters regarding the weapon switching or it was just an optical illusion.
There is something what is called fast- or quickswitching. You can find much about it in the web, but this video shows very well, that the actual time you need for usual switching is the same as you need for quickswitching.

Anyway it's a good strategy to switch weapon instantly after shooting (with AWP especially). While some players just want to keep "their hands busy", others want to switch to pistol directly in order to turn off the enemy with it, when the AWP shot missed.
Also found this post: Things about CS:GO that you probably did not know. Next to quickswitching there are other interesting things explained.


Neutral (grounded conductor) for bathroom switch (NEC 404.2(C))?

Question: I understand that a grounded conductor (neutral) is not required by code (404.2(C)) for bathroom switches, but is there any reason that I would want to include it - future-proofing, etc.?
I'm going to rewire my bathroom soon (fan with light, vanity, and one GFCI outlet).  The home run is in the ceiling, so I'd have to run a traveler to the switches in the walls if I want a neutral at that location.
Comment: I agree the wording is poor, but I believe "*Where the switch does not serve a habital room or bathroom*" means in a place other than a habitable room or a bathroom. So the neutral **is** required in a bathroom.
Comment: I think the book's interpretation is incorrect. The NEC does not consider a bathroom to be a "*habitable*" room, as evidenced by ***210.70 (A)(1) Habitable Rooms** At least one wall switch controlled lighting outlet shall be installed in every habitable room and bathroom.*.  Notice that a bathroom is **not** a habitable room.  So in the text you're referencing, they have to include the bathroom as a separate item.  So if the switch is in an area that is not a habitable room or a bathroom (e.g. a garage), then a neutral is not required.
Comment: Where do you see that bathroom switches are excluded from this requirement?
Comment: @Tester101 I'm using Mullin & Simmons' "Electrical Wiring Residential, 18th ed."  They quote 404.2(C), Item 2, which states one exception for the requirement for grounded neutrals as "where the switch does not serve a habitable room or bathroom."  They follow up this quote with a table stating bathrooms don't need the grounded neutral.  My question stems from the fact that 404.2(C) is extremely poorly worded.  The reader is being asked to address more exceptions to the rule than actual implementations, hence my wish to clarify if I need the neutral in my switch leg or not.  Thanks!
Comment: @Tester101 Yeah, that's exactly how I initially interpreted that sentence, too (neutral required), but the book contradicts that interpretation - in other words, the book interprets Item 2 as being read as if it were two separate clauses: the case  "where the switch does not serve a habitable room" and the case "where the switch does not serve a bathroom."  Again, adding up the double-negatives would mean that one doesn't need the grounded neutral - per the book's interpretation - in any bathroom switch.
Comment: The only reason to run a neutral would be to, as you said, future-proof. Timer switches, motion sensing (IR) switches need a neutral, and likely future specialty electronics. I have found that neutrals in switch boxes often cause problems when lay persons start fiddling around.
Comment: @JimmyFix-it -- that's only because switch loops were wired with 14/2 and a retagged white wire to begin with ;)  Had I had my dibs, neutrals at switch boxes would have been Code for a long time by now -- retagged white wires bite people on a regular basis.
Answer: Your book is faulty -- 404.2(C) may not have required neutrals at bathroom light switches at one point in time, but it certainly does in the current (2014) NEC!

C) Switches Controlling Lighting Loads. The grounded circuit conductor for
  the controlled lighting circuit shall be provided at the location where switches
  control lighting loads that are supplied by a grounded general-purpose branch
  circuit for other than the following:
(4) Where a switch does not serve a habitable room or bathroom


Python 2.7(sqlite3) to SQL Oracle, Safe Variables (Prevent SQL Injection)

Question: if instance = "PROD":
     dblink = ('db9_pub',)
elif instance = "BETA":
     dblink = ('dbq9_pub',)
elif instance = "TEST"
     dblink = ('dbt9_pub',)

#Pre-defined SQL Statements

table1_select = ("""select * from example.table1@? """)
table1_insert = ("""insert into example.table1@? (SQL_SELECT_STATEMNT) """)

conn1 = cx_Oracle.connect(logininfo)
cursor1 = conn1.cursor()

cursor1.execute(table1_select,(dblink))
cursor1.execute(table1_insert,(dblink))

So I'm about to start writing a lot of python scripts that will need to pass variables into the SQL statements. Some will be safer like the posted script, some will need to be guarded from SQL injection attacks. I would like to understand the difference between the use of the various variable techniques and which ones are most appropriate.
** %s, '%s', ?, :1  All seem the same to me. What is the appropriate way to do this for safe code? ** I think I've worked this out, I need ?s due to the API I'm using.
BTW, the posted script is throwing an error: illegal variable name/number, so i'm obviously not understanding even the basic application of this.
=============
Edit:
I found this information on a page (http://bobby-tables.com/python) that actually helps some. It helps me work out which version of placeholder to use, but doesn't inform me of how to guard from SQL injection.
Answer: In your above code you can't use a variable in the query string for the specified DBLink. Bind variables are only allowed in places where an expression are allowed, and they will never be interpreted as a database object (table name, column name, function name, etc). However, since you appear to be in complete control of the DBLink through your chained if statements it would be safe (in this instance) to concatenate the DBLink into your query strings:
if instance = "PROD":
     dblink = ('db9_pub',)
elif instance = "BETA":
     dblink = ('dbq9_pub',)
elif instance = "TEST"
     dblink = ('dbt9_pub',)

#Pre-defined SQL Statements

table1_select = ("""select * from example.table1@%s """%(dblink))
table1_insert = ("""insert into example.table1@%s (SQL_SELECT_STATEMNT) """%(dblink))

conn1 = cx_Oracle.connect(logininfo)
cursor1 = conn1.cursor()

cursor1.execute(table1_select)
cursor1.execute(table1_insert)


How concatenate a 2 constants

Question: I am having a few global variables declared in an NSObject class.
NSString *const SAT_NAME=@"http://you.com";
NSString *const DOMAIN= [NSString stringWithFormat:@"%@name/",SAT_NAME,nil];

I want to append the DOMAIN as shown (http://you.com/name/), but it does not work. How can i fix this ?
Comment: What do you mean by "it does not work"?
Comment: possible duplicate of [NSString concatenate on creation](http://stackoverflow.com/questions/21628472/nsstring-concatenate-on-creation)
Comment: Unrelated to issue - why are you passing `nil` at the end of `stringWithFormat`? That's not needed.
Comment: possible duplicate of [How to create constant NSString by concatenating strings in Obj-C?](http://stackoverflow.com/questions/3060139/how-to-create-constant-nsstring-by-concatenating-strings-in-obj-c)
Comment: add a / before %@ it should be /%@name or add it after .com like .com/ and remove nil from your second line.
Comment: @johnykumar No, the slash needs to be between the `%@` and `name` like: `@"%@/name/"`.
Comment: maybe it depends upon its url m just clarifying his issue
Answer: NSString *const SAT_NAME=@"http://you.com";
NSString *const DOMAIN= [NSString stringWithFormat:@"%@name/",SAT_NAME,nil];

Look at the format string. It starts with %@. The %@ is replaced with "http://you.com". Now if you use copy and paste, you see that the result is
http://you.comname/

I don't quite see what you think the nil is good for. There is no formatting for it, so it is just ignored.

How concatenate a 2 constants


Cumulative sum on preceding rows in the same column - R

Question: data:
    test <- structure(list(fgu_clms = c(14621389.763697, 145818119.352026,
21565415.2337476, 20120830.8221406, 12999772.0950838), loss_to_layer = c(0,
125818119.352026, 1565415.23374765, 120830.822140567, 0)), row.names = c(NA,
5L), class = "data.frame")

    > test
   fgu_clms loss_to_layer
1  14621390           0.0
2 145818119   125818119.4
3  21565415     1565415.2
4  20120831      120830.8
5  12999772           0.0

I want to create a new column which tries to use a cumulative sum on the rows above it. It's easier if I show how the calculation on the new column works row by row:
row 1: first calculate the sum the value of rows above in the same column. As this is row 1 there are no rows above this value is 0, call this cumsum_1. It should then take the minimum of the value of row 1 in column "loss_to_layer" and the calculation "x2 - cumsum_1".
In row 2: calculate the cumsum by looking at the value above, i.e. min(x2-cumsum_1,loss_to_layer value). Call this cumsum_2. Then repeat as above, i.e. be subject to the minimum of the value on row 2 of the loss-to_layer column and x2 - cumsum_2.
And so on.
In excel, this would be done by using MIN(B2,x2 - SUM(C$1:C1)) and dragging this formula down.
The results with x2 = 127,000,000 should be:
   fgu_clms loss_to_layer   new_col
1  14621390           0.0         0
2 145818119   125818119.4 125818119
3  21565415     1565415.2   1181881
4  20120831      120830.8         0
5  12999772           0.0         0

As you can see the sum of the "new_col" always sums back up to "x2", in this case 127,000,000.
I have tried:
test <- test %>% mutate(new_col = pmin(loss_to_layer,127e6-cumsum(lag(new_col,1,default=0))))

But get an error as it cannot find the column new_col in the lag function
Comment: @akrun sorry what do you mean
Comment: @akrun Yes that's the problem - that was only my attempt, but I want the new_col to be created with values looking at rows above, but I'm not sure how I can do it.
Answer: test %>%
  mutate(
    cumsum_1 = cumsum(lag(loss_to_layer, default = 0)),
    new_col = pmin(loss_to_layer, 127000000 - cumsum_1),
    new_col = ifelse(new_col < 0, 0, new_col)
  ) %>%
    select(-cumsum_1)

Comment: While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.


how to get the value of a node in xsl based on a value from other node

Question: How do I get the the index of the string that is provided inside node "s" and find the corresponding index value based on the name in the "strings" node?
This is my XSL template:
 <xsl:template match="norm" >
     <xsl:variable name="name" select="@string" />
     <xsl:value-of select="/s/string/@name=$name/@index"/>,
 </xsl:template>

This is a fragment from my source XML:
<s name="main">
    <norm string="back-slash"/>
    <norm string="open-braces" />
    <norm string="close-braces" />
</s>
<strings  name="consts">
  <string name="back-slash" val="\\" index="0"/>
  <string name="close-braces" val="]" index="2"/>
  <string name="remove-null" val="null" index="3" />
</strings>

Answer: You want:
<xsl:value-of select="//strings/string[@name=$name]/@index" />

The big thing you did wrong was you used / instead of [ and ] to enclose your conditional @name=$name.
You also used /s when you want //strings. There is no s/string element.
Comment: thanks i just need to add "//strings" and it started working. thanks a lot
Comment: @user2421350 Thanks for the feedback, I have updated my answer. It was a copy and paste error from my test environment.
Answer: I would define a key <xsl:key name="s" match="strings/string" use="@name"/> and then use <xsl:value-of select="key('s', @string)/@index"/> in the template.


Not able to compile solution after adding new fields to Kentico Page Type

Question: We're using Kentico 11.0.26 with MVC.
We have a page type called Header. It has several custom fields and everything has been pulling over on MVC side just fine. Today I needed to add couple of new fields. After adding the fields, I copied the generated code for Header.cs and HeaderProvider.cs into MVC solution in Visual Studio.
The solution won't compile now.
The 2 new fields are available in the Header.Fields property, but 4 old fields are not available. Remaining old fields are available.
HeaderLogo is one of those 4 fields that are no longer available in Intellisense:
On this line: string HeaderLogo = header.Fields.HeaderLogo; I get the following compiler error:

Header.HeaderFields' does not contain a definition for 'HeaderLogo'
  and no extension method 'HeaderLogo' accepting a first argument of
  type 'Header.HeaderFields' could be found (are you missing a using
  directive or an assembly reference?)

Header.cs does have the definition for HeaderLogo as well as all other fields.
Answer: I'd recommend you to roll back Header.cs and HeaderProvider.cs files and paste only new code from auto-generated by Kentico Info and InfoProvider files. In other words do not replace files, but merge changes.
Looks like you've removed some fields by replacing the file. The question is why Kentico does not include old fields? - Is your database up to date?
Comment: Some fields' name may have been changed since last time code was copied over.


PEX vs PE coiled pipe for underground use

Question: I couldn't find exactly a direct answer; what should be used for an outside, buried water line? I've seen mention of using PEX, but had the black polyethylene pipe recommended.
I'm curious because I need to put in two 60 ft runs of pipe. I'll have to either buy two 100 ft rolls of PE or a 300 ft roll of PEX for roughly the same price and then cut what I need with spare.
From what I see, they are both 160 PSI and can both be used outside, so is there any reason of one over the other?
Answer: "Black polyethylene" seems to commonly refer to HDPE pipe, which is pretty comparable to PEX.  "Just" PE pipe is cheaper and less durable than HDPE - I'd advise against that underground.
PEXa ("Uponor/Wirsbo", "ProPEX", "F1960") is the best option, especially underground and in places with a potential for freezing, since it simply expands and contracts instead of bursting and leaking.  However, PEXa is a bit more expensive but the advantage is it's a lot easier to route in tight areas because it's more flexible. Additionally you have the option of using "expansion" style fittings (which can't be used with other PEX types), which while they are most reliable and free-flowing of all PEX connections, typically require more expensive tools that may not be worth it for a one time job if you can't rent them. PEXa.
PEXb is the more common and typically cheapest form; connections are commonly "crimp" or "clamp" style which are more restrictive than expansion style, but the tool tends to be cheaper. (You can use those types of connections with PEXa as well.)  PEXb will also expand and contract, but to a far lesser degree before risk of splitting. PEXc is also available but is rare.
A downside to PEXa vs PEXb is that PEXa leeches far more chemicals than PEXb. Aside from the health worry, the chemicals taste bad. This doesn't matter for bathrooms, but you may want to use PEXb to the kitchen, or have a dedicated drinking water spout.
Ultimately, PEX is the best option these days, but the type of PEX is more dependent on your situation.

If you plan to do more plumbing in the future and/or the pipe could be subject to freezing, PEXa along with Milwaukee's expansion tool (Milwaukee #2432) is the way to go for worry-free connections.  There are also hand tools available for about half the price of a used Milwaukee kit ($160-200 on eBay at the time of writing).
If you can't rent or find the expansion tool for a reasonable price, or are simply more budget minded, PEXb using crimp or clamp style connections is likely the best path.  Home Depot near me rents the tool for $16/day.
Comment: To tack onto this comment a few years later, there are cheaper tools from major manufacturers like Dewalt. I did a cost comparison of HDPE and PEXa/ProPex, and by the time all the tools were sorted out it was *cheaper* to run PEXa in addition to being substantially more reliable and easier.
Comment: I used PexC for my new house plumbing supply and heating system. I am quite happy with it two years in. I also used it to run a cold line to my outbuilding. I didn't bury it very deep so I blow it out every fall with an air compressor to prevent freezing. Very inexpensive system and you can make wet changes very easily. Can't do that with copper or PVC.
Comment: That's a good point about the chemicals in pexA.  I had never thought of it but it makes sense that more plastisizer chemicals are required to make a more flexible pipe.


How to set information in Kubernetes Network Policy dynamically?

Question: I have a few questions regarding Kubernetes: How to secure Kubernetes cluster?
My plan is to develop an application that secures Kubernetes cluster by default. I have written and tested a few Network Policy successfully.
As a second step I want to set these information dynamically in my application based on cloud provider and so one.
1.) I want to block access the host network as well as the meta data services (my cluster runs on AWS):
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
        except:
        - 10.250.0.0/16     # host network
        - 169.254.169.254/32    # metadata service

Does anyone know how I can access the host network dynamically?
I found an issue that says that you must use the Meta Data Service: https://github.com/kubernetes/kubernetes/issues/24657
Does anyone know how I can find out on which cloud provider I am currently running?
Based on that information, I want to set the meta data service IP.
2.) I want to block access to the "kube-system" namespace:
  egress:
  - to:
    - podSelector:
        matchExpressions:
        - key: namespace
          operator: NotIn
          values:
          - kube-system

Does anyone know how I can enforce the actual denied access?
As far as I understood, the key labled "namespace" is just a name that I choosed. How does Kubernetes know that I actually mean the namespace and nothing else?
3.) I want to block Internet access:
spec:
  podSelector: {}
  policyTypes:
  - Egress

Does anyone know, if something like the DNS server in the DMZ zone is still reachable?
4.) I want to block communication to pods with a different namespace:
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          project: default

Here, I developed a controller that set the namespace dynamically.
Answer: Your ideas are good in terms of a least-privilege policy but the implementation is problematic due to the following reasons.

The logic you are trying to achieve it beyond the capabilities of Kubernetes network policies. It is very difficult to combine multiple block and allow policies in k8s without them conflicting with each other. For example, your first snippet allows access to any IP outside of the cluster and then your 3rd question is about blocking access to the internet - these two policies can't work simultaneously.
You shouldn't block access to the kube-system namespace because that's where the k8s DNS service is deployed and blocking access to it will prevent all communications in the cluster.
To answer your 1st question specifically:

How I can access the host network dynamically?
The cluster subnet is defined when you deploy it on AWS - you should store it during creation and inject it to your policies. Alternatively, you may be able to get it by calling an AWS API.
You can also get the cluster node IPs from Kubernetes: kubectl get nodes -o wide
How I can find out on which cloud provider I am currently running?
Kubernetes doesn't know which platform it is running on, but you can guess it based on the node name prefix, for example: aks-nodepool1-18370774-0 or gke-...

Your 4th point about blocking access between namespaces is good but it would be better to do it with an ingress policy like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all
  namespace: default
spec:
  podSelector: {}
  policyTypes:
  - Ingress

For more details, I recommend this blog post that explains the complexities of k8s network policies: https://medium.com/@reuvenharrison/an-introduction-to-kubernetes-network-policies-for-security-people-ba92dd4c809d
Answer: As Mark pointed out, NP may not be able to address all your use cases. You might want to check out the Open Policy Agent project and there specifically the Gatekeeper tool, which could be utilized, to at least in part cover some of your needs.


Is this a scala bug or am I doing something wrong

Question: I have some code that works in scala 2.10 but fails with an 'Assertion Error' in scala 2.11. I would like some feedback on whether I am being an idiot, if something has changed, or if there is a bug in 2.11 (unlikely, I know.)
Its a simple thing. I have a file of words that is read in and the letters split out into a map.
for (token <- logData.getLines().flatMap(x => x.split("\\s+"))) {
        // Ignore empty lines which appear in the word count as ""
        if (token != "") {
            words += 1
            counts(token) += 1
            for (letters <- token.split("")) {
                if (isOrdinary(letters)) {
                    letterCounts(letters) += 1
                }
            }
        }
    }

Having read in and mapped the letters to letterCounts, I'd now like to extract the letter with the maximum frequency. I try to do this with
val maxLetterCounts = fixedLetterCounts.values.max
    val highestLetter = letterCounts.filter((t) => t._2 == maxLetterCounts)

and I get the error when it tries to run the filter.
This works in scala 2.10 but in scala 2.11 I get
java.lang.AssertionError: assertion failed: List(value _2$mcI$sp, value _2$mcI$sp)
at scala.reflect.internal.Symbols$Symbol.suchThat(Symbols.scala:1916)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.matchingSymbolInPrefix$1(SpecializeTypes.scala:1460)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transformSelect$1(SpecializeTypes.scala:1483)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform1(SpecializeTypes.scala:1579)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.reportError(SpecializeTypes.scala:1420)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform(SpecializeTypes.scala:1371)
at scala.reflect.internal.Trees$class.itransform(Trees.scala:1347)
at scala.reflect.internal.SymbolTable.itransform(SymbolTable.scala:16)
at scala.reflect.internal.SymbolTable.itransform(SymbolTable.scala:16)
at scala.reflect.api.Trees$Transformer.transform(Trees.scala:2555)
at scala.tools.nsc.transform.TypingTransformers$TypingTransformer.transform(TypingTransformers.scala:44)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform1(SpecializeTypes.scala:1712)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.reportError(SpecializeTypes.scala:1420)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transformSelect$1(SpecializeTypes.scala:1467)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform1(SpecializeTypes.scala:1579)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2$$anonfun$transform$3.apply(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.reportError(SpecializeTypes.scala:1420)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform(SpecializeTypes.scala:1428)
at scala.tools.nsc.transform.SpecializeTypes$$anon$2.transform(SpecializeTypes.scala:1371)
at scala.reflect.internal.Trees$class.itransform(Trees.scala:1347)
at scala.reflect.internal.SymbolTable.itransform(SymbolTable.scala:16)
at scala.reflect.internal.SymbolTable.itransform(SymbolTable.scala:16)
at scala.reflect.api.Trees$Transformer.transform(Trees.scala:2555)

I've truncated the error somewhat.
Any idea why this works and returns me the map I want in 2.10 but breaks in 2.11?
Thanks
Dean
P.S. I'm sure the style of this is not in the scala spirit and if there are better ways to do anything I show, feedback is great, but please answer the main question too.
Comment: Can you point the exact line where the error is? Also, can you add the assertion that fails?
Comment: This looks kind of familiar but I don't remember details. Can you provide a complete working example and specify your 2.11 version?
Comment: I added an edit to show where it failed. It fails when the filter tries to run. I don't know what you mean by 'the assertion that fails'. The error message follows the filter line immediately with no other information.
Comment: Travis, I'll cut something together and get a complete version up tomorrow. It's version 2.11.5 that is failing.
Answer: It's scala bug indeed - SI-9099

Fix Version/s: Scala 2.11.6


Cannot display jpeg from outside asset folder in swift 2

Question: This is probably a problem with my ignorance, but I am simply trying to show an image ... as per the code below.
I don't get any errors. The image exists, but does not appear in the simulator.
If I change the path string to a non-existing image I get an error, so I assume it is finding the image correctly.
What am I missing?
image of view controller
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var hotspotImage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let path = "/Users/Mel/Library/Developer/CoreSimulator/Devices/5760868E-BC01-4021-9500-1D4C09FE5106/data/Containers/Data/Application/2E99C508-30E5-4C83-BC72-CBF141A64769/Documents/tours/22/HI2.jpg"
        let image = UIImage(contentsOfFile: path)
        hotspotImage = UIImageView(image: image!)
    }

}

Comment: You are creating the UIImageView but you aren't adding it to the view hierarchy so it won't appear on screen. HotspotImage will already be a UIImageView, so you should assign image to its image property
Comment: This was happened to my app. In Objective-C we can retrieve the path and dynamically we can show the image
Answer: instead of hotspotImage = UIImageView(image: image!) try hotspotImage.image = image!.
Comment: That worked. (thanks very much). Can you tell me what was wrong with my version?
Answer:     let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let getImagePath = paths.stringByAppendingString("filename")
    testingImageView.image = UIImage(contentsOfFile: getImagePath)

Answer: You should call and give path for Document directory
let path = NSSearchPathForDirectoriesInDomains(
       .DocumentDirectory, .UserDomainMask, true)[0] as NSString
let fileName = NSUserDefaults.standardUserDefaults()
               .stringForKey("HI2.jpg") ?? defaultName
let imagePath = path.stringByAppendingPathComponent(fileName)!
let image = UIImage(contentsOfFile: imagePath )

// display the image
someImageView.image = image


Rails has_many :through with custom foreign_key

Question: I have the following set of models:
class Cardstock < ActiveRecord::Base
  has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
  has_many :palette_colors, :through => :color_matches
end

class ColorMatch < ActiveRecord::Base
  belongs_to :palette_color
  has_many :cardstocks, :foreign_key => :hex, :primary_key => :hex
end

class PaletteColor < ActiveRecord::Base
  has_many :color_matches
  has_many :cardstocks, :through => :color_matches
end

Calling Cardstock.last.palette_colors yields the following error:
ActiveRecord::StatementInvalid: PGError: ERROR:  operator does not exist: character varying = integer
LINE 1: ...".palette_color_id    WHERE (("color_matches".hex = 66))  OR...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "palette_colors".* FROM "palette_colors"  INNER JOIN "color_matches" ON "palette_colors".id = "color_matches".palette_color_id    WHERE (("color_matches".hex = 66))  ORDER BY name ASC

This shows me that the query ActiveRecord generates is using the cardstock's id (66) where it should be using the cardstock's hex (bbbbaf). Somewhere, I need to specify to ActiveRecord to use the hex column to join between cardstocks and color_matches. Does ActiveRecord support this?
Comment: This is Rails 2.3.x, by the way.
Answer: Your relationships are all out of whack here.

the relationships between Cardstock and ColorMatch should be a has_and_belongs_to_many relationship on both sides
anywhere you have a has_many relationship, you need a corresponding belongs_to relationship in the corresponding class
Comment: That's not quite true. There's absolutely nothing wrong with using `has_many :through` instead of `has_and_belongs_to_many`; I believe it's even the preferred way these days. However, you are correct that there's something wrong with the relationships.
Comment: Thank you, I need to change the `has_many` call in ColorMatches to a `belongs_to`. But I think there's more to the issue, because that bad query is still generated.
Answer: There's something wrong with the way your relationships are set up. I don't quite understand your specific use case here, so I'm not sure where the problem is. The way to think about this is probably as a many-to-many relationship. Figure out what the two sides of that many-to-many are, and what's the join model. I'm going to give an example assuming that ColorMatch is your join model -- it's what relates a PaletteColor to a Cardstock. In that case, you'll want your relationships to look something like this:
class Cardstock < ActiveRecord::Base
  has_many :color_matches, :primary_key => :hex, :foreign_key => :hex
  has_many :palette_colors, :through => :color_matches
end

class ColorMatch < ActiveRecord::Base
  belongs_to :palette_color
  belongs_to :cardstocks, :foreign_key => :hex, :primary_key => :hex
end

class PaletteColor < ActiveRecord::Base
  has_many :color_matches
  has_many :cardstocks, :through => :color_matches
end

In terms of your database, you should have a palette_color_id and a hex field on the color_matches table, and a hex field on the cardstocks table.
Comment: Exactly! However, after setting up my associations like that, I still get the same error. Does ActiveRecord support this? Or do I need to set up another table, just for the hexes, that `cardstocks` and `color_matches` would both point to with integer columns?


Errors while compiling Aseprite on Ubuntu

Question: I was trying to compile Aseprite on Ubuntu linux, when I got this error:
CMake Error at laf/CMakeLists.txt:86 (message):
  set SKIA_DIR/SKIA_LIBRARY/SKIA_LIBRARY_DIR to compile w/skia backend

-- Configuring incomplete, errors occurred!
See also "/home/cran/aseprite/build/CMakeFiles/CMakeOutput.log".
See also "/home/cran/aseprite/build/CMakeFiles/CMakeError.log".

What should I do to alleviate this error and install this application properly? Any help would be much appreciated.
Comment: Are you following [these instructions](https://github.com/aseprite/aseprite/blob/main/INSTALL.md#linux-dependencies)?
Comment: Also, did you download using `git clone --recursive https://github.com/aseprite/aseprite.git`
Comment: And what command did you use that returned this error?
Comment: Reminder: There is a paid version which gives you binaries and full support.
Comment: @mchild Yes, I am following those instructions. Here is the error I get now:
Answer: we have the same problem encountered
check first if you have skia extracted in deps folder
$HOME/deps/skia/

if that don't solve it i think you copy the wrong code like me
you need to copy the code below the Linux details
this
cd aseprite
mkdir build
cd build
export CC=clang
export CXX=clang++
cmake \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DCMAKE_CXX_FLAGS:STRING=-stdlib=libc++ \
  -DCMAKE_EXE_LINKER_FLAGS:STRING=-stdlib=libc++ \
  -DLAF_BACKEND=skia \
  -DSKIA_DIR=$HOME/deps/skia \
  -DSKIA_LIBRARY_DIR=$HOME/deps/skia/out/Release-x64 \
  -DSKIA_LIBRARY=$HOME/deps/skia/out/Release-x64/libskia.a \
  -G Ninja \
  ..
ninja aseprite

hope that solved it
Comment: It states that I do not have a directory for $HOME/deps/skia/, I will go fix that and see if aseprite works
Comment: I've created the directory, and entered in the commands you listed but it still did not work.
Comment: did you download the skia?
Comment: download the m102 and extract it in the deps. after that rename it skia
Comment: Here's the link [Skia](https://github.com/aseprite/skia/releases). Copy the on named Skia-Linux-Release-x64-libc++.zip


What does this Blight Tower UI mean?

Question: Specifically, what do the lightning bolt, fist, lightning bolt, and x2 mean?
Answer: The icons inside the circles are the type of enemies that will spawn from that gate. Enemies will take little to no damage from towers of matching symbols. So lightning bolt portals spawn lightning monsters and will take reduced damage from matching towers. The monsters can also have additional mods such as cannot be shocked, or in the case of the fist (physical), cannot be stunned or knocked back.
It may be hard to tell, but the X2 follows a little loot bag symbol and means you will get two chests from that portal upon successful defending it instead of the standard single one. The blighted symbol at the top of that same portal indicates a boss will spawn from there as well, which is why it is giving double rewards.

What does this Blight Tower UI mean?


Determine if a matrix is an orthogonal projection matrix

Question: We define an orthogonal projection as a linear transformation that maps a vector into its orthogonal projection in some (given ahead) subspace $W$. Let's call the matrix of that transformation (relative to the standard basis) the orthogonal projection matrix.
Now, suppose I have a matrix $Q$.

Is there a way to determine if $Q$ is an orthogonal projection matrix?

I mean, we can check if $Q^2=Q$ and check if $\text{Null}(Q) \perp \text{Col}(Q)$. Is that sufficient to conclude that $Q$ is a projection matrix?
Comment: You may want to see [this page](https://en.wikipedia.org/wiki/Projection_(linear_algebra)), in particular the second point [here](https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Projection_matrix). (So basically check that $Q^T = Q$ and $Q^2 = Q$, i.e. $Q$ is *symmetric and idempotent*.) You may also want to see the comments [here](https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Orthogonal_projections) regarding your question of the null space and column space of $Q$.
Comment: Thank you @MinusOne-Twelfth.
Answer: Yes, with $W:=\operatorname{Col}(Q)$ we have for every $v$,
$$ Q(Qv-v)=Q^2v-Qv=0,$$
hence $Qv-v\in\ker Q\subseteq W^\perp$, of course $Qv\in W$, and for $v\in W$ we have $Qv=v$.


List of strings into Bson Array

Question: I am using MongoDb 2.4.9 version. when i try to convert list of strings in to Bson Array i end up in below error:
BsonArray bArray = new BsonArray();
foreach (var term in termMonitorIds)
{
    bArray.Add(term.ToBson());
}

Server Error in '/' Application.
A String value cannot be written to the root level of a BSON document.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: A String value cannot be written to the root level of a BSON document.

EDIT
When i use that in the LINQ Query below:
entities =
                    (from e in this.collection.AsQueryable<SocialRecord>()
                     where sources.Contains(e.SocialType) && (e.DateCreated >= fr) && (e.DateCreated <= to) && e.TermMonitorIds.Any(X=> bArray.Contains(X)) && e.IsExactMatch == isInstagramExactMatch
                     select e)
                    .Take(5000)
                    .ToList();

results in Value cannot be null. Parameter name: name . This error message only happens when i added bArray to the Query.
Answer: You don't need to invoke ToBson. There's already an implicit conversion from string to BsonValue. Using ToBson actually generates bson, which probably isn't your goal:
BsonArray bArray = new BsonArray();
foreach (var term in termMonitorIds)
{
    bArray.Add(term));
}

Comment: You could make this a little more succinct by using: bArray.AddRange(termMonitorIds)
Comment: I've settled on: BsonArray bArray = new BsonArray(termMonitorIds);
Comment: If you have a different question you should really make a new post.

List of strings into Bson Array


Generating Pythagorean triples $(a,b,c)$ such that $b>a+n$ for integer $n$, and $a+b$ is minimum

Question:
I'm trying to generate a Pythagorean triple, that is, $a,b,c \in \mathbb N$ that
$$a^2 + b^2 = c^2$$
under the condition that $b > a + n$, $n \in \mathbb N$ and $a+b$ is minimum.

I tried expanding the forumula or trying to use the Euclid's formula but I don't know how to add the constraint.
Comment: Must the triple be primitive ?
Comment: @Peter No, it's not needed
Answer: The difference between legs of a  [primitive] Pythagorean triple is always
$\quad P=p_1^a p_2^b p_3^c \cdots\quad$
the product "P" of one-or-more [non-negative] "powers" of primes "p" where
$\quad P\equiv p_n^x\equiv\pm1\pmod8.\quad $
Under
$200,$ $$\space  P\in \bigg\{1,\space 7,\space  17,\space  23,\space  31,\space  41,\space  47,\space  \big(7^2\big),\space  71,\space  73,\space  79,\space  89,\space  97,\space  \big(7\times 17\big),\\
  127,
 137,\space 151,\space \big (7\times23\big),
\space  167,\space  191,\space 199
\bigg\}$$
The statement of this question
$\mid B-A\mid >n$ would be better phrased as
$\mid B-A\mid \le P\space$ as we will see below.
For $P=1$. there are three formulas, two of which generates the "pell" number pairs
$\big(2,5,12,29,70,\cdots\big)$
needed to feed Euclid's formula here shown as
$\quad A=m^2-k^2,\quad B=2mk,\quad C=m^2+k^2.\quad$  For example
$$F(2,1)=(3,4,5)\quad
F(5,2)=(21,20,29)\quad
F(12,5)=(119,120,169)$$
For $P>1,\quad$ one formula may be generalized to $\quad m=k+\sqrt{2k^2\pm P}\quad
1\le k \le\big\lfloor \sqrt{P}\space\big\rfloor
\quad$
which generates  at least $2^x$ series  of pell-like numbers where $x$ is the sum of powers of $p_n.\quad$ Any $k$-value in range which yields an integer is the first-k
$\space (k_1)\space$
of such a series. For $P=7,\space$ this means there are $2^1$= $2$ series:
$\space P=7\implies  k_1\in\{1.2\}.$
\begin{align*}
1+\sqrt{2+7}=4\quad  &  F(4,1)=(15,8,17)\\
 4+\sqrt{32-7}=9\quad  &   F(9,4)=(65,72,97)\\
9 +\sqrt{162+7}=22\quad  &  F(22,9)=(403,396,565)\\
 22 +\sqrt{968-7}=53\quad  &  F(53,22)=(2325,2332,3293)\\
 \vdots\\
\text{ and }\\ \\
 2+\sqrt{8-7}=3\quad  &F(3,2)=(5,12,13)\\
   3 +\sqrt{18+7}=8\quad &F(8,3)=(55,48,73)\\
 8 +\sqrt{128-7}=19\quad &F(19,8)=(297,304,425)\\
    19 +\sqrt{722+7}=46\quad &F(46,19)=(1755,1748,2477)\\ \vdots
 \end{align*}
In this case, we have generated triples for $n>6.\quad$ For $n>7$, we would have to use the formula
$m=k+\sqrt{2k^2\pm 17},\space
1\le k \le\big\lfloor \sqrt{17}\space\big\rfloor
=4\quad$  to get $\space k_1\in\{2,3\}$
$$F(7,2)=(45,28,53)\quad
F(16,7)=(207,224,305)\quad
F(39,16)=(1265,1248,1777))\quad\cdots\quad\\
F(4,3)=(7,24,25)\quad
F(11,4)=(105,88,137)\quad
F(26,11)=(555,572,797)\quad\cdots $$
For $P=49=7^2,\space k_1\in\{4,5,6,7\};\quad$
for $P=119=7\times17,\space
k_1\in\{1,5,8,10\},\space$  etc.
Do note that, for half of all triples, $A>B. \quad$ This simply means
$\mid\space B-A\mid\space\equiv
\space\pm1\pmod8.\quad$
The generalized formula works for any $P>n.$
The smallest first triple in any of the
one-or-more series of triples generated contains the minimum for the criteria. For example, for $\quad n>6\longrightarrow (15,8,17),\space (5,12,13),\quad$
the minimum $A+B\space$ is $\space 5+12=17$.
A brief list of these minimum $B+A$ values for $n\le P$ is
\begin{equation}n(A,B,C)\longrightarrow B+A\\
1(3,4,5)\longrightarrow 7\\
7(5,12,13)\longrightarrow 17\\
17(7,24,25)\longrightarrow 31\\
23(35,12,37)\longrightarrow 47\\
31(9,40,41)\longrightarrow 49\\
41(77,36,85)\longrightarrow 113\\
47(63,16,65)\longrightarrow 79\\
49(11,60,61)\longrightarrow 71\\
\end{equation}


Synchronous function inside Task or outside - any difference?

Question: Will there be any difference in running a function that is not marked as async and running it inside a Task?
.onChange(of: callState.current) { state in
    viewModel.changeNavigation(title: state.controllerTitle) // 1 - outside
    Task {
        viewModel.changeNavigation(title: state.controllerTitle) // 2 - inside
        Task.detached(priority: .background) {
            await viewModel.audit(state: state)
        }
    }
}

onChange is called from MainActor (SwiftUI View).
Both options are executed on the main thread.
Is there any difference in the performance exerted on the main thread and UI?
Comment: The first variant should perform slightly better since it doesn't involve the extra step of creating a Task.
Answer: The difference is how the function runs relative to code around it.  With the viewModel.changeNavigation code outside of the task, it will certainly run before any of the code that follows it.
With it inside the task you know that it will run at some point in the future, but you don't have any idea what other code might run before it.
If something else has been sent to the main queue it might execute first.  If there are other tasks in the same execution context they could run before that call too.
The performance impact of creating the task and having it work through the scheduler is non-zero, but at user interface speeds probably won't be noticeable.
But you've definitely changed the timing of when the code will run and that may cause race conditions and the like if you're not careful.


LocalService and LocalBinder leak memory in Android 10

Question: I have a LocalService implementation exactly as suggested here in order to provide access to service methods through the binder.
https://developer.android.com/guide/components/bound-services#Binder
public class LocalService extends Service {
    // Binder given to clients
    private final IBinder binder = new LocalBinder();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
}

Starting Android 10 this implementation seems to leak memory. When the service is unbound (and destroyed) the LocalService and LocalBinder objects are not garbage collected. The next bind creates a new service object. According to the memory profiler the LocalBinder object is referent in Cleaner. Any idea how to fix?
Answer: A bit late but here it is. Binders are not tied to the lifecycle of components (e.g. services). The instance of a Binder is kept around internally in case some other process/thread calls the Binder's transact method.
In your code, LocalBinder is an inner class. Therefore, implicitly LocalBinder has a reference to LocalService. So even though the LocalService may have been destroyed, its reference is still contained inside of the LocalBinder, thereby leaking the LocalService.
The solution is to make LocalBinder a static class (or an entirely separate class) and use a WeakReference for your LocalService.
I am aware that your code comes straight from the Android Documentation, but it is still wrong. In fact, if you want to go looking, there is an old bug report where the Android team acknowledges this and then marks the bug as "Obsolete (Won't Fix)" because the team has decided to go in a different direction -- I have no clue what that means only that they won't be changing it in the near future. Link to the Android Issuetracker.


How can I prevent water from getting behind the gutter?

Question: A friend of mine is having a water problem; the water is coming down behind the gutter.  It turns out the drip edge isn't covering up the gutter completely on the one side for a considerable length of the house, as the gutter slants downward.  Is there a way to fix this?  Is there a flashing you can use, or something else?
Note that this started happening after a recent replacement of a roof.  I've included some pictures of what this looks like.
Comment: First rule of roofing, you slope down to the edge of the roof. When you have standing water on your shingles, they screwed up. Some roofer owes you a refund, and you should hire someone more competent to fix it.
Comment: Look at those pics and you can see water collecting on the white edge just below the shingles.  This is because the slow moving water is simply seeping down around the shingle and catching the edge below it.  The whole point of a drip edge it that it extends out over the gutter's opening, at a point lower than the surface beneath, so water collects on that edge and drips down into the gutter.  Your "drip edge" isn't dripping, it's running off...
Answer: Is the water running down the roof not going into the gutter, and instead flowing behind the gutter? If so, then there is a problem with the gutter and/or flashing installation. In addition to the drip flashing, you should check that the gutters are properly affixed. They should be sloped toward the downspouts, but are they securely attached to the fascia board? The fascia board could be rotted, and the gutter hangers unable to hold the gutters firmly against the building. (This is the sort of problem that rapidly gets worse, as the more the fascia board is exposed to water, the more it rots, letting the gutter hangers fail.)
Alternatively, if the gutters are overflowing and draining toward the house instead of down the downspouts, then you probably just need to clean the gutters so they can drain properly.
Comment: I should have also noted this was after a recent roof replacement too.  Thanks
Comment: OK. In that case, they might have simply installed the first course of shingles too high up, and a repair like what Greebo suggested would address this.
Comment: updated with some pictures.
Answer: Carefully raise the lowest shingles on the roof line.  Slip an additional shingle in under those shingles - install them oriented so the normally top edge of the shingle is the bottom edge (but make sure they stay face up).
Nail in place as high up as you can close to the layer of shingles above, leaving a 1" over hang over the gutter to create a new drip edge.  Install using proper roofing nails.
Run a 3/8" bead of roofing caulk (black tar like substance) along the top edge of that new layer of shingles, then lay the old layer of shingles back down on top of the new drip edge.
Comment: Exactly - the idea is to put the new row of shingles *under* the existing row, with a proper overhang.  The old shingles lay on the new shingles, water runs from the old onto the new, and then into the gutter.
Comment: "then lay the old layer of shingles back down on top of the new **drip edge**" - you mean the new shingles row?  Do you mean this new row acts like a drip edge?
Comment: I updated with some pictures.
Comment: Yeah, the first row is way too high up.  You don't even HAVE a drip edge in places.
Answer: Same thing happened to me.  1yr old roof.  In the off season (late fall) I had window caulked a 1" cut strip of vinyl gutter material with a curved edge in where the shingles were turning up and the drip edge was lacking.
Once spring came I replaced the bottom course (very time consuming) and used proper asphalt caulk/nails to tack it down.  Now looking for a good soffit contractor since mine are now dry-rotten...
Best advice I can give is to put on a rain coat and go out in the rain or have a buddy lightly hose roof edge.  You have to see where the water is going to see just how far the water goes.  I also used my garage stethoscope since the drips can be heard inside when they hit the soffit.


Django Model is not printing the Model Details

Question: I am new to Django/python and I am helping the team in migrating Django project as the installed server needs to be migrated.
Old Version
Django - 1.6.5
Python - 2.7
Due to some compatibility and versions not available, below the versions which we migrated to and was able to bring up the application without any errors. There were some compilation error related to deprecated methods and was able to correct that.
Migrated Version
Django - Django-1.6.5
Python – 3.4
Database – sqllite
Pillow - Pillow-3.3.0
PIP - pip-1.5.4
Everything looks fine, except the admin module. In the main admin screen instead of displaying the module fields, it is just displaying the object name.
Below the location model list it used to display before migration
Location
Room: A | Cabinet: 23 | Drawer: 7
Room: A | Cabinet: 24 | Drawer: 4
After Migration, it just displays the location object name
Location
Location object
Location object
I looked at the model.py and below the location model defined
**class Location(models.Model):
room = models.CharField(max_length=31,
                        help_text='(Required) e.g. A, B, C, D, E, F')

station = models.IntegerField(max_length=5,
                        blank=True,
                        null=True,
                        help_text='e.g. 1, 2, ...')

cabinet = models.IntegerField(blank=True,
                              null=True,
                              help_text='e.g. 1, 2, ...')

shelf = models.IntegerField(blank=True,
                            null=True,
                            help_text='e.g. 1, 2, ...')

drawer = models.IntegerField(blank=True,
                             null=True,
                             help_text='e.g. 1, 2, ...')

map = models.ImageField(upload_to='location_maps',
                        blank=True,
                        null=True)

class Meta:
    unique_together = (('room', 'station', 'cabinet' ,'shelf', 'drawer'),)

def __unicode__(self):
    string = 'Room: {}'.format(self.room)
    if self.station:
        string += ' | Station: {}'.format(self.station)
    if self.cabinet:
        string += ' | Cabinet: {}'.format(self.cabinet)
    if self.shelf:
        string += ' | Shelf: {}'.format(self.shelf)
    if self.drawer:
        string += ' | Drawer: {}'.format(self.drawer)
    return string*

Below the configuration for admin.py

*from django.contrib import admin
from mgmt.models import *
admin.site.register(Location)*

Any help would be really appreciated as I am not seeing any code change in the admin.py to make any correction
Below the Table
*CREATE TABLE "mgmt_location" (
"id" integer NOT NULL PRIMARY KEY,

"room" varchar(31) NOT NULL,

"station" integer,

"cabinet" integer,

"shelf" integer,

"drawer" integer,

"map" varchar(100),

UNIQUE ("room", "station", "cabinet", "shelf", "drawer")

)*
Comment: Update: When I tried with below code in the model.py, it is displaying the names.    def __str__(self):
         return self.id. But then it started giving below error when we tried to edit the items or click on to display the edit admin screen           TypeError at /admin/mgmt/equipment/S040942/
__str__ returned non-string (type Item)
Answer: try replacing def __unicode__(): with def __str__(): as
in Python 2, def __unicode__(): had been used to determine the human-readable representation of an object.But in Python 3, it's has been replaced with def __str__():
Comment: sorry, forget to say. Please also change the last line  return string*  to this  return self.string  as it's a class variable. if it's still give the same error try typecasting this string like  return str(self.string)
Comment: Thanks Again Muhammad. In each model, there are different data types, files, lists, date etc. So in the return, should i convert each fields? Current code is returning only the id. So when I use as below it still gives error ->     def __str__(self):

        return str(self.id)
Comment: or do I need to do any modifications in admin.py. My admin.py just looks as admin.site.register(InventoryUser)
admin.site.register(Tooling)
admin.site.register(Location)
admin.site.register(Equipment)
admin.site.register(DvtSample)
Comment: hi Dais, i have tried with `return str(self.id)` and it's working fine.
First of all `__str__()` must always return a String and you shouldn't return a List or Dict in `__str__()`. As Admin expecting a single String attribute. So, instead of returning a List you can return concatenate String and it'll be working fine.
Comment: Thanks Muhammad, it started working. Really appreciate your help
Answer: Thanks Muhammad, I have tried that, then the templates started giving error.
For example I am getting different errors in different templates like below. I have different models and all different models started giving one or the other error related to non-string(type Item), in the edit screen
Error 1 - When I click on the history
*str returned non-string (type Item)
Request Method:
GET
Request URL:
http://10.20.130.91:8000/admin/mgmt/equipment/S040942/history/
Django Version:
1.6.5
Exception Type:
TypeError
Exception Value:
str returned non-string (type Item)
Exception Location:
C:\Python34\lib\site-packages\django\utils\encoding.py in force_text, line 106*
Error 2, when I click on edit
*TypeError at /admin/mgmt/tooling/PRO102937/
str returned non-string (type Item)
Request Method:
GET
Request URL:
http://10.20.130.91:8000/admin/mgmt/tooling/PRO102937/
Django Version:
1.6.5
Exception Type:
TypeError
Exception Value:
str returned non-string (type Item)
Exception Location:
C:\Python34\lib\site-packages\django\utils\encoding.py in force_text, line 106*


Store fetch data in variable to access it later

Question: I'm facing a probably super easy to solve problem regarding fetching.
I'd like to fetch some json datas and store it in a variable to access it later.
The problem is that I always ends up getting undefined in my variable. What's the way to do to deal with that kind of data storing ?
Here's my code.
const fetchCities = () => {
      fetch('cities.json')
      .then(response => response.json())
      .then(data => {
        return data;
        });
      }
    let cities = fetchCities();
    console.log(cities)

Already looked up for answers but couldn't find a way to do. Thanks !
Comment: You need to return the `fetch` function and also handle the promise with something like `Async/await`. [**Example Code**](https://stackblitz.com/edit/node-xntpkp?file=index.js)
Answer: Sending a fetch request takes time, so the console.log works before the data arrives.
The best way to deal with fetch is using async functions and await like so:
const fetchCities = ()=>{
    return fetch('cities.json');
}

async function main(){
    try {
        const res = await fetchCities();
        const data = await res.json();
        // handle the data here, this will work only after the data arrival
        console.log(data);
    } catch (err) {
        console.log(err);
    }
}
main();

Note: await can only be used in async functions, that's the main purpose of the main function.
Or if you want to use .then:
const fetchCities = ()=>{
    return fetch('cities.json');
}
function main(){
    fetchCities()
    .then(res => res.json())
    .then(data => {
        // handle the data here, all you code should be here
    })
    .catch (err => console.log(err));
}
main();

Comment: Thanks I finally used this solution and put all my code in there. Thanks for your time !
Answer: You could do this very simply with async/await like this:
const fetchCities = async () => {
  let cities = await fetch('cities.json');
  return cities.json();
};

let cities = await fetchCities();
console.log(cities);

Comment: await can only be used in async functions
Comment: As of ES2020, [Top-level await can be used in javascript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await).


What are the differences between segues: "show", "show detail", "present modally", "present as popover"?

Question: What do the different segues do in Xcode 6?
Comment: Check out http://stackoverflow.com/questions/25966215/whats-the-difference-between-all-the-selection-segues
Comment: duplicate? http://stackoverflow.com/questions/25966215/whats-the-difference-between-all-the-selection-segues
Comment: Possible duplicate of [What's the difference between all the Selection Segues?](http://stackoverflow.com/questions/25966215/whats-the-difference-between-all-the-selection-segues)
Answer:
1. Show - Pushes the destination view controller onto the navigation stack, moving the source view controller out of the way (destination slides overtop from right to left), providing a back button to navigate back to the source - on all devices.
Example: Navigating inboxes/folders in Mail.
2. Show Detail - Replaces the detail/secondary view controller when in a UISplitViewController with no ability to navigate back to the previous view controller.
Example: In Mail on iPad in landscape, tapping an email in the sidebar replaces the view controller on the right to show the new email.
3. Present Modally - Presents a view controller in various different ways as defined by the Presentation option, covering up the previous view controller - most commonly used to present a view controller that animates up from the bottom and covers the entire screen on iPhone, but on iPad it's common to present it in a centered box format overtop that darkens the underlying view controller.
Example: Tapping the + button in Calendar on iPhone.
4. Popover Presentation - When run on iPad, the destination appears in a small popover, and tapping anywhere outside of this popover will dismiss it. On iPhone, popovers are supported as well but by default if it performs a Popover Presentation segue, it will present the destination view controller modally over the full screen.
Example: Tapping the + button in Calendar on iPad (or iPhone, realizing it is converted to a full screen presentation as opposed to an actual popover).
5. Custom - You may implement your own custom segue and have complete control over its appearance and transition.
Comment: **Show** detail: _The default implementation of this method calls the targetViewController(forAction:sender:) method to locate an object in the view controller hierarchy that overrides this method. It then calls the method on that target object, **which displays the view controller in an appropriate way**. If the targetViewController(forAction:sender:) method returns nil, this method uses the window's root view controller to **present vc modally**._
Comment: Show: What if there is no navigation stack?


ajax function not working fine

Question: I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
    //alert("this comes in this");
    var data1 = $("#country_id").val();
    $.ajax({
        alert("ajax start");
            url: 'ajax_submit.php',
            type: 'Post',
            dataType: 'json',
            data:{getRespondents:"getRespondents", data:data1},
            success: function(e){
                    alert(e);
                    $("#rCategory").val(e.respondents[0]['category']);
                    $("#gender").val(e.respondents[0]['gender']);
                    $("#rAddress").val(e.respondents[0]['address']);
                    $("#rContact").val(e.respondents[0]['contact']);
                    alert("In this");
            }
      });
});

and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
      $regionID= $_POST["data"];
      $obj = new controller();
      $result = $obj->getRespondents($regionID);
      $json = array("respondents"=>$result);
      echo json_encode($json);
      exit();
 }

In class function is written as:
function getRespondents($a){
    $connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
    $db = mysql_select_db("demon", $connection); // Selecting Database

    list($number1, $number2, $number3) = explode('/', $a);
    //$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
    $sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
    $rsd = mysql_query($sql);
    $row= array();
    $i=0;
    while($rs = mysql_fetch_array($rsd)) {
        $row[$i]["id"]      = $rs ['id'];
        $row[$i]["name"]    = $rs ['name'];
        $row[$i]["contact"] = $rs ['contact'];
        $row[$i]["address"] = $rs ['address'];
        $row[$i]["category"] = $rs ['category'];
        $row[$i]["gender"] = $rs ['gender'];
        $i++;
    }
    return $row;
}

I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
Comment: Welcome to StackOverflow! Have you watched the request / response in the browser's console? Any errors?
Comment: The possible solution for your unnamed problem is to debug process step-by-step. Checking/debugging `data1`, Ajax result, PHP code.
Comment: i think the problem is here data:{getRespondents:"getRespondents", data:data1}, here you change the variable name data to some other name
Comment: e.respondents[i]['category'] here i is undefined
Comment: What do you mean by 'returns nothing'? Does it go to success function in the ajax setup?
Comment: @JayBlanchard when i first load the page it says "Uncaught SyntaxError: Unexpected token ("
Comment: You have to fix that error, then your code may work.
Comment: @satishrajak i changed them like a many times but all fail,
Comment: Additionally you have two `$sql` variables. `$rsd = mysql_query($sql);` will only execute the second one.
Comment: @JqueryKing i made it 0 index now. but still nothing is on page.
Comment: @JayBlanchard okay let me try
Comment: [Quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead.
Comment: i want print console.log(e) then told the result
Answer: First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.

ajax function not working fine


Can't use command make for makefile on Visual Studio Code

Question: Backround
I have been coding (mostly C) on Linux so far but i want to be able to code on Windows as well. So i searched for a better editor than notepad and found Visual Studio Code that has extensions to make your life easier.

Problem
I wanted to use a makefile with the command make for more complex compilations of my .c files, but it doesn't seem to recognize the command make no matter what extensions i tried for Visual Studio Code nor from the embeded terminal.

Extensions Tried

Make
makefree
VS Code C/C++ Makefile Project
Makefile Command Runner
Comment: In Linux, make comes with the system.  In Windows, it does not.  Extensions to VSCode may provide you _interfaces_ to run the make program, but they will not contain the make program itself.  You'll have to install that separately.
Comment: @MadScientist ohh okey, thanks!
(i even ran into some sources that said to install make into the system but i wasn't sure if that was my case)
Answer: Firstly, I would ensure that make is installed on your system.
Secondly, if make is installed, make sure you are operating from the correct directory. If you open a terminal using Terminal > New Terminal and type in make, does it work. If so then you may just need to create a simple task that runs on an F5 press or whatever OR just type make in to build every time.
If make doesn't work, make sure you are using the directory containing the makefile as your WD or otherwise cd or set your settings in those extensions to use a subdir as the root.
Answer: In Windows, the compiler that comes with Visual Studio is MSVC. You are most probably using cl.exe to compile your files. Visual Studio projects has .vcxproj extension.
GCC, on the other hand, is the most used compiler in Linux environments. Its project file is a Makefile, which is compiled by make command.
There are a couple of options in Windows.

You can opt-in to use Windows default development environment Visual Studio. Its debugging capabilities are very good. You may not like this option if you are a terminal guy.
You can use MinGW to port GCC to Windows. Makefile will work in this option. Keep in mind that this is not a native solution.
You can use the cross platform solution CMake. After writing a CMakeLists.txt, it will create the project file depending on your compiler (Makefile for GCC, or .sln and .vcxproj files for MSVC).
You can use both terminal to compile your files and open the solution file to debug your applications in Visual Studio.

VSCode is not an IDE, it is a fancy text editor with extensions. Once you have decided what development environment to use, you can find related extensions to make your life easier.
Answer: I ran into the same problem and discovered that I was using a wrong path in my environment.
The right reference for me was: Edit the PATH variable (in the environment Variables interface of the PC) to add that path of the folder containing the make.exe binary.
Answer: I had the same problem and i fixed it by adding " C:\msys64\usr\bin " to " PATH ".
" C:\msys64\usr\bin " contain the " make " file


kineticJS createImageHitRegion for sprites, not images

Question: I am using KineticJS and wish to create a precise image hit region (ignore transparent pixels) for my sprites. I see how createImageHitRegion accomplishes this for images, but I don't see how to apply this to sprites. Said another way, while method createImageHitRegion is a method which accomplishes what I want for images, there appears no similar method for sprites. If I could create an image hit region on just one image of each of my sprite that could work for me, but a big rectangular region which encompasses the entire width and height of the image of the sprite can't work. Any ideas for a workaround? Perhaps I've missed something?
Answer: There's no easy way hit-test non-transparent pixels on sprites.
I can think of a couple of theoretical workarounds...
If you can draw a path outlining the pixels you want to hit.
The sprite object allows a custom drawHitFunc so you could use mySprite.afterFrame to redefine a custom hit area for each of your sprite images.
mySprite.afterFrame(0, function() {
    mySprite.setDrawHitFunc(function(){
        // draw the path you want used for frame#0
    });
});

// repeat for all frames

If you can't draw a path outlining the pixels you want to hit.
Instead of using sprites, make your own sprites using individual images.
Do that by creating a series of images (including createImageHitRegion) and sequentially making one of those images visible so it appears to be playing a spritesheet.
Comment: I hadn't noticed the drawHitFunc before. This seems perfect as it's easy in Inkscape to create paths outlining the pixels. Thanks!


How to host a wordpress project htdocs to hostinger.com server

Question: Hi Iam create new website in wordpress (event management)in my system (test run in localhost).and im trying to host my website in hostinger.com. iam create my domain ,username,password.and cpanel databse name,username,password..
then iam connect filezila and transfer my localhost wordpress files all to my new host domain folder. and also pass my database.
then run (host address is ipsr.esy.es) the first homepage is loaded ,but iam click the about link its go to(localhost/wordpress/about)object not found. wordpress is my local foldername(xampp/htdocs/wordpress)
how to solve this problem??
what is the changes of htaccess.exe page
Comment: # BEGIN WordPress

RewriteEngine On
RewriteBase /ipsr.esy.es//
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /ipsr.esy.es//index.php [L]

# END WordPress
Comment: how to see customize page in host site
Answer: Go to Phpmyadmin>Wp-options> Edit-->> Site Address from localhost/wordpress to your domain name
Comment: no sir its not possible. because my domain id is http://www.ipsr.esy.es/ its load prefectly. but other links are (like about,services,contact, and other connected links) not work. they have url address started like ( http://localhost/wordpress/about/) how to change url address. like http://www.ipsr.esy.es/about/.
Comment: first im create m project in localhost. now im  files transfer host domain.


Batch program writing output of 'dir' in text file

Question: I am learning about batch programming and I have got problem.
I want make a program which places the output of the dir command to file.txt.
What am I doing wrong?
ECHO OFF DIR > file.txt

Answer: Right now, you are writing "OFF DIR" into to textfile:
ECHO OFF DIR > FILE.TXT

You need to place these commands on two separate lines:
@ECHO OFF
DIR > FILE.TXT

The @ sign before ECHO OFF will hide that command from showing.
Answer: I suppose "the problem" is in ECHO OFF
try this
DIR > file.txt


Is Collatz' conjecture the only stable solution of its type?

Question: The Collatz Conjecture is well known with the sequence
$$f(n) = \begin{cases} n/2 &;\text{if } n \equiv 0 \pmod{2}\\ k\,n+1 &; \text{if } n\equiv 1 \pmod{2} \end{cases}$$
and $k=3$; the sequence converging $1$ (so called oneness).
Is there any conjecture/theorem on whether the sequence would converge for any other value of $k$; or could it be shown that the sequence diverges for values of $k$ other than $3$?
By convergence here I mean that the sequence after finite steps ends with a stable fixed number such as in case of Collatz it is the case with the number $1$.
Append: In the mean time I wrote out a conjecture on this over here >>>, for those who might be interested.
Comment: At least, we have two obvious properties: for even $k$ the sequence can diverge, for $k=1$ the sequence always converges. I think it's possible to show that for $k\ge 5$ the sequence can diverge.
Comment: I don't know if there are explicit examples of divergence for larger (odd) $k$, but there are heuristic arguments in favor of divergence; see http://terrytao.wordpress.com/2011/08/25/the-collatz-conjecture-littlewood-offord-theory-and-powers-of-2-and-3/ for more details.
Comment: @al-Hwarizmi Just so - if you read the argument before that point, though, you'll see why for the $3n+1$ problem the expectation is that the average size of an iterant 'should' decrease over time, while for the $5n+1$ (and larger) problems the average size 'should' increase.
Comment: You may be interested in [this arXiv paper](https://arxiv.org/abs/1807.00908).
Comment: Nothing here about *divergence*. But on *cycles* ("oneness","stability"): all $k \in \{3,7,15,31,...,2^j-1,..\}$ have the trivial cycle at $1$. All $k \in \{3,5,9,17,...,2^j+1,..\}$ have the trivial cycle at $-1$.
Answer: Here are some pictures for your/our intuition. I graphed the trajectories for initial values $x=5,15,25,...$ for the first $256$ steps of $x_{k+1}=(5x_k+1)/2^A$.
To get the curves to a meaningfully visual interval I show logarithmic scales. The pictures show how most trajectories begin to diverge (not really a safe indication of what characteristic the infinite curves really have) but some show cycling already at early iteration indexes $k$ .
I find $2$ cycles besides the "trivial" one.

$x=5,15,25,35,...,95$ detail of the first few iterations . At the bottom we see the "trivial" cyle (brown curve):

$x=5,15,25,35,...,95$ first $2^8 = 256$ iterations. At later iteration-indexes $k$ a first "non-trivial" cycle occurs (red line):

$x=105,115,125,135,...,195$ first $2^8 = 256$ iterations .

$x=205,215,225,235,...,295$ first $2^8 = 256$ iterations . Here a second "non-trivial" cycle becomes visible:

$x=205,215,225,235,...,295$ first $2^{11} = 2048$ iterations
It seems really that all trajectories which are divergent up to iteration $k=256$ are also divergent up to iteration $k=2048$ . In general: I doubt that there are "later" cycles:

Answer: It can be shown that for $k=5$ the sequence can "converge" to other numbers rather than $1$:
$$13\to 66\to 33\to 166 \to 83 \to 416\to 208\to 104\to 52\to 26\to 13.$$
Comment: see also here: http://mathoverflow.net/questions/139073/beyond-collatz-a-5n1-conjecture
Answer: I find the following formalism helpful for my own understanding of the problem, so I think I'll add this here too.
To have this transformation generalized let's write:
$$ T_M(x) = (M \cdot x+1) / 2^A \qquad \small \text  { where A equals the exponent at 2 in the numerator }$$
and we look only at the odd numbers (because all even numbers can be seen as "trivially" dealt with.
For easier notation I like also to write it in this form
$$ a_{k+1}= {M \cdot a_k +1 \over 2^{A_k}}$$
or, for linear writing, using consecutive letters instead of numerical indexes
$$ b = {M\cdot a +1 \over 2^A}, c={M\cdot b +1 \over 2^B }, \text{ and so on} $$
Then to have a one-step-cycle we must have the result equalling the input
$$ b = {M\cdot a +1 \over 2^A} =a$$
and obviously we must have
$$ 2^A =M + \frac 1a $$
To have such a one-step-cycle on the number $a$ we must have that $M$ is a mersenne number $M=2^A-1$ and because of its simpliness it usually denotes the "trivial cycle".
$M=3,7,15,31,...$ are such mersenne numbers and they allow "trivial cycles".
If we allow negative integers, then for $a =-1$, we have a similar pattern, only that the allowed $M$ ar $M=3,5,9,17,...$. For $ |a| \ne 1$ the expression $ \frac 1a$ would introduce fractional values and thus other one-step-cycles are not possible.
To look at two-step-cycles it suffices to look at the generalization
$$ b\cdot c = {M\cdot a +1 \over 2^A}\cdot {M\cdot b +1 \over 2^B} = b \cdot a$$
It is too complicated for the place here to discuss this in generality. But to show one helpful pattern I'll show this for $M=3$ and $M=5$
For $M=3$ we get
$$ bc =  {3a+1 \over 2^A}\cdot {3b+1 \over 2^B} = ba $$
Rearranging gives
$$ 2^{A+B} = (3+ {1 \over a})\cdot (3+{1 \over b})  $$
We see immediately, that the rhs can only fall in the interval $9 .. 16$ (where $16$ can only occur if $a=1$ and thus for the trivial case). But there is no other exact power of 2 in this interval, so the lhs-part cannot be satisfied.
If we allow negative integers we get instead
$$ 2^{A+B} = (3- {1 \over a})\cdot (3-{1 \over b})  $$
which covers now the interval $4..9$. It gives for $4$ the trivial cycle in the negatives, and for $a=5,b=7$ another solution compatible with the lhs which means thus a two-step cycle (and we must not forget that the sign must reverted to the negatives).
For $M=5$ this looks like
$$ 2^{A+B} = (5+ {1 \over a})\cdot (5+{1 \over b} ) $$
The range for the rhs is now $25..36$ and there is only one number (=32) compatible with the lhs.
The smallest numbers for a $M=5$ cycle are $1$ and $3$ . We try these numbers
$$ 2^{A+B} = (5+ {1 \over 1})\cdot (5+{1 \over 3} )=6\cdot {16 \over 3} =32 $$
Bingo!
So we just found the smallest cycle-length for the $M=5$-problem.
Now again in the negative integers integ
$$ 2^{A+B} = (5- {1 \over a})\cdot (5-{1 \over b} ) $$
The range for the rhs is 16..25 where 16 indicates the trivial cycle in the negatives. There is not other perfect power of 2 in that interval, so no 2-step-cycle in the negatives for the $M=5$ problem.

This expositions for the one- and for the two-step cycles can generalized for multistep-cycles in the obvious way. However, with more steps the view at it through the modular glasses does not lead very far. But there is another tool (which leads to another numbertheoretic tool with which finally R.Steiner proved the non-existence of the "1-cycle" (arbitrary many steps with exponents $A=1$, and only one exponent $B \gt 1$)): we arrange the $M$'s out of the rhs getting
$$ {2^S\over M^N} = (1+{1 \over M\cdot a})\cdot (1+{1 \over M\cdot b}) \cdots $$
where I denote the sum-of-exponents (=number of divisions by 2) as $S$ and the number of steps (=number of multiplications by 3 = number of parentheses on the rhs) as $N$
Now with high $a,b,c,...$ on the rhs and high $M$ this is very near to 1, in many cases much nearer than the quotient on the lhs, and one can look at the approximation of $2^S / M^N$ for many $N$ and discover a trend which suggest a required minimal cycle length for a set of integers all larger than its minimal element $a$
Answer: Perhaps you have noticed it works for other $m$ and $q$ in the form:
$$
 f(n) = \begin{cases}
   n/m & \text{if } n \equiv 0 \mod m \\
   (m+1)n + m-1       & \text{if } n \equiv 1 \mod m \\ \cdots \\
   (m+1)n + m-q  & \text{if } n \equiv q \mod m
  \end{cases}
$$
for all integers $q$ and $m$, where $ 0 < q < m$.
-TJL
Comment: Hey just came across this and was wondering if you had a source? I'm guessing there's no proof since it would be in some sense "generalized Collatz" but would be very interested :)
Comment: I did not have a source, but instead just programmed different sequences to see the convergence, and it so happened to work out. However I should contribute any help to Bart Goddard, a professor of mine.
Answer: I think the replies provided are fantastic yet I can reply in more of a layman's observations than a graph.  In fact I am wishing to learn how to present data in graphs.
I have observed the cycle in many dynamic systems.  We can expand the Collatz by a generic form (my notation so pardon this) [A(X)+Y,X/2] Where in Collatz A = 3 and Y = 1 and the [] are used here to denote iteration. Again my notation so if that is bad form please let me know.
It turns out that there is a "Cycle" of the odd Y for all Odd Y. So 3(x)+3 has a cycle on that 3 and so on.
Recently I posted on MathStackExchange about what happens if we change the grouping of the Collatz Form and we do this [(X+Y)*A,X/2] In some cases there is a cycle on the multiplier and in some cases it is a divergent system.
 Interesting is the output for X is a member of {2,3} in that the sequences look similar to what we see in [3X+1,X/2]
With Dynamic Unary an entire class of numbers exists that are all cycles.  For example with parity reference b0 and a length of 32 bits there are 67,108,864 of these dynamic integers where each "Cycle" has 64 elements. also interesting is that each 67,108,864 when each of the 64 32 bit unsigned integers are added up each cycle's sum is the same as all others. I call these dynamic integers ( they are spinning) but a case could be made to call them Quantum Numbers rather then extend the QBit concept to QByte and so on.
Google Introduction to Dynamic Unary or follow this link http://arxiv.org/abs/1405.2846
I hope I have been helpful.  I do enjoy this subject.


Why colors are set to high saturated in most smarphones?

Question:
From the very first time of buying android smartphones, we see those colors which are less realistic. Only few percentage of people change it by going deep level down inside settings.
Why it is set so vibrant?
Comment: As stated here : https://material.io/guidelines/style/color.html , it's kind of google material design's principles that color should be unexpected and vibrant.
Comment: The screenshot is from samsung s3, ahead of time of material design
Comment: Manufacturers like users to think they're getting an amazing screen so they set to be as colourful as possible without looking ridiculous - this is more about marketing than UX.
Answer: Because smartphones are used outdoors...
I suspect it is mostly fashion and showing off, as Koen Lageveen suggests here. However, there is a potential usability benefit. Smartphones are more likely to be used outdoors in bright ambient light. Bright ambient light tends to wash out colors, all other things being equal. If the color saturation were lower, images would appear duller and possibly even harder to recognize. If color coding is used, color differences would be harder to distinguish.
...but that's becoming less of an issue...
Today, most smartphones have programmably accessible ambient light sensors, opening the possibility for an app to dynamically adjust color saturation so that colors are distinct in high ambient light, but not so jarring in normal and low light. See:

Yu J, Zhao J, Chen Y, Yang J, 2015 Sensing Ambient Light for User Experience-Oriented Color Scheme Adaptation on Smartphone Displays. Proceedings of the 13th ACM Conference on Embedded Networked Sensor Systems, 309-321.

...so, get ready for a backlash.
Technology fashion seems to be driven by a combination of reacting against the previous fashion while showing off current technical capacities. Remember 3-D? Transparency and reflections? Skeuomorphism? Therefore, I predict the next fashion will be dynamically adjusted color schemes that are consistently "Quiet" or "Serene." Be the first.
Comment: Almost a year, I became influenced by your article "Name calling" which completely changed my perception about ux. I just wanna say many thanks for writing such wonderful article. it is a big asset to beginners like me. And talking about your answer, I didn't thought of washing out of colors. And I think it meets my curiosity.
Answer: Seeing that bright and colourful display and might cause you to think "wow this is a great phone I'm going to buy it". That experience and the moment of purchase is actually a pretty strong part of the user experience of owning something and very important aspect of the customer journey.
Also, properly calibrated colours are usually a bit dull. If you don't care about accuracy (e.g. you're not colour correcting photo's for print) there is something to be said about pumping it up a bit.
Comment: I had the original Nexus 7 tablet for a while and then I upgraded my phone to the Samsung S3. The first time I opened some of the more colorful apps on that phone (The Simpsons: Tapped Out comes to mind), I was duly awestruck by the "vividness" of the display. In fact, after using the phone for a while, the next time I opened that app on the tablet, I thought it looked faded, washed out. So there's anecdotal evidence that cranking up the saturation is a decision on Samsung's part that led to a good UX for at least one of their customers. FWIW
Comment: Thoughts you wrote here hit my mind too. I think it is more than that.
Comment: @DanHenderson thanks for sharing your experience. My experience is like. I prefer mobile(display set in faded color) for browsing most of informations in web. When someone pass me their mobile, I feel like fake, over-exaggerated UI may be it is because of my age. anway +1 for your comment.


How should I wire a switch/outlet combo to a split outlet if the feed is at the split outlet?

Question: What if my incoming source starts at the outlet I want to split (always on for the dishwasher, switched for the garbage disposal) and not in the switch/outlet combo? How would I wire that?
I read this and looked at the diagram on your site:

If you want to have power always on to a box that is downstream of a switch, you'll need to use 3-conductor cable between the switch and split the hot side of the outlet.
At the outlet, break off the tab on the hot side only between the top and bottom outlet. Wire the red conductor to one of the hot screws, the black conductor to the other one, and then the white to the other side of the outlet.
At the switch/outlet, you'll need to wire the incoming black wire to one of the hot screws, and the outgoing black wire (to the 3 condutor cable) to the other hot screw. The outgoing red wire (the one controlled by the switch) goes on the neutral side of the switch, and the incoming white wire gets wire-nutted together to the neutral side of the outlet along with the outgoing white wire (from the 3 conductor cable)
Be sure to ground all outlets and switches as well.

I think its image #6?
Answer: That description is OK, but you really only need to run 2-wire with ground romex up to the switch, not 3-wire. Split the hot side of the outlet as described. Use a wire nut to pigtail a short piece of wire from your source hot to the terminal of the receptacle that you want "always on" and also connect to the new black wire from the romex running to your switch. Connect the other end of your new black wire to one terminal of your new switch.
Remember, the switch just "makes" or "breaks" the hot.
Connect the new white wire from the romex to the other side of the switch. Permanently mark the white wire at the switch box with red or black permanent marker to identify it as a "switched hot". Connect the other end of the white wire from the romex to the hot terminal of the receptacle that you want switched (for the disposer). Permanently mark the white wire at the receptacle with red or black permanent marker to identify it as a "switched hot". Connect the source neutral to the receptacle and ground everything.