text:
Q: How to update a column depending on the overall rows of a table I have a table containing a colunm parentId (which has no constraint it may happens that this id does not exists , bacause of bad data !!!).
I have two separate things I would like to do
Add a bit column IsChild
- Contains true only if it has a ParentId and this one actually exists in my table
Add a bit column IsParent
- Contains true only if it has referencing child
I come up with something similar to :
UPDATE MyTable
  Set IsParent = 1
  WHERE Id in (select distinct parentId from MyTable) and IsParent = 0
UPDATE MyTable
  Set IsChild = 1
  WHERE parentId in (select id from MyTable) and IsChild = 0

But It is quite slow !!! Any idea how we can make it faster
Bonus Question : MyTable is a temporal table
If we can update all fields at once to not create as many entries as statement

A: You can try an update join.  This would be ideal if MyTable had indices on both the Id and parentId columns.
UPDATE t1
SET IsParent = 1
FROM MyTable t1
INNER JOIN MyTable t2
    ON t1.Id = t2.parentId
WHERE isParent = 0

UPDATE t1
SET IsChild = 1
FROM MyTable t1
INNER JOIN MyTable t2
    ON t1.parentId = t2.Id
WHERE isChild = 0


text:
Q: Calling method twice in same block. Why? I'm reading a blog post and trying to understand what's going on.
This is the blogpost.
it has this code:
if (validation().hasErrors())
      throw new IllegalArgumentException(validation().errorMessage());

In the validation() method we have some object initialization and calculations so let' say it's an expensive call. Is it going to be executed twice? Or will it be optimized by the compiler to be something like this?
var validation = validation();
if (validation.hasErrors())
    throw new IllegalArgumentException(validation.errorMessage());

Thanks!

A: The validation method will be called twice, and it will do the same work each time. First, the method is relatively big, and so it won't get inlined. Without being inlined, the compiler doesn't know what it does. Therefore, it safely assumes that the method has side effects, and so it cannot optimize away the second call.
Even if the method was inlined, and the compiler could examine it, it would see that there are in fact side effects. Calling LocalDate.now() returns a different result each time. For this reason, the code that you linked to is defective, although it's not likely to experience a problem in practice.
It's safer to capture the validation result in a local variable not for performance reasons, but for stability reasons. Imagine the odd case in which the initial validation call fails, but the second call passes. You'd then throw an exception with no message in it.

A: The Java to Bytecode compiler has a limited set of optimization techniques (e.g. 9*9 in the condition would turn into 81).
The real optimization happens by the JIT (Just In Time) compiler. This compiler is the result of over a decade and a half of extensive research and there is no simple answer to tell what it is capable of in every scenario.
With that being said, as a good practice, I always handle repetitive identical method calls by storing their result before approaching any loop structure where that result is needed. Example:
int[] grades = new int[500];
int countOfGrades = arr.length;
for (int i = 0; i < countOfGrades; i++) {
    // Some code here
}

For your code (which is only run twice), you shouldn't worry as much about such optimization. But if you're looking for the ultimate – guaranteed – optimization on the account of a fraction of space (which is cheap), then you're better off using a variable to store any identical method result when needed more than once:
var validation = validation();
if (validation.hasErrors())
    throw new IllegalArgumentException(validation.errorMessage());

A: However, I must simply question ... "these days," does it even actually matter anymore?  Simply write the source-code "in the most obvious manner available," as the original programmer certainly did.
"Microseconds" really don't matter anymore.  But, "clarity still does."  To me, the first version of the code is frankly more understandable than the second, and "that's what matters to me most."  Please don't bother to try to "out-smart" the compiler, if it results in source-code that is in any way harder to understand.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\underline{\int_0^1} f(x) \, dx$ and $\overline{\int_0^1} f(x) \, dx$ if $f(x) = x$ when $x$ is rational and $f(x) = -x$ when $x$ is irrational My book says $\underline{\int_0^1} f(x) \, dx = \frac{1}{2}$ and  $\overline{\int_0^1} f(x) \, dx = -\frac{1}{2}$.
I would think that the answers are $\underline{\int_0^1} f(x) \, dx = -\frac{1}{2}$ and  $\overline{\int_0^1} f(x) \, dx = \frac{1}{2}$. My understanding is that the lower integral is the supremum of all lower sums and that a lower sum is the sum of the product of the infimum of $f(x)$ on an interval and the length of the interval for all intervals on a partition of $[0, 1]$. Won't the infimum always be some value of $f(x)$ where $f(x)=-x$, since irrationals are dense in the reals, and thus there is always an irrational on any interval within a partition?
Can anyone explain where I'm going wrong? By my reasoning, the lower integral should definitely be less than or equal to zero and the upper integral should be greater than or equal to zero. Apparently I've flipped it, though.


text:
Q: Avoid rendrawing chart, D3 I am drawing a scatter chart with NVD3 library in React when a component is first mounted. I hide and show the component depending on the buttons clicked. Each time the component appears, it is mounted, so it is re-drawn but I want to avoid the redrawing, doing some kind of caching of the chart since it takes quite a bit of time to draw the chart with many datapoints. I am calling createScatterChart in componentDidMount:
createScatterChart() {
  const node = this.node
  nv.utils.symbolMap.set('thin-x', function(size) {
    size = Math.sqrt(size);
    return 'M' + (-size/2) + ',' + (-size/2) +
            'l' + size + ',' + size +
            'm0,' + -(size) +
            'l' + (-size) + ',' + size;
  });
// create the chart
  var chart;
  nv.addGraph(function() {
    chart = nv.models.scatterChart()
        .showDistX(true)
        .showDistY(true)
        .useVoronoi(true)
        .color(d3.scale.category10().range())
        .duration(300)
    ;
    var data_func = () => this.props.datum;
    var data_obj = data_func();
    var that = this;
    chart.tooltip.contentGenerator(function (d) {
      //var html = "
";
      var html = "";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
              that.showBarChart(elem.key);
              html += "
cluster " + elem.key + "
";
              /*var expr = outer_obj["values"][0]["expr"];
              html += "
" + elem.key + "
";
              html += "
x = " + d.value + ", y = " + elem.value + "
";*/
          }
        });
      })
      //html += "
";
      return html;
    });

    chart.dispatch.on('renderEnd', function(){
        console.log('render complete');
    });

    chart.xAxis.tickFormat(d3.format('.02f'));
    chart.yAxis.tickFormat(d3.format('.02f'));

    d3.select(node)
        .datum(data_func)
        .call(chart);

    nv.utils.windowResize(chart.update);
    chart.dispatch.on('stateChange', function(e) { ('New State:', JSON.stringify(e)); });
    return chart;
}.bind(this));
}

The function ultimately returns chart, so could I somehow save it in a variable and then draw it much faster? Or what would you recommend for such caching of the chart?

A: The problem can be resolved by changing visible attribute of the html element instead of rendering it.


text:
Q: Активировать PUT DELETE методы в WebAPI ASP.Net Core Столкнулся с такой проблемой. Имею контроллер
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
    [HttpGet("[action]/")]
    public async Task<IActionResult> GetAll()
    {
        return Ok(await _employeeService.GetAllEmployees());
    }
    [HttpDelete("[action]/{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        await _employeeService.DeleteEmployee(id);
        return Ok();
    }
}

Через Swagger всё замечательно работает, все запросы выполняются. А вот если ввести строку запроса напрямую, в моём случае: https://localhost:7080/Employee/Delete/3, то возвращает 405. Почитал в инете, встретил похожую ситуацию, только уже с задеплоиными API, а у меня даже на локал хосте не работает. Что мог упустить?
Вызываю в TypeScript вот таким вот образом:
async function deleteById(url: string, id: number) {
    return await fetch(url + id.toString(), { method: 'DELETE', }).then((response) => {
        if (!response.ok)
            console.log(response);
        else
            return response.json();
    });
}
deleteById("https://localhost:7080/Employee/Delete/", id).then((json) => {
        console.log(json);
    });

И получаю вот такое...


text:
Q: Is there a way to get a list of all the words in the solr spellcheck index? I'm using Solr's SpellCheckComponent with IndexBasedSpellChecker.  Wondering if there's a way to get an output of all the words in the dictionary.
Might help us catch some of the misspellings on our site.

A: yes, there is. IndexBasedSpellChecker, according to the doc: "The IndexBasedSpellChecker uses a Solr index as the basis for a parallel index used for spell checking. It requires defining a field as the basis for the index terms "
So it just uses one field you choose from the index. To enumerate all terms on a field you use the Terms component and you set terms.fl to that field. If you have lots of terms, you could play do some scrolling with terms.lower, terms.limit and terms.upper to get the info in multiple calls.


text:
Q: Getting geodetic area from rgeos::gArea? I need to get an area of different polygons at continental scale (like third of Africa etc.). Usual functions like rgeos::gArea work only in the projection units.

*

*Is there any function which works correctly in real square meters on the geoid surface? I.e. real, geodetic area?

*If not, what projection should I use to get the least distortion?

I need to measure 6 really huge areas (like third of Africa), so UTM or national projections are out of question.
Can I use a single one projection that has minimal distortion area-wise across the whole Africa?
Right now I am thinking of Mercator projection used by google maps (EPSG:3857), but I am not really sure.

A: Geodetic area calculations are not part of GDAL. You would probably need to write your own function to do it and exact solutions are computationally intensive.
You're better off using an Equal-Area projection, such as Albers, Azimuthal, or Lambert azimuthal (https://en.wikipedia.org/wiki/Category:Equal-area_projections). For largish regions in Africa, you're best bet is probably the lambert azimuthal equal area (Check with table partway down page: http://www.geo.hunter.cuny.edu/~jochen/gtech201/lectures/lec6concepts/map%20coordinate%20systems/how%20to%20choose%20a%20projection.htm)


text:
Q: Unable to show text on mouse over of SVG I am trying to show only text whenever the user hover on svg element(a rectangle in my case) either with CSS or JS.

 <svg width="400" height="180">
  <rect x="50" y="20" width="150" height="150"
  style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9" />
  <text class="img__description" x="50" y="100" font-family="Verdana" font-size="35" fill="blue">Hello</text>
</svg>

I would appreciate any help.

A: You can add css styles to the elements of the svg, e.g. display: none.
Working example:

svg:hover rect {
    display: none;
}

svg text {
    display: none;
}

svg:hover text {
    display: block;
}
<svg width="400" height="180">
  <rect x="50" y="20" width="150" height="150"
    style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9"
  />
  <text class="img__description" x="50" y="100" font-family="Verdana" font-size="35" fill="blue">Hello</text>
</svg>


text:
Q: Determine the number of functions $f: \{1,2,3....,1999\}\to \{2000,2001,2002,2003\}$satisfying the condition that $f(1)+f(2)+...f(1999)$ is odd. Problems:Determine the number of functions $$f: \{1,2,3....,1999\}\to \{2000,2001,2002,2003\}$$ satisfying the condition that $f(1)+f(2)+...f(1999)$ is odd.
My Attempt: Each integer in domain has $4$ choices and therefore the total number of functions is $f$ is $4^{1999}.$ Since there are an equal number of functions that yield odd or even result, we can directly write that the number of functions satisfying the above condition to be $2*4^{1998}.$ I am unsure about this last claim and would like to prove it (if it is true.)Also is the answer to this problem correct?
Edit $1$: I tried to proceed further in the following manner:
For a given mapping $f$ let the number of integers assigned to $2000,2001,2002$ amd $2003$ be $p,q,r$ and $s$ respectively, where $p,q,r,s\in \mathbb{Z}^+$. Therefore the sum in question can be written as $f(1)+f(2)+...+f(1999)=2000p+2001q+2002r+2003s.$ Clearly the sum will be odd iff $q+s$  is odd. Also note that $p+q+r+s=1999\Rightarrow p+r$ is even. On the other hand if we let $q+s$ as even then $p+r$ must be even. Now the number of values of $p,q,r$ and $s$ for which the above two lemmas hold is the same and therefore if we let $f$ to be the function which maps elements form $\{1,2,3,...,1999\}$ to $\{2000,2001,2002,2003\}$ such that $q+s$ is even and $g$ to be the function  hich maps elements form $\{1,2,3,...,1999\}$ to $\{2000,2001,2002,2003\}$ such that $p+q$ is even we will get a bijection.(Maybe!)

A: Your result is correct.  To justify the result, you can say that you have $4^{1998}$ choices of where to send the first $1998$ numbers.  For each of them, there will be two complete functions that have odd sum, because if the sum of the first $1998$ values is odd, you can choose $2000$ or $2002$ for $f(1999)$ while if the sum of the first $1998$ values is even, you can choose $2001$ or $2003$ to get an odd sum, so there will be $2 \cdot 4^{1998}$ functions with odd sum.
To specifically justify the claim that half the functions have odd sum and half have even sum,  pair up two functions that agree on the first $1998$ values, one with $f(1999)=2000$ and the other with $f(1999)=2001$  One of these will have even sum and one will have odd sum.  Do the same with the other two values for $f(1999)$.  You have shown a bijection between the set of functions that have even sum and the set of functions that have odd sum, so they must have the same number of members.

A: Take an arbitrary image of $f(k)$ for $k\in\{1,\ldots,1998\}$ so you have for each $k$ a value from $2001$ to $2003$ and so you have $4^{1998}$ choices. Now for $f(1999)$ and since the sum would be odd, we have only two choices: so the desired number is $2\times 4^{1998}$

A: The amount of elements mapped to $2001$ or $2003$ should be odd.
For each odd amount of $n$ elements chosen from $[1,1999]$:

*

*The number of ways to map these elements to $2001$ or $2003$ is $2^n$

*The number of ways to map the remaining $1999-n$ elements to $2000$ or $2002$ is $2^{1999-n}$

The answer is therefore:
$\sum\limits_{k=0}^{999}\binom{1999}{2k+1}\cdot2^{2k+1}\cdot2^{1999-(2k+1)}=$
$\sum\limits_{k=0}^{999}\binom{1999}{2k+1}\cdot2^{1999}=$
$2^{1999}\cdot\sum\limits_{k=0}^{999}\binom{1999}{2k+1}=$
$2^{1999}\cdot2^{1998}=$
$2^{3997}$

A: I did this one probably in a dumb way since i didn't see that the number of odd results is the same as the even one, but here we go:
The total number of such functions is $4^{1999}$
The number of sets that contain an even number of odd $f(x)$'s is:
$$
\sum\limits_{k=0}^{999}\binom{1999}{2k}\cdot2^{2k}\cdot2^{1999-2k}
$$
Where the term $2^{2k}\cdot2^{1999-2k}$ comes from the fact that there are 2 possible choices for even and odd numbers (this was kind of a trick since $2^{(2k)+(1999-2k)}=2^{1999}$, which is constant). Since we have 2 possibilities for both even and odd, namely {$2000,2002$} and {$2001,2003$} respectively, this is exactly half of:
$$
\sum\limits_{j=0}^{1999}\binom{1999}{j}\cdot2^{j}\cdot2^{1999-j}= 4^{1999}
$$
Half of it being  (and this is where my mental autopilot went off and I realized my stupidity):
$$
2*4^{1998}
$$
Hence we finally have:
$$
4^{1999}-2*4^{1998}=2*4^{1998}
$$


text:
Q: Using a query result to set table of next query I have the following query that returns the min, max and user total of basically unique rows
in two different tables.
select sum(user_count) as user_count_sum, sum(min_count) as min_count_sum,
sum(max_count) as max_count_sum
from(
select max(case when di = 'i' then di_count end) as user_count,
       min(di_count) as min_count,
       max(di_count) as max_count
from (
    select di,
           count(distinct rt) as di_count
    from gpstablev2
    where rt >  GETDATE() - '1 day'::INTERVAL
    group by di
)
UNION
select max(case when di = 'i' then di_count end) as user_count,
       min(di_count) as min_count,
       max(di_count) as max_count
from (
    select di,
           count(distinct rt) as di_count
    from powertablev2
    where rt >  GETDATE() - '1 day'::INTERVAL
    group by di
)
)

Now I also have a master table, that if I were to run the following query would return the following
select table from mastertable;

gpstablev2
powertablev2
...(more table names)

Instead of pasting 9 more UNION blocks like the one I have to sum all the tables listed in mastertable, is there a way I can use a query to mastertable to clean this up?
If I were doing this in java I would have first get my ResultSet from master table and then do 10 queries and UNION them myself. But I rather have my database do ALL the processing, and be able to update based on the contents of mastertable.
EDIT:
Based on feedback I am trying a Dynamic Query and have gotten this far, but am still have trouble putting together the rest of the pieces
CREATE OR REPLACE FUNCTION get_sums()
RETURNS TABLE(user_count_sum bigint, min_count_sum bigint, max_count_sum bigint)
$BODY$
BEGIN

RETURN QUERY EXECUTE "
SELECT $$SELECT sum(user_count) AS user_count_sum
      ,sum(min_count) AS min_count_sum
      ,sum(max_count) AS max_count_sum
FROM  (
   SELECT max(case when di = 'id' then di_count end) AS user_count
         ,min(di_count) AS min_count
         ,max(di_count) AS max_count
   FROM  ($$
||
string_agg(format($$
      (SELECT di, count(distinct rt) AS di_count
       FROM   %I
       WHERE  rt >  now() - interval '1 day'
       GROUP  BY 1)$$, tbl)
      ,'

      UNION ALL')
|| '
      ) sub1
   ) sub2'
FROM   mastertable;
INTO results_var"

END;
$BODY$
LANGUAGE plpqsql;

A: You need dynamic SQL for that. SQL does not accept the dynamic conversion of literals / values to identifiers. So you need to build the query first and then execute it. You can do this in your client (seems to be Java), or do it all inside Postgres, which is generally fastest:
SELECT $$SELECT sum(user_count) AS user_count_sum
      ,sum(min_count)  AS min_count_sum
      ,sum(max_count)  AS max_count_sum
FROM  (
   ($$
||
string_agg(format($$
   SELECT max(case when di = 'i' then di_count end) AS user_count
         ,min(di_count) AS min_count
         ,max(di_count) AS max_count
   FROM  (
      SELECT di, count(distinct rt) AS di_count
      FROM   %I
      WHERE  rt >  now() - interval '1 day'
      GROUP  BY 1
      ) t
   )$$, tbl)
      ,'

   UNION ALL
   (')
|| '
   ) sub'
FROM   mastertable;

Produces the query-string:
SELECT sum(user_count) AS user_count_sum
      ,sum(min_count)  AS min_count_sum
      ,sum(max_count)  AS max_count_sum
FROM  (
   (
   SELECT max(case when di = 'i' then di_count end) AS user_count
         ,min(di_count) AS min_count
         ,max(di_count) AS max_count
   FROM  (
      SELECT di, count(distinct rt) AS di_count
      FROM   gpstablev2
      WHERE  rt >  now() - interval '1 day'
      GROUP  BY 1
      ) t
   )

   UNION ALL
   (
   SELECT max(case when di = 'i' then di_count end) AS user_count
         ,min(di_count) AS min_count
         ,max(di_count) AS max_count
   FROM  (
      SELECT di, count(distinct rt) AS di_count
      FROM   powertablev2
      WHERE  rt >  now() - interval '1 day'
      GROUP  BY 1
      ) t
   )

   UNION ALL
   ...

   ) sub;

*

*GETDATE() is not a valid Postgres function. You probably mean now() or CURRENT_DATE .. depending on the undisclosed type of rt. I use now() instead.

*You most probably want to use UNION ALL instead of UNION here.

*Also fixed missing aliases for subqueries and made some minor simplifications.
Wrap this into a plpgsql function with EXECUTE. There are plenty of closely related examples here on SO with code and links and explanation ...


text:
Q: A case when $I \otimes_R M$ and $ IM$ are locally isomorphic at minimal primes? Let $(R,\mathfrak m)$ be a local Cohen--Macaulay ring of dimension $1$. Let $M$ be a finitely generated $R$-module of depth $1$. Let $I$ be an ideal of $R$ of height $1$.
Then my question is: Is it true that $I_P \otimes M_P \cong (IM)_P$ for every minimal prime ideal $P$ of $R$?
Of-course there is always a natural surjection $I \otimes_R M \to IM$ sending $x \otimes m\to xm$, but I am unable to see if this also becomes injective when localising at minimal primes.
Please help.

A: As $R$ is Cohen-Macaulay, the set of minimal and associated primes are equal. Also, since $R$ is Cohen-Macaulay, the height of an ideal is equal to the grade.
Let $P$ be a minimal prime and $I$ a height 1 ideal. Since the grade of $I$ is $1$, $I \not\subset P$. Thus, $I_P \cong R_P$. This is sufficient to deduce the isomorphism
$$
I_P \otimes_{R_P} M_P \cong R_P \otimes_{R_P} M_P \cong M_P
$$
and $(IM)_P \cong I_P M_P \cong R_P M_P \cong M_P$.
If you prefer keeping track of the surjective map in your post and familiar with the Tor functor, one can show that $\operatorname{Tor}_1^R (R/I,M)$ becomes zero after localizing at a minimal prime $P$, since $(R/I)_P =0$.


text:
Q: Trigger a task when another finished with success My use-case is as follows:

*

*Task A is generating dataset using some input raw data

*Task B is running some code using dataset as input

*Task C is running some other code using dataset as input

The three tasks are scheduled to run daily, and Task B and Task C are scheduled to run enough time after Task A, and simply fail if the input dataset has not been generated for some reason.
As a first improvement I added an ExternalTaskSensor in both Task B and Task C, but this just avoids to run them if Task A did not yet finished or failed.
However, ExternalTaskSensor seems not to be working fine with backfilling (it is pretty fragile as it relies on execution date only, plus if Task A is run again, Task B and Task C won't know).
Solution 1 (not applicable):
I have seen this SO's question: In airflow, is there a good way to call another dag's task?
This is not ideal for me because I'd like to keep Task A unaware of the dependent tasks, and handle the logic in Task B and Task C (or externally). Reason is that other tasks consuming the output of Task A will be added in the future (from different teams across the organization), and it's not desirable to update Task A each time.
Summary
I'd like to trigger Task B and Task C if and only if Task A has been executed with success (independently if it has been scheduled or triggered manually), without modifying Task A to achieve that.

A: To suit your scenario, the only concept I can think of is SubDags. (Refer to WARNING before you implement)
SubDagOperator allows you to attach a set of tasks to your task A. Refer to code below.
dag = DAG('parent_dag', description='Parent',
          schedule_interval='@daily',
          start_date=datetime.now())

task_a = DummyOperator(dag=dag, task_id='task_a')

subdag_task = SubDag(task_id='load_tasks',
    subdag=load_subdag('parent_dag', 'dependent_tasks'),
    dag=dag)

task_a >> subdag_task

Now in a separate file you define your load_subdag function.
def load_subdag(parent_dag_name, child_dag_name):
    dag_subdag = DAG(
        dag_id='{0}.{1}'.format(parent_dag_name, child_dag_name),
        schedule_interval="@daily",
    )
    with dag_subdag:
        task_b = DummyOperator(
            task_id='load_subdag_task_b',
            dag=dag_subdag)

       task_c = DummyOperator(
            task_id='load_subdag_task_c',
            dag=dag_subdag)

    return dag_subdag

WARNING (In Red and bold): SubDag tasks occupy slots in your worker like maggots. Please understand the caveats completely before you jump into this. AIRFLOW-74 gives a picture of how bad it can be. It is outright rejected by many developers for the same reason.


text:
Q: dividing the sum of two value in each group in a number format using rtf I try to divide the sum of two value in each group and then I got the result. Now I want the result to in a number format '#,##0.00' but I got an error 'XML-22047: (Error) Invalid instantiation of 'xsl:when' in '_h' context.' How can I do that? Please see my code below, it's working if I remove the xdofx:format_number.
<?xdoxslt:set_variable($_XDOCTX, 'a', sum(current-group()/OR_AMOUNT))?>
<?xdoxslt:set_variable($_XDOCTX, 'b', sum(current-group()/WT_TOTAL))?>

<?xdofx:format_number(<?choose:?><?when: sum(current-group()/OR_AMOUNT)=0?>0<?end when?><?when: sum(current-group()/OR_AMOUNT)>0?><?xdofx: format_number(xdoxslt: get_variable($_XDOCTX,'b') div xdoxslt:get_variable($_XDOCTX,'a'),'#,##0.00','EURO')?><?end when?><?otherwise:?>0<?end otherwise?><?end choose?>

Thanks,
Lawrence

A: <?xdofx:format_number(
    <?choose:?>
        <?when: sum(current-group()/OR_AMOUNT)=0?>
            0
        <?end when?>
        <?when: sum(current-group()/OR_AMOUNT)>0?>
             <?xdofx: format_number(xdoxslt: get_variable($_XDOCTX,'b') div xdoxslt:get_variable($_XDOCTX,'a'),'#,##0.00','EURO')?>
        <?end when?>
        <?otherwise:?>
            0
        <?end otherwise?>
    <?end choose?>

The first part <?xdofx:format_number( opens a bracket ( and an element <?. Both are never closed. This is incorrect syntax. You also can't open an element and then open a new element before closing the first one. <?a <?b?> ?> is incorrect.
It is unclear why you need the first format_number function anyway. You are formatting the value when OR_AMOUNT)>0 and in the other cases you have a hardcoded 0. What are you trying to format?
This will work:
<?choose:?>
    <?when: sum(current-group()/OR_AMOUNT)=0?>
        0
    <?end when?>
    <?when: sum(current-group()/OR_AMOUNT)>0?>
       <?xdofx: format_number(xdoxslt: get_variable($_XDOCTX,'b') div xdoxslt:get_variable($_XDOCTX,'a'),'#,##0.00','EURO')?>
    <?end when?>
    <?otherwise:?>
        0
    <?end otherwise?>
<?end choose?>

Or if you really want the mask on the hardcoded 0's:
<?choose:?>
    <?when: sum(current-group()/OR_AMOUNT)=0?>
        <?xdofx: format_number(0,'#,##0.00','EURO')?>
    <?end when?>
    <?when: sum(current-group()/OR_AMOUNT)>0?>
        <?xdofx: format_number(xdoxslt: get_variable($_XDOCTX,'b') div xdoxslt:get_variable($_XDOCTX,'a'),'#,##0.00','EURO')?>
    <?end when?>
    <?otherwise:?>
        <?xdofx: format_number(0,'#,##0.00','EURO')?>
    <?end otherwise?>
<?end choose?>


text:
Q: ZIP files created with GUI have more bytes than ZIP files created in a shell I created two ZIP files of the same directory. One with the GUI, the other with:
$ zip -r alpha_cmd.zip Alpha

The Alpha directory is 33.640 MB with 164 items.
The ZIP file created by the GUI is 2,100 bytes larger than the ZIP file created on the command line.
Why is the ZIP file created with the GUI larger?
Note: Even though the ZIP files have different sizes, when unzipped, each's directory has the exact same number of bytes. Basically, I'm very wary of possible inconsistencies introduced by managing my file system with the GUI and with shell commands.

A: Even apart from the main cause in this case (Finder adding extra hidden stuff, as empedocle says), different sizes for ZIPs of the same data doesn't indicate a problem, when the size difference is a fraction of a percent.
Different ZIP implementations might have a different default compression level (tradeoff between CPU time and size saved), or just have different code that saves more or fewer matches, saving more or fewer bytes at the default compression level.
For example, 7-Zip usually makes smaller .zip files than other ZIP programs. (And no, I'm not talking about its own .7z file format. It has a better plain-ZIP compressor, too.)
zipcmp is a cmdline program that can compare ZIP files. It defaults to comparing just the ZIP directory, to check that all files are the same name, size, and CRC. If this is the case, both ZIP files are almost certain to have the same contents, but just compressed differently (if the compressed size differs.) As long as the ZIP files aren't damaged, of course. Use unzip -t foo.zip to test a ZIP file for decompression errors, non-matching CRCs, etc.

A: Zipping from the Finder adds a folder __MACOSX, invisible on Macs, that contains OS X resource forks like custom icons and such. From Wikipedia:

The resource fork is a fork or section of a file on the Apple Mac OS operating system used to store structured data along with the unstructured data stored within the data fork. A resource fork stores information in a specific form, containing details such as icon bitmaps, the shapes of windows, definitions of menus and their contents, and application code (machine code). For example, a word processing file might store its text in the data fork, while storing any embedded images in the same file's resource fork. The resource fork is used mostly by executables, but every file is able to have a resource fork.


text:
Q: Using ios google sign in api - what are those two values? I'm looking at the sample AppDelegate.swift file from Google stored on their git hub: https://github.com/googlesamples/google-services/blob/c2830d8413097c79117a0f9519e9af14aaeb4587/ios/signin/SignInExampleSwift/AppDelegate.swift
and there is this method:
  @available(iOS 9.0, *)
  func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
      sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as! String?,
      annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
  }

can you tell me what exactly is the UIApplicationOpenURLOptionsAnnotationKey and UIApplicationOpenURLOptionsSourceApplicationKey?

A: These are the key for extracting source annotation & source application.
UIApplicationOpenURLOptionsAnnotationKey - source annotation
UIApplicationOpenURLOptionsSourceApplicationKey- source application
Earlier we get this values ready made from the method parameters.Now in iOS 9 we need to fetch it explicitly.


text:
Q: PHP: Grouping array values by keys I have three array like this:
array1(
   0=>'title 1',
   1=>'title 2'
)

array2(
   0=>'description 1',
   1=>'description 2'
)

array3(
   0=>'price 1',
   1=>'price 2'
)

There is a php function to grouping array values by keys like this?
array(
   0=>array(title 1, description 1, price 1),
   1=>array(title 2, description 2, price 2),
)

A: array_map(null, $array1, $array2, $array3)

See http://php.net/manual/en/function.array-map.php example #4.

A: Try this code.
$array3 = array();
foreach ( $array1 as $key => $val ) {
    if ( !isset($array3[$val]) )
        $array3[$val] = array();

    $array3[$val][] = $array2[$key];
}

print_r($array3);

A: $pool =array();
foreach ( array_map(null, $array1, $array2, $array3) as $key => $value) {
    $pool[$key] = implode(", ", $value);
}
print_r($pool);

Result :
Array
(
    [0] => title 1, description 1, price 1
    [1] => title 2, description 2, price 2
)


text:
Q: Google Drive Android SDK: where to start from? I have been looking all day at the Google Drive SDK for Android,
but I am a bit confused.
I need to make the list of folders and files in the user Google Drive account.
I thought that was a simple, basic standard feature, but maybe not...
Please can you help me?

A: You have two possible ways to go:

*

*use RESTful API, or

*use Google Drive Android Api (GDAA)
I would say the former would be easier to start with.

*

*If you decide to go with the REST, you may use the GitHub demo here, that has both the REST and the GDAA 'CRUD' implementations (you just comment out the one you don't need). It also has some code to deal with the authentication / authorization which you need to do anything on Google Drive. See SO 28439129.

*In case you decide to use GDAA, (you still have to get the authorization done), the 'official' to get you started demos are here and here.

You will definitely run into a lot of roadblocks and the solutions are mostly found here under the tag 'google-drive-android-api'.
Good Luck.


text:
Q: NSTextView highlight selected text attachments (Images and Movies) like in Apple's Notes I have an NSTextView, that can drag & drop images and pdf's. mov and mp4 can only be dragged in, but not out, because they can't be selected only played back. I like to have the same functionality as in Apple's Notes App. There images and video (mov, mp4) can be selected and dragged in and out.
I spend a lot of time searching the internet to get a proper solution, but can't find one.
As I select a image, only the glyph is highlighted on the left side. Not the whole frame.
Here is a screenshot of Apple's Notes App, where images and movies can be selected and dragged in and out.
Selected image and video in Apple's Notes App
Here my custom textViewController class
//
//  RKTextViewController.h
//  RKon_OSX
//
//  Created by Robert Kyriakis on 23.10.20.
//  Copyright ©2020 RKon.eu. All rights reserved.
//

#import <Cocoa/Cocoa.h>

#import "RKTextView.h"

/*
 By double clicking a text attachment from the textView, the file is openend in Preview App.
 Making this work whitout errors the preview file must be copied to a location on the file system and exists there till the app terminates.
 Here it's copied to the app documents path within the directory /Documents/Previews/
 You must delete the 'Previews' directory either by lauching or terminating the app to clean it!
 */

@class RKTextViewController;

@protocol RKTextViewDelegate <NSObject>

@required
- (NSFont*)fontForTextView:(NSTextView*)textView;
- (NSColor*)textColorForTextView:(NSTextView*)textView;
- (NSColor*)placeholderTextColorForTextView:(NSTextView*)textView;
- (NSString*)placeholderStringForTextView:(NSTextView*)textView;

@optional
- (void)textDidBeginEditing:(NSTextView*)textView;
- (void)textDidEndEditing:(NSTextView*)textView;

@end

@interface RKTextViewController : NSViewController

@property (nonatomic, strong) IBOutlet RKTextView *textView;
@property (nonatomic, strong) IBOutlet NSProgressIndicator *progressIndicator;

@property BOOL contentHasChanged;
@property id <RKTextViewDelegate> rkTextViewDelegate;

- (void)updateTextViewWithTextStorage:(NSTextStorage*)textStorage;

@end

//
//  RKTextViewController.m
//  RKon_OSX
//
//  Created by Robert Kyriakis on 23.10.20.
//  Copyright ©2020 RKon.eu. All rights reserved.
//

#import <RKon_OSX/RKon_OSX.h>

#import "RKTextViewController.h"

@interface RKTextViewController () <NSTextViewDelegate>

@property (nonatomic, strong) NSFont *textViewFont;
@property (nonatomic, strong) NSColor *textColor;
@property (nonatomic, strong) NSColor *placeholderTextColor;
@property (nonatomic, strong) NSString *placeholderString;

@end

@implementation RKTextViewController

- (void)awakeFromNib
{
    [self initProperties];
}

#pragma mark - Extensions
- (void)initProperties
{
    dispatch_async(dispatch_get_main_queue(), ^{

        self.textView.delegate = self;

        // this property must be set to determine, when dragging into the textView
        // makes changes and the boolean contentHasChanged here can be set
        self.textView.rkTextViewController = self;

        if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(fontForTextView:)]) {
            self.textViewFont = [self.rkTextViewDelegate fontForTextView:self.textView];
            self.textView.font = self->_textViewFont;
        }

        if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(textColorForTextView:)]) {
            self.textColor = [self.rkTextViewDelegate textColorForTextView:self.textView];
        }

        if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(placeholderTextColorForTextView:)]) {
            self.placeholderTextColor = [self.rkTextViewDelegate placeholderTextColorForTextView:self.textView];
            self.textView.textColor = self->_placeholderTextColor;
        }

        if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(placeholderStringForTextView:)]) {
            self.placeholderString = [self.rkTextViewDelegate placeholderStringForTextView:self.textView];
            self.textView.string = self->_placeholderString;
        }

        self.textView.allowsUndo = YES;
        self.textView.selectable = YES;

        self.textView.richText = YES;
        self.textView.importsGraphics = YES;
        self.textView.allowsImageEditing = YES;

        self.textView.automaticLinkDetectionEnabled = YES;
        self.textView.automaticDataDetectionEnabled = YES;

        self.textView.smartInsertDeleteEnabled = YES;

        // automitically scale larger images or other content to fit in the textView
        self.textView.layoutManager.defaultAttachmentScaling = NSImageScaleProportionallyDown;
        self.textView.layoutManager.allowsNonContiguousLayout = YES;

        self.contentHasChanged = NO;

        [RKLogger logDebugInfoFromObject:self withSelector:_cmd log:@"contentHasChanged = NO"];

        // register video pboard types
        // videos are not allowed jet. They can be dropped, but not dragged out of the textView
//        NSString *movPboardType = NSCreateFileContentsPboardType(@"mov");
//        NSString *mp4PboardType = NSCreateFileContentsPboardType(@"mp4");

//        [self.textView registerForDraggedTypes:@[NSFilenamesPboardType,movPboardType,mp4PboardType]];
    });

}

- (void)updateTextViewWithTextStorage:(NSTextStorage*)textStorage
{
    [_progressIndicator startAnimation:self];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSTextStorage *newTextStorage;
        NSData *textStorageData;
        NSAttributedString *attributedString;

        if (textStorage) {
            // check the data of the textStorage,
            // because the storage can have only glyphs with attachments
            textStorageData = [NSKeyedArchiver archivedDataWithRootObject:textStorage];
            attributedString = [NSKeyedUnarchiver unarchiveObjectWithData:textStorageData];

            // first manage the textStorage, with default font and text color
            if (attributedString && (attributedString.length > 0)) {
                newTextStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
            } else {
                newTextStorage = [[NSTextStorage alloc] initWithString:self->_placeholderString];
            }
        } else {
            // textStorage is Nil
            // return only placeholder string
            newTextStorage = [[NSTextStorage alloc] initWithString:self->_placeholderString];
        }

        [self.textView.layoutManager replaceTextStorage:newTextStorage];

        // Important textColor and font must be set after
        // the textStorage is replaced in the noteTextView to have an effect

        self.textView.font = self->_textViewFont;

        if (attributedString && (attributedString.length > 0)) {
            self.textView.textColor = self->_textColor;
        } else {
            self.textView.textColor = self->_placeholderTextColor;
        }

        // TextView must be redrawn in the case of large attributes
        // to take effect with delay on main runloop
        [self performSelector:@selector(refreshTextView) withObject:Nil afterDelay:0.02];
    });
}

- (void)refreshTextView
{
    dispatch_async(dispatch_get_main_queue(), ^{

        NSRect rect = self.textView.bounds;

        [self.textView setNeedsDisplayInRect:rect
                       avoidAdditionalLayout:YES];

        [self.progressIndicator stopAnimation:self];

    });

}

#pragma mark - NSTextViewDelegate methods
- (BOOL)textShouldBeginEditing:(NSText*)textObject
{
    dispatch_async(dispatch_get_main_queue(), ^{

        // while editing the note text set always the text color
        // some times it chanes after drop of images
        textObject.textColor = self->_textColor;
        textObject.font = self->_textViewFont;

    });

    return YES;

}

- (void)textDidBeginEditing:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{

        NSTextView *textView = (NSTextView*)notification.object;

        // while editing the note text set always the text color
        // some times it chanes after drop of images
        textView.textColor = self->_textColor;
        textView.font = self->_textViewFont;

        if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(textDidBeginEditing:)]) {
            [self.rkTextViewDelegate textDidBeginEditing:textView];
        }

// removing placeholderstring when typing the first
// character doesn't work, when an object is dropped into the textView first
/*
        // remove placeholder string, when it's at the begining
        NSString *string = textView.textStorage.string;

        NSRange placeholderStringRange = [string rangeOfString:self->_placeholderString options:NSCaseInsensitiveSearch];

        if ((placeholderStringRange.location == 0) && (placeholderStringRange.length == self->_placeholderString.length)) {
            textView.string = [textView.string stringByReplacingOccurrencesOfString:self->_placeholderString withString:@""];
        }
*/
    });

}

- (void)textDidEndEditing:(NSNotification *)notification
{
    NSTextView *textView = (NSTextView*)notification.object;

    if (self.rkTextViewDelegate && [self.rkTextViewDelegate respondsToSelector:@selector(textDidBeginEditing:)]) {
        [self.rkTextViewDelegate textDidEndEditing:textView];
    }

    _contentHasChanged = YES;

    [RKLogger logDebugInfoFromObject:self withSelector:_cmd log:@"contentHasChanged = YES"];

}

#pragma mark - drag & drop
- (void)textView:(NSTextView*)view
     draggedCell:(id<NSTextAttachmentCell>)cell
          inRect:(NSRect)rect
           event:(NSEvent*)event
         atIndex:(NSUInteger)charIndex;
{
    [RKLogger logDebugInfoFromObject:Nil withSelector:_cmd log:Nil];

    NSTextAttachment *textAttachment = cell.attachment;
//    NSString *fileType = textAttachment.fileType;
    NSFileWrapper *fileWrapper = textAttachment.fileWrapper;

    NSURL *documentsURL = [RKFileManager userApplicationDocumentsURL];
    NSURL *fileURL = [documentsURL URLByAppendingPathComponent:fileWrapper.preferredFilename];

    // because the method after need a file at path
    // first write the fileWrapper to an URL
    NSError *error;
    [fileWrapper writeToURL:fileURL
                    options:NSFileWrapperWritingAtomic
        originalContentsURL:Nil
                      error:&error];

    if (!error) {
        [view dragFile:fileURL.path
              fromRect:rect
             slideBack:YES
                 event:event];

        // now the file at app docuemnts path is no longer neccesary
        // and can be deleted
        [[NSFileManager defaultManager] removeItemAtPath:fileURL.path
                                                   error:&error];
    }

    if (error) {
        [RKError showRKAlertWithError:error completion:^{
        }];
    }

//     This is not working, only the attributed string with pblic.rtf pboard is dragged
//     NSTextAttachment *textAttachment = cell.attachment;
//     NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment:textAttachment];

//     NSDraggingItem *draggingItem = [[NSDraggingItem alloc] initWithPasteboardWriter:attributedString];
//     draggingItem.draggingFrame = rect;

//     [self.textView beginDraggingSessionWithItems:@[draggingItem]
//     event:event
//     source:self.textView];

}

@end

Here my custom textView class
//
//  RKTextView.h
//  RKon_OSX
//
//  Created by Robert Kyriakis on 26.10.20.
//  Copyright ©2020 RKon.eu. All rights reserved.
//

#import <Cocoa/Cocoa.h>

#import "RKTextViewController.h"

@class RKTextViewController;

/*
 By double clicking a text attachment from the textView, the file is openend in Preview App.
 Making this work whitout errors the preview file must be copied to a location on the file system and exists there till the app terminates.
 Here it's copied to the app documents path within the directory /Documents/Previews/
 You must delete the 'Previews' directory either by lauching or terminating the app to clean it!
 */

@interface RKTextView : NSTextView

@property (nonatomic, strong) RKTextViewController *rkTextViewController;

@end

//
//  RKTextView.m
//  RKon_OSX
//
//  Created by Robert Kyriakis on 26.10.20.
//  Copyright ©2020 RKon.eu. All rights reserved.
//

#import <RKon_OSX/RKon_OSX.h>

#import "RKTextView.h"

@interface RKTextView ()

//@property NSPoint dropPoint;

@end

@implementation RKTextView

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.
}

- (void)mouseDown:(NSEvent*)event
{
    if (event.clickCount == 2) {
        // doubleClikk detected
        // get fileWrapper of the attributedString at mouse point
        NSPoint doubleClickPoint = [self convertPoint:[event locationInWindow]
                                             fromView:nil];

        NSUInteger attribIndex = [self characterIndexForInsertionAtPoint:doubleClickPoint];

        // get the attributes at index
        NSDictionary <NSAttributedStringKey, id> *attributesDict = [self.textStorage attributesAtIndex:attribIndex effectiveRange:Nil];

        // set the attachment, if exists
        NSTextAttachment *attachment = [attributesDict valueForKey:NSAttachmentAttributeName];

        // check, if an attachment exists
        if (attachment) {
            // there is an attachment with a fileWrapper
            NSFileWrapper *fileWrapper = attachment.fileWrapper;

            // bevor oppening the file in an app it has to be stored at a path.
            // It can't be deleted from this path, while an application like Preview want's to save it later!!
            // You must delete all files from that folder when lounging the app.
            NSURL *documentsURL = [RKFileManager userApplicationDocumentsURL];
            NSURL *docPreviewsURL = [documentsURL URLByAppendingPathComponent:@"Previews"];

            // check, if previews path exists
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSError *error;
            BOOL isDirectory;

            if (![fileManager fileExistsAtPath:docPreviewsURL.path isDirectory:&isDirectory]) {
                // not exists -> create it
                [fileManager createDirectoryAtPath:docPreviewsURL.path
                       withIntermediateDirectories:NO
                                        attributes:Nil
                                             error:&error];

                if (error) {
                    [RKError showRKAlertWithError:error completion:^{
                    }];
                    return;
                }
            }

            NSURL *fileURL = [docPreviewsURL URLByAppendingPathComponent:fileWrapper.preferredFilename];

            // because the method after need a file at path
            // first write the fileWrapper to an URL
            [fileWrapper writeToURL:fileURL
                            options:NSFileWrapperWritingAtomic
                originalContentsURL:Nil
                              error:&error];

            if (!error) {

                // open attachment with preview app
                NSString *previewAppPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"Preview"];
                [[NSWorkspace sharedWorkspace] openFile:fileURL.path withApplication:previewAppPath];
            }

            if (error) {
                [RKError showRKAlertWithError:error completion:^{
                }];
            }

        } else {
            // no attachement exists, so it's only a text without attachments
            // call only super
            [super mouseDown:event];
        }

    } else {
        // by ontime mouse click call only super
        [super mouseDown:event];
    }

    NSPoint dragPosition = [self convertPoint:event.locationInWindow
                                     fromView:Nil];

    [RKLogger logDebugInfoFromObject:Nil withSelector:_cmd log:[NSString stringWithFormat:@"Dragposition (x/y) (%.0f/%.0f)",dragPosition.x,dragPosition.y]];

}

#pragma mark - Drag & Drop methods
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender
{
    [RKLogger logDebugInfoFromObject:Nil withSelector:_cmd log:Nil];

//    return [super performDragOperation:sender];

    BOOL performDragginOperation = NO;

    NSPasteboard *pboard = [sender draggingPasteboard];
    NSArray *pboardTypes = [pboard types];
    NSDragOperation dragOperation = NSDragOperationNone;

    NSTextAttachment *attachment;
    NSAttributedString *attributedString;

    // dragging files into the TextView
    if ([pboardTypes containsObject:NSFilenamesPboardType]) {

        NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];

        for (NSString *filePath in files) {

            NSString *fileName = filePath.lastPathComponent;
            // turn all filename signs to lowercase to compare suffixes
            NSString *lowercaseFileName = [fileName lowercaseString];;

            if (
                [lowercaseFileName hasSuffix:@"jpg"] || [lowercaseFileName hasSuffix:@"jpeg"] ||
                [lowercaseFileName hasSuffix:@"png"] ||
                [lowercaseFileName hasSuffix:@"gif"] ||
                [lowercaseFileName hasSuffix:@"tif"] || [lowercaseFileName hasSuffix:@"tiff"] ||
                [lowercaseFileName hasSuffix:@"psd"] ||
                [lowercaseFileName hasSuffix:@"pdf"] ||
                [lowercaseFileName hasSuffix:@"icns"]
                ) {
                dragOperation = NSDragOperationEvery;
            }

            if (dragOperation == NSDragOperationEvery) {
                // dragged file is valid for dragging

                NSError *error;
                NSURL *url = [NSURL fileURLWithPath:filePath];
                NSFileWrapper *fileWrapper = [[NSFileWrapper alloc] initWithURL:url
                                                                        options:NSFileWrapperReadingImmediate
                                                                          error:&error];
                if (!error) {
                    fileWrapper.preferredFilename = filePath.lastPathComponent;

                    // insert the dragged file at cursor position
                    attachment = [[NSTextAttachment alloc] initWithFileWrapper:fileWrapper];
                    attributedString = [NSAttributedString attributedStringWithAttachment:attachment];

                    NSPoint dropPoint = [self convertPoint:[sender draggingLocation] fromView:Nil];
                    NSUInteger caretLocation = [self characterIndexForInsertionAtPoint:dropPoint];
                    // insert the new attachment at dragging cursor position
                    [self.textStorage insertAttributedString:attributedString atIndex:caretLocation];

                    // check, if the attributedString already exists and remove it
                    [self.textStorage enumerateAttribute:NSAttachmentAttributeName
                                                 inRange:NSMakeRange(0, self.textStorage.length)
                                                 options:0
                                              usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
                        NSTextAttachment *attachement = (NSTextAttachment*)value;

                        if ([attachement.fileWrapper.preferredFilename isEqualToString:filePath.lastPathComponent]) {
                            // same attachment found
                            // check, if it's the new inserted
                            if (range.location != caretLocation) {
                                // is not, so delete it
//                                [self.textStorage replaceCharactersInRange:range withString:@""];
                                [self.textStorage deleteCharactersInRange:range];
                                *stop = YES;
                            }
                        }

                    }];

                    _rkTextViewController.contentHasChanged = YES;

                } else {
                    [RKError showRKAlertWithError:error completion:Nil];
                    dragOperation = NSDragOperationNone;
                }
            }
        }
    }

    if (dragOperation == NSDragOperationEvery) {
        performDragginOperation = YES;
    } else {
        performDragginOperation = NO;
    }

    return performDragginOperation;

}

A: If you want to be able to drag media from your app, as well as into your app, then you need to set up your window as a dragging source as well as a dragging destination.
There's a good introductory tutorial on this stuff here: https://www.raywenderlich.com/1016-drag-and-drop-tutorial-for-macos
Apologies if you've already seen this.


text:
Q: Postgresql - как загрузить данные в таблицу из текстового файла, в Sql-запросе? Загрузка нужно именно из текстового файла или *.csv, но только через sql запрос, без tools вроде pgql и других.
При этом, чтобы работали относительные пути (путь до файла источника можно было указывать от корня, где находится sql файл.)
Можно ли это оформить в виде процедуры или функции, так как заполнение тестовыми данными, сгенерированными из случайных символов,
не очень читаемо, а если нужно загрузить несколько сотен пользователей с читаемыми именами и другими данными, то скрипт наполнения писать очень неудобно.
Есть вариант использовать Liquibase (loadData), но его нужно поднимать и настраивать для работы. Хотелось бы более простой способ, если конечно он есть.
CREATE TABLE weather
(
    city    varchar(80),
    temp_lo int,  -- низкая температура --
    temp_hi int,  -- высокая температура --
    prcp    real, -- количество осадков --
    date    date
);

COPY weather FROM './weather.txt';

weather.txt
'San Francisco', 43, 57, 0.0, '1994-11-29'
'London', 45, 56, 0.1, '1994-11-30'
'Berlin', 35, 46, 0.2, '1994-11-15'

Этот вариант не работает.

Файлы, указанные в команде COPY, читаются или записываются непосредственно сервером, не клиентским приложением. Поэтому они должны располагаться на сервере или быть доступными серверу, а не клиенту. Они должны быть доступны на чтение или запись пользователю PostgreSQL (пользователю, от имени которого работает сервер), не клиенту. Аналогично, команда, указанная параметром PROGRAM, выполняется непосредственно сервером, а не клиентским приложением, и должна быть доступна на выполнение пользователю PostgreSQL. Выполнять команду COPY с файлом (или командой) разрешено только суперпользователям базы данных, так как она позволяет прочитать и записать любой файл, к которому имеет доступ сервер.

Хорошо, чтобы решение работало как в Windows среде, так и в Ubuntu.


text:
Q: How build a website on blockchain to prevent it from blocking in some countries? I know that my question is general and can have tons of answers, but I couldn't find any guide or tutorial on the internet.
Think of China, North-Korea or other restricted countries which block millions of websites or IPs. is there a way to build a website based on blockchain or other technologies to prevent it from being blocked?

A: A blockchain may not be suitable for serving HTML content because web pages are usually huge compared to a transaction data. There are other alternatives such as IPFS (InterPlanetary File System), based on a P2P protocol to share files in a decentralized manner.
However, blockchains can be used in conjunction to provide a decentralized name service (e.g., namecoin) or incentivizing storage on IPFS nodes (e.g., filecoin).

A: Idea of blocking certain things on a blockchain network is essentially contrary to the original idea of peer-to-peer networks.
But if you are willing to do it you'd have to find a way to host a website on the blockchain. e.g: Codius  by Stefan Thomas
There's even an example of hosting a simple react-app


text:
Q: Need help figuring out why I am getting a java.lang.StackOverflowError on my TestClock.java program Hello and thanks for any help you can offer,
I am still pretty new to Java and I need some help figuring out why my program doesn't work. Everything looks good when I compile and I used two command line args (11:45:12 11:48:13). When I run the program it kicks back this error:
Exception in thread "main" java.lang.StackOverflowError at Clock.toString(Clock.java:37)

What am i forgetting to do? Any idea what i need to fix?
Here is the code:
For my Clock Class:
//header files

import java.time.LocalTime;
import static java.lang.System.out;

// creating class clock
public class Clock {

// private data fields
private LocalTime startTime;
private LocalTime stopTime;

// no argument cosntructor to initilize startTime to current time
protected Clock() {
    startTime = LocalTime.now();
}

//method start() resets the startTime to the given time
protected LocalTime start() {
    startTime = LocalTime.now();
    return startTime;
}

//method stop() sets the endTime to given time
protected LocalTime stop() {
    stopTime = LocalTime.now();
    return stopTime;
}

//getElapsedTime() method returns elapsed time in sconds
private void geElapsedTime() {
    long elapsedTime = stopTime.getSecond() - startTime.getSecond();
    out.println("Elapsed time is seconds: " + elapsedTime);
}

public String toString() {
    return toString();
}
}

For my TestClock Class:
// header files
import java.time.LocalTime;
import static java.lang.System.err;
import static java.lang.System.out;

// creating class of TestClock
class TestClock {

// construct a clock instance and return elapsed time
public static void main(String[] args) {

// creating object
    Clock newClock = new Clock();

// checking the condition using loop
    if (args.length == 2) {
        LocalTime startTime = LocalTime.parse(args[0]);
        LocalTime endTime = LocalTime.parse(args[1]);
    }
    else {
        err.println("Application requires 2 command line arguments");
                  System.exit(1);
    }

// display new clock value
    out.println(newClock);

}

}

A: Your toString() method in the Clock class is recursively calling itself. I think you probably wanted super.toString(), although, in that case overriding the method in the first place is unnecessary. If you wanted to print the times, you would use startTime.toString() or stopTime.toString().

A: You are returning toString() to itself basically, which looks to me to be a recursive call.  This is over-flowing the stack and giving you the error.  toString() is a method in the Object class, which all objects inherit from.  You need to over-ride it with your own String interpretation.  You should do something like
@Override
public String toString()
{
return "The starttime is: " + startTime " and endtime is: " + endTime";
}

A: Your toString method calls itself infinitely. You should just remove it,especially since it does not output anything special.


text:
Q: Can JSON data dynamically specify an angular filter to use? I have an Angular (v1.2) app that accepts JSON data and displays it in a table using a set of ng-repeats and a structure defined by another JSON object. Within the structure, I specify the filter using an ng-switch.
data JSON:
[
    {
        first: "Lorem",
        second: "Ipsum",
        arg: 2
    },{
        first: "Dolor",
        second: "Sit",
        arg: 3
    },{
        first: "Amet",
        second: "Consectetur",
        arg: null
    }
]

structure JSON:
[
    {
        key: "first",
        filter: "lowercase"
    },{
        key: "second",
        filter: "uppercase",
        rgmnt: "arg"
    }
]

HTML:

But this seems sloppy. For one, you need to specify the filter name in two places, in the script and in the html. It would be simpler if you could pull the filter name from the data, like this:

Is there any way to dynamically pull a filter name from data?

A: Actually you can specify the filter id dynamically:

See working plunker.
EDIT: You may want to set a default filter or no filter with a simple workaround:
Create a new filter which just returns the input:
app.filter("same", function() {
    return function(input) {
        return input;
    };
});

Modify the ngBind
ng-bind="nextItem.name | {{nextItem.filter ? nextItem.filter:'same'}}"
See final plunker.

A: Thanks to himmet-avsar!
The filter can specified simply by using handlebars.

But, this assumes that the filter property is always specified. You can use another filter to specify if the pipe is shown and even pass arguments through it:

function isThereAFilter() {
    return function (input, arg1) {
        if (input != null) {
            return "| " + input + ": " + arg1;
        }
    }
}


text:
Q: How do I show a range of numerical values first in SQL? How would I arrange this so that it is still ordered by time but also any IDs under 10 would be shown first?
Time  |   ID
9:15  |   1
9:20  |   5
9:25  |   12
9:30  |   3
9:35  |   26
9:40  |   22
9:45  |   15

Can this be achieved with an "order by" code? Or do I need something else?
I'm using Microsoft SQL Server 2012.
EDIT: This is the output I'm hoping for:
Time  |   ID
9:15  |   1
9:20  |   5
9:30  |   3
9:25  |   12
9:35  |   26
9:40  |   22
9:45  |   15

ID 12 and 3 would be switched. So the priority would be on ID number THEN time.

A: Use this custom sort
SELECT *
FROM   Yourtable
ORDER  BY CASE
            WHEN id <= 10 THEN id
            ELSE 11-- Just a number greater then 10 to keep the id>10 after id<=10
          END ASC,
          time

Demo
Schema setup
create table #tts(Time  time,   ID int)
insert #tts values
('9:00' ,21 )
('9:15' ,1 ),
('9:20' ,5  ),
('9:25' ,12),
('9:30' ,3  ),
('9:35' ,26),
('9:40' ,22),
('9:45' ,15)

Query
SELECT *
FROM   #tts
ORDER  BY CASE
            WHEN id <= 10 THEN id
            ELSE 11
          END ASC,
          time

A: A nested query with ORDER BY can work as well, though you will end up with a 3rd  sort column:
SELECT t.* FROM
( SELECT Time
        ,ID
        ,CASE WHEN ID < 10 THEN 1 ELSE 2 END AS 'ColOrder'
  FROM YourTable) as t
ORDER BY t.ColOrder, t.Time


text:
Q: Minimize a function in two variables with constraint I have to minimize this:
\begin{align*}
\min&\quad{ (x-3)^2+(y-1)^2} \\
s.t.& \quad 2x+y \leq 2 \\
&\quad x^2 + 2y = 3\\
&\quad x, y \geq 0
\end{align*}
Can I isolate $y$ in the second constraint and substitute it in the first?

A: Let $$(x-3)^2+(y-1)^2=z~~~(1)$$ Let us put $x^2=(3-2y)$ in (1), we get $$y^2-4y-6x+13-z=0.~~~(2)$$ $z$ will attain optimum value if when the line $y=2-2x$ touches the curve (2)
which is a parabola. Let us but this line in (2)
$$4x^2-6x+9-z=0.~~~~(3)$$
Now demand $B^2=4AC$.This gives $z=27/4,$ the answer.


text:
Q: Запуск asp.net Core приложения через Powersell Мне необходимо запускать asp.net Core приложение сбилденное для автономного развертывания средствами PowerShell.
При запуске через даблклик по файлу .exe приложение запускается без проблем. При вызове команды PowerShell Start-Process "{myPath}\bin\Debug\netcoreapp3.1\app\App.exe" получаю ошибку:
An error occurred while seeding the database.
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')

Подскажите, пожалуйста, в чем проблема?

A: Проблема решена. Запуск необходимо осуществлять предварительно перейдя в директорию с исполняемым файлом.


text:
Q: SQL Server: Generic Stored Procedure to move data from one table to another table Here are my requirements:

*

*To archive data from one table to another, I am looking for a perfect way. I want to schedule a job and set the parameter like DatabaseName, SchemaName, TableName, FilterQuery, etc.

*Parameter should be the configurable

*I can achieve this requirement through the Dynamic Query, but my DBA told me to avoid the dynamic query.

*Is there any way I can achieve the requirement without a dynamic query?


text:
Q: Is it possible to call a command inside a thread Generally while writing a c/cpp program, if i ever need to execute any bash command for which there is no c library, i fork a child and then do execvp on it by passing a script name.
But i want to know is it possible to call like this in a thread without forking(if forking then there's no advantage of threads), or is there any other way to do this?
Actual Problem:
Background:
there's a commandline utility called criu which can checkpoint a running program and creates a folder containing files for the program state. This command has options to leave the program in running state after creating the checkpoint.
Goal: I've to call this utility multiple times periodically(say in a period of 50 milliseconds). Send this checkpoint folder to the destination(i use rsync utility to do this) asynchronously which means the program should not wait for the transmission of checkpoint to complete as soon as it creates a checkpoint by calling criu utility it resumes for another iteration, wait for another 50 ms and then again makes a call to criu to create a checkpoint.
A diagram will help more to understand the flow of program:
see image The blue colored execute duration is for say 50 ms. Do SomeTask(4) and execution is in parallel.
My approach: see below pseudo code for my design of the program:
while(true){

 sleep(50ms) // wait for 50 milliseconds

 call criu utility // which takes checkpoint of another running  program.This part is not so much of focus right now, can assume there is something which just creates a folder.

 send the checkpoint to the destination in parallel // using rsync utility for this, so i've no idea how will i build the part where this program will recieve an acknowledgement back and perform another task parallely with the help of threads.

}

Note: program takes a checkpoint of another running program using pid of that program, mentioning this to remove any confusion.
Please comment below if you want further clarifications. I hope this question is not creating any confusions with the word criu, rsync command line utilities. you can forget those and just see the flow which is the main problem right now.
Reason for question statement:
I've thought of creating threads instead of forking each time i call a command usng bash script inside this c/cpp program as this program is running infintely at some point it system will have a large number of process created and may throw an error of system resources unavailable if use forking. Thtat's why wanted to know if it's possible to call commands inside a thread.


text:
Q: Using immer.js - reassigning draft array reference results in same array reference in state I have this failing test using the produce method of immer.js:
     it('should replace array reference in state', () => {
        let state = {
            someArray: [1],
        };
        const somArrayUpdate = [2, 3];

        state = produce(state, draft => {
            draft.someArray = somArrayUpdate;
        });
        console.log(state.someArray);
        // update external array
        somArrayUpdate.push(4);
        // expect that the state array is not the same reference with the external array
        console.log(state.someArray);
        expect(state.someArray).not.toBe(somArrayUpdate);
    });

You can see the failing test here:
https://stackblitz.com/edit/jasmine-gwrbgh
I am trying to understand why this is not working and also how should an array replacement be performed using immer.js (there are no relevant examples in the documentation AFAIK).


text:
Q: At what point does a domain suit a network better than a workgroup? At what point does a domain suit a network better than a workgroup?
Is there a threshold below which a domain is simply too much work for benefits gained?
Is there a point after which a workgroup is too hard to manage and a domain is more practical?
What criteria do you use to make this decision?

A: Somewhere between five and ten users.
If you want to change your password in a workgroup, you have to change it on every computer.  That's a pain in the [expletive deleted].
Domains solve this.  Small Business Server is pretty cheap for what it is, and that starts at five users, which is where I came in.
SBS is fantastic if you've got 5-75 Windows desktops.  Really.  Get it.

A: I don't think you can pin down a single "point" where it suddenly becomes better to use a domain vs. a workgroup.
That said, I generally consider around 5 computers to be the max size for a workgroup. Any larger than that, and domains start to have some attractive advantages that make it worth the effort.
Some criteria that might suggest a domain is the right choice:

*

*You need a central location for sharing files/enforcing permissions

*You have users that change passwords or even users that come and go (e.g., new employees)

*You have users that aren't good at "managing" their own computers (i.e., they don't install updates, don't know not to run suspicious attachments, etc.) and so need the "structure" and security that you can get from a domain

*Windows Update Services is really nice once you get it up & running, and ensures that computers are up-to-date.

*You need (or want) to use some of the features that a domain's Group Policy can give you

There are some factors that make a domain impossible of course:

*

*You have a bunch of "home" type computers (e.g., running "Home" versions of Windows and therefore can't join a domain). (You could replace the OS of course, but I'm assuming that if you're using "home" machines, you might not have access to or the budget for the "pro" versions of the OS)

*You don't have a server

*The computers aren't yours (you don't have permission to join them to a domain; as in say people who bring in their own laptops and don't want to join a domain that they won't be able to access while at home)

Like so many things, the choice of whether to set up a simple workgroup or a domain is a very personal, subjective one... anyway, these are some of the things that guide my decision when I have to make that choice. Hopefully they will help you as well.

A: If you need to centrally manage the network - set up a domain based network.
If you intend to let each user be the master and controller of his machine, go for a wourkgroup based network.


text:
Q: Display SnackBar at top when Theme.NoTitleBar.Fullscreen is applied I'm displaying a SnackBar at the top of my view by implementing the following:
Snackbar snack = Snackbar.make(rootlayout, "SnackBar Test!", Snackbar.LENGTH_LONG);
View view = snack.getView();
FrameLayout.LayoutParams params =(FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
view.setLayoutParams(params);
snack.show();

This is working perfectly, but the problem is that the activity is full screen / NoTitleBar, I have done this by adding the following to the activity in Manifest:
<activity android:name=".MyActivty"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />

When I run it I get the following error:
Caused by: android.view.InflateException: Binary XML file line #41: Error inflating class <unknown>
This only happens when I set the activity theme to Theme.NoTitleBar.Fullscreen.

A: Your problem is the following.
First Snackbar dependes on the support design library. Which works with AppCompatActivity. The theme that you are trying to use is not from the suport library. In order to use fullscreen appcompat theme you can use this
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Change your theme to this in the manifest also and try if it is going to work.


text:
Q: Perl regex capturing multiple instances $string = "BLAH1234 xyz BALH3214 xxyyzz BALH3452"
I want to capture all instances of 4 capital letters in a row followed by 4 numbers.
I did: $line =~ /([A-Z]{4}[0-9]{4})/g but I can only capture the first instance. When I do $2 it says it's uninitialized.
How can I capture all instances?

A: my @matches = $string =~ /[A-Z]{4}\d{4}/g;

A: Given:
$ echo "$tgt"
"BLAH1234 xyz BALH3214 xxyyzz BALH3452"

You can do:
$ echo "$tgt" | perl -lne 'print join("|", /[A-Z]{4}\d{4}/g)'
BLAH1234|BALH3214|BALH3452

Or, more explicitly:
my $line="BLAH1234 xyz BALH3214 xxyyzz BALH3452";
for ($line=~/[A-Z]{4}\d{4}/g) {
    print "$_\n";
}

A global find returns a list.


text:
Q: Piping From Child To Parent Process I am currently writing a program in C using Linux in which a parent process creates a child process and then that child process creates another child processes (so three processes total).  I have to pipe a string from parent to the first child process and then from the first child process to the child of that process.  I am currently piping the string from parent to child using code similar to this (all code not shown):
pipe(pipeArray)

write(pipeArray[1], myString, length);

close(pipeArray[1]);

read(pipeArray[0], FirstProcessString, length+1);

close(pipeArray[0]);

My problem is the second part of of my program in which now I must take the string from the second child process and pipe it all the way up to the first parent process.  How do you pipe from the second child process to the original parent process (the first process)?  I have tried variations of this code in order to pipe up with no luck and also researched this topic and was not able to find anything helpful.


text:
Q: About finally block I know finally's purpose is to guarantee that some instructions or cleanup code get executed. But what is the actuall difference of using finally or putting the code after the catch block.
I mean, give me an example of a case where you need to use finally because otherwise the code might not execute at all.

A: Finally will execute regardles of what happends in the catch block. Several cases exist.
catch(Exception E)
{
    ...
    throw new OtherException(BetterMessage, E);
}

or
catch { return null; }

or
catch { SomeMethodThatWillThrowAnException(); }

Thus, even if you return or throw an exception to exit the Catch block, you'll still execute a finally block, while any code simply after the try-catch will be ignored.

A: finally executes no matter what.
One example
public void test() {
    try {
       int x = 0;
       return;
    } catch(Exception ex) {
       ex.printStackTrace();
    } finally {
      System.out.println("Hello from finally");
    }

    System.out.println("Hello from after catch");
}

In this case "Hello from after catch" will not be printed but "Hello from finally" will.

A: A finally block is going to fire no matter what, even if you throw and catch.  Code placed after the catch that's not in a finally block might not execute, for example if your catch might cause a process to end or an application to crash.

A: The finally block is executed regardless of whether or not an exception is thrown.
Your question is, what is the difference of using finally, and putting code after the catch block. If an exception is thrown, code after the catch block won't be executed. If you place the code in the finally block, it will.

A: There might occur some exception that you won't catch. finally block guarantees execution of code inside of it even if unexpected exception is thrown.


text:
Q: Composer update with "doctrine/doctrine-bundle": "2.0.*" conflicts I am trying to upgrade a version of doctrine-bundle that is currently quite old, to be able to ultimately upgrade Symfony to 4.4.
I am currently getting these
Package doctrine/doctrine-cache-bundle is abandoned, you should avoid using it. No replacement was suggested.
Package doctrine/mongodb is abandoned, you should avoid using it. No replacement was suggested.
Package doctrine/reflection is abandoned, you should avoid using it. Use roave/better-reflection instead.

this is a part of my composer.json:
"require": {
    "php": "^7.1",
    "symfony/symfony": "3.4.*",
    "doctrine/orm": "2.*",
    "doctrine/doctrine-bundle": "1.*",
...

When I would like to install a higher version of doctrine (i.e. 2.*) I get the following:
Problem 1
- symfony/cache[v5.0.0, ..., v5.0.8] require php ^7.2.5 -> your php version (7.1.33) does not satisfy that requirement.
- symfony/cache[v5.0.9, ..., v5.4.11] require php >=7.2.5 -> your php version (7.1.33) does not satisfy that requirement.
- Root composer.json requires symfony/symfony 3.4.49 -> satisfiable by symfony/symfony[v3.4.49].
- doctrine/doctrine-bundle 2.0.10 requires symfony/cache ^4.3.3|^5.0 -> satisfiable by symfony/cache[v4.3.3, ..., v4.4.44, v5.0.0, ..., v5.4.11].
- Only one of these can be installed: symfony/cache[v3.1.0, ..., v3.4.47, v4.0.0, ..., v4.4.44, v5.0.0, ..., v5.4.11, v6.0.0, ..., v6.1.3], symfony/symfony[v3.4.49]. symfony/symfony replaces symfony/cache and thus cannot coexist with it.
- Root composer.json requires doctrine/doctrine-bundle 2.0.10 -> satisfiable by doctrine/doctrine-bundle[2.0.10].

So it's a little bit unclear for me why the following happen:

*

*Why is it complaining about symfony/cache 5.* when according to packagist it can just install the ^4.3.3 version

*Why is it trying to install symfony/cache in the first place, if my composer json contains symfony/symfony which apparently replaces it?

Can you help me to figure out how to upgrade doctrine-bundle? Also, when it says "Problem 1", which one of these is actually the problem?
Thank you!


text:
Q: Can't install material-ui/core for React.js project using npm I can not solve this problem while installing Material UI core or icon. Can you please help me with solution what is going on here in this error message?
Unrecognized token in source text.
At line:1 char:7
+ npm i  <<<< @material-ui/core
    + CategoryInfo          : ParserError: (:) [], ParentContain
   sErrorRecordException
    + FullyQualifiedErrorId : UnrecognizedToken

Thanks,
Susmoy Debnath


text:
Q: Does $\cup_{n=1}^{\infty} {h_n}^{-1} (\overline{U_n}) \subset \overline{ \cup_{n=1}^{\infty} {h_n}^{-1} (U_n) }$ hold? Let $\{ h_n :X \to Y\}_{n \in \mathbb{Z^+}} $ be a sequence of continuous functions from a topological space $X$ to another topological space $Y$, and for each $n$ let $U_n$ be an open subset of $Y$.
Does
$$
\bigcup_{n=1}^{\infty} {h_n}^{-1} (\overline{U_n}) \subset \overline{ \bigcup_{n=1}^{\infty} {h_n}^{-1} (U_n) }
$$
holds?

A: No, even for one function $h$. Let $X$ be $\Bbb N$ endowed with the discrete topology, $Y$ be $\Bbb R$ endowed with the standard topology, $h(n):X\to Y$ be a enumeration of the rationals and $U=\Bbb R\setminus\{0\}$. Then $$h^{-1}(\overline{U})= h^{-1}(\Bbb R)=\Bbb N\not\subset  \Bbb N\setminus\{ h^{-1}(0)\}=h^{-1}(U)= \overline{ h^{-1}(U)}.$$

A: A counterexample with one function is as follows. Let $X = \mathbb R$ and $Y = [0,+\infty)$, both with standard topologies. Let $h : X \to Y$ be defined by
$$
h(x) = \max\{ 0, x^2-1\}.
$$
Let $U = (0,1)$. Then $\overline{U} = [0,1]$ and
$$
h^{-1}([0,1]) = [-\sqrt{2}, \sqrt{2}]
$$
and
$$
\overline{h^{-1}((0,1))} = [-\sqrt{2},-1] \cup [1, \sqrt{2}]
$$.


text:
Q: react-native ios get mac address In the react-native application I use the react-native-device-info library to get the MAC address of the device.
But I can only get the mac address of Android devices. I could not find a library to get the mac address of iOs devices.
How do I get the MAC address of iOs devices?

A: There is no way of doing this in iOS 7 or later, citing apple:

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead.

Instead, you should use "identifierForVendor" which could be received with react-native-device-info:
import DeviceInfo from 'react-native-device-info';

const uniqueId = DeviceInfo.getUniqueID();


text:
Q: Basic design of low-wattage 5V battery charger (is this realistic?) I'm trying to come up with a solution for keeping a very small GPS tracker mounted someplace where it will stay indefinitely without an external power source. Since my main interest will be using such a thing on my vehicles in case of theft, one possible way it could be self-powered would be through kinetic energy.
I'm thinking I might be able to make a 'shake flashlight' style dynamo - a rod on a shaft which moves past copper coils as it bounces up and down. I know it'll work to generate electricity, I'm just not sure how much will be enough to realistically charge a ~3-5v lithium battery. All I know is my 18650 battery charger says it supplies them with 4.2V DC at 750mA.
As for a GPS receiver chipset with GSM rx/tx, it requires very little power when set to connect only a few times per day and send its location. Even the smallest GPS trackers you see on eBay claim about 2 weeks battery life with just their built-in 400 mAh battery. So, if I can make this work, I believe that on a bicycle, motorcycle, etc., as long as it's being ridden it should be able to keep enough of a charge. Forever. In theory.
So, please, tell me why nobody else has done this.. Would it just be too much trouble to convert a trickle of microwatts into ~3 watts, over time?

A: In theory it sounds feasible to me.
If a 400mAh battery last two weeks, it means that the circuit consumes about 4.3mW on average (400mAh * 3.6V / (2 wks * 7 days * 24 hours)) . Let's say that your shake-based generator will work 30 minutes per day, then it would have to generate about 206mW when active (24 hours/ 0.5 hour * 4.3mW). On top of that I would add about 20% extra to account for inefficiencies of the power conversion circuitry (generator power conditioning + battery charging), what translates into a requirement of 250mW of output power from the generator when it's active.
My next step would be to research generators that can actually deliver these 250mW on average in realistic driving/riding conditions. It will probably be a trade off between size and output power. Considerations in terms of how smooth the driving/riding are will also be important.


text:
Q: Write csv file at server-side, and send it to silverlight client via WCF RIA Services I have created csv file at server-side. Now I want to send it to my silverlight client
via WCF RIA Services. I created the following:
public byte[] GetMyCSV()
{
  string file = @"c:\test.csv";
  using (StreamWriter sw = new StreamWriter(file, true, Encoding.GetEncoding(932)))
  {
    //write csv file content
    ...
  }

  ???
}

Should my service send byte array? If then how to get byte array from StreamWriter?

A: First of, the StreamWriter class if for writing to a file. As long as i understand your question you want to read from the File.
The easiest way to read all bytes from a file is to use the File class and the ReadAllBytes method.
public byte[] GetMyCSV(){
  string file = @"c:\test.csv";
  bytes[] fileBytes;

  using (var fileStream = File.OpenRead(file))  {
    fileBytes = fileStream.ReadAllBytes();
  }

  return fileBytes;
}

The other way is to use the StreamReader class, to read blocks of bytes from the file and to define additional encodings for reading.


text:
Q: No package found with specified pattern: d:\a\r1\a\**\*.zipCheck if the package mentioned in the task is published as an artifact I am creating a Build and release pipeline for my .Net core FunctionApp in Azure. I am getting the following error
2020-07-13T07:59:10.6443361Z ##[error]Error: No package found with specified pattern: d:\a\r1\a\**\*.zip<br/>Check if the package mentioned in the task is published as an artifact in the build or a previous stage and downloaded in the current job.

Below is the yaml file of the pipeline
YAML file
# .NET Core Function App to Windows on Azure
# Build a .NET Core function app and deploy it to Azure as a Windows function App.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/en-us/azure/devops/pipelines/languages/dotnet-core

trigger:
- master

variables:
  # Azure Resource Manager connection created during pipeline creation
  azureSubscription: 'f296911a-0481-4fed-ba93-a30ef6a5b0f2'

  # Function app name
  functionAppName: 'srlcustomermanagerapp'

  # Agent VM image name
  vmImageName: 'vs2017-win2016'

  # Working Directory
  workingDirectory: '$(System.DefaultWorkingDirectory)/CustomerOrderApi'

stages:
- stage: Build
  displayName: Build stage

  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)

    steps:
    - task: DotNetCoreCLI@2
      displayName: Build
      inputs:
        command: 'build'
        projects: |
          $(workingDirectory)/*.csproj
        arguments: --output $(System.DefaultWorkingDirectory)/publish_output --configuration Release

    - task: ArchiveFiles@2
      displayName: 'Archive files'
      inputs:
        rootFolderOrFile: '$(System.DefaultWorkingDirectory)/publish_output'
        includeRootFolder: false
        archiveType: zip
        archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
        replaceExistingArchive: true

    - publish: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
      artifact: drop

- stage: Deploy
  displayName: Deploy stage
  dependsOn: Build
  condition: succeeded()

  jobs:
  - deployment: Deploy
    displayName: Deploy
    environment: 'development'
    pool:
      vmImage: $(vmImageName)

    strategy:
      runOnce:
        deploy:

          steps:
          - task: AzureFunctionApp@1
            displayName: 'Azure functions app deploy'
            inputs:
              azureSubscription: '$(azureSubscription)'
              appType: functionApp
              appName: $(functionAppName)
              package: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip'

Release configuration

A: 1.Make sure you've set the Build Pipeline as artifact source, and the build do provide the artifacts:

2.If the issue persists, try to specify the path via Browse Package or folder option:

Then you can check if your release can get the required xx.zip file via this option. Also you can choose to specify the file path using this option.


text:
Q: Is coprimality in $NC$? Following reference https://pdfs.semanticscholar.org/e86e/8d7a267a29b9ad4ca112828109adfec55e8b.pdf claims integer coprimality is in $NC$ and it also has one citation. Is this claim valid?

A: Probably it's not valid:
On ECCC, Comment #3 to TR98-009 | 11th May 2001 12:33
Comment on parallel complexity of coprimality
Referee Report of SICOMP submission
...
Recommendation
The paper is not acceptable for publication. The algorithm contains a
flaw I believe to be fatal. In fact, I do not think that the author's approach, though innovative and promising at first sight, is viable.
...


text:
Q: Run a bash command until diff between two files is non-empty I have a two versions of a program, say : normalProgram and bruteProgram.
I have an input generator for both of these : programGenerator
Now I want to do this:

*

*Put the output of ./programGenerator into input.txt : ./programGenerator > input.txt

*Redirect input.txt as the input of normalProgram : cat input.txt | ./normalProgram

*

*Put the output of ./normalProgram into op1.txt : (cat input.txt | ./normalProgram) > op1.txt

*Similar thing for ./bruteProgram :

*

*(cat input.txt | ./bruteProgram) > op2.txt

*Now I want to compare op1.txt and op2.txt : diff op1.txt op2.txt
The whole command will look like this:
./programGenerator > input.txt &&
(cat input.txt | ./normalProgram) > op1.txt &&
(cat input.txt | ./bruteProgram) > op2.txt &&
diff op1.txt op2.txt

So this is a one time command.
I want to run this until diff op1.txt op2.txt gives a non-empty response.
I tried putting diff op1.txt op2.txt as the condition for until (or while, just to check whether the conditional is correct)
But this didn't work, and I got an error that, that is not a correct conditional.
Example:
while [diff normalOp.txt bruteOp.txt]
do
echo "hello"
done

This is giving me the error:
zsh: bad pattern: [diff

A: I just had to remove the square brackets from the condition:
while diff normalOp.txt bruteOp.txt
do
echo "hello"
done

And this started working.

The exact bash command in this case would be:
while diff op1.txt op2.txt
while> do
while> ./programGenerator > input.txt
while> (cat input.txt | ./normalProgram) > op1.txt
while> (cat input.txt | ./bruteProgram) > op2.txt
while> done


text:
Q: How can I get any unique id flutter android and ios I need to get a unique information of my device. This may be the mac address, it may be the imei address, or something different, ios and android return a constant value after a certain version and do not give the unique id.
The unique id as currently used changes when the application is deleted and reinstalled. I have a chat system and I don't want some members to come back.
Is there a way to access a device's unique information by obtaining a permission if necessary?

A: you can use a package called firebase_messaging and get device token
String deviceToken = await FirebaseMessaging.instance.getToken();
To get the IMEI of user phone device_information
 String imeiNo = await DeviceInformation.deviceIMEINumber;

A: The token is generated per the client app instance.

On initial startup of your app, the FCM SDK generates a registration token for the client app instance.

See Best practices for FCM registration token management for details.
Only one user at the time is logged in on the app instance. Delete the token when a user logs out and then you get a new token when a new user logs in.


text:
Q: ArrayList sorting incorrect order; Selection Sort I had to code Selection Sort, and I previously used an Array and it worked perfectly, but the textfiles were too large to use an Array so I had to convert the code to ArrayList. What happens now is, (with the large textfile too) majority numbers are sorted but there are a few unsorted number in between the sorted ones, think it might be a duplication error...
I have tried changing to descending order and it does the same thing. I used a smaller textfile to show the output. All the relevant methods are below.
public void SelectionSort() // ascending order
{

    for (int i = 1; i <= List.Count; i++) // go through the list
    {
        ListClass minimum = (ListClass)List[i-1];
        int min = i - 1;
        for (int j = i;j <= List.Count-1; j++)
        {
            ListClass cur = (ListClass)List[j];

            if (minimum.getNum() > cur.getNum())
                min = j; // min equals smallest in list j

        }
        swap(List, i-1, min);
    }
    Console.WriteLine("Array after selection sort: ");
    foreach (ListClass cur in List)
    {
        cur.Display();
    }
public static void swap(ArrayList List, int x, int y)
{
    object temp = List[x];
    List[x] = List[y];
    List[y] = temp;
}
public void Display()
{
    foreach (ListClass cur in List)
    {
        cur.Display();
    }
}

Array before sorting: 1 2 5 7 8 90 889 88 654 33 2 3 Array after selection sort: 1 2 3 5 7 8 90 2 88 33 654 889

A: you shouldn't compare the minimum of unsorted part with the last sorted value and swap it with that, you just have to find the minimum of the unsorted part and swap it with the first unsorted value(next to the last sorted value).


text:
Q: appending elements to a list I am trying to append a list element dynamically to already existing list.
I've a list in the form,

YYAAHOOOOOO

I am trying to add an extra item to this list using jQuery append or after...
What I did was:
$(".testField").after("
TEST MESSENGER
");

Used after function as append did not work, the after function works fine first time as there is only one element with the class name testField, but as the list grows, the after function will add the list items to all elements present,
To make it clear, on first trial I will get an output:

YYAAHOOOOOO

TEST MESSENGER

If I try the to add another element now for example
GOOGLE
, the output will be like:

YYAAHOOOOOO

GOOGLE

TEST MESSENGER

GOOGLE

I thought about using ids, but I am trying to have an option to remove elements from the list too... So if I try to append to an undefined id, it will return error. Is there anyway to find the first element inside a list and append the element to that first one?

A: Try:
$(".testField:first").after("
TEST MESSENGER
");

this will make sure that you are appending after the first element only

A: Alternatively, you could do this without jQuery:
var li = document.createElement('li');                       // Create a List item.
    li.setAttribute("class", "testfield");                   // Set the li's class
    li.addChild(document.createTextNode("Your Text Here!")); // Set the li's text
document.getElementById("test").addChild(li);                // Append the li to the list

It's slightly more code, yes, but it's pretty much what jQuery does under the hood. (And faster, too)
If you want to add the new ul after the first li already in the list, replace the last line with:
var ul = document.getElementById("test");
if(ul.children.length > 1){              // If the list has 2 or more children (li's)
    ul.insertBefore(li, ul.children[1]); // Insert the new item before the second item in the list.
}else{
    document.getElementById("test").addChild(li);
}

Now, why am I posting a answer that requires more code?
Anything that can be done in jQuery can be done in native JS. I think it's good to have multiple different answers available on SO, especially if they use different techniques to do the same thing. That way, users can chose for themselves: short'n easy (jQuery), or if they don't want to use the library, native code.


text:
Q: Using facebook ads sdk in symfony I downloaded facebook ads sdk using composer. Everything worked fine. Now I want to add this sdk to my existing symfony project. I copied all content to /lib/vendor. After that I am trying to use api here:
if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
      throw new \Exception(
        'You must set your access token, app id and app secret before executing'
      );
    }
    else
    {
        echo "fine.";
    }
    if (is_null($account_id)) {
      throw new \Exception(
        'You must set your account id before executing');
    }
    else
    {
        echo "fine.";
    }
// define('SDK_DIR','/var/www/html'); // Path to the SDK directory
// $loader = include '/vendor/autoload.php';
// $this->loader->registerNamespace('FacebookAds',sfConfig::get('sf_lib_dir') . '/vendor/facebook/php-ads-sdk/src/FacebookAds');
// use FacebookAds\Api;

Api::init($app_id, $app_secret, $access_token);

I am getting error: Fatal error: Class 'Api' not found in
How can I add this sdk to symfony.