Set a session when page is loaded

Question: I want to define a session in contributed module (field collection module) in drupal 7 when the page is loaded.
This session takes a value from the URL and fill one of the field that depend on it. I defined a session in the form_alter function but I need to refresh the page to let the session take the value? So, could anyone tell me where I can define it? In which function of the module?
Comment: `In which function of the module?` see [How to run check on each page load?](http://drupal.stackexchange.com/questions/33789/how-to-run-check-on-each-page-load)
Comment: in field_collection_form_alter function.
Comment: I checked the link that you post it. The suggest to use MYMODULE_boot()
function. I try to use it but without any success. I think I cannot use this function in contributed module.
Comment: which contrib module?
Comment: field collection module
Comment: What do you need the session for?
Comment: I need the session to take the node id and then I use this session to get the author of the node and  fill a field with the data that related to the author.
Comment: You don't need a session to do that.
Comment: The session is passed to the view and in the view it will do the contextual filtration depending on the session. So I need this session.
Answer: You can use the session that Drupal creates. Just add your data to an element of the $_SESSION variable:
<code>$_SESSION['my_module']['some_key'] = 'some value';
</code>
It will
Comment: I use this in field_collection_form_alter function but I need to refresh the page to set the session. In which function that I can use it to set the session when page is loaded?
Comment: You don't need to. Drupal already initiates the session.
Comment: Sorry.. But it which file I have to add this session. Does this work if I want to set the node id in the session when the user edit the node?
Comment: You can see it in hook _form_alter like you have already done.
Comment: The session is saved. But the session is set after the page is build. Is there a way to set the session when the page is loaded?
Comment: The session is initiated before page build. Why don't you tell us what you are trying to do, rather than how you are trying to do it.
Comment: I posted a question in this [link](http://drupal.stackexchange.com/questions/227656/the-data-in-unlimited-entity-reference-select-field-does-not-appear-after-adding) but unfortunately nobody help me or maybe nobody know how we can solve this issue. So, I tried to solve my issue by using another way. I tried to save the node id in a session then I pass it to the view. in contextual view i add this code in php code '$nidar=(int)$_SESSION['field_collection']['favcolor'];

$node = node_load($nidar);

$uid =  ($node->uid);

drupal_set_message('user id: '. $uid ,'warning');

return $uid;'
Comment: I added the session in form_alter function but I could not get the user id until I refresh the page once.

Set a session when page is loaded


Ubuntu 10.04 32-bit server only sees 8TB of 10TB LUN

Question: I've created a 10TB LUN (7x 2TB disks in RAID6) on a storage array and presented it to our backup server, running Ubuntu 10.04 32-bit. The OS only sees 8000GB as per fdisk:
# fdisk -l /dev/sde

WARNING: GPT (GUID Partition Table) detected on '/dev/sde'! The util fdisk
doesn't support GPT. Use GNU Parted.

Disk /dev/sde: 8000.0 GB, 7999999442944 bytes
255 heads, 63 sectors/track, 972611 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/sde doesn't contain a valid partition table

This isn't a filesystem issue (I plan to use XFS FWIW), because I'm seeing the incorrect capacity before I've even partitioned this device.
I've searched Google high and low and I can't seem to find an answer on where this limit is. Is it because of the 32-bit kernel?
update: using parted doesn't make a difference.
# parted /dev/sde
GNU Parted 2.2
Using /dev/sde
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel gpt
(parted) print
Model: YA-16SAE Backup_Vol_001 (scsi)
Disk /dev/sde: 8000GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start  End  Size  File system  Name  Flags

(parted) quit
Information: You may need to update /etc/fstab.

Comment: Did you even try the suggestion fdisk gave you? Use `parted` to see more accurate information.
Comment: @JannePikkarainen: no difference, updated question.
Comment: At this point the question becomes, did you configure the storage array _correctly_? That's what I would be checking right now.
Comment: @MichaelHampton: the configurable values when creating the LUN are the stripe size (which AFAIK has no impact on this) and ">2TB volume support" which is either "64bit LBA" (which I selected) or "4k block". I don't recall the specifics, but last time I looked at this, "64bit LBA" was preferred over "4k block".
Comment: What does dmesg say on the matter?  Can you access the LUN with the full 10TB from a different type of system?
Answer: First, you shouldn't be using fdisk. It can't create partitions over 2TB anyway.
Check to see whether it's a problem with fdisk by using parted:
parted /dev/sde print

If things look good, put a GPT label and a partition on it:
parted /dev/sde mklabel gpt
parted /dev/sde mkpart primary xfs 1 -1

If things don't look good (which you said they didn't) then it's time to double check that you actually put all seven disks in the array, rather than just six of them.
Comment: I wasn't using fdisk to create partitions, I just used the `-l` option to view the block device properties. parted also only sees it as 8000GB.
Answer: Well that's annoying. After a reboot its now showing as 10000GB. Partitioned, formatted, mounted, rebooted, no issues.


Strimzi kafka - Topic authorization exception on non-tls

Question: i have a Strimzi kafka cluster, deployed using the following yaml.
LoadBalancer is enabled on port 9094, without TLS
I've a KafkaTopic created, and when i try to produce to the Topic on port 9094, it gives TopicAuthorization exception.
# KafkaDeployment.yaml
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
metadata:
  name: dataproc-poc #1
spec:
  kafka:
    version: 3.0.0
    replicas: 3
    listeners:
      - name: plain
        port: 9092
        type: internal
        tls: false
      - name: tls
        port: 9093
        type: internal
        tls: true
      - name: external
        port: 9094
        type: loadbalancer
        tls: false
    authorization:
      type: simple
    config:
      offsets.topic.replication.factor: 3
      transaction.state.log.replication.factor: 3
      transaction.state.log.min.isr: 2
      log.message.format.version: "3.0"
      inter.broker.protocol.version: "3.0"
    storage:
      type: jbod
      volumes:
      - id: 0
        type: persistent-claim
        size: 2Gi
        deleteClaim: false
    logging: #9
      type: inline
      loggers:
        kafka.root.logger.level: "INFO"
  zookeeper:
    replicas: 3
    storage:
      type: persistent-claim
      size: 2Gi
      deleteClaim: false
    resources:
      requests:
        memory: 1Gi
        cpu: "1"
      limits:
        memory: 2Gi
        cpu: "1.5"
    logging:
      type: inline
      loggers:
        zookeeper.root.logger: "INFO"
  entityOperator: #11
    topicOperator: {}
    userOperator: {}

# kafka-topic.yaml
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaTopic
metadata:
  name: my-topic
  labels:
    strimzi.io/cluster: dataproc-poc
spec:
  partitions: 3
  replicas: 3
  config:
    retention.ms: 7200000
    segment.bytes: 1073741824

apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaUser
metadata:
  name: my-topic
  labels:
    strimzi.io/cluster: dataproc-poc
spec:
  authentication:
    type: scram-sha-512
  authorization:
    type: simple
    acls:
    # Topics and groups used by the HTTP clients through the HTTP Bridge
    # Change to match the topics used by your HTTP clients
    - resource:
        type: group
        name: mygroup
      operation: Read
    - resource:
        type: topic
        name: my-topic
        patternType: literal
      operation: Write

---
apiVersion: kafka.strimzi.io/v1beta2
kind: KafkaBridge
metadata:
  name: my-topic
spec:
  replicas: 1
  bootstrapServers: dataproc-poc-kafka-bootstrap:9092
  http:
    port: 8080

When i try to access the Topic using commandline, it gives the error as shown below:
Karans-MacBook-Pro:dataproc-poc karanalang$ $CONFLUENT_HOME/bin/kafka-console-producer --broker-list 184.108.40.206:9094 --topic my-topic
>hi therr
[2022-01-30 21:59:47,985] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {my-topic=TOPIC_AUTHORIZATION_FAILED} (org.apache.kafka.clients.NetworkClient)
[2022-01-30 21:59:48,008] ERROR [Producer clientId=console-producer] Topic authorization failed for topics [my-topic] (org.apache.kafka.clients.Metadata)
[2022-01-30 21:59:48,012] ERROR Error when sending message to topic my-topic with key: null, value: 8 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TopicAuthorizationException: Not authorized to access topics: [my-topic]

Any ideas what i need to do to fix this ?
tia !
Answer: None of your listeners has enabled authentication. So when you connect to it, you are just authenticated as ANONYMOUS. And ANONYMOUS has no ACLs, so it is not allowed to do anything. So you either need to enable authentication and use it or you need to disable the authorization. You should also always check the broker logs where you get the full authroization error with all details and make it more clear what the issue is.
Comment: thanks @Jakub for the input - was able to get this working


How do I add joins with selects in CodeIgniter/ActiveRecord?

Question: I want to add this part to my current sql in Active-Recod-class:
JOIN
(SELECT product_id, max(angle) AS max_angle
FROM image t1
WHERE width = 100 AND height = 200
GROUP BY product_id) AS t1 ON (t1.product_id = mv_products.id)

What would be the correct approach to manage this?
Is the only way to download subquery-class github? https://github.com/NTICompass/CodeIgniter-Subqueries
?
Answer: This is exactly the kind of thing that you shouldn't do via CI's Active Record (Query Builder). It's there to help you with simple queries, not to force you to use it.
This is a custom query as such, should be executed via $this->db->query().
With the currently released versions of CI, you wouldn't be able to do that via AR anyway because join() will break that subquery while trying to escape it (it assumes that you're only passing two field names). CI 3.0-dev allows you to disable field name escaping, but again - you shouldn't use the query builder for what you're asking here.
Comment: Ok thanks a lot for input! My issue is that a LOT of other sql-statements are written with CI'S Active Record and as I understand there are no options to mix custom queries with CI's Active Record. I don't want to retype the whole query (long query based on filters category etc). Anyway I figured out a total different way to solve my problem, but I will give you heads up for your answer because it is very relevant!


encode url in javascript like UrlEncode method of asp.net does

Question: i have a requirement to encode the url in javascript and in redirected page i can't use javascript so i must decode the url back in code. so i needs a javascript encode method which encodes url like URLEncode method of asp.net so that i can decode it in code with UrlDecode method
Answer: JavaScript encodeURI() Function
http://www.w3schools.com/jsref/jsref_encodeURI.asp
http://www.w3schools.com/jsref/jsref_decodeURI.asp
Answer: <code>alert(escape("http://stackoverflow.com/questions/4470255/encode-url-in-javascript-like-urlencode-method-of-asp-net-does"));
</code>
Answer: You have two native options: encodeURI() or encodeUriComponent()


best way to process images already on S3 (rails)

Question: I have a set of images on Amazon S3, and I'd like to automatically generate thumbnails for them to serve on my site.
I've considered Cloudinary, but it seems that I'd have to copy over all my images to Cloudinary servers first. I want to keep them on S3.
I've considered Dragonfly, but it seems that Dragonfly only works with files I'd upload after installing Dragonfly. I already have uploaded all my files.
What's a good solution for me? I'm in a Rails environment (rails 3.2).
Thanks!
Answer: If it's just a 'set of images' it's not really that well structured. You're better off reorganizing the way you store and manage images.
Try Paperclip.
class ModelName < ActiveRecord::Base

  attr_accessible :image #more here
  has_attached_file :image, :styles => { :large => "450x450>", :medium => "300x300>", :thumb => "150x150>" },
    :storage => :s3,
    :s3_credentials => "#{Rails.root}/config/s3.yml",
    :path => "people/:style/:id/:filename",
    :s3_protocol => "https"

   def original_image_url
     image.url
   end

   def large_image_url
     image.url(:large)
   end

   def medium_image_url
     image.url(:medium)
   end

   def small_image_url
     image.url(:thumb)
   end

 #etc

 end

Then simply do this to assign an existing image to an existing instance through the console:
require 'uri'
@instance.image = open(URI::encode(url))
@instance.save
# s3 will now contain the images in the appropriate sizes in the format specified above.

Since the original will also be saved, I'd advise to then delete the 'set of images' on s3 you started with, otherwise you'll be duplicating them.
Comment: It turns out I was wrong about Dragonfly -- dragonfly can work with already-uploaded files. I'm using that and it's working out great. Thanks for the advice, though, Niall.
Answer: I was wrong about Dragonfly. You can use Dragonfly on already-uploaded files. I'm using it on my project and it's working out great.
Comment: It would be great if you explained how to do this with Dragonfly.


Airflow scheduler keep on Failing jobs without heartbeat

Question: I'm new to airflow and i tried to manually trigger a job through UI. When I did that, the scheduler keep on logging that it is Failing jobs without heartbeat as follows:
[2018-05-28 12:13:48,248] {jobs.py:1662} INFO - Heartbeating the executor
[2018-05-28 12:13:48,250] {jobs.py:1672} INFO - Heartbeating the scheduler
[2018-05-28 12:13:48,259] {jobs.py:368} INFO - Started process (PID=58141) to work on /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:48,264] {jobs.py:1742} INFO - Processing file /Users/gkumar6/airflow/dags/tutorial.py for tasks to queue
[2018-05-28 12:13:48,265] {models.py:189} INFO - Filling up the DagBag from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:48,275] {jobs.py:1754} INFO - DAG(s) ['tutorial'] retrieved from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:48,298] {models.py:341} INFO - Finding 'running' jobs without a recent heartbeat
[2018-05-28 12:13:48,299] {models.py:345} INFO - Failing jobs without heartbeat after 2018-05-28 06:38:48.299278
[2018-05-28 12:13:48,304] {jobs.py:375} INFO - Processing /Users/gkumar6/airflow/dags/tutorial.py took 0.045 seconds
[2018-05-28 12:13:49,266] {jobs.py:1627} INFO - Heartbeating the process manager
[2018-05-28 12:13:49,267] {dag_processing.py:468} INFO - Processor for /Users/gkumar6/airflow/dags/tutorial.py finished
[2018-05-28 12:13:49,271] {dag_processing.py:537} INFO - Started a process (PID: 58149) to generate tasks for /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:49,272] {jobs.py:1662} INFO - Heartbeating the executor
[2018-05-28 12:13:49,283] {jobs.py:368} INFO - Started process (PID=58149) to work on /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:49,288] {jobs.py:1742} INFO - Processing file /Users/gkumar6/airflow/dags/tutorial.py for tasks to queue
[2018-05-28 12:13:49,289] {models.py:189} INFO - Filling up the DagBag from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:49,300] {jobs.py:1754} INFO - DAG(s) ['tutorial'] retrieved from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:49,326] {models.py:341} INFO - Finding 'running' jobs without a recent heartbeat
[2018-05-28 12:13:49,327] {models.py:345} INFO - Failing jobs without heartbeat after 2018-05-28 06:38:49.327218
[2018-05-28 12:13:49,332] {jobs.py:375} INFO - Processing /Users/gkumar6/airflow/dags/tutorial.py took 0.049 seconds
[2018-05-28 12:13:50,279] {jobs.py:1627} INFO - Heartbeating the process manager
[2018-05-28 12:13:50,280] {dag_processing.py:468} INFO - Processor for /Users/gkumar6/airflow/dags/tutorial.py finished
[2018-05-28 12:13:50,283] {dag_processing.py:537} INFO - Started a process (PID: 58150) to generate tasks for /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:50,285] {jobs.py:1662} INFO - Heartbeating the executor
[2018-05-28 12:13:50,296] {jobs.py:368} INFO - Started process (PID=58150) to work on /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:50,301] {jobs.py:1742} INFO - Processing file /Users/gkumar6/airflow/dags/tutorial.py for tasks to queue
[2018-05-28 12:13:50,302] {models.py:189} INFO - Filling up the DagBag from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:50,312] {jobs.py:1754} INFO - DAG(s) ['tutorial'] retrieved from /Users/gkumar6/airflow/dags/tutorial.py
[2018-05-28 12:13:50,338] {models.py:341} INFO - Finding 'running' jobs without a recent heartbeat
[2018-05-28 12:13:50,339] {models.py:345} INFO - Failing jobs without heartbeat after 2018-05-28 06:38:50.339147
[2018-05-28 12:13:50,344] {jobs.py:375} INFO - Processing /Users/gkumar6/airflow/dags/tutorial.py took 0.048 seconds

And the status of job on UI is stuck at running. Is there something i need to configure to solve this issue?
Comment: The line ```INFO - Failing jobs without heartbeat after 2018-05-28 06:38:50.339147``` is just an info message and states what the scheduler is doing, it is not an error message related to your DAG not running. There must be some other reason that your job is hanging.
Comment: I understand that it is not an error message. The problem is that these messages are coming repeatedly.
Comment: Do you know what your scheduler interval is set to in your airflow.cfg file? the scheduler will run every `scheduler_interval` to check for things that need to be scheduled and killed.
Comment: Check https://stackoverflow.com/questions/38200493/scheduling-airfflow-dag-job
Comment: Did you figure out what was causing this? I'm having the same problem.
Comment: @Mazar, I didn't.
Answer: It seems that it's not a "Failing jobs" problem but a logging problem. Here's what I found when I tried to fix this problem.

Is this message indicates that there's something wrong that I should
be concerned?
No.
"Finding 'running' jobs" and "Failing jobs..." are INFO level logs
generated from find_zombies function of heartbeat utility. So there will be logs generated every
heartbeat interval even if you don't have any failing jobs
running.
How do I turn it off?
The logging_level option in airflow.cfg does not control the scheduler logging.
There's one hard-code in
    airflow/settings.py:

LOGGING_LEVEL = logging.INFO

You could change this to:

LOGGING_LEVEL = logging.WARN

Then restart the scheduler and the problem will be gone.
Comment: In my case, it is also marking downstream tasks as "upstream failed". Do you know how to resolve this issue ?
Answer: I think in point 2 if you just change the logging_level = INFO to WARN in airflow.cfg, you won't get INFO log. you don't need to modify settings.py file.
Comment: Thanks for answering! You could improve your answer by stating what "point 2" is, rather than referring to something not in the question, and by explaining why not needing to modify settings.py is preferable.
Comment: Your solution would simply mask an underlying issue, not solve it.


angular2 and ngIf - test if greater or less than

Question: How do I make this work? If value is 9 or less, display "Month", else display "Months". Here's my code:
<select id="analysis_horizon" class="custom-select form-control" [(ngModel)]="basic_setup.analysis_horizon" formControlName="analysis_horizon" describedby="basic-addon_analysis_horizon">
    <option disabled>Select Analysis Horizon</option>
    <option *ngIf="'i<=9'" *ngFor="let i of analysis_horizon_array">{{i}} Month</option>
    <option *ngIf="'i>9'" *ngFor="let i of analysis_horizon_array">{{i}} Months</option>
</select>

This is the error I get:

Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("isabled>Select Analysis Horizon
                                          ]*ngFor="let i of analysis_horizon_array">{{i}} Month
                                          {{i}} Month
                                          9'" [ERROR ->]*ngFor="let i of analysis_horizon_array">{{i}} Months
                                       ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
      Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * ("isabled>Select Analysis Horizon
                                          ]*ngFor="let i of analysis_horizon_array">{{i}} Month
                                          {{i}} Month
                                          9'" [ERROR ->]*ngFor="let i of analysis_horizon_array">{{i}} Months
Answer: You can't use multiple template bindings on one element, in this case *ngIf and *ngFor. You can achieve what you want with interpolation and ternary operator, you don't need to use *ngIf directive:
<select id="analysis_horizon" class="custom-select form-control" [(ngModel)]="basic_setup.analysis_horizon" formControlName="analysis_horizon" describedby="basic-addon_analysis_horizon">
    <option disabled>Select Analysis Horizon</option>
    <option *ngFor="let i of analysis_horizon_array">
        {{i}} {{ i <= 9 ? "Month" : "Months" }}
    </option>
</select>


Ensuring that a symmetric matrix with nonnegative elements is positive semidefinite

Question: I have the following matrix $A$:

symmetric
all positive and/or zero values
the main diagonal is all the same value, $x$.

To ensure that the matrix $A$, is positive semidefinite, must I only ensure that $x \geq 0$?  It seems correct from my thinking, but wanted to make sure. Thanks.
Comment: http://mathworld.wolfram.com/DoublyNonnegativeMatrix.html
Answer: It is not sufficient to have positive diagonal entries.
To see this, consider the matrix
$$
A=\pmatrix{1& 10\\10& 1}.
$$
It has the negative eigenvalue $-9$ to the eigenvector
$$
v=\pmatrix{1\\-1},
$$and is thus not positive semi-definite.
Answer: Note however that a diagonally dominant symmetric matrix is positive semi definite.
In your case it is sufficient to add the condition $x \ge \sum_{j\neq i} A_{ij}, i\neq j$ to ensure $A$ to be positive semi definite.
Comment: Why does it suffice for $x\ge A_{ij}$?  I would appreciate a reference for this if you have one.
Comment: @user3281410 The wikipedia article states this property for Hermitian diagonally dominant matrices, so it applies for real symmetric matrices as well : https://en.wikipedia.org/wiki/Diagonally_dominant_matrix
Comment: I believe you mean to say $x\ge \sum_{j\neq i}^{}A_{ij}$ for all $i$, not just $x\ge A_{ij}$ for all $i\neq j$.  There are symmetric, matrices with nonnegative entries such that the entries on the diagonal are all the same (denoted $x$) and satisfy $x \ge A_{ij}$ but $A$ is not positive semidefinite.  See the first answer here: https://math.stackexchange.com/questions/2669941/is-a-doubly-stochastic-matrix-positive-semidefinite-if-the-maximum-of-each-row-o
Comment: @user3281410 Yep sorry I really meant $x \ge \sum_j A_{ij}, i\neq j$. I've updated the answer !
Comment: @Tool is the converse statement true? If I have a positive semidefinite matrix, can I say that it must also be diagonally dominant with nonnegative real entries on the diagonal?


Parse JSON to array of objects

Question: Currently I'm receiving the following JSON data in my action:
[
    { "civilStatus": "M" },
    "and",
    { "familySize": "2|bw|4" },
    "or",
    { "civilStatus": "D" }
]

I've been trying to use play.libs.Json to parse the string I receive at the server, but I can't find a way to obtain the array nor the objects.
I have also looked at the org.codehaus.jackson.JsonNode documentation, but I didn't figure any way. Also I'm using Java, not Scala.
Comment: Check this question for handling array of objects: http://stackoverflow.com/questions/6349421
Answer: I have found using Gson is easier.  Just add it as a dependency in Build.scala file:
val appDependencies = Seq(
    ... other dpenedencies ...
    "com.google.code.gson" % "gson" % "2.1",
    ... other dpenedencies ...
)

Then just parse with something like:
Gson gson = new Gson();
List<YourCustomBean> data = gson.fromJson(jsonString, new TypeToken<List<YourCustomBean>>(){}.getType());

Parse JSON to array of objects


Como lidar com as caracteres especiais ao introduzir dados ao banco com php+mysql

Question: Então pessoal, estou tentando inserir alguns dados de uma uma tela de registro no banco, mas quando eu insiro, as caracteres especiais bugam no banco. Segue o código no php:

<?php
header('Content-Type: text/html; charset=utf-8');
$fullName = $_POST["name"];
$senha = $_POST["password"];
$confirmSenha = $_POST["confirmPassword"];
$rua = $_POST["endereco"];
$numero = $_POST["numero"];
$bairro =  $_POST["bairro"];
$conn = mysqli_connect("localhost", "usuario", "senha", "teste");
if (!$conn) {
    echo "Failed to connect with MySQL" . mysqli_connect_errno();
}
if ($senha == $confirmSenha) {
    $sql = "INSERT INTO usuario (fullName,senha,rua,numero,bairro) VALUES('$fullName','$senha','$rua','$numero','$bairro')";
    if (mysqli_query($conn, $sql)) {
        echo ("");
    } else {
        echo "Erro";
    }
} else {
    echo ("");
}

E o banco:
No caso, o usuario de id 3 e 5 foi inserido manualmente por uma query no próprio heidisql, os outros que estão bugados forem inseridos por meio do código.
Answer: Olá, como vai?
Então, vamos fazer o seguinte, vamos informar qual o charset o MySQL deve utilizar para a conexão atual, faremos da seguinte forma:
mysql_set_charset("utf8");

Após sua conexão, insira o código acima.
Até breve...
Comment: Obrigado, amigo! Resolveu o erro.
Comment: Utilize as ferramentas para [agradecer](https://pt.meta.stackoverflow.com/questions/605/como-dizer-obrigado-em-respostas), não há a necessidade de escrever obrigado, porem, por nada!


How do I change the comment of a not most recent git commit

Question: So I accidently made a commit with a comment message that was inappropriate while I was in the middle of a messy merge conflict.
Is there a way to change this comment?
I have made commits since then that I would rather not undo.
I tried to google it but I couldn't find a way to do it since i've made 9 commits since then. I don't want to undo those commits because some of those are important. Also I made that commit from my server, so do I need to fix it from that server? Thanks.
Comment: Possible duplicate of [How to modify existing, unpushed commit messages?](https://stackoverflow.com/questions/179123/how-to-modify-existing-unpushed-commit-messages)
Comment: https://stackoverflow.com/search?q=%5Bgit%5D+edit+commit
Answer: Disclaimer: rewriting Git history can be dangerous (when the history is public or shared with others, including yourself on a different system). That said, …

Use Git's interactive rebase mechanism, to reword commits:
git rebase -i $some_commit_before_your_commit

This will show you a list of commits prepended with pick each. Change that pick to reword (or simply r) for the commit you want to edit. Save and exit the file to start the rebasing process. Your $EDITOR will automatically open with the commit's message prefilled. Change to your liking, save, exit. Wait for rebase to finish. Done.
If you then try to push this branch, Git will complain about a "non fast-forward". This is due to the fact that history was rewritten. You need to force-push in this case (see disclaimer above).


Limit supremum properties

Question: I have the following theorem that I'm trying to prove:
Let $(s_n)$ be a bounded sequence and let $m = \lim\sup s_n$. Then the following properties hold:

For every $\varepsilon > 0$ there exists a natural number $N$ such that $n\geq N$ implies that $s_n < m + \varepsilon$.
For every $\varepsilon > 0$ and for every $i\in\mathbb{N}$ there exists an integer $k > i$ such that $s_k > m-\varepsilon$.

What I have so far is the following:

Suppose that for a bounded sequence $(s_n)$, $m = \lim\sup s_n$. Then no number larger than $m$ can be a subsequential limit of $(s_n)$. That is, given any $(s_{n_k})$ and any $\varepsilon > 0$, $\lim_{k\to\infty} s_{n_k} < m+\varepsilon$. Thus there can only be a finite number of terms as large as $m+\varepsilon$, otherwise a subsequence of those terms would have a limit greater than $m$.

The thing I'm struggling with is defining an $N$ such that $n\geq N$ implies $s_n < m + \varepsilon$. Any pointers on how to define such $N$ would be great!
Answer: I will define $(a_m^+)_{m=n}^{\infty}$ to be the sequence $(c_m)_{m}^{\infty}$ where $c_k=\text{sup} (a_N)_{N=k}^{\infty}$ (in other words this sequence consists of the suprerum of the sequence $(a_m)_{m=n}^{\infty}$ with the first element of the sequence shifted each time.) The definition of $\limsup s_n$ is then $\inf(s_{N}^+)_{N=m}^{\infty}$.
(1) We always have $m+\epsilon > m ~
\forall \epsilon > 0$, so that $m+\epsilon>\inf (s_N^+)_{N=m}^{\infty}$.
Now if $m+\epsilon < s_k^+ ~ \forall k\geq m$ , then $ m+\epsilon<\inf(s_N^+)$, a contradiction
So $\exists t\geq m$ such that $m+\epsilon > s_t^+$, or $m+\epsilon > \sup (s_t)_{t}^{\infty}$, and by the definition of supremum, we conclude $m+\epsilon > s_n ~\forall n \geq t$.
(2) One always has $m-\epsilon < m ~\forall \epsilon >0$. Thus,
$m-\epsilon<\inf(S_N^+)_{N=m}^{\infty}$ and thus by the definition of infimum,
$m-\epsilon<s_N^+ \forall N\geq m$, fix $N$
Or, $m-\epsilon <\sup (s_m)_{m=N}^{\infty}$.
Now, if $s_k \leq m-\epsilon ~\forall k\geq N$ it would imply $\sup (s_k)_{k=N}^{\infty}=m-\epsilon < \sup (s_m)_{m=N}^{\infty}$, contradiction!
Thus, $\exists j\geq N$ for which $m-\epsilon < s_j$ holds and we are done
Comment: Hello! It is helpful to relate and understand the relationship between $>$ and $\limsup=\inf(\sup (\text{blah blah}))$,for example if one has that $T>\limsup $ then it would imply $T>\inf (\sup (\text{something}))$ and the presence of $"sup"$ inside $"inf"$ and use of $>$ tells you that $T>\sup (something)$ and by definition of "sup" it follows this holds for all the elements of the sequence $(a_N)^+$ (indeed this is just for motivation, dont take it rigorously) and the existence of $N$ comes from the "inf" in front, you can make a similar analogy between $<$ and $\liminf$,for motivation

Limit supremum properties


What techniques can be used determine the degree of which one set of data can be predicted from another?

Question: Specifically I have to determine to what extend the prices of some houses in one year can be predicted from the prices of some houses in a previous year. The data set is split up into houses of various types. I have made numerical summaries of each set of data in each year and have made normal quantile plots for each type of house in each year but I don't really know where to go from here. Any help or ideas about where to start would be very helpful.
Edit: Would one way to approach this to be to show how similar or different the distributions of the earlier and later year prices are? Similar meaning easier to predict and different meaning harder to predict?
Answer: Sebastian Ruder has some work on measuring the distance of datasets from your target dataset, using Bayesian Optimization:
http://ruder.io/learning-select-data/
Paper: https://arxiv.org/abs/1707.05246 "Learning to select data for transfer learning with Bayesian Optimization"
First couple of paragraphs from the blog post above:
"In Machine Learning, the traditional assumption is that the data our model is applied to is the same as the data we used for training. This assumption is proven false as soon as we move into the real world: many of the data sources we encounter will be very different than our original training data (same meaning here that it comes from the same distribution). In practice, this causes the performance of our model to deteriorate significantly.
"Domain adaptation is a prominent approach to transfer learning that can help to bridge this discrepancy between the training and test data. Domain adaptation methods typically seek to identify features that are shared between the domains or learn representations that are general enough to be useful for both domains. In this blog post, I will discuss the motivation for, and the findings of the recent paper that I published with Barbara Planck. In it, we outline a complementary approach to domain adaptation – rather than learning a model that can adapt between the domains, we will learn to select data that is useful for training our model."


Lumen passport Using $this when not in object context

Question: Hi I'm new in Lumen and i want to build a restful app with oauth2.
so i installed lumen passport.
one of those steps is to add
Dusterio\LumenPassport\LumenPassport::routes($this->app);

in app.php
later once i run php artisan list or any other cmd it show this error :
In app.php line 97:

  Using $this when not in object context

please can some one tell me how could i fix that.
here is the link to the doc i have pursuive:
https://packagist.org/packages/dusterio/lumen-passport
and here is my app file:
<?php

require_once __DIR__.'/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);
// Enable Facades
$app->withFacades();
// Enable Eloquent
$app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/** Add auth for passport**/
$app->configure('auth');

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);

// Enable auth middleware (shipped with Lumen)
 $app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
$app->register(App\Providers\AppServiceProvider::class);
 $app->register(App\Providers\AuthServiceProvider::class);
 $app->register(App\Providers\EventServiceProvider::class);
//added for passport
$app->configure('auth');

// added for flipbox to generate controller and model in lumen
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
//for lumen passport
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
Dusterio\LumenPassport\LumenPassport::routes($this->app);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    require __DIR__.'/../routes/web.php';
});

return $app;

Answer: As the error says: $this is accessible only inside instance methods.
To get an application object, you could call app() function.
In your case:
Dusterio\LumenPassport\LumenPassport::routes(app());

Comment: This will work, although It can just be `Dusterio\LumenPassport\LumenPassport::routes($app);`
Comment: thnk u very very much it works perfectly thnk u again and again


Differential of Hopf's map

Question: Let $$h : \mathbb{C^2} \rightarrow \mathbb{C \times R} $$
$$h(z_1, z_2) = (2z_1z_2^*, |z_1|^2-|z_2|^2)$$
How do you find the differential of $h$ and show it is onto/surjective?
I know that I can express $h$ as $\mathbb{R^4}$ instead of $\mathbb{C^2}$, but then how do I proceed? Do I just differentiate with respect to each $x_1, x_2, x_3, x_4$ instead of $z_1, z_2$ given that $x_2, x_4$ are the imaginary part?
So, let's say $h(z_1, z_2)$ becomes $$h(x_1,x_2,x_3,x_4) = (2(x_1+x_2i)(x_3-x_4i),\  x_1^2+x_2^2-x_3^2-x_4^2) \\ \rightarrow (2(x_1x_3 + x_2x_4), 2(x_2x_3-x_1x_4), x_1^2+x_2^2-x_3^2-x_4^2)$$
But if I start differentiating $h$ with respect to each variable, I am getting a Jacobian matrix $\mathbb{R^{3 \times 4}}$. I think I am doing something wrong here.
Comment: Welcome to Math.SE ! I recommend that you share more of your work when asking a question. This will help to clarifiy the question and understand what is the difficult you encounter. For instance you could to show what you obtain if you differentiate $h$ both ways and make the question more precise.
Answer: In fact you must understand $h$ as a map from $\mathbb{R}^4$ to $\mathbb{R}^3$ and the derivative of $h$ as a the derivative in the sense of real multivariable calculus. You have done this almost correctly (I corrected a typo), and you are right that the Jacobian $Jh(x)$ of $h$ at $x$ is a $3 \times 4$-matrix. With respect to the standard bases of $\mathbb{R}^4, \mathbb{R}^3$ it is the matrix representation  of the differential $Dh(x)$ of $h$ at $x$ which is linear map $Dh(x) : \mathbb{R}^4 \to  \mathbb{R}^3$.
You have to determine for which $x$ the map $Dh(x)$ is a surjection. This is equivalent to determining when $Jh(x)$ has maximal rank, i.e. rank $3$. You have
$$Jh(x) = \left( \begin{array}{rrrr}
2x_3 & 2x_4 & 2x_1 & 2x_2 \\
-2x_4 & 2x_3 & 2x_2 & -2x_1 \\
2x_1 & 2x_2 & -2x_3 & -2x_4 \\
\end{array}\right) = 2 \left( \begin{array}{rrrr}
x_3 & x_4 & x_1 & x_2 \\
-x_4 & x_3 & x_2 & -x_1 \\
x_1 & x_2 & -x_3 & -x_4 \\
\end{array}\right) = 2 M(x) .$$
You see that $Jh(0) = 0$. i.e. $Jh(0)$ has rank $0$. Let us show that the rank is $3$ if $x \ne 0$. Denote by $M_i(x)$ the matrix obtained from $M(x)$ be deleting the $i$-th column. Easy computations show that
$$\det M_1(x) = -x_2(x_1^2 + x_2^2 + x_3^2 + x_4^2)$$
$$\det M_2(x) = -x_1(x_1^2 + x_2^2 + x_3^2 + x_4^2)$$
$$\det M_3(x) = -x_4(x_1^2 + x_2^2 + x_3^2 + x_4^2)$$
$$\det M_4(x) = -x_3(x_1^2 + x_2^2 + x_3^2 + x_4^2)$$
At least one of these four expressions is $\ne 0$ which proves our claim.

Differential of Hopf's map


Dimension of fibers of scheme over $\mathbb{Z}$

Question: Let $X$ be a reduced scheme of finite type over $\mathbb{Z}$: given a prime $p \in \mathbb{Z}$,I'm going to denote as $X_p$ its base change over $\mathbb{F}_p$. I would be interested in knowing the following:is it true that the dimension of $X_p$ is eventually costant?(i.e there exists an $n \in \mathbb{N}$ such that for every $p \geq n$, we have $\dim X_p=n$).
I tried to  reduce to the affine and irreducible  case, so that $X=\operatorname{Spec}(A)$ with $A$ a finitely generated domain. By a stronger version of Noether normalization lemma, there exists an $f \in \mathbb{Z}$ such that there exists a finite injective morphism $\mathbb{Z}_f[x_1,x_2, \dots, x_r] \subseteq A_f$.Now, we have $\dim X_f=r+1$ and I would like that to imply  $\dim X_p = r$ for every $p $ such that $p$ does not divide $f$. The only thing that might be useful that comes to my mind here is   the standard result about fiber dimension:
$$\dim \mathcal{O}_{X_y,x} \geq \dim \mathcal{O}_{X,x}-\dim \mathcal{O}_{Y,y} $$
However, we do not have a real control over $\dim \mathcal{O}_{X,x}$ so I do not know how to conclude. Is there any known statement in the literature? Are there any mild conditions under which this fact is true?
I would also be interested in the following fact: suppose that eventually $\dim X_p=0$ so that every fiber is a finite collection of points. I would like to have $X_p(\overline{\mathbb{F}_p})$ to be also eventually constant. I imagine that one could actually prove something like that the number of irreducible components of maximal dimension of $X_p$ should be eventually constant, but I would know how to prove this.
Comment: My idea would be to use the fact that, if the morphism is flat then it has fibers of constant dimension (see Görtz-Wedhorn, Theorem 14.129). You can understand the points in which $f$ is flat by Theorem 1.16 in [here](https://people.sissa.it/~cscarpa/docs/Flatness.pdf).

You want to restrict $f:X\rightarrow \mathbb{Z}$ to a map $f^{-1}(U)\rightarrow U$ that is flat and whose fibers have the same dimensions they have before the restriction. probably this needs some conditions on $X$ (hopefully dominant when restricted to each component works)
Comment: Looking back at the problem,using that $\mathbb{Z}$ is actually a Dedekind Domain,if every component of $X$ dominates $\mathbb{Z}$, we should get that the map $f:X \to \mathbb{Z}$ is actually flat.(I'm referring to prop. 3.9 in Liu's book about schemes).I've not been able to find the proposition about constancy of fiber dimension you are referring to (I know a similar version for varieties over a field, but I do not  how to extend to the case of varieties over the integers)
Comment: The proposition in a generality enough to apply it here is in Görtz and Werdhorn Algebraic Geometry I as I said. See my answer [here](https://math.stackexchange.com/questions/3357994/precise-general-statement-of-flat-morphisms-being-equidimensional/3625003#3625003) where I talk about this flatness property.
Comment: Oh I'm sorry. I've looked up to the theorem you linked:f I understood well the demonstration, the hypothesis that X is equidimensional can be weakened here if one restricts himself to the points $y$ in $\cup f(Xi)$ where $Xi⊆X$  are the irreducible components of maximal dimension
Answer: This is a simple application of some genericness results.
To handle the dimension side of things, use Stacks 05F7:

Lemma: Let $f:X\to Y$ be a morphism of schemes. Assume $Y$ is irreducible with generic point $\eta$ and $f$ of finite type. If $X_\eta$ has dimension $n$, then there exists a nonempty open set $V\subset Y$ so that for all $y\in V$, the fiber $X_y$ has dimension $n$.

Applied to our situation at hand, the open subset $V$ contains all but finitely many primes, so there is a largest prime $p$ not in $V$. Then $\dim X_q$ is constant for all $q>p$.
For the eventually-dimension-zero case, we note that by our previous work, there's an affine open $U=\operatorname{Spec} S^{-1}\Bbb Z \subset \operatorname{Spec} \Bbb Z$ so that $X_U=\operatorname{Spec} S^{-1}A$ is dimension zero. By your noether-normalization type lemma and an application of generic freeness, we may shrink $U$ so that $S^{-1}A$ is actually finite free over $S^{-1}\Bbb Z$.
As $X\to \operatorname{Spec}\Bbb Z$ is finite type and the generic fiber is geometrically reduced (because the localization of a domain is a domain and reduced implies geometrically reduced in characteristic zero), Stacks 0578 applies and we can again shrink $U$ a bit so that on this open set, $X_U\to U$ has geometrically reduced fibers.
At this point, we have that the fiber over every point in $U$ is geometrically reduced and module-free of the same finite rank, so the only obstruction to saying that it has  the number of $\overline{\Bbb F_p}$-points equal to the rank is that it be a product of separable field extensions of $\Bbb F_p$. But this is not hard: a non-separable field extension has degree divisible by $p$, so all we need to do to guarantee separability is to restrict to primes larger than the finite, constant rank of our fiber. (This last bit was unnecessary because finite fields are perfect and therefore all algebraic extensions are separable.)  So the result is proven.
Your idea about irreducible components is also correct, and can be handled by mostly the same sorts of logic as above: the situation at the generic point will be the situation on a dense open set. I leave the details to you.
Comment: Thank you for the answer! In the $0$ dimensional case, shouldn't it suffice to have the fiber $U_p$ reduced? As a $\mathbb{F}_p$ finite reduced algebra is a product of finite field extensions, which are always separable over $\mathbb{F}_p$, I think. Do you know if  there is any statement of the form " generic fiber reduced $ \Rightarrow$ fiber reduced over an open subset" which does not use the fact about geometrically reduced fiber (which seems a bit hard to prove)?
Comment: You're right, I went a little overboard there - finite fields are perfect, so every algebraic extension is separable. I don't remember another proof of the generically reduced fibers off the top of my head right now, but I don't think that proof is so hard - it's just more genericness arguments, basically.


How to query Nodes by a referenced Term Value (via EntityFieldQuery)?

Question: I have to query my content types (firm_unit) based on different fields conditions, and for that I came to use EntityFieldQuery.
$query = new EntityFieldQuery;

$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $type = 'firm_unit')
  ->propertyCondition('status', 1);

This is nice when I want to query conditions on direct content fields, like these:
$query->fieldCondition('field_name', 'value', $keyword, 'CONTAINS');
$query->fieldCondition('field_sector', 'value', $sector, '=');

It seems to be unable to directly access, and then query by, referenced contents, like names/titles and fields of referenced terms (it just can access their tids).
Which is then the way I may query my node contents based on term referenced values?
Should I query the tid before (is the _taxonomy_get_tid_from_term  func the proper to use?), and then query the content like this?
$my_tid = _taxonomy_get_tid_from_term ($term_to_match);

$query->fieldCondition('term_fieldname', 'tid', $my_tid);

Answer: EntityFieldQuery can not, as you have noticed JOIN tables, because it may run queries against a backend where JOIN does not make sense.
You will need bridge this gap in code, which is what your own suggestion is doing, it looks fine to me.
However, if you don't intend to run on MongoDB or some such, my personal preferance is would be to ditch EntityFieldQuery in favor of a SQL-query with db_select instead. This mostly because MySQL provides the ACID, while all the "no-sql" db's needs to break atleast one of those.
Comment: You'd be better off with using Views to generate the query for you. It's rather tedious manually. Also, Letharion is right, only Drupal 8 has relationship support for entity queries. Finally, if you want speed, you do need MongoDB ;)
Comment: thank you!
going to db_select? mmmhhhhh ...
The matter is that ... if I switch to db_select instead I would probably have to face multiple/complex joins conditions to query my content fields values (quite a lot) ... and still have to do the same with taxonomies term values, too. With EntityFieldQuery I have easy access (and can easily query) at least my content (cck) field values ... isn't it?
Which would be the advantage of db_select, that I don't get?
Comment: Added my reasoning for this to the answer. :)
Comment: Thanks again Letharion. Your reasoning sounds nice, and quite technical. Now my concern is reduce and keep manageable the query code. Would with db_select have to write so many joins & fields conditions, as I am worrying about? or am I missing some easier approach with db_select itself?
Answer: You should probably use the taxonomy_get_term_by_name() function.
$terms = taxonomy_get_term_by_name($your_term_name);
$tid = $terms[0]->tid; // Assuming you have one term with that name.

Your query would then contain:
$query->fieldCondition('term_fieldname', 'tid', $tid);

So basically your question contains the answer already.


Given $r>0$, find $k>0$ such that $\sqrt{(x-2)^2+(y-1)^2}<k$ implies $|xy-2|<r $

Question: Using the axioms, theorem, definitions of high school algebra concerning the real numbers, then prove the following:
Given $r>0$, find a $k>0$ such that:
$$\text{for all }x, y: \sqrt{(x-2)^2+(y-1)^2}<k\implies|xy-2|<r $$
I tried with several values given to $k$ and $r$ to find the relation between them.
Suppose then $r=1$ and we choose $k$ to be $\frac{1}{2}$
Now let us check if $\forall x,y$ such that $\sqrt{(x-2)^2+(y-1)^2}<\frac{1}{2}$ then $|xy-2|<1$
However we know that $|x-2|\leq\sqrt{(x-2)^2+(y-1)^2}$
Therefore if $\sqrt{(x-2)^2+(y-1)^2}<\frac{1}{2}$ then $|x-2|<\frac{1}{2}$..........(1)
For the same reason $|y-1|<\frac{1}{2}$...................(2)
But, (1) implies $\frac{3}{2}<x<\frac{5}{2}$.......................(3)
Also (2) implies $\frac{1}{2}<y<\frac{3}{2}$....................(4)
And the question now is, do ALL the values of x and y satisfying (3) and (4), satisfy $|xy-2|<1$
No because for $x=\frac{16}{10}$ and $y=\frac{6}{10}$ the relation $|xy-2|<1$ is not satisfied.
And the question is, which is the proper relation between $r$ and $k$ so that the above inequality is satisfied for all the values of $x$ and $y$
Comment: the problem is not missing any context .It corresponds to a well formed formula and as such it is either provable or not provable.
Comment: I good start woud be to share your own thoughts on the subject.
Answer: what you are looking for are the two hyperbolas that either touch at two place or touch and go through the end point of a diameter of the semicircle.  take the upper part of the semicircle $$(x-2)^2 + (y-1)^2 = k^2.$$ let the hyperbola $$xy = 2+r, \frac{dy}{dx} = -\frac y x$$ touch at $$x = 2 + \cos t, y = 1 + \sin t$$ the common tangent has the slope $-\frac{\cos t}{\sin t}.$  the constraints on $t$ are $$ (2+\cos t)(1+\sin t)= 2 + r, \frac{\cos t}{\sin t} =\frac{1+\sin t}{2+\cos t}$$ simplifying the last equation, we get $$ \cos t + 2 \sin t + \cos t \sin t= r,2\cos t-\sin t + \cos^2 t-\sin^2 t=0 \tag 1$$
here is what i will try to do. solve numerically $$2\cos t-\sin t + \cos^2 t-\sin^2 t=0$$ for $t.$ use the second equation $$r = \cos t + 2 \sin t + \cos t \sin t $$  to find $r.$
Comment: Thank you for your solution but certainly your solution is far beyond the limits of highs chool algebra
Answer: The center of the circle is at $(2,1)$, which is also on the hyperbola $xy = 2$. So it makes sense to write $x = 2 + a$ and $y = 1 + b$. Then your problem can be restated as: Given $r > 0$, find a $k > 0$ such that if $\sqrt{a^2 + b^2} < k$, then $|a + 2b + ab| < r$.
If $\sqrt{a^2 + b^2} < k$, then both $|a|$ and $|b|$ are less than $k$, which implies $|a + 2b + ab| < 3k  + k^2$. So your task is to find a $k$ such that $3k + k^2 < r$.
I think you can take it from here...


When to use fixed effects vs using cluster SEs?

Question: Suppose you have a single cross-section of data where individuals are located within groups (e.g. students within schools) and you wish to estimate a model of the form Y_i = a + B*X_i where X is a vector of individual level characteristics and a a constant.
In this case, suppose unobserved between-group heterogeneity biases your point estimates of B and their SEs since it is correlated with your independent variable of interest.
One option is to cluster your SEs by groups (schools). Another is to include group FEs. Another is to use both. What should one consider when choosing between these options? It is particularly unclear why one might cluster SEs by group AND use group FE. In my specific case, I have 35 groups and 5,000 individuals nested within each group. I have followed the discussion in this pdf, but it is not very clear on why and when one might use both clustered SEs and fixed effects.
(Please discuss the pros and cons of clustered SEs vs. FEs instead of suggesting I just fit a multilevel model.)
Answer: Both approaches, using group fixed effects and/or cluster-adjusted standard error take into account different issues related to clustered (or panel) data and I would clearly view them as distinct approaches. Often you want to use both of them:
First of all, cluster-adjusted standard error account for within-cluster correlation or heteroscedasticity which the fixed-effects estimator does not take into account unless you are willing to make further assumptions, see the Imbens and Wooldridge lecture slides for an good discussion of short and long panels and various issues related to this problem. There is also a novel paper about this topic by Cameron and Miller: A Practitioner's Guide to Cluster-Robust Inference which might be interesting for you. If you do not want to model the variance-covariance matrix and you suspect that within-cluster correlation is present, I advise to use cluster robust standard error because the bias in your SE may be severe (much more problematic than for heteroscedasticity, see Angrist & Pischke Chapter III.8 for a discussion of this topic. But you need enough cluster (Angrist and Pischke say 40-50 as a role of thumb). Cluster-adjusted standard error take into account standard error but leave your point estimates unchanged (standard error will usually go up)!
Fixed-effects estimation takes into account unobserved time-invariant heterogeneity (as you mentioned). This can be good or bad: On the hand, you need less assumptions to get consistent estimations. On the other hand, you throw away a lot of variance which might be useful. Some people like Andrew Gelman prefer hierarchical modeling to fixed effects but here opinions differ. Fixed-effects estimation will change both, point and interval estimates (also here standard error will usually be higher).
So to sum up: Cluster-robust standard error are an easy way to account for possible issues related to clustered data if you do not want to bother with modeling inter- and intra-cluster correlation (and there are enough clusters available). Fixed-effects estimation will take use only certain variation, so it depends on your model whether you want to make estimates based on less variation or not. But without further assumptions fixed-effects estimation will not take care of the problems related to intra-cluster correlation for the variance matrix. Neither will cluster-robust standard error take into account problems related to the use of fixed-effects estimation.
Comment: Good response. The key remaining question is why one would want BOTH. Imbens and Wooldridge cover this to some extent.
Comment: The link to the "Imbens and Wooldridge lecture slides" is dead. [Here is](https://web.archive.org/web/20210327131431/https://www2.nber.org/WNE/lect_8_cluster.pdf) a link that works.
Answer: Fixed effects are for removing unobserved heterogeneity BETWEEN different groups in your data.
I disagree with the implication in the accepted response that the decision to use a FE model will depend on whether you want to use "less variation or not". If your dependent variable is affected by unobservable variables that systematically vary across groups in your panel, then the coefficient on any variable that is correlated with this variation will be biased. Unless your X variables have been randomly assigned (and they never will be with observation data), it is usually fairly easy to make the argument for omitted variables bias. You may be able to control for some of the omitted variables with a good list of control variables, but if strong identification is your number 1 goal, even an extensive list of controls can leave room for critical readers to doubt your results. In these cases, it is usually a good idea to use a fixed-effects model.
Clustered standard errors are for accounting for situations where observations WITHIN each group are not i.i.d. (independently and identically distributed).
A classic example is if you have many observations for a panel of firms across time. You can account for firm-level fixed effects, but there still may be some unexplained variation in your dependent variable that is correlated across time. In general, when working with time-series data, it is usually safe to assume temporal serial correlation in the error terms within your groups. These situations are the most obvious use-cases for clustered SEs.
Some illustrative examples:
If you have experimental data where you assign treatments randomly, but make repeated observations for each individual/group over time, you would be justified in omitting fixed effects, but would want to cluster your SEs.
Alternatively, if you have many observations per group for non-experimental data, but each within-group observation can be considered as an i.i.d. draw from their larger group (e.g., you have observations from many schools, but each group is a randomly drawn subset of students from their school), you would want to include fixed effects but would not need clustered SEs.
Comment: What do you mean when you say firm-level fixed effects?
Comment: For your examples, is the difference between randomized treatments and observational data key to your decision about which method to use, or is it a coincidence?
Comment: For the schools example, would you hope to make inferences about a broader population of schools, not all of which are included in the study?
Answer: These answers are fine, but the most recent and best answer is provided by Abadie et al. (2019) "When Should You Adjust Standard Errors for Clustering?"  With fixed effects, a main reason to cluster is you have heterogeneity in treatment effects across the clusters. There are other reasons, for example if the clusters (e.g. firms, countries) are a subset of the clusters in the population (about which you are inferring). Clustering is a design issue is the main message of the paper. Don't do it blindly.
Answer: @Kishore Gawande referenced the NBER working paper by Alberto Abadie, Susan Athey, Guido W. Imbens, and Jeffrey Wooldridge but I think it would be useful to repeat the key conclusions here as (per my reading) they do not necessarily align with every aspect of the the most accepted answers here.
First, clustered standard errors are a design rather than a model issue. Just because clustering standard errors makes a difference (results in larger standard errors than robust standard errors) is no reason that you should do it. Here's the top line: you should use clustered standard errors if you're working with a cluster sample or with an experiment where assignments have been clustered.
There's one exception. If there's no heterogeneity in the treatment effects and assignments have not been clustered, you don't have to use clustered standard errors. If you're using fixed effects, this requirement is looser. If there's no heterogeneity in the treatment effects, you don't have to use clustered standard errors. However, as Abadie et al. note, it's very unlikely that in practice there will be no heterogeneity in treatment effects, so this difference doesn't make much difference in practice. Hence, whether you're using fixed effects or not, if you're working with a cluster sample or clustered assignments, use clustered standard errors.
To quote Abadie et al. directly:

Without fixed effects, one should cluster if either (i) both $P_{C_n}$ < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment). With
fixed effects, one should cluster if either (i) both PCn < 1
(clustering in the sampling) and there is heterogeneity in the
treatment effects, or (ii) σ2 > 0 (clustering in the assignment) and
there is heterogeneity in the treatment effects. In other words,
heterogeneity in the treatment effects is now a requirement for
clustering adjustments to be necessary, and beyond that, either
clustering in sampling or assignment makes the adjustments important

In his answer, @Alex's says "Clustered standard errors are for accounting for situations where observations WITHIN each group are not i.i.d. (independently and identically distributed)" and provides the following example:

Alternatively, if you have many observations per group for
non-experimental data, but each within-group observation can be
considered as an i.i.d. draw from their larger group (e.g., you have
observations from many schools, but each group is a randomly drawn
subset of students from their school), you would want to include fixed
effects but would not need clustered SEs.

This is misleading. If the sample is clustered and there is heterogeneity in the treatment effects (and there usually is), you need clustered standard errors.
To put this in the terms of survey sampling, if the design effect is greater than 1, i.e. observations from a group are not independent because they are more similar to each other than to observations from other groups, then you have to account for this. Ensuring that you sample from each group (e.g. school) is random, doesn't in any way bale you out here. Your effective sample size is less than your actual sample size. This is what leads to standard errors that are too narrow unless they are adjusted (via clustered standard errors) to account for this.
For all the fine print, include simulations and mathematical proofs, see Abadie et al. When Should You Adjust Standard Errors for Clustering.


Problem using javascript to schedule function on Chrome console

Question: I have this function I use to copy elements from a webpage on Chrome Console (web scraping), but when I try to repeat it with setInterval, it just doesn't run. There is no error message or something, but alerts at the end of each option do not show.
setInterval(function() {
    try {
        var lobby = [{}];
        lobby[0]['1'] = document.querySelector("#root > div > div.app-container > div.lobby.lobby_floating.lobby-enter-done > div.lobby__body > div.lobby__container > div > div > div.common-scroll__scroll-view > div > div > div:nth-child(1) > div > div > div.lobby-table__container > div.lobby-table-history.lobby-table-history_game-rol.lobby-table-history_type-numb").innerText;
        lobby[0]['2'] = document.querySelector("#root > div > div.app-container > div.lobby.lobby_floating.lobby-enter-done > div.lobby__body > div.lobby__container > div > div > div.common-scroll__scroll-view > div > div > div:nth-child(2) > div > div > div.lobby-table__container > div.lobby-table-history.lobby-table-history_game-rol.lobby-table-history_type-numb > div").innerText;
        copy(lobby);
        alert('1');
    } catch (err) {
        var lobby = [{}];
        lobby[0]['1'] = document.querySelector("#root > div > div.app-container > div.lobby.lobby_external > div.lobby__body > div.lobby__container > div > div > div.common-scroll__scroll-view > div > div > div:nth-child(1) > div > div > div.lobby-table__container > div.lobby-table-history.lobby-table-history_game-rol.lobby-table-history_type-numb").innerText;
        lobby[0]['2'] = document.querySelector("#root > div > div.app-container > div.lobby.lobby_external > div.lobby__body > div.lobby__container > div > div > div.common-scroll__scroll-view > div > div > div:nth-child(2) > div > div > div.lobby-table__container > div.lobby-table-history.lobby-table-history_game-rol.lobby-table-history_type-numb > div").innerText;
        copy(lobby);
        alert('2');
    }
}, 1000);

One option would be to save that var into a txt file, but I would be happy just by updating and copying the var from time to time.
Thank you guys
Comment: Can you show your call to setInterval?
Comment: Where's the set interval you're trying?
Comment: Some browsers will block pages from showing multiple alerts. I would get rid of the alerts and just do a console log instead to see if the that code in your function is actually executing. Give that a try, otherwise as the others have said post a bit more of your code as it's hard to tell exactly what's going on with what you have here.
Comment: @Marvin and Caleb Jay I updated the post with the call to setInterval, sorry about that.
Comment: @TheOneTrueColter About the alerts, I am using it just to check if its working, but its not. When I clean all the function and let just the setInterval calling for the alert its totally working.
Answer: It seems to be fine in my simplified fiddle.

setInterval(function() {
    try {
        var lobby = [{}];
        lobby[0]['1'] = document.querySelector("#root > div.lobby-table-history").innerText;
        lobby[0]['2'] = document.querySelector("#root > div ").innerText;
        copy(lobby);
        console.log('1');
    } catch (err) {
        var lobby = [{}];
        lobby[0]['1'] = document.querySelector("#root > div.lobby-table-history").innerText;
        lobby[0]['2'] = document.querySelector("#root > div").innerText;
        copy(lobby);
        console.log('2');
    }
}, 1000);

function copy() {

}

Using this code, it logs "1" indefinitely. I predict that you have a bug in your copy() function and something there is leading the setInterval() function to terminate.
Comment: Sure, but the code runs well without the serInterval thing.
Do you think it is maybe chrome stopping me to run this on console?

It its the problem, there's any way for me to do it?
Comment: I'm not familiar with web scraping, but I think you should 1) replace alert with console.log and 2) Review your copy function because that's the only other JavaScript component that I left empty


JPA : Checked exception to verify Database connection

Question: I use JPA, with datasource configured in a persistence.xml file.
What is the exception that I must throw (Checked Exception) if the database name doesnt exist anymore after deploying the application or password wrong because it has been changed after deploying ( generally Database connection failure) ?
Because I don't succeed in catching it by the exception PersistenceException in my java project...
Thank you a lot.
Answer: That must not be a checked exception, as I do not imagine any possible recovering mechanism from this situation. This is called (at least in the EJB spec) a system exception.


How do you determine dimension

Question: Suppose $U$ and $V$ are $2$ dimensional subspaces of $\mathbb{R}^4$. How do you determine the dimension of $U \cap V$? I know that
\begin{equation*}
\text{dim}(U + V) = \text{dim}(U)+ \text{dim}(V) - \text{dim}(U \cap V).
\end{equation*}
So it seems that $\text{dim}(U \cap V) = 0$.
Comment: There is not enough information to uniquely determine the answer.  The dimension of the intersection can be 0, 1, or 2.
Comment: @Tom for 2, let U=V. For 1, consider U and V as planes which are intersecting in a line.
Comment: how can it be 1 or 2?
Answer: First: it is incorrect, in general, to even write $\dim(U\cup V)$, because $U\cup V$ is almost never a subspace: it is a subspace if and only if $U\subseteq V$ or $V\subseteq U$. Not being a subspace, it doesn't even make sense to talk about its dimension.
Rather, what you probably meant is the correct equation
$$\dim(U+V) = \dim(U) + \dim(V) - \dim(U\cap V)$$
(though I prefer to put the intersection on the left hand side, because in that form it is valid even in the infinite dimensional case). Here, $U+V$ is the smallest subspace that contains $U$ and $V$, and it happens to equal the set of all vectors of the form $u+v$ with $u\in U$ and $v\in V$.
The equation does not give you the full answer, because there are several situations that can occur: you could have $U$ and $V$ intersect trivially: this is what happens when $U+V=\mathbb{R}^4$. For an explicit example, you could have $U=\{(a,b,0,0):a,b\in\mathbb{R}\}$, and $V=\{(0,0,c,d) : c,d\in\mathbb{R}\}$. Here, $\dim(U\cap V)=0$.
Or you could have that $U$ and $V$ intersect in a one-dimensional subspace (for example, take $U$ as above, but take $V=\{(0,b,c,0) : b,c\in\mathbb{R}\}$).
Or you could have $U=V$, in which case the intersection has dimension $2$.
What you can say is: if the spaces are distinct, then the intersection will either have dimension 1 or dimension 0. But that is all you can say with the given information.
Answer: If you have B and B', basis of U and V respectively, you can check if the vectors of B are linearly independent with those of B'. If so, then $\dim(U\cap V) = 0$. If not, you may be able to write a new basis of $U+V$ eliminating the linearly dependent vectors. $\dim(U\cap V)$ is the amount of vectors you have eliminated from $U+V$'s basis.
Also, $\dim(U+V) = \dim(U) + \dim(V) - \dim(U\cap V)$.
Comment: I edited just to make the "dim"s into roman (using `\dim`); pet peeve of mine inherited from my advisor (mathematical operators written with roman characters that are two characters or longer are written in roman, not italic; dim, ker, id, rk, ord, etc).
Comment: Also, keep in mind that if $U \oplus V= \mathbb{R}^4$, then $dim(U \cap V)=0$
Comment: @Tom: It can be 2 if $U=V$. It can be 1 if one vector from U's basis is linearly dependent with the vectors from V's basis or vice versa.

How do you determine dimension


Sample size for validation of questionnaire

Question: how to determine sample size for a questionnaire validation study in a certain population. the questionnaire has underwent psychometric validation before this.
Answer: The question implies a measure of reliability, read the link to Cronbach's alpha, and use that. Make sure that you have enough data to be reliable ($\alpha\geq0.8$).


How to save resources on android when loading several bitmaps from assets that are needed in various activities

Question: Sorry for the long title just wanted to be specific So I have several activities that once started should have all bitmaps in assets initialized, the code that follows works but there most be better solutions please all help will be appreciated.
Class that initializes bitmaps:
public class Images {
private String[]eyes=new String[]{
        "images/character/face/eyes/blue.png"
};
public LinkedList<Bitmap> eyesBM=new LinkedList<Bitmap>();
private int eyesIndex = 0;

private String[]faceandhands=new String[]{
        "images/character/face/faceandhands/white.png",
        "images/character/face/faceandhands/black.png"
};
public LinkedList<Bitmap> faceandhandsBM=new LinkedList<Bitmap>();
private int faceandhandsIndex = 0;
private String[]facialhair=new String[]{
        "images/character/face/facialhair/black.png"
};

public LinkedList<Bitmap> facialhairBM=new LinkedList<Bitmap>();
private String[]hair=new String[]{
        "images/character/face/hair/grey.png"
};
public LinkedList<Bitmap> hairBM=new LinkedList<Bitmap>();
private String[]tattoes=new String[]{
        "images/character/face/tattoes/test.png"
};
public LinkedList<Bitmap> tattoesBM=new LinkedList<Bitmap>();
private String[]legs=new String[]{
        "images/character/legs/brown.png"
};
private LinkedList<Bitmap> legsBM=new LinkedList<Bitmap>();
private String[]shirt=new String[]{
        "images/character/shirt/purple.png"
};
public LinkedList<Bitmap> shirtBM=new LinkedList<Bitmap>();
private String[]shoes=new String[]{
        "images/character/shoes/red.png"
};
public LinkedList<Bitmap> shoesBM=new LinkedList<Bitmap>();
private String[]background=new String[]{
        "images/character/background/normal.png"
};
public LinkedList<Bitmap> backgroundBM=new LinkedList<Bitmap>();

public Images(Context c) {
    loadBitmaps(c,eyes,"eyes");
    loadBitmaps(c,faceandhands,"faceandhands");
    loadBitmaps(c,facialhair,"facialhair");
    loadBitmaps(c,hair,"hair");
    loadBitmaps(c,tattoes,"tattoes");
    loadBitmaps(c,legs,"legs");
    loadBitmaps(c,shirt,"shirt");
    loadBitmaps(c,shoes,"shoes");
    loadBitmaps(c,background,"background");
}

public Bitmap getBitmapFromAsset(Context context, String filePath) {
    AssetManager assetManager = context.getAssets();
    InputStream istr;
    Bitmap bitmap = null;
    try {
        istr = assetManager.open(filePath);
        bitmap = BitmapFactory.decodeStream(istr);
    } catch (IOException e) {
        System.out.println("Fudeu geral !");
    }

    return bitmap;
}
public void loadBitmaps(Context c,String[] src,String dest){
    Bitmap bit=null;
    for (int i = 0;i<src.length;i++){
        bit= getBitmapFromAsset(c,src[i]);
        switch (dest){
            case "eyes":
                eyesBM.add(bit);
                break;
            case "faceandhands":
                faceandhandsBM.add(bit);
                break;
            case "facialhair":
                facialhairBM.add(bit);
            break;
            case "hair":
                hairBM.add(bit);
            break;
            case "tattoes":
                tattoesBM.add(bit);
            break;
            case "legs":
                legsBM.add(bit);
            break;
            case "shirt":
                shirtBM.add(bit);
            break;
            case "shoes":
                shoesBM.add(bit);
            break;
            case "background":
                backgroundBM.add(bit);
            break;
        }
        //dest.add(bit);
        //dest.add(BitmapFactory.decodeResource(r, src[i]));
        }
}
public Bitmap getBitmap(String name){
    switch (name){
        case "eyes":
            eyesIndex=eyesIndex>=eyesBM.size()?0:eyesIndex;
            Bitmap aux =eyesBM.get(eyesIndex);
            eyesIndex++;
            return aux;
        case "faceandhands":
            faceandhandsIndex=faceandhandsIndex>=faceandhandsBM.size()?0:faceandhandsIndex;
            Bitmap aux1=faceandhandsBM.get(faceandhandsIndex);
            faceandhandsIndex++;
            return aux1;
            //return faceandhandsBM.get(0);
        case "facialhair":
            return facialhairBM.get(0);
        case "hair":
            return hairBM.get(0);
        case "tattoes":
            return tattoesBM.get(0);
        case "legs":
            return legsBM.get(0);
        case "shirt":
            return shirtBM.get(0);
        case "shoes":
            return shoesBM.get(0);
        case "background":
            return backgroundBM.get(0);
    }
    return null;
}}

´
Code from main activity:
setContentView(R.layout.activity_character);
    final EditText eT=(EditText)findViewById(R.id.characterName);
    v = (ImageView)findViewById(R.id.characterDisplay);
    img = new Images(this);
    LD=null;
    DD= new Drawable[]{
            new BitmapDrawable(img.getBitmap("legs")),
            new BitmapDrawable(img.getBitmap("faceandhands")),
            new BitmapDrawable(img.getBitmap("shirt")),
            new BitmapDrawable(img.getBitmap("eyes")),
            new BitmapDrawable(img.getBitmap("facialhair")),
            new BitmapDrawable(img.getBitmap("hair")),
            new BitmapDrawable(img.getBitmap("shoes")),
            new BitmapDrawable(img.getBitmap("tattoes"))
    };
    LD=new LayerDrawable(DD);
    v.setImageDrawable(LD);
    ((Button)findViewById(R.id.buttonSkin)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            DD[1]=new BitmapDrawable(img.getBitmap("faceandhands"));
            LD=new LayerDrawable(DD);
            update(LD);
            //saveCaracter(eT.getText().toString());
            //loadGame(eT.getText().toString());
        }
    });

Update method:
private void update(LayerDrawable ld) {
    v.setImageDrawable(ld);
}

Answer: The simplest way I know of is to use the Picasso library. It cuts down on coding by a ton. http://square.github.io/picasso/


Interpret effect of adding random effects to ordinal regression (R - ordinal package - clmm)

Question: I know there are already lots of questions around this topic (especially this one and this one) but I haven't really seen anything that directly helps me (It will be obvious I'm not a great statistician, but I'll do my best to explain).
I am running an ordinal regression in R (clm and clmm). My response variable is a rating between 0 and 4. I have two types of explanatory variables: individual and scenario variables [let's say IVs and SVs].
Six different scenario variables (all dummies with at most 4 different values) represent potential collaboration scenarios that get rated by the respondent (between 0 and 4) creating the response variable. (Research design is a conjoint analysis; there are a total of 192 different scenarios possible)
On top of that I have a variety of individual characteristics about the respondent (age, gender, work experience, networking skills, ...) all derived from a survey.
Every respondent rates between 3 and 16 different scenarios (average 8.1); every scenario is rated by at least 8 respondents. Every respondent and every scenario have a unique identifier (called IVid and SVid). So they are non nested within each other.
Thus the basic regression looks like this:
clm.base <- clm(rating ~ SVs + IVs, data = dt)

The hypothesis I am trying to test is that there are specific individual characteristics, that will influence the rating of the scenarios, independent of the actual content of the scenarios. Basically, some people are more or less favourable to all types of collaboration scenarios.
Now a reviewer of my paper asks me to include individual fixed effects (which in management [my field] basically means dummies for each individual). My assumption originally was that this would result in all individual variables being dropped. This is exactly what happens when I use another model (package lfe)
felm.complete <- felm(rating ~ SVs + IVs | SVid + IVid | 0 | IVid, data = dt)

In this regression basically all my variables are perfectly collinear as expected.
However, when I approximate this in the ordinal package, there is no perfect collinearity. I presume this is related that clmm adds so-called 'random effects'. The regression takes a couple of minutes to run but eventually returns results
clmm.complete <- clmm(rating ~ SVs + IVs + (1|SVid) + (1|IVid), data = dt)

Now, the results here are pretty useless:

All but one of my IVs are insignificant

I am trying to understand what exactly happens when adding the (1|IVid) term in the clmm model. If it basically adds something like an individual dummy than the fact almost everything is now insignificant is no surprise. The coefficients of the IVid dummies would capture the effect I am looking for (some people rate all scenarios higher or lower, regardless of scenario content) most accurately.
Now I wonder whether this interpretation is correct or whether the results I got from running the simple clm regression are just not reliable?
Concretely, I'd like to find out:

What happens when adding a random effect to clmm
A laymen explanation of how the Laplace approximation works
How to group errors around individuals when running clm
Is it possible to extract the coefficients of these random effects (1|id) for as far as there is such a thing?
Answer: I can't answer all of your questions, but this is what I know for sure.
Adding a random effect to clmm has much the same impact as adding a random term to a logistic regression model. Take a simple case with ordinal response $Y$, continuous covariate $X$ and grouping variable $G$. Write $p_k=Prob(Y \leq k)$, for some level of the ordinal response. The model posits that for subject $i$ in group $j$, $$\log \frac{p_k}{1-p_k}=\theta_k - \beta x_{ij} - g_j$$
Takeaways:

We are modeling a chain of logistic regressions where the binary response is: "less than or equal to a certain level" vs "greater than that level".
the $\theta$ parameter depends only on the ordinal response. It's like an intercept term, although there is one of these for each level.
$\beta$ is the slope parameter for the fixed effect $x$, and it does not depend on $k$. The impact of $x$ applies proportionally to all levels of the response.
$g_j$ is an unseen, grouping effect. clmm will estimate the value of $g_j$ and the variance parameter of its (assumed) normal distribution.
The minus signs are a convention of clm and clmm. In interpreting the parameters, negative values imply a greater probability for low ranking responses and positive values imply that the odds favour higher levels of the response. I do not believe that this convention is universal. SPSS, I'm looking at you.

In this simple model, the random effect increases or decreases the odds ratio by a factor of $e^{-g_j}$. This factor is independent of the level itself. Say, if $e^{-g_j}=0.5$ in some group, then all odds ratios are cut by a half for members of that group. This assumption is the weak link of the proportional odds model.
You could include random slopes as well, if you believe there is an interaction between the group and covariate $x$.
You can extract the random effects that the model estimates using method ranef, as in ranef(clmm.complete).
Laplace approximation is a method of numerical integration. Random effects models involve an iterative procedure to estimate the random effects and the process parameters, the EM algorithm. I believe that's where the Laplace approximation comes in, since during the estimation phase, you have to integrate over the unknown parameters. However, I don't know the details of the algorithm employed by clmm. Perhaps someone else can give a better answer.
Be aware that clmm requires an optimization to produce estimates. As part of the summary function, you get some information about whether or not the optimization succeeded. The gradient should be near zero and the Hessian index should be less than 10000.
Regarding the specifics of your model, I don't quite understand the difference between variable SV and variable SVid. In any case, adding (1|SVid) basically changes the odds ratio for each group indexed by SVid. The model has to estimate one parameter for each SV group, a variance and possibly some covariance terms with other parameter estimates. Your description of the study suggests a lot of groups and not much data in each, so that could lead to problems with instability and convergence of the model.
I'm not sure what you mean by "grouping errors around individuals".
Comment: Hi Placidia, Thanks a lot for this extensive answer and apologies for the delay. I have just moved to Singapore and have been extremely busy sweating too much :). Re your clarification question: SV represents a scenario variable (e.g. a dummy for whether or not the respondent knows the potential collaborator). SVid is a unique identifier for each scenario (there are 192 different scenarios in total, characterized by 6 different SVs that each have 2,3, or 4 alternative values). I agree about the high # of groups and few data points in each, which is why I wanted to leave out these effects...
Comment: Re "grouping errors around individuals", this is something commonly done in the lfe package. For as far as I understand, it allows you to say the error terms within each individual are correlated and take this into account in the determination of the standard deviation of the betas.