text:
Q: d3.js range of values for lab colour I am working on an X-colours palette (kinda like this one) but based on d3's lab colour space implementation. I have read the documentation here, here and here, even had a look at the source code here and I figured that l-value must be within [0,100] but I couldn't find a range for a and b. Does any value work with them or are they bound to a specific range (like [0, 255] for rgb for example)?

A: The a parameter is a point in the range yellow-blue component and the b parameter is a value in the green-magenta component. It's hard to determine valid range values for a and b, as the valid range depends on the value of the parameter L (which is expected to be in the range [0, 100]). This article contains more details. You could use d3.interpolateLab(l, a, b). In this context, a and b are object that can be interpreted as colors (string, d3.rgb, d3.hsv).


text:
Q: Design for User hierarchy in Ruby on Rails I have an application that requires authentication, and have a User model. There are 4 levels of authorisation with the following rules:

*

*Level 1 users can create/edit/delete all level 2,3 and 4 users.

*Level 2 users can create level 3 and 4 users, and edit only those users they own.

*Levels 3 and 4 have no authorisation to create/edit/delete users.

*UPDATE: Level 3 and 4 users could have multiple level 2 parent users.

In addition to this, I want all users to be able to login through a single interface.
Are there any patterns for dealing with such a hierarchy? using an authorisation plugin such as cancan will allow me to define the different levels of authorisation, but not the relationships between the different users.
Essentially I would like a design that would enable me to write controller code such as this:
@level_two_users = current_user.find_all_my_level_two_users

Thanks

A: You could add a attribute level to your user model and a method to query for allowed users.
To get all users with level X just use a query like User.find_all_by_level(2)
class User
  attr_accessible :level

  def allowed_to_edit_user?(user)
    case self[:level]
      when 1
        user.level > 1
      when 2
        user.level > 2 && user.created_by?(self)
    end
    false
  end

  def allowed_to_create_user_with_level?(level)
    self[:level] <= 2 && self[:level] < level
  end
end

Btw. who creates level 1 users? ;-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access Silverlights collection from javascript I have Silverlight class embedded into page, in App.xaml.cs this component registered to allow calls SL methods from javascript and it is working right.
But now I would like to access not method, but collection.
For example, I have public property
[ScriptableMember]
ICollection<FileInfo> Files {get;set;}

At the runtime i checked accessibility of Files member:
silverlightPlugin.Content.Uploader.Files    | {...}  | Object

defined and has type of Object
But when I trying to call any of following:
silverlightPlugin.Content.Uploader.Files.Count
silverlightPlugin.Content.Uploader.Files.Count()
silverlightPlugin.Content.Uploader.Files.get_Count
silverlightPlugin.Content.Uploader.Files.get_Count()

I've got an exception "Input string was not in a correct format".
Is there any way to access collections from JS or I need to implement special method?

A: Unfortunately, it is not possible. I using function to get required data.


text:
Q: how to concat react-query previous data with new data I have a hook, if I scroll down it will call for new data as like infinite scroll, but when I scroll down it calls the API for new data but it is removing the previous data. I want to concat with previous data. I think it is possible by the select method of react query but how can I get the previous data
const useActivityFeedData = (
  activityFeedPageIndex: number,
  pageSize = Config.defaultPageSize,
) =>
  useQuery(
    [ACTIVITY_FEED, activityFeedPageIndex],
    () => Api.user.getActivityFeedData(activityFeedPageIndex, pageSize),
    {
      initialData: {
        activityList: [],
      },
      keepPreviousData: true,
      select: (res: any) => ({
        activityList: res.activityList,
      }),
    },
  );

A: You are really looking for an infinite query - useInfiniteQuery is made for this exact use-case.

A: Just create a array on mounting of component like this,
 let [data, setData] = useState([])
useEffect(()=>{

    },[])

Now get axios in same useEffect
useEffect(()=>{
       let data = []
axios.get(`....`).then(res=>{
setData(res.data)
})
    },[])

Now after scrolling when u get new Data, just concat it to previous array.
eg: axios.get(`...`).then(res=>{
let var = data.concat(res.data)
setData(var)
})

Then when u map Data, as it updates the page keeps scrolling.
Hope this helps : )

A: Why not something like:
const useActivityFeedData = (
  activityFeedPageIndex: number,
  pageSize = Config.defaultPageSize,
) =>
  const prevData = queryClient.getQueryData([ACTIVITY_FEED,activityFeedPageIndex]).
  useQuery(
    [ACTIVITY_FEED, activityFeedPageIndex],
    () => Api.user.getActivityFeedData(activityFeedPageIndex, pageSize),
    {
      initialData: {
        activityList: [],
      },
      keepPreviousData: true,
      select: (res: any) => ({
        activityList: res.activityList,
      }),
    },
  );

and then just return the prevData with your resposnse or assign the response to a variable from useQuery, and return it.


text:
Q: Determing PID of CGI Script on Windows I'm obtaining a PID, using python, of a CGI script, however, the PID is not valid i.e. can't Taskkill it from CL.  I get:
"Process: no process found with pid xxxx" where xxxx is the pid
I thought maybe I have to kill a parent python shell instance, but os.ppid doesn't work in windows.
So then I installed psutil python module and can now get parent PID, but it just shows the parent as the actual WebServer (Abyss), which I don't think I want to kill, since it is the http process that I notice runs constantly and not just a CGI interpreter instance.
Using psutil I CAN get the process status of the actual script, using the pid returned by os.getpid(), and see that it is running.  So the pid works for purposes of process information retrieval using psutil.  But this gets me no further to obtaining the actual PID I need to kill the script, using EITHER Taskkill on the CL or via kill() from psutil!
What exactly is a cgi shell script from a process perspective, and if it is not a process, why is os.getpid() returning a pid?

A: Why are you assured that your CGI script are still working when you try to kill it?  Web server starts one instance of CGI script for one request and when script finishes it... just finishes.


text:
Q: Why don't we approach the point angularly to find the derivative of Complex functions? In case of Real functions, we approach the point from left and right and see if both derivatives are equal. But in case of Complex functions, the point can be approached from infinitely many directions. Then how can we check that the derivatives from all the directions are equal?
I think in case of Complex functions, we should approach the point angularly. For example, to find a derivative at a point $z$, we can rotate through an angle $d\theta$ about the origin clockwise or anti-clockwise and then find the difference in the value of the function, then divide by the angle change and apply the limit $d\theta \rightarrow0$. In this case, we'll have clock-wise and anti-clockwise derivatives and we can see if they're equal. So, if the argument of $z$ is $\arg{(z)}$, then the derivative would be:
$$\lim_{d\theta \rightarrow0}\frac{f(|z|(\cos{(\arg{(z)}+d\theta})+i\sin{(\arg{(z)}+d\theta})))-f(z)}{d\theta}$$
I think approaching the point angularly should be more convenient than approaching the point from all directions. So, why do we approach the point linearly even in case of Complex functions?
EDIT: I've one more idea, we can even approach the point from outward and inward directions along the line joining the point with the origin. So, we have outward derivative and inward derivative.
In this case the angle remains constant but the modulus changes by an infinitesimal amount. It will be:
$$\lim_{dz\rightarrow 0}\frac{f((|z|+dz)(\cos{(\arg{(z)})}+i\sin{(\arg{(z)})})-f(z)}{dz}$$
So, if a Complex function is given as a function of modulus ($|z|$) and argument ($\theta$ )instead as a function of the co-ordinates, then my 'angluar' derivative is the partial derivative of the function w.r.t $\theta$ and my 'modular' derivative is the partial derivative of the function w.r.t. $|z|$.
Together, both my angular and modular derivatives can get from value of the function to another.
For example, let $f(|z|,\theta)$ be a complex function. Let it's partial derivative w.r.t $\theta$ be $a(|z|,\theta)$ and the partial derivative w.r.t $|z|$ be $m(|z|,\theta)$. Let $z_1$ and $z_2$ be two points. Then,
$$f(z_2)=f(z_1)+\int_{\arg{(z_1)}}^{\arg{(z_2)}}a(|z_1|, \theta)d\theta+\int_{|z_1|}^{|z_2|}m({|z|, \arg{(z_2)}})d|z|$$
Also, what if the definition of the complex derivative is $$f'(z) = \lim_{w\to z} \frac{f(w)-f(z)}{w-z}$$
That doesn't make a difference. Problem is, how do we evaluate that limit? If we substitute $w=z+h$, then that's the same thing as approaching $z$ from the right along the line parallel to the the real axis passing through $z$. If we substitute $w=z+ih$, then that's the same as approaching $z$ from upward along the line parallel to the imaginary axis passing through $z$. If we substitute $w=z+h(cos45+isin45)$, then that's the same as approaching $z$ from North-East along the line passing through $z$ and inclined 45 degrees to the real axis. But how do we know that all those approaches are equal? If they are, only then the derivative exists.

A: Note that a multivariable function may have a derivative in every linear direction but yet have no tangent plane at the point! So even the idea of approaching the point at every angle is logically incorrect because it is insufficient to guarantee differentiability. One example of such a function is:
$
\def\lfrac#1#2{{\Large\frac{#1}{#2}}}
$

Let $f(x,y) = \cases{ \lfrac{x}{y} \sqrt{x^2+y^2} & if $y \ne 0$ \\ 0 & if $y = 0$}$.
Then $\lfrac{d(f(rt,st))}{dt}$ exists for every pair of reals $(r,s)$ such that $r^2+s^2 = 1$.
For instance if $s \ne 0$ then $\lfrac{d\Big(\lfrac{rt}{st}\sqrt{(rt)^2+(st)^2}\Big)}{dt} = \lfrac{r}{s}$, which in particular holds at $t = 0$.
Thus $f$ has all directional derivatives (and is in fact linear in every direction).
But $f$ has no tangent plane at the origin and is hence not differentiable there.

I'll emphasize that complex differentiability is much stronger than multivariable differentiability, but at least you should realize that it's wrong to think of differentiation as simply approaching in all directions.

A: We do indeed approach points "angularly". The definition is
$$
f'(z) = \lim_{w\to z} \frac{f(w)-f(z)}{w-z}.
$$
That means $w$ can approach $z$ from any direction at all, or can follow a spiral toward $z$ so that you can't identify a direction from which it approaches, and no matter how it approaches, the limit must be the same; otherwise the derivative does not exist at all.
Consider, for example, this:
$$
f(z) = \begin{cases} e^{-1/z^2} & \text{if  }z\ne0, \\ 0 & \text{if } z=0. \end{cases}
$$
If we restrict all attention to real numbers, then this is differentiable at $0$. In fact, it is posisble to show it has derivatives of all orders at $0$ (but that takes a lot more work). However, consider what happens as $w$ approaches $0$ from the imaginary direction. We then conclude that $f$ is not differentiable at $0$ as a function of a complex variable.
The exclusion of functions like this from among those that are differentiable as functions of a complex variable is the reason why the only functions differentiable as functions or a complex variable are quite well behaved, so that some very strong theorems apply to them that do not apply to functions of a real variable.

A: Limits of complex functions approach from "all directions" because we want continuity to mean that $z \approx w$ implies $f(z) \approx f(w)$. You don't get that property if you fix a particular direction.
To wit, let $g$ be any discontinuous function of the nonegative real numbers. Then the function $f$ defined by $f(z) = g(|z|)$ would be 'angularly' continuous,  but it would not be continuous.

That said, it only looks like infinitely many directions when you pretend the complexes are a real plane; in some sense there is only one "complex" direction, and many basic limits are still obvious to compute; e.g.
$$ \lim_{h \to 0} \frac{(z+h)^2 - z^2}{h} = \lim_{h \to 0} \frac{2zh + h^2}{h} = \lim_{h \to 0} (2z + h) = 2z $$

A: If there is $dx$ in denominator, you are taking $x$ in two directions.If there is $d\theta$ in denominator, you are taking $\theta$ in all directions.OK? Then why are you switching back along a line in polar coordinates still?

A: There is one obvious problem with this idea: it doesn't give a sensible definition of "a derivative" at the point $z = 0$. No doubt that could be fixed up in some arbitrary fashion.
A bigger, but less obvious problem, is that this definition won't have many useful properties. The important point about the standard definition is that the limit is the same for any approach to the point $z$, and because of that, you can form a power series approximation to the function (analogous to a Taylor series for real variables) which is valid for all points in a region around $z$, not just for points lying on some particular line in the complex plane.
This leads to the concept of an "analytic function," which is one of the most important theoretical and practical ideas in Complex Analysis. The standard definition of a complex derivative may seem a bit peculiar, but it turns out that it divides complex functions into those that are "well behaved" (and in fact much better behaved than one might initially have guessed) and those that are not well behaved at all.
Of course, for analytic functions, the OP's definition will give the same derivative as the standard definition, but it won't answer the important question of whether the function is analytic or not.


text:
Q: why Thread.currentThread.interrupt() combined with return can stop a current running thread Well, I am trying to understand why the following combination  of Thread.currentThread.interrupt() and return  is working fine, when I want to terminate a current thread.
Thread.currentThread.interrupt();
return;

I write a small program:
public class Interr implements Runnable {
    @Override
    public void run() {
        for(int i= 0; i<10000;i++){
            System.out.println(i);
            if(i==500){
                Thread.currentThread().interrupt();
                return ;
            }
        }

    }
    public static void main(String args []){
        Thread thread = new Thread(new Interr());
        thread.run();
    }
}

I know I can also use Thread.currentThread.stop() but it is an unsafe way to terminate a thread. So I tried to use the combination interupt() and return.
It works but I do not undestand why it works.
Any Explanation?
Edit: in the above example, I am the owner of a Thread. Assume, I am not the owner of a thread. Why This combination is working?

A: You don't need interrupt(). The return is enough to exit run() which will then cause the thread to stop, since it has no more work to do.

A: No need to call interrupt() from same thread.
interrupt method will be used to interrupt a thread from other thread.
as per java docs.

Interrupts this thread. Unless the current thread is interrupting
  itself, which is always permitted, the checkAccess method of this
  thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long),
  or wait(long, int) methods of the Object class, or of the join(),
  join(long), join(long, int), sleep(long), or sleep(long, int), methods
  of this class, then its interrupt status will be cleared and it will
  receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible
  channel then the channel will be closed, the thread's interrupt status
  will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt
  status will be set and it will return immediately from the selection
  operation, possibly with a non-zero value, just as if the selector's
  wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt
  status will be set.
Interrupting a thread that is not alive need not have any effect.

So it will send interrupt signal to the thread which is in I/O block.
@Override
public void run() {

    while (true) {

    }
}

if a thread has implementation like that , it wont interrupt even after calling this method.

A: Actually in the code you posted the reason the thread stops is because you called return.
As per the documentation, calling Thread.interrupt() does nothing more than set a flag on the thread you're calling it on. The owner of the thread checks the flag and must find a way to stop what it is doing.


text:
Q: Exclude folders for the reduces the size of images I have a script that reduces the size of images in folders and subfolders. However, I would like to exclude some of the folders.
I have find the parameter $source_listephotos = Get-ChildItem $source -Recurse | where {$_.FullName -notmatch $exclude_list} but it allows exclude one folder and not several.
$source = "U:\TEST\Compression\images"
$exclude_list = @('Imprimerie')

$source_listephotos = Get-ChildItem $source -Recurse | where {$_.FullName -notmatch $exclude_list}

Do you have a solution ?

A: you can use the exclusion list on get-childitem
$source_listephotos = Get-ChildItem $source -Recurse -exclude $exclude_list| where {$_.FullName}

A: The match/notmach operators use regular expressions (regex) so the easiest solution to fix your code is to use alternation with pipe symbol for your folders' list.
$source = "U:\TEST\Compression\images"
[regex] $exclude_list = "(Imprimerie|TestAnotherName)"

$source_listephotos = Get-ChildItem $source -Recurse | where {$_.FullName -notmatch $exclude_list}


text:
Q: fetching a python or php file appears as sourcecode and not my desired response Js:
fetch('app.py').then(res=>res.text()).then(data=>console.log(data));

Python:
print('helloworld')

console.log() shows print('helloworld') instead of helloworld
Am I not getting something here? I want the Python code to return "helloworld" to the browser's console, but instead it sends the sourcecode. Same with php(note that php --version in cmd sends PHP Warning:'vcruntime140.dll' 14.0 is not compat..). But python appears to have no issues on my pc.
Is my problem in my code? Or what is necessary for the app.py or app.php to run when I fetch it?
Hi, I'm a young programmer, have been trying to add scripts to my server to let client-side send data to server-side, in which server-side's job is to receive and write data into files to my server. Thanks

A: All that code is doing is fetching a local file (app.py) and then printing its contents to the browser console. This isn't how api's work. You can create an api endpoint in Flask (a Python library for writing apis) that will print helloworld to a separate (the server) console, or return it as data. Follow this guide to get you started (you may want to follow the installation instructions first - link on the page) https://flask.palletsprojects.com/en/1.1.x/quickstart/
Your fetch statement will look like this
fetch('/').then(res=>res.text()).then(data=>console.log(data));
your app.py will look as follows:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

I am not familiar with php so afraid I can't give you pointers there.

A: You cannot run Python or PHP files on the client side, this has to be done on the backend. For Python you need to run a script (server) that listens for incoming requests, and on that send a response. The same applies to PHP, you can use web servers like Apache, Nginx, Lighttpd and more to run php.
Seems like you have a static server for files fetching, but again, you cannot request the file and expectate it to run.


text:
Q: Measurability of conditional distribution Let $X,Y$ be discrete random variables from $(\Omega,\mathcal{A},\mathbb{P})$ to  $(\mathbb{R}^n,\mathcal{B}^n)$ and $(\mathbb{R}^m,\mathcal{B}^m)$ respectively.
Define $Q:\mathcal{B}^m\times \mathbb{R}^n \rightarrow [0,1]$ as follows:
$Q(B,x)=\mathbb{P}(Y^{-1}(B) \cap X^{-1}(x))/ \mathbb{P}(X^{-1}(x))$ if $\mathbb{P}(X^{-1}(x))\neq 0$
$Q(B,x)=P(B)$ otherwise ($P$ is a probability on $(\mathbb{R}^m,\mathcal{B}^m)$
Now for fixed $B\in\mathcal{B}^m$, is the function $x\mapsto Q(B,x)$ measurable? If yes, how can I prove it? (my background in measure theory is very limited)
Thank you!

A: Yes, the function $f(x)=Q(B,x)$ is measurable.  There are only countably many values of $x$ such that $\mathbb{P}(X^{-1}(x))\neq 0$ (if there were uncountably many, then you could pick a countable collection such that the values $\mathbb{P}(X^{-1}(x))$ sum to more than $1$).  So, this function $f$ is just defined one way on some countable subset $C\subset\mathbb{R}^n$ and is the constant function with value $P(B)$ on the rest of $\mathbb{R}^n$.  This implies $f^{-1}(S)$ is either countable or cocountable for any set $S$ (since $f^{-1}(S)$ must either contain $\mathbb{R}^n\setminus C$ or be a subset of $C$).  Since any countable or cocountable subset of $\mathbb{R}^n$ is measurable, this means $f$ is measurable.


text:
Q: How do I dynamically add some piece of php code to an exact position in page before it is returned to the browser? I need to add this piece of code right before my wp_head(); call using PHP because the code has to execute server side. Hooking the code into my wp_head(); does not work. I need to add it right before. Here is the PHP code to be added.
gravity_form_enqueue_scripts(1,true);

Here is where the code needs to be inserted:
<?php

/* We add some JavaScript to pages with the comment form
 * to support sites with threaded comments (when in use).
 */
if ( is_singular() && get_option( 'thread_comments' ) )
    wp_enqueue_script( 'comment-reply' );

/* Always have wp_head() just before the closing </head>
 * tag of your theme, or you will break many plugins, which
 * generally use this hook to add elements to <head> such
 * as styles, scripts, and meta tags.
 */

gravity_form_enqueue_scripts(1,true);

wp_head(); ?>

The code should not show on return to browser. How do I add this PHP snippet to this exact location dynamically?

A: I actually needed to :
add_action('wp', 'gforms_add_before_wp_head');

not
add_action('wp_head', 'gforms_add_before_wp_head');

I turns out I just needed to find the right hook to add_action to.


text:
Q: Обновить данные пользователя с Identity Здравствуйте, мне нужно обновить данные пользователя с помощью Identity. Есть такой метод контролера :
[HttpPost]
public async Task<ActionResult> Edit(WDetailsModel model)
{
    if (ModelState.IsValid) {
    try
    {
        var upd_user = new ApplicationUser
        {
            About = model.About,
            City = model.City,
            Country = model.Country,
            FName = model.F_Name,
            LName = model.L_Name,
            WebSite = model.WebSite,
            Phone = model.Phone,
            Email = model.Email,
        };
        var result = await UserManager.UpdateAsync(upd_user);
            if (!result.Succeeded)
            {
                foreach (var err in result.Errors)
                {
                    ModelState.AddModelError("", err);
                }
            }
            else
            {
                ViewBag.Result = "Новые данные сохранены";
                return View();
            }
    }
    catch (Exception ex)
        {
                ModelState.AddModelError("", ex.Message);
        }
    }
    return View(model);
}

Однако при попытке сохранить изменения получаю ошибку :

Name cannot be null or empty.

Если же поставить UserName, тем же что и у текущего User.Identity.Name выпадет ошибка о том, что пользователь с таким именем уже существует. Логично но я же использую UpdateAsync а не CreateAsync. Может вообще все неправильно сделал ? Подскажите. И связанный вопрос - по умолчанию Identity создает 6 таблиц при первом запуске - юзеры, клеймы, роли, миграции и т.д. Вопрос - если мне нужно создать еще несколько таблиц и работать с ними как поступить ? Нужно написать класс-модель этих таблиц ?

A: Ну так если вы пытаетесь у какого-то пользователя изменить имя на то, которое уже занято то и ругается, и так и должно быть, просто используйте уникальные имена.
И да, для ваших личных классов создавайте свои классы модели и прописывайте их в стиле EF Code First
public class ApplicationDbContext : IdentityDbContext
{
    public DbSet<Class1> Class1s { get; set; }
    public DbSet<Class2> Class2s { get; set; }
    // ...
}

Обновлено:
Я обновление делаю обычно так:
ActionResult Edit(UserViewModel userViewModel ) {
   var userOld = db.Users.Find(userViewModel.UserName);
   if(userOld ==null) return null; // тут нужно статус код вернуть
   userOld.Name = userViewModel.Name;
   userOld.SomeField = userViewModel.SomeField;
   // ...
   db.SaveChanges();
}


text:
Q: What's the simplest way to remove a filter with Google Sheets Script, that doesn't pop out an error if there's no active filters at the moment? I managed to automate some calculations with barely any coding experience, but I've hit a snag.
I've been using the code:
spreadsheet.getSheetByName('Formulas & Data').getFilter().remove();

but it doesn't work if there's no active filter in the sheet.
I need an if function so the above code is executed only if there is an active filter.

A: Requirement:
Check if filter is currently applied before removing it.

Code:
function removeFilter() {
  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var filter = sh.getFilter();
  if (filter) {
    filter.remove();
  }
}

As you can see, we define the filter in var filter, then check if it exists in the if statement. If the statement returns true, the filter will be removed, if false, do nothing.

References:

*

*JavaScript if Statements

*getFilter()

*filter.remove()


text:
Q: What is the default GC used in Java 1.7 (45) on Linux Our JVM is HotSpot -64-Bit Server (mixed mode) on Linux.
Looking at the GC logs it seems that ParallelGC is the default. Why isn't CMS the default GC algo? Is it due to the lack of compaction? But that would be the case with parallelGC too.
We notice that a FullGC is not fired even when the heap reaches 75% capacity. When does a full GC fired for the default GC in java 1.7?

A:
Looking at the GC logs it seems that ParallelGC is the default.

It has been since it was added.

Why isn't CMS the default GC algo?

ParallelGC is the fastest for throughput, lowest CPU usage and the easiest to use.

Is it due to the lack of compaction?

That is one issue.

But that would be the case with parallelGC too.

Not such an issue for this GC as it defragments.

We notice that a FullGC is not fired even when the heap reaches 75% capacity. When does a full GC fired for the default GC in java 1.7?

When the JVM cannot allocate memory, even if you have CMS enabled. (Or when System.gc() triggers it to do a full collection)  CMS only fires a major collection of the tenured space when it runs.  There is no CMS for FullGC.


text:
Q: Syscall param read(buf) points to unaddressable byte(s) Ima trying to debug my code using Valgrind, but I do have some problems w/ the read function.
Here is the Valgrind log :
==4333== Syscall param read(buf) points to unaddressable byte(s)
==4333==     at 0x4F0C600: __read_nocancel (in /lib64/libc-2.18.so)
==4333==     by 0x400AB7: my_read (get_next_line.c:132)
==4333==     by 0x400B6C: get_next_line (tmp.c:25)
==4333==     by 0x400B27: main (get_next_line.c:146)
==4333== Address 0x401000 is not stack'd, malloc'd or (recently) free'd
==4333==
==4333==
==4333== HEAP SUMMARY:
==4333==    in use at exit : 4,106bytes in 1 blocks
==4333==  total heap usage: 1 allocs, 0 frees, 4,106 bytes allocated
==4333==
==4333== 4,106 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4333==    at 0x4C277AB: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==4333==    by 0x400A59: my_read (get_next_line.c:129)
==4333==    by 0x400B6C: get_next_line (tmp.c:25)
==4333==    by 0x400B27: main (get_next_line.c:146)
==4333==
==4333== LEAK SUMMARY:
==4333==    definitely lost: 4,106 bytes in 1 blocks

And here is the code :
int    my_read(int fd)
{
  char *str;
  void *buff;
  int   x;

  str = NULL;
  if ((buff malloc(BUFFER_SIZE + 10)) == NULL)
     return (NULL);
  buff = NULL;
  while ((x = read(fd, buff, BUFFER_SIZE)) > 0) //LINE 132
     str = (str == NULL) ? my_strdup(buff) : my_strcat(buff, str);
  return (str);
}

BUFFER_SIZE is defined at 4096.
I understand the error, but I don't know how to carry this.
If you guys could help me fix this up, it would be awesome. Ty.

A: The problem is the
buff = NULL;

statement. After you allocate the space for buffer, you're forgetting that and overwriting it with NULL, and then using that when you call read(). Get rid of that statement.
You also need to free(buff); before you return from the function. Otherwise you'll leak memory every time you call my_read().
And since you return a pointer, the function should be declared:
char * my_read(int fd)


text:
Q: Compiling Java in terminal gives illegal character errors within a string I am new and just trying to do the most basic of all, simple 'Hello World'
Here is the code, The same you find anywhere:
class HelloWorld {
    public static void main (String args[]) {
        System.out.println("Hello World!");
    }
}

When I run in the terminal (I use a Mac) I am posed with the following errors:
HelloWorld.java:3: error: illegal character: '\u201c'
    System.out.println("Hello World!");
                       ^
HelloWorld.java:3: error: ';' expected
        System.out.println("Hello World!");
                        ^
HelloWorld.java:3: error: not a statement
        System.out.println("Hello World!");
                                  ^
HelloWorld.java:3: error: ';' expected
        System.out.println("Hello World!");
                                       ^
HelloWorld.java:3: error: illegal character: '\u201d'
        System.out.println("Hello World!");
                                        ^
5 errors

What is going on here? All the errors are the string!

A: " is the wrong character to use to denote a string - you should use ".

A: "" is not valid String, use "". At your code, Change from
 System.out.println("Hello World!");

To,
System.out.println("Hello World!");

A: " is different from " in Java.
You need to replace "Hello World!" with "Hello World!"


text:
Q: Database Design Suggestion I am building a shopping cart system on my localserver for practice.
Now, I am using sessions to insert the product to the MySQL database, but I am creating a table for each of the sessions. I know this is not an ideal way to do things.
My question:
Should I define a number of rows in the sessions table, so that there will be a maximum number of items added to the cart?
So if I re design the table it would be
User INT NULL,
product_1 INT NULL,
product_2 INT NULL,
...
....

I know that creating a table for each of the orders will only cause problems in the future

A: No, this design will be incredibly difficult to maintain. Instead, have one table that will hold all cart data; something like:
User    Product    Quantity
2       5          1
2       3          3
2       7          1
3       5          2
3       6          2

where the "user" column is a foreign key on the user table (or cart table, whichever), and the "product" column is a foreign key on the product table. That way there is no restriction on the number of unique products in the cart at one time.

A: It would probably be better to check number of items in cart before adding a new item to the database.  If number of cart items is equal to the maximum, then don't allow another item to be added or row to be added to database.  I don't think it is possible to set a maximum number of rows in an SQL table and if it is possible, it probably isn't good practice.
Why not have a single table which holds all cart items (for all users) and store a unique customer ID in the Session variable which references to a row in the SQL cart table.
Something like this...
Columns: CustomerID | ProductID | QTY
Row 1:     1293993933 | 393939399 | 3
Row 2:     1293993933 | 339933992 | 4
Store the customer ID in a session variable ($_SESSION['CustomerID'] if you're using PHP)
Do a select count SQL query each time a product is added to cart.  If it equals maximum allowed cart items, don't allow user to run the insert into SQL command.
Hope this helps


text:
Q: Get UTC epoch time till start of current year in C++ I'm trying to get EPOCH time (universal time without region difference) at start of the current year. Below is what I wrote:
    time_t getEpochTimeAtSOY(){
        /* Get the current year */
        time_t currTime = time(NULL);
        struct tm *aTime = localtime(&currTime);
        int currentYear = aTime->tm_year;   // This is (actualCurrentYear - 1900), so 2020 - 1900 = 120

        /* Now find out EPOCH time for start of currentYear */
        struct tm t;
        time_t timeSinceEpoch = 0;
        memset (&t, 0, sizeof(t));  // Initalize to all 0's
        t.tm_year = currentYear;
        t.tm_mday = 1;

        timeSinceEpoch = timegm(&t); // EPOCH time of 1st Jan <currentYear> 00:00

        return (timeSinceEpoch);
    }

This returns correct result (ie. 1577836800) on x86 or x86_64, but the target board (cross compiler) doesn't support timegm() function. If I use mktime() inplace of timegm(), it results in region time difference. Can someone please suggest an alternative portable solution? Maybe using std::chrono  or something else?

A: I just realized that getEpochTimeFromSOY() is intended to just return the time_t associated with the first of the year, and not do the subtraction between the current time and the first of the year.  Here's that:
std::time_t
getEpochTimeFromSOY()
{
    using namespace date;
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(sys_days{y/1/1} - sys_days{})/1s;
}

This is very easy in C++20, and there is a library to do it with C++20 syntax that works back to C++11 (using chrono).
Here's the C++20 syntax:
#include <ctime>
#include <chrono>

std::time_t
getEpochTimeFromSOY()
{
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(currTime - sys_days{y/1/1})/1s;
}

Here's the header-only, free, open-source library that you can use prior to C++20, and here is the syntax for using it:
#include "date/date.h"

#include <ctime>
#include <chrono>

std::time_t
getEpochTimeFromSOY()
{
    using namespace date;
    using namespace std::chrono;
    auto currTime = system_clock::now();
    auto y = year_month_day{floor<days>(currTime)}.year();
    return floor<seconds>(currTime - sys_days{y/1/1})/1s;
}

I.e. include date.h and add using namespace date.
Explanation of the code:

*

*Get the current time as a system_clock::time_point.

*Get the year of the current time in UTC.

*Subtract the first instant of the year (UTC) from the current time, truncate it to seconds precision, and extract the count by dividing by 1 second.

The syntax 1s was introduced in C++14.  In C++11 you can change that to seconds{1}.  Or you can replace /1s with .count() to extract the seconds as an integral type.
If you would rather not use a free, open-source library to do this, you can grab the underlying algorithms from here and code it yourself.

A: [ Note: this is more of a "design meta-answer". Howard's answer is correct - and I have upvoted it. ]
If I were writing this code, I would instead write two functions getCurrentYear() and epochTimeAtStartOfYear(year y).  Each does a single thing, and can be combined to do what you want, but they also can be used in other contexts.
(Warning - untested code)
std::chrono::year
getCurrentYear()
{
    using namespace std::chrono;
    return year_month_day{floor<days>(system_clock::now())}.year();
}

std::time_t
getEpochTimeFromSOY(std::chrono::year y)
{
    using namespace std::chrono;
    return floor<seconds>(sys_days{y/1/1} - sys_days{})/1s;
}

std::time_t getEpochTimeAtSOY()
{
    return getEpochTimeFromSOY(getCurrentYear());
}


text:
Q: Aggregate rows in Pandas DataFrame I have pandas DataFrame with the following columns:

*

*VisitorID (unique for each user - cookie based)

*VisitNumber (1 = first visit, 2 = second visit and etc...)

*TimeSpentOnVist (visit duration in seconds)

*Channel (the referrer of the visit. ex: Facebook, Google and Bing )

*Media type (paid or organic)

The visitor ID is repeating for each visit (1, 2, 3). I would like to aggregate it considering the last visit for channel and media type, but at the same time, aggregate (summing up) the timespent across all the visits. My goal is to group by the visitorID so there is no duplication.
What is the most efficient way to perform this aggregation in Pandas ?

A: IIUC
df.sort_values(['VisitNumber']).groupby('VisitorID').\
     agg({'TimeSpentOnVist':'sum','Channel':'last','Media type':'last'})

A: Wen answers the aggregation question, but I'd also create a MultiIndex to organize the DataFrame:
 df.set_index(['VisitorID','VisitNumber']).sort_index()


text:
Q: focus() will not work I am at a loss here, never had a problem with this before.
I cannot get focus() to work at all in any browser.  I'm using jquery and can't even get it to work with standard javascript. I tried adding the timeout as well but still nothing.  All I get in the alert is "undefined".
Here is the input
<input type="text" name="SearchBox" id="SearchBox" class="SearchBox" />

and here is the jquery
$(document).ready(function(){
    setTimeout(function(){
        $("#SearchBox").focus();
    }, 0);
    alert($("*:focus").attr("id"));
});

I've stripped the page down to just the above in case something was interfering with it but still no success.  It has to be something simple I'm missing!!!!

A: The searchbox will not get the focus until the document ready handler completes.
When you call setTimeout, even if the timeout is set to zero, JavaScript will not handle that timeout until the current function is complete. This is because JS is single threaded.
Calling setTimeout with a timeout of zero is like saying "Here's something I'd like you to do, once this function has completed."
Hence, the searchbox won't get focus until after the alert is called.
An example

A: try this..
$(document).ready(function(){
    setTimeout(function(){
        $('#SearchBox').focus();
    },0);
    $(":input").focus(function(){
        alert($(this).attr("id"));
    });
});


text:
Q: Has anyone been successful in implementing google optimize in a SPA React App? I am fairly new to the Google Analytics Suite and am currently trying to integrate Google Optimize for A/B testing in a react app.
I have gotten to the point where the variant changes display on the desired web page, but only in Preview mode, and am stumped as to how to proceed to viewing the variant changes on a live site.
So far:

*

*google optimize scripts are installed in app
<style>.async-hide { opacity: 0 !important} </style>
<script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'GTM-XXXXXXX':true});</script>

*ga tracking is setup using ReactGA

*GTM is setup and is firing tags to track

*firing google optimize experiments on custom activation event and using dataLayer to push new events
const initializeReactGa = () => {
  console.log('called to initialize react ga');
  ReactGA.initialize(config.gaTag)
  ReactGA.ga('require', config.optimizeTag);
  ReactGA.pageview(window.location.pathname + window.location.search);
}
const googleOptimizeLoader = () => {
  console.log('called google optimize loader');
  if(window.dataLayer) {
    window.dataLayer.push({'event': 'optimize.activate'})
  }
}
The problem

*

*unable to see variant changes in live site (without preview running)

Any help is appreciated.
TIA
Nayyir
[SOLVED]
Was able to determine the issues were not with the setup. The issue was that google optimize's cookie management was unable to set the required cookie for the expirement on localhost:3000, but rather a custom domain pointing to localhost, similar to XXXX.local:3000.

A: This might be what you are looking for
How to Add Google Optimize A/B Testing to Your React App in 10 Lines of Code


text:
Q: Magento2 programatically create coupon code error I have a code I have used in the past. However now I have a cms page that calls in the phtml file and when I then try to go to the page in my browser i just get an error saying "an error occurred while trying to generate this content. Which is not very informative.
I am hoping someone might be able to spot the error (second pair of eyes sometimes help)
I know it is not best practice to use the ObjectManager. I just need this to work and be backwards compatible with something else it is doing later on in this file.  Anyway the error seems to be generated after trying to render the below lines. It is something about the first 3 lines that is triggering an error
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$state->setAreaCode('adminhtml');

$coupon['name'] = "Warranty test code";
$coupon['desc'] = "Warranty Code For";
$coupon['start'] = date('Y-m-d');
$coupon['end'] = '';
$coupon['max_redemptions'] = 1;
$coupon['discount_type'] ='by_fixed';
$coupon['discount_amount'] = 15;
$coupon['flag_is_free_shipping'] = 'no';
$coupon['redemptions'] = 1;
$coupon['code'] ='AUG92022TEST';

$shoppingCartPriceRule = $objectManager->create('Magento\SalesRule\Model\Rule');
$shoppingCartPriceRule->setName($coupon['name'])
      ->setDescription($coupon['desc'])
      ->setFromDate($coupon['start'])
      ->setToDate($coupon['end'])
      ->setUsesPerCustomer($coupon['max_redemptions'])
      ->setCustomerGroupIds(array('0','1','2','3'))
      ->setIsActive(1)
      ->setSimpleAction($coupon['discount_type'])
      ->setDiscountAmount($coupon['discount_amount'])
      ->setDiscountQty(1)
      ->setApplyToShipping($coupon['flag_is_free_shipping'])
      ->setTimesUsed($coupon['redemptions'])
      ->setWebsiteIds(array('1','2','6','7'))
      ->setCouponType(2)
      ->setCouponCode($coupon['code'])
      ->setUsesPerCoupon(NULL);
 $shoppingCartPriceRule->save();

 echo "created";

A: I don't see any critical issues with this code, just small mistakes which should not affect to save.
Make sense to emulate environment if you want to apply observers or plugins. Make sense to catch and log/handle errors.
Try following code (I've changed few coupon arguments for verify in my environment)
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$logger        = $objectManager->get(\Psr\Log\LoggerInterface::class);
$emulation     = $objectManager->get(\Magento\Store\Model\App\Emulation::class);
$emulation->startEnvironmentEmulation(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
try {
    $coupon['name']                  = "Warranty test code";
    $coupon['desc']                  = "Warranty Code For";
    $coupon['start']                 = date('Y-m-d');
    $coupon['end']                   = '';
    $coupon['max_redemptions']       = 1;
    $coupon['discount_type']         = 'by_fixed';
    $coupon['discount_amount']       = 15;
    $coupon['flag_is_free_shipping'] = 0;
    $coupon['redemptions']           = 1;
    $coupon['code']                  = 'AUG92022TEST';

    $shoppingCartPriceRule = $objectManager->create(\Magento\SalesRule\Model\Rule::class);
    $shoppingCartPriceRule->setName($coupon['name'])
        ->setDescription($coupon['desc'])
        ->setFromDate($coupon['start'])
        ->setToDate($coupon['end'])
        ->setUsesPerCustomer($coupon['max_redemptions'])
        ->setCustomerGroupIds(['0', '1', '2', '3'])
        ->setIsActive(1)
        ->setSimpleAction($coupon['discount_type'])
        ->setDiscountAmount($coupon['discount_amount'])
        ->setDiscountQty(1)
        ->setApplyToShipping($coupon['flag_is_free_shipping'])
        ->setTimesUsed($coupon['redemptions'])
        ->setWebsiteIds(['1', '4', '7'])
        ->setCouponType(2)
        ->setCouponCode($coupon['code'])
        ->setUsesPerCoupon(0);
    $shoppingCartPriceRule->save();
} catch (\Exception $e) {
    $logger->critical($e);
} finally {
    $emulation->stopEnvironmentEmulation();
}

If you still have the issue, please see var/log/system.log and provide exception.


text:
Q: Ordering sub-collections in an EF/LINQ query I am having trouble figuring out how (and where) to order a subcollection in a LINQ/EF query.
Basically I have a collection of SubscriptionTypes, each having its own collection of Subscriptions. I would like each Subscription in the collection to be ordered by NumberOfMonths.
Here is my current query:
    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           select a;
}

I would like the Subscriptions to be ordered by NumberOfMonths. I tried this:
    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
    {
        return from a in db.SubscriptionTypes.Include("Subscriptions")
               where a.Subscriptions.OrderBy(q => q.NumberOfMonths).Any(x => x.PropertyCode == propertyCode)
               select a;
    }

.. but that did not order the subscriptions correctly.
Does anybody know of an easy way to do this?
UPDATE: SubscriptionType and Subscription are types generated by the EF designer.
Thanks,
Adam

A: Change your select part to sth like this
   select new SubscriptionType{ ?,?,?,
                    Subscriptions = a.Subscription.OrderBy(b=>b.?)}

A: You can change your existing query to this, and it should do what you're looking for.
public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           order by a.NumberOfMonths descending
           select a;
}

Obviously, descending could be ascending if that's what you want.


text:
Q: How to activate full screen control DOTS (SDK14) Does anybody know what i mean?
In fullscreen mode of the new camera app on my galaxy nexus the control buttons are changing into 3 dots.
How can i activate that programmatically?

A: You can use
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);

within your activity.
See View.SYSTEM_UI_FLAG_LOW_PROFILE

A: It's a standard Options Menu.  On 3.0+ it creates those dots, in 2.3.3- you access it with the menu key.
http://developer.android.com/guide/topics/ui/menus.html


text:
Q: Intermittent SQL Server ODBC Timeout expired We have a bunch of VB6 applications that access two different database servers (both 32-bit windows 2003, one SQL Server 2000, one SQL Server 2005). About every ten minutes or so, we are getting a few errors:

[Microsoft][ODBC SQL Server Driver]Timeout expired
[Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.
[Microsoft][ODBC SQL Server Driver]ConnectionRead()

This is happening on more than a dozen different computers at random times. We also have IP phones that all run through the same network and those are not having any problems. We can also VNC into a users computer and reproduce the error they were getting, but VNC still continues to work. Email also works. It just seems to be an ODBC connection to SQL Server that causes the issue. The errors happen for both of our SQL Servers. We have scoured google, but haven't been able to come up with a solution. Is there anything we can try to diagnose the problem? Is there any fix out there?
Update:
We have no internal firewalls on either the servers or clients. We connect through TCP/IP via the dns name of the server (also have tried IP address).
One server has Windows 2003 SP2 and the other doesn't.
The strange thing is that it has worked fine for years and now all of a sudden these errors are happening. Nothing has changed on those servers for quite some time. That leads us to beleive it is a bad switch, but that seems unlikely since nothing else (email, phones, vnc, file server, etc) all work without problems.

A: Take a look at this Microsoft Knowledge Base article.
Some problems occur after installing Windows Server 2003 SP2
I would also suggest that you switch to an OLE DB provider.  In my experience, it's faster than ODBC and more reliable too.
Connection Strings
Scroll down to: SQL Native Client OLE DB Provider

A: Are you using non-default instances? Or do you have internal firewalls?
We changed to "server.fqdn.tld\instance,port" to avoid this exact (IIRC) intermittent connection issue from clients behind internal firewalls.
Only SQL connections were affected.

A: We never did figure out why this was happening. We upgraded our server to SQL Server 2008 and the error messages stopped.

A: I recently came across a very similar problem and posted it here.
ScottE found the solution.


text:
Q: How to filter ng-repeat data by time range? I'm creating a app which will give flight list using third party API. I have a problem filtering between two time from different date and time format, I have gone thorough lot of tutorials but there are all using date only but I need to filer using time from different date and time format.
JSON
"Combination": [
    "OutboundLeg" :{
            "DepartureDateTime": "07/14/2015 12:00"
    }
    "OutboundLeg" :{
            "DepartureDateTime": "07/15/2015 10:55"
    }
    "OutboundLeg" :{
            "DepartureDateTime": "07/18/2015 12:10"
    }
    "OutboundLeg" :{
            "DepartureDateTime": "07/14/2015 10:10"
    }
    "OutboundLeg" :{
            "DepartureDateTime": "07/18/2015 12:00"
    }
]

HTML

    {{data.OutboundLeg.DepartureDateTime}}

How to achive this?

A: First the data that you have is not correct, since you have an object that has the same key, only the last value of OutboundLeg will be taken into account. You have an array with one object, that has the same key multiple times.
You need an array of objects, because angular filters work only on arrays.
The template:

The filter:
function dateFilter() {
  return function(input, start, end) {
    var inputDate = new Date(input),
        startDate = new Date(start),
        endDate = new Date(end),
        result = [];

    for (var i=0, len = input.length; i < len; i++) {
        inputDate = new Date(input[i].DepartureDateTime);
        if (startDate < inputDate && inputDate < endDate) {
           result.push(input[i]);
        }
    }
    return result;

  }
}

The full code can be found in the fiddle I've created with a small update on the array, that filter the dates between a start and end date defined. You can adjust this as needed for you example.
Fiddle - filter between two dates
Update - filter on ng-repeat

A: You can use the date filter which allows you to format a date based upon a requested format style. The date formatter provides several built-in options.
If no date format is passed, then it defaults to showing mediumDate (as you can see below).
Here are the built-in localizable formats:
{{ data | date:'medium' }}
{{ data | date:'short' }}
{{ data | date:'fullDate' }}
{{ data | date:'longDate' }}
{{ data | date:'mediumDate' }}
{{ data | date:'shortDate' }}
{{ data | date:'mediumTime' }}
{{ data | date:'shortTime' }}

So you can try this:

    {{data.OutboundLeg.DepartureDateTime}}

A: You can use a function as filter like this
HTML

{{c.name}}

CONTROLLER
$scope.ofYear = function(year) {
  return function(c) {
    return c.date.getFullYear() === year;
  }
}

http://plnkr.co/edit/vxIewUDGDjiz80W1Itag?p=preview


text:
Q: Stack Exchange Web Banners Are there any web banners I can use to promote Stack Overflow, Server Fault, etc.?
I don't want to use a flair banner.

A: Hmm, we don't have any banners per se, but I am OK with using the logos -- as long as they are linked back to the site.
We also now have an official logos page:
https://stackexchange.com/about/logos


text:
Q: Scala for ( ) vs for { } I'm trying to understand for comprehensions in Scala, and I have a lot of examples that I sort of understand...
One thing I'm having a hard time figuring out is for ( ) vs for { }. I've tried both, and it seems like I can do one thing in one but it breaks in the other.
For example, this does NOT work:
def encode(number: String): Set[List[String]] =
  if (number.isEmpty) Set(List())
  else {
    for (
      split <- 1 to number.length
      word <- wordsForNum(number take split)
      rest <- encode(number drop split)
    ) yield word :: rest
  }.toSet

However, if you change it to { }, it does compile:
def encode(number: String): Set[List[String]] =
  if (number.isEmpty) Set(List())
  else {
    for {
      split <- 1 to number.length
      word <- wordsForNum(number take split)
      rest <- encode(number drop split)
    } yield word :: rest
  }.toSet

These examples are from a Coursera class I'm taking. The professor didn't mention the "why" in the video & I was wondering if anyone else knows.
Thanks!

A: From the syntax in the spec, it might seem that parens and braces are interchangeable:
http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#for-comprehensions-and-for-loops
but because the generators are separated by semis, the following rules kick in:
http://www.scala-lang.org/files/archive/spec/2.11/01-lexical-syntax.html#newline-characters
I have read and understood that section in the past, from which I vaguely recall the gist that newlines are enabled in the braces, which is to say, a newline char is taken as nl which serves as a semi.
So you can put the generators on separate lines instead of using semicolons.
This is the usual "semicolon inference" that lets you not write semicolons as statement terminators.  So the newline in the middle of the generator is not taken as a semi, for instance:
scala> for (c <-
     | List(1,2,3)
     | ) yield c+1
res0: List[Int] = List(2, 3, 4)

scala> for { c <-
     | List(1,2,3)
     | i = c+1
     | } yield i
res1: List[Int] = List(2, 3, 4)

A: In Scala () are usually for when you only have one statement. Something like this would have worked:
def encode(number: String): Set[Int] =
  if (number.isEmpty) Set()
  else {
    for (
      split <- 1 to number.length // Only one statement in the comprehension
    ) split
  }.toSet

Add one more and it would fail to compile. The same is true for map for example
OK
List(1,2,3).map(number =>
  number.toString
)

Not OK (have to use curly braces)
List(1,2,3).map(number =>
  println("Hello world")
  number.toString
)

Why that is. I have no idea :)


text:
Q: How do I compare two edge-images (in OpenCV)? in my project i need to compare to images. One image shows a render-model and the other image is a photo, in which the real object, which is represented in the model, is shown. What i exactly want:

*

*The algorithm has to compare the two images and return a number, that describes the similarity. Let's say the lower the number is, the better the images fit together.

*Both images are represented as binary images which only contain the contours / edges of the real render-image / photo.

*The photo has a lot more objects in it than the render-image. So i only want to check if the viewpoint to the render-object is nearly the same than the viewpoint to the real object in the photo. (Example: A car is modelled so it approximates a real car. I take a photo of the real car from a special position and orientation. Now i want to check, if the position and orientation of my virtual camera looking at the render-car is nearly the same, than the position and orientation of my real-life-camera). The solution is only to compare the white pixels of the render image to the pixels of the photo (as edge-image). The other pixels are not interesting.

*The returned value of the image-comparision should decrease the better my orientation and position of the virtual camera fits to the real camera's orientation and position.

I tried to calculate the euclidian distance of the two images but the result is only good, when the pixels exactly fit to each other. Now i am searching for alterantives.
Until now i considered to use the normalized cross-correlation, but i really dont know if it fits to my task.
The question is, if the normalized cross-correlation is worth a try or if there are better methods of solving my problem!
The algorithm should be as fast as possible, because i compare a lot of images.
Thanks a lot

Thanks for your suggestions. I am a little confused due to the fact that the normalized cross-corellation and Haussdorff distance seem to be good for finding a small pattern in a big picture.
The question is: Are the two algorithms also good for comparing 2 pictures of the same size?
Here is an example of 2 images that have to be compared. At the moment i am comparing around 120 pictures-paires a second.
Too bad that i cannot post images as a new user. So here is the direct link:
http://s14.directupload.net/file/d/2674/t8qzbq9i_png.htm

A: How about experimenting with the Haussdorff distance as a starting point? General idea and c implementation here. Article here:

Comparing images using the Hausdorff distance, by DP Huttenlocher - 1993.

A: You could also check-out cosine similarity. I used it with great success on detecting cut-scenes in a video stream. Essentially, you treat the entire image as a 1D vector, and proceed with the cosine similarity measure. Basically, small angles mean a close match, and large values mean there is a mismatch. The thresholds would need some tuning for your dataset, but it might work, and it's very fast.
Normalized cross-correlation should be more robust, but it will take a bit more time. Since you mentioned needing to handle different poses you should also look at a feature detection and extraction solution. Have a look at opencv's matcher_simple.cpp and matching_to_many_images.cpp samples. These techniques have some tolerance for scale and rotation differences.
Hope that's helpful!


text:
Q: Importing code and running from terminal problem I am relatively new to Python and I am having some Python code which is organised under separate subfolders, each of which has a init.py file. However, when I run the code, I have two issues (see image example with link at the end of the text):

*

*When I attempt to import code (called data_utils) under e.g. subfolder "utils" from a code (called  base_loader) which is under subfolder "loaders", none of the sobfolders and codes is recognised. I have followed similar topics in the community, and double checked that all subfolders contain init.py files, but still can't figure out what's going wrong.

*When I attempt to run an experiment calling (all the interconnected codes) using the "python3 experiment.py" code from the terminal, I get an invalid syntax error which I really don't understand why! I double checked my spelling and whether the code is listed under the path, but nothing works.
Any ideas would be so much appreciated as I am stuck!
See Image Example


text:
Q: PHP variable scope after multiple includes Let's say I hava a page index.php and in it I execute:
require_once("file1.php");
echo $myVar;

in file1.php I have:
require_once("file2.php");

and in file2.php I have
$myVar = "test";

After executing this script, index.php can't get to $myVar and outputs undefined variable.
Any reason on that ?

A: require/include act as if the contents of the file being included were literally cut/pasted into the place where the include directive is. Your variable will work, unless something else is trashing it between the include calls.
e.g.
core.php:
<?php
$foo = 'bar';

file1.php:
include('core.php');
$foo = 'baz';

file2.php
echo $foo; // undefined
include('core.php');
echo $foo; // outputs bar
include('file1.php');
echo $foo; // outputs baz


text:
Q: How to store multiple datatypes in an array? I'm looking for something like an Array, but it needs to store multiple data types. The Oracle Java tutorials says, "An array is a container object that holds a fixed number of values of a single type." So if I can't use an array for multiple types, what do I use?
I've got this code that only adds one marker to the map at a time because it writes over my lat and long values each loop and only passes the last to the onPostExecute. So I will need something like an array to pass multiple forms of contact info. ie I'm pulling the location from each JSON string, but I need to pull and pass the name & phone number too to the UI from this background thread.
try {

    String apples = endpoint.listContactInfo().execute().toString();

    JSONObject jObject = new JSONObject(apples);

    JSONArray jsonArr = jObject.getJSONArray("items");

     for(int i =0 ; i<jsonArr.length() ;i++ ){
         JSONObject jsonObj1 = jsonArr.getJSONObject(i);

                    // Storing each json item in variable
                    String id = jsonObj1.getString(TAG_ID);
                    String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
                    String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
                    String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
                    String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
                    String phone1 = jsonObj1.getString(TAG_PHONE);

                    //test to see if made it to string
                    Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);

                       address = coder.getFromLocationName(streetAddress1,5);

                        Address location1 = address.get(0);

                        // SET LAT LNG VALUES FOR MARKER POINT

                     lati = location1.getLatitude();
                         longi = location1.getLongitude();

                         Log.d("Location", "Location:" + lati + " " +  longi);

     }

    } catch (IOException e) {
    e.printStackTrace();
  } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
      return (long) 0;

    }
         // ADD MARKER TO MAP UI
    protected void onPostExecute(Long result) {
        mMap.addMarker(new MarkerOptions()
        .position(new LatLng(lati, longi))
         .title("Hello world"));
    }

A: You can create an array of your Custom-Class.
public class YourCustomClass {

     String id;
     String name;
     double longitude;
     // and many more fields ...

    public YourCustomClass() {  // constructor

    }

    public void setID(String id) {
        this.id = id;
    }

    public String getID() {
        return id;
    }

    // and many more getter and setter methods ...
}

Inside your custom-class you can have as many fields as you want where you can store your data, and then use it like that:
// with array
YourCustomClass [] array = new YourCustomClass[10];
array[0] = new YourCustomClass();
array[0].setID("yourid");

String id = array[0].getID();

// with arraylist
ArrayList<YourCustomClass> arraylist = new ArrayList<YourCustomClass>();
arraylist.add(new YourCustomObject());
arraylist.get(0).setID("yourid");

String id = arraylist.get(0).getID();

You can also let the AsyncTasks doInBackground(...) method return your Custom-class:
protected void onPostExecute(YourCustomClass result) {
 // do stuff...
}

Or an array:
protected void onPostExecute(YourCustomClass [] result) {
 // do stuff...
}

Or a ArrayList:
protected void onPostExecute(ArrayList<YourCustomClass> result) {
 // do stuff...
}

Edit: Of course, you can also make a ArrayList of your custom object.

A: You should consider the use of the typesafe heterogeneous container pattern.
There the data is stored in a Map<Key<?>, Object> and access to the map is hidden behind generic methods, that automatically cast the return value.
public <T> T getObjectByKey(Key<T> key)
  return (T) map.get(key);

The same for put.

A: You can use an ArrayList.
ArrayList<Object> listOfObjects = new ArrayList<Object>();

And then add items to it.
listOfObjects.add("1");
listOfObjects.add(someObject);

Or create your own object that encapsulates all the field that you require like
public class LocationData {
   private double lat;
   private double longitude;

   public LocationData(double lat, double longitude) {
       this.lat = lat;
       this.longitude = longitude;
   }
   //getters
   //setters
}

and then add your lat/long pairs to an ArrayList of type LocationData
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();

listOfObjects.add(new LocationData(lat, longitude));

A: The most simplistic way of storing objects of different data types is just by declaring the type of your Array(or Collection) as an "Object".
Object[] arr = new Object[10];
   arr[0] = "ab";
   arr[1] = 2;
   arr[2] = 2.3;

Java.lang.Object class is the root or superclass of the class hierarchy. All predefined classes and user-defined classes are the subclasses from the Object class. So, objects of all other classes are also of type "Object" and hence can be stored.


text:
Q: Split 1 column into multiple columns with up to 500 cells each In Google Sheets, I have a column that is arbitrarily long.
I want to split this column into separate columns of length 500.
How can I do this?
Some things I've been thinking may be involved in a solution:

*

*TRANSPOSE

*ARRAY_CONSTRAIN

A: Arrayformula, an example for number 5, change to 500.
=ArrayFormula(IFERROR(
  vlookup(
   (TRANSPOSE(ROW(INDIRECT("a1:a"&ROUNDUP(COUNTA(A:A)/5))))-1)*5 + ROW(INDIRECT("a1:a"&5)),
  {ROW(A:A),A:A},2,)
))

*

*ROUNDUP(COUNTA(A:A)/5 the number of columns. Up because the last column may contain less than N rows.

*TRANSPOSE(...)*5 + ROW(INDIRECT("a1:a"&5)) to get matrix of numbers.

Matrix:
1   6   11  16
2   7   12  17
3   8   13  18
4   9   14  19
5   10  15  20

*

*{ROW(A:A),A:A} to get the number of a row and value to return

*vlookup to return a value

*IFERROR to show "" if error.

A: Having an arbitrarily long column implies you'll need arbitrarily many columns for the split, and spreadsheet formulas cannot create new columns. So the best we can is to use all columns available.
Assuming the data column begins with cell A1, and the  upper left corner of the range in which it should be split is B1, the following formula will work, if you fill the first 500 rows of the sheet with it:
=offset($A$1, row()-row($B$1) + 500*(column()-column($B$1)), 0)

Otherwise, change A1 and B1 to the top source and upper-left corner of destination.
Explanation: the offset moves from A1 down by the specified amount, which increments by 1 with every row and by 500 with every column.

A: You could also use this formula:
=ARRAYFORMULA(
    TRIM(
        SPLIT(
            TRANSPOSE(
                SPLIT(
                    QUERY(
                        <long_column_range> & "," & IF(
                            MOD(1, <columns>) = 0, "|", ""
                        ),, 9^9
                    ), "|"
                )
            ), ","
        )
    )
)

where:

*

*<long_column_range> is the range of the long column that you want to split (e.g. A1:A) and

*<columns> is the number of columns that you want for the long column to be split into.

Taken from this article.


text:
Q: peer node start => Cannot dial to 0.0.0.0:7050, because of grpc: timed out when dialing Can someone suggest how to resolve error, Cannot dial to 0.0.0.0:7050, because of grpc: timed out when dialing, when running peer node start.

2017-01-01 16:48:24.391 UTC [committer] initDeliver -> ERRO 097 Cannot dial to 0.0.0.0:7050, because of grpc: timed out when dialing
  2017-01-01 16:48:24.392 UTC [committer] startDeliver -> ERRO 098 Can't initiate deliver protocol [grpc: timed out when dialing]

I am also getting error when running :
peer chaincode deploy -n mycc -c '{"Args": ["init", "a","100", "b", "200"]}'

Error: Error getting broadcast client: Error connecting to 0.0.0.0:7050 due to grpc: timed out when dialing

A: Seems like you are using the wrong port for grpc. 7050 is the REST port for the peer. The default grpc port is 7051.


text:
Q: Geometric interpretation of the Kronecker product? Is there any geometric interpretation of the Kronecker product of two $2\times 2$ matrices?

A: It pays to notice that the Kronecker product is really the tensor product acting on operators: if $f: A \to B$ and $g: X \to Y$ are linear mappings, then $f \otimes g: A \otimes X \to B \otimes Y$ is given by the Kronecker product in any bases of the form $a_i \otimes x_j$, $b_k \otimes y_l$, where $\{x_i\}$ is the basis of $X$ etc.
Now consider a pure vector $a \otimes x \in A \otimes X$. By definition we have $(f \otimes g)(a \otimes x) = f(a) \otimes g(x)$. E.g. if $B = Y$ and $g = 1$, we have $(f \otimes 1)(a \otimes x) = f(a) \otimes x$, so the "$X$ part" is untouched.
Thus, at least when both $f$ and $g$ are endomorphisms you can picture $f \otimes g = (f \otimes 1) \circ (1 \otimes g) = (1 \otimes g) \circ (f \otimes 1)$ as acting independently on factors of its domain by $f$ and $g$ respectively. This is obviously a corollary of $(f \otimes g)(a \otimes x) = f(a) \otimes g(x)$, which remains true in general.


text:
Q: Programmatically Set First Image as Featured I have over 400 posts with images inside them, I have got a new template which requires a featured image for each post, something my last template did not require... I am wondering if there is a script I can add to my functions.php to be able to grab the first image in each post and set it as the featured... So far i have found this, but it is not working...
function auto_set_featured() {
global $post;
$has_thumb = has_post_thumbnail($post->ID);
if (!$has_thumb)  {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
    if ($attached_image) {
        foreach ($attached_image as $attachment_id => $attachment) {
            set_post_thumbnail($post->ID, $attachment_id);
        }
    }
}
}
add_action('the_post', 'auto_set_featured');
add_action('save_post', 'auto_set_featured');
add_action('draft_to_publish', 'auto_set_featured');
add_action('new_to_publish', 'auto_set_featured');
add_action('pending_to_publish', 'auto_set_featured');
add_action('future_to_publish', 'auto_set_featured');

This script will work for new posts, but i need it to affect all my older posts, any suggestions?

A: Regarding the code you posted, I would say some things:

*

*you can avoid using 6 different actions because one is enough: 'save_post' is triggered everytime a post is created or updated

*you can drop globalize $post: 'save_post' will pass the post id, you can use it, in addition, preparing the function to receive an argument will help you to run the same function programmatically

The edited version of your code becomes:
function auto_set_featured( $post = NULL ) {
  // retrieve post object
  $post = get_post( $post );
  // nothing to do if no post, or post already has thumbnail
  if ( ! $post instanceof WP_Post || has_post_thumbnail( $post->ID ) )
     return;
  // prepare $thumbnail var
  $thumbnail = NULL;
  // retrieve all the images uploaded to the post
  $images    = get_posts( array(
    'post_parent'    => $post->ID,
    'post_type'      => 'attachment',
    'post_status'    => 'inherit',
    'post_mime_type' => 'image',
    'posts_per_page' => 1
  ) );
  // if we got some images, save the first in $thumbnail var
  if ( is_array( $images ) && ! empty( $images ) )
     $thumbnail = reset( $images );
  // if $thumbnail var is valid, set as featured for the post
  if ( $thumbnail instanceof WP_Post )
     set_post_thumbnail( $post->ID, $thumbnail->ID );
}

add_action( 'save_post', 'auto_set_featured' );

Now, the only thing you need for old posts, is to retrieve them with a query and then run the same function for every post.
Just keep attention to perform the task only once: it's a very time & resource consuming task, so it should be ran only once, possibly on backend.
I'll use a transient for the purpose:
add_action( 'admin_init', function() {

  if ( (int) get_transient(' bulk_auto_set_featured' ) > 0 )
     return;

  $posts = get_posts( 'posts_per_page=-1' ) ;
  if ( empty( $posts ) )
    return;

  array_walk( $posts, 'auto_set_featured' );

  set_transient( 'bulk_auto_set_featured', 1 );
});

After adding this code to your functions.php or to a plugin, log in the backend, and prepare yourself to wait some seconds before the dashboard appear, but after that all post should have a thumbnail, at least every post that has an image uploaded in it.
If everything goes as it should you can the remove the last code snippet keeping only the first.
Note my code require php 5.3+

A: Use this code in your child themes functions file and them regenerate thumbnails
function wpsites_auto_set_featured_image() {
      global $post;
      $featured_image_exists = has_post_thumbnail($post->ID);
          if (!$featured_image_exists)  {
          $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                      if ($attached_image) {
                            foreach ($attached_image as $attachment_id => $attachment) {
                            set_post_thumbnail($post->ID, $attachment_id);
                            }
                       }
                    }
  }
add_action('the_post', 'wpsites_auto_set_featured_image');

A: "Set All First Images As Featured" worked for me.
With a hack it could reverse the operation.
Easy Add Thumbnail may also do the trick, and the pro version of Quick Featured Images does it, and I think I saw another plugin that does this when I searched.

A: Simple Function Code
 //Set First Image as FeaturedImage
add_action('add_attachment', 'set_first_as_featured');
add_action('edit_attachment', 'set_first_as_featured');
function set_first_as_featured($attachment_ID)
  {
   $post_ID = get_post($attachment_ID)->post_parent;
   if (!has_post_thumbnail($post_ID)) {
    set_post_thumbnail($post_ID, $attachment_ID);
  }
}

A: I have had to develop the same functionality. On my case, I had to set the featured images according one posts category.
Here you have the code you must insert in a template of your current theme. This template must be called, for example: 'page-set-images.php' (if you need it you have more information about how creating pages templates here):
<?php

/* In the URL of the page 'set-images', put as parameter 'setting = 1' to
   set, as featured image of the posts of the category entered that do not
   have featured image, the first image shown in each post. */

echo 'In the URL of the page put as parameter "setting = 1" to set,
as a featured image of the posts of the category entered that do not have
featured image, the first image shown in each post.';

$setting = isset($_GET['setting']) ? $_GET['setting'] : '';

if($setting == 1){
    get_posts_by_category();
}

/**
 * We get all the posts in a category. To enter the category, you have to change
 * the value of the key 'category-name' by the corresponding slug.
 *
 * @author Sergio Lovillo
 * @return bool
 */

function get_posts_by_category():bool{

    $args = array(
        'posts_per_page' => '-1',
        'category_name' => 'category-slug'
    );
    $posts = get_posts($args);

    if(isset($posts) && !empty($posts)){
        get_posts_first_image($posts);
    }
    return true;
}

/**
 * We check if each post in the category entered has a featured image; If the
 * post doesn't have it, we get the URL of the first image shown in the post.
 *
 * @author Sergio Lovillo
 * @param array $posts
 * Array containing all posts in the category entered
 * @return bool
 */

function get_posts_first_image(array $posts):bool{

    $posts_without_thumbnail = 0;
    $changed_posts_total = 0;

    foreach($posts as $post){

        $featured_image_exists = has_post_thumbnail($post->ID);

        if(isset($featured_image_exists) && empty($featured_image_exists)){

            $posts_without_thumbnail++;
            $doc = new DOMDocument();
            $doc->loadHTML(apply_filters('the_content', $post->post_content));
            $xpath = new DOMXPath($doc);
            $src = $xpath->evaluate("string(//img/@src)");

            if(isset($src) && !empty($src)){
                $res = set_posts_featured_images($src, $post->ID);
            }
            if($res){
                $changed_posts_total++;
            }
        }
    }
    echo '
---
Total posts: ' . count($posts) . '.
Posts without
    featured image: ' . $posts_without_thumbnail . '.
Total modified
    posts:' . $changed_posts_total . '.';
    return true;
}

/**
 * We remove the width and height of the URL of the first image shown in the
 * post. Then we get the ID of the image based on its URL. Finally, we set the
 * first image displayed in the post as its featured image, using the post ID
 * and the image ID.
 *
 * @author Sergio Lovillo
 * @param string $firs_image_url
 * String that contains the URL of the first image shown in the post.
 * @param int $post_id
 * Post ID.
 * @return bool
 */

function set_posts_featured_images(string $first_image_url, int $post_id):bool{

    $first_image_formatted_url = preg_replace('/-\d+x\d+(?=\.[a-z]{3,4}$)/i', '', $first_image_url);
    $first_image_url_id = attachment_url_to_postid($first_image_formatted_url);
    $res = false;
    $featured_image_total = 0;

    if(isset($first_image_url_id) && !empty($first_image_url_id)){
        $res = set_post_thumbnail($post_id, $first_image_url_id);
    }
    return $res;
}

?>

As well, you will have to publish one page with this slug on my example: 'set-images'. Once the page is published, you must go to that page on your browser and add as parameter 'setting=1'. So, on my example it would be: https://domain.com/set-images/?setting=1.
Also, once executed the script, on the page you will be able to see the total of posts of the category, the total of posts of that category without featured image and the total of modified posts.


text:
Q: windows service project The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration' I'm coding a Windows Service.
I added the dll and namespace as shown below .
using System.Configuration;
//This line cause error but why ?
var settings = System.Configuration.ConfigurationManager.AppSettings;
Error:The type or namespace name 'ConfigurationManager' does not exist in the namespace 'System.Configuration'
Project Target is v4.0 and I successfully install and start service
Thanks.

A: appSettings is a readonly property so we need to define in App.config I think.
<?xml version="1.0"?>
<configuration>
 <appSettings>

 </appSettings>
 ....
 <system.webServer>
   <modules runAllMan....


text:
Q: DJI SDK Android - unwanted yaw motion on GoToAction in time line mission I am trying to develop a mobile application using DJI Mobile Android SDK. The goal of the application is navigate a Mavic 2 Pro to a target GPS coordinates and automatically center a camera on a vehicle and take a snapshot. After taking off and flying to target altitude a new tracking mission in spotlight mode is called to find an object and center a camera on it.
The first process goes normally after an aircraft is turned on and the mobile application runs the missions. The aircraft is landed manually.
The second trial with the mobile application goes wrong. There is an additional yaw motion that is not in time line mission. I have missed some cleaning method that reset the aircraft to an initial clean state probably.
How to setup the aircraft to a clean state before the application starts the missions please?
I don't understand why there is a yaw 45° motion in a simple
time line mission:
missionControl.scheduleElement(new TakeOffAction());
missionControl.scheduleElement(new GoToAction(2.0f));
missionControl.startTimeline();

Why the aircraft yaw 45° after the takeoff while it is lifting to target
altitude? It's to see https://youtu.be/-gCWFXou-WI

A: You never share any other code. so below is my list of guess/checklist for a possible solution.
First, clear all other code, e.g disable drone yaw following or any other possible routing with the keyword of tracking/following etc from both code and remote controller screen
The easiest way to check if it caused by this is to call
elements.add(new GoToAction(new LocationCoordinate2D(homeLatitude+0.00001, homeLongitude+0.00001), 5));
elements.add(new GoToAction(new LocationCoordinate2D(homeLatitude-0.00001, homeLongitude-0.00001), 5));

if the camera still follows you while at a multiple location. Then sth at tracking is bothering you. If follow it could be caused by home lock also
Secondly, GoToAction never mentions about the orientation but only 3D position. Theoretically, they can do anything they want. so check API for all orientation method/setting e.g
Use setFlightOrientationMode to set course lock  or home lock to get your desired behavior.
method setFlightOrientationMode
void setFlightOrientationMode(@NonNull FlightOrientationMode type,
                                                 @Nullable CompletionCallback callback)
Package:    dji.sdk.flightcontroller
SDK Key:    FlightControllerKey.ORIENTATION_MODE
Description:
Sets the aircraft flight orientation relative to the Aircraft Heading, Course Lock, or Home Lock. See the Flight Controller User Guide for more information about flight orientation.

Last I assume you removed all other possible following modes and it is still not behave according to your wish.
The api given is
GoToAction(LocationCoordinate2D coordinate)

GoToAction(float altitude)
float altitude  Target altitude in meters.

GoToAction(LocationCoordinate2D coordinate, float altitude)

If the direct setting altitude has an issue. Can you try the full command to determine it is a bug in the source code or it is sth else
double homeLatitude = get your start gps lat;
double homeLongitude = get your start gps long;
elements.add(new GoToAction(new LocationCoordinate2D(homeLatitude, homeLongitude), 2));

If you are sure that you have no other routing that bothers the drone, and both GoToAction(float altitude) and GoToAction(LocationCoordinate2D coordinate, float altitude) has the same yaw problem. open a ticket in dev@dji.com.
Personally, I don't think it is DJI`s issue.  Because you never post the full code so I have no idea what you have done or you haven't have done but should have done.  So good luck in finding the solution to your unwanted behavior.


text:
Q: asp.net Check if the string from a textBox exist in my access table This is the code I try
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
    Dim ds As New DataSet
    Dim strSQL As String = "SELECT * FROM Client WHERE UserName = '" & TextBox1.Text & "'"
    Dim da As New OleDbDataAdapter(strSQL, con)

    Try
        con.Open()
        Dim builder As New OleDbCommandBuilder(da)
        da.Fill(da)

        If ds.Tables.Count > 0 Then
            MsgBox("exist")
        Else
             MsgBox("not exist")

        End If
        con.Close()
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

End Sub

The ds.table.count its every time = 1 whatever the TextBox1.Text.
Thanks for helping me to Check if the string from a textBox exist in my access table.


text:
Q: How to get the request header sent by requests.get()? I'd like to know what a HTTP GET request header is sent by requests.get() from the client side.
requests.get('http://localhost:9000')

The request header sent by the above python command monitored by netcat is the following. However, I don't find a way to directly monitor the HTTP GET request header sent at the client side.
GET / HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.18.4

import requests
import sys
req = requests.Request('GET', 'localhost:9000')
print req.headers

prepared = req.prepare()

s = requests.Session()
page = s.send(prepared)

The request header sent by the above python command monitored by netcat is the following.
GET / HTTP/1.1
Host: localhost:9000
Accept-Encoding: identity

Also, req.headers can be used to monitor the header. It is not exactly the same as the header sent as it does not contain the Accept-Encoding header. Also, the HTTP GET request header sent by this way is also different from that of the first way.
$ ./main.py
{}

Is there a method to directly monitor what HTTP GET header is sent in the first way?
Also, why the requests send by the two methods are not the same? Isn't it better to make them consistent to avoid possible confusion?

A:
I'd like to know what a HTTP GET request header is sent by requests.get() from the client side

If I got it right, you want to view headers, that were actually sent by requests.get().
You can access them by using .request.headers attributes:
import requests

r = requests.get("http://example.com")
print(r.request.headers)


text:
Q: How to remove scrolling behavior for child AppBarLayout/TabLayout only? I have a main activity that I use for all my activities which has this layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            style="@style/ToolBar"
            android:id="@+id/toolbar"
            app:layout_scrollFlags="scroll|enterAlways"/>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

And inside of one of my fragments I have this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <android.support.design.widget.AppBarLayout
        android:id="@+id/tabs_app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            style="@style/TabLayout"
            app:tabIndicatorHeight="0dp"/>

    </android.support.design.widget.AppBarLayout>

</LinearLayout>

Is it possible I can disable the Scrolling View Behavior for the @+id/tabs_app_bar_layout only? Basically I have two AppBarLayouts, one for the Toolbar and one for bottom navigation tabs. I want the scrolling view behavior to only affect the Toolbar.
What is the best way I can disable the scrolling behavior for only certain child views?


text:
Q: The summation $\sum_{n\geqslant1} \frac1n\sum_{d\mid n}\frac{d}{n^2+d}.$
I wish to evaluate $\sum\limits_{n\geqslant1}\frac1n\sum\limits_{d\mid n}\frac{d}{n^2+d}.$

Some observations:
Let $f(n)=\sum\limits_{d\mid n}\frac{d}{n^2+d}$.
Then $f(p)=\frac{p^2+p+2}{(p^2+1)(p+1)},\ f(2)=\frac8{15},\  f(4)=\frac{283}{765}.\ \ f$ isn't multiplicative, there is no way to relate $f(4)$ to $f(2),$ and trying to add the summation for $f$ to itself by considering $\frac{d}{n^2+d}+ \frac{n\mid d}{n^2+n\mid d}= \frac{n^2+d^2n+2d}{(n^2+d)(nd+1)}$ doesn't look promising.
Because none of these approaches worked, I turned to changing the order of summation.
Each summand for $f(n)$ is $\leqslant \frac{n}{n^2+n}=\frac1{n+1}<\frac1n$ so, the sum is $\leqslant\sum\limits_n \frac{d(n)}{n^2}\leqslant\sum\limits_n \frac{2\sqrt{n}}{n^2},$ which converges. Each term is positive, so the sum absolutely converges and we may rearrange the order of summation to sum over $d$ and $n=dk$ for $k\geqslant 1.$ We get $\sum\limits_{d\geqslant1} \sum\limits_{k\geqslant1}\frac1{dk} \frac{d}{(dk)^2+d}=\sum\limits_{d\geqslant 1}\frac1{d}\sum\limits_{k\geqslant 1}\frac1{k(dk^2+1)}=\sum\limits_{d \geqslant1}\frac1d\sum\limits_{k\geqslant1}\left(\frac1k- \frac{dk}{dk^2+1}\right).$ But now we have a difference of $2$ divergent series. How do we proceed when the partial fraction decomposition turns against you? Even the sum for $d=1$ does not appear to have a nice closed form.

Update: The problem has a typo and should have $d^2+n$ in the denominator. I found a solution to the corrected version.
Let $f(n) = \sum\limits_{d|n} \frac{d}{n+d^2}$ so that we seek $\sum\limits_{n \ge 1} \frac{f(n)}{n}.$ Since $\frac{n/d}{n+(n/d)^2} = \frac{d}{n+d^2},$ we have $f(n) \le  2\sum\limits_{d|n \atop d \ge \sqrt{n}} \frac{d}{n+d^2} < 2\sum\limits_{d|n \atop d \ge \sqrt{n}} \frac{1}{d} = \frac{2}{n} \sum\limits_{d|n \atop d \le \sqrt{n}} d \le \frac{d(n)\sqrt{n}}{n} < \frac{1}{n^{1/4}}$ for $n$ sufficiently large since $d(n) = o(n^{\epsilon})$ for any $\epsilon>0$ (here we chose $\epsilon = 1/4$)*. By comparison to $\sum\limits_{n \ge 1} n^{-5/4},$ the sum converges. Each term is positive, so the sum absolutely converges and we may rearrange the order of summation to sum over $d$ and $n = dk$ for $k \ge 1.$ We get $\sum\limits_{d \ge 1} \sum\limits_{k \ge 1} \frac{1}{dk} \frac{d}{dk+d^2} = \sum\limits_{d \ge 1} \frac{1}{d} \sum\limits_{k \ge 1} \frac{1}{k(d+k)} = \sum\limits_{d \ge 1} \frac{1}{d^2} \sum\limits_{k \ge 1} \left(\frac{1}{k} - \frac{1}{d+k}\right) = \sum\limits_{d \ge 1} \frac{H_d}{d^2}.$
Using the integral representation $H_n = \int_0^1 \frac{1-x^n}{1-x} \, dx,$ we get that the sum is $\int_0^1 \frac{g(x)}{1-x} \, dx$ where $g(x) = \sum\limits_{n \ge 1} \frac{1-x^n}{n^2}.$ Since $g(1) = 0$ and $xg'(x) = -\sum\limits_{n \ge 1} \frac{x^n}{n} = \log(1-x),$ we get $g(x) = -\int_x^1 \frac{\log(1-t)}{t} \, dt.$ Using integration by parts we get $\int_0^1 \frac{g(x)}{1-x} \, dx = -\log(1-x)g'(x) \big|_0^1 + \int_0^1 g'(x)\log(1-x) \, dx = \int_0^1 \frac{\log(1-x)^2}{x} \, dx = \int_0^1 \frac{\log(x)^2}{1-x} \, dx.$ Let $I_n = \int_0^1 \log(x)^2 x^n \, dx.$ By expanding $\frac{1}{1-x}$ as a power series and exchanging the order of summation and integration, we get $\int_0^1 \frac{\log(x)^2}{1-x} = \sum\limits_{n \ge 0} I_n.$
We turn our attention to $I_n = \int_0^1 \log(x)^2 x^n \, dx = \int_{-\infty}^0 u^2 e^{u(n+1)} \, du = \frac{1}{(n+1)^3} \int_{-\infty}^0 v^2 e^v \, dv = \frac{1}{(n+1)^3} \int_0^{\infty} v^2 e^{-v} = \frac{2!}{(n+1)^3}.$ Finally, the original sum is nothing but $2 \sum\limits_{n \ge 0} \frac{1}{(n+1)^3} = 2\zeta(3).$
*The elementary bound $d(n) \le 2\sqrt{n}$ is almost but not quite enough (you get the harmonic series), so we must resort to a result of Apostol. If there is a very fast proof of $d(n) = o(n^c)$ for some $c<1/2,$ I'd like to hear it.

A: By switching the order of summation and by applying the inverse Laplace transform we have
$$S=\sum_{n\geq 1}\sum_{d\mid n}\frac{d}{n(n^2+d)} = \sum_{d\geq 1}\sum_{k\geq 1}\frac{1}{k(k^2 d^2+d)}=\int_{0}^{+\infty}\frac{ds}{e^s-1}\sum_{k\geq 1}\frac{1-e^{-s/k^2}}{k}\,ds=\sum_{k\geq 1}\frac{H_{1/k^2}}{k} $$
and now we may invoke the Maclaurin series of $H_s$ in a right neighbourhood of the origin
$$ H_s = \zeta(2)s-\zeta(3)s^2+\zeta(4)s^3-\ldots $$
in order to get
$$ S = \frac{1}{2}+\sum_{m\geq 2}(-1)^m\left[\zeta(m)\zeta(2m-1)-1\right] $$
which turns $S$ into an essentially geometric series, whose value is $\approx 1.29534$.


text:
Q: Corecursion Doesn't Terminate After Small Change I wrote a function in Racket to produce something similar to the following fractal.

(define CUT-OFF 5)
(define CIRCLE-MODE "outline")

(define (circle-fractal size colour)
  (local [(define full-circle (circle size CIRCLE-MODE colour))]

    (cond [(<= size CUT-OFF) full-circle]
          [else
           (overlay/align "middle" "middle"
                          full-circle
                          (beside (circle-fractal (/ size 2) colour)
                                  (circle-fractal (/ size 2) colour)))])))

It passes my tests.
I changed the code, thinking the below would be more readable.
(define (circle-fractal size colour)
  (local [(define full-circle (circle size CIRCLE-MODE colour))
          (define half-circle (circle-fractal (/ size 2) colour))]

    (cond [(<= size CUT-OFF) full-circle]
          [else
           (overlay/align "middle" "middle"
                          full-circle
                          (beside half-circle half-circle))])))

Now the function doesn't terminate. Racket reaches its memory limit with no output.
Does each corecursive call somehow not approach the trivial case after this change?

A: In the first version (circle-fractal (/ size 2) colour) is evaluated only if size > CUT-OFF. In the second it's called regardless of size. This way you lost your recursion base case.
Try:
(define (circle-fractal size colour)
  (define full-circle (circle size CIRCLE-MODE colour))
  (cond [(<= size CUT-OFF) full-circle]
        [else
         (define half-circle (circle-fractal (/ size 2) colour))
         (overlay/align "middle" "middle"
                        full-circle
                        (beside half-circle half-circle))]))


text:
Q: MVC JOptionPane and checkbox for don't show this message again What is the best way to implement JOptionPanes for error messages? I could have a total of ten error messages if I decide to take the application that far but a minimal of 5 in design. The JOptionPanes would be called in a class that extends abstract action. The JOptionPanes would only be shown if the user input fails validation. The design pattern I chose was static factories.
public class ApplicationErrorPanes {

    public static class NewSupplierError extends JOptionPane {
        //JOptionPane details with return.....
    }

    //More static factories.....
}

For the checkbox in the JOptionPanes I am going to use an Object[] as the object param of the API but what is the best way to keep track of the checkbox whether it has been checked or not in the application even when the application closes?

A: Basically I did exactly what MadProgrammer suggested in the above comments....
This is the model:
public class ErrorMessageModel {

  private Properties settings;

  private FileInputStream inputStream;

  private FileOutputStream outputStream;

  public ErrorMessageModel() {

    settings = new Properties();

  }

  public void loadProperties() {
    if (settings != null) {
        try {
            inputStream = new FileInputStream("config.properties");

            settings.load(inputStream);

            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  }

  public String getErrorMessage(String key) {
    return settings.getProperty(key);
  }

  public boolean isDisplayable(String key) {
    if (settings.getProperty(key).equals("false")) {
        return false;
    } else {
        return true;
    }
  }

  public void saveProperties(String key, String value) {
    settings.put(key, value);

    storeProperties();
  }

  public void storeProperties() {
    try {
        outputStream = new FileOutputStream("config.properties");

        settings.store(outputStream, null);

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

This is the view:
public class ErrorMessagePane {

  private JLabel message;

  private JCheckBox checkBox;

  private JPanel panel;

  public ErrorMessagePane(Container parent, String errorMessage) {

    panel = new JPanel (new MigLayout(""));

    message = new JLabel (errorMessage);
    message.setFont(ApplicationStyles.STANDARD_FONT);
    panel.add(message);

    checkBox = new JCheckBox("Don't Show This Message Again");
    checkBox.setFont(ApplicationStyles.STANDARD_FONT);
    panel.add(checkBox);

    JOptionPane.showMessageDialog(parent, panel, "Error",
            JOptionPane.ERROR_MESSAGE);
  }

  public boolean isCheckBoxSelected () {
    return checkBox.isSelected();
  }
}

This is an example of the controller:
public class NewSupplierAction extends AbstractAction {

  private CSVFileController controller;

  private Dialog dialog;

  private AddSupplierPanel panel;

  public NewSupplierAction(String name, CSVFileController controller,
        Dialog dialog, AddSupplierPanel panel) {
    super(name);
    this.panel = panel;
    this.controller = controller;
    this.dialog = dialog;
  }

  @Override
  public void actionPerformed(ActionEvent e) {

    if (new ValidateSupplierID().validate(panel.getSupplierID())
            && new ValidateString().validate(panel.getSupplierName())) {
        controller.addSupplier(new Supplier(panel.getSupplierName(),
                Integer.parseInt(panel.getSupplierID())));
        dialog.getDialog().dispose();
    } else {

        ErrorMessageModel errorModel = new ErrorMessageModel ();

        errorModel.loadProperties();

        if (errorModel.isDisplayable("NewSupplierDisplay")) {
            ErrorMessagePane pane = new ErrorMessagePane (panel.getAddSupplierPanel(), errorModel.getErrorMessage("NewSupplier"));
            if (pane.isCheckBoxSelected()) {
                errorModel.saveProperties("NewSupplierDisplay", "false");
                errorModel.storeProperties();
            }
        }
    }
  }
}