How to Limit the CPU usage for a process and its children whether there is another process demanding resources or not

Question: I was thinking about using CPUlimit to limit process CPU usage, but I am aiming to apply the same percentage of usage for its child processes too automatically.
Is there something that can limits the CPU usage for a process and its children whether there is or there is not another process needing resources at the same time?
cgroup cpu.shares limits only when there is another process needing the resources consumed by a previous process. What I'm looking for is something like sudo cpulimit -p 1234 -l 20 so the limit on cpu usage doesn't consider whether there is another process or not demanding the used resources.
This was applied to the parent process (pid =1234) but not its children.
Comment: Have a look at this: [Cpulimit](http://www.howtoforge.com/how-to-limit-cpu-usage-of-a-process-with-cpulimit-debian-ubuntu)
Comment: Well I didn't read your post thoroughly... I search a bit and found this [LINK](http://ubuntuforums.org/showthread.php?t=992706). Hope this helps :)
Comment: Easily Change 'CPU Affinity' in Ubuntu using 'procexp' http://www.hecticgeek.com/2013/03/change-cpu-affinity-ubuntu-procexp/
Comment: yes thank u , i read it ,but excuse me  ı didnt get what ıs the new thing u want to tell me , i am beginner
Comment: I'm not sure but if you look at `pstree -p` you can see the processes in a tree kind of way... now if you take the first PID and limit the cpu the "children PIDs" should automatically take over the cpu limit? But as mentioned i'm not sure.
Comment: well actually i am not sure too but i can tell that by using it i found that the child process of the parent process on gnome-system-monitor exceeds the limits which i specified
Comment: yes thank u it is very useful but actually i want to specify one my own which one i want to limit and which one not and with varying ration of limitation not for 20% for all running process as mentioned
Comment: Well Sir looks like you beat me to it... :D just wanted to post that myself...
Answer: This link may help  Set maximum CPU consumption in percentage by any process
  searched by : MrSeed
this script may help too , any any one wants to enter suggestions on this script to enhance it , it will be my pleasure
       #!/bin/bash -xv

read -p "Which program u want to limit its processes?" ProgrameName
read -p "Which limitation percentage u want for it ?" limitationPercentage
read -p "Period to be sleep " sleepInterval
dataFile="/home/ahmedubuntu/Desktop/.file.txt"
separator="######"
trap "echo \"\" > $dataFile"  SIGINT SIGTERM SIGHUP
########################################################
if [ -e $dataFile ]; then
  echo "File $dataFile already exists!"
  echo -e "" > $dataFile
else
  echo >> $dataFile
fi
echo -e "$ProgrameName \n $limitationPercentage \n" >> $dataFile
getAllPIDRunUnderThisProgram=$( ps -e | grep "$ProgrameName" | awk '{print $1;}')
echo -e "${getAllPIDRunUnderThisProgram[@]}  \n $separator \n" >> $dataFile
for i in $getAllPIDRunUnderThisProgram
   do
    gnomeTab+=( --tab -e "cpulimit -p $i -l $limitationPercentage ")
   done
gnome-terminal "${gnomeTab[@]}"
#echo gnome-terminal "${gnomeTab[@]}"
########################################################
while sleep $sleepInterval
do
i=0
while read line
do
if [ -n "$line" ] && ["$line" != "separator"]
then
programeNameAndPID[i]=$line
((i++))
elif [["$line" == "separator"]] ; then
getAllPIDRunUnderThisProgram=$( ps -e | grep "$programeNameAndPID[0]" | awk '{print $1;}')
if [${#getAllPIDRunUnderThisProgram[*]} -gt ${#programeNameAndPID[*]}-2  ]
then
unset gnomeTab
newProcessNumber=${#getAllPIDRunUnderThisProgram[*]}-${#programeNameAndPID[*]}-2
index=${#getAllPIDRunUnderThisProgram[*]}-1
for (( c=$newProcessNumber ; c > 0 ; c-- ))
do
gnomeTab+=( --tab -e "cpulimit -p $getAllPIDRunUnderThisProgram[$index] -l $programeNameAndPID[1] ")
((index--))
done
gnome-terminal "${gnomeTab[@]}"
fi
i=0
unset programeNameAndPID
fi
done < $dataFile
done

and by adding nice -10 will work well with no need to sudo and password


How to add playbook permissions in azure sentinel via terraform?

Question: I have terraformized Log Analytics Workspace, Sentinel by using below code:
resource "azurerm_log_analytics_workspace" "log_analytics_workspace" {
  name                = "log-test-permissions"
  location            = "xxx"
  resource_group_name = "xxx"
  sku                 = "PerGB2018"
  retention_in_days   = 90
}

resource "azurerm_log_analytics_solution" "sentinel" {
  solution_name         = "SecurityInsights"
  location              = "xxx"
  resource_group_name   = "xxx"
  workspace_resource_id = azurerm_log_analytics_workspace.log_analytics_workspace.id
  workspace_name        = azurerm_log_analytics_workspace.log_analytics_workspace.name

  plan {
    publisher = "Microsoft"
    product   = "OMSGallery/SecurityInsights"
  }

  depends_on = [azurerm_log_analytics_workspace.log_analytics_workspace]

}

I'm planning to terraformize the playbook permissions configuration by following below steps.

Go to Azure Sentinel -> Configuration -> Settings -> Playbook permissions -> Configure Permissions
Check 'Current permissions' tab to see if the resource group containing the playbook is listed. Else select the required resource groups in 'Browse' tab and select 'Apply'.

Can anyone please help me out regarding how can we terraformize the playbook permissions on sentinel for a specific resourcegroup ?
Answer: Check the following code :
 terraform {
      backend "azurerm" {
        resource_group_name  = "XXX"
        storage_account_name = "remteccc1"
        container_name       = "terraform"
        key                  = "terraform.tfstate"
      }
  }

resource "azurerm_log_analytics_workspace" "exm" {
  name                = "dsd"
 location                    = xx
  resource_group_name         = xxx
  sku                 = "PerGB2018"
  retention_in_days   = 90
}

resource "azurerm_log_analytics_solution" "log_analytics_solution_sentinel" {
  solution_name         = "SecurityInsights"
 location                    = data.azurerm_resource_group.example.location
  resource_group_name         = data.azurerm_resource_group.example.name
  workspace_resource_id = azurerm_log_analytics_workspace. exm.id
  workspace_name        = azurerm_log_analytics_workspace. exm.name
  plan {
    publisher = "Microsoft"
    product   = "OMSGallery/SecurityInsights"
  }
  depends_on = [azurerm_log_analytics_workspace.rgcore-management-la]

}

The  permissions to playbook can be given is as follows.
You need to have Permissions to playbook for which we can add roles like Microsoft Sentinel Automation Contributor role to the resource which allows the access on sentinel.
resource "azurerm_role_assignment" "sentinel_contributor" {
  scope              = "/subscriptions/<subId>/resourceGroups/<rg>"
 // role_definition_id = azurerm_role_definition.sentinelcontributor.id
  role_definition_name = "Azure Sentinel Contributor"
  principal_id       =  "3367a746-xxx18686"#objectid of azure security insights app objectId or servicepincipal
data.azurerm_client_config.current.object_id
}

These roles are to be assigned to the security insights  or resource group that contains the Microsoft Sentinel workspace.

With the permissions , automation rule is created and is reflected in portal under microsoft Sentinel.
resource "azurerm_sentinel_automation_rule" "example" {
  name                       = "56094f72-ac3f-40e7-a0c0-47bd95f70336"
  log_analytics_workspace_id = azurerm_log_analytics_workspace.rgcore-management-la.id
  display_name               = "automation_rule1"
  order                      = 1
  action_incident {
    order  = 1
    status = "Active"
  }
}

Comment: Hi Kavya... by using Sentinel Automation Contributor role , can we run playbook automatically ?
Comment: Hi Kavya .. have done the similar changes. Able to create Sentinel Automation Contributor on securityInsights on resource group level on serviceprincipal. But I could not create the automation rule. Facing the below issue : [BadRequest] : Caller is missing required playbook triggering permissions on playbook resource '/subscriptions/359ca389-01e3-4f49-813a-a0afe3c68e40/resourceGroups/tie0-cl040-tst-t0/providers/Microsoft.Logic/workflows/Send-email-with-formatted-incident-report', or Microsoft Sentinel is missing required permissions to verify the caller has permissions
Comment: Able to create automation rule by changing the severity. But not able to create automation rule to trigger playbook
Comment: try to create another role assignment ,  make  the scope to ID of your playbook resource, and principal_id to the service principal /user trying with ` Contributor` role.
Comment: Hi Kavya.. I'm able to create Sentinel Automation Contributor on serviceprincipal on resource group level  but not on Azure Security Insights. How to fetch the objectId of AzureSecurityInsights app using terraform ?


EF migrations claims there were changes in the context while there were none

Question: I'm using Entity Framework Migrations & Code First and recently encountered a very weird problem.
The problem was reproduced with versions 4.3.1 and 4.4.
EF thinks that the context was changed while actually it didn't.
It happens when I change the path of the solution. for example:
If my solution is located in C:\integration\something.sln the migration may work but if now I will change the path to C:\development\something.sln and re-build the solution the migration will throw an exception saying there are pending changes in the database. (Of course without any changes in the source code.
I used IL Disassembler to create a dump of the output assemblies and with BeyondCompare I saw that there are differences. I assume the data is the same but its written in different order...
How EF determines if there were changes in the context? Is it possible that the assembly check-sum comes out different and will cause EF to think that there were changes?
Any ideas are most welcome...
Comment: What do you mean by changing the path? What differences are between solutions? Model changes are detected from hashes. If anything related to mapping changes (even order) the hash will be different.
Comment: By changing the path I mean renaming the folder - as simple as that.
It's the same solution without any changes in the code, just renamed the folder that contains it.
And what I saw is that building the same solution while it is contained in two different folders - will result in assemblies that are not the same.

So there are two issues here:
1. Visual Studio is not consistent with its output assemblies.
2. EF will get confused if the same code will result in assemblies that differ from each other.
Answer: First, this is not a migration issue - its probably a bug in the Entity Framework's algorithm to check if there are changes in the database.
I had a class hierarchy that contained an abstract class with no properties, making that class not abstract solved the problem.
After gaining some precious debugging experience, I found several ways to solve this issue and each one raised more eyebrows than the one before which makes me very convinced that I fell on a very rare corner case. As I mentioned, I decided to solve by making a class not abstract.
I tried to reproduce the bug in a clean solution so I can send it to Microsoft but until now it didn't really work.
So... to sum things up, if you find yourself with such a problem (very frustrating one), a good tip is to look for abstract classes!


What does good condition mean in a Pokemon Contest?

Question: In Pokemon Ruby/Sapphire/Emerald, the description for Rock Smash on the Contest Moves page says "The appeal works well if the user's condition is good". What does this mean? How can I tell if my condition is good in a Pokemon Contest?
Answer: Good condition is marked as a blue star during the contest. It's gained through some moves that are described as "Ups the user's condition". You can gain up to three stars in a single contest, and for each star you have, you get an extra appeal point on your next move.
These moves are:

Cool

Cosmic Power, Dragon Dance, Howl

Beauty

Bulk Up, Growth, Meditate, Silver Wind, Swords Dance, Tail Glow

Cute

Amnesia, Belly Drum, Refresh, Sharpen

Tough

Acid Armor, Ancientpower, Swallow


Access to AWS Elastic Load Balancer using AWS SDK for python

Question: So I'm using boto3 to connect to AWS and manage my web server instances which are behind an Elastic Load Balancer (ELB). The problem is that I do not have access to my ELB, it is while I have access to the other existing resources like Instances. For example, while I'm running this piece of code, I can see my running instances:
ec2 = boto3.resource('ec2', region_name="us-east-2")
instances = ec2.instances.all()
for instance in instances.all():
     print(instance)

The output is like this:
ec2.Instance(id='i-xxxxxxxxxxxxxxxxx')
ec2.Instance(id='i-xxxxxxxxxxxxxxxxx')
ec2.Instance(id='i-xxxxxxxxxxxxxxxxx')

By running the below code, I expect to see my ELBs:
elb = boto3.client('elb', region_name="us-east-2")
elbs = elb.describe_load_balancers()
print(elbs)

But the output is like this:
{'LoadBalancerDescriptions': [], 'ResponseMetadata': {'RequestId': 'f813b2d3-b5e8-11e7-8b34-73b6f3d263a2', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'f813b2d3-b5e8-11e7-8b34-73b6f3d263a2','content-type': 'text/xml', 'content-length': '335', 'date': 'Fri, 20 Oct 2017 22:49:45 GMT'}, 'RetryAttempts': 0}}

As you can see in the output, there is no ELB in LoadBalancerDescriptions, while according to the API refference, it should contains the name of existing ELBs. But I have an ELB in my console that works fine:

I do not know why the python code does not work.
Answer: Use the class ElasticLoadBalancingV2 for the newer load balancers: ALB and NLB. Example: client = boto3.client('elbv2')
Use the class ElasticLoadBalancing for the "Classic Load Balancer".
ElasticLoadBalancingv2


Invalid use of this in member function

Question: I have method in my class how return reference to an object, but I don't know how can I access to my attribut in this method.
Particule& update(double timestamp)
{
    this->vx += timestamp;
}

vx is an attribut to my Object Particule. But if I try to access vx with this I have an error why ? I thought this would work.
My class definition:
#include <stdio.h>
#include <iostream>

class Particule{

    public:

    double rx, ry;      //position
    double vx, vy;      //velocity
    double fx, fy;      //force
    double mass;        //mass

    Particule ();
    Particule(double rx, double ry, double vx, double vy, double fx, double fy, double mass);

    Particule& update(double timestamp);

    friend std::ostream& operator<<(std::ostream& str, Particule const& p)
    {
        return str <<
        "rx : " << p.rx <<
        " ry : " << p.ry <<
        " vx : " << p.vx <<
        " vy : " << p.vy <<
        " mass : " << p.mass << '\n';
    }
};

And I don't know how can access to my object in my method update. I call this methode by object.update(timestamp);
Comment: You have declared `update` outside of its class definition.  Either move the method into the class definition or change it to "your_class_name"::update
Comment: Is this code within a class definition?
Comment: Error is : `Invalid use 'this' outside of a non static member function`
Comment: Please provide an [mcve]
Answer: If definition is outside the class, you have to do something like:
Particule& Particule::update(double timestamp)
{
    this->vx += timestamp;
    return *this;
}

Invalid use of this in member function


Can attached properties work within the INotifyPropertyChanged framework?

Question: First, please forgive (and correct!) any misconceptions - I'm brand new to anything .NET.
Me and my team are building an application in Silverlight, using the MVVM pattern.  Right now, we a viewmodel for an object with various properties (e.g. its background color).  The VM implements INotifyPropertyChanged so that when those properties are updated, listeners are notified.
The problem is that these are drag-and-drop objects on a canvas, and we want to run some logic every time the position on the canvas is changed.  However, my understanding is that because Canvas.Left and Canvas.Top are attached properties I can't treat them the same way as I did the properties native to the object.
Is there any way to make these attached properties work with INotifyPropertyChanged?  If not, what's the best way to react to changes in the Canvas.Left and Canvas.Top properties.
Thank you very much!
Answer: Two things:
(1)  To keep with the MVVM pattern, I would suggest using style triggers for these attached properties and leave them out of your View Model altogether.
(2)  Along those same lines, I wouldn't have your view models know about concepts like "background color" that are purely view concerns.  If there is something in your business logic/VM that keys a view concern like color, you can use value converters to translate from what the view model knows about to what the view needs to do.


Find p(0) if...

Question: Question
If $p(x)$ is a polynomial and $p(x)-p'(x)=x^n$ where n is a positive integer,find the value of p(0)
Options
(A) $n!$
(B) $(n-1)!$
(C) $1/n!$
(D) $1/(n-1)!$
My approach
I started solving the question by assuming $p(x)=a0+a1•x^1+a2•x^2+.....+an•x^n$ and
$p'(x)=a1+2•a2•x+3•a3•x^2+.....+n•an•(x^{(n-1)})$
So then
$p(x)-p'(x)=a0+a1(x^1-1)+a2(x^2-2x)+.....+an(x^n-nx^{(n-1)})
=x^n$
Now I can't quite understand what to do.any help is appreciated.Thanks :)
EDIT
I tried taking the x terms common so I get
$p(x)-p'(x)=a0-a1+x(a1-2•a2)+x^2(a2-3•a3)+.....+x^{n-1}(a(n-1)-n•an)+an•x^n=x^n$
So $p(0)=a0-a1$
Now I still don't understand how the answer is in terms of n
Answer: Hint: try taking the expression you got for $p(x) - p'(x)$ (which I can confirm is correct), and rearranging it to combine terms with like powers of $x$. (So the constant term is $a_0 - a_1$, the coefficient of $x$ is $a_1 - 2a_2$, and so on.)
Once you've done that, you can figure out what has to be true about $a_0, a_1, \dots, a_n$ for this to be the same polynomial as $x^n$.

Find p(0) if...


My Xonar audio card has disappeared upon installing Nvidia card (980 GTX). What can I do to restore it?

Question: I've installed a brand new GTX 980 and my Xonar audio card (plugged in!) has suddenly disappeared (I'm using one HDMI and DVI port for my two displays).
In order to listen to something I had to re-enable onboard audio, but I would want to use my Xonar, not the rubbish onboard solution.
Any idea?
Cheers!
Answer: Apparently was just a wire making contact to the audio card. Everything is now ok... what a kultz!


Cardinals proof |A| ≤ |B| iff |B| ≥ |A|

Question: So i have a little bit problems proofing this.
 |A| ≤ |B| iff |B| ≥ |A|

i know, that if |A| ≤ |B| => f: A => B, must be injective
and likewise, that if |B| ≥ |A| => g: B => A, A = ø or it must be surjective.
Good, but how do i exactly do this proof? I am a little bit lost on how to write it down in a mathematical accurate way. Would anyone be able to help me out?
Thanks in advance
Comment: The notation is terrible. $\geq$ and $\leq$ are *usually* understood to be the same relation written backwards.
Answer: I will prove the first implication and leave the other to you.
Assume $\vert A\vert\leq \vert B\vert$.
If $A=\emptyset$, there is nothing to prove, so we can assume $A\ne\emptyset$. Since $\vert A\vert\leq \vert B\vert$ there is an injective map $f:A\to B$. We prove that this has a left-inverse, i.e. there is a $g:B\to A$ such that $g\circ f=\operatorname{id}_A$. Pick $a_0\in A$ arbitrary (possible since $A\ne\emptyset$). Then we define $g:B\to A$ as follows:
\begin{align*}
g(b)=\begin{cases} a ~~~\text{if }a\in A,f(a)=b\\a_0~~~\text{otherwise, i.e. if }b\notin f(A)\end{cases}
\end{align*}
Note that this is well-defined since $f$ is injective, i.e. if there is som $a\in A$ with $f(a)=b$ then this $a$ is uniquely determined. Similarly we can check that $g\circ f = \operatorname{id}_A$. Now we claim that this $g$ has to be surjective. Let $a\in A$. Then $g(f(a))=\operatorname{id}_A(a)=a$ hence $f(a)$ is a preimage of $a$ for $g$, so $g$ is surjective. So we proved that there is a surjective map $B\to A$, hence $\vert B\vert\geq\vert A\vert$.
Now do something similar for the other direction, i.e. $\vert B\vert\geq\vert A\vert\implies \vert A\vert\leq\vert B\vert$.
(Here I assumed that the definition of $\vert B\vert\geq\vert A\vert$ is that there is a surjective map $B\to A$ and for $\vert A\vert\leq\vert B\vert$ that there is an injective map $A\to B$)
Comment: Thanks, i'll study your answer.

Cardinals proof |A| ≤ |B| iff |B| ≥ |A|


GE dimmer works with 3 LED lights, somewhat with 4 and not at all with 5

Question: I've got a brand new single pole GE 14294 Z-Wave Plus dimmer.  Before I try to connect it to z-wave, I wanted to make sure it was working.  I have five LED lights (4W, 65mA, BR20 flood) lights in series.  They were dimming fine on my old Leviton dimmer so I know they are OK.
Using the switch itself, the dimmer will switch the lights on and off no problem, but will not dim. BUT, if I unscrew two bulbs, then the remaining three work fine - i.e., the dimmer works correctly.  If I add the 4th back in, the will dim slightly.
I've checked the current, and 3 lights are pulling about 0.2A.  With four that goes up to 0.26A, with five about 0.32A.  Switch is rated for 1500W and is compatible with LED.
I've tried a different 14294 and have exactly the same problem.  Note that at this stage I'm just using the physical switch, so nothing to do with z-wave.
Any ideas?  Bug in the firmware?  Could it be the bulbs?
I Called Jasco/GE and they didn't know.
Comment: What make and model are the bulbs?
Comment: What is the power factor of the bulbs?
Comment: Screw one incandescent bulb in (with 4 LED bulbs) and test. What happens?    Also you probably don't mean "in series", if they are in fact in a series circuit fix that first.
Comment: @Tyson - correct - my bad.  Not in series.
Comment: @Harper - will measure and let you know.
Comment: The reason for one incandescent as part of a test is it increases the load.  Your scenario is a little different than most having a compatibility issue, but there is a minimum wattage issue that often shows up....
Comment: @harper - I've tried two different LED bulbs in a test setup, along with an incandescent (i,e., outlet->dimmer>killawatt->bulb).  PF on both LEDs was 0.96.  Leviton dimmer takes PF down to about 0.6 when fully dimmed - but bulbs are still relatively bright, though dimmed.  GE dimmer does nothing.  PF stays at 0.96 and no dimming happens.

Incandescent behaves as expected - both dimmers work fine, taking bulb through full range of brightness.

Seems like the GE dimmer really doesn't like the LEDs.  Faulty dimmer?
Comment: Weird that it works on 3 bulbs, but not on 4, 5 or 1!!
Answer: I think this has todo with minimum load. These dimmers require 50 watt min
Comment: Hello, and welcome to Stack Exchange. You should improve this answer because as it stands it is being flagged as low quality and is in danger of being deleted. I would suggest as a minimum if you could support the claim of the minimum load by taking a snapshot of the spec sheet for the switch that shows this data and explain what that means.
Comment: And, if this is true, then why do things start going wrong when the OP adds load to a working system?
Answer: I'm having similar issues, and looked in page one of the manual and it says for incandescent lighting only. Not impressed!
Comment: Hello, and welcome to Home Improvement. Good answer, but is this the same model as the OP? Would you elaborate a bit?
Comment: Based on the manual available online @ zwave.eu for the GE 14294, this doesn't seem to be correct. It says "Compatible with all incandescent and most dimmable CFL/LED bulbs".


Run mini-split heat pump heads at different temperatures

Question: I vaguely remember the contractor who did maintenance on our ductless heat pumps two summers ago telling us not to set the thermostats of the two small heads that share an outdoor unit to different temperatures.
My memory is that there was something about the outdoor unit's inability to adjust the amount of work it's doing that made such an arrangement bad. I haven't been able to find any confirmation of this online though.
Am I making this up, or is it really good advice?
It's a two-story house, 900sqft.
(not counting the basement, where we occasionally use a radiant/oil space heater to keep the pipes thawed.)
The whole downstairs has a single double-wind heat-pump head with its own outdoor unit.
Upstairs the bedroom and office each have a head with piping out to their shared unit.
The reason I'm stressing about this now is because, with both of us working from home every day, we've been mostly-closing the door of the office so we can have that one room ~10F hotter than the rest of the house during the day. (The difference is large enough that we're not much worried we'll forget and leave it overnight.)
Comment: It is a half truth: you could not use a split for cooling and another for heating if connected to the same compressor, this is due to the fluid path being "reversed" when heating; the compressor could be sucking mode or pumping mode, noth both.
But you'll have no problem in running two rooms at different temperatures if both are heating or cooling, the extreme is that you could keep an inner split turned off and the system should work with no issues.
Comment: I"m not going post this as an answer, since I'm not sure. I've never heard of that advice before.  One of the advantages of split systems IS the ability to set different zones to different temps.  I think you got bad advice and you're fine with different temp settings.
Answer: It's complete BS. If that was actually a problem, then the system wouldn't let you do that.
Comment: LOL, you said it much more succinctly than I did.  I was trying to be polite!  But I agree with you completely. It's complete BS advice. +
Comment: I think it may have just been a misunderstanding between different cycles and different temperatures.


Export variable from a shell script into a perl script

Question: Perl Code
`. /home/chronicles/logon.sh `;

print "DATA  : $ENV{ID}\n";

In logon.sh , we are exporting the variable "ID" (sourcing of shell script).
Manual run
$> . /home/chronicles/logon.sh
$> echo $LOG

While I am running in terminal manually (not from script). I am getting the output. (But not working from the script)
I followed this post :
How to export a shell variable within a Perl script?
But didnt solve the problem.
Note
I am not allowed to change "logon.sh" script.
Comment: see: http://stackoverflow.com/questions/2967762/how-to-export-shell-variable-within-perl-script/14077546#14077546
Answer: The script inside the backticks is executed in a child process. While environment variables are inherited from parent processes, the parent can't access the environment of child processes.
However, you could return the contents of the child environment variable and put it into a Perl variable like
use strict; use warnings; use feature 'say';
my $var = `ID=42; echo \$ID`;
chomp $var;
say "DATA: $var";

output:
DATA: 42

Here an example shell session:
$ cat test_script
echo foo
export test_var=42
$ perl -E'my $cmd = q(test_var=0; . test_script >/dev/null; echo $test_var); my $var = qx($cmd); chomp $var; say "DATA: $var"'
DATA: 42

The normal output is redirected into /dev/null, so only the echo $test_var shows.
Comment: This is printing the output of the script. (Not printing the exported data). I am not allowed to change the logon.sh script.
Comment: @Chronicles Then just silence the script — you aren't using the output anyway. See my update for that. If you do need the output, redirect it to a file instead and read from there.
Comment: This is a nice approach, but I would change the example to: `my $id = qx( . logon.sh; echo \$ID )`
Answer: It won't work.
An environment variable can't be inherited from a child process.
The environment variable can be updated in your "manual run" is because it's in the same "bash" process.
Source command is just to run every command in login.sh under current shell.
More info you can refer to: can we source a shell script in perl script
Answer: Well, I've find a solution, that sound nice for me: This seem robust, as this use widely tested mechanism to bind shell environment to perl (running perl) and robust library to export them in a perl variable syntax for re-injecting in root perl session.
The line export COLOR tty was usefull to ask my bash to export newer variables... This seem work fine.
#!/usr/bin/perl -w

my $perldumpenv='perl -MData::Dumper -e '."'".
    '\$Data::Dumper::Terse=1;print Dumper(\%ENV);'."'";

eval '%ENV=('.$1.')' if `bash -c "
        . ./home/chronicles/logon.sh;
        export COLOR tty ID;
        $perldumpenv"`
    =~ /^\s*\{(.*)\}\s*$/mxs;

# map { printf "%-30s::%s\n",$_,$ENV{$_} } keys %ENV;
printf "%s\n", $ENV{'ID'};

Anyway, if you don't have access to logon.sh, you have to trust it before running such a solution.
Old...
There is my first post... for history purpose, don't look further.
The only way is to parse result command, while asking command to dump environ:
my @lines=split("\n",`. /home/chronicles/logon.sh;set`);

map { $ENV{$1}=$2 if /^([^ =])=(.*)$/; } @lines;

Comment: Nitpick: Your code is equivalent to ``print `. /home/chronicles/logon.sh;set`;``. In list context, the backtick operator returns a list of output lines. Also, it is unidiomatic to use `map` in void context. `say for @lines` or `print "$_\n" for @lines` would accomplish the same thing.
Answer: You could do something like:
#/usr/bin/perl

use strict;
use warnings;

chomp(my @values = `. myscript.sh; env`);

foreach my $value (@values) {
    my ($k, $v) = split /=/, $value;
    $ENV{$k} = $v;
}

foreach my $key (keys %ENV) {
    print "$key => $ENV{$key}\n";
}

Answer: This can now be done with the Env::Modify module
use Env::Modify 'source';
source("/home/chronicles/logon.sh");
... environment setup in logon.sh is now available to Perl ...

Answer: Your Perl process is the parent of the shell process, so it won't inherit environment variables from it. Inheritance works the other way, from parent to child.
But when you run the script with backticks, as shown, the standard output of the script is returned to the Perl script. So, either modify the shell script to end with the echo $LOG statement you show, or create a new shell script that runs the login.sh and then has echo $LOG. Your Perl script would then be:
my $value = `./myscript.sh`;
print $value;


sendKeys(CharSequence[]) error

Question: I have installed java JDK1.8.0_05. I am using selenium 2.50.0. I have entered below code:
<code>username.sendKeys("Ashok");
</code>
and I got the error  as below.

The type java.lang.CharSequence cannot be resolved. It is indirectly
  referenced from required .class    files
    - The method sendKeys(CharSequence[]) from the type WebElement refers to the missing type    CharSequence

Can anyone help me on this issue?
Comment: It will be great if you will provide your full tried code.
Comment: Upgrade your Selenium version to 3.0 or above
Comment: Possible duplicate of [The type java.lang.CharSequence cannot be resolved in package declaration](http://stackoverflow.com/questions/24301986/the-type-java-lang-charsequence-cannot-be-resolved-in-package-declaration)
Comment: It would be nice if you spent a few minutes googling error messages, etc. and trying to find an answer to your question before asking it here. I googled the error message and the first result contains your answer.
Answer: change your jre to 1.6 will be ok

sendKeys(CharSequence[]) error


Importing objects from another python file as a list

Question: I have a file (Crop_Library.py) containing a list of objects with various attributes (same number for all):
from Crop import Crop

Basil = Crop("Basil", 3, 0, 5, 10, 5)
Lettuce = Crop("Lettuce", 3, 4, 5, 10, 7)
Kale = Crop("Kale", 1, 2, 3, 4, 5)

I would like for my GUI program (GUI.py) to read all the objects in Crop_Library.py and store them in a list so that my GUI can list them in a Combobox (so they also need to be converted to strings, or just read the crop.name string, which is the first attribute for all).
For now, importing is the question. However as an FYI, I would like to add edit functionality to another part of my GUI in the future such that the objects can be created/edited/deleted. I am open to using a json file instead of a python file to store these objects if that is a better approach - I am new to python and just very lost so any guidance is appreciated.
Thanks in advance!
Answer: If you use JSON, what you read won't be Crop objects.  You could turn the input into Crop objects after reading the data.
Here's how you could have a list upon import of what you have:
from Crop import Crop

Basil = Crop("Basil", 3, 0, 5, 10, 5)
Lettuce = Crop("Lettuce", 3, 4, 5, 10, 7)
Kale = Crop("Kale", 1, 2, 3, 4, 5)

crops = [ Basil, Lettuce, Kale ]

or more concisely, if you don't need the object names, which you shouldn't...
from Crop import Crop

crops = [
    Crop("Basil", 3, 0, 5, 10, 5),
    Crop("Lettuce", 3, 4, 5, 10, 7),
    Crop("Kale", 1, 2, 3, 4, 5,)
]

BTW, per proper Python naming conventions, your Crop object names should be lowercase.
Comment: Hi Joe, thanks for the response! I'm still having trouble finding a way for my code to automatically create a list of just the crop names in that list of Crop objects. What I need at the moment is a list like in the last line of your first example, but created automatically since I will be adding the ability to edit/add/delete from that list, but need my combobox to read what is currently in that list of crops.
Comment: Look at Pickle.  Pickling is a way of serializing (turning into a stream of bytes) arbitrary Python objects rather than just dicts, lists and sets.  Check this out:  https://www.thepythoncorner.com/2016/12/object-serialization-in-python/?doing_wp_cron=1550454785.8881769180297851562500 . So you can have your user build up the list, and then Pickle it off to a datafile.  Then, when the user runs your app again, you can Unpickle the data file to reconstruct the in-memory list.
Comment: I don' know that it's the best way, but it wouldn't be too hard to write code that produced the equivalent of your Python input file we've been working with.  So you'd write special code to serialize your list as Python code, but then you'd just import the file to read it back in.  There are other ways to do this too.  A common way for robust apps is to have each of your objects know how to produce a serialized (stream of bytes or characters) representation of itself, and to be able to reconstruct itself from such a representation.
Comment: One specific way to do this last thing is to have your object be able to represent itself as an in-memory structure of lists, dicts, and sets.  Then the Python JSON library can be used to store and read back in that structure, and you would write code to turn that in-memory structure into your actual list of objects.   PS: If you can accept this answer so I can get some points, that would be great.
Comment: Hi Joe, I will go ahead and accept this and work through a few of your suggestions. Thanks a lot for all your input!


Are mini wall switches available that are less conspicuous?

Question: As I rewire my room, I'm going to add some pin spots in the ceiling to illuminate artwork on the walls. I would like to have them switched, but not with a regular sized commonly available switches. Instead I'd ideally like small round toggles or push-button switches placed near the artwork itself unobtrusively.
So far, my searches result in either bigger switches, ones for small electronics devices, automotive switches or ones intended for low voltage cabinet lighting. What term should I be searching for to find what I'd like? In an ideal world, they would be manual with a wifi option and possibly a dimmer option, but I'd settle for just a simple psh-button on/off.
Alternatively, if you have a suggestion for a work-around I'd appreciate that too.
Comment: I don't consider this a product recommendation request. It's about a solution to a problem involving a hypothetical _category_ of products.
Comment: Unfortunately, this question as asked seems to be asking for a product recommendation, which is off topic here. But with your requirements, you will need to be looking at either going fully low voltage, or look into some sort of low voltage control system for line voltage, which would typically be used more in commercial buildings.
Comment: Thanks for your input. I tried my best not to ask for a specific product recommendation but I couldn't find the words to ask my question without it seeming like that. I thank you for your low-voltage suggestion, but in light of the answers received so far, I'm thinking a remote for a smart switch or smart bulb is the direction I should be heading.
Comment: Would a purely-software solution work for you?  No physical switches, just a phone/tablet app?
Comment: Not really. I'm installing other wifi-enabled switches for room lighting which will likely be useful in that way, but for the art I wanted it to be controlled close to the art by anyone visiting.
Comment: Have you considered an 'architrave switch' - like a standard switch but in a narrower enclosure?
Comment: Alternatively, you could incorporate the switch plates into the art itself - I've seen cases where a switch was placed on a wall with a full painted mural on it, and they just painted right on the switch plate as part of the mural.  From a distance it's nearly invisible.  (I don't recommend painting the switch itself, as the paint might gum it up so it doesn't work, and could potentially leak in and cause electrical problems.)
Answer: Low voltage is the key. LEDs are naturally low voltage devices. That is different from traditional incandescent. While incandescent bulbs can be low voltage (e.g., in cars), they require a lot of power, which means either higher voltage (safety issues) or higher current (wire size issues). LEDs can produce a significant amount of light using low voltage and low current, so you get to use small wires and use safer low voltage components.
There are packaged low voltage lighting systems, but for a real custom system, as you describe, you can essentially plop a right-sized, UL/ETL/similar listed power supply somewhere and then run low voltage wires to that power supply without (at least in most jurisdictions) the same restrictions as with 120V or 240V power. The end result can be a mimic of a traditional lighting system, with each switch controlling a light or set of lights, to an intelligent system with a microcontroller wired up to several switches and lights, to a WiFi/remote controlled "do anything" system.
Comment: Absolutely. Came here to write this answer (but happy for you to get the points).  Low voltage wiring greatly reduces the safety issues and therefore, the Code requirements.
Answer: It's not really a matter of the switches. House wiring needs to connect in approved boxes, which in turn need to be accessible. The somewhat large plate is a symptom of those requirements.
I suggest that you consider either relocating the switches to a less conspicuous area, or using remotely-controlled smart switching. You may find modern smart bulbs in a configuration you can use in your fixtures, or you may find control modules that can be installed inline.
Answer: Low voltage, individually addressable, smart LED bulbs would probably be the way to go. They could all be fed from one transformer to simplify the power requirements
You can get a small, discrete, momentary contact switch to locate next to each piece of art. This would allow you to get creative with, for example:

A single tap to toggle the light for this art piece
A double-tap for 3 spots on

This one
One artwork to the left
One artwork to the right
A long tap to turn them all off

Other options available and limited only by your creativity.
Answer: If you're looking for a subtle artistic way to control 120V lights, here are some options.
I have to get it out of the way... there is exactly what you are asking for: An electrical switch that is installed in a junction box and beautifully and artistically buried in drywall with no face plate.  It's gorgeous, one of a kind, and it's insanely expensive.  But if you're building a sort of art gallery in your home, you may be willing to do something like this.  Here's a photo of their outlet, because their switch is so subtle it just looks like a circle and gives no sense of scale.

Or, go with a 100% low voltage solution which you can control with switches from automotive or industrial, you can use touch, proximity, whatever you want and you don't need boxes, covers, etc.
 .
Some electronic switches have very limited current capacity so you'd have to use a relay as with the next suggestion for 120V lights.
Or, with 120V lights use relays.  See this answer to my question about controlling a closet light.   You could use the same relay, which would have to be installed in the light's junction box, and a pair of LV wires going to wherever you want the switch.  You could use that relay's included magnetic reed switch, hidden in the plaster of your wall, with a clever and pretty magnetic toggle that you design.  Or you could replace the reed switch with any kind of switch at all.  Doorbells, Automotive, electronic, you could put capacitive switches in the frames of your art, foot plates, you name it.

Or Put motion sensing switches (normal 120V ones in normal boxes) in the ceiling above your art.
Comment: How is your first suggestion legal? It's apparently not accessible.
Comment: I seriously doubt that any electrical or fire inspector would accept that as a procedure.
Comment: @isherwood "apparently" is their whole convoluted, expensive gimmick.  It does look nice though.  I can't speak for every inspector of course.  It's easy for me to paste a link. :)
Comment: Insanely expensive is correct, and now that I'm conscious of the accessibility issue it's a non-starter - beautiful as it is. Regardless of whether it would pass or not, I'd rather comply with intent of code. The LV relay and magnetic reed switch has my mind racing though.
Comment: For the record, I did not expect OP to select the 22 Systems switch.  I thought it had to be part of the answer because it suits the question so perfectly.   But a relay and a magnetic switch hidden in the wall opens the door to clever, beautiful and thematic ideas for someone looking to complement their art displays.  There's a whole industry of switches for home flight simulators and [rocket ships](https://www.concordaerospace.com/collections/project-apollo) ... depending on what imagery you want to invoke, you could use anything if it's LV.
Comment: @isherwood excellent point! However, on their website, the have a [removal guide](https://resources.22system.com/22System-RemovalGuide.pdf) (PDF). You simply pull the plug/switch out of the wall using their installation/removal tool (at only $80, it's a bargain!). They claim that, "An installation tool is required for each 22 System installation (sold separately)." So it's a heck of a profit center for them, too! It does mount to a standard wall box, the cover plate is embedded behind the finish material and the tool allows "easy" removal for wiring access. (con't...)
Comment: Loads of gotchas, like each device must be served by one set of wires, so no daisy-chaining devices - there's got to be a box elsewhere with all the junctions and each one must be at the end of the line. The price ($190-265 per switch) is just the beginning!
Comment: They are UL & cUL (Canada) certified according to their web site.   I'm not trying to promote these and I can't speak for inspectors.  They are legitimate to some extent and they seem relevant to the question.  I would leave it to OP to determine practicality and local acceptability .... Edit: which I see has has done :)
Comment: Ah, glad you found it, @jay613. In my quick perusal, I did not. I retract my comment.
Answer: Use smart spots. You can buy smart spots that can be operated with small battery powered remote switches that just send a radio signal. I use zigbee, that standard that is also used by Philips Hue and Ikea Tradfri because I think it is one of the most stable ones. It also gives the option to dim the spots or change white balance or color, depending on which spots you buy.
Answer: It's not readily available (or certified) outside Aus/NZ, but Resene SmartTouch or a similar product could work.
It uses a conductive paint with a cable back to a control module (which could be located behind a normal light switch, or e.g. in a box in a ceiling space). Capacitive coupling is used to detect when people touch the surface, similar to touch lamps or cellphone screens.
That area could be an unmarked area of wall, or something visible with e.g. a colour change, a symbol, or a sticker.
https://www.youtube.com/watch?v=92RfqQ7PffU
https://www.youtube.com/watch?v=yfT5AVvfu6Q


Minecraft from an old laptop to a new one

Question: How do I get Minecraft on my new pc after buying it on my old one that got fried without having to pay for it again?
Comment: You should be able to sign into Minecraft on the website and download it again without having to pay. (I may be wrong though).
Answer: Minecraft is account-based. Download Minecraft off minecraft.net and just sign in with your account.


What is the relationship between docutils and Sphinx?

Question: There seems to be a plethora of documentation tools for Python. Another one that I've run across is epydoc. It seems like Sphinx is the de facto standard, because it's used to generate the official Python docs. Can someone please sort out the current state of Python's documentation tools for me?
Comment: Maybe you should edit the title of this question.
Comment: Current State?  What does that mean?  Can you expand on that?  Sphinx requires docutils; epydoc can use the same RST notation.  What do you want to know?  Can you be more specific?
Comment: eg what tools have strong community support, active development? Is there an incumbent solution, or are there many with none having significantly larger following?
Answer: epydoc and Sphinx are different types of tools.
They are the same in that they:

Both use ReST via docutils.
Both are very Pythonic in their focus
Both can generate HTML and PDF documentation

They are different in their focus.

Epydoc is focused on API (Developer) documentation.  You get more results quicker with Epydoc.  You point it at your source code and you get something.  This is what I want from an API documentation tool.
Sphinx is focused on general (User) documentation.  While Sphinx does pull a lot of information from your source code you need to put a little more into it.  Sphinx can generate API documentation but, it's not as straight forward, and IMO doesn't do as good of a job as Epydoc.  I know some will disagree because Sphinx is chosen for Python. BUT, it depends on how much work you want to put into it.  I do love Sphinx for general documentation.

So it depends on how much work you want to put into it and what you are documenting.
Comment: Sphinx is not focused on general User documentation. Sphinx is a tool which helps you write a complete and detailed documentation, which you simply cannot provide by concatenating docstrings. Also Sphinx will support so-called domains with 1.0 which will allow you to document a project written in multiple languages for example a webapp written in Python, Javascript and C.
Comment: Well, the easy answer to why one is better at one thing that another is that is the way they were designed.  Epydoc is made to just pull from the code and Sphinx is made to generate a lot of it's documentation from ReST files you write.   There is a lot of overlap.  Sphinx is the new kid on the block.  I've heard rumors that in .7 it will have much better auto-generation built in.  I have a lot of respect for Epydoc but Sphinx seems to have all the momentum right now.  I like it because it looks like the python.org documentation AND I think it looks better.
Comment: Thanks for explaining what these tools have in common (eg their relationship to docutils) as well as their differences. What makes epydoc better for API documentation and Sphinx better for functional documentation? You mentioned that they both use reST. Seems like there's alot of overlap. Is it just a matter of convenience? Also, epydoc development doesn't seem to be very active. The last commit was in Feb 2009, and the last correspondence on the devel list was in May 2009.
Comment: I was about to ask for pointer on how Sphinx generates API docs and then I found [this](http://www.gossamer-threads.com/lists/python/dev/726475) post of yours. `sphinx.ext.autodoc` *doh*. Thanks.
Answer: I recently changed from Python2 to Python3 and found that there was no Epydoc package for Python3. So it seems with Python3 there is a clear focus on using Sphinx as API documentation.
Answer: It seems like Epydoc is, if not dead, at least pining for the fjords.
Sphynx with the sphinx-apidoc command and the autodoc extension looks to be the most popular option for API docs at this time.
Good examples are:

requests (src)
boto (src)

See: Should we use Epydoc, Sphinx or something else for documenting Python APIs? (SO5579198)
Sphinx encourages a more narrative style than tools in the javadoc mold, but maybe this is a good thing?


QGraphicsScene::items returns no items for a given rect

Question: I'd like to select all items within a certain area and change their opacity. I'm using QGraphicsScene::items() to do this, but I can't seem to get it to return any items. An example:
#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QDebug>
#include <QKeyEvent>
#include <QGraphicsPixmapItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
  , scene(new QGraphicsScene())
{
    ui->setupUi(this);

    ui->graphicsView->setScene(scene);
    ui->graphicsView->installEventFilter(this);
    ui->graphicsView->show();

    for (int y = 0; y < 20; ++y) {
        for (int x = 0; x < 20; ++x) {
            QPixmap pixmap("desert.png");
            QGraphicsPixmapItem* newItem(scene->addPixmap(pixmap));
            newItem->setPos(x * 25, y * 25);
            newItem->setOpacity(0.0);
            qDebug() << newItem;
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
    delete scene;
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Space) {
            QRectF rect(0, 0, 25 * 3, 25 * 3);
            QList<QGraphicsItem*> items(scene->items(rect, Qt::ContainsItemBoundingRect, Qt::AscendingOrder));
            qDebug() << items;
            foreach (QGraphicsItem *item, items) {
                item->setOpacity(1.0);
            }
        }
        return true;
    }
    return QObject::eventFilter(obj, event);
}

I'm pretty sure that I don't need to supply the deviceTransform argument, and I know that the rect I'm passing in should cover 9 tiles. What am I doing wrong?
Answer: When creating the items, you already set their opacity to 0 so that they are not visible -  items() returns visible items only, see http://qt-project.org/doc/qt-4.8/qgraphicsscene.html#items-10:

Returns all visible items ...

Set the opacity to a value > 0 in your constructor, e.g.
newItem->setOpacity(0.001);

When now pressing the space bar, the four items in the given rectangle will appear.
Comment: Thanks Andreas. Is it just me or is this not explained anywhere? I can see from your link that it mentions "all visible items", but the definition of visible does seem to include transparent items.
Comment: I have not yet checked further - maybe that is an optimization in QGraphicsScene which assumes that a completely transparent item is invisible by definition ...
Comment: The documentation (5.0) will be updated with clarification soon.


Upload image to web server

Question: I want to upload UIImage to web site.I have implement some code.I have selected image from first page and upload on second page.where in this -----[body appendData:[NSData dataWithData:_imgData]];---- the _imgData becomes nil. enter code hereI have already written some code, but I don't know Where is my mistake.
    My Code is:

           -(void)ImgaeCropped:(UIImage *)image
    {
        _imageView.image=image;

        Register2 *reg2=[self.storyboard instantiateViewControllerWithIdentifier:@"Register2"];
      //  reg2.self.selected_image=_imageView.image;

        reg2.imgData=imageData;

        picture_view.hidden=YES;
    }

    - (void)imagePickerController:(UIImagePickerController *) Picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        @try {
           // transparent_view.hidden=YES;
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            [indicator startAnimating];
            indicator.frame=CGRectMake(0, 0, 10, 10);
            indicator.center = CGPointMake(CGRectGetMidX(_imageView.bounds), CGRectGetMidY(_imageView.bounds));
            [_imageView addSubview:indicator];
            [indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
            [indicator setColor:[UIColor grayColor]];
            [indicator startAnimating];

            [self dismissViewControllerAnimated:YES completion:^ {
                [indicator removeFromSuperview];
                [indicator stopAnimating];
                CropViewController *crop=[self.storyboard instantiateViewControllerWithIdentifier:@"CropViewController"];
                crop.cropDelegate=self;
                crop.image=[info objectForKey:UIImagePickerControllerOriginalImage];

    //           UIImageView *imgvUserImage = [[UIImageView alloc]init];
                UIImage *imgvUserImage= [info objectForKey:UIImagePickerControllerOriginalImage];

                imageData=UIImageJPEGRepresentation(imgvUserImage, 0.9);

                [self presentViewController:crop animated:YES completion:nil];
            }];

        }
        @catch (NSException *exception) {
            //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish Picking" message:exception.description delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            //        [alert show];
        }
        @finally {
            //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish Picking" message:@"Final" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            //        [alert show];
        }

    }

And the image selection code is ---------------

-(void)ImgaeCropped:(UIImage *)image
{
    _imageView.image=image;

    Register2 *reg2=[self.storyboard instantiateViewControllerWithIdentifier:@"Register2"];
  //  reg2.self.selected_image=_imageView.image;

    reg2.imgData=imageData;

    picture_view.hidden=YES;
}

- (void)imagePickerController:(UIImagePickerController *) Picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    @try {
       // transparent_view.hidden=YES;
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [indicator startAnimating];
        indicator.frame=CGRectMake(0, 0, 10, 10);
        indicator.center = CGPointMake(CGRectGetMidX(_imageView.bounds), CGRectGetMidY(_imageView.bounds));
        [_imageView addSubview:indicator];
        [indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [indicator setColor:[UIColor grayColor]];
        [indicator startAnimating];

        [self dismissViewControllerAnimated:YES completion:^ {
            [indicator removeFromSuperview];
            [indicator stopAnimating];
            CropViewController *crop=[self.storyboard instantiateViewControllerWithIdentifier:@"CropViewController"];
            crop.cropDelegate=self;
            crop.image=[info objectForKey:UIImagePickerControllerOriginalImage];

//           UIImageView *imgvUserImage = [[UIImageView alloc]init];
            UIImage *imgvUserImage= [info objectForKey:UIImagePickerControllerOriginalImage];

            imageData=UIImageJPEGRepresentation(imgvUserImage, 0.9);

            [self presentViewController:crop animated:YES completion:nil];
        }];

    }
    @catch (NSException *exception) {
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish Picking" message:exception.description delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //        [alert show];
    }
    @finally {
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Finish Picking" message:@"Final" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //        [alert show];
    }

}

Comment: And what's your problem with it?!
Comment: Sorry, we don't want to guess your errors. Voting to close.
Answer: add the AFNetworking to your project
https://github.com/AFNetworking/AFNetworking
 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = @"Loading";

NSMutableDictionary* data=[NSMutableDictionary new];
//if you want to add parameters with the image
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = responseSerializer;

AFHTTPRequestOperation *op = [manager POST:@"http://www.pickkup.com/webservice/uploadpictureios.php" parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"image" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    [hud hide:YES];
    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [hud hide:YES];

    NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];

[op start];

Upload image to web server


How to separate Arabic with alphabetical?

Question: If you try this link https://jsfiddle.net/u4bxz74c/10/. Later the result will be like this
PART 1

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

PART 2

This is a samplasde textssss فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

Question PART 1 : If you see the code below, all paragraphs or
 are class="ENGLISH".
How to make it into a paragraph or
 class="ENGLISH" to be class="ARAB", if the writing in a paragraph is Arabic? But if the writing is not Arabic, so the paragraph of class="ENGLISH"
PART 1

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

*****     I WANT TO BE LIKE THIS     *******

This is a samplasde textssss

فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

Question PART 2 : But if the Arabic joins with plain writing or regular fonts. So paragraph or
 remain class="ENGLISH"
Like this

 This is a sa   لْيُسْرَى ثُم تَشَهدْ

  لْيُسْرَى ثُم تَشَهدْ This is a sa

 This is a sa  ا لْيُسْرَى ثُم تَشَهدْ This is a sa

  لْيُسْرَى ثُم تَشَهدْ This is a sa   لْيُسْرَى ثُم تَشَهدْ

Note: I've tried this code, but it seems, this code encapsulates the entire contents of the textarea
if (pattern.test(newText)) {
    str = newText.replace($format_search[i], $arab_format_replace[i]);
} else {
    str = newText.replace($format_search[i], $format_replace[i]);
}

Answer: You can create a RegExp pattern from string "abcdefghijklmnopqrstuvwxyz " with RegExp() constructor with case insensitive flag i; iterate elements using a loop; if .textContent of element begins with one of the characters of string cast to RegExp  or every character of element .textContent is one of the characters within RegExp, set element .className to "ENGLISH", else set element .className to "ARAB".
Note that id of element in document should be unique. Also,
 is not a valid child element of
 element.
Substituted class="posttextareadisplay" for id="posttextareadisplay" at parent
 element and  for child
 element.

const en = "abcdefghijklmnopqrstuvwxyz ";

for (let el of document.querySelectorAll(".ENGLISH")) {
  if (new RegExp(`^[${en.slice(0, en.length -1)}]`, "i").test(el.textContent)
     || [...el.textContent].every(char =>
          new RegExp(`${char}`, "i").test(en))) {
    el.className = "ENGLISH"
  } else {
    el.className = "ARAB"
  }
}
PART 1

    This is a samplasde textssss
    فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

PART 2

    This is a samplasde textssss فَإِذَا جَلَسْتَ فِي وَسَطِ الصلَاةِ فَاطْمَئِن، وَافْتَرِشْ فَخِذَكَ الْيُسْرَى ثُم تَشَهدْ

Comment: If using your code, work but not yet typed anything. But if I try typing in textrea column. Thus, the Arabic returns to `ltr` https://jsfiddle.net/u4bxz74c/11/
Comment: Typing was not part of text of either question at OP.
Comment: Oh, I mean, what if to enter function on `function arabtanpaparaf(str)`


"Continuous dehumidifier" randomly fills bucket and stops. Why?

Question: Several "continuous" dehumidifiers all had the same problem.  There is a bucket to collect water, and also an outlet for a hose where the water can flow out so water does not collect in the bucket.  With a hose connected, from time to time, the bucket does fill up with water and then the float switch stops the machine.
I had this problem with 5 machines from 3 manufacturers over the last 15 years.  With each one:

The hose is not blocked.  Water does flow from the unit into the drain.  After I empty the bucket water continues to flow.  The bucket does not immediately start to fill up again .... but sooner or later, weeks or months, it does.
I place the dehumidifier up on blocks and the end of the hose inside a sump pit, so there is about 3 feet of vertical fall through the hose.  The hose is not very long.  About 6 feet.  It does not coil or rise back up at any point.

My point is, there is no blockage.  There is something that causes water to enter the bucket and fill it up under certain circumstances.
There must be something about the design of all these that is causing this.. Any clues?
(I've had Frigidaire, Delonghi, Kenmore).
[Edit] Adding some pics and thoughts on answers and comments
I disassembled several of the units, and they all used the same simple system to select hose or bucket: There is drip tray to collect moisture and the tray has two outlets, one higher than the other.  The lower outlet goes to the hose.  If it is sealed with a cap it fills up, and the water rises to the level of the higher outlet that goes to the bucket.  It's impossible to photograph this without destroying the machine so here is a diagram:

Answers to questions in comments:

Is there a valve that might be failing?  No
Is the hose big enough?  Yes, it's a regular garden hose.  The flow varies but at its greatest it's a fast drip.
Ice because of dirty filter?  No.  I clean my filters regularly and at the most recent occurrence it was clean.
Ice because of low temp environment ?  No. It's a basement in the summer.  About 70 degrees and 55% RH all the time (except after the bucket becomes full).
Ice, we don't know why?  This one is intriguing me.  It's the only viable explanation so far.  The only way for the water to rise to the bucket outlet is for the hose outlet to be blocked.  The only way for the hose outlet to sometimes randomly be blocked, but never when I'm looking, is ice.  I have to think about this one.
Hose not tight enough?  That's not the problem.  In my current unit, and at least one other one, the hose outlet is outside the cabinet.  If it were loose the water would drip on the floor.

[Edit 2] Leading theories
Some truly enlightening discussion in the answers and comments here.  I'm going to summarize the leading theories that I intend to test through experimentation in the coming weeks:

Negative Pressure at the continuous flow exit hole produces an inflow of air that prevents water from dripping out.   Water collects in the pan. It drains out between cycles or, if there is enough humidity, it backs up to the point that it drains out to the bucket.  The bucket exit hole is vertical, and it is usually larger than the continuous hole so it does not suffer the same problem.
The negative pressure theory would be exacerbated by a dirty filter, and by periods of high humidity such as after a storm, and by setting the machine's fan to run continuously rather than in cycle with the dehumidification.
Gunk buildup in the hose limits outflow, normally not significantly but during periods of peak humidity the limitation is enough to cause water to back up and overflow the pan into the bucket.
Possibly the two above things combine.  Possibly gunk buildup near the continuous exit hole increases air inflow velocity to exacerbate the problem.
Possibly a P trap in the exit hose will help.
Possibly flushing the exit hose periodically will help.  Maybe manually annually, or maybe by connecting the hose to the bucket instead of the hose connection, as described in one of the answers.

[Edit 3] An update, one month later
Edit 3 is 33 days after Edit 2.  I've been watching the bucket level indicator daily.  We have had a couple of rain storms over the past month where there was more moisture in the basement walls and air than usual.   The bucket remained empty throughout.  Not a drop of water in the bucket, ever ... until today.  Between yesterday and today, the bucket filled up and the machine stopped.  It was a bone dry day.  It rained lightly yesterday, nothing special.  Temps are in the 70s.  I checked the hose, and ran water through it from a garden faucet ... it's completely clear and unobstructed.
I can positively say that high humidity, ice, and gunk are not the cause. of the bucket filling up today.
The only remaining theory is negative pressure.  This is corroborated by my internet tutorials on a similar problem with central A/Cs.
I have created a makeshift "trap" for my unit using its cord keeper.  It will be hard to say conclusively if this is working or not, since I cannot correlate this with weather or anything else, and it's quite normal to go more than a month without the problem.  But we'll see.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/129417/discussion-on-question-by-jay613-continuous-dehumidifier-randomly-fills-bucket).
Comment: I have ruled out ice, gunk, and wet weather as being causes of the bucket filling up.  The only remaining theory is negative pressure, and while the randomness of it remains unexplained, I've added a trap as explained in an update to the question.  TBD.
Answer: This sounds like a leak at the internal connection from the bucket drip point to the hose adapter.
Internally, our Artic King dehumidifier has a small pipe coming out of the dehumidifier over the bucket. It also has an attachment to convert the unit from bucket to hose. The attachment consists of a plastic flange for the hose to attach to and a short piece of flexible plastic hose that press-fits over the bucket drip pipe. The plastic hose is only press-fit and I see how it could stiffen over time, no longer press firmly over the bucket pipe, and start leaking into the bucket.
Comment: Yup, that's what it is.  Hose leak right at the coupler, or faulty gasket in the coupler, or in my case a limp wrist doing the tightening.
Comment: The problem with my current unit and at least one previous one is not a loose hose or gasket.  I can't be sure about every one of the units that did this, but in my current and previous one the hose outlet is outside the cabinet.  A loose or faulty fitting would cause water to drip on the floor, not in the bucket.  Will add photo to question.
Comment: To further clarify, one of my previous units had a "hose adapter" that INTERNALLY screwed into the machine but my current and all other ones had a hose "outlet", fully and permanently integrated into the inner drip tray and sticking outside the machine where the hose attaches.
Comment: The design in your pictures is different from my unit, so it appears that a loose internal hose may not be the problem, at least on the present unit.
Answer: Here's one further possibility: an ice blockage.
If the airflow is too weak (dirty filters, externally obstructed, or a failing fan), or the humidity very high at fairly low temperature, ice builds up on the coils.  Then the heat pump cuts out, but the fan might keep running.  The ice should melt and drip, but it can come off in lumps, and those can block the hose outlet.  They'll melt by the time you can strip the machine down.  I've had the same effect cause an intermittent leak onto the floor because the outlet from the drip tray to the bucket  blocked.
Comment: I too had exactly this happening to me. The basement was about 20 °C (68 °F) but humidity was high, being near the seaside - 60% to 80% all the time. Luckily, my drip tray was 5 cm deep, so I could just stopper the drip tray outlet without risking flooding the floor.
Comment: @jay613 in my case, I saw a large ice shard floating in the tray, being sucked against the hose outlet and sticking there.  I had a DeLonghi with "de-icing" system, it heated the cold coil somehow so that instead of slowly melting, the ice would just fall down in solid form. Who knows, maybe protecting the area with some large-mesh steel net would have worked too. By stoppering the other outlet, the water accumulated in the tray and the ice had time to melt down, or maybe it was just floated upwards, unblocking the hose. But you're right, a shallow tray would have flood the floor.
Comment: Ice.  Hmmm.   Random occurrence, never when I'm looking, comes and goes.  This is a good lead.  It's not as simple as "high humidity at low temp" because this is a basement, in the summer, with a dehumidifier so the temperature and humidity is fairly constant.   But maybe something is causing the hose exit hole to ice up.
Comment: @LSerni could you determine what was causing the water to a) stop flowing through  the hose and then later b) start again?     Otherwise, if you plug the drip tray drain, and the hose has this problem, the water will eventually go on the floor.  Can you explain any more?
Answer: If the dehumidifier uses a pump to actively remove water from the collection bucket, then it could be an issue with the controls system. We had a cheap dehumidifier that had to be set explicitly to "continuous mode" before it would employ the pump. Unfortunately if the device lost power at any time, it would forget and reset itself to the default "bucket mode" when it booted back up.
The solution was to return it and buy a more expensive brand that the manufacturer confirmed would remember its settings between power cycles.
This problem seems less likely if your system relies on gravity to drain, but it's still possible that there is some electronically controlled valve that's getting shut off.
Comment: good old market segmentation right there. Buy a more expensive one for something it should be able to do anyway.
Comment: My cheap one just uses fluid flow to select continuous or bucket.  If the water can get out the hose hole, it will.  Simple and foolproof, unless the fool loses the screw cap for the hose fitting
Comment: One of my dehumidifiers had a pump option that I never used.  None of the others even had a pump.  The problem I am describing is with units that employ gravity.  As @ChrisH describes, and I'll add a diagram to the question soon ... if the water can fall out the hose it does, but if it's capped off the water backs up and falls out another hole into the bucket.
Answer: Having had this many times on various dehs over the years it seemed to be a consequence of the drain hose becoming blocked with some sort of slime that presumably grew in the presence of moisture and dust in the circulated air that would contaminate the condensate
The slow flow experienced by a relatively narrow hose seemed to further exacerbate the problem as did the small amount of water emitted regularly in continuous drain mode. In the end I made a modification to the bucket that resolved things and have since run a deh for several years without tending to it at all:

I drilled a hole in the side of the bucket (blue), below the maximum water level (yellow) defined by the float mechanism that shuts off the deh, and slightly smaller than the hose (red) outer diameter, so that the hose made a good seal when pushed through the hole. The end of the hose was cut at an angle to prevent it sucking flat against the base of the bucket. The deh was placed higher than the end of the hose outlet (only about 6 inches; deh on a worktop next to a sink).
The deh would dump into its bucket continuously, eventually filling the bucket to a level where a siphon started down the hose, at which point the hose would rapidly empty the bucket. The higher velocity of the water seems to keep the inside of the hose clear of slime and also cope with any slime in the bucket; far from the hose there appears to be some buildup on the bucket floor but near where the hose picks up it's relatively clean..
Comment: I like this idea.   Although, if the explanations here are correct it might be better to just flush or replace the hose a couple of times a year.  The fact you've had it running reliably for years is great.
Comment: Looking at the discussion in another answer about using a P-trap, I wonder if the problem you solved here was not "flushing the pipe" but rather, avoiding the negative pressure problem?  And if it would be sufficient to install a P trap on the usual continuous flow connection and flush the hose manually once a year or so.  I'm going to experiment.
Answer: I want to give Glen Yates the credit for cracking this (at least for my situation, which may or may not be the same as the OPs) but his comment on the question about p-trap put this together for me.  My basement is pretty damp without dehumidification.  Better drainage has helped but if I don't run a dehumidifier 3-seasons of the year, my tools rust, and anything that absorbs humidity like paper or cardboard will be damp to the touch.  I've dealt with a number of issues like the tilt of the dehumidifier, pinched hose, clogged hose, etc. and it works reliably now, with one particular exception: when we get heavy rains, I have learned that I need to go down and check the bucket.  It will often be filled and the dehumidifier stopped.
This didn't make sense to me.  How could it be that the dehumidifier was pulling more water out of the air than a garden hose can handle?  But then Glen mentioned a p-trap.  And I looked into it and it all makes sense.  The p-trap on a AC unit is there to prevent air from coming into the unit through the condensate drain as described here:

Since the Air Conditioner is at a negative pressure relative to the outside air, the outside air will rush into the air conditioner through any openings (the condensation drain, is an opening).  On our A/C the air rushing in through the condensation drain was preventing the water from exiting through the drain.

Now it makes sense why I'm seeing that.  A dehumidifier is very similar to an AC unit.  If it's pulling air through the drain line, water can't exit through it and it ends up in the bucket.  In normal circumstances, the unit will cycle frequently enough that the water doesn't reach the level required to go into the bucket (per your drawing.)  But if it's running continuously for a long time, there's no pause in the negative pressure and it will drain to the bucket and then stop running once it's full.
So I'm going to be hooking up a p-trap on the drain connection of my unit.  Maybe this will help you as well.  I found this page which has a lot of technical details around p-traps and includes this helpful image:

Initially I wrote that I thought the image is inaccurate because water will find it's level.  But if it's under negative pressure, perhaps the image shows the amount of water column height needed to keep it from being pulled into the pan.  I just had this happen again and it was after a heavy rainfall that lasted for multiple days.
Comment: "If the negative pressure were enough to suck water back up the pipe, it would also suck the water off the evaporator and blow it back into the house." Sorry busy morning and I just looked more closely at this.  I don't think the negative pressure is enough to suck water up the hose/pipe.  A p-trap wouldn't help if that were the case.  It's air that's being pulled in.  Water is 400x heavier than air.  That airflow back into the pan prevents water from going into it.  Keep in mind, there's no water column in the pan to hold back the air which is what the p-trap creates.
Comment: @jay613 "why does the negative pressure (if that is the reason at all) SOMETIMES prevent water exiting but not always?" That's actually what clicked on the lightbulb for me.  Most of the time, my dehumidifier runs for a while, then stops, runs again, stops, etc.  When that's happening, there are no issues.  It's only when it's running nonstop all day that I get water in the bucket.  So the hypotheses is that when it's running, it's collecting in the  drip pan, and shuts down before it goes above the 2cm or so that causes it to drop into the bucket.
Comment: "The exit hole to the bucket should suffer exactly the same fate. If the fan is on constantly (as I believe it is)" I think it's the fan that causes the negative pressure so if your fan is running constantly, that would suggest this is not a viable theory.  Mine does not run constantly.  One thing that is different is that the hole to the  bucket is positioned vertically and the hole to the drain is horizontal.  Imagine blowing air in each and which would be easier to stop water flowing from.  Also, it might not be all or nothing.  Maybe the drain is just slowed enough to back up.
Comment: I added a makeshift trap by simply looping the hose as shown in my last question edit.  The problem has not recurred in **a year**.   Test successful.  Answer marked correct.
Comment: @jay613 I was thinking that it would need to be filled but I realize now that as long as you don't have the continuous run issue right off the bat while it's dry, it should fill on it's own.
Comment: @jay613 Why would it matter if the air was from the outside of  the house or not with regard to causing negative pressure within the drip pan?  Consider the next sentence after the quote above: "So water was building up in our A/C unit and when it would turn off "Woosh…"  All that water would pour out of any hole it could find!"  The p-trap stops air from going in.  For AC there are two reasons for that: to improve efficiency and to allow water to escape.  The former is not relevant here but the latter is.
Comment: I just watched this video demonstrating your point. https://www.youtube.com/watch?v=6P-0Ix-bmdU.     I really need to take a close look at my dehumidifier now, and think about how and why A) it EVER drains, given this theory about negative pressure, and B) it sometimes does not drain, perhaps during high humidity periods as discussed here .... why does the negative pressure (if that is the reason at all) SOMETIMES prevent water exiting but not always?   Thanks for the thought-provoking answers!
Comment: I have to look at whether my new dehumidifier is set to run its fan constantly or only when dehumidifying.   If the fan shuts down between cycles that would strongly support the negative pressure theory.  Water would drain between cycles.  If the air is too wet, that will never happen.  On the other hand, why then would the water drain down into the bucket?   The exit hole to the bucket should suffer exactly the same fate.  If the fan is on constantly (as I believe it is) the question remains, why does it EVER drain if negative pressure is the culprit?
Comment: No more comments from me here because I'm afraid someone will move it all to Chat and I like it here.  I've consolidated these ideas in an edit to the question.
Comment: See Edit #3 to my question.  Negative pressure is the only surviving theory.  Testing it now.
Comment: @jay613 I Love the loop solution.  Did you fill the 'trap' with water when you set it up?
Comment: I don't remember if I prefilled it.   I guess in theory the trap could dry up over the winter and fail to prime itself when it becomes humid again in spring.  But that test will take several years.   I guess it would be good to establish a spring maintenance routine: check the bucket, clean the air filter, fill the trap, change the batteries in the (separate) nearby leak detector.
Comment: I like to have the fan on continuous run but this unit I have now doesn't have a setting for that ... so the trap is working.  :)
Answer: I've seen gelatinous blobs of some kind of fungus living in a dehumidifier. You might have one of these blobs occasionally getting big enough to block the channel that leads to the the drain hose, backing up the condensate until it spills into the tank.
Unscrew the hose and have a look into the nipple with a flashlight to see if something is growing in there. If you can see the drainage channel from another angle, that would be helpful. If something is growing in there, it's time for a cleanout. Follow your dehumidifier manufacturer's instructions for cleaning and sanitizing the unit.
Comment: I've seen that gunk too in my older machines, but I determined that they were NOT blocking the exit or the hose.   I tested for that.  Also, my current machine is less than two months old and has absolutely no mold, fungus, dust or anything else collecting or blocking anything.   I've already had the problem twice.   But note, the hose DOES WORK.  If it were not working, the bucket would fill up several times a week.


HTML content with reference to javascript object attrtibute

Question: Is there a way in javascript to make this work?
<code>// define an user class
var User = function (name) {
    this.name = name;
}

// create an user object
var user = new User('John');

var anchor = document.createElement('a');

anchor.innerHTML = user.name;
// add the anchor to DOM
document.body.appendChild(anchor);

// change the user name
user.name = 'James';
</code>
After this, the html of the anchor changes the content automatically
because its holds a reference to object user. Maybe this sounds dumb, but what I thinking is if is there a way to DOM watch any changes on its values through object reference.
Many thanks.
Answer: This will not work. You need to update the innerHTML manually to reflect the value. You can use clever frameworks like AngularJS for this to taken this manual action away.
Comment: Yeah, I thought about angular, it's a good choice. But I was trying to figure out a solution without an entire framework, thinking about a quick solution with pure javascript, but seems there is no way out. Thanks for your answer.
Answer: You can't use the DOM to watch for this because you are looking for when a property of an object changes.
You can watch for that by using a property with a setter function instead of a plain one.

<code>// define an user class
function User(name) {
  this._name = name;
}

// Add some functions to watch variables and play with the DOM

Object.defineProperties(User.prototype, {
  add_to_dom: {
    value: function add_to_dom(parent_element) {
      this._parent_element = parent_element;
      this._text_node = document.createTextNode("");
      this._parent_element.appendChild(this._text_node);
      this.update_dom();
    }
  },
  update_dom: {
    value: function update_dom() {
      this._text_node.data = this._name;
    }
  },
  name: {
    get: function() {
      return this._name;
    },
    set: function(name) {
      this._name = name;
      this.update_dom();
    }
  }
});

// create an user object
var user = new User('John');
var anchor = document.createElement('a');
document.body.appendChild(anchor);
user.add_to_dom(anchor);

// change the user name
user.name = 'James';</code>

For larger scale approaches, you might want to look into tools like React.
Comment: Thanks for your answer. This is a good solution, but as you and Bas Slagter said, the best choice would use a tool that do it for me, since there is no quick solution.
Answer: You have to make seomthing like MVC (Model, View Control)
Your user class ist the Model
Your HTML Element is a view
What you need is a controller, which controls the changing of the value


Is a Func always the same object?

Question: Basically, if I do something like this ...
class Bla
  T Run(Func<T> myFun)
    return myFun()

  void SomeMethod()
    Run( () => whatever() )

and then myFun always the same object, or a new object each time? Or formulated in a slightly different manner ... if I would put a lock on it, would it prevent parallel execution?
Comment: If you don't know how an object got created then you can *never* be sure that the object is suitable to store the lock state.  True for GetType(), true for *this*, double-true for a method argument, triple-true for a delegate object.  Always, *always* create your own object with `new object()`.
Comment: Are you asking if `() => whatever()` creates a new delegate object each time?
Comment: @LasseV.Karlsen: yes.
Answer: This:
() => whatever()

creates a new delegate object every time.
That means that if two threads both call SomeMethod at the same time, then each of them will construct their own delegate and putting a lock inside Run will not ensure only one thread can run the delegate passed to its Run.
You can test this in this .NET Fiddle.
Comment: Damn, thought as much, but was hoping I was wrong. Also neat site there, didn't know that one.

Is a Func always the same object?


How to filter list in AngularJS by variable

Question: I have what should be a very simple task. I want to sort a drop down menu in angular based off of a given parameter. Should be easy.
I make a call to a dataservice the returns some data like so:
"success" : true,
    "data" : {
        "this_status" : [{
                "DefNo" : "111*A",
                "Com" : "111",
}, {
                "DefNo" : "222*B",
                "Com" : "222",
}, {
                "DefNo" : "333*C",
                "Com" : "333",
}
];
        "this_info" : [{
                 "Req" : "MUST",
                 "DefCom" : "111",
}, {
                 "Req" : "NoMUST",
                 "DefCom" : "222"
}, {
                 "Req" : "MUST",
                 "DefCom" : "333"
}]}

My task is to make a list with all the DefCom values that also have an associated MUST value. I need to list "DefCom" numbers that have a "Req" that is "MUST", inside of a dropdown. So in my example, my dropdown would have values 111 and 333.
In my controller, I execute the call
   $scope.getDefCom = function(){
        MyAPIservice.getDefCom().success(function(response){
            $scope.info = response.data.this_info;
            $scope.infoList = $scope.info;
        });
        }

Where I have this factory:
angular.module('MyAPI.services', [])
  .factory('MyAPIservice', function($http) {
    var MyAPI = {};
    MyAPI.getDefCom = function () {
        return $http({
            method: 'GET',
            url: '/thisis/mylink/'
        });
    };

    return invoiceheaderAPI;
});

This works for my first initiative, make a drop down that will list DefCom numbers. However, next I need to filter them.
$scope.require = MUST in this example.
Inside my template:
<option ng-repeat="option in DefComList" value="{{option.DefCom}}">{{option.DefCom}} </option>

I tried doing a filter like so:
ng-repeat="option in DefComList | filter: {Req: $scope.require}"

However upon more reading I couldn't find anything where you can insert a $scope variable into a filter. Most of the suggestions leaned towards writing your own filter. I did this, using angular.forEach. My filter is below:
 $scope.filterDefs = function($scope) {
        var clrreturn = false;
        angular.forEach($scope.info, function(value, key) {
            if (value.DefCom == $scope.require)
                clrreturn = true;

        });
        return clrreturn;
    };

However, my custom filter is running before getting the results of $scope.info from the $scope.getDefCom function. This is throwing an Error: undefined is not an object (evaluating '$scope.info') before $scope.info is ready.  I know that this has to do with promises, so I tried writing in deferred promises. However, this didn't work either, and I have gotten frustrated because this seems like it should be a very simple task and I might be making it way harder for myself than it should be.
Answer: I feel you might be over thinking it; If I'm understanding what you want to do then all you should need in your filter is:
ng-repeat="option in DefComList | filter: require : true"

Note the true for exact matching as your search for 'MUST' would also match 'noMUST'.
Here is a quick fiddle I put together for you: https://jsfiddle.net/nqya24r4/
Also if you specifically only want to search the Req property, you can filter using an object instead of a string. Here's another fiddle demonstrating this: https://jsfiddle.net/t3bw5L5d/2/
I hope this helps.
Comment: Thank you! This works perfectly. I was definitely overthinking it, this is way easier than writing a custom filter.
Comment: No problem, glad to help!
Comment: With `ng-options` you could also do it like in this [jsfiddle](https://jsfiddle.net/awolf2904/0e5wfes3/).


Question about Grids and Layouts in UI Design

Question: grids and layouts are something that i've struggled with since starting my design career two years back. I've read books like grid systems and watched several videos and courses but as a UI designer, it feels like a lot of these resources aren't particularly catered towards my profession. Layout Essentials is next on my reading list, but judging from a quick flip through, looks to be still catered for graphic design.
I understand that grids for web design are fairly simple, and whenever in doubt, I can always fall back on the bootstrap columns, I'm not particularly sure about other cases studies such as desktop, TV or even car UI design. I get that we just need to define a column size, some dimensions for our margins and gutters and that's it, but my issue is coming up with these specific numbers in the first place. Any number I come up with just feels very arbitrary even when catered to the use case.
Wondering if someone could share their process on defining a grid when designing a desktop app, mobile app or website, or if there are any good books that can be recommended for grid systems in UI design specifically.
Answer: This article is great resource on why 8 is the magic number you are looking for.
The 8-point grid system is used for sizing, spacing, and laying out components relative to one another. This means that any padding, margin, button height, etc. is always a multiple of 8 pixels.
8-point or 8-pixels is widely used for the following reasons:

It scales perfectly in all the different screen displays (including android's @0.75 and @1.5)
It's a good basic unit to work with. the numbers 4 and 8 are easily multiplied, they provide flexible and consistent, yet distinct enough, steps between them
Apple and Google advise you work with them

Now looking specifically at designing within a grid, you can take this 8pt rule and apply it to your grid creation.
Fixed width grid
Using multiples of 8 find your column size. Let's use 8x9 to get 72. So you'll have 12 columns x 72. Now calculate your gutters. You could use 8x3 to get 24. That will look like 12 gutters x 24. You'll split the 12th gutter up on the left and right side to get 12px. Ultimately your grid calculation will be (12 columns x 72) + (12 gutters x 24) = 1152px width

Fluid grid
If you want your grid width to be fluid depending on the users screen size, you'll only need to to calculate your gutter size. The column width will ultimately be determined by the users screen size. In this case, I'd still advise calculating based on the 8pt grid. Ultimately your calculations will look something like this where n will change based on your screen size:

iPhone 11 Pro Max: (12 columns x n)+(12 gutters x 24)=414px
Macbook Pro : (12 columns x n)+(12 gutters x 24)=1440px

There are plenty more articles on the internet based on the 8pt grid. Ultimately, there is a bit of preference on what you feel comfortable designing with. With time will come experience and confidence in your designs and the choices you make. Good luck!


Can't remove twist-style / turn-style / knob cap on overflow drain in tub

Question: I have an American Standard brand tub with jets. Its drain has a pop-up stopper, and the stopper is controlled not by a lever, but by one of these twist-style knobs, placed over the overflow drain. I removed the screw holding the cap in place (see the right-hand picture), but no matter what I do, I can't pull the cap off:

I've looked around inside as best I could to see if there's some other mechanism holding it in place, but I don't see anything. I don't think this thing has been removed in 15 years. I've tried turning it this way and that, pushing it in and out in case there's some kind of special release. I've tried knocking it with a hammer to loosen things up or try to break up deposits. I've tried vinegar, and then WD-40. I've tried using big screwdrivers as levers between the cap and the plate behind it. Nothing, refuses to come off.
There's another question here from someone with a similar problem, but in their case, they couldn't get the screw out, and the problem wasn't answered anyway:
How to remove turn-style tub overflow cover?
Anyone have any ideas? Or does this need to be sawed off? Can a plumber handle this?
EDIT #1: here's a closer look at the area where the cap meets the stem--nice and gross:
Comment: Welcome to [diy.se]. Well done on your first post - you'd be amazed to see how many people don't include pictures. You _could_ saw it off, but that guarantees you'd have to replace it, but hang out - someone will most likely have a better answer for you.
Comment: From your new pic, I would _guess_ that this is supposed to pry off, but that 15+ years of gunk have built up to "weld" it in place. Try pouring something like [CLR™](https://clrbrands.com/Products/CLR-Household/CLR-Calcium-Lime-Rust-Remover) (_no particular endorsement, just a brand I'm aware of_) on it to see if that will help. You may have to get creative with a baggie full of it, placed over the knob and tied up to allow it to soak. Maybe a balloon would work (don't know, never tried, it may get dissolved by the chemicals) to hold the decalcifier in place.
Comment: have you tried spinning the cap?
Comment: @jsotola yup, the cap spins fine. But that's about all it does.
Comment: you may have to clamp the stem with needlenose pliers
Comment: @jsotola The cap seems fused to the stem. They spin 1 to 1. And I can't fit my needle-nose pliers into the gap between the cap and plate anyway, just tried it. I also tried just now to use a flathead screwdriver to chip at the meeting place between the cap and stem, just in case I could clear some deposit or loosen it etc, but nothin doin.
Comment: check the American Standard website for parts catalog ... there may be a drawing available which you could study ... you could also make a tool to clamp the stem  ... two parallel flat metal bars that would fit behind the knob, hinged together at one end ... the other end could be squeezed together with pliers or a bolt and nut
Comment: @jsotola you're suggesting I try to keep the stem from rotating (keep it still), while rotating the cap, to break the bond that way? The stem is round, and it's obscured by some other stuff, so I don't know if that's possible. I attached another pic to the original post to give you an idea. I'd also looked up parts info on American Standard's website, but can't find anything relevant. This thing is at least 15 years old, and I can't find the model number or any other info, unfortunately.
Comment: @FreeMan good call. I tried a few things, but no go. I ended up taking my anger out on the knob (see my own answer to post below). Then I tried soaking the thing in CLR, and even then it refused to come un-fused.
Answer: (Answering my own question.) After trying a million things, I went with the destructive option. I used a metal file to shave a hole into the knob so I could access the screws on the plate behind it. I unscrewed the screws, turning the knob to be able to access each screw, and then took the whole assembly out. Afterwards, I soaked the still-fused-together knob and plate in CLR for 10 hours, and by the end, it still didn't come apart. After looking closer, it might be the case that the knob was held in place by a screw on the opposite side of the plate, which, when mounted to the tub, is completely inaccessible unless you open up the wall behind the tub and cut into the overflow waste pipe. What genius designed this?
Comment: Thanks for providing your solution. Be sure to give yourself a check mark, too!