`ls` with wildcard with subdirectories

Question: When I execute a command ls *, it will show

files in the current directory
directories in the current directories
files and directories in the directories in the current directories.

When I do use ls I don't want to see inside the directories in the current directory. I'm bit confused because for more than 8 years I've been using ubuntu, I've never seen anything like this before.
Is this how ls should work? Is there a way to stop 3 from happening?
For example, if I have
file1.file
folder1
folder2
folder3
textfile1.txt
I want ls f* to show only
file1.file
folder1
folder2
folder3

Ubuntu 20.04 LTS
Comment: `ls -l -d *` should do what you want.
Comment: +1 for Doug Smythies's tip, or even simpler (with only the names) `ls -d *` and `ls -d f*`
Answer: You are expecting it to work like in MS-DOS, however, this is linux.
Wildcards in linux are expanded by your shell to match all items fitting the wildcards. ls does not see your wildcard. It only sees a list of file and directory names matching the wildcard. So it will show the contents of all items listed, i.e., the name of a file or the contents of a folder. In MS-DOS, wildcards would cause the dir command itself to filter the list to list only names fitting the wildcard.
To filter the output of  ls, e.g., to only see file and folder names  matching f*, use  grep, i.e., pipe the output of ls into grep like:
ls | grep ^f.*

^ and .* are regular expressions. ^f means: f but only at the very start. .* means . any character * any number of times.
Comment: Thank you for the answer. I don't know why this was never an issue for me until now.
Answer: One way is to use the find command instead of ls.  You can use -maxdepth 1 so that you don't read into folders, and use only the -name option for wild cards.
Example:
find . -maxdepth 1 -name 'f*'

Will return everything in the current folder . starting with a lower case f even folder names, but not show you any contents within the folder(s).

`ls` with wildcard with subdirectories


Kubernetes Executor : Task is receiving SIGTERM signal if it runs more than 5 mins

Question: I have airflow instance deployed on kubernetes cluster using bitnami helm chart with Kubernetes Executor. If I try to execute a task which takes more than 5 mins, Scheduler automatically kills that task.
I have already tried [this][1] but does not work
Scheduler Logs:
[2022-08-05 18:27:20,117] {kubernetes_executor.py:147} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e had an event of type MODIFIED
[2022-08-05 18:27:20,118] {kubernetes_executor.py:213} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e is Running
[2022-08-05 18:27:38,908] {kubernetes_executor.py:454} INFO - Found 0 queued task instances
[2022-08-05 18:28:39,212] {kubernetes_executor.py:454} INFO - Found 0 queued task instances
[2022-08-05 18:29:39,394] {kubernetes_executor.py:454} INFO - Found 0 queued task instances
[2022-08-05 18:30:39,575] {kubernetes_executor.py:454} INFO - Found 0 queued task instances
[2022-08-05 18:31:39,766] {kubernetes_executor.py:454} INFO - Found 0 queued task instances
[2022-08-05 18:32:10,603] {kubernetes_executor.py:147} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e had an event of type MODIFIED
[2022-08-05 18:32:10,603] {kubernetes_executor.py:213} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e is Running
[2022-08-05 18:32:11,436] {kubernetes_executor.py:147} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e had an event of type MODIFIED
[2022-08-05 18:32:11,436] {kubernetes_executor.py:206} INFO - Event: process1800.404b6cc740064e90955e28dd736f899e Succeeded
[2022-08-05 18:32:11,943] {kubernetes_executor.py:374} INFO - Attempting to finish pod; pod_id: process1800.404b6cc740064e90955e28dd736f899e; state: None; annotations: {'dag_id': 'kubernetes_pod', 'task_id': 'process1800', 'execution_date': None, 'run_id': 'manual__2022-08-05T18:26:58.893963+00:00', 'try_number': '1'}```

Worker Log

/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/configuration.py:357 DeprecationWarning: The base_log_folder option in [core] has been moved to the base_log_folder option in [logging] - the old setting has been used, but please update your config.
[2022-08-05 18:27:20,359] {dagbag.py:500} INFO - Filling up the DagBag from /opt/bitnami/airflow/dags/git_dataextractor-dag/docker_scraplimit.py
/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/kubernetes/volume.py:22 DeprecationWarning: This module is deprecated. Please use `kubernetes.client.models.V1Volume`.
/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/kubernetes/volume_mount.py:22 DeprecationWarning: This module is deprecated. Please use `kubernetes.client.models.V1VolumeMount`.
Running <TaskInstance: kubernetes_pod.process1800 manual__2022-08-05T18:26:58.893963+00:00 [queued]> on host process1800.404b6cc740064e90955

Process finished with exit code 0

Task Log:

[2022-08-05, 18:32:09 UTC] {local_task_job.py:82} ERROR - Received SIGTERM. Terminating subprocesses
[2022-08-05, 18:32:09 UTC] {process_utils.py:120} INFO - Sending Signals.SIGTERM to group 18. PIDs of all processes in the group: [18]
[2022-08-05, 18:32:09 UTC] {process_utils.py:75} INFO - Sending the signal Signals.SIGTERM to group 18
[2022-08-05, 18:32:09 UTC] {taskinstance.py:1430} ERROR - Received SIGTERM. Terminating subprocesses.
[2022-08-05, 18:32:09 UTC] {kubernetes_pod.py:459} INFO - Deleting pod: airflow-yield-datalayer.7859414c89794502b683608a386a819c
[2022-08-05, 18:32:09 UTC] {taskinstance.py:1774} ERROR - Task failed with exception
Traceback (most recent call last):
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py", line 417, in execute
    self.pod_manager.follow_container_logs(
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/providers/cncf/kubernetes/utils/pod_manager.py", line 208, in follow_container_logs
    last_log_time = follow_logs(since_time=last_log_time)
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/providers/cncf/kubernetes/utils/pod_manager.py", line 195, in follow_logs
    for line in logs:  # type: bytes
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/urllib3/response.py", line 811, in __iter__
    for chunk in self.stream(decode_content=True):
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/urllib3/response.py", line 575, in stream
    for line in self.read_chunked(amt, decode_content=decode_content):
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/urllib3/response.py", line 767, in read_chunked
    self._update_chunk_length()
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/urllib3/response.py", line 697, in _update_chunk_length
    line = self._fp.fp.readline()
  File "/opt/bitnami/python/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
  File "/opt/bitnami/python/lib/python3.8/ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "/opt/bitnami/python/lib/python3.8/ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
  File "/opt/bitnami/airflow/venv/lib/python3.8/site-packages/airflow/models/taskinstance.py", line 1432, in signal_handler
    raise AirflowException("Task received SIGTERM signal")
airflow.exceptions.AirflowException: Task received SIGTERM signal

  [1]: https://github.com/apache/airflow/issues/18041

Comment: @tadman thank you for help, Solution provided by Hussein Awala worked for me.
Comment: Are you sure you don't have a health check that's failing and Kubernetes terminates the process to try and restart it?
Comment: I am using default settings currently and not getting any specific error message. Only pattern that I am able find out with this behavior is whenever task runs more than 5 mins scheduler try to kill the task.
Comment: The fact that it's precisely five minutes suggests to me there's a health check that fails and five minutes is when it pulls the plug on the pod. Keep a close eye on `kubectl describe pod` for the pod that's failing, perhaps with `-l` to scope it automatically to the right type of pod. You'll probably see `0/1` pods ready until it shuts the party down and starts over.
Comment: If you know the name of the deployment you can also `kubectl describe` or `edit` that, too, to find out what's going on internally. Check the pod logs as well, `kubectl logs` on that pod.
Answer: In bitnami helm chart, there is an option to add a livenessProb to the pod_template (the template used to create a new pod/worker).
This livenessProbe is enabled by default, with initialDelaySeconds=180s (3 min), 20 seconds between each two tries, and 6 as failure threshold, so 2 min for the checking and 3 min before the first try, which is 5 min in total.
You can check what is the problem with this Prob and solving it, or just disable the Prob by setting:
worker:
  livenessProbe:
    enabled: false

Answer: You can check for Airflow configurations at:

DAG level: dagrun_timeout -> check if it is greater than 300 seconds;
Core level: AIRFLOW__CORE__DEFAULT_TASK_EXECUTION_TIMEOUT -> check the value here.

You can also explore Kubernetes airflow configs.


What is a correct Amp for your RCD?

Question: If i am running my panel board with the 60Amps MCB.
Does my RCD needs to be also rated at 60A?
Answer: Nah, it should be OK if the RCD is rated more.  There are 2 different jobs being done here:

Overcurrent detection (at 60 amp setting) - the MCB does that
Ground fault/Residual Current detection at any current - the RCD does that

The RCD might also do overcurrent protection, but if it does, it's redundant.

So yeah, perfectly safe to use an 80 amp RCD. It can certainly handle any current a 60A MCB will let through.
Obviously a 30A RCD doesn't have the internal wiring to survive 60A going through it, so that's a no-go.

What is a correct Amp for your RCD?


Using the camera modes in Rocket League

Question: In Rocket League, you can keep the camera facing forward or locked onto the ball.  Usually I go the entire match using the camera that locks onto the ball.  This gets a little disorienting when the ball goes high and your car scrolls out of view.  When should I be using each of the two camera modes?
Answer: It's completely up to you. I used to like the fixed camera back in SARPBC but since I've gotten used to the ball cam in Rocket League, I prefer that one much more any time I'm trying to track the ball.
It's a lot easier if you can get used to one camera mode, but if you really want to switch off, use the fixed camera when you want to know where you are and the ball cam when you want to know where the ball is.

Using the camera modes in Rocket League


Pass CATV and ethernet over single ethernet wire

Question: I have a fiber-optic router which also outputs a CATV signal. CATV was unused previously (the service provider includes CATV in the pack but I've never used it before) so it was not taken into account when deciding a place for the router and the fiber-optic ingress to the house.
The room the router is at (and where the fiber-optic enters the house) doesn't have any coax cabling (no TV was put there, it's a "computer room").
Now I'm moving an old TV to a wall where I have a coax cable (TV/SAT) outlet and a ethernet outlet set up, and I want to set up DVB-C on that TV, coming from the router, and also ethernet LAN (for SmartTV related services)
The ethernet outlet on the "TV" has direct connection to a wall outlet near the router (so ethernet wouldn't be a problem), but the current TV/SAT coax outlet doesn't (and there's no easy way to cable it as it is now, those hoses go to a completely different direction and don't come near the "computer room").
So I'm wondering... is there any device I can use to pass the coax cable signal over ethernet? kind of like a MoCA system but the opposite (pass coax over ethernet, not ethernet over coax). Also, I'd need to keep the existing ethernet connection for IP. Not sure if such a thing exists, but that'd basically allow me to do what I need without having to run cables.
My option if that doesn't exist is to -try- and run (I'm not sure how polluted the conduit where the ethernet cable goes might be at some point, I didn't do the installation) a coax cable on the same conduit as the ethernet is in (have both cables in) and split it at the "router room" outlet: would that significantly affect ethernet data (using UTP cat-6 cable, not shielded) by running both on the same conduit? I don't really need that ethernet to be extremely fast (it's just for a FHD Smart TV) so some packet loss should be more thank ok.
There's a third option which would be adding a compatible wifi dongle to the TV and just replace the ethernet cable and wall outlet altogether for coax ones, but if I could avoid that, that'd be great.
I also don't have good experiences with wireless video transmitters (which would be another option), plus that'd also mean buying another STB for cable, which I want to avoid if possible (the TV already has a DVB-C tuner, which I suppose is what the router outputs through the CATV output)
I'm open to alternatives also which could be more work/cost effective than those presented. I'm extremely far from being an expert on these matters and there's surely something I haven't thought of
Comment: I'm voting to close this question because the OP failed to do a simple search for "coax over ethernet", which is what he's after and that search turned up a wide variety of products within the top 5 results.
Comment: The word you're after for that "tube" is "conduit" or "trunking" (the former North American, the latter British)
Comment: My apologies - I searched for "coax over ethernet" but found "ethernet over coax" solutions. More careful searching turned up this [AVforum thread](https://www.avforums.com/threads/sky-coax-over-ethernet.2175850/) which says (as of 2018), that extending a coax signal over ethernet is not possible, and that even if it were, it's a bad idea. (check the thread for details) Based on this thread, you would be better off converting at the incoming location with some sort of remote tuner, then sending the final output via HDMI (which can be transmitted via ethernet).
Comment: A) a quick sketch of all the different bits and pieces may help people draw a mental image. B) "those hoses go to a completely different direction" - don't think I've ever heard someone refer to a cable as a "hose" before... C) Not VtC, but I'm not quite sure that this falls under the DIY guidelines for on topic questions. D) I will, however VtC because a search for "coax over ethernet" returned a variety of options under $200.
Comment: @FreeMan I have indeed searched, but all that comes up is MoCA (which is ethernet over coax) and one cable adapter that said only worked for DOCSIS data. I'm in Spain so my google results (even when searching in english) may vary from yours, but I did indeed search before
Comment: And about the "hose"... I'm not referring to the cable, but the "corrugated tube" (sorry if that's a wrong word, English is not my native) that runs over the walls where the cables go in
Comment: Have you contacted your service provider?  They do keep coming up with new configurations.
Comment: @ThreePhaseEel thanks, edited, hope it's more clear now :-)
Comment: @FreeMan hdmi over ethernet + ir remote, I have considered, but that means adding a stb plus having another remote. That'd be my last resort, but if I can avoid it, that'd be great
Comment: Based on the thread I linked, it sounds less like "last resort" and more like "only resort". Well, that, or pull some coax through your walls. Honestly, if you've got conduit all the way from the network interface to where you want the TV, pulling a cable should be reasonably easy. (For some values of "reasonably"...)
Comment: @FreeMan yes, and I'll probably do that... part of my question was asking if passing both (ethernet + coax) on one conduit would give too much interference... but I've googled around and it seems that triple-shielded coax would work ok with even UTP Cat-6, so I believe I'll go that route. Thanks for your input, much appreciated (and really on point)!
Answer: Based on this AVforum thread (from 2018), forwarding a coax-delivered TV/satellite signal over Ethernet isn't possible and if it were, it would probably be a bad idea anyway. Some relevant quotes in case the link dies:

Unlike say a HDMI signal you had previously which is just one signal albeit high bandwidth satellite signals are lots of different ones on the cable. Hence you use a satellite tuner to tune into the relevant frequency.
Sky Q uses a wideband LNB which has a frequency range of 230MHz to 2359MHz so not feasible to send all these signals this cables in a different manner down a CAT cable.I'm not certain what TV carrier the OP is using, but I believe the concept is similar no matter who the carrier is. --Ed

A good friend of mine is an aerial/satellite specialist and says it's not even a good idea to extend coax with more coax! Whenever there is a break in the copper joined by couplers or whatever, the impedance can change massively affecting signal quality. He doesn't even terminate to sockets and runs cable from LMB to Sky box because of these issues; he's been burned by this too many times.

Since it seems you have conduit in your walls, your best bet would be to pull a good quality coax cable (I believe RJ56 (or is it RJ59?) is the current "best") from the entry point in your house to as close to your use point as possible.
Both high-grade coax and Cat6 cables are well insulated against RF interference, and the Cat6 cables design even allows it to run next to power lines without picking up significant interference. (Note: it's still recommended to keep Ethernet cables away from power, but it's not critical in most use cases, and it's only a few inches.)
Answer: I think your question could benefit from some consolidation.  However, my suggestion is investigate any wireless TV options your service provider may offer.  In the U.S. this is the trend and it makes installations in homes much easier.
I had such a system from AT&T/DirecTV.  The main box was located in a second-floor loft with a coax cable run to the satellite antenna.  Additional wireless TV boxes were in other rooms, including one in the basement.  This worked great.
Comment: Thanks for the answer. I checked with them and no dice. It's a very small provider reselling fiber-optic for areas where "big ones" don't reach and their services are very limited I'm afraid


Recursive function result as array not showing desired result

Question: I have a controller ajax where the two functions exists :
  function customer_comission()
  {
            ---------------------------
            ---------------------------
        $arr = $this->show_parent_id( $child_node );

        var_dump($arr);
            ----------------------------
            ---------------
  }

function show_parent_id( $cust_id ){

    if( $cust_id > 2 ):
        $cust_id2 = $this->comission_model->show_parent_id( $cust_id );
        $cust_array[] = $cust_id2;
        //echo $this->show_parent_id( $cust_id2 );
         $this->show_parent_id( $cust_id2 );
    endif;

    return $cust_array; // <-- This is Line 38
}

So what I want to display is the array of parent_id's for the $cust_id hierarchy. The echo $this->show_parent_id( $cust_id2 );   prints the desired results, but when I tried to add them in an array, and then I got the error is showing :

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: cust_array
Filename: controllers/ajax.php
Line Number: 38
Comment: Obviously, when `$cust_id<=2`, `$cust_array` is never defined. Either give it a default value beforehand, or provide an `else` branch defining it. Apart from that, why `$this->comission_model->show_parent_id( $cust_id )`? Wouldn't `$this->show_parent_id( $cust_id )` suffice?
Comment: `$this->comission_model->show_parent_id( $cust_id )` returns the `parent_id` from database.
Comment: I was referring to the `comission_model->` part being maybe redundant?
Answer: That is because whenever $cust_id <= 2 then $cust_array variable falls undefined.So just initialize it befor the if condition like this
function show_parent_id( $cust_id ){
    $cust_array = array();
    if( $cust_id > 2 ){
        $cust_id2 = $this->comission_model->show_parent_id( $cust_id );
        $cust_array[] = $cust_id2;
        //echo $this->show_parent_id( $cust_id2 );
         $this->show_parent_id( $cust_id2 );
    }

    return $cust_array; // <-- This is Line 38
}

Comment: It returns `parent_id` of `$cust_id` passed. The `parent id` s for the results are not in the array


Can not save PDF file with inputs, error message "Document is encrypted"

Question: I have inserted inputs to a form given as a PDF file. Using Evince document viewer 3.2.1 on Ubuntu 11.10, there is no problem with inserting inputs to the form and to print the result.
But it is not possible to save the PDF file with inputs (as a new file) and the following error message is given:
The file could not be saved as "file:///home/username/Downloads/file.pdf"

Document is encrypted

Note for the message above that if I try to save the file in a different folder (e.g. Documents), the error message is still referring to the Downloads folder.
How to save the PDF file with inputs?
P.S. I know that similar questions are in the database, but I have not seen a similar error message in previous questions
Comment: Saving in another folder works, saving to the same folder however does not work (keine Berechtigung, which seems the same error as above).
Answer: There is a bug report for Envince. Have a look for further information and status update, the bug is still open.
There is a possible workaround that seems to work for some users, you might try and let us know.
Run these steps on a terminal:

Install the tool
sudo apt-get update && sudo apt-get install qpdf
Run this command, input.pdf is the source file and the output.pdf
is the saved file after running the tool.
qpdf --decrypt input.pdf output.pdf

Try opening the output.pdffile and doing your changes there.
Comment: Thanks! I have tried the proposed workaround and it worked fine.
Answer: This will work but only save the raw PDF - you lose the form controls.
Select File -> Print.
Choose "Print to File" as Printer.


How to get date from IonDateTime with Ionic React

Question: I have recently started using react due to the performance it provides, so I'm not used to this new framework. I have searched on this exact topic but cannot find an answer.
Although the problem is very simple, (Just want to return the selected date).
Here's what I currently am trying to do:
        let dateValue = format(new Date(), 'yyyy-MM-dd')+ 'T09:00:00.000Z';

        const dateChanged = (value: any) => {
        console.log("value: ", value);
        dateValue = value;
        };

        const DateModal: React.FunctionComponent<any> = ({ isOpen, onClose }) => {
        return (
          <IonModal className="datemodal" isOpen={isOpen}>
            <IonContent className="dateModalOpen">
              <IonDatetime
                locale="en-GB"
               value={dateValue}
               id="datetime"
                onChange={() => dateChanged(datetime)}
                showDefaultButtons={true}
                min="1920"
                max="2022"
                className="calendar"
                presentation="date"
              >
                Date of Birth
              </IonDatetime>
            </IonContent>
          </IonModal>
        );
      };

I recieve an error on the "onChange" (Cannot find name 'datetime'.), this is what I used to do in Angular. I tried to use a template reference by doing "id=datetime", which in Angular was "#datetime". And in so doing would work inside the onChange event.
How do I make this work?
Thank you in advance!
Answer: You just need to use the ionOnChange handler:
<IonDatetime presentation="date"
             id="datetime"
             onIonChange={(e) => console.log(e)}>
</IonDatetime>

Answer: Solved. On react you can use "Controller" to get the data from IonDateTime as follows:
const {
    handleSubmit,
    control,
    setValue,
    register,
    getValues,
    formState: { errors },
  } = useForm({
    defaultValues: {
      fullname: "",
      date: "",
      gender: "MALE",
      email: "",
    },
  });
  console.log(getValues());

  /**
   *
   * @param data
   */
  const onSubmit = (data: any) => {
    alert(JSON.stringify(data, null, 2));
  };

const [ionDate, setIonDate] = useState("");

  const dateChanged = (value: any) => {
    let formattedDate = format(parseISO(value), "dd-MM-yyyy").replace(
      /-/g,
      "/"
    );
    setIonDate(formattedDate);
    setshowDate({ isOpen: false });
  };

  const DateModal: React.FunctionComponent<any> = ({ isOpen }) => {
    console.log(isOpen);
    return (
      <IonModal className="datemodal" isOpen={isOpen}>
        <IonContent className="dateModalOpen">
          <Controller
            render={({ field }) => (
              <IonDatetime
                value={field.value}
                onIonChange={(e) => dateChanged(e.detail.value)}
                locale="en-GB"
                onChange={dateChanged}
                showDefaultButtons={true}
                onIonCancel={() => setshowDate({ isOpen: false })}
                min="1920"
                max="2022"
                className="calendar"
                presentation="date"
              >
                Date of Birth
              </IonDatetime>
            )}
            control={control}
            name="date"
            rules={{ required: "This is a required field" }}
          />
           <IonButton type="submit">submit</IonButton>
        </IonContent>
      </IonModal>
    );
  };
};

Comment: You can you se ```toLocaleDate()``` function on the time passed iondatetime, it will be automatically formatted to dd/mm/yyyy


How do you read these symbols?

Question: I want to learn computer graphics, so I bought a book where on the very first page there is a sentence:

Parametric surfaces are defined by a vector-valued parameterization function: $f: Ω \rightarrow S$ that maps a 2D parameter domain  $Ω \subset \mathbb{R} ^2$ to the surface $S = f(Ω) \subset  \mathbb{R} ^3 $. In contrast, an implicit (or volumetric) surface representation is defined to be the zero set of a scalar-valued function $F: \mathbb{R} ^3 \rightarrow \mathbb{R} $, i.e., $S = \{ x \in \mathbb{R}^3 | F(x) = 0\}$

It is on the first page, so I assume that I should be easily able to read these lines. Now you can condemn me, but I have never learned it that well to being able to easily read it. What does Ω and S represent here, and what should I look after so I can improve myself here as well?
Many Thanks,
Mat
Comment: It would help if you describe your mathematical background, because my first guess is that you are looking at a book for which you do not have the prerequisite math background, which I would guess is at least the 3rd semester of an elementary calculus course (U.S. type), where the 3rd semester covers multivariable calculus.
Comment: recommend do Carmo     as he does parametrization in detail https://www.google.com/books/edition/Differential_Geometry_of_Curves_and_Surf/uXF6DQAAQBAJ?hl=en
Comment: alright, similar  https://people.math.wisc.edu/~jwrobbin/Do_Carmo/diffgeo.pdf
Comment: some of his notes on do Carmo's book https://people.math.wisc.edu/~jwrobbin/Do_Carmo/Do_Carmo.html
Answer: I think it would be easier if I give you an example.  Suppose that you want to describe the half sphere that lies above the $x-y$ plane, in the positive $z$ direction, with radius $1$. This is surface $S$. The projection in the $x-y$ plane of this figure is a disk, centered on $(0,0)$, with radius $1$. So that is $\Omega$. $$\Omega=\left\{(x,y)|x^2+y^2\le 1\right\}$$and$$f(x,y)=\left(x,y,\sqrt{1-x^2-y^2}\right)$$
For the second case, let's use the full sphere. Then $$F(x,y,z)=x^2+y^2+z^2-1$$
The points where $F(x,y,z)=0$ are the points where $x^2+y^2+z^2=1$, which is the sphere of radius $1$.
Answer: Let's describe a simple surface, say a cylinder with height $1$ and radius $1$, in two ways.
First, a parametric surface is given by a function $f$, which eats two values and returns a point. If we look at the set of all points returned, we'll have a surface! For our cylinder that means looking at the function
$$f(\theta,h) = \langle \cos(\theta), \ \sin(\theta), \ h \rangle$$
Evaluating this at $(\theta,h) = (0,0)$ tells us that the point $\langle 1, 0, 0 \rangle$ is in our surface. Of course, evaluating at $(\theta,h) = (0,100)$ tells us that $\langle 1, 0, 100 \rangle$ should be in the surface, which we don't want. After all, we want to describe a cylinder of height $1$. We solve this problem by restricting what inputs we're allowed to plug in. That is, we restrict attention to a certain domain for the function. Restricting the domain also lets us ensure that each point on the surface is hit exactly once. Currently, the inputs $(0,1)$ and $(2\pi,1)$ both describe the point $\langle 1, 0, 1 \rangle$. We would like to not "double count" points on the surface, since eventually we'll be computing surface area, etc. in terms of these functions $f$, and we don't want to double count surface area.
So then, we restrict our domain, and see that our cylinder of height one can be defined as
$$
f(\theta, h) = \langle \cos(\theta), \ \sin(\theta), \ h \rangle \quad \quad 0 \leq \theta < 2 \pi, \ 0 \leq h \leq 1
$$
Here the domain $\Omega = \{ (\theta, h) \mid 0 \leq \theta < 2 \pi, \ 0 \leq h \leq 1 \}$ is the allowable set of inputs, and the function $f : \Omega \to \mathbb{R}^3$ takes an allowable input and gives us a point on our surface. If we look at every point we get in this way, we trace out a surface.

The second approach is an implicit representation. In this way we give an equation (or a system of equations) and ask that our surface be exactly those points solving the equation. For our cylinder, the defining (in)equations are
$$
x^2 + y^2 = 1 \quad 0 \leq z \leq 1
$$
Indeed, if we look at $\{ (x,y,z) \mid x^2 + y^2 = 1, \ 0 \leq z \leq 1 \}$, the set of points $(x,y,z)$ which make our two equations true, then the points we've kept are exactly the points in our cylinder!

Also, as a small piece of unrequested advice: If you're struggling with the first sentence of the book, it might be worth looking for a book on surfaces that's written for someone with a background more similar to yours. You mention computer graphics as an interest of yours, and I'm completely sure that there's a book on surfaces which doesn't require this kind of familiarity with mathematical formalism, and will probably teach you things that are more relevant for your interests than a very math heavy textbook. If you're dead-set on reading this book for some reason, you might want to look for any prerequisites it lists, and brush up on some of the things that will be useful for reading this book going forwards.

I hope this helps ^_^

How do you read these symbols?


iOS In-App Purchase sandbox test account keeps popping up for verification

Question: I have Auto-Renewable In-App Purchase item in my application which is in development stage. I could able to test the complete transaction till 2 days ago with different sandbox test accounts (+email@example.com). From past couple of days when I am trying to test the transaction with new sandbox test accounts (+email@example.com), it is giving me an alert saying AppleID Verification - Open settings to continue signing with ******+firstname.lastname@example.com. I have already verified the account before trying to purchase. I have tried and tested with numerous new accounts I have created, getting the same alert message. When I googled the issue, got suggestions to create a sandbox account with different AppStore locations Like Canada, UK....etc. but didn't worked out for me.
Could anyone help, as I am struck in testing my transaction process.
Comment: I'm getting the exact same issue. Have never seen this until now. I was getting [this Sandbox signup error](http://stackoverflow.com/questions/41496572/java-lang-nullpointerexception-error-when-adding-sandbox-tester-in-itunes-connec/41496866) a few days ago, and now that signup is working again it seems they've changed something on their side.
Answer: Came to know this is an issue from Apple side, which they are aware of now and working on it.
https://forums.developer.apple.com/message/204979#204979
Comment: I wonder how long this fix will take. We urgently need to test in-app purchases, but this annoying issue prevents us from keeping the time schedule.
Answer: Finally it's working, sort of.

Make a fresh sandbox account.
Confirm it after receiving the email
Login in your app
If a Change password dialog appears, then change your password you confirmed a few seconds ago...
...and then it works.

Don't try to use accounts you have made the past few days before 13 January 2017, these are currently unusable.
Answer: no idea I have created multiple sandbox users never found this issue ever
https://forums.developer.apple.com/message/204979#204979
Its working great...
1. You need to create another test id from your iTunes account.
2. It will prompt to signing to settings.
3. Go there and change the password.
4. Now come back to app. and purchase any item. It will allow you to buy that item...


noisy Air-conditioner compressor

Question: I bought a new split AC that worked great for a week or so, but now I can hear some annoying noise coming from the outdoor unit.
The outdoor unit in installed on a flat roof so I can hear this noise even when I'm inside the room. (Noise sample), is this normal?
Another things I noticed is that the the AC pipe gets wet when it's running, is this normal ? (Video).
Comment: Have you contacted the company that installed the unit?  They likely have some form of warranty or satisfaction guarantee, and would be willing to at least come take a look.
Comment: The suction line will get wet when it's running. It's cold, so moisture from the air around it is condensing on it. No problem there.
Comment: I didn't contact the company that installed the unit yet, I just wanted to know if this is normal or not. You didn't answer my first question about the compressor noise, it passes through my roof into my room and I can hear it, is this the normal compressor sound and I should just install anti-vibration pads below the compressor  or it's a faulty compressor ?
Comment: I didn't *answer* either of your questions, I simply *commented* on why an A/C pipe would be wet.
Answer: The compressor noise in your video is not normal.
Some of the possibilities for this noise are:

Non-Condensables
Things that can't condense, such as moisture, ambient air, etc. can
make a compressor chatter like that because it is trying to compress
something that doesn't want to compress.
Ask an HVAC Technician to recover, evacuate, and recharge your unit
to eliminate the chances of non-condensables being present in the
system. Refrigerant filter installation would also help.
Compressor Bearings
Sometimes compressors aren't pre-charged with oil from the factory.
That could an oversight on the manufacturer, or the contractor that
did the installation. Most mini-splits however do come pre-charged
with oil. What could also be a problem, is oil from your compressor
has pumped itself throughout the system, and hasn't been able to
return to the compressor.
This can be eliminated depending on how the line set is installed.
Creating oil-traps is typically the best way to go - it prevents the
oil from leaving the compressor. But there should only be one oil
trap close to the unit in the line set. Additional traps throughout
the system will trap oil and prevent it from going back into the
system.
Oil is integral for keeping the bearings lubricated and from
overheating. Friction will warp the bearings, and cause the spin of
the compressor to make loud noises.
Non-Level Installation
If the outdoor unit is not installed level, then the compressor
could be spinning on an uneven axis. This could also create noise,
and will eventually warp bearings (if it is a compressor that has
them) which creates even more noise.
High Amperage
Check the amperage of the power going into the compressor - not the
entire unit. Make sure that it matches its amp rating. If it is too
high, then it can start making noise because a by-product of
electricity is heat. Heat causes metal expansion internally and can
increase friction of delicate parts within the compressor - creating
noise - warping bearings - etc.

The moisture on your line set is normal.
As was mentioned in comments, this is natural. In the HVAC industry, we call it "sweat back." Meaning, you have heat transfer happening - it's doing its job. This is no different than setting a cold can of Coke onto the table, and seeing the condensation build up on the outside of the can.

If you don't like to see the drips, then installing more insulation (Armor Flex is a common term) on your line set will help a lot. Some technicians will even try to cover the service ports. Moisture will attract dirt. Dirt is an inconvenience on the service ports and if not removed prior to hooking up manifold gauges, can clog the gauges themselves.
Something else to consider is Slim Duct or SpeediChannel (those are brand names) but it protects your entire line set from the environment (and other mischievous creatures such as rodents and people). Here is an example:

It also has an aesthetic quality - it looks better on the outside of your home and can even be painted to match the color of your home.

noisy Air-conditioner compressor


Getting "Failed to open database" error when copying a sqlite database from assets In Android 4.2

Question: My Code works fine For Android 2.3 but i don't know why it doesn't work for Android 4.2
My Exception log is here
01-17 09:54:04.411: E/SQLiteLog(24202): (14) cannot open file at line 30176 of [00bb9c9ce4]
01-17 09:54:04.411: E/SQLiteLog(24202): (14) os_unix.c:30176: (2) open(/data/data/com.example.myapp/databases/myapp.db) -
Failed to open database '/data/data/com.example.mypapp/databases/myapp.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
at com.example.myapp.DataBaseHelper.checkDataBase(DataBaseHelper.java:80)
at com.example.myapp.DataBaseHelper.createDataBase(DataBaseHelper.java:47)
at com.example.myapp.MainActivity.onCreate(MainActivity.java:61)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

My MainActivity.java
public class MainActivity extends Activity {

    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.activity_main);

        DataBaseHelper myDbHelper;
        myDbHelper = new DataBaseHelper(this);

        try {

            myDbHelper.createDataBase();

        } catch (IOException ioe) {

            throw new Error("Unable to create database");
        }

        try {
            myDbHelper.openDataBase();

        } catch (SQLException sqle) {

            throw sqle;

        } finally {

            myDbHelper.close();
        }
}}

My DatabaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.myapp/databases/";

    private static String DB_NAME = "myapp.db";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){
            Log.i("Hellloooo", e.getMessage());
            //database does't exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

        // Add your public helper methods to access and get content from the database.
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
       // to you to create adapters for your views.

}

Comment: http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application/9109728#9109728
Answer: I had to modify checkDataBase() to
 private boolean checkDataBase() {
    File databasePath = mContext.getDatabasePath(DB_NAME);
    return databasePath.exists();
}

Comment: Do you know what caused this problem ?
Comment: I would give you +5 if I could. Great solution mate!
Answer: I faced this problem, it was because in 4.2, there is multi users support, and if you are testing with non-admin user, you cannot acess /data/data path..
In my case i'm using the path:
context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator

Hope that helps..
Comment: in 4.0 too - I can't create database via getDatabasePath("bla.db"), but only getFilesDir()+'/bla.db'
Answer: Some devices cannot handle large assets. What I did is split database to 1 MiB chunks and copied them to a file
I created a script (for Linux) to easily split the file
#!/bin/bash

#split database file into chunks not larger than 1 MiB
split -b 1048576 databasename db -d -a1

The chunks will be named db0, db1, db2, ..., dbN
/**
 * Copies database from assets to a file if not exists.
 *
 * @param context Application's Context
 */
public static void copyDatabase(Context context)
{

    File target = context.getDatabasePath(databasename");
    if (target.exists()) {
        return;
    }

    target.getParentFile().mkdirs();

    InputStream is = null;
    OutputStream os = null;
    try {
        List<String> filesl = new ArrayList<String>();
        String[] files = context.getAssets().list("");
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (Pattern.matches("^db\\d.db$", files[i])) {
                    filesl.add(files[i]);
                }
            }
        }
        files = null;
        Collections.sort(filesl);

        if (filesl.isEmpty()) {
            return;
        }

        os = new FileOutputStream(target);

        for (int i = 0; i < filesl.size(); i++) {
            is = context.getAssets().open(filesl.get(i),
                    AssetManager.ACCESS_BUFFER);

            byte[] buffer = new byte[5096];
            int read;

            while (true) {
                read = is.read(buffer, 0, buffer.length);
                if (read < 0)
                    break;
                os.write(buffer, 0, read);
            }
            is.close();
        }

    } catch (Exception e) {
        if (target.exists()) {
            target.delete();
        }
        e.printStackTrace();
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception e) {
            }
        if (os != null)
            try {
                os.close();
            } catch (Exception e) {
            }
    }
}

Note that Collections.sort will sort names in proper order if not more that 10 files in case db0 ...db9 - after db10 your will have to write your own sorting or comarator.


Give key names to an array with numerical keys

Question: I have a function that takes an entry from a textarea, splits it in to lines and makes an array of the data from each line. However, this is a numerical array, and the data needs to have specific keys associated to it.
Is there a function that can insert these keys in to my desired positions, to avoid manually coding each key?
Here is my code, which produces a 4 element array -
function do_split_invitations(){

    /** Split the lines into individual elements in an array */
    $lines = explode("\n", $_POST['invitations']);

    $invites = array(); // Initiate array to avoid errors
    if(!empty($lines)) : foreach($lines as $line) :

            $parts = explode(',', $line); // Split in to parts
            $parts = array_slice($parts, 0, 4); // Take only the first 4 parts (the rest are not needed
            $parts = array_map(array($this, '_clean_callback'), $parts); // Clean the parts

            $invites[] = $parts;

        endforeach;
    endif;

}

Current output (for one line) -
Array
(
    [0] => firstname.lastname@example.com
    [1] => John
    [2] => Smith
    [3] => Mr Smith
)

Desired output (for one line) -
Array
(
    ['email'] => email@example.com
    ['first_name'] => John
    ['surname'] => Smith
    ['custom'] => Mr Smith
)

Answer: Array combine is help for you
for eg.
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Edit
Try in your foreach. i am write a basic structure.
foreach ($Offer as $key => $value) {
  $offerArray[$key] = $value[4];
}

Output like this format
key => value
key => value

Answer: This will be helpful to you,
$key=array("email","first_name","surname","custom");
$parts = explode(',', $line);
$parts = array_slice($parts, 0, 4);
$invites[] = array_combine($key,$parts);

Answer: The answer here is to use array_combine($keys, $values);
Note that the function will fail if the number of elements in the $keys and $values array are different.
Comment: Because I struggled to find the answer, and isn't that what SO is all about?
Comment: very fast, if you knew the answer then, why you use `stackoverflow`


Access parent datacontext in listbox in Silverlight

Question: In Silverlight 2 I'm using a usercontrol which inherits the datacontext of the page that it's embedded on. This datacontext contains question text, a question type and a collection of answers. In the user control is a listbox which is bound to the collection of answers. As shown below:
<ListBox DataContext="{Binding}" x:Name="AnswerListBox" ItemContainerStyle="{StaticResource QuestionStyle}" Grid.Row="1" Width="Auto" Grid.Column="2" ItemsSource="{Binding Path=AnswerList}" BorderBrush="{x:Null}" />

This listbox has an associated style to display the answers in the form of radio buttons or checkboxes (which I would like to hide or show depending on the question type) as:

So my question is then: how do you access the parent data context in order to get the QuestionType (as this is a property on the user control datacontext itself, not a property on an AnswerItem in the AnswerList)?
Alternatively is there a better way to switch styles dynamically in the xaml based on a binding value?
Comment: Do you have any way to change your accepted answer? The one below, by Roboblob, is a correct answer. The accepted answer is incorrect for Silverlight and misleading.
Answer: In Silverlight 3 and higher you can use Element to Element binding and point to the controls DataContext and then some property in my example its Threshold property.
So first name your control (for example in my example its x:Name="control")
<UserControl x:Class="SomeApp.Views.MainPageView" x:Name="control" >

then inside this control in your ListBox ItemTemplate you can access parent DataContext like this:
    <ListBox ItemsSource="{Binding Path=SomeItems}" >
        <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding ElementName=control, Path=DataContext.Threshold}"/>
            </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate>
       </ListBox>

Comment: important not to miss that you need to explicitly put in 'DataContext'. i had previously abandoned an attempt to do this because i managed to forget to put 'DataContext'
Comment: This solution looks very elegant, but unfortunately I haven't been able to get it working with a DataGrid.  Specifically I've been trying to use this solution for a DataTemplate for the "CellEditingTemplate" on a DataGridTemplateColumn. I believe it is the same problem that Simon_Weaver is pointing out.
Comment: @roboblob - do you happen to know a good way to do this within a DataForm (doesn't work in same way as shown in my post below)
Comment: @Roboblob - Clever solution to a common problem. I will go down-vote the one marked as "the" answer as it is misleading and actually wasted our time until we saw yours.
Comment: I've tried this from a `DataTemplate` in `sdk:DataGrid`'s `RowDetailsTemplate` and doesn't work. Any ideas? I want to determine if the `DataGrid` is currently in edit mode.
Answer: I've just been battling with a similar problem. Mine consists of a combobox that displays for each listitem. The top-level DataContext is bound to my viewmodel (MVVM) and looks like this:
class ViewModel{
    ObservableCollection<ComboboxListItemType> DataForTheComboBoxList;
    ObservableCollection<MyDataType> DataForTheListBox;
    ...
}

Because the combobox is within the ItemTemplate (=DataTemplate) for the listbox, the DataContext for each list item is set to the appropriate item in DataForTheListBox, the combobox can no longer see the DataForTheComboBoxList it needs from the top-level DataContext.
My (dirty, ugly) workaround involves setting the complete combobox list on each item in the list, so it becomes visible to the DataContext in this list item.
First you make a partial class for your listbox data type. (Generally this will be coming from a service reference, so you cant touch the generated code directly without potentially losing it). This partial class contains a new property referring to your combobox list item type:
public partial class MyDataType
{
    private ObservableCollection<ComboboxListItemType> m_AllComboboxItems;
    public ObservableCollection<ComboboxListItemType> AllComboboxItems
    {
        get { return m_AllComboboxItems; }
        set
        {
            if (m_AllComboboxItems != value)
            {
                m_AllComboboxItems = value;
                RaisePropertyChanged("AllComboboxItems");
            }
        }
    }
}

Next you have to set this property on each element in the DataForTheListBox collection
// in ViewModel class
foreach(var x in this.DataForTheListBox)
{
    x.AllComboboxItems = this.DataForTheComboBoxList;
}

Then back in your XAML:
<DataTemplate x:Key="ListBoxItemTemplate">
    ...
    <Combobox
        ItemsSource="{Binding AllComboboxItems}"
        SelectedItem="{Binding CurrentBlah}"/>
</DataTemplate>

Dont forget that for the combobox to correctly display the current item, the selected item must refer to the actual item in the combobox's ItemsSource. If you are getting data from a webservice that has IDs or objects to represent the item for the combobox, you must re-reference them to point to the actual collection.
Answer: On of the very cool things you can do with silverlight is to use the Tag attribute to store a reference  to the object to which it is bound.
First, in your class, declare a property like this
public IMyObject Current
{
  get {return this;}
}

Then on the control raising the event in you can get a reference to the object
var fe= (FrameworkElement) sender;
var src = fe.Tag as IMyObject;

So now that I have the object, it's reasonable for an object to have reference to its parent so then you bind to
Current.Parent.QuestionType

Answer: If you're trying to do this with a DataForm he same method shown by Roboblob doesn't work.
This question may have some useful information


SDL_SaveBMP saves images upside down

Question: I have used SDL to save the window image via SDL_SaveBMP. The problem is that the saved image is upside down.
The saved image is

while it has to be

How should I fix the code?
screen_shot function:
void screen_shot(std::string filename)
{
    int width = glutGet(GLUT_WINDOW_WIDTH);
    int height = glutGet(GLUT_WINDOW_HEIGHT);

    SDL_Surface * image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
    glReadBuffer(GL_FRONT);
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, image->pixels);

    SDL_SaveBMP(image, filename.c_str());
    SDL_FreeSurface(image);
}

Update
I try to flip the pixels. The result is a pure black output image. What is the problem?
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"

#include <stdio.h>
#include <assert.h>
#include <iostream>
#include <GL/freeglut.h>
#include <boost/thread/thread.hpp> // for sleep
#include <SDL2/SDL.h>

Uint32 GetPixel24(SDL_Surface * surface,int x, int y)
{
    Uint32 rgb;
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint8) * 3);
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rgb=(pixel[2] << 8)+(pixel[1] << 16)+(pixel[0] << 24);
#else
    rgb=(pixel[2] << 16)+(pixel[1] << 8)+(pixel[0]);
std::cout<<int(pixel[0])<<","<<int(pixel[1])<<","<<int(pixel[2])<<std::endl;

#endif

    return rgb;
}

void PutPixel24_nolock(SDL_Surface * surface, int x, int y, Uint32 color)
{
    Uint8 * pixel = (Uint8*)surface->pixels;
    pixel += (y * surface->pitch) + (x * sizeof(Uint8) * 3);
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    pixel[0] = (color >> 24) & 0xFF;
    pixel[1] = (color >> 16) & 0xFF;
    pixel[2] = (color >> 8) & 0xFF;
#else
    pixel[0] = color & 0xFF;
    pixel[1] = (color >> 8) & 0xFF;
    pixel[2] = (color >> 16) & 0xFF;
#endif
}

void PutPixel24(SDL_Surface * surface, int x, int y, Uint32 rgb)
{
    if(SDL_MUSTLOCK(surface))
        SDL_LockSurface(surface);
    PutPixel24_nolock(surface,x,y,rgb);
    if(SDL_MUSTLOCK(surface))
        SDL_LockSurface(surface);
}

SDL_Surface *flip_vertical_surface(SDL_Surface *surface)
{
    SDL_Surface *flipped = nullptr;

    flipped = SDL_CreateRGBSurface( SDL_SWSURFACE, surface->w, surface->h, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);

    for(int x=0;x<surface->w;x++)
        for(int y=0;y<surface->h;y++)
        {
            int ry=(surface->h)-1-y;
            Uint32 pixel=GetPixel24(surface,x,y);
            PutPixel24(flipped,x,ry,pixel);
        }
    return flipped;
}

void screen_shot(std::string filename)
{
    int width = glutGet(GLUT_WINDOW_WIDTH);
    int height = glutGet(GLUT_WINDOW_HEIGHT);

    SDL_Surface * image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
    SDL_Surface *image_fliped=flip_vertical_surface(image);
    if(image_fliped==nullptr)
        std::cout<<"image_fliped must be different than nullptr"<<std::endl;

    glReadBuffer(GL_FRONT);
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, image->pixels);

    SDL_SaveBMP(image_fliped, filename.c_str());
    SDL_FreeSurface(image);
    SDL_FreeSurface(image_fliped);
}

void cback_render()
{
    if(!glutGetWindow())
        return ;
    static float rotations = 0;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glRotatef(rotations, 0, 0, 1);

    glBegin(GL_TRIANGLES);
        glVertex3f(0,0,0);
        glVertex3f(1,0,0);
        glVertex3f(0,1,0);
    glEnd();

    glutSwapBuffers();
}

void timer(int )
{
    if(!glutGetWindow())
        return ;
    static bool saved=false;
    if(!saved)
    {
        screen_shot("image.bmp");
        saved=true;
    }
    glutPostRedisplay();
    glutMainLoopEvent();
    glutTimerFunc(30, timer, 1);
}

void init()
{
    int argc=1;
    glutInit(&argc, nullptr);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(512, 512);
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    glutCreateWindow("freegluttest");
    glutDisplayFunc (cback_render);
    glutTimerFunc(30, timer, 1);
}

int main()
{

    init();
    glutMainLoop();

    return 0;
}

Comment: afaik OGL coordinate system usually uses the bottom left corner as origin, whereas BMP uses the top right corner - you will have to either conform to the latter coordinate system or flip the image before saving to get the picture right.
Comment: When you say *"the saved image is [...]"*, how did you verify this? What tool have you used to display it? Does this tool honor, whether the bitmap is [top-down or bottom-up](https://msdn.microsoft.com/en-us/library/windows/desktop/dd407212.aspx)? By default, Windows GDI bitmaps are bottom-up.
Comment: @Steeve, this url does not work with 24-bit colors.
Comment: @Steeve, I am new in opengl.  how should I do that via the code?
Comment: Here is a function that can flip an SDL image: http://lazyfoo.net/SDL_tutorials/lesson31/index.php
Comment: @IInspectable, I used GNOME image viewer 3.18.2 (Ubuntu 16.04)
Comment: @Steeve, the code you referred is buggy unfortunately. It does not transform an image properly.
Comment: "I try to flip the pixels": you copy from top to bottom and so halfway you start to overwrite. Loop y only over `flipped->h >> 1` (yes: rounding down--the center line, if there is one, does not need to be flipped), save the pixel at the top, store bottom in top, store saved top in bottom.
Comment: @RadLexus, oops. it is my mistake. I had to read from `surface` than `flipped`. I have realized the problem is from `GetPixel24` all read pixels are zero.
Comment: Ah, and I thought you wanted an in-place flip :P Does your code finally work, then?
Comment: @RadLexus, No still gives a black output. I am sure the problem is with `GetPixel24` which is written by me (as a beginner in openGL). It only gives zero as a pixel color.
Comment: Hm. Perhaps the bytes-per-pixel is not 3 for your screen? Try `screen->format->BytesPerPixel` instead. See an oldie of mine: http://stackoverflow.com/a/24687147/2564301
Comment: @RadLexus, It didnt fix the problem.
Comment: @Steeve: Actually BMP supports both top-down or bottom-up line ordering. The information which direction to use is stored in the image header's `height` field. A *negative* value indicates bottom-up order.
Comment: @datenwolf Yes, I was aware of that, but how the image is stored is irrevelant - when loaded, the upside-down image should be flipped by the loader, so still, it's origin is top left.
Comment: @datenwolf, there is no field called `height`. are you talking about `h`?
Comment: @ar2015: There is a *biHeight* member in the [BITMAPINFOHEADER](https://msdn.microsoft.com/en-us/library/windows/desktop/dd318229.aspx) structure.
Comment: @IInspectable, thanks for quick response. You are linking to MS. What field is it in `SDL`? compiler does not recognize `surface->height`.
Comment: @ar2015: I linked to Microsoft's documentation, because the BMP file format is owned by Microsoft. [SDL_Surface](https://wiki.libsdl.org/SDL_Surface) stores the height in a member called *h*. I don't think it has the same semantics as `BITMAPINFOHEADER`'s *biHeight* member, though. You'd have to look into SDL's bitmap loader to find out.
Answer: After a lot of struggles, I have found the solutions and I share it for programmers who will have the same problem in future.
The solution is here.
#include "SDL/SDL.h"
#include <iostream>
#include <GL/freeglut.h>
#include <SDL2/SDL.h>

#define SDL_LOCKIFMUST(s) (SDL_MUSTLOCK(s) ? SDL_LockSurface(s) : 0)
#define SDL_UNLOCKIFMUST(s) { if(SDL_MUSTLOCK(s)) SDL_UnlockSurface(s); }

int invert_surface_vertical(SDL_Surface *surface)
{
    Uint8 *t;
    register Uint8 *a, *b;
    Uint8 *last;
    register Uint16 pitch;

    if( SDL_LOCKIFMUST(surface) < 0 )
        return -2;

    /* do nothing unless at least two lines */
    if(surface->h < 2) {
        SDL_UNLOCKIFMUST(surface);
        return 0;
    }

    /* get a place to store a line */
    pitch = surface->pitch;
    t = (Uint8*)malloc(pitch);

    if(t == NULL) {
        SDL_UNLOCKIFMUST(surface);
        return -2;
    }

    /* get first line; it's about to be trampled */
    memcpy(t,surface->pixels,pitch);

    /* now, shuffle the rest so it's almost correct */
    a = (Uint8*)surface->pixels;
    last = a + pitch * (surface->h - 1);
    b = last;

    while(a < b) {
        memcpy(a,b,pitch);
        a += pitch;
        memcpy(b,a,pitch);
        b -= pitch;
    }

    /* in this shuffled state, the bottom slice is too far down */
    memmove( b, b+pitch, last-b );

    /* now we can put back that first row--in the last place */
    memcpy(last,t,pitch);

    /* everything is in the right place; close up. */
    free(t);
    SDL_UNLOCKIFMUST(surface);

    return 0;
}

void screen_shot(std::string filename)
{
    int width = glutGet(GLUT_WINDOW_WIDTH);
    int height = glutGet(GLUT_WINDOW_HEIGHT);

    SDL_Surface * image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);

    glReadBuffer(GL_FRONT);
    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, image->pixels);

    invert_surface_vertical(image);
    SDL_SaveBMP(image, filename.c_str());
    SDL_FreeSurface(image);
}

void cback_render()
{
    if(!glutGetWindow())
        return ;
    static float rotations = 0;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);

    glLoadIdentity();
    glRotatef(rotations, 0, 0, 1);

    glBegin(GL_TRIANGLES);
        glVertex3f(0,0,0);
        glVertex3f(1,0,0);
        glVertex3f(0,1,0);
    glEnd();

    glutSwapBuffers();
}

void timer(int )
{
    if(!glutGetWindow())
        return ;
    static bool saved=false;
    if(!saved)
    {
        screen_shot("image.bmp");
        saved=true;
    }
    glutPostRedisplay();
    glutMainLoopEvent();
    glutTimerFunc(30, timer, 1);
}

void init()
{
    int argc=1;
    glutInit(&argc, NULL);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(512, 512);
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    glutCreateWindow("freegluttest");
    glutDisplayFunc (cback_render);
    glutTimerFunc(30, timer, 1);
}

int main()
{
    init();
    glutMainLoop();

    return 0;
}

build:
g++ main.cpp -o main -lGL -lglut -lSDL -lSDL2

Comment: The link is dead, but this invert_surface_vertical() works wonderfully.

SDL_SaveBMP saves images upside down


The icon disappears when you change the color of the button?

Question: NSFW warning about the link
I have site:
link
On this page you will find your add to cart button is orange
Button has an icon (a shopping cart) ... the Track icon appears only if you delete the following code.
Please delete the code below and you'll see the icon appears.
.button.button span{
background:red !important;}

How can I make these icons appear even if the button is orange?
Thanks!
Comment: Can you please post your HTML and CSS for the button. Also, if this link is NSFW please specify.
Answer: Use background-color instead of background since the font-icon is generated through background property.
Remove
.button.button span {
   background: red !important;
}

And add it instead here in this css property:
.product-view .add-to-cart button.button span span {
  line-height: 52px;
  font-size: 14px;
  text-transform: capitalize;
  padding: 0 20px 0 70px;
  background: url('../images/icon_cart_product.png') 17px 50% no-repeat;
  background-color: red !important;
}


Performance of DynamoDB with single item

Question: I have a DynamoDB setup with a single item, so there is only one partition. How does the rcu/wcu be divided? Since I have a single partition, will all the rcu and wcu be used by the one partition?
Answer: No of partitions doesn't just depend upon the size(1 partition for 10GB), it also depends on the provisioned rcu and wcu.
If you provision 1000 rcu , 1000 wcu , it will use 2 partitions (1000rcu/3000 + 1000wcu/1000) Then, each partition will get half of RCU and half of WCU which is 500rcu and 500wcu per partition.
and yes, if there is only one partition entire rcu and wcu will be used by that partition.
But with Adaptive Capacity, unused rcu/wcu will be distributed to hot partitions, with which we don't have to worry about hot partitioning unless we endup consuming more than provisioned.


Java how to determine Square contains another shapes inside

Question: In squre2d plane class...
i need logic to calculate shape is inside the square or outide......
shape contain point (x,y ) which can be circle center or topleft point of square
and a double length which can be circle radius or side length of square...
How to identify  given circle is inside the square or outside....
         and square is inside the  square or outside....
Comment: So, what's your question?
Answer: Your question isn't clear, but I think that you're asking how to determine the type of Shape that something is.
Given some Shape s, you can determine its type not by checking the equality to a subclass of Shape, but by using the instanceof keyword, like so:
if (s instanceof Circle) { ... }
Once you do this, you can cast s as a Circle and perform the operations on it as if it were a Circle.
if (s instanceof Circle) {
  Circle c = (Circle) s;
  // Do what you have to do to c
  s = c;
}

Comment: i am sorry being unclear .... i have idea about casting object i need logic to check weather given circle shape or square shape inside of a square or not ....... @wadda_wadda


When I press a 'z' on the keyboard I want it to change the key "a" that had sound1.wav to now play a sound2.wav when pressed

Question: So what I'm trying to accomplish is this:
Pressing 'a' on keyboard plays 'hello.wav'.
Pressing 'z' on keyboard changes the key 'a' to 'goodbye.wav'.
Now by pressing 'a' on keyboard it plays this 'goodbye.wav' instead of 'hello.wav'.
So in html I have a div of a bunch of audio id:
<code>            <audio id="c1" controls style="display:none">
              <source src="hello.wav" type="audio/mpeg">
            </audio>
</code>
and to trigger the sound is by pressing the key "a" which is keycode=65 and the javascript code is:
<code>    document.addEventListener('keydown', function(e) {
      if (e.keyCode == 65) {
        document.getElementById('c1').play();
      }
    });
</code>
What I don't know how to do is that if I pressed key "z" then keycode == 65 would now play goodbye.wav instead of hello.wav:
<code>     <audio id="ex1" controls style="display:none">
          <source src="goodbye.wav" type="audio/mpeg">
    </audio>
</code>
Answer: You could track if z was pressed using some flag, and on A key, play the approrpiate music. Hope I've understood your requirement correctly.
<code>var enableGoodbye = false;
document.addEventListener('keydown', function(e) {
  if (e.keyCode == 65) {
    if (enableGoodbye === true)
        document.getElementById('ex1').play();
    else
        document.getElementById('c1').play();
  } else if (e.keyCode == 90) { //If Z, set flag to true
        enableGoodbye = true;
  }
});
</code>
Here is a fiddle: http://jsfiddle.net/t8owxqo6/
Comment: Thanks! so z is pressed and enableGoodbye = true. How can I get it back to false if z is pressed again?
Comment: @Qwisatz In  that case, simply flip `enableGoodbye` instead of setting it to true i.e. instead of `enableGoodbye = true;`, use   `enableGoodbye = !enableGoodbye`. Updated fiddle: http://jsfiddle.net/t8owxqo6/2/
Comment: That's a little more complicated. In which order will they toggle? Or is it randomly pick one from a list?
Comment: Thanks! how could I get z to toggle a bunch of audio files instead.                                                                       1.pressing key 'a' plays 'c3.mp3' and pressing key 's' plays 'd3.mp3'                                                                              2.'pressing 'z' changes key'a' to play 'c2.mp3'. and also key's' to play d3.mp3.  http://jsfiddle.net/qwisatz/b5t5mb3v/


Using one style on several buttons with different background images

Question: Hi I am trying to style several buttons in one menu with the same size and shadow,
I found code here How to provide shadow to Button to help me do this but I want each button to have a different background image but as I am already calling this style using          android:background="@anim/button_menu" I cannot change the background of each button by saying android:background="@drawable/imageclassroom" as background has already been called. Any help on how to overcome this issue would be great
Answer: use this tyep make a color button
 <Leniarlayout
 android:layout_width="match_parent"
 android:layout_hight ="40dp"
 android:background ="#000"
 android:padding ="5dp">

 <Button
 android:id="@+id/angry_btn"
 android:text="Button"
 android:textColor="#FFFFFF"
 android:textSize="30sp"
 android:layout_width="270dp"
 android:layout_height="60dp"
 android:background="@drawable/(set image path)"
 android:shadowColor="#A8A8A8"
 android:shadowDx="0"
 android:shadowDy="0"
 android:shadowRadius="5"
 />
 </Leniarlayout>

Comment: thats cool but doesn't solve my problem, I am trying to apply a style to several buttons but also change the background of each button so that they all look different
Comment: what type of style u want
Comment: all buttons should have curved corners with a shadow behind them and shadow behind the text, then each button will have a different image as the background
Comment: all you are saying is great except I don't know how to set the button background as an image
Comment: android: background = "@drawable/image.file
Comment: yes but I cant use that and andorid:background="drawable/ the xml file    as there is two android:background which is not allowed
Comment: edit your image in use Photoshop customize size example :60x30 pixel
Comment: btn backgroud using image file k shadow btn using put the bellow code in button  android:shadowColor="#A8A8A8"
 android:shadowDx="0"
 android:shadowDy="0"
 android:shadowRadius="5"
Comment: What you are saying adds the shadow to the text in the button not the other edge of the button
Comment: Yes that adds shadow to the text I want shadow on the outside of the button not the text just the button
Comment: use above code create linear-layout set shadow background on linear-layout put button on linear-layout


Pytorch DDP get stuck in getting free port

Question: I try to get a free port in DDP initialization of PyTorch. However, my code get stuck. The following snippet could repeat my description:
def get_open_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

def setup(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    port = get_open_port()
    os.environ['MASTER_PORT'] = str(port)   # '12345'

    # Initialize the process group.
    dist.init_process_group('NCCL', rank=rank, world_size=world_size)

class ToyModel(nn.Module):
    def __init__(self):
        super(ToyModel, self).__init__()
        self.net1 = nn.Linear(10, 5)

    def forward(self, x):
        print(f'x device={x.device}')
        return self.net1(x)

def demo_basic(rank, world_size):
    setup(rank, world_size)

    logger = logging.getLogger('train')
    logger.setLevel(logging.DEBUG)
    logger.info(f'Running DPP on rank={rank}.')

    # Create model and move it to GPU.
    model = ToyModel().to(rank)
    ddp_model = DDP(model, device_ids=[rank])

    loss_fn = nn.MSELoss()
    optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)  # optimizer takes DDP model.

    optimizer.zero_grad()
    inputs = torch.randn(20, 10)  # .to(rank)

    print(f'inputs device={inputs.device}')
    outputs = ddp_model(inputs)
    print(f'output device={outputs.device}')

    labels = torch.randn(20, 5).to(rank)
    loss_fn(outputs, labels).backward()

    optimizer.step()

    cleanup()

def run_demo(demo_func, world_size):
    mp.spawn(
        demo_func,
        args=(world_size,),
        nprocs=world_size,
        join=True
    )

run_demo(demo_basic, 4)

The function get_open_port is supposed to free the port after invocation. My questions are: 1. How does it happen? 2. How to fix it?
Answer: The answer is derived from here. The detailed answer is: 1. Since each free port is generated from individual process, ports are different in the end; 2. We could get a free port at the beginning and pass it to processes.
The corrected snippet:
def get_open_port():
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.bind(('', 0))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        return s.getsockname()[1]

def setup(rank, world_size, port):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = str(port)

    # Initialize the process group.
    dist.init_process_group('NCCL', rank=rank, world_size=world_size)

def cleanup():
    dist.destroy_process_group()

class ToyModel(nn.Module):
    def __init__(self):
        super(ToyModel, self).__init__()
        self.net1 = nn.Linear(10, 5)

    def forward(self, x):
        print(f'x device={x.device}')
        # return self.net2(self.relu(self.net1(x)))
        return self.net1(x)

def demo_basic(rank, world_size, free_port):
    setup(rank, world_size, free_port)

    logger = logging.getLogger('train')
    logger.setLevel(logging.DEBUG)
    logger.info(f'Running DPP on rank={rank}.')

    # Create model and move it to GPU.
    model = ToyModel().to(rank)
    ddp_model = DDP(model, device_ids=[rank])

    loss_fn = nn.MSELoss()
    optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)  # optimizer takes DDP model.

    optimizer.zero_grad()
    inputs = torch.randn(20, 10)  # .to(rank)

    print(f'inputs device={inputs.device}')
    outputs = ddp_model(inputs)
    print(f'output device={outputs.device}')

    labels = torch.randn(20, 5).to(rank)
    loss_fn(outputs, labels).backward()

    optimizer.step()

    cleanup()

def run_demo(demo_func, world_size, free_port):
    mp.spawn(
        demo_func,
        args=(world_size, free_port),
        nprocs=world_size,
        join=True
    )

free_port = get_open_port()
run_demo(demo_basic, 4, free_port)


Is there a short cut for going back to the beginning of a file by vi editor?

Question: When reading a long file by vi editor, it would be very nice to get back to the beginning of the file by some short cuts when you really need to do so. Even ctrl+B sometimes is too slow. Does anyone know such a tool?
Answer: After opening a file using vi
1) You can press  Shift + g  to go the end of the file
and
2) Press g twice to go to the beginning of the file
NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)
Comment: gg does not exist in vi, only Vim.
Comment: @Subhashree Pradhan - Thank you for the insights on Vi Vs Vim. However, looks like there is no such operator/command called 'Shift + GG' - I have just verified in both Vi and Vim. Otherwise, you can use 1G to go to the beginning of the file as the operator G takes a quantifier as a prefix.
Comment: `Shift` + `g` ---> Go to the bottom of the file.
`Shift` + `GG` ---> Go to the top of the file.
Answer: using :<line number> you can navigate to any line, thus :1 takes you to the first line.
Answer: Go to the bottom of the file

G
Shift + g

Go to the top of the file

g+g
Answer: Key in 1 + G and it will take you to the beginning of the file. Converserly, G will take you to the end of the file.
Comment: Works fine in AIX
Comment: Works in OpenBSD
Comment: Works in FreeBSD.
Answer: Well, you have [[ and ]] to go to the start and end of file. This works in vi.
Answer: To go end of the file:
press ESC
1) type capital G (Capital G)
2) press shift + g (small g)
To go top of the file there are the following ways:
press ESC
1) press 1G (Capital G)
2) press gg (small g) or 1gg
3) You can jump to the particular line number,e.g wanted to go 1 line number, press 1 + G
Answer: In command mode: : + 1  will take you to first line
Comment: Very useful to go to any line in the file.
Answer: Typing in 0% takes you to the beginning.
100% takes you to the end.
50% takes you half way.
Answer: I've always used Ctrl + Home (start of file) and Ctrl + End (end of file).
Works in both insert and nav modes.


What's the measure of the angle $\angle DAC$ in the triangle below?

Question: For reference: In the figure, $AB = 11$, $BC = 5$ and $DE = 3$.
Calculate $\angle DAC$.

My progress:
Extend $BE$ until$I: F\in AD$
Angle chasing: $HBI = \theta$
Can I say that the triangle $ABI$ is isosceles e therefore $\angle AIB = \theta \implies$
$\triangle ABI: 90^o = 3\theta \therefore \theta = 30^o$?
Comment: How do you know that angle at $E$ is right?
Comment: @Aqua  sorry...it was an error in the drawing...the indication was missing
Answer: I don't see really why is $ABI$ isosceles.
Let $S$ be a midpoint of $AH$ and  $x= CE = BE$ and $BH = t$.
If angle at $E$ is realy right then we have $$\triangle AEC\sim \triangle ABH \implies {16\over 2r} = {x+3\over t}$$ and $$\triangle BCD\sim \triangle BHS \implies {5\over t} = {x\over r}$$
We get $${t\over r} = {5\over x} = {x+3\over 8} \implies x^2+3x-40 =0\implies x=5$$
and so angle is $30^{\circ}$.
Comment: would  be x = CD and CD = BD
Answer:
Note that $BE = CE$. If $H$ is the foot of the perp from $E$ to $BC$, $BH = BC/2$. Also, $\triangle BEH \sim \triangle CAD$.
If $BE = CE = x$,
$ \displaystyle \frac{CD}{AD} = \frac{BH}{BE}  ~ \text { or } ~ \frac{3+x}{16} = \frac{5/2}{x}$
$x^2 + 3x - 40 = 0 \implies x = 5$
So, $\triangle BCE$ is equilateral and $\angle C = 60^\circ$. Hence $\angle A = 30^\circ$.
Comment: Interesting solution.


How to prevent codeigniter to use cache

Question: When I am logging out form  my account than page is redirecting me to login page . But if i am pressing back button then it is showing me all the previous pages i visit.
I dont know where to set or reset it.
Please check my logout function
/**
 * Logout user
 */
public function logout()
{
    $this->session->sess_destroy();
    logout_user();
    redirect('login');
}

I even set a function to get user details in
 parent::__construct();
    // redirect to Login page if user not logged in
    $this->mUser = get_user();
    if ( empty($this->mUser) )
    {
        redirect('login');
        exit;
    }

Answer:
You cant control Browser back button. For that you can check each and every controller/method whether session is set or not.
if set allow user to view page
if not redirect the page to login
public function login()
{
        $session = array(
        'username'  => $name,
        'logged_in' => TRUE
    );

    $this->session->set_userdata($session);
}

public function home()
{
    $user = $this->session->userdata('username');//check session is set
    if(empty($user))
    {
        $this->session->set_flashdata('error', 'Session has Expired');
        redirect('controller/method');//loging page
    }
    else
    {
        $this->load->view("my_view");
    }
}

NOTE : I have already running with this Error. I found lot of possible answers but this one only effects.
Answer: I think this is browser cache issue, So try to add the following to the pages where users are required to be logged in:
//Prevent browsers from using history to browse in the user system.
$this->CI->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->CI->output->set_header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
$this->CI->output->set_header("Pragma: no-cache");

Please take a look below threads, hope you will get some more help from there:
Browser Cache issue in codeigniter
logout issue in code igniter (PHP)

How to prevent codeigniter to use cache


Why is my ScrollView too wide only when it doesn't need to scroll?

Question: I have an activity layout file:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/compose_message_view"
        style="@style/Container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout style="@style/SectionContainer" >

            <TextView
                style="@style/FieldHeader"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:focusable="true"
                android:focusableInTouchMode="true" />

            <Spinner
                android:id="@+id/compose_message_department"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="8dp"
                android:prompt="@string/compose_message_department_prompt"
                android:spinnerMode="dropdown" />
        </LinearLayout>

        <LinearLayout style="@style/SectionContainer" >

            <TextView
                style="@style/FieldHeader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawablePadding="8dp"
                android:text="@string/message_account_label" />

            <Spinner
                android:id="@+id/compose_message_account"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingBottom="8dp"
                android:prompt="@string/compose_message_account_prompt"
                android:spinnerMode="dropdown" />
        </LinearLayout>

        <EditText
            android:id="@+id/compose_message_subject"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="32dp"
            android:layout_marginTop="16dp"
            android:hint="@string/compose_message_subject_hint"
            android:inputType="textCapSentences" />

        <EditText
            android:id="@+id/compose_message_body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/compose_message_body_hint"
            android:inputType="textMultiLine|textCapSentences" />
    </LinearLayout>

</ScrollView>

The relevant styles look like this:

Now when I open this activity on a Nexus 7 in landscape (haven't tried other tablets yet), the ScrollView and its contents extend beyond the right edge of the screen. When I type several lines into the compose_message_body EditText so that the UI extends below the bottom of the screen, the right edge of the UI comes in to where it belongs. See screenshots below.

Any ideas as to what is going on here?
Answer: This is a side effect of using the fillViewPort attribute on your ScrollView. If you have set fillViewPort to true, then this will only be taken into account if the measured height of your child is lower than the height of your ScrollView. In that case the ScrollView will stretch the content to fill the viewport and your margins won't be applied correctly. As soon as your child's content is greater than the height of your ScrollView, your margins will be applied correctly.
I suggest to not use margins on your child layout (LinearLayout) that you have placed in the ScrollView, but only use padding.
So your Container style could become

Comment: You got me on the right track, so thank you very much for that. For the record, I ended up removing the margin from the container and adding padding to the ScrollView (equal to the removed margin). This allowed me to keep the style of the whole screen. I also needed to add `android:scrollbarStyle="outsideInset"` to the ScrollView to allow scrolling outside the inner LinearLayout.
Answer: In styles, your container has a margin left 130dp. Pushing your entire layout to the right by that much. If you set it to 0dp it should be in its correct position.


How to set the vs project's PostBuildEvent to download from FTP on Linux?

Question: I need to compile a VS project under Linux using MonoDevelop. It worked successfully except the command at the project.csproj file like this:
<PostBuildEvent>echo get pub/xxx.exe | ftp -A xxx.com</PostBuildEvent>

It can't run on Linux.I know it is possible to use a sh-script to establish the ftp connect, but I really want to know how to run it just by setting the project's postBuildEvent. The code I tried to connect FTP server is this:
echo anonymous |ftp -p xxx.com

This couldn't login to the server.I could use it at normal Linux's command line.
Thanks.
Answer: OK it is so easy.Just needs 7zSD.sfx and a config.txt, then
cat 7zSD.sfx config.txt yourproject'spackage.7z > yourproject.exe


Using a UserControl type vs a control's concrete type

Question: Okay, I understand what a UserControl is and how they can be shared across multiple Windows/Views to share functionality, etc. Though, what is the benefit of using a UserControl type? It seems a lot cleaner if you were to use the root control instead of wrapping it inside a UserControl.
Example:
<UserControl>
   <Grid>
     //...
   <Grid/>
</UserControl>

vs.
<Grid>
  //...
</Grid>

Using the root control also has the benefit if reducing the VisualTree.
Answer: UserControl has some properties it inherits from ContentControl, like ContentTemplate, ContentTemplateSelector, some other stuff. If you don't need those, you can create a user control, change the outermost element to Grid and change its base class to Grid in the .xaml.cs, and it'll compile. At least with the trivial example I just tried, it works fine.
However, unless you've identified some concrete problem being created by UserControl in your application, I can't see any reason to go to the trouble. But go ahead, if you like doing things that way.
Comment: Right, I understand that UserControl does have some "special" properties, like the ones you have mentioned. I've worked with both ways, and feel that it's cleaner to just remove the UserControl type from the root all together if you are not utilizing UserControl specific properties.
Comment: Yeah, if that's your thing.


Jquery tablesorter row hover

Question: I need a snippet to highlight a table row when a mouse is hovered. I was not able to add this functionality if it has jquery tablesorter plugin.
Answer: Without affect the zebra widget of tablesorter, you could add some additional css in tablesorter/style.css
table.tablesorter tr.even:hover td,
table.tablesorter tr.odd:hover td {
    background-color: blue;
}

Answer: To highlight rows in a table, you could use:
$(document).ready(function() {
    $("table").tablesorter();
    $('table tr').has(':not(th)').hover(
        function(){
            $(this).data('currColor',$(this).css('background-color'));
            $(this).css('background-color','#cdd');
        },
        function(){
            $(this).css('background-color',$(this).data('currColor'));
        }
    );
});

http://jsfiddle.net/userdude/gjm6g/2/
Comment: existing css should not be removed.
Answer: You could try using the jQuery.Colorize plugin along with tablesorter. It will allow you to retain alternative colors. http://jquerycolorize.blogspot.com/2012/01/how-to-use-tablesorter-plugin-with.html
Btw, if you use asp.net mvc a better option would be to use MvcContrib Grid.
Answer: I wanted to further analyze the row metadata & display an overlay. I found this question, but the solutions didn't really work properly with tablesorter. I found a working solution from this 2009 blog post:
http://rogtopia.com/entries/jquery-js/tablesorter-hover-with-custom-widget
Re-add hover by creating a tablesorter widget.

Jquery tablesorter row hover


Problem with Broadcom BCM43142 wireless driver on 14.04

Question: I have been facing some issues with the wireless drivers on my lenovo Z5070 laptop. Here is the history of the problem

After installing 14.04 Wifi was not working. So I followed the below article and installed bcmwl-kernel-source.

Installing Broadcom Wireless Drivers

After installing this driver, I am able to connect to Wifi. But the connection drops every now and then. I searched online and found the below article. But the issue in the referred  article uses a different wifi chipset.

Drivers for Broadcom BCM43142 on Ubuntu 14.04 (Trusty Tahr)
Please help me fix this. I installed all the upgrades to check if that fixes the issue. But it didn't help. I also tried disabling the ipv6.
Answer: I've been struggling with the same issue with Broadcom BCM43142 on my HP Envy 15 Touchsmart, Ubuntu 14.04. The Wifi card performance deteriorated after an update I did with Software Updater.
I tried purging and reinstalling bcmwl-kernel-source, installing firmware-b43-install and b43-fwcutter in various combinations. Nothing worked.
In the end, I had to downgrade bcmwl-kernel-source to a lower version by doing the following in the terminal:
sudo apt-get remove --purge bcmwl-kernel-source
sudo apt-get install bcmwl-kernel-source=126.96.36.199+bdcom-0ubuntu2
sudo reboot

It's not ideal, but the wifi now works as it did before the update.
Comment: I found that this was happening because of the laptop was far away from the router. Once I moved to the other room in my house there were no issues.
Answer: I had no wifi after upgrading the kernel. rfkill always showed hard blocked: yes
and I was unable to turn it off, not even through BIOS. I tried everything but I finally found the solution that worked immediately.
All you need to do is COVER THE PIN 20 OF THE WIFI PCI-CARD with some tape.
Answer: I have been facing the same issue with my wireless and was able to solve it by upgrading the kernel to 3.18
https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/1297286
Kernel update:
Step 1)
go to URL: kernel.ubuntu.com/~kernel-ppa/mainline/v3.18-vivid/
Step 2)
Choose the kernel suitable for your system (32-bit or 64-bit)
In my case I chose: linux-image-3.18.0-031800-generic_3.18.0-031800.201412071935_amd64.deb
Step 3)
Download it
Step 4)
Open it using the Ubuntu Software Center for installing it.
Step 5)
Reboot
Step 6)
Check kernel version: Open Terminal with CTRL-ALT-T, type "uname -a" and then hit  in the command prompt. The kernel version should be on 3.18 now and your wifi issue hopefully fixed.
I am now enjoying a stable 802.11n connection at around 300mbits.
Hope that helps.
Comment: did this. got completely screwed. Wifi is not working at all
Comment: Reboot, hold shift key during boot until grub menu appears, select Advanced Options for Ubuntu and select a 3.13 kernel.  Download the newer version of the driver from http://packages.ubuntu.com/utopic/bcmwl-kernel-source and see if it works in the 3.18 kernel


What to use to harden up a gravel driveway

Question: I have a gravel driveway uphill. I put new 1/2" rock gravel in last fall because of washout. I also spread concrete and sprayed it, but it didn't take. I have a 05 Harley Davidson Road King custom that I can't get up or down the driveway without almost dumping it.
Can I put anything on it to harden it up enough to get my bike up and down? It's too long to cement or asphalt it.
Comment: Unfortunately, it may be difficult to fix now. It would have been better to have used a self-binding gravel. These gravels contain a range of particle size from fines, through sand to gravel. Local quarries are likely to produce some form of gravel with fines. It might be possible to top dress with smaller aggregates and sand to approximate a self-binding gravel in situ. Results may vary (hence a comment rather than an answer) and it is would be worth experimenting with a small area first.
Answer: What shape is the gravel?  Go look at railroad ballast, you want that stuff, aka "crushed stone", very jaggy and will interlock when tamped down. Very hard to shovel for that reason. You want a smaller size though.
Any sort of round or half-round pea gravel type stuff has to go.  Get a loader, shovel it outta there, save it for aggregate for concrete.
The difference is night and day.
Answer: You could use a plate compactor and attempt to compact the gravel into the soil to provide a firm base. Take a look at this similar post for good suggestions.
Answer: Here around Pittsburgh, Pa. we have a combination gravel called "modified". It has several sizes of lime or slag chips and a lot of what is called "fines". You spread it out, tamp it down with a compactor and after a short time it compacts to a very hard surface. You can still dig it up with aggressive tire action,  but it is better than the stuff you used.  George of all trades has a similar recommendation
Answer: I had the same promblem with my driveway a couple years ago and i got estimates on getting it both asphalt and concrete and both were really expensive but the asphalt guy mentioned a tar and chip driveway was what i needed for traction and for the price i could afford which was a fraction of the price of asphalt and the best part was it didnt require regular maintenance like seal coating or cracking like asphalt or concrete and it also brought a very decorative look to my driveway. Maybe you should check for tar and chip pavers and ill post a link to what im referring to.https://youtu.be/IgYnrFt3TqM


Meaning of "print test page" "print self-test page"and "clean print heads"

Question: In System->Administration->Printing, when choosing a printer's property, we have three options: "print test page" "print self-test page" and "clean print heads".
I was wondering what their differences are? Thanks and regards!
Answer: A test page is one sent from Ubuntu containing the Ubuntu/CUPS logo and some coloured charts.
A self-test page is a simple command sent to the printer to instruct it to do exactly that - most printers will print out a sheet showing the expected life of their ink cartridges/drum, toner, how many pages they've printed in their life and so on.
Having said that, Self-Test Page doesn't work on either my Brother HL-2030 or my HP 2605dn via CUPS. The 2605dn prints "PrintSelfTestPage" and the HL-2030 does nothing!
Clean print heads should be fairly self explanatory though :)
Comment: Thanks! Why do we need to "clean print heads"?
Comment: I think it was more relevant in the days of inkjets where ink could frequently dry up in the nozzles and really screw up the print quality. These days with lasers, not so much. I've never pressed that button for my lasers and nothing's stopped working ;)