Local fields. A $p$ - field $(k,v)$ with $\mathfrak{l=o/p}=\mathbb{F}_q$. Proof of lemma.

Question: $(k,v)$ i a local field, $\mathfrak{p} = \{x | x \in k, v(x) > 0 \}$,  $\mathfrak{o}=\{x | x\in k, v(x) \geq 0\}$.
I'm working on Local Fields and I don't understand few things in proof of this Lemma:

Let $\mathfrak{l=o/p}=\mathbb{F}_q$ for a $p$-field $(k,v)$. Then, for each $x \in \mathfrak{o}$, the limit $\omega(x) = \lim_{n\to\infty}x^{q^n}$ exists in $\mathfrak{o}$, and the map $\omega :\mathfrak{o} \to \mathfrak{o} $ has the following properties: $\omega(x)\equiv x \ mod \ \mathfrak{p}$, $ \ $ $\omega(x)^q = \omega(x) \ $, $\omega(xy)=\omega(x)\omega(y)$.

Proof: By induction, we shall prove the congruences $x^{q^n}\equiv \ x^{q^{n-1}} \ mod \ \mathfrak{p}^n$ for all $n\geq 1$. For $n=1$,$x^q \equiv x \ mod \ \mathfrak{p}$ follows from th fact that $\mathfrak{l=o/p}$ is a finite field with $q$ elements. Assume the congruence for $n \geq 1$ so that $x^{q^{n}}=x^{q^{n-1}}+y$ with $y \in \mathfrak{p}^n$. Then
$$x^{q^{n+1}} = \sum_{i=0}^{q}{q\choose i}x^{iq^{n-1}}y^{q-i}.$$
For $0<i<q$, the integer $${q\choose i}=\frac{q}{i}{q-1\choose i-1} $$ is divisble by $p$ so that ${q\choose i}y^{q-i}$ is contained in $\mathfrak{p}^{n+1}$. Since the same is obviously true for $i=0$, we obtain $$ x^{q^{n+1}} \equiv x^{q^{n}}mod \ \mathfrak{p}^{n+1}.$$ Now, we see from these congurences that $\{x^{q^{n}} \}_{n \geq 1 }$ is a Cauchy sequence in $\mathfrak{o}$ in the $v$ - topology. As $v$ is complete and $\mathfrak{o}$ is closed in $k$, the sequence converges to an element $\omega(x)$ in $\mathfrak{o}$. It is clear that congruences yield $x^{q^{n}} \equiv x \ mod \ \mathfrak{p}$ for all $n \geq 1$. Hence $\omega(x) \equiv x \ mod \ \mathfrak{p} $. We also see $$\omega(x)^q = lim_{n \to \infty}x^{q^{n+1}} = \omega(x), \ \omega(x)(y) = lim_{n \to \infty}x^{q^{n}}y^{q^{n}} = \omega(x)\omega(y).$$ QED
1) Why we are interested in  congruences modulo $\mathfrak{p}^n$ ?
2) Why divisibility of ${q\choose i}$ by $p$ implies that ${q\choose i}y^{q-i}$ is contained in $\mathfrak{p}^{n+1}$?
3) Why we see from these congruences that $\{x^{q^{n}} \}_{n \geq 1 }$ is a Cauchy sequence in $\mathfrak{o}$ in the $v$ - topology?
Comment: To make things concrete pick an element $\pi \in \mathfrak{p}, \pi \not \in \mathfrak{p}$ then $ \mathfrak{p} = (\pi)$ and everything works exactly as in $\mathbb{Z}_p$.
Answer: For 1) and 3)
Recall that a sequence $(x_n)$ of elements of $k$ is convergent iff there exist an element $l\in k$ such that $v(l-x_n)\underset{n\to+\infty}{\longrightarrow}+\infty$ and is Cauchy iff $v(x_{n+1}-x_n)\underset{n\to+\infty}{\longrightarrow}+\infty$. Moreover, since the valution $v$ is discrete, we may assume that $v(k^*)=\mathbb{Z}$ and so for every integer $n$, we have ${\frak{p}}^n=\{x\in k\vert v(x)\geqslant n\}$. In particular, if $(x_n)$ is a sequence of $\frak{o}$ such that for all $n\geqslant 1$, $x_{n+1}\equiv x_n \pmod{{\frak{p}}^n}$ then $x_{n+1}-x_n \in {\frak{p}}^n$ ie $v(x_{n+1}-x_n)\geqslant n$ so $(x_n)$ is a Cauchy sequence.
For 2)
For $0<i<q$: since $p$ is in $\frak{p}$ and $\frak{p}$ is an ideal of $\frak{o}$, the divisibility of $\binom{q}{i}$ by $p$ implies that $\binom{q}{i}$ is in $\frak{p}$. Likewise, ${\frak{p}}^n$ is an ideal, $y\in{\frak{p}}^n$ and $q-i\geqslant 1$, so $y^{q-i}\in{\frak{p}}^n$ hence $\binom{q}{i}y^{q-i}\in {\frak{p}}{\frak{p}}^n={\frak{p}}^{n+1}$.
For $i=0$:  $y^q \in {\frak{p}}^{qn}\subseteq {\frak{p}}^{n+1}$ since $qn\geqslant 2n\geqslant n+1$.


How to dynamically pass a variable to delta table updateAll() in python?

Question: We are using delta (.io) for our data lake. Every X hours we want to upsert all record that are new/changed.
Our initial code looks like this:
from delta.tables import *

for table in output_tables.keys():
  update_condition = "old." + output_table_unique_keys[table] + " = new." + output_table_unique_keys[table]
  new_df = output_tables[table].drop_duplicates([output_table_unique_keys[table]])
  old_df = DeltaTable.forPath(spark, des_file_path + table)

  old_df.alias("old").merge(new_df.alias("new"), update_condition) \
  .whenMatchedUpdateAll()\
  .whenNotMatchedInsertAll() \
  .execute()

Currently the update_condition is old.unique_key = new.unique_key but we come across some errors. We are prone to the ConcurrentAppendException, see https://docs.databricks.com/delta/concurrency-control.html.
The example shows us this code as a solution
// Target 'deltaTable' is partitioned by date and country
deltaTable.as("t").merge(
    source.as("s"),
    "s.user_id = t.user_id AND s.date = t.date AND s.country = t.country")
  .whenMatched().updateAll()
  .whenNotMatched().insertAll()
  .execute()

So in order to implement the solution for this we need to make our update_condition more explicit. We want to do this by adding the following statement (our partitions).
old.unique_key = new.unique_key AND new.Division = <Division> AND new.company = <company>
Just like in the scala code in the example (from the link) we have our value of our new statement in <>. How does this work in Python? How can I dynamically replace that value with the value of each corresponding row?
Comment: The Python code works similar to how the Scala code works, some good references for this are [Simple, Reliable Upserts and Deletes on Delta Lake Tables using Python APIs](https://databricks.com/blog/2019/10/03/simple-reliable-upserts-and-deletes-on-delta-lake-tables-using-python-apis.html) and [Upsert into a table using merge](https://docs.delta.io/0.8.0/delta-update.html#upsert-into-a-table-using-merge).

In terms of dynamically changing the values, you could run multiple statements and loop through all the values but could would it be possible to generate a hash of the keys to avoid this?
Comment: @DennyLee Looping will take too long since it's a lot of data. Since I couldn't find a fix (not even in delta repository) I ended up with using the same method `old.X = new.X AND old.y = new.y`, but this time adding a retry mechanism whenever it encounters a `ConcurrentAppendException`.
Comment: Is it possible that the `target` table contains multiple updates to the same row thus causing the `ConcurrentAppendException`?
Answer: This solution could be extrapolated to your situation.
First I created a date variable
#Update active values
active_date = datetime.today() + relativedelta.relativedelta(months=0, day=1)
active_date = active_date.strftime('%Y-%m-%d')
print(active_date)

I inputted this variable as a conditional to update my delta table using the following code.
from delta.tables import *

deltaTable = DeltaTable.forPath(spark, '/tmp/delta/people')

# Declare the predicate by using a SQL-formatted string.
deltaTable.update(
  condition = "startDate != " + active_date,
  set = { "gender": "'Female'" }
)

As you can see the conditional can be updated accordingly to the current date. To alter another column. In this case the gender column.


RSS Events Calendar

Question: I installed 'Calendar' module in Drupal 7. What I want to know is if it's possible to get an RSS feed and feed that to the Calendar ?
I do realize that the 'Feeds' module will break it down and store it in the database, but was wondering if there is a more direct approach to displaying the RSS on the calendar?
Thank you.
Answer:
Calendar - Requires Views and the Date API (packaged with the Date module).
Views - support natively RSS Feeds.

So you need just add Feed display.
For importing events to calendar, you can use Feeds module, on source side there's some date(s) provided.
Comment: Hi Nikit, thank you for your answer. Was wondering can the Calendar receive those events through Views which supports RSS feeds? I just dont know how to connect them both.
Comment: Answer changed due to comment.
Comment: Hi Nikit, when you say on source side there's some date's provided, how do you mean? thx
Comment: Usually any date information there should be. If no date, then you can just use Feed item date.
Answer: Just a note that Events aren't really supported well in RSS, i.e. there isn't a place to provide start and end times. There was a draft spec made for RSS events (http://web.resource.org/rss/1.0/modules/event/), but It's not natively supported in Drupal. You would be better off setting up a generic XML or JSON feed that exposes the fields you need.

RSS Events Calendar


position: "absolute" with Button is not working on IOS | React Native

Question: I have a hamburger button that triggers a side menu in a mobile app. The button doesn't respond when position is set to absolute. I have seen similar issue which suggest wrapping the button with <View> </View> and setting its position to absolute, however this didn't work in my case. The button doesn't respond when being clicked on IOS. Android works perfectly fine
Code Snippet:
import React, { useState, useEffect } from "react";
import { View, StyleSheet } from "react-native";

import Hamburger from "@psyycker/rn-animated-hamburger";

function HamburgerIcon({ navigation }) {
  const [status, setStatus] = useState(false);

  useEffect(() => {
    const unsubscribe = navigation.addListener("drawerClose", (e) => {
      setStatus(false);
    });

    return unsubscribe;
  }, [navigation]);

  async function callBack() {
    setStatus(true);
    navigation.toggleDrawer();
  }
  return (
    <View style={styles.btnContainer}>
        <View style={{ marginTop: 40, marginLeft: 20 }}>
          <Hamburger
            active={status}
            type="spinArrow"
            color="blue"
            onPress={() => callBack()}
          ></Hamburger>
        </View>
    </View>
  );
}

const styles = StyleSheet.create({
  btnContainer: {
    position: "absolute",
    flex: 1,
  },
});

Answer: Solved by wrapping around SafeAreaView and setting zIndex to a high number.
<SafeAreaView style={{ position: "absolute", margin: 40, marginLeft: 20, zIndex:99999 }}>
    <Hamburger active={status}
           type="spinArrow"
           color="blue"
           onPress={() => callBack()}
          >
    </Hamburger>
</SafeAreaView>


How to order a query by a field that is not being selected

Question: I am a nwbie to SQL queries and stored procedures and I am trying to order a query where there is 3 inner joins but I get this error:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

Here is the code of query that I have tried:
SELECT DISTINCT
    P.ProductId,
    PID.IndexId
FROM
    Products AS P
INNER JOIN
    #ProductIds AS PID ON P.ProductId = PID.ProductId
INNER JOIN
    ProductStores AS PS ON P.ProductId = PS.ProductId
ORDER BY
    CASE PS.Status
       WHEN 1 THEN 1
       ELSE 2
    END
    OFFSET (@PageIndex * @PageSize) ROWS
    FETCH NEXT (@PageSize) ROWS ONLY;

When I remove the distinct keyword, the rows are being repeated many times
Comment: Often when you get repeating rows it is an indication that the join predicates are not correct. The error message can't be more clear though.
Comment: The problem has nothing to do with the JOIN; the error is actually telling you the problem. You're trying to order your data by the expression `CASE PS.Status WHEN 1 THEN 1 ELSE 2 END` however, that expression is **not** in your `SELECT`. With `DISTINCT` you can only order your dataset by rows that appear in the `SELECT`.
Comment: I am guessing you may be able to use group by with max & case here and then order by the calculated column. But without sample data it's impossible to know.
Answer: Try it ...
SELECT * FROM (
    SELECT DISTINCT
    P.ProductId,
    PID.IndexId,
    (CASE tb.Status WHEN 1 THEN 1 ELSE 2 END) AS Status
FROM Products AS P
    INNER JOIN #ProductIds AS PID ON P.ProductId = PID.ProductId
    INNER JOIN ProductStores AS PS ON P.ProductId = PS.ProductId ) as tb
ORDER BY tb.Status OFFSET (@PageIndex * @PageSize) ROWS FETCH NEXT (@PageSize) ROWS ONLY;

Because The order by statement execute after select statement. And when distinct two column may be include difference status. This mean that thing that two row. 1st row 1 (ProductId), 2 (IndexId), 1 (Status) and 2nd row 1 (ProductId), 2(IndexId), 2(Status). When you get the first distinct two column. It return only 1 row but which status? But you add status column then it know status column individually.
Comment: Code only answers are often considered low quality because they don't explain why the original code was incorrect.
Comment: Because The order by statement execute after select statement. And when distinct two column may be include difference status. This mean that thing that two row. 1st row 1 (ProductId), 2 (IndexId), 1 (Status) and 2nd row 1 (ProductId), 2(IndexId), 2(Status). When you get the first distinct two column. It return only 1 row but which status? But you add status column then it know status column individually.
Answer: Your results are only interested in showing fields that come from Products and #ProductIds - (ProductId and IndexId) - however you are then joining a third table which you are attempting to order by (ProductStores).
If you had a ProductId which had 100 ProductStores associated with it then the DISTINCT would show you that one ProductId regardless of the ProductStores.Status field.
It may be better to ask you - what answer are you wanting?
I'm guessing you are wanting to list Products which have an Status = 1 associated with them first. However, it looks like there's nothing to stop a Product being associated with both a Status = 1 store and a Status = 0 store. This is why it's not possible for SQL to give you answers in this case - where you are wanting one row per Product.
To order by the status you would need to output it. However then, you will get a row for every combination of Product, Index, Status.
@mimamiq's answer could probably work without the outer SELECT...
SELECT DISTINCT
    P.ProductId,
    PID.IndexId,
    PS.Status
FROM Products AS P
    INNER JOIN #ProductIds AS PID ON P.ProductId = PID.ProductId
    INNER JOIN ProductStores AS PS ON P.ProductId = PS.ProductId
ORDER BY
    CASE tb.Status WHEN 1 THEN 1 ELSE 2 END
OFFSET (@PageIndex * @PageSize) ROWS FETCH NEXT (@PageSize) ROWS ONLY;

But note - if you are wanting one row per product/productid combination - then this won't work (unless there are other constraints on your database which we don't know about).


what is in intuitive explanation of the histogram equalization invariant feature?

Question: Ojala et al, proposed the uniformed local binary patterns(LBP) approach to extracting rotation and histogram equalization invariant features.

what is  histogram equalization invariant feature? i need your help.
Answer: It's a feature that remains the same after the application of histogram equalization.
Consider the following 3 x 3 image (256 levels) -
\begin{bmatrix}3&1&200\\20&32&55\\45&0&120\end{bmatrix}
The LBP is -
\begin{bmatrix}0&0&1\\0& &1\\1&0&1\end{bmatrix}

The histogram-equalized image is -
\begin{bmatrix}69&40&243\\97&125&186\\158&28&215\end{bmatrix}
The LBP of the histogram-equalized image is -
\begin{bmatrix}0&0&1\\0& &1\\1&0&1\end{bmatrix}
Both images have the same LBP, since histogram equalization doesn't change the inequalities between the pixel values.
This is because histogram equalization, by definition, remaps the pixel values using the cumulative distribution function which is non-decreasing,
i.e., if x1 < x2, then cdf(x1) ≤ cdf(x2).


Multiple checkbox in ionic framework

Question: I am new in ionic framework.I am create one user profile and pass user input's through api url (yii2 api) . For example normal text field
<input name="location" ng-model="data.location" type="text" placeholder="location" ng-required="true">

my api url like this
return $http.get('http://localhost/web/index.php?r=apiprofile/new&user_id='+$scope.data.user_id+'&location='+$scope.data.location)

This is working fine and the location value stored database correctly.But i use multiple checkbox means how to pass this url.
<ion-checkbox  ng-model="data.jobtype1" ng-true-value="'parttime'">parttime</ion-checkbox>
<ion-checkbox  ng-model="data.jobtype2" ng-true-value="'fulltime'">fulltime</ion-checkbox>
<ion-checkbox  ng-model="data.jobtype3" ng-true-value="'contract'">contract</ion-checkbox>

I want user clicks three checkbox means look like this in database [parttime,fulltime,contract] that is same as in php multiple checkboxes.
I am already try same ng-model name for three checkbox ,but it is not working properly,when i click any one checkbox means all three checkbox is clicked and the database value is  "undefined". And i passing like below url means the value in database like this [parttimefulltimecontract]
 return $http.get('http://localhost/web/index.php?r=apiprofile/new&user_id='+$scope.data.user_id+'&jobtype='+$scope.data.jobtype1+$scope.data.jobtype2+$scope.data.jobtype3)

Please help any one
Answer:  <ion-checkbox ng-model="jobtype1" ng-true-value="parttime" ng-false-value="0" ng-checked="jobtype1== parttime" />

Try this.
http://codepen.io/ionic/pen/hqcju

Multiple checkbox in ionic framework


how to make hyperlink to other viewcontroller based on calculating result?

Question: i'm make a diet application which is can tell user how much calories do they need per day by input the data like height, weight and age. then the result will be appear when user press "hitung" button. After that user will press next button bellow or i called "selanjutnya" then user will find the food menu who can they choose based on their calorie per day such as >1400, >1600, >1800, >2000 then when user press one of those choices the food menu will be appear. but i have difficulty to make it simple, i want is when the result appear user can click on calorie result and directly go to food menu without choose in next page.
exp: when the result is 1823, user can press the result and directly go to food menu that serve >1800 calories.
Answer: <code>//In the button action method
if(calories > 2000)
{
    // show food items type 1
}
else if (calories > 1800)
{
    // show food items type 2
}
else if (calories > 1600)
{
    // show food items type 3
}
... // so on
else
{
    // show food items type n
}
</code>
Comment: You must provide details of your app including the code and screenshots in your questions, not by sending emails to users.
Comment: how to add food items? the result is a label?


Why does video resolution change when streaming from Android via WebRTC

Question: I'm trying to stream at 640x480 from Chrome on Android using WebRTC, and the video starts off at that, but then the resolution drops to 320x240.
Here are the getUserMedia parameters that are sent:
 "getUserMedia": [
  {
   "origin": "http://webrtc.example.com:3001",
   "pid": 30062,
   "rid": 15,
   "video": "mandatory: {minWidth:640, maxWidth:640, minHeight:480, maxHeight:480}"
  }

My question is why does the resolution fall?  When I try it from Chrome on my Mac that does not happen.  I would like to make adjustments so that the video resolution does not change.
video frames dumped using ffmpeg
chrome://webrtc-internals text dump
I'm using the Licode WebRTC streaming server, but have also seen the same behavior using Kurento.
Comment: I know that Vp8 dynamically changes frame sizes due to latency(network or processing).
Answer: getUserMedia constraints only affect the media requested from the browser to the hardware and returned as a stream. getUserMedia constraints don't have any effect on what is done to that stream afterwards (i.e., when it's streamed over a connection). The degradation you're seeing is in the PeerConnection layer, not in the getUserMedia layer. Degradation is triggered by the webrtc implementation when hardware and bandwidth statistics are indicative of low performance, and is negotiated by both sides.
[Hardware] <-   getUserMedia   -> [javascript client] <- PeerConnection -> [another client]
           <- 640x480 captured ->                     <-  320x240 sent  ->

You'll have to dig into source code for documentation and evidence of how it's done in each implementation, but references to behavior:
From the OReilly Chapter on WebRTC:

The good news is that the WebRTC audio and video engines work together with the underlying network transport to probe the available bandwidth and optimize delivery of the media streams. However, DataChannel transfers require additional application logic: the application must monitor the amount of buffered data and be ready to adjust as needed.

...

WebRTC audio and video engines will dynamically adjust the bitrate of the media streams to match the conditions of the network link between the peers. The application can set and update the media constraints (e.g., video resolution, framerate, and so on), and the engines do the rest—this part is easy.
Comment: It seems like it's not possible to force the resolution like I expected.  We have resorted to post-processing the the video using ffmpeg to normalize the resolution.
Comment: @JayP. unless if modify source code of webrtc and use this new modified binaries outside of browser environment somewhere in native desktop apps or mobile


Can this PHP node leak memory?

Question: I have a Drupal 7 installation that apparently leaks memory somewhere. The memory usage of nginx is going up in production until the server fails. This started basically when I added a new node with PHP content to it. My PHP code does basically this:
<?php

global $user;
$token = uuid();
$uid = user_load($user->uid);
$myprofile = 'main';
$profile = profile2_load_by_user($uid, $myprofile);
$birth_date= $profile->field_birth_date['und'][0]['value'];

$conn = mysql_connect ("my.sql.server:3306/somedb", "user", "pass");
mysql_select_db("somedb", $conn);
mysql_query("INSERT INTO special_table (TOKEN, USER) VALUES ('$token','$user->name')");
mysql_close ($conn);

echo 'output some html based on birthdate..';

In addition I use memcached module. That custom DB connection that I have to open and do a single insert is not the DB of the drupal installation, that is going into a separate database. Surely not the nicest solution, but I guess that should not leak anything.
Do you see anything in this code that can possibly lead to memory leak?
Comment: No need for `$uid = user_load($user->uid);` just use `$user->uid` also no need for `mysql_query` use `db_set_active` and `db_query` instead
Comment: I dont see anything wrong. Dunno why you're using basic php Mysql functions, D7 supports multiple database connections ...
Comment: thank you @tenken for taking a look. that basic mysql thing was just the quickest thing that I could come up with.
Answer: It doesn't look like this is causing a memory leak as @tenken said in his comment.  However, since this is going in a node, that whole PHP snippet is stored in the database which isn't recommended.  It will take more memory to grab this code from the database, then run it.
Try sticking the code in a function in PHP file and then running that function somewhere else on the site, i.e. a custom module.  This is a good tutorial on how to do that.
Answer: mysql_connect() is deprecated. See that big red box in the API docs? So yes, it may cause various unhealthy effects on your site. Use Drupal's built-in multiple database handling to be safe.

Can this PHP node leak memory?


Webform - User to edit submission (admin can close)

Question: I have a webform that a authenticated user can submit. Where is the page for the authenticated user to re-edited their submission? I can't find it?
I also want to extend a another function. I want to have the ability to close a submission (so the authenticated user) can't re-edit it anymore.
Any suggestions?
Thank you,
Answer: You have to view your submission and click on edit to update. Remember you can only edit your own submission.


How do I change the default value of a field with AJAX?

Question: Related to my previous question: Form fields created via Ajax are missing element attributes
I have a date field and a series of text and number fields which need their default values to change based on the value of the date field. I've updated my code so it functions this way:
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['date'] = array(
        '#type' => 'date',
        '#ajax' => [
            'callback' => '::dateCallback',
            'wrapper' => 'wrapper',
        ],
        '#default_value' => date("Y-m-d")
    );
    $form['wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'wrapper'],
    ];

    //insert logic to determine value of a variable called $field1
    $form['wrapper']['options'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('options'))
    );
    $form['wrapper']['options']['field1'] = array(
        '#type' => 'textfield',
        '#title' => "Field 1",
        '#value' => $field1
    );
    $form['wrapper']['table'] = array(
        '#type' => 'table',
        '#title' => t('Table'),
        '#header' => array("H1", "H2", "H3"),
        '#attributes' => array('class' => array('custom-table'))
    );
    //insert logic to generate table rows
    return $form;
}

/**
 * Implements callback for Ajax event on date selection.
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Date selection section of the form.
 */
public function dateCallback(array &$form, FormStateInterface $form_state) {
    return $form['wrapper'];
}

There are 2 problems I am having with this:
1) Implementing it in this way, such that the #value property is changed when the date field is changed, technically works, however if the user then chooses to modify any of the textfield values, that is not reflected in the $form_state object and is overridden by whatever #value was last set to in buildForm().
2) I have also tried using #default_value instead, but the value in the field will not update if it already has something in it (which it usually does from the first time #default_value is set in buildForm()). I have seen some threads like this one suggesting to unset the value in $form_state before setting #default_value again, however all such suggestions are for Drupal 7 where $form_state is a completely different data structure.
Is there a known way to do what I am trying to accomplish?
Update: I tried method 2 again by adding $form_state->unsetValue('field1'); before declaring $form['wrapper']['options']['field1'], but this did not change the behaviour.
Answer: Method 1 setting #value does indeed make it impossible for the user to input data.
So the method 2 setting #default_value is I think still the best approach. As the old trick from D7, unsetting the value in $form_state, doesn't work anymore, you can try this one:
Create the field in a subkey, which is incremented for each request. Set the property #tree on the first level of the field, so you get back the field value as array [$key => $value]:
$form['wrapper']['options']['field1']['#tree'] = TRUE;

if ($form_state->hasValue('field1')) {
  $key = key($form_state->getValue('field1'));
  $value_field1 = current($form_state->getValue('field1'));
  $key++;
}
else {
  $key = '0';
  $value_field1 = NULL;
}

// insert logic to determine new field value
// but check, if there is user input in $value_field1, that you don't want to overwrite

$form['wrapper']['options']['field1'][$key] = [
  '#type' => 'textfield',
  '#title' => 'Text 1',
  '#default_value' => $value_field1,
];

Comment: Thanks for the reply, I've implemented this code and according to my debug logs it is working fine and setting #default_value to the appropriate value. However on the form it is only ever showing the form fields that would be at $key = 0 (confirmed by inspecting element attributes). Is this the expected behaviour? I am not sure how to get it to show the fields that would be at index $key instead.
Comment: Drupal renders all keys in a form render array, I see no reason why this is not happening. Btw. there is only ever one version of the field, because on a rebuild the field with the last key is not built again. If you have on a rebuild in an ajax request still the field in key 0 then the key didn't increment.
Comment: Oops, it was a typo in one of my $form indexes.... This is working perfectly. Thank you!
Comment: @4k4 You might consider refactoring the use of the `each` function, it's been deprecated and using it is highly discouraged
Comment: @Clive, thanks, this is indeed deprecated in PHP 7.2
Answer: There is another way to do the same: Set #value property on ajax callback.
    <?php

    namespace Drupal\drupal_miseries\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;

    class AjaxResponse extends FormBase {
      protected $ts_values = [
        'ts1' => [
          'values1' => [
            'id' => 1,
            'description' => 'Valor1',
            'status' => '1',
          ],
          'values2' => [
              'id' => 2,
              'description' => 'Valor2',
              'status' => 2,
          ],
        ],
      ];

      public function getFormId() {
        return 'AjaxResponseForm';
      }

      public function ajaxTableSelect(array &$form, FormStateInterface $form_state) {
        $element = $form_state->getTriggeringElement();
        if (isset($element) && $element['#type'] == 'checkbox') {
          $check_value = $element['#return_value'];
          $textfield_ts = $this->ts_values['ts1'][$check_value]['description'];
          $form['ts_textfield']['textfield']['#value'] = $textfield_ts;
        }

        return $form['ts_textfield'];
      }

      public function buildForm(array $form, FormStateInterface $form_state) {

        $form['ts_container'] = [
          '#type' => 'container',
          '#attributes' => ['id' => 'ts-container'],
        ];

        $header = [
          'id' => $this->t('ID'),
          'description' => $this->t('Description'),
          'status' => $this->t('Status'),
        ];

        $form['tableselect'] = [
          '#type' => 'tableselect',
          '#description' => $this->t('Test Tableselect'),
          '#header' => $header,
          '#options' => $this->ts_values['ts1'],
          '#empty' => $this->t('No values'),
          '#ajax' => [
            'callback' => [$this, 'ajaxTableSelect'],
            'wrapper' => 'ts-textfield',
          ],
        ];

        $form['ts_textfield'] = [
          '#type' => 'container',
          '#attributes' => ['id' => 'ts-textfield'],
        ];

        $form['ts_textfield']['textfield'] = [
          '#type' => 'textfield',
          '#description' => $this->t('Value fill by ajax'),
          '#title' => $this->t('Ajax Textfield'),
        ];

        $form['actions'] = [
          '#type' => 'actions',
        ];

        $form['action']['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Submit'),
        ];

        return $form;
      }

      public function submitForm(array &$form, FormStateInterface $form_state) {
        dpm($form_state->getValue('tableselect'));
        dpm($form_state->getValue('textfield'));
      }
    }

When you click on any tableselect checkbox, textfield is set with checkbox value => if you click 'submit' checkbox value is assigned to textfield.
When you click on any tableselect checkbox, textfield is set with checkbox value => if you change textfield manually and click 'submit' new value will be assigned to textfield.
but.......Is this the correct way to do that?
Answer: A solution to append a default value to the field after callback but with option for user to change input:
add the value to field attributes: '#attributes' => array('value' => array($form_state->getValue('option2'))),
        $o = [];
    $form['option1'] = array(
        '#type' => 'select',
        '#size' => 1,
        '#options' => ['a' => 'A', 'b' => 'B'],
        '#title' => $this->t('option 1'),
        '#required' => TRUE,
        '#ajax' => array(
            'callback' => array($this, 'next'),
            'wrapper' => 'option2',
        ),
    );

    if ($form_state->getValue('option1') == 'a') {
        $o = [1 => 'one', 2 => 'two'];
    }
    if ($form_state->getValue('option1') == 'b') {
        $o = [3 => 'three', 4 => 'four'];
    }

    $form['option2'] = array(
        '#type' => 'select',
        '#size' => 1,
        '#options' => $o,
        '#title' => t('option 2'),
        '#required' => TRUE,
        '#prefix' => "
 '
',
        '#ajax' => array(
            'callback' => array($this, 'get_data'),
            'wrapper' => 'data',
        ),
    );

    $form['data'] = [
        '#type' => 'textfield',
        '#id' => 'test',
        '#title' => t("choice") . " " . $form_state->getValue('option2'),
        '#default_value' => $form_state->getValue('option2'),
        '#size' => 5,
        '#attributes' => array('value' => array($form_state->getValue('option2'))),
        '#prefix' => "
 '
',
    ];

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Test'),
        '#suffix' => ''
    );

    return $form;
}

/**
 * callback functions
 */
public function next(array &$form, FormStateInterface $form_state) {
    return $form['option2'];
}

public function get_data(array &$form, FormStateInterface $form_state) {
    return $form['data'];
}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
    dpm($form_state->getValue('data'));
}

Answer: I've solved this by using the AJAX callback to reload the page, rather than return the form. For example:
$path = '/path/to/form';
$response = new AjaxResponse();
$response->addCommand(new RedirectCommand($path));
return $response;

It's slower than returning the form, but is a lot less code, especially if you're talking about a complex form with a lot of default values.


CMD error filename/directory error

Question: I used to program batch files for work but I quit since a long time, now I'm back on the job and there seemed to be a bit of a problem.
I try to edit txt files using CMD commands on a batch file:
e.g. echo hello >> *.txt
the thing is I want to add the text to all the txt files in that directory and I remember the * represented all the files in that directory with the same extension unless it's used as *.* then it includes all the files, but now all it does is just writes this error on cmd:

The filename, directory name, or volume label syntax is incorrect.

Can anyone can give a little help?
Comment: the directory has many other non txt fiels in it, I need to specify the extension.
Comment: is it possible to chat? or message you in private, way easier. ( I dont know how to do it on this website stil la rookie)
Comment: the code line still not working...is it not possible to just do it in a simple way? like why isnt echo >> *.txt working? it used to work few years ago
Comment: well..I changed it , I even tried using %cd% still errors
Comment: the following usage of the path operator in batch-parameter substitution is invalid: %~FPNXF
Comment: I just added as an answer so look it over when you get a chance too for more clarification than the comments.
Answer: You can use a FOR /F loop with a DIR command to iterate the full paths and pass those over to the redirection append >> to echo to the text files accordingly.
Example FOR Loop
Be sure to change the value of the Folder= variable to be the directory you need to append to the files with the ECHO command.
Confirmed working batch script example
@ECHO ON
SET Folder=C:\MyFolder
CD /D "%Folder%"
FOR /F "TOKENS=*" %%A IN ('DIR /B /A-D "%Folder%\*.txt"') DO ECHO HELLO>>%%~fA
PAUSE
EXIT

Further Resources

DIR
FOR /F

In addition, substitution of FOR variable references has been
  enhanced. You can now use the following optional syntax:
%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

Comment: so basically FPNXA that you used is combinations of FOR /F syntaxes?
Comment: @saladassPEPE Here's how [Accepting An Answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) works in case you didn't know
Comment: im running a script, and no it didnt work I was mistaken , the result shown was from other test scripts
Comment: Change `FOR /F "TOKENS=*" %A IN ('DIR /A-D /B "C:\Folder\*.txt"') DO ECHO HELLO >> "%~FPNXA"` to `FOR /F "TOKENS=*" %A IN ('DIR/B/A-D "C:\Folder\*.txt"') DO @ECHO HELLO>>"%A"` In a batch file double up the %, **`%A`** becomes **`%%A`**
Comment: If you have already turned off echoing using `@ECHO OFF` then the `@` can be omitted. The variable substitutions are shown, they should be either, `%~dpnxA` OR `%~fA` however as the full path was given the full path is already output as %A there is no need to substitute.

CMD error filename/directory error


I'm having trouble using a variable's value for making a class' name and getting the name of classes (the variable assigned to them)

Question: today I am having an issue with using the value of a variable for making the variable name of a class, so say if we do
class human():
    def __init__ (self, name="unknown", age="unknown")
    self.name=name
    self.age=age

def sethuman():
    x = input("Enter Name: ")
    x = human()

BUT this overwrites the VARIABLE x and sets x to be an object (which will have attributes, etc) when i want the input FROM x (the name entered) to be said object, so instead of using say, "x.name", I wanna say (if the inputted name is John) then "John.name"
Another issue is also if I have a class and there is an object from this class (say  John = human("John",27)
then how could I later use this in code, as I have no idea how to get this name back later short of putting all of the objects' names into an array and letting the user type which user they wanna edit or look at the attributes of
So if:
def humanhasbeenset():
    John=human("John",27)

def printhuman():
#             ↓Should be "John"
    print(<object name>.name)

Then how would I get the object's name? or a list of object names for that class?
Comment: See https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables. **TL;DR**: don't, use a dictionary.
Comment: Understand that variable names in code are for YOU, the developer, not for the user.  If your user needs to be able to set or view something that thing needs to be the VALUE of a variable, not the name of one.  Dictionaries are 100% the answer here.
Comment: I didn't really intend on using dictionaries, I just feel like there's an easier way to use the value of the variable like this
Comment: So if the user typed in "human" as their name, you're perfectly OK with the resulting object overwriting the class itself, completely destroying the functionality of your program?
Comment: Oh boy... I hadn't thought of that, thanks for bringing that issue to my attention, I could make it so if they try to use human it won't work, so, excluding that issue, how could I get the value of x (John), could getattr be used? Or something similar... I'm vastly confused by this issue and its solutions, I just want a variable name system that a user can use (say, for a game of some kind, to set their character's name, or even use pre-set names)
Comment: Apologies, jonrsharpe, I didn't see the comma, I'll try dictionaries :D
Comment: To clarify, Dictionaries are ABSOLOUTELY the answer, coming back to this nearly a year later makes me facepalm, sorry for the trouble I caused :/
Answer: You would need to inject the user's input into local variable space. From the answer of this post, it is likely impossible to do. Even if you could, Python's offical documentation for exec() recommends not attempting to.

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

In this Python bug post, according to George Brandl,

To modify the locals of a function on the fly is not
possible without several consequences: normally, function locals are not
stored in a dictionary, but an array, whose indices are determined at
compile time from the known locales.  This collides at least with new
locals added by exec.  The old exec statement circumvented this, because
the compiler knew that if an exec without globals/locals args occurred
in a function, that namespace would be "unoptimized", i.e. not using the
locals array.  Since exec() is now a normal function, the compiler does
not know what "exec" may be bound to, and therefore can not treat is
specially.

Even if you could do all of this, it still would make for a ton of head aches and messy code, as jasonharper and commenters at this post have noted. An alternative solution, such as storing Human objects in a dictionary, would be better. Without seeing the rest of your code, a quick example would be
humans = {}

class Human:
    def __init__ (self, name="unknown", age="unknown"):
        self.name=name
        self.age=age

def sethuman():
    x = input("Enter Name: ")
    humans[x] = Human(name=x)

def gethuman():
    name = input("Enter name: ")
    if name in humans:
        user = humans[name]
        return user
    else:
        print(f"We could not find {name}."

Comment: OH MY GOODNESS, I didn't see jonrsharpe's comma, my bad! Sorry about that jonrsharpe, I'll try dictionaries :D


Lista Entity Framework

Question: Estou criado a action de Edit para editar os dados dos meus models. O que acontece é que uso ViewModel para "juntar" vários models em um.
Ok, eu consigo pegar os dados de models que não são List<>, ou seja, os models que não estão uma lista. O meu caso é que tenho listas e precisava pegar todos os registros referentes ao id que estou passando na assinatura da Action para que os dados possam ser carregados na tela, e e editar esses dados.
O código que tenho é esse aqui:
 CliCliente cliente = db.CliCliente.Find(id);
 Tabela2 tabela2 = db.Tabela2.Find(id);
 Tabela3 tabela3 = db.Tabela3.Find(id);

 List<Tabela4> tabela4 = db.Tabela4.ToList<Tabela4>();

Em que List<Tabela4> tabela4 = db.Tabela4.ToList<Tabela4>(); me retorna todos os dados, porque não tenho um critério para retornar somente o que está relacionado no id que estou trazendo na action.
Como que eu poderia fazer para varrer e trazer os dados da lista especificos relacionados ao id enviado na assinatura da action?
Comment: Se o `id` é de `CliCliente` e `Tabela2`, `Tabela3` e `Tabela4` estão relacionados, por que você não seleciona apenas de `CliCliente` e usa apenas `Include()`s para carregar os dados agregados?
Comment: Eu tentei, mas não consegui... E dessa forma com o include sairia uma lista? Porque preciso retornar uma lista...
Comment: Retornar para onde?
Comment: para a view... E tambem no controller
Answer: Aqui você disse como são os relacionamentos entre suas tabelas. Supondo isso, posso fazer o seguinte:
CliCliente cliente = db.CliCliente
                       .Include(c => c.Tabela2)
                       .Include(c => c.Tabela3)
                       .Include(c => c.Tabela4)
                       .FirstOrDefault(c => c.CliClienteId == id);

return View(cliente);

Sua View:
@model SeuProjeto.Models.CliCliente

@foreach (var elemento in Model.Tabela4)
{

@elemento.Nome

}

Lista Entity Framework


How to use different static (global) variables in different objects?

Question: for now i have a class which represents a tree. Every node within this tree has exactly the same number of children, lets call it N. I managed this with a static variable for the class, which has the value of N, so this is basically a global variable.
My problem now is that i want to construct a different tree with the same class, but now the value of N should be different. So let's say i want to create the first tree with N=4 and the second with N=2. To save memory i only want to store those values of N once for the tree and not in every node of the tree. Is there a simple conceptual way to achieve this?
Thanks in advance!
Comment: Have you considered non-type template parameter?
Answer: <code>template<size_t N>
struct TreeNode {
    ...
    TreeNode<N>* children[N];
    ...
};
</code>
Used as TreeNode<2> or Treenode<7>
Comment: Yep, textbook usage.


Sending mail with blastula through a secured smtp server fails (r)

Question: I try to send an email using the R package blastula.
The email should be sent though my employers secure smtp server, but I am stuck with the error "No Kerberos credentials available".
A similar setup works in python, but I would like to do it from R, as it fits my workflow better.
The r code used to send the mail, is shown here.
library(blastula)
email <- prepare_test_message()
to <- "email@example.com"
from <- "email@example.com"

create_smtp_creds_file(
  file = "cred_file",
  user = "username",
  host = "smtps.server.com",
  port = 465,
  use_ssl = TRUE
)
#> Please enter password in TK window (Alt+Tab)
#> The SMTP credentials file (`cred_file`) has been generated

smtp_send(email, to, from,
          subject = "Hello",
          credentials = creds_file(file = "cred_file"),
          verbose = TRUE)
#> Error in curl::curl_fetch_memory(url, handle = h): Failure when receiving data from the peer

Created on 2019-12-10 by the reprex package (v0.3.0)
The verbose output from the smtp_send command is given here:
* Rebuilt URL to: smtps://smtps.server.com:465/
*   Trying xx.xx.xx.xx...
* TCP_NODELAY set
* Connected to smtps.server.com (xx.xx.xx.xx) port 465 (#1)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* Server certificate:
*  subject: XXXXXXXX
*  start date: Apr 20 00:00:00 2017 GMT
*  expire date: Apr 23 12:00:00 2020 GMT
*  subjectAltName: host "smtps.server.com" matched cert's "smtps.server.com"
*  issuer: C=NL; ST=Noord-Holland; L=Amsterdam; O=TERENA; CN=TERENA SSL CA 3
*  SSL certificate verify ok.
< 220 mail.server.com Microsoft ESMTP MAIL Service ready at Tue, 10 Dec 2019 12:49:44 +0100
> EHLO henrik-HP-EliteBook-840-G5
< 250-mail.sdu.dk Hello [xx.xx.xx.xx]
< 250-SIZE 62914560
< 250-PIPELINING
< 250-DSN
< 250-ENHANCEDSTATUSCODES
< 250-STARTTLS
< 250-AUTH GSSAPI NTLM LOGIN
< 250-8BITMIME
< 250-BINARYMIME
< 250 CHUNKING
> AUTH GSSAPI
< 334 GSSAPI supported
* gss_init_sec_context() failed: No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_501).
* Closing connection 1
Error in curl::curl_fetch_memory(url, handle = h) :
  Failure when receiving data from the peer

And output from sessionInfo()
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.3 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] blastula_0.3.1.9000

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.3        compiler_3.6.1    prettyunits_1.0.2 remotes_2.1.0     tools_3.6.1       getPass_0.2-2
 [7] testthat_2.3.1    digest_0.6.23     pkgbuild_1.0.6    uuid_0.1-2        pkgload_1.0.2     jsonlite_1.6
[13] memoise_1.1.0     rlang_0.4.2       cli_2.0.0         rstudioapi_0.10   commonmark_1.7    curl_4.3
[19] yaml_2.2.0        xfun_0.11         withr_2.1.2       stringr_1.4.0     knitr_1.26        fs_1.3.1
[25] desc_1.2.0        devtools_2.2.1    rprojroot_1.3-2   glue_1.3.1        R6_2.4.1          processx_3.4.1
[31] fansi_0.4.0       sessioninfo_1.1.1 callr_3.4.0       magrittr_1.5      usethis_1.5.1     backports_1.1.5
[37] ps_1.3.0          ellipsis_0.3.0    htmltools_0.4.0   assertthat_0.2.1  stringi_1.4.3     crayon_1.3.4

Comment: Did you find a workaround for this, I think I might have the same issue
Comment: #ashcrashbegash I settled with my existing python based solution, as I did not make it work then.
Answer: This looks identical to an error I received while trying to use SendGrid as the SMTP service. The issue was not with blastula, but with the fact that I had not verified a "Single Sender Identity".
In the SendGrid UI you will find "Sender Authentication" under settings. Verify the address that you will use as the from address in you blastula message. Once you have clicked on the verification email that you receive in your inbox send again from blastula. The message should now be delivered without issues.
Comment: @ashcrashbegash I am referring to the ui of https://sendgrid.com/ (one of many email delivery services)
Comment: I'm lost. What's the SendGrid UI?


Applications of Second Order Differential Equations

Question: Hanging Spring.
A 10 kilogram mass suspended from the end of a vertical spring
stretches the spring $\frac{49}{90}$ metres. At time t = 0, the mass is started in motion from the equilibrium position with an initial velocity of $1 $ $m/s$ in the upward direction. At the same time, a constant downward force of $360$ Newtons is applied to the system.
Assume that air resistance is equal to $60 $ times the instantaneous velocity and that the acceleration due to gravity is $g = 9.8 $ m/s^2.
(a) Determine the spring constant.
(b) Show that the equation of motion is
$$ \ddot{x}  + 6 \dot{x} + 18x = 36 $$
where $x(t)$ is the displacement of the mass below the equilibrium position at time
$t$ . In your answer include a diagram of all forces acting on the mass.
(c) Find the position of the mass at any time. Would you describe the motion as
overdamped, underdamped or critically damped?
I'm struggling with part (c) and any help would be appreciated.
Solving for $\lambda$ I know that
$$ X_p =A\cdot t\cdot e^{-3t}\cdot\cos(3t)+B\cdot t\cdot e^{-3t}\cdot\sin(3t) $$
since without $t$, using the equation gives a result of zero,
using
$$ \ddot{x} + 6 \dot{x} + 18x = 36, $$
with $X_p$ I get
$$  6=e^{-3t} (b \cos(3t)-a \sin(3t))$$
but the answer say
$$ x(t) = −2 e^{−3t} \cos (3t) −\frac73 e^{−3t}\sin (3t) + 2 $$
where does this $+2 $ come from, and how is the equation used without multiplying by t if it equals to zero? Sorry if this question is unclear and if any clarification is needed please ask.
Comment: Remember the _method of undetermined coefficients_: in this case, you assume that $x=k$ (constant) is a solution of the equation, so $18k=36$. The general solution is $x=2\,+$ the general solution of the associated homogeneous equation that you already found.
Comment: You need to format you're questions using latex [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?rq=1) is a good link to get you started.
Comment: Where is $\lambda$ defined in your question?
Comment: I haven't defined $\lambda$ in the equation and honestly I might have a lack of understanding about what it is, but from what i've done in the past i've used $ \lambda ^{2}+6\lambda +18=0 $ and solved to get $\lambda$=-3$\frac{+}{-}$$3i$ which I used to find my x(t)
Comment: Thanks for formatting my question
Comment: Wasn't aware of this method, I performed the working out again and reached the correct answer, thanks tony!
Answer: Your $X_p$ without the extra $t$ is the solution of the homogeneous equation, i.e. when you set the RHS equal to zero.
To get the complete solution, you need to add a particular solution of the non-homogeneous equation.
In $$ \ddot{x} + 6 \dot{x} + 18x = 36, $$ if you try a constant solution $x=C$, the equation simplifies to
$$0+0+18x=36$$ and the constant is $2$.
Hence the general solution
$$e^{-3t}(A\cos 3t+B\sin 3t)+2.$$
Remains to determine the constants using the initial conditions.
Answer: Notice, we can find out the solutions as follows
a) let $k$ be the spring constant of the spring then the elongation of the spring when it is acted upon by a force $mg=10\times 9.8=98\ N$ is given as $$=\frac{\text{applied force}}{\text{spring constant }}=\frac{mg}{k}$$ $$ \frac{98}{k}=\frac{49}{90}$$$$\implies \color{red}{k=180\ N/m}$$
b) Now, let $x$ be the downward displacement of the mass at time $t$ when a total $F_t=360\ N$ force is applied in the downward direction at the equilibrium state of mass then let's consider all the forces acting on the mass as follows
The spring force acting in the upward direction$$F_s=kx=180 x$$
 Air resistance acting in the upward direction $$R_a=60v=60\frac{dv}{dt}=60\dot x$$ Restoring force acting in the upward direction $F_r=ma=m\frac{d^2x}{dt^2}=10\ddot x$
Now, for the dynamic equilibrium of mass, we have $$\text{net force acting in the upward direction}=\text{net force acting in the downward direction}$$
$$F_s+R_a+F_r=F_t$$ $$180x+60\dot x+10\ddot{x}=360$$
$$\ddot{x}+6\dot x+18x=36$$
c) Now, the damping factor $$=\frac{\text{damping coefficient}}{2\sqrt{km}}$$ $$=\frac{60}{2\sqrt{180\cdot 10}}=0.707<1$$
Hence, the vibrations are under-damping.
For finding out the position of the mass solve the differential equation for $x$ in terms of time $t$.
Answer: Since this is a linear autonomous differential equation, you can always add a linear combination of the general solutions. Here the general solution solves the homogeneous differential equation, so with the right-hand-side of the differential equation equal to zero.
I believe you did find the correct general solutions, but you are incorrect by multiplying it by $t$. When you have a nonhomogeneous differential equation, you have to find the particular solution, which solves the nonhomogeneity. If the nonhomogeneity is a polynomial of order $n$, then there will always be a polynomial of also order $n$ which solves the nonhomogeneous differential equation, and thus would be the particular solution.
The generalized solution to your differential equation would thus be equal to the particular solution plus a linear combination of the general solutions.
PS: you only have to multiply by $t$ if the right-hand-side of the nonhomogeneous differential equation is equal to a linear combination of the general solutions, of if you have a repeating eigenvalues.
Answer: $$
\ddot{x}  + 6 \dot{x} + 18x = f(t)
$$
$$
x(t) = x_h(t) + x_p(t)
$$
$$
x_h(t) : \ddot{x}  + 6 \dot{x} + 18x = 0 \rightarrow x_h(t) = C_1 e^{-\lambda_1 t} + C_2 e^{-\lambda_2 t}
$$
$$
x_p(t) : \ddot{x}  + 6 \dot{x} + 18x = f(t) = 36
$$
since $f(t)$ is constant you can assume a $x(t) =$ constant
$$
x(t) = k \\
0 + 0 + 18k = f(t) = 36 \rightarrow  k = 2
$$
$$
x(t) = x_h(t) + x_p(t) = C_1 e^{-\lambda_1 t} + C_2 e^{-\lambda_2 t} + 2
$$


How to rearrange fields in user/%/edit page

Question: I have tried rearranging fields in user/edit page and I succeeded in arranging only few fields.
I cannot move user image field and timezone field. I have used hook_form_alter and $form['#after_bulid'] to rearrange field but not working.
This is the code
function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
  $form['#after_build'][] = 'MY_MODULE_user_profile_form_after_build';
}
function MY_MODULE_user_profile_form_after_build($element, &$form_state) {
  $element['field_user_image']['#weight'] = '';
  $element['timezone']['#weight'] = '';
}

I have tried all weight from -10 to 10 but not working. Fileds should be arranged in the order as I specified in the screenshot. Can any one help me?
Answer: use nod template as page--user--edit.tpl.php and you can able too rearrange the fields by its machine name like as we did for content types...
just try this..
Answer: You can use $form['#pre_render'] instead of $form['#after_bulid']
<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#pre_render'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = 10;
  return $form;
}

Comment: This snippet works, but i can't able to move the timezone field above facebook connect as specified in the screenshot.


Save the current state of the docker container into a new docker image

Question: I have a simple project that has a Cassandra database in a docker container. The database contains only one keyspace and a table. I want to save the container as an image after creating the keyspace and the table. So in the new docker image, it will contain both. The main idea behind this is to use this new image to create TestContainers during the testing of the functionalities of the application. Also, I won't need to every time generate the table since the new container will have it anyway, and in the test classes I can only focus on the actual functionality testing.
The project contains a student service that has CRUD operations to add, update, get, and delete student data. I created the first container using the following docker-compose file
docker-compose.yml
version: '3'

services:
  cassandra:
    image: cassandra:latest
    container_name: test-container-student
    ports:
      - 9042:9042
    volumes:
      - C:/Users/{username}/Documents/backup/student:/var/lib/cassandra

Student class
public class Student
{
    public Guid StudentId { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public int Age { get; set; }
}

Then I ran this Program.cs to generate the keyspace and the students table.
using Cassandra;

namespace TestProject;

class Program
{
    static void Main(string[] args)
    {
        // Define the Cassandra cluster
        var cluster = Cluster.Builder()
            .AddContactPoint("127.0.0.1")
            .Build();

        // Create a session
        var session = cluster.Connect();

        // Create the keyspace if it doesn't exist
        session.Execute(@"
            CREATE KEYSPACE IF NOT EXISTS StudentDetails
            WITH replication = {
                'class': 'SimpleStrategy',
                'replication_factor': 1
            }");

        session.Execute(@"
        CREATE TABLE IF NOT EXISTS StudentDetails.students (
            student_id UUID PRIMARY KEY,
            first_name TEXT,
            last_name TEXT,
            age INT
        )");
    }
}

After running the project it successfully creates the keyspace and table. And I saved the docker image using docker commit. Then I generated a new docker container using this new docker image. But when checked the tables in the new container, I realized that the table I previously created, is not there. Is there any way that I can successfully save the image with the table? Thank you.
Comment: Could you try to remove the volume from your docker-compose and retry everything again? It may interfere with your new container.
Comment: Hi @kevto, first I tried without adding a volume. But it also didn't work as expected.
Comment: Database container images tend to contain a `VOLUME` directive, which means the database data will _always_ be stored in a volume, and `docker commit` won't include it in an image.  Questions like [docker postgres with initial data is not persisted over commits](https://stackoverflow.com/questions/27377876/docker-postgres-with-initial-data-is-not-persisted-over-commits) suggest changing the data directory to avoid this.  But in any case `docker commit` is almost never a best practice (how would you recreate the image if you need to update the database version?).
Comment: @DavidMaze yes it is not the best solution. May be I can try adding cql query as an entryPoint as in the reference question you sent. Thank you.
Answer: I had done the same thing for superset and worked. Following are the steps I followed.

Get running cassandra:latest ID using sudo docker ps
sudo docker commit <docker-container-id-of-cassandra> new-cassandra
Go to your docker-compose.yml file location sudo docker-compose down
Edit docker-compose.yml with new cassandra image

version: '3'

services:
  cassandra:
    image: new-cassandra
    container_name: new-container-student # <- change name here
    ports:
      - 9042:9042
    volumes:
      - C:/Users/{username}/Documents/backup/student:/var/lib/cassandra

sudo docker-compose up -d
Comment: This is working. ```WithBindMount("C:\\Users\\{username}\\Documents\\backup\\student", "/var/lib/cassandra")``` worked for testContainers. :)
Comment: If all of the data is in the named volume, you don't need the `docker commit` step. You can (and should) use the unmodified original image in combination with the persistent data volume.
Comment: Hi @sachith, Can you please explain what is happening here? It's not very clear where did you add your tables to the container.
Comment: @Panda153 You mounted your docker image to local and in new image also uses the same volume. So data will be available. Docker commit will create a new image (if you had added additional configs to container) and can be used in new as fresh.
Comment: @DavidMaze Yes, I added that step for the worst case, assuming changes were made to docker container on run time,


Correct numerical result in Bayesian model comparison

Question: I was wondering how to calculate the following Bayesian model comparison.
Suppose you have a couple of models:
$$M_{1}: x \sim Bin(n, \pi); p \sim Be(1,1)$$
$$M_{2}: x \sim Bin(n, \pi); p \sim Be(30,30)$$
Congdon's book says this:

As a toy example, consider comparing two beta priors, $p ∼ Be(\alpha, \beta)$,
  for a binomial probability, when the data are x = 1 sucesses in n = 10
  trials.
This choice can be solved analytically to give $P(M_1 |x) = 0.8634$.
  In particular, integrating $\pi$ out from the binomial-beta mixture
  model, $x \sim Bin(n, π)$, $π \sim Be(\alpha, \beta)$, gives a
  beta-binomial distribution, $x ∼ Beta−Bin(n, \alpha, \beta)$, with
  density:
$$p(x|n,\alpha, \beta)= \frac{Be(x+\alpha, n-x+\beta)}{Be(\alpha,
 \beta)}Bin(n, x)$$
  which can be evaluated at $p(x|10, 1, 1)$ and $p(x|10, 30, 30)$

where $Beta-Bin$ is the Beta-Binomial distribution.
I was assuming that $P(M_{1}|x)$ was calculated in the following way:
$$P(M_{1}|x) \propto  P(M_{1})p(x|M_{1}) = P(M_{1})\int _{0}^{1}p(x|\pi,M_{1})p(\pi|M_{1})d\pi$$
In the equation above, $p(x|\pi,M_{1})$ should be the likelihood $Bin(n,\pi)$ and the second term $p(\pi|M_{1})$ is the prior $Beta(1,1)$ under model $M_{1}$.
The integral $\int _{0}^{1}p(x|\pi,M_{1})p(\pi|M_{1})d\pi$ is simply
$$\int _{0}^{1}Bin(n,\pi)Beta(1,1)d\pi=\int_{0}^{1}\binom{n}{x}p^{x}(1-p)^{n-x}\frac{p^{\alpha-1}(1-p)^{\beta-1}}{B(\alpha,\beta)}dp = \frac{Be(x+\alpha, n-x+\beta)}{Be(\alpha,\beta)}\binom{n}{x}$$
However, even though I obtain the result described in the quote as $p(x|n,\alpha, \beta)$ after solving the integral, I don't get the correct numerical result (assuming $P(M_{1})=0.5$ and after normalizing both $P(M_{1}|x)$ and $P(M_{2}|x)$)
Does anyone know how to obtain the correct result?
Comment: Damn, turns out that now I get the correct result! Maybe I miscalculated something the first time. I will update it anyway.
Comment: What is the observed $x$?
Comment: Oh, sorry. It is supposed to be $x=1$ and $n=10$. Let me add that part too.
Comment: Add also the computations and values you obtain for $P(x \mid M_i)$ and $P(M_i \mid x)$.
Answer: It seems I miscalculated something the first time. Now I get the correct answer.
Basically, I did the following calculation (again assuming $P(M_1) = P(M_2) = 0.5$):
$$\frac{P(M_{1}|x)}{P(M_{2}|x)} =  \frac{P(M_{1})p(x|M_{1})}{P(M_{2})p(x|M_{1})} =\frac{p(x|M_{1})}{p(x|M_{2})}=\frac{0.0909091}{0.014382}$$
However, since this is not normalized, $0.0909091+0.014382=0.105291$ and recompute each value:
\begin{array}{ccc}p(M_{1}|x)=&0.0909091/0.105291=0.863407 \\  p(M_{2}|x)=&0.014382/0.105291=0.136593\end{array}


End NodeJS program using streams

Question: I have a small program that is running an ETL pipeline on some XML data. I'm using pump (package) to combine a Readable, Duplex, and Writeable streams. I'm getting the final 'done' callback, but the program doesn't exit. Is the only way to handle this to call process.exit(0)?
Here's the code snippet:
pump(
    fileStream,
    parser,
    inserter,
    (err) => {
        if (err) {
            console.log(err);
        } else {
            console.log('done');
        }
    });

Edit: Just to close the loop, what @FakeFootball suggested does the trick:
pump(
        fileStream,
        parser,
        inserter,
        (err) => {
            if (err) {
                console.log(err);
            } else {
                parser.destroy();
                inserter.destroy();
                fileStream.destroy();
            }
        });

Answer: Without seeing the rest of your code, my guess is you aren't closing/destroying any of your streams so they are still active. Node won't close as it is still listening for potential actions on those streams. See the example in the usage section of the pump documentation for how they close the stream and it destroys the rest of them. Pump usage
Comment: Well process.exit will in effect destroy your stream, you want to handle it elegantly as there may be housekeeping (e.g closing database connections) that happens when you destroy the streams in your code and may not happen if you kill the program with process.exit. In your case, I would just add the destroy statements in the finished callback along side the console.log("done").
Comment: Yeah so that's my question. Is there a 'proper' way to signal that the streams are done without calling `destroy`? Ideally I'd like the `end` event from the file stream to trigger an end on the parser and then an end on the db handler. Manually calling `destroy` is more or less the same as calling `process.exit()` for my purposes.

End NodeJS program using streams


Using ajax to GET a token from external site returns empty response

Question: I have two sites right now.  One that has a token and one that is supposed to allow a user to do stuff with the token.
When I visit the first site that has the token, mySite.local/services/session/token it shows it: OTV4Gu9VQfjIo2ioQ0thajdEJ6nEINoxsLuwgT_6S0w
When I am on the page that is supposed to GET this token, I get an empty response and the error for the ajax function is thrown.
The weird part is that when investigating the issue with firebug, I can see the response for the ajax request is 43B - the same size as the token.  So for some reason the page with the token is being hit properly, but the response is not coming through.
Here is a screenshot of the firebug response:

And here is the JQuery with the ajax request:
var nid; //global node id variable
  $('html').click(function(){
    try {
      $.ajax({
        url:"http://mySite.local/services/session/token",
        type:"get",
        dataType:"text",
        error:function (jqXHR, textStatus, errorThrown) {
          alert('error thrown - ' + errorThrown);
          console.log(JSON.stringify(jqXHR));
          console.log(JSON.stringify(textStatus));
          console.log(JSON.stringify(errorThrown));
        },
        success: function (token) {
          //Do some stuff now that token is received
        }
      });
    }
    catch (error) {
      alert("page_dashboard - " + error);
    }
  });

Comment: I know it says the IP address is 127.0.0.1, but are you accessing it from the same domain name `mysite.local`?
Comment: Then your running into cross domain restriction with AJAX (aka [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy)). You can't make a AJAX request to another domain without using CORS to white list the domain(s), or [JSONP](http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain).
Comment: Nope, the one hosting the token would be mysite.local and the other would be mysitemobile.local
Comment: Would you post this as the answer so that I may mark the question as solved?
Answer: Your running into the Same Origin Policy which essentially states any request done by client side/browser language like Javascript must be on the same port, with the same domain name and the same protocol. In your case http://mysitemobile.local does not equal http://mysite.local so you're request is being blocked. Firebug's way of displaying that is no response with 43 bytes.
There are two ways to work around this, Cross-origin resource sharing (CORS) or JSONP. CORS is a HTTP header that is added to the server you are requesting to and provides a whitelist of acceptable domains that are allowed break the same origin policy. Most recent browsers support this header.
The other option is JSONP, wraps a JSON object into a Javascript function that is called using


Javascript slideUp / slideDown / one button

Question: I am having trouble of solving a problem. I have 2 buttons, the one is for slideUp and the other is for slideDown. What i would like to do is to have one button that toggle instead of having 2.
Thanks.
I have this code in html:

Show / Hide

  <button onclick="slideUp('box');">Slide Up</button>
  <button onclick="slideDown('box');">Slide Down</button>

and i have this code in css:
body{
  background:grey;
}

#box{
  width:400px;
  height:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}

and my javascript code is this:
function slideUp(el) {
  var elem = document.getElementById(el);
  elem.style.transition = "all 2s ease-in-out";
  elem.style.height = "0px";
}
function slideDown(el) {
  var elem = document.getElementById(el);
  elem.style.transition = "all 2s ease-in-out";
  elem.style.height = "400px";
}

Comment: I actually was looking for the implementation as two separate functions for a demo and I thought your code would work,  but it doesn't.
Answer: You can create CSS class with the height:0 rule, and toggle that class with JS:

var elem = document.getElementById("box");
function slide() {
  elem.classList.toggle('hide');
}
.box {
  width: 400px;
  height: 400px;
  overflow: hidden;
  background: orange;
  margin: 0 auto;
  transition: all 0.4s ease-in-out;
}
.hide {
  height: 0;
}
<button onclick="slide();">Slide Toggle</button>

Show / Hide

Comment: @Bosworth99: "Every time the user clicks" is not very expensive. They don't do that a thousand times per second.
Comment: @MattiVirkkunen Its expensive enough, and shouldn't be promoted as a good design pattern. These clicks tend to do more and more as an application grows in complexity. My humble $.02
Comment: `transition : all 2s ease-in-out` doesn't have to be set in js.
Comment: Every time you click, the DOM must be analyzed. This gets expensive over time.
Comment: @itsgoingdown hey in line one of your CSS it needs to be "#box" because box is the ID not the class. Just a heads up.
Answer: Put the css properties into a class, add the class to your element, and then toggle the class that affect the height on/off of the element using classList.toggle()

function slideToggle(el) {
  var elem = document.getElementById(el);
  elem.classList.toggle("open");
}
body{
  background:grey;
}

#box{
  width:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}

.slider {
    transition:all 2s ease-in-out;
    height:0px;
}
.slider.open {
    height:400px;
}

Show / Hide

<button onclick="slideToggle('box');">Slide</button>
Answer: I like to track state with a simple boolean, a bit like so :
var _bool = false;
var _box = document.getElementById('box');
var _clik = document.getElementById('clik');

_clik.addEventListener('click', function(){
  if (_bool){
      _box.style.height = '100px';
      _bool = false;
   } else {
      _box.style.height = '10px';
      _bool = true;
   }

});

Here's a Fiddle
Importantly, we're not storing state on the DOM, and so once your app gets complicated, it will stay performant. You, obviously, can use these two states in whatever way you like (animation, css transition, etc);
Answer: You can create class .slideup
#box.slideUp {
    height:0;
}

And toggle this class on #box:
function toggle(){
    document.getElementById('box').classList.toggle('slideUp')
}

Example here
Answer: Best way is to toggle a class on the box when the button is clicked. That class will set the height on the box to 0, and so the transition will take effect and smooth the change.
JS
document.querySelector('.js-button').addEventListener('click', function (event) {
  document.querySelector('.box').classList.toggle('box-closed')
});

CSS
.box-closed {
  height: 0px;
}

Demo
Answer: Apply transition to  #box via css stylesheet;
 #box {
  -webkit-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
  width:400px;
  height:400px;
  background:orange;
  margin:0 auto;
  margin-top:3%;
  overflow:hidden;
}

I am trying to get more familiar with modules today, so this is a modular approach - solution
  var Dropdown = function(el) {

      var is_open = false;
      var elem = document.querySelector(el);
      // in case you cannot set transition via stylesheet
      elem.style.transition = "all 2s ease-in-out";

      function slideUp() {
        elem.style.height = "0px";
        is_open = false;
      }
      function slideDown() {
        elem.style.height = "400px";
        is_open = true;
      }
      function init() {
        if(is_open) {
          slideUp();
        }else{
          slideDown();
        }
      }
      return {
        init : init
      }
  };

  myDropdown = Dropdown('#box');
  document.querySelector('#your-button').addEventListener('click',  myDropdown.init);

Answer: Make it shorter:
<button onclick="slide()"></button>

JS: slide(){document.getElementById("box").classList.toggle('hide');}
#box {
  overflow: hidden;
  transition: all .5s ease-in-out;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -ms-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
}
.hide {
  height: 0px !important;
}


Montart loop com variáveis para exclusão com PDO

Question: Após um filtro tenho esse form com os usuários e seus serviços, o que estou tentando fazer é enviar as informações para deleção dos registros com os parâmetros setados no form, no caso seria o ID do Usuário e o Serviço, na sequência vou inserir os que estiverem com check marcados, ou seja, podem ser vários registros ao mesmo tempo sendo enviados.
Esse é o meu formulário:

As minhas variáveis estão assim no meu form:
 <input type="checkbox" name="Check[]"  class="checkbox1" <?php if ($retorno >= 1) { echo "checked='checked'"; } ?> value="<?php echo $IdUsuario;  ?>">
 <input name="IdUsuario" type="hidden" value="<?php echo $IdUsuario;  ?>" />
 <input name="IdServico" type="hidden" value="<?php echo $IdServico;  ?>" />
 <input name="IdInterface" type="hidden" value="<?php echo $IdInterface;  ?>" /

Estou precisando executar um loop para uma efetuar uma exclusão do meu BD, mas não tenho como fazer esse loop, pois só recebo as variáveis vinda de um form, existe alguma maneira de fazê-lo somente com essas variáveis?
As variáveis que recebo são essas:
$IdUsuario = (isset($_POST['IdUsuario'])) ? $_POST['IdUsuario'] : '';
$IdServico = (isset($_POST['IdServico'])) ? $_POST['IdServico'] : '';

O meu código de exclusão está assim:
$sql = "DELETE FROM `gasUsuarioServico` WHERE `IdUsuario` = :IdUsuario AND `IdServico` = :IdServico";
$stm = $conexao->prepare($sql);
$stm->bindValue(':IdUsuario', $IdUsuario, ':IdServico', $IdServico);
$retorno = $stm->execute();

Comment: Não estou entendendo, pode oferecer mais detalhes? Por que você não pode usar essas variáveis no loop?
Comment: Olá @MagicHat, justamente é esse a minha dificuldade, como montar um loop com variáveis.
Comment: Deixa eu tentar entender a situação... Pelo que percebo os dados contidos nas variáveis são únicos(pois são ids), o loop executa uma ação repetidas vezes até que uma condição seja satisfeita, entretanto nesse caso(aparentemente) você não poderá executar a ação mais do que uma vez... Então aí que não estou entendendo a  necessidade do loop... Tente explicar mais detalhadamente o funcionamento desse processo que deseja, ex: de onde vão vir os valores desses ids(embora vc tenha mencionado de um form)... Quero dizer, será enviado 1 usuário e serviço por vez?
Answer: Bom eu fiz o código baseado no seu.
Deixei documentado no código.
<?php

if(isset($_POST['check'])){ //Verifica se tem algum usuário selecionado

   $checked = $_POST['check'];//Posicoes selecionadas

   $IdUsuario = $_POST['IdUsuario']; //Array de usuarios
   $IdServico = $_POST['IdServico']; //Array de Servicos
   $IdInterface = $_POST['IdInterface']; //Array de Interfaces

   $total = count($checked); //Quantidade de usuários selecionados

    for($i=0;$i<$total;$i++){ //Varrer eles

        //echo $IdUsuario[$checked[$i]]; //Usuario selecionado
        //echo $IdServico[$checked[$i]]; //Servico selecionado
        //echo $IdInterface[$checked[$i]]; //Interface selecionado

        $sql = "DELETE FROM `gasUsuarioServico` WHERE `IdUsuario` = :IdUsuario AND `IdServico` = :IdServico";
        $stm = $conexao->prepare($sql);
        $stm->bindValue(':IdUsuario', $IdUsuario[$checked[$i]], ':IdServico', $IdServico[$checked[$i]]);
        $retorno = $stm->execute();
    }
}
?>
<form name="form1" method="post">
<?php
    //Dados colocados fixos, mas deve alterar para a sua busca
    $db_usuarios = array(
                    array("user"=>"Usuário 1",
                          "usuario"=>"1",
                          "servico"=>"1",
                          "interface"=>"1"),
                    array("user"=>"Usuário 2",
                          "usuario"=>"2",
                          "servico"=>"2",
                          "interface"=>"2"),
                   array("user"=>"Usuário 3",
                          "usuario"=>"3",
                          "servico"=>"3",
                          "interface"=>"3")
                );

   $total_usuarios = count($db_usuarios); //Alterar para a sua busca

for($i=0; $i<$total_usuarios; $i++){ //Criar os usuários dinamicamente
?>

<input type="checkbox" name="check[]"  class="checkbox1" value="<?php echo($i); ?>"><?php echo($db_usuarios[$i]['user']); ?>
<input name="IdUsuario[]" type="hidden" value="<?php echo($db_usuarios[$i]['usuario']); ?>" />
<input name="IdServico[]" type="hidden" value="<?php echo($db_usuarios[$i]['servico']); ?>" />
<input name="IdInterface[]" type="hidden" value="<?php echo($db_usuarios[$i]['interface']); ?>"/>

<?php

}

?>

<input type="submit" value="Enviar">

</form>

Comment: Obrigado pela grande ajuda @Everson, muito interessante essa solução.


Update remaining points in different site once purchase through points method

Question: I am using userpoints module. What I need to do is once the purchase is done through points methos, update the remaining points in different drupal site.
I have tried for webservices. I have created web services which will update the remaining points in other site.
I have gone through the code and found function uc_userpoints_payment_uc_order() 'all\modules\userpoints_ubercart\uc_userpoints_payment\uc_userpoints_payment.module' where it updates (uc_userpoints_payment_payment) or refund the points (uc_userpoints_payment_refund). So here (in these two functions), I want to call webservice.
Could anyone please throw some light and point me in right direction?
Answer: You can call web service using hook_uc_checkout_complete. it takes action when checkout process is completed.
Please refer uc_cart api


Simple way to change color of "special" special character

Question: Is it possible to change the color of this and other special characters?

This text is red but the following symbol isn't: &#10006

Apparently, the symbol is actually an image. So that explains why it's immune to the color attribute. But is there a way of changing the color nonetheless?
I found this question Change color of PNG image via CSS? but the answer a) didn't work in my browser or b) required several lines of code. I wondered whether there might be a better alternative, since this should be a very common issue.
Comment: Thanks for the comment! Huh... yes, it works for me, too. However, on my website, it doesn't.

I use Wordpress and the Tempera theme. If you need more info, please let me know.
Comment: On [this fiddle](http://jsfiddle.net/fguu1cgd/) the code works fine, and the 'X' is turned red. You might need to post a little more code for us to work out what's happening.
Comment: Special characters usually are represented purely as text, rather than images. It sounds more like a problem specific to wordpress, and perhaps specific to the Tempera theme too. Consider double-checking with the Wordpress community themselves or asking/checking under the `wordpress` tag here on stackoverflow.
Answer: The code is working perfectly. Use ✖ instead of &#10006 as HTML entity is not closed and might create style error.
To change color, use CSS color property.
Comment: Thanks, but, unfortunately, while working in the fiddle, both codes don't work on my website.


How is it possible that neither if nor else branch gets executed here?

Question: I'm developing one of my first drupal modules and stuck here:
$maxexp = db_result(db_query("SELECT max(expiration) FROM {uc_roles_expirations} WHERE UID=%d and rid=%d", $uid_befizeto, 4));
dpm('DB query finished');
dpm('me = '.$maxexp);

if($maxexp) {
   dpm('True branch');
 } else {
   dpm('False branch');
 }

This is a snippet from mymodule_nodeapi's case 'insert'. My problem is that I do not understand why do I see the following messages after saving a node:
DB query finished
me =
Node blah saved successfully

I simply do not understand if there is no error, how it is possible that I cannot see True branch or False branch among the messages..
Comment: examined `dpm(is_null($maxexp))` and the result is 1. but when I tried to replace the condition of the `if` statement with `if(is_null($maxexp))` still the same happened: neither true nor false branch got executed.
Answer: It was a character encoding problem in the source file. I changed the encoding in my favorite  text editor, and the code started working.


Python: Random item from list combining only two

Question: I'm making a slot machine program in Python and for some reason, the random selector wants to combine a known two elements.
<code>    itmlist = random.choice(['banana', 'cherry', 'bar', 'seven', 'banana', 'cherry' 'banana', 'cherry', 'seven'])
    print itmlist
</code>
It shows up as "cherrybanana" every once in a while and I am really confused.
Comment: have pity on the maintainer of your code and create the list as `['banana'] * 3 + ['cherry'] * 3 + ['seven'] * 2 + ['bar']`
Answer: You miss a comma between 'cherry' and 'banana' near the end of the list.
Python concatenate the strings so it becomes 'cherrybanana'
itmlist = random.choice(['banana', 'cherry', 'bar', 'seven', 'banana', 'cherry' 'banana', 'cherry', 'seven'])
Comment: @Kimvais' suggestion would avoid this problem neatly. You could also have diagnosed it by storing the list separately (you may well need the same list in a few different places, if you're doing what I think you're doing) and printing it to verify its contents.


bt-hci btu_ble_process_adv_pkt still runs after iBeaconManager.unBind(this); is called onDestroy()

Question: I am using Radius Networks iBeacon library for Android to build my first Android app. It's been really easy to implement the library and I've got a half-decent demo app working (thanks a lot davidgyoung!).
I am now trying to iron out the kinks. My app works as a demo whereby a user needs to tick off 3 checkboxes by going near 3 iBeacons. They are then presented with an activity that asks if they want to do it again with a button to restart.
The function that displays the 'completed' activity also finish()s the 'checkbox' (ranging) activity, and onDestroy calls the unBind method of iBeaconManager.
Intermittently, after a restart the iBeacons aren't picked up and LogCat is spits out this forevermore.
02-18 14:52:38.800: I/bt-hci(1392): BLE HCI(id=62) event = 0x02)
02-18 14:52:38.800: I/bt-hci(1392): btu_ble_process_adv_pkt
02-18 14:52:38.850: I/bt-hci(1392): BLE HCI(id=62) event = 0x02)
02-18 14:52:38.850: I/bt-hci(1392): btu_ble_process_adv_pkt
02-18 14:52:38.910: W/bt-btif(1392):  bta_dm_ble_observe BTM_BleObserve  failed. status 2
02-18 14:52:38.980: I/bt-hci(1392): BLE HCI(id=62) event = 0x02)

It usually happens on the second/third run of the app.
My hunch is that it is because of a failing with
iBeaconManager.unBind(this);

not releasing the BT stack properly, so ending up with two instances overlapping.
Could anyone shed some light on this because I've reached a point where I'm not getting anywhere.
Please let me know if you'd like to see more code.
Best
Andrew
Comment: I actually had these values set to the same thing and at 400 ms no less! iBeaconManager.setForegroundScanPeriod(ranging_frequency); iBeaconManager.setBackgroundScanPeriod(100000); I would like to know if there is a way to completely stop the BackgroundScan though if anyone has any ideas? Cheers
Comment: This probably deserves a question of its own.  The IBeaconService should stop completely if you properly unbind() with the IBeaconManager.
Answer: I suspect the issue does have to do with binding to/unbinding from the service.  This should be no problem doing what you describe if the code always unbinds before rebinding later.  It is hard to say for sure what is going wrong without seeing the code (or a simplified version that reproduces the problem.)
I would suggest adding a log statement when you bind and another when you unbind, then run the app and make sure they match up.  The Android life cycle can be tricky.  I bet you will find that there is a mismatch.  Are you sure the on Destroy() is always getting called?
Understand that if iBeaconManager.unbind() is called when no other clients are bound, the IBeaconService will stop, and LogCat should confirm this.  If you later rebind, it will simply start back up again.  Are you seeing this?
One other tip: if you have two apps running on your phone using the Android iBeacon Library, you will have two copies of the service running.  This is by design, and should pose no problem, but might make LogCat output confusing.  Use settings to stop or uninstall all but one of these apps to aid in debugging.
Answer: I had this issue as well and tracked it down to a bug within the IBeaconLibrary itself. I was about to report the issue to RadiusNetworks but noticed on their GitHub that this was already found (or a similar bug with related cause) and was fixed in their current code. Unfortunately, it is not yet in an official release and so you'll need to download the source from GitHub and build the library yourself but I can confirm that after having done so, I am no longer seeing this issue.


How to show all tables in database dynamically?

Question: I want to select all tables in my database

Using Dynamic-SQL:
DECLARE @sql nvarchar(max) = N'',
  @base nvarchar(max) = N'select * from $x$;';
SELECT  @sql += REPLACE(@base, N'$x$;', QUOTENAME(name)+';
')
  FROM sys.all_objects where type='U'
--PRINT @sql;
/*
select * from [trace_xe_action_map]; -- Why get this table!
select * from [trace_xe_event_map];  -- and this too!
select * from [errorTable];
select * from [table_objects];
select * from [table_fields];
select * from [alter_table];
select * from [computed_colonnes];
select * from [colonnes];
select * from [nullish_columns];
select * from [test];
*/
EXEC sys.sp_executesql @sql;

When I've run this: it tells me error that:

Msg 208, Level 16, State 1, Line 1
Invalid object name 'trace_xe_action_map'.

besides that I've added in the clause where condition  and (name!='trace_xe_action_map' or  name!='trace_xe_event_map'); but the same error?
How can I skip those two selected values (trace_xe_action_map, trace_xe_event_map)?
I also tried Top 8 with  order by 1 desc to avoid two first records, But in the result I just got the first table selected dynamically! Instead of all tables.
Comment: Use `sys.objects` instead of `sys.all_objects`. Better yet, use `sys.tables` with no `WHERE` clause.
Comment: FYI self referencing variables like that are a [documented Antipattern](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/select-local-variable-transact-sql?view=sql-server-ver15#c-antipattern-use-of-recursive-variable-assignment) use actual string aggregation.
Comment: thanks for specification, but just out of curiosity how can I avoid the two rows returned in table?
Comment: Add `and is_ms_shipped = 0`
Comment: What do you mean avoid the two rows?
Comment: @Larnu even though the query returned tables that I don't want how can I don't show them I've used `where clause` it's not worked for me, so I tried `top with order by`
Answer: I've just solved with the help of dan-guzman and larnu
DECLARE @sql nvarchar(max) = N''
select @sql = String_Agg(Concat('select * from ', QuoteName(name)), '; ' + Char(13)) from sys.tables
EXEC sys.sp_executesql @sql;


Custom URL for entity create and view

Question: I am using ECK (Entity Construction Kit) to create my custom entities. Now I want to create custom url for various operation on my entities such as create (example.com/my-entity/create) or view (example.com/my-entity/view/custom-unique-field)
I have tried pathauto but it seems I cant define custom patterns for my own entities. Any help towards this step is highly appreciated.
Thanks,
Naveen
Answer: You can use the path (url alias) module for the create path. Since that's a single url, you can create a single path alias to change that.
It's a bit harder for your custom entities. You would have to create a custom module and integrate with path auto module to be able to create path aliases for the view urls of your custom entities. It's a lot of code, you can see how the path auto module does it for the node module. But be warned, it's not easy as there are many parts.
The gist of it is that you need to make some tokens available for the path system you are going to make, like the entity label and such. Then you need to create a function that can create an alias when given an entity. This is, however, a bit harder since you need to use the path auto API functions for this.
Comment: URL alias makes sense for creating an entity, which would be single but for viewing and might be editing, it wont be possible :(

Did you have a chance to look into http://drupal.org/sandbox/damz/1332096. The module promises to solve this particular problem, though still in sandbox and will need to use it.
Comment: @Naveen I have solved this problem before in several cases of custom url patterns that needed to be rewritten: (Views, panels, and custom entity urls), so trust me when I say the above method will work. But it's not easy for novice Drupal developers.
Comment: thanks @googletorp. Any tutorial / code sample for reference. It would be really helpful.
Comment: @Naveen The closest thing I've come has been to look at how path auto did it for the node module. You basically need to do the same thing, only for your custom entity. I could show my own code, but that wouldn't be any better than what path auto does with nodes it would be better to use for you than any of my code, since you know how nodes work already.

Custom URL for entity create and view


Android BottomSheetBehavior setState() NullPointerException

Question: I'm trying to implement BottomSheetBehavior from Android Support Design Library. I initialize BottomSheetBehavior like this:
private void initBottomSheet() {
        new AsyncTask<Void, Void, Void>() {

            View bottomSheetFrame = rootView.findViewById(R.id.bottom_sheet);

            }

            @Override
            protected Void doInBackground(Void... params) {
                bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetFrame);

                bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                    private boolean isOnTop = false;

                    @Override
                    public void onStateChanged(@NonNull View bottomSheet, int newState) {
                        switch (newState) {

                            case BottomSheetBehavior.STATE_DRAGGING: {
                                ...
                            }

                            case BottomSheetBehavior.STATE_SETTLING: {
                                ...
                            }

                            case BottomSheetBehavior.STATE_EXPANDED: {
                               ...
                            }

                            case BottomSheetBehavior.STATE_COLLAPSED: {
                                ...
                            }

                            case BottomSheetBehavior.STATE_HIDDEN: {
                                ...
                            }

                            default: {
                                break;
                            }
                        }
                    }

                    @Override
                    public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                        ...
                });

                bottomSheetBehavior.setPeekHeight((int) Utils.convertDpToPixel(100f, activityContext));
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); // NPE here

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }.execute();
    }

It's very strange, because I can change state with Button click or some other action. Please, help me.
Comment: Remove this line View bottomSheetFrame = rootView.findViewById(R.id.bottom_sheet); outiside of async task, and make find the view inside onCreate method. Also if you are updating a view you should do in onPostExecute method.
Comment: @AgustinSivoplás, thank you very much. I event didn't notice method is called from `doInBackground()`.
Answer: Problem
NPE happens because you call BottomSheetBehavior.setState(...) before your view — bottomSheetFrame was laid out. At this moment BottomSheetBehavior have null reference on the view and can't apply your state to it.
Solution
I fixed this by using View.post(Runnable) method:
View sheetView = ... ;
BottomSheetBehavior behavior = BottomSheetBehavior.from(sheetView);
int initState = BottomSheetBehavior.STATE_EXPANDED;

sheetView.post(new Runnable() {
    @Override
    public void run() {
        behavior.setState(initState);
    }
});

In my situation this helped to stop NPE-s :)
Comment: Hey! Thank you for reply. Nice solution, but in my case I need just put code out of `AsyncTask`.
Comment: Great solution, you saved me from an afternoon of frustration :)
Answer: If you are using it in a Fragment, just be sure to call it on the onCreateView() method. And if you are using it on an Activity, then call it at the onCreate() method.
At those points, your Views have to be already created, unless you are creating them programmatically.
Since you are calling methods that are related with the UI from an AsyncTask, then you'll need to surround it with the runOnUiThread as explained here https://stackoverflow.com/a/27992603/973919
Basically, you need to call to anything that is related with views, from the main thread of the app, which is the UI thread.