text:
Q: CastError: Cast to ObjectId failed for value "x" at path "y" for model "Answer" Another CastError question! None of the Cast error solutions I see on SO seems to solve my problem. I created schemas below to link my entities but I'm stuck on how to create/persist on the database n the docs are quite confusing after getting the basics. Is there a way of getting ObjectId from the database for the user coz I need it in route.post()

var QuestionSchema = Schema({
    id          : ObjectId,
    title       : String,
    employees   : [{ type: ObjectId, ref: 'User'}]
});

var UserSchema = Schema({
    username    : String,
    //response    : String,
    questions   : [{ type: ObjectId, ref: 'Question'}]
});

//new schema/collection I've had to create
var AnswerSchema = Schema({
    response    : {type :String, default:null},
    question    : { type: ObjectId, ref: 'Question'},
    employees   : [{ type: ObjectId, ref: 'User'}],
})

module.exports = mongoose.model('Question', QuestionSchema);
module.exports = mongoose.model('User', UserSchema);
module.exports = mongoose.model('Answer', AnswersSchema);

api

router.get('/', function(req, res){
        User.findOne({ username: req.params. }).exec(function(err, user) {
            console.log(user);//null

            if(err) throw err;

            if(!user) {

                res.json({ success: false, message: 'Could not authenticate user' })
            } else if (user) {
                Question.findOne({ title:"Should we buy a coffee machine?"})
                    .exec(function (err, docs){
                    res.json(docs);
                });
            }
        });
    });

    //for feedback
    router.post('/', function (req, res) {
        User.findOne({ username: req.body.username }).exec(function(err, user) {
            if(err) throw err;

            if(!user) {
                res.json({ success: false, message: 'Could not authenticate user' })
            } else if (user){
                Answer.findOneAndUpdate({
                            question: req.body.question_id,
                            employee: req.body.user_id //CastError points to here
                        },
                        req.body,
                        {
                            upsert: true
                        })
                .exec(function(err, answer) {
                    console.log(err);//Cast error shows up here
                    console.log(answer);//prints undefined
                });
                console.log('entry saved to answer >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
            };
        });
    });


text:
Q: Add Days Google Script I wondered if anyone could help. I have a script where I am pulling out data from a spreadsheet list, where this is a match for this week (basically an events list, to produce a weekly agenda). I will use a for loop to increment the days to add on, but I am just trying to make it work for one day for now...
The first column is the data in format dd/mm/yyy
I am trying to take today's increment by 1 and then search through the list to find a match. The searching etc, I can make work, but the date part is just not playing. I wondered if anyone could advise.
E.g. Date Column A:
06/07/2021
06/07/2021
01/11/2021
01/11/2021
01/11/2021
01/11/2021
02/09/2021
02/09/2021
 var selectedDate = row[0];

selectedDate = Utilities.formatDate(new Date(selectedDate), "GMT+1", "dd/MM/yyyy");

 var currdate = new Date();
  currdate = Utilities.formatDate(new Date(selectedDate), "GMT+1", "dd/MM/yyyy");
  var daystochange = 1;
  var newdate = new Date(currdate.getFullYear, currdate.getMonth, currdate.getDay+daystochange );

Could anyone help?
Thanks

A: Only use Utilities.formatDate() to output dates, not to work with dates.
The JavaScript date object has all you need to work with dates and compare. When you use the Utilities function it converts it to a string, and so you lose all the functionality of the Date object.
Also bear in mind that if you have dates, that are formatted as dates in your sheet, they will automatically be returned as Date objects.
For example, if your sheet has a date in cell A1
var date = Sheet.getRange("A1").getValue()
date instanceof Date // true

Once you have your date, if you want to add one day to it, you can take an approach similar to what you have already done:
var selectedDate = new Date(2021, 1, 15)
var newdate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate() + 1);
console.log(newdate) // Tue Feb 02 2021 00:00:00

Note - use getDate to return the day of the month, getDay only returns day of the week.
To check if two dates are the same, you can write a function to compare:
function isSameDate(a, b) {
    return  a instanceof Date &&
        b instanceof Date &&
        a.getYear() === b.getYear() &&
        a.getMonth() === b.getMonth() &&
        a.getDate() === b.getDate()
}

This function will return true if the dates are the same.
Reference

*

*Date

redpajama_set_name: RedPajamaStackExchange


text:
Q: rich:autocomplete not showing in the browser I'm doing a Rich Faces tutorial, I'm done with code but when I deployed the project the rich:autocomplete box did not appear in the browser, I have tried different browsers and still the same
here is  my code
test.xhtml
 <body>
    <rich:panel>
        <f:facet name="header">
        Richfaces sample validation and auto-completion Updated
        </f:facet>
        <h:form>
            <h:outputText value="Enter your name" />
            <h:inputText id="name" value="#{UserBean.name}">
                <rich:validator />
            </h:inputText>

            <rich:message for="name" />
            <br />

            <h:outputText value="Enter your state" />
            <rich:autocomplete mode="ajax" showButton="true" value="#{UserBean.state}" minChars="1"
                autocompleteMethod="#{UserBean.autocomplete}" />
        </h:form>
    </rich:panel>
</body>

the UserBean.java code is
    @ManagedBean
public class UserBean {

    public List<String> autocomplete(String prefix) {

        ArrayList<String> result = new ArrayList<String>();
        result.add("England");
        result.add("France");
        result.add("Germany");
        result.add("Italy");
        result.add("Spain");

        return result;
    }

    @Size(min=3, max=12,message="Must be between 3 and 12 chars")
    private String name;

    private String state;

    public String getState() {
        return state;
    }

    public String getName() {
        return name;
    }

}

this is 'web.xml'
    <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
  <display-name>rich</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
</web-app>

when I run the war file in the browser it shows like this:

while the actual preview in the Eclipse showing like this:


text:
Q: Android Gallery children onClickListener I have a Gallery with implemented BaseAdapter. Each view of Gallery contains LinearLayout with many TextVIew. Because I want different onClickListeners for each TextView (loads different web pages) I put onClickListeners  in getView in the adapters. This action (set listeners in getView in the adapter) freeze the Gallery and it's not possible to be scrollable. On the other hand outside of Adapter I can put only listener for the whole Gallery but not specially for each child of each element of the gallery. My question is how I can put  onClickListener in BaseAdapter attached to Gallery for children for each element in Gallery without removing sliding functionality of Gallery.I tried to play with touchevent but doesn't work. Any ideas?

A: Inside OnItemClickListener,you have to take the id for all child views and check the views over the parent views.while surely you can get the touch for every specific child views,if child view equals to the parent child view.


text:
Q: Show product price element only in Post type pages I've configured my theme to hide product elements like price, add to cart, category... And this affects all the websites.
I'm trying to get a PHP snippet to make the price element work only in POST-type pages.
What I have now:
// Active price:
wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) );

//Regular price:
wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );

//Sale price:
wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );


text:
Q: strcat in C not working Hi all I'm trying to write a function that returns the line of data and returns it in a String. Below is my code and I'm not sure why it's not working. I've added in a printf function and when I call the function nothing prints out.?
EDIT (cause i can't answer yet) - Thanks for your replies. When I change char c to char *c it still doesn't work. I just need to read the line into a string and return it.
char* getLine(FILE *file, int lineNum){

    char c;
    int lineCount=0, size = 1;
    char *line = NULL;
    line = malloc(sizeof(char)*size);
    while ((c=getc(file)) != EOF){

        if (c=='\n'){
            ++lineCount;
            continue;
        }
        if (lineCount==lineNum){
            size += 1;
            line = realloc(line, size*sizeof(char));
            strcat(line, c);
            printf("Line: %s\n", line);
        }
    }
    return line;
}

A: Variable c is not of type const char *
See strcat documentation

A: It's not very efficient, but it should do what you want:
Note that lineCount starts at 0. (The first line is line 0).
char* getLine(FILE *file, int lineNum){
    char c;
    int lineCount=0, size = 0; // start size at zero, not one
    char *line = NULL;

    while ((c=getc(file)) != EOF){
        if (lineCount==lineNum){
            size += 1;
            if(line == NULL) {
                line = calloc(sizeof(char), size);
            } else {
                line = realloc(line, size*sizeof(char));
            }
            char ac[2] = { c, 0 }; // this line is new
            strcat(line, ac); // ac is new here
            printf("Line: %s\n", line);
            if(c == '\n') {
                return line;
            }
        }
        if (c=='\n'){
            ++lineCount;
        }
    }
    printf("Could not find line %d\n", lineNum);
    return NULL;
}


text:
Q: Where to find large stock Android drawables? Just as the title says.  I know there are drawables in android.R.drawables, but because they are so small, they look horrible when scaled up.  Does anyone know where I can find the current 4.x drawables that are larger than the ones in the folder?
Since I don't know much about drawables anyways, are the stock drawables in android.R.drawables all in a single size, or are there multiple versions to support different density screens?  If so, how can I access these larger drawables?

A:
Does anyone know where I can find the current 4.x drawables that are larger than the ones in the folder?

If you mean larger than the -xhdpi ones, they are probably on some graphic designer's workstation at Google.

are the stock drawables in android.R.drawables all in a single size, or are there multiple versions to support different density screens?

They ship in multiple densities.

If so, how can I access these larger drawables?

They are in your SDK directory, in platforms/$VERSION/data/res/, where $VERSION is one of the available API levels that you have installed.


text:
Q: Build time for makefile recipe I want to caluclate time spent for each recipe in makefile
SYS_TIME = $(shell date)
SUBDIRS = a b c d

.PHONY = default

default:
    for dir in $(SUBDIRS); \
    do \
       $(eval ST = $(SYS_TIME)) \
       $(MAKE) -C FOLD=$$dir; \
       $(eval ET = $(SYS_TIME))
       echo "time spent  =   $(ST) - $(ET) "
   done; \

result should look like:

time spent  = 1:35
time spent  = 2:23
time spent  = 10:59
time spent  = 5:35

it signify 1 minute 35 sec for first and same for others
or some other alternative for $(shell date)

A: Just prefix your command lines with time, e.g.: time $(MAKE) -C $$dir.


text:
Q: Exercise 2.7.1 of J. Norris, "Markov Chains" I am working though the book of J. Norris, "Markov Chains" as self-study and have difficulty with ex. 2.7.1, part a.
The exercise can be read through Google books. My understanding is that the probability is given by (0,i) matrix element of exp(t*Q). Setting up forward evolution equation leads to differential difference equation which I was hinted admits no closed form solution (see my question on mathoverflow).
I obviously need an nudge in a right direction, and the exercise must admit a simple solution. Any directions are much appreciated.

A: It seems you misread the question. One is not interested in the probability of the event $[X_t=i]$ for a given time $t$ but in the probability of the event that there exists a time $t$ such that $X_t=i$.
Here is a nudge...
One approach is to consider the sequence $(Y_n)_n$ of the successive different states visited by $(X_t)_t$. You could try to show that $(Y_n)_n$ is a discrete Markov chain, to compute its transition probabilities (these are very simple and, hint, they do not depend on the numbers $q_i$) and, finally, to compute the probability that there exists an integer time $n$ such that $Y_n=i$.

A: At first, I misread the question just as Didier said. (Bit of lacking in taste for probability problems. )
To summarize the previous answer and comments, I'll write a brief formularized answer.
Without loss of generality, we assume $i > 0$,
$$P(\exists t > 0, s.t. X_t = i) = \lim_{n \to \infty} P(T_i < T_{-n})$$
So the problem can be simplified into calculating $P_0(T_i < T_{-n})$. (I add the subscript because it can be helpful later. $P_k$ denotes starting from $X_0 = k$. $T_i$ denotes the hitting time for $i$. )
First of all,
$$P_i(T_i < T_{-n}) = 1, P_{-n}(T_i < T_{-n}) = 0$$
Then, according to the transition matrix,
$$P_j = \lambda P_{j-1} + \mu P_{j+1}, \quad -n < j < i$$
which can be rewritten into
$$P_{j+1} - P_j = \frac{\lambda}{\mu} (P_j - P_{j-1})$$
Therefore, (and the final form will be slightly different for $\frac{\lambda}{\mu} = 1$)
$$1 = P_{i} - P_{-n} = \sum_{j = -(n-1)}^{i} (P_{j} - P_{j-1})$$
$$ = \sum_{j = -(n-1)}^{i} (\frac{\lambda}{\mu})^{j+(n-1)} (P_{-(n-1)} - P_{-n}) = \frac{1 - (\frac{\lambda}{\mu})^{i+n}}{1 - \frac{\lambda}{\mu}} (P_{-(n-1)} - P_{-n})$$
The rest are simple calculations.
$$P_0 = P_0 - P_{-n} = \sum_{j=-(n-1)}^0 (P_{j} - P_{j-1}) = \ ... $$
I'll add part b for reference:
(b) Find for all integers $i$, the expected total time spent in state $i$, starting from $0$.
1) $\lambda = \mu = \frac{1}{2},$ all expected total time is $\infty$, because the jump chain is recurrent.
2) $\lambda > \mu,$ time spent in each state is positive but not $\infty$, because the jump chain is transient.
I don't know a closed form yet. For $i \geq 0$,
$$t_0(i) = \sum_{j = i}^{\infty} \binom{2j-i}{i} \lambda^{j} \mu^{(j-i)} $$
For $i \le 0$,
$$t_0(i) = \sum_{j = -i}^{\infty} \binom{2j-(-i)}{-i} \lambda^{(j - (-i))} \mu^{j} $$
is the expected times of visits for the jump chain to i.
And the expected time for each visit is $\frac{1}{q_i}$.
They are independent.
3) $\lambda < \mu,$ similar to 2).


text:
Q: Как в VBA при начале выполнения макроса указать окно для ввода нескольких значений? В общем при выполнении макроса мне нужно открыть диалоговое окно в котором будет сразу несколько полей и combobox с выбором. После указания всех значений мне нужно с ними работать. Как создать такое окно? В комбобоксе должно быть указано "Машина, Марка". Всего 2 значения в комбобоксе: Машина1 Марка1, Машина2 Марка2. Но дальше при работе мне нужно будет записать это в разные ячейки, к примеру в А1: Машина1, в А2: Марка1, А3: масса нетто, а4: масса брутто и т.д.
На данный момент у меня по очереди открываются окна в которых я ввожу по 1 значению, combobox вообще не знаю как сделать.
Вот как я открываю нужные мне окна, но они должны быть в одном окне:
inputNetto = Val(InputBox("Введите вес Нетто"))
NewWorkbook.Worksheets(1).Cells(3, 25).Value = inputNetto

inputBrutto = Val(InputBox("Введите вес Брутто"))
NewWorkbook.Worksheets(1).Cells(27, 23).Value = inputBrutto

inputPallets = Val(InputBox("Введите кол-во палетов"))
NewWorkbook.Worksheets(1).Cells(27, 26).Value = inputPallets

Подскажите как реализовать такое окно, буду очень благодарен

A: Нет такого диалогового окна. Нужно рисовать форму (UserForm).
Создаем форму - Insert-UserForm. Кнопочкой ToolBox вызываем окошко с элементами формы. Перетаскиваем нужные элементы на форму, размещае/форматируем. Параметры элемента (или формы) задаются в окне Properties (по F4).
Обработки элементов и самой формы (инициализирование, активация, изменение, выход и проч.) прописываются в модуле формы (ПКМ на форме - View Code)/
Двойной клик на элементе создает пустой макрос (обычно - событие изменения), в теле которого можно дописать необходимый код:
Private Sub TextBox1_Change()

End Sub

Для удобства работы с формой элементы желательно переименовать:
tBoxName - TextBox для ввода имени, cButClose - кнопка закрытия и проч.
Часто при открытии формы должны быть заполнены списки, в зависимости от ситуации вписаны данные... Для придания форме требуемого вида - событие инициализации формы:
Private Sub UserForm_Initialize()


text:
Q: How does ScalaTest syntax work? I've done some programming in Scala, and I know that, e.g.,
xs map f

is the same thing as
xs.map(f)

but I have no idea how to generalize this syntax to something like ScalaTest's syntax, e.g.,
it should "throw NoSuchElementException if an empty stack is popped" in {
  val emptyStack = new Stack[String]
  evaluating { emptyStack.pop() } should produce [NoSuchElementException]
}

I'm mainly wondering about the things that look like multi-word constructs, namely should produce. It's neat.

A: It's reasonably easy because it's normal code - it should is equivalent to it.should hence there must be a value (or method) called it in scope. And there is!
This variable is of type ItWord which exposes a method called should which takes an object of type BehaveWord. These matchers are mixed in via implicit conversions in the ShouldMatchers trait.
ScalaTest is actually extremely well documented with tons of examples and descriptions of how things work.

A: That kind of syntax is method calls in operator notation, but carried forward more than just three tokens. As you already mentioned:
xs map f

means:
xs.map(f)

But you could go further and say:
xs map f map g

which means:
xs.map(f).map(g)

In ScalaTest matchers, for example, you could say:
result should not be null

That gets desugared by the compiler to:
result.should(not).be(null)

This:
it should "throw an exception" in { ... }

gets desugared into:
it.should("throw an exception").in { ... }

The curly braces at the end is really just a way to pass the code in between the curly braces (the test code) into the in method, wrapped as a no-arg function. So all of these are the same idea. Operator notation used twice in a row.
The last one you asked about is a tad different:
evaluating { ... } should produce [IllegalArgumentException]

This gets transformed into:
evaluating { ... } is, well, evaluated first, because the curly braces give it precedence. So that is a method call, you are calling a method named "evaluating", passing in the code in between the curly braces as a no-arg function. That returns an object, on which should is invoked. So should is a method on the object returned by invoking evaluating. What should actually takes is the result of invoking produce. Here produce is actually a method, which has a type parameter such as [IllegalArgumentException]. It must be done this way so the Scala compiler can "poor-man's-reify" that type parameter. It passes an implicit "Manifest" parameter into produce that can provide the java.lang.Class instance for IllegalArgumentException. When that should method is invoked, therefore, it has a function containing the code passed to evaluating, and a way to find the java.lang.Class of the exception type put in the square brackets. So it executes the block of code wrapped in a try, catches the exception, compares it with what's expected. If no exception is thrown, or the wrong one, the should method throws a TestFailedException. Otherwise the should method just returns silently.
So, the answer is that line gets desugared into:
(evaluating { ... }).should(produce[IllegalArgumentException] (compilerSuppliedManifest))

And the moral of the story is that high level code like this makes it easier to see the programmer's intent, but often harder to understand how the code actually works. Most of the time in practice all you care about is the intent, but now and then you need to know how something works. In such cases in Scala you can pass -Xprint:typer as a command line arg to the Scala compiler and it will print out a version of your file after all the desugaring has happened. So you can see what's what when you need to.


text:
Q: Constraint Layout Leaking in Fragment - Leak Canary - Leak in TextInputLayout I got a memory leak in my login page and I can`t figure why. I am using Leak Canary to identify the leak and this was the leak trace I got.
D/LeakCanary: ┬───
    │ GC Root: Input or output parameters in native code
    │
    ├─ okio.AsyncTimeout class
    │    Leaking: NO (PathClassLoader↓ is not leaking and a class is never leaking)
    │    ↓ static AsyncTimeout.$class$classLoader
    ├─ dalvik.system.PathClassLoader instance
    │    Leaking: NO (InternalLeakCanary↓ is not leaking and A ClassLoader is never leaking)
    │    ↓ PathClassLoader.runtimeInternalObjects
    ├─ java.lang.Object[] array
    │    Leaking: NO (InternalLeakCanary↓ is not leaking)
    │    ↓ Object[].[957]
    ├─ leakcanary.internal.InternalLeakCanary class
    │    Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
    │    ↓ static InternalLeakCanary.resumedActivity
    ├─ com.eim.rdoApplication.ui.activity.MainActivity instance
    │    Leaking: NO (LoginFragment↓ is not leaking and Activity#mDestroyed is false)
    │    mApplication instance of com.eim.rdoApplication.AppApplication
    │    mBase instance of androidx.appcompat.view.ContextThemeWrapper, not wrapping known Android context
    │    ↓ MainActivity.mActivityResultRegistry
    ├─ androidx.activity.ComponentActivity$2 instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    Anonymous subclass of androidx.activity.result.ActivityResultRegistry
D/LeakCanary: │    this$0 instance of com.eim.rdoApplication.ui.activity.MainActivity with mDestroyed = false
    │    ↓ ComponentActivity$2.mKeyToCallback
    ├─ java.util.HashMap instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    ↓ HashMap.table
    ├─ java.util.HashMap$Node[] array
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    ↓ HashMap$Node[].[2]
    ├─ java.util.HashMap$Node instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    ↓ HashMap$Node.value
    ├─ androidx.activity.result.ActivityResultRegistry$CallbackAndContract instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    ↓ ActivityResultRegistry$CallbackAndContract.mCallback
    ├─ androidx.fragment.app.FragmentManager$11 instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    Anonymous class implementing androidx.activity.result.ActivityResultCallback
    │    ↓ FragmentManager$11.this$0
    ├─ androidx.fragment.app.FragmentManagerImpl instance
    │    Leaking: NO (LoginFragment↓ is not leaking)
    │    ↓ FragmentManagerImpl.mParent
    ├─ com.eim.rdoApplication.ui.fragment.login.LoginFragment instance
    │    Leaking: NO (Fragment#mFragmentManager is not null)
D/LeakCanary: │    componentContext instance of dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper,
    │    wrapping activity com.eim.rdoApplication.ui.activity.MainActivity with mDestroyed = false
    │    ↓ LoginFragment.mAnimationInfo
    │                    ~~~~~~~~~~~~~~
    ├─ androidx.fragment.app.Fragment$AnimationInfo instance
    │    Leaking: UNKNOWN
    │    Retaining 319257 bytes in 3340 objects
    │    ↓ Fragment$AnimationInfo.mFocusedView
    │                             ~~~~~~~~~~~~
    ├─ com.google.android.material.textfield.TextInputEditText instance
    │    Leaking: UNKNOWN
    │    Retaining 319171 bytes in 3339 objects
    │    View not part of a window view hierarchy
    │    View.mAttachInfo is null (view detached)
    │    View.mID = R.id.inputEditTextEmailField
    │    View.mWindowAttachCount = 1
    │    mContext instance of androidx.appcompat.view.ContextThemeWrapper, wrapping activity com.eim.rdoApplication.ui.
    │    activity.MainActivity with mDestroyed = false
    │    ↓ TextInputEditText.mParent
D/LeakCanary: │                        ~~~~~~~
    ├─ android.widget.FrameLayout instance
    │    Leaking: UNKNOWN
    │    Retaining 2231 bytes in 14 objects
    │    View not part of a window view hierarchy
    │    View.mAttachInfo is null (view detached)
    │    View.mWindowAttachCount = 1
    │    mContext instance of androidx.appcompat.view.ContextThemeWrapper, wrapping activity com.eim.rdoApplication.ui.
    │    activity.MainActivity with mDestroyed = false
    │    ↓ FrameLayout.mParent
    │                  ~~~~~~~
    ├─ com.google.android.material.textfield.TextInputLayout instance
    │    Leaking: UNKNOWN
    │    Retaining 204872 bytes in 2728 objects
    │    View not part of a window view hierarchy
    │    View.mAttachInfo is null (view detached)
    │    View.mID = R.id.textInputLayoutEmail
    │    View.mWindowAttachCount = 1
    │    mContext instance of androidx.appcompat.view.ContextThemeWrapper, wrapping activity com.eim.rdoApplication.ui.
    │    activity.MainActivity with mDestroyed = false
D/LeakCanary: │    ↓ TextInputLayout.mParent
    │                      ~~~~~~~
    ╰→ androidx.constraintlayout.widget.ConstraintLayout instance
         Leaking: YES (ObjectWatcher was watching this because com.eim.rdoApplication.ui.fragment.login.LoginFragment
D/LeakCanary:      received Fragment#onDestroyView() callback (references to its views should be cleared to prevent leaks))
         Retaining 4897 bytes in 71 objects
         key = 0d74b072-904d-4aba-9a0e-4e17260ffc96
         watchDurationMillis = 9630
         retainedDurationMillis = 4627
         View not part of a window view hierarchy
         View.mAttachInfo is null (view detached)
         View.mWindowAttachCount = 1
         mContext instance of dagger.hilt.android.internal.managers.ViewComponentManager$FragmentContextWrapper, wrapping
         activity com.eim.rdoApplication.ui.activity.MainActivity with mDestroyed = false
    METADATA
    Build.VERSION.SDK_INT: 27
    Build.MANUFACTURER: motorola
    LeakCanary version: 2.5
    App process name: com.eim.aplicativo_rdo

What could be causing this leak? Any help ?
I am working with one activity and multiple fragments being handled by navigation component.
From what I could understand, the main problem is that my textInputlayoutEmail somehow is not part of a view hierarchy at some point of the lifecycle of my fragment. This is my Fragment Code :

private const val ERROR_LOGIN = "ERROR_LOGIN"
@AndroidEntryPoint
class LoginFragment : Fragment() {

    private val navController by lazy {findNavController()}

    private val loginViewModel: LoginViewModel by navGraphViewModels(R.id.navigation_graph){
        defaultViewModelProviderFactory
    }

    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        setLoadingView()
        setGoToForgotPasswordFragmentButton()
        setLoginButton()
        super.onViewCreated(view, savedInstanceState)
    }

    private fun setLoginButton() {
        binding.buttonSignIn.setOnClickListener {
            if(areFieldsValid()){
                loginViewModel.emailField = binding.inputEditTextEmailField.text.toString()
                loginViewModel.passwordField = binding.editTextPasswordField.text.toString()
                loginUser(loginViewModel.let { UserDataRequest(it.emailField, it.passwordField) })
            }
        }
    }

    private fun areFieldsValid(): Boolean {
            return !(binding.editTextPasswordField.text.isNullOrBlank()||binding.inputEditTextEmailField.text.isNullOrBlank())

    }

    private fun setGoToForgotPasswordFragmentButton() {
        binding.forgotPasswordEditText.setOnClickListener{
            val action = LoginFragmentDirections.actionLoginFragmentToForgotPasswordFragment()
            navController.navigate(action)
        }
    }

    private fun setLoadingView() {
        binding.apply {
            loadingIconLoginFragment.visibility = View.INVISIBLE
            loadingBgLoginFragment.visibility = View.INVISIBLE
        }
    }

    private fun loginUser(loginUserRequest: UserDataRequest){
        viewLifecycleOwner.lifecycleScope.launch {
            loginViewModel.loginUser(loginUserRequest).collect {
                when(it.status) {
                    Resource.Status.LOADING -> {
                        withContext(Dispatchers.Main) {
                            setLoadingInterface()
                        }
                    }
                    Resource.Status.ERROR -> {
                        withContext(Dispatchers.Main){
                            val errorMessage = "Não foi possível realizar seu Login"
                            clearLoadingInterface()
                            showErrorInterface(errorMessage, ERROR_LOGIN)
                        }
                    }
                    Resource.Status.SUCCESS -> {
                        withContext(Dispatchers.Main) {
                            clearLoadingInterface()
                            val action = LoginFragmentDirections.actionLoginFragmentToGeneralHomeFragment(0, "", "")
                            navController.navigate(action)
                        }
                    }
                }

            }
        }
    }

    private fun setLoadingInterface() {
        binding.apply {
            loadingBgLoginFragment.visibility = View.VISIBLE
            loadingIconLoginFragment.visibility = View.VISIBLE
        }
        rotateAnimation()
    }

    private fun showErrorInterface(errorMessage: String, errorType: String) {
        clearLoadingInterface()
        val dialog = NetworkErrorDialog.newInstance(errorMessage, errorType)
        dialog.show(childFragmentManager, dialog.tag)
    }

    private fun clearLoadingInterface() {
        binding.apply {
            loadingBgLoginFragment.visibility = View.GONE
            loadingIconLoginFragment.apply {
                visibility = View.GONE
                clearAnimation()
            }
        }
    }

    private fun rotateAnimation() {
        val animation = AnimationUtils.loadAnimation(activity?.applicationContext, R.anim.rotate)
        binding.loadingIconLoginFragment.startAnimation(animation)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}

In my views so I don`t know what else can I do to clear this reference.
If anyone could show me in which part of the code I am holding a reference to this view, would help me a lot. Thanks


text:
Q: Apache write permission in public_html? I have an account on a hosted webserver, where I have SSH access.
Files put in /home/sandra/public_html are online.
DokuWiki recommends that the data and conf directory is not in Document Root, so I have moved them to /home/sandra/data/ and /home/sandra/conf.
The problem is, that apache can't write to these directories.
Ownership of /home/sandra/ is sandra.sandra.
Question
Are there other solutions to this problem than
chmod 777 /home/sandra

Can the root user help me out?

A: As Hex already wrote, the directory must be writable for the user under which Apache runs. You can achieve this by changing the group to the Apache user's primary group (www-data on Ubuntu) and give the group write permission.
chgrp -R www-data /home/sandra/data /home/sandra/conf
chmod -R g+rwX /home/sandra/data /home/sandra/conf

The user must also be able to cd into those directories, so it needs execute permissions on the parent directory.
chmod o+X /home/sandra

Another option would be to add respective ACLs for the Apache user, if the filesystem supports them.
setfacl -m default:u:www-data:rwx /home/sandra/data /home/sandra/conf
setfacl -m u:www-data:x /home/sandra

I wouldn't recommend changing the owner.

A: You can try
chown -R apache /home/sandra/conf

This command will make apache the owner of these files. You can then give apache full access to the folderby doing
chmod 770 /home/sandra/conf

Both commands must be run on both folders respectively.


text:
Q: Google maps won't work on my website despite good API key I had a website with google map, but few weeks ago google maps on my website stop working. I created google maps api key and entered it in my Joomla btgoogle maps module, but maps still won't work. What can be the problem?
URL Link: http://studiomob.rs/index.php/en/contact

A: Upon inspecting the URL provided, I see that you have few Maps Javascript calls in your implementation which looks like:
<script src="//maps.google.com/maps/api/js?language=en-GB&key=AIza...bLBZ8" type="text/javascript"></script>

And
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

To fix this, kindly remove all your Maps Javascript API calls and just include one Maps Javascript that contains your API key which looks like the first one above.


text:
Q: Search for child values within two dates in Firebase android This is how the json looks like
"Node" : {
      "1-5-2018" : {
        "10001" : {
          "centre" : "centre_1",
          "name" : "name_1",
          "paidAmt" : "25000"
        },
        "10002" : {
          "centre" : "centre_2",
          "name" : "name_2",
          "paidAmt" : "25000"
        },
        "10003" : {
          "centre" : "centre_3",
          "name" : "name_3",
          "paidAmt" : "10000"
        }
        },
      "2-5-2018 : {
        "10004" : {
            "centre" : "centre_4",
            "name" : "name_4",
            "paidAmt" : "20000"
            }
        }

I want to retrieve the values(centre, name and paidAmt) inside the given dates
I've tried using this particular query but it always shows data does not exist
Query query = databaseReference1.orderByKey().startAt(fromDate.getText().toString()).endAt(toDate.getText().toString());

                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if(dataSnapshot.exists()) {
                            Log.d(TAG, "Data exists within dates");
                            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                                Log.d(TAG , "Data are " + ds.getValue().toString());
                            }
                        }
                        else {
                            Log.d(TAG, "Data does not exist within dates");
                        }
                    }

Please let me know if it's possible to retrieve all the data within dates. In future i'm planning to add multiple data inside different dates and want to retrieve them based on requirement. Maybe monthly or weekly.

A: You are using timestamp instead of a date it may look like this.
"Node" : {
      "1525188857" : {
        "10001" : {
          "centre" : "centre_1",
          "name" : "name_1",
          "paidAmt" : "25000"
        },
        "10002" : {
          "centre" : "centre_2",
          "name" : "name_2",
          "paidAmt" : "25000"
        },
        "10003" : {
          "centre" : "centre_3",
          "name" : "name_3",
          "paidAmt" : "10000"
        }
        },
      "1525188873" : {
        "10004" : {
            "centre" : "centre_4",
            "name" : "name_4",
            "paidAmt" : "20000"
            }
        }


text:
Q: Can I use async / await to simulate a background worker? I'm trying to avoid having to chain a bunch of BackgroundWorkers together.  I'm doing something that requires me to wait for the UI to update before continuing execution.  Obviously, I can't use Sleep, as this blocks the UI thread from updating and defeats the purpose.  I found the code below which I thought was the answer, but it appears the task.Wait(); line is still blocking the UI thread.
static void Main(string[] args)
{
    var task = Task.Run(() => DoSomething());
    task.Wait();
    // once the task completes, now do more
}

static void DoSomething()
{
    // something here that is looking for the UI to change
}

I also tried the following, which did the same thing:
static void Main(string[] args)
{
    var task = Task.Run(() => DoSomethingAsync());
    task.Wait();
    // once the task completes, now do more
}

private async Task DoSomethingAsync()
{
    // something here that is looking for the UI to change
}

Is it possible to do what I want, and if so, what am I doing wrong?

A: You need to await the task instead of blocking on it. You can do that inside an async method.
Now, Main can't be async but an event handler can be (which I guess is where you actually use that code):
public async void EventHandler(object sender, EventArgs e)
{
    await Task.Run(() => DoSomething()); // wait asynchronously
    // continue on the UI thread
}

Note that it's async void which should only be used on event handlers. All other async methods should return a task.
Using Task.Run means your using a ThreadPool thread. To really wait asynchronously for the UI to "do something" you should use TaskCompletionSource. You create it and await it's Task property and you complete that task when the UI changed:
public async void EventHandler(object sender, EventArgs e)
{
    _tcs = new TaskCompletionSource<bool>();
    await _tcs.Task;
}

public void UIChanged(object sender, EventArgs e)
{
    _tcs.SetResult(false);
}


text:
Q: Family tree relationship calculation This is the structure of my family graph

*

*I tried solving this with the commonly used Least Common Ancestor algorithm and was successful to some extent. The algorithm can find relationships having common ancestors like 3 and 8 and 1 and 8
However the algorithm fails to find relationships between (For instance)
3 and 11 and 3 and 4

*In these cases there is no common ancestor.

*In the given image 6,7 and 9,8 and 10,11 and 4,5 are couples, so I could add another connection between either of them to form a marriage link.

*Is there an alternative approach to the LCA algorithm to find relationships between nodes that don't have common ancestors?

*The ultimate aim is to answer questions like 3 is the grandson of 9 and 3 is the nephew/niece of 10.


text:
Q: vswprintf keeps prefixing a Byte Order Mark character I am still a rookie with C, and even newer to wide chars in C.
The below code should show
4 points to Smurfs
but it shows
4 points to  Smurfs
In gdb I see this:
(gdb) p buffer
$1 = L" 4 points to  Smurfs",

But when I copy paste from the console, the spaces are magically gone:
(gdb) p buffer
$1 = L"4 points to Smurfs",

Also, buffer[0] contains this according to gdb:
65279 L' '
Apparently the character in question &#65279 is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). I retyped the code making sure I did not enter this. I don't know where this comes from. I also opened the code in notepad per https://stackoverflow.com/a/9691839/7602 and there is no extra chars there.
I wouldn't care if ncurses would stop showing this as a space.
Code (heavily cut down):
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <wchar.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <locale.h>
#define NCURSES_WIDECHAR 1
#include <ncursesw/ncurses.h>

#include "types.h"
#include "defines.h"
#include "externs.h"

WINDOW * term;

/*row column color n arguments */
void rccn(int row, int col, const wchar_t *fmt, ...)
{
    wchar_t buffer[80];
    int size;

    va_list args;
    va_start(args, fmt);
    size = vswprintf(buffer, 80, fmt, args);
    va_end( args );

    if(size >= 80){
        mvaddwstr(row, col, L"Possible hacker detected!");
    }else{
        mvaddwstr(row, col, buffer);
    }
}

int main(void)
{
    int ch;
    setlocale(LC_ALL,"");
    term = initscr();

    rccn(1,1,L"%i points to %ls",4,L"Smurfs");
    ch = getch();

    return EXIT_SUCCESS;
}

The problem goes 'away' with
rccn(1,1,L"%i points to %ls",4,L"Smurfs"+1);
As if the wide encoding of the constant adds that char in front..

A: Found it..
I had followed a tutorial where it was advised to add this compiler flag:
-fwide-exec-charset=utf-32
My code was not running on Cygwin at all, and I read that Windows is utf-16 centered, so I removed that compiler flag and it started working on Cygwin.
Then out of curiosity I removed the compiler flag on Raspbian, and it is now working as expected there as well, no more byte order marks.


text:
Q: Repetindo a subtração de grupos em um data frame para todas as variáveis numéricas Tenho o seguinte código:
 df <- data.frame(grp = rep(letters[1:3], each = 2),
                     index = rep(1:2, times = 3),
                     value = seq(10, 60, length.out = 6),
                     value2 = seq(20, 70, length.out = 6),
                     value3 = seq(30, 80, length.out = 6))

library(tidyverse)
tbl_df(df) #para melhor visualização

# grp   index value value2 value3
# <fct> <int> <dbl>  <dbl>  <dbl>
# 1 a      1    10     20     30
# 2 a      2    20     30     40
# 3 b      1    30     40     50
# 4 b      2    40     50     60
# 5 c      1    50     60     70
# 6 c      2    60     70     80

# resultado esperado:
# grp   index value value2 value3
# <fct> <int> <dbl>  <dbl>  <dbl>
# 1 a      1    10     20     30
# 2 a      2    20     30     40
# 3 b      1   -20    -20    -20
# 4 b      2   -20    -20    -20
# 5 c      1    50     60     70
# 6 c      2    60     70     80

# subtrair um grupo de outro
df$value[df$grp=="b"]  = df$value[df$grp=="b"]  - df$value[df$grp=="c"]
df$value2[df$grp=="b"] = df$value2[df$grp=="b"] - df$value2[df$grp=="c"]
df$value3[df$grp=="b"] = df$value3[df$grp=="b"] - df$value3[df$grp=="c"]

Como subtraio todos os value# do grupo 'c' dos value# do grupo 'b', de uma vez, sem a necessidade de repetir
df$value[df$grp=="b"]  = df$value[df$grp=="b"]  - df$value[df$grp=="c"]

para cada variável?

A: O seguinte faz o que quer com R base.
ib <- which(df$grp == "b")
ic <- which(df$grp == "c")
df[3:5] <- lapply(df[3:5], function(x){
  x[ib] <- x[ib] - x[ic]
  x
})

df
#  grp index value value2 value3
#1   a     1    10     20     30
#2   a     2    20     30     40
#3   b     1   -20    -20    -20
#4   b     2   -20    -20    -20
#5   c     1    50     60     70
#6   c     2    60     70     80

Agora, arruma-se a casa. As variáveis ib e ic usadas para indexar os vetores a transformar já não são necessárias.
rm(ib, ic)

A: É possível fazer assim com dplyr:
bind_rows(
  df %>%
    filter(grp == "a"),

  df %>%
    filter(grp != "a") %>%
    group_by(index) %>%
    mutate_at(vars(starts_with("value")), funs(. - lead(., order_by = grp, default = 0)))
)

  grp index value value2 value3
1   a     1    10     20     30
2   a     2    20     30     40
3   b     1   -20    -20    -20
4   b     2   -20    -20    -20
5   c     1    50     60     70
6   c     2    60     70     80

O código fica meio estranho pq existe o grupo A. Se na prática vc sempre subtraisse o valor do grupo anterior pelo valor do próximo grupo poderia ignorar o bind_rows e filtros.


text:
Q: Hiding a custom quick access button in Sharepoint 2007 programmatically I created a quick access button in the editing toolbar of a Sharepoint 2007 site, modified the CustomQuickAccess.xml file to include my buttons
Wrote the code behind to handle the postback, etc.  What I want to do is hide the button for certain content types or based on metadata for the document.  I override the visible property etc in my code behind and try to hide but the button still displays.  Thanks in advance for your help.  Below is the code behind for button/console action (as well as CustomQuickAccess.xml markup):
<?xml version="1.0" encoding="utf-8" ?>
    <Console>
    <references>
        <reference TagPrefix="myToolbar"
        assembly="MyCustom_PageEditToolbarQuickAccess, Version=1.0.0.0,
        Culture=neutral, PublicKeyToken=f3a1dd21f335f2ad"
        namespace="MyCustom_PageEditToolbarQuickAccess" />
    </references>
    <structure>
        <ConsoleNode
            Action="myToolbar:PageEditingToolbarArchive"
            DisplayText="Archive Item"
            ConfigMenu="Add"
            UseResourceFile="false"
            Sequence="1900"
            RequiredRightsMode="Any"
            HideIfDisabled="true"
            ID="ArchiveItem" />
        <ConsoleNode
            Action="MyToolbar:PageEditingToolbarRetain"
            DisplayText="Keep Item"
            ConfigMenu="Add"
            UseResourceFile="false"
            Sequence="1901"
            RequiredRightsMode="Any"
            HideIfDisabled="true"
            ID="KeepItem" />
    </structure>
    </Console>

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.WebControls.EditingMenuActions;
using Microsoft.SharePoint.Publishing.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace MyCustom_PageEditToolbarQuickAccess
{
    public sealed class PageEditingToolbarArchive : ConsoleAction
    {

    SPListItem _item;

    /// <summary>
    /// constructor
    /// </summary>
    public PageEditingToolbarArchive()
        : base()
    {
        _item = SPContext.Current.ListItem;
        this.DisplayText = "Archive Item";
        //this.ImageUrl = "/_layouts/images/bdc1tom.gif";

    }

//HERE IS MY INTENT--------
    //public override bool Visible
    //{
    //    get
    //    {
    //        SPListItem item = SPContext.Current.ListItem;
    //        if (MySPutility.Content.doesContentTypeExpire(item)
    //            return false;
    //        else
    //            return base.Visible;
    //    }
    //    set
    //    {
    //        base.Visible = value;
    //    }
    //}

    /// <summary>
    /// returns the permissions required to use this action,
    /// otherwise button is disabled
    /// </summary>
    public override SPBasePermissions UserRights
    {
        get {
            if (_item != null && MySPutility.Content.doesContentTypeExpire(_item))
            {
                return SPBasePermissions.EditListItems;
            } else {
                return SPBasePermissions.EmptyMask;
            }
            //return SPBasePermissions.FullMask;
            //return SPBasePermissions.BrowseUserInfo;

        }
    }

    /// <summary>
    /// Page must be published to archive
    /// </summary>
    public override AuthoringStates RequiredStates
    {
        get
        {
            return AuthoringStates.IsPublishingPageTrue;

        }
    }

    public override void RaisePostBackEvent(string eventArgument)
    {
        string destinationListName = MySPutility.PropertyBag.PropertyBagValue("ArchiveLocation", SPContext.Current.ListItem.Web.Site.WebApplication);
        string archivedFileLocation = "";

        if (eventArgument == PageEditingToolbarArchive.ArchivePostBackEventArgument)
        {
            try
            {
                SPListItem item = SPContext.Current.ListItem;
                archivedFileLocation = MySPutility.Site.ArchiveItem(item, ((SPDocumentLibrary)item.Web.Lists[destinationListName]).RootFolder.Url, item.Web);
            }
            catch (Exception ex)
            {
                ConsoleNode actionsNode = new ConsoleNode();
                ConsoleNode exitNoArchive = new ConsoleNode(actionsNode);

                exitNoArchive.Action = new ExitWithoutSavingAction();
                exitNoArchive.Action.ID = "archiveDocumentErrorActionNeSave";
                actionsNode.ChildConsoleNodes.Add(exitNoArchive);
                this.ShowError(ex, new ConsoleError(ex.Message, actionsNode));
            }
            finally
            {
                SPUtility.Redirect(archivedFileLocation,
                    SPRedirectFlags.Default, Context);
            }

        }
        //base.RaisePostBackEvent(eventArgument);
    }

    public override string NavigateUrl
    {
        get
        {
            return "javascript:" +
                Page.ClientScript.GetPostBackEventReference(this,
                PageEditingToolbarArchive.ArchivePostBackEventArgument);
        }
        set
        {
            base.NavigateUrl = value;
        }
    }

    private const string ArchivePostBackEventArgument = "archiveDocumentItem";
}

}


text:
Q: How to purposely throw an error to test database rollback? I have the following code within my application:
try {
    //start transaction
    repository.startTransaction();

    //carry out deletion logic
    repository.deletedata()

    //commit all 3 transactions
    repository.commitTransaction();

} catch (Exception e) {
    repository.rollback();
}

How can I intentionally throw an error within this code to test if the data is correctly being rolled back?

A: You are getting testing wrong here.
You should be doing two things instead: you write a test that makes sure that your rollback method does what it promises to do. You test that on the side.
Then you have another unit test that simply makes sure that whenever there is an exception within your try block that the expected call to rollback takes place.
If you really want to do a functional test that does end-2-end testing including rollback, then you have to add some injection mechanism, something like:
interface ErrorInject {
  void throwException();
}

and in your try block, you would have something like:
try {
  repository.startTransaction();
  inject1.throwException();
  repository.deletedata()
  inject2.throwException();
  repository.commitTransaction();
}

and by default, those two "inject" objects simply do nothing; but for your test case, you make sure that one of those two objects really throws an exception.
But of course - you don't want to do something like that in your production code. So - you better step back and think if my first suggestion works for you.
One alternative could be aspect oriented programming; which might allow you to use some annotation for example to instruct your framework to  fail at a certain method call. But as said: you shouldn't pollute your production code with "testing aspects".


text:
Q: Align custom view in relative layout dynamically not working android I have a created a custom view , in relative layout .

I'm able to align it in in center/left/right through xml but not
  programatically

.
Custom View
public class HotspotView extends RelativeLayout {

    public HotspotView(Context context) {
        super(context);
        init(context);
    }

    public HotspotView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public HotspotView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.hotspot_view, this);
    }
}

Custom view xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/hotspot_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/tohome"

        />

</RelativeLayout>

Activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"

    >

    <VideoView
        android:id="@+id/vv_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:clickable="true"
        android:onClick="onclick"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:contentDescription="@string/content_description"
        android:onClick="onclick"
        android:scaleType="fitXY"
        android:visibility="gone"

        />

    <ImageView
        android:id="@+id/lv_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:contentDescription="@string/content_description"
        android:onClick="onclick"
        android:visibility="gone" />

    <

    <android.gesture.GestureOverlayView
        android:id="@+id/gesture_area"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1.0"
        android:alpha="1.0"
        android:background="@android:color/transparent"
        android:gestureColor="@android:color/white"
        android:onClick="onclick"
        android:visibility="visible" />

    <WebView
        android:id="@+id/ticker_webview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:visibility="gone"></WebView>

    <WebView
        android:id="@+id/wv_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:adjustViewBounds="true"
        android:onClick="onclick"
        android:scaleType="fitXY"
        android:visibility="gone"

        />

    <ProgressBar
        android:id="@+id/webview_progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:visibility="gone" />

        <com.devstring.imageframe.views.HotspotView
            android:id="@+id/hotspot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:clickable="true"
            android:visibility="visible" />

</RelativeLayout>

Code:
 RelativeLayout.LayoutParams lp = new

RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.MATCH_PARENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        ImageFrameActivity.hotspotView.setLayoutParams(lp);
           ImageFrameActivity.hotspotView.setVisibility(View.VISIBLE);

I have gone through various similar questions but I'm not able to resolve the problem.

A: try this :
 RelativeLayout.LayoutParams lp =
(RelativeLayout.LayoutParams) ImageFrameActivity.hotspotView.getLayoutParams();
 lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 ImageFrameActivity.hotspotView.setLayoutParams(lp);

A: Try using
 lp.gravity = Gravity.LEFT;


text:
Q: Understanding Flash SWC's imported into Flex Builder 3 and key framed animation I am trying to understand what is going on in a SWC that I am importing from Flash CS4 into Flex Builder 3. Specifically I am using a SWC supplied by a Designer as the animation for a custom preloader (a subclassed DownloadProgressBar).
The issue I am trying to understand is, once the FlexEvent.INIT_COMPLETE is fired, I cleanup by removing the swc by running this :
removeChild(myPreloader);
myPreloader = null;

though even after I have removed this (which is successful, as I have checked by comparing this.numChildren before and after the call) the key framed animation still continues to run (not visibly). This has been detected by the Designer placing a trace in the time line of the animation (in Flash).
Can anyone tell me why is it, that even after I have removed the animation from the subclassed DownloadProgressBar, it still keeps running ?
Also, is it standard practice when importing SWCs to manage the cleanup of resources from the Flash side of things (much like releasing memory in obj-c). I find it counter intuitive that removing the child from the Flex side does not stop the animation.
Any clues to this would be greatly appreciated.

A: Basically, your SWC file is nothing more than a ZIP containing a SWF.  So what you're doing is removing a MovieClip from the stage, but it is NOT stopping or unloading it.  You might want to try
myPreloader.stop();

to stop the animation and
myPreloaderLoader.unload();

after you removed the item from the stage to free up memory.
Beware, though: the Flash Player garbage collection does not always work correctly.  If there is any kind of ActionScript running within myPreloader, chances are it will continue to run, and it will be ignored during garbage collection.  It is usually best to include a clear() or destroy() method for all AS classes and call it upon Event.REMOVED_FROM_STAGE.
This would have to be done by your designer colleague, but in my experience it is the cleanest procedure.


text:
Q: EventTrigger и PreviewMouseMove Как правильно установить <EventTrigger RoutedEvent="PreviewMouseMove">, чтобы ListBoxItem менял цвет?
<ListBox Grid.Column="0" ItemsSource="{Binding Category}" Background="#171717">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <ListBoxItem>
                            <ListBoxItem.Content>
                                <StackPanel Orientation="Horizontal">
                                    <Image></Image>
                                    <TextBlock Text="{Binding Name}"></TextBlock>
                                </StackPanel>
                            </ListBoxItem.Content>
                        </ListBoxItem>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="Background" Value="LightSteelBlue"/>
                        <Setter Property="Padding" Value="5"/>
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Foreground" Value="White"/>
                                <Setter Property="BorderThickness" Value="0"/>
                                <Setter Property="Background" Value="Red"></Setter>
                            </Trigger>
                            <EventTrigger RoutedEvent="PreviewMouseMove">
                                <!--<Setter Property="Foreground" Value="Black"/> как реализовать такие сеттеры?
                                <Setter Property="BorderThickness" Value="2"/>
                                <Setter Property="Background" Value="Red"/>-->
                            </EventTrigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
            </ListBox>

A: <EventTrigger RoutedEvent="PreviewMouseMove">
    <BeginStoryboard>
        <Storyboard>
            <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(ListBoxItem.Background).(SolidColorBrush.Color)">
                <EasingColorKeyFrame KeyTime="0" Value="Red" />
            </ColorAnimationUsingKeyFrames>
            <ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(ListBoxItem.BorderThickness)">
                <EasingThicknessKeyFrame KeyTime="0" Value="2"/>
            </ThicknessAnimationUsingKeyFrames>
        </Storyboard>
    </BeginStoryboard>
</EventTrigger>

При изменении таким же образом Foreground - ошибки, так что будьте осторожны)


text:
Q: what is the definition of an interpretation of first order theory $T$ ? what is a model for $T$? what is the definition of an  interpretation of  first order theory $T$ ? what is a model for $T$ ?
can you give me the definition supported with some simple examples ?

i read the definition in first order mathematical logic by angelo margaris , 1990 ed , dover publications , in page 35
but the definition made no sense for me..
thanx

A: The entry on Wikipedia: First-order Logic helps to disambiguate the terms, and sort of gives examples.
See especially, under the heading "Semantics":

*

*"First order structure"

"The most common way of specifying an interpretation (especially in mathematics) is to specify a structure (also called a model; see below). The structure [model] consists of a nonempty set D that forms the domain of discourse and an interpretation I of the non-logical terms of the signature. This interpretation is itself a function..."

*"Satisfiability",

*the sub-section "first-order theories and models",

*

*"A first-order structure that satisfies all sentences in a given theory is said to be a model of the theory."

One great resource, as you embark on your study of Enderton (and perhaps good to read before digging deeply into Enderton) is Paul Teller's Logic Primer. (It's free to download, and importantly, discusses interpretations and models extensively, as it does tautological implication, wff, and First Order Logic in general.)

A: Consider for example the theory of partial ordered groups:
In their language there is a binary operation symbol, $\cdot$ (the multiplication), a constant symbol $1$ (the unit), a unary operation symbol ${()}^{-1}$, and a binary relation symbol $\le$. (The equality symbol is usually assumed to be also present, by default.) An axiom system for it is the $6$ element set $T$ of the following formulas ($T$ itself is also called the theory):

*

*$\forall x\forall y\forall z \ ((x\cdot y)\cdot z=x\cdot(y\cdot z))$

*$\forall x\ (1\cdot x=x)$

*$\forall x\ (x^{-1}\cdot x=1)$

*$\forall x\ (x\le x)$

*$\forall x\forall y\forall z\ ((x\le y\,\land\, y\le z )\implies x\le z)$

*$\forall x\forall y\forall z\ (x\le y \implies (x\cdot z\le y\cdot z\ \land\ z\cdot x\le z\cdot y) )$

A model of $T$ is a realization of the operation and relation symbols on a base set such that they satisfy the axioms. So, first we have to consider a model $\mathfrak M$ for the given first order language: it is thus far nothing else than a set $M$, equipped with a binary ($\mu:M\times M\to M$), a unary ($\sigma:M\to M$) and a constant ($c\in M$) operation, and a binary relation $(L\subseteq M\times M)$.
This $\mathfrak M$ is said to be a model for $T$, if all elemets of $T$ is satisfied on $\mathfrak M$ when interpreting the symbols accordingly, with respect to all evaluations of the variables (whenever the variable $x$ is evaluated in $M$,  $x\cdot y$ is evaluated as $\mu(x,y)$, $x^{-1}$ as $\sigma(x)$, $1$ as $c$, and $x\le y$ as $(x,y)\in L$).


text:
Q: class diagram mvc javascript&C# I roughly know how to make a mvc uml class diagram en can find enough info/ examples on the internet. The only thing i cant find info about is if it makes a difference when you have a jacascript controller/model and a c# controller/model.

A: In general: no.
UML is technology independent. Most models don't assume the technology. MVC can also be applied to different programming languages.
You only need to be aware that there are some concepts that are not handled by particular languages. The only thing that comes to my mind here is multiinheritance. Just use interfaces instead of (eventual) multiinheritance and there'll be no problem.
I can also imagine that some details can be designed in different ways to achieve better performance, but you'd need to know both languages perfectly to be able to make such decisions.
So don't bother about specific language and your diagram will be fine.


text:
Q: Getting output as NaN when calculating the sum values I am trying to generate the SUM of some numbers, however, getting output as   NaN when calculating the sum values
Below is the sample code
Demo
$("#rTpe2").keyup(function(e){
  $("#rFor2").val((this.value * $("#PerHourRate2").val()).toLocaleString('en-IN'));
  $("#rFor3").val.toLocaleString('en-IN')(Number($("#rFor1").val().toLocaleString('en-IN')) + Number($("#rFor2").val().toLocaleString('en-IN')))
});

A: val().toLocaleString() is not valid.
do like below:-
Example:-

$('tr').find('td:eq(2) input').keyup(function(){
 var final_td_value = $(this).val()*  $(this).closest('td').prev('td').find('input').val();
 var final_bar_value =final_td_value+Number($("#rFor2").val().replace(/,/g , ''));
 $(this).closest('td').next('td').find('input').val(final_td_value.toLocaleString('en-IN'));
  $("#rFor3").val((Number($("#rFor1").val().replace(/,/g , ''))+Number($("#rFor2").val().replace(/,/g , ''))).toLocaleString('en-IN'))

});

Technology Design Services

        Service Area
        Per Hour Rate
        Number Of Hours
        Total Rate

        Service1

<input  name="" type="number" placeholder="" class="form-control input-md"id="PerHourRate1"type="text" value="2325" readonly>

<input  name="" type="number" placeholder="" class="form-control input-md"value="0" id="rTpe1">

<input  name="" type="text" placeholder="" class="form-control input-md"value="0" id="rFor1" readonly>

        Service2

<input  name="" type="number" placeholder="" class="form-control input-md"id="PerHourRate2"type="text" value="2025" readonly>

<input  name="" type="number" placeholder="" class="form-control input-md"value="0" id="rTpe2">

<input  name="" type="text" placeholder="" class="form-control input-md"value="0" id="rFor2" readonly>

<input  name="Total" type="text" placeholder="" class="form-control input-md"value="0" id="rFor3" readonly>


text:
Q: boost asio multicast rejoining a group I've implemented a set of successfully functioning multicast readers but periodically and randomly during the day one or more of them loses a block of 2 minutes of data. My working theory is that either the router's periodic request for report is getting lost or the host report is getting lost. So I would like to preemptively send a report to the router on a some interval. So the question is how would I do that? I don't see a rejoin method in boost:asio for multicast. Any ideas would be greatly appreciated.
// code snippet from the constructor method
//
boost::asio::ip::udp::endpoint listen_endpoint(listen_address, mcPort);
socket_.open(listen_endpoint.protocol());
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket_.bind(listen_endpoint);

boost::asio::socket_base::receive_buffer_size option(65536*16);
socket_.set_option(option);
//
// Join the multicast group.
//
socket_.set_option(boost::asio::ip::multicast::join_group(multicast_address));

m_TimerRejoinGroup.expires_from_now(boost::posix_time::seconds(10));
m_TimerRejoinGroup.async_wait(boost::bind(&Feed::handleRejoin, this));

A: In answer to your direct question, there is no rejoin option, but you can leave and join again
socket_.set_option(boost::asio::ip::multicast::leave_group(multicast_address));
socket_.set_option(boost::asio::ip::multicast::join_group(multicast_address));


text:
Q: Fetching data till the end instead of using multiple next(v)[1] Hi i have a python code that grab data from sample_data.csv before parsing them into out.csv.
Do see the image for better visualisation of sample_data.csv
http://i.imgur.com/wwi4RC7.jpg
My question is how do i start from the the last next(v)[1] in
datetime = next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1]

and begin all the way till the end of the line instead of being silly and using multiple next(v)[1]? This is an issue as different receipt has different amount of line thus i cant have a fix number of next(v)[1] for transaction

transaction= next(v)[1], next(v)[1],
  next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1]

import csv
    from itertools import groupby
    from operator import itemgetter
    import re

    with open("sample_data.csv", "rb") as f, open("out.csv", "wb") as out:
        reader = csv.reader(f)
        next(reader)
        writer = csv.writer(out)
        writer.writerow(["Receipt ID","Name","Address","Date","Time","Items","Amount","Cost","Total"])
        groups = groupby(csv.reader(f), key=itemgetter(0))
        for k, v in groups:
            id_, name = next(v)
            add_date_1, add_date_2 = next(v)[1], next(v)[1]
            combinedaddress = add_date_1+ " " +add_date_2
            datetime = next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1]
            abcd = str(datetime)
            dateprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(1)
            timeprinter = re.search('(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)', abcd).group(2)

            transaction= next(v)[1], next(v)[1], next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1],next(v)[1]
            writer.writerow([id_, name, combinedaddress, dateprinter, timeprinter, transaction])

A: If I understand the question correctly, you could use a list comprehension to finish reading values in v , like that :
transaction = [ x[1] for x in v ]

That code will be like grabing all remaining  next(v)[1] until the end of v.
Side note : calling next(v) all the time is quite ugly and unpractical, you could instead start by converting v to a list and then use simple list slicing to get what you want :
 v = list(v)
 id_, name = v[0]
 add_date_1, add_date_2 = [x[1] for x in v[1:3]]
 ...
 transaction = [ x[1] for x in v[1234:] ]


text:
Q: Precedence of CSS stylesheet links with title attribute I have seen:

*

*CSS 2, precedence of stylesheets imported using link element

*In which order do CSS stylesheets override?

*stylesheet - Can one CSS file take priority over another CSS file?
They all seem to say that, for the same selector occurring multiple times, the last one wins. However that is not what happens for me. So given that "Aqua.css" has:
body {color:aqua;}

And "Red.css" has:
body {color:red;}

Then using the following:
<link rel="stylesheet" type="text/css" href="Aqua.css" title="Aqua"/>
<link rel="stylesheet" type="text/css" href="Red.css" title="Red"/>
<style type="text/css">
body {color: lime;}
body {color: yellow;}
</style>

The last one, Yellow, is used, as the other answers say. If I change that however to:
<style type="text/css">
body {color: lime;}
body {color: yellow;}
</style>
<link rel="stylesheet" type="text/css" href="Aqua.css" title="Aqua"/>
<link rel="stylesheet" type="text/css" href="Red.css" title="Red"/>

Then Aqua is used, not the last one, Red. See Precedence of CSS rules Sample 2. The body color is Aqua yet Aqua.css is before Red.css. All the answers I find say that the body color would be Red.
Whenever I have multiple links to css stylesheets and the only difference among them is the color of something (element or class or whatever) then the first stylesheet is used, not the last, yet that seems to not be what everything I read says should happen. I have tried Edge, Chrome and IE; I notice no relevant difference among them.
So I have the following two questions:

*

*Am I correct that the behavior I am seeing (the first link tag is used instead of the last) is different from the other answers?

*If so, then why?

I apologize if I should have posted an answer to one of the other threads, but I think it is cleaner to create a new question.
The reason I am asking is that I am trying to create a dynamic stylesheet system so understanding the precedence is more important, it is less effective to just try something to see what works than in normal circumstances. I will attempt to interpret the specifications but to the extent that has been in other answers, I want to understand what has been provided here in other threads.

A: Disclaimer: My old answer and line of thinking was completely wrong, so I've deleted it, and am posting this as a replacement so as not to be confused with any of the prior discussion.
When you give a <link> element a title attribute, you are defining it as an alternative style sheet set.
<link rel="stylesheet" type="text/css" href="Aqua.css" title="Aqua"/>
                                                       ^^^^^^^^^^^^
<link rel="stylesheet" type="text/css" href="Red.css" title="Red"/>
                                                      ^^^^^^^^^^^

The precedence of styles was a red herring. The Red.css styles were never being applied at all, because that style sheet set was not currently active.
Per the spec:

Also, the title attribute has special semantics on this element: Title of the link; alternative style sheet set name.

Also worth reading: "CSS: alternative style sheets":

A document doesn't need to have a single style sheet. You can give it a default style and any number of alternatives for the reader to choose from. This page, for example, has as alternatives all the W3C Core Styles, plus two style sheets found elsewhere on the Web (author: David Baron).
How the reader can select the alternatives depends on the browser. Not all browsers yet offer a menu for it, but many do. E.g., in Opera, Internet Explorer and Firefox you can find the styles under the "View" menu. As of 2012, Chrome requires an extension (e.g., Decklin Foster's Style Chooser).

You're supposed to use rel="alternative stylesheet" when defining alternative stylesheets, but this appears to be a case where the browser anticipated the behavior. Remove the title attributes, and the <link> elements return to their standard behavior as defined in the spec.


text:
Q: Woocommerce Change 'Select Options' button text for specific category I have the following code that changes the button text of a variable product from 'select options' to select dates.
add_filter( 'woocommerce_product_add_to_cart_text', 'change_select_options_button_text', 9999, 2 );

function change_select_options_button_text( $label, $product ) {
   if ( $product->is_type( 'variable' ) ) {
      return 'Select Dates';
   }
   return $label;
}

I'm wanting to apply this only to a certain category instead of it applying to every variable product. Would this be possible?
I've tried adding : if ( is_product_category('cat1')
like so but have had no luck.
add_filter( 'woocommerce_product_add_to_cart_text', 'change_select_options_button_text', 9999, 2 );

function change_select_options_button_text( $label, $product ) {
   if ( is_product_category('cat1') && $product->is_type( 'variable' ) ) {
      return 'Select Dates';
   }
   return $label;
}

Any help would be greatly appreciated.
Thank You!

A: add_filter('woocommerce_product_add_to_cart_text', 'change_select_options_button_text', 9999, 2);

function change_select_options_button_text($label, $product) {
    if ($product->is_type('variable') && has_term(array('kids clothing'), 'product_cat', $product->get_id())) {
        // Do something if the product is variable and in category "kids clothing"
        return 'Select Dates';
    }
    return $label;
}


text:
Q: Download Themes From LocalHost WordPress Site I am wanting to download themes from my localhost install of Wordpress.  My issue is that anytime I click download, I get a pop-up asking me for Connection Information.
I tried to input localhost and my Wordpress username and password, but it will not download.  What step have I missed here?
edit
And I am running localhost on a Ubuntu laptop with LAMP installed.
edit 2
This is an image of the request screen that I get, where I input localhost and my valid username and password

And this is an image of the error I receive when I try those reds

A: Probably your local FTP service is not running. You can verify this by trying to connect to the local FTP server at the command prompt:
ftp localserver

and it will ask for your credentials.
Also possible is that 'localserver' is not being resolved locally. You can check that with a command
nslookup localserver

And seeing if it gives you your servers' IP address.
But this is not a WP Development question. Ask the googles/bings/ducks for help with enabling/starting your local FTP service.

A: Try entering your system username and password. It sounds like you don't have permissions set correctly (or rather, in LAMP they are but not for what you are trying to do with WordPress). Also, you might have a look at the FS_METHOD constant and try setting it in to ftpext (along with the other required settings) in wp-config.php.
If these things don't work, consider editing your question to include a screen shot of the username and password window you are seeing so that we know exactly which screen is blocking you.


text:
Q: How to make PhpStorm autocomplete props from a node_modules library In my React project I've installed blueprintjs as a dependency.
When I do this in code:
import {Popover} from "@blueprintjs/core";

...

render() {
        ...
        <Popover /* No autocomplete for props */>
        </Popover>

I don't get any autocomplete for PropTypes of Popover component.
Note: the Popover component is written in TypeScript.
How can I get autocomplete to work in PhpStorm?

A: The issue is tracked at WEB-38214, please follow it for updates


text:
Q: how to see Spring Batch Step descriptions in STS Bean list I use STS and am writing a Spring-Batch application.  When I click on the xml with all my beans, it opens a panel where I can look at the job configuration.  There are 6 tabs to choose from: Source:NamesSpaces:OverView:batch:batch-graph:beans.
One day out of the blue on the batch tab, I saw the ID of each job step displayed to the right of the Step in the left-side list.  Now, I can't figure out how to see the ID again.  It's gone.
I don't know what I did to make it show, nor what I did to lose it.
It makes working with the steps far easier when you can see the ID.
Thanks,


text:
Q: Irregular Spacing Between List Items Bear with me I am new at this
I have been faced with an issue of irregular spacing between list items, it looks like the image below. First, when I did not as many list items, it was normal, then once I exceeded a number, which I do not know it started showing spaces:

I played around with it some and apparently margins have nothing to do with it. Below are the HTML5 code and the CSS for the gallery and the list items. Here is my code:
CSS
#gallery {
  margin: 0;
  padding: 0;
  list-style: none;
}

#gallery li {
  float: left;
  width: 45%;
  margin-left: 2.5%;
  margin-bottom: 2.5%;
  background-color: #212121;
  color: #fff;
  font-weight: bold;
  cursor: pointer;
}

HTML

Abraham Lincoln

Night of the Living Dead

Africa Screams

Born to Win

Meet John Doe

Charade

The Terror

Angel and the Badman

Rock, Rock, Rock!

A: Since you have given each thumbnail a class try giving the thumb nails a class styling width and height so that they don't go beyond a fixed grid.

A: You can use display inline block instead of float, check following css
#gallery {
    margin: 0;
    padding: 0;
    list-style: none;
    font-size: 0px;
}
#gallery li {
    display: inline-block;
    font-size: 16px;
    vertical-align: top;
    width: 45%;
    margin-left: 2.5%;
    margin-bottom: 2.5%;
    background-color: #212121;
    color: #fff;
    font-weight: bold;
    cursor: pointer;
}


text:
Q: high-speed uart in python I have a microcontroller that sends data via UART at 3 MBaud. The microcontroller sends a start/status Byte every 8000 Bytes. I d'like my python script to read all data and analyse the data between the start bytes.
I know that Python is able to handle 3 MBaud since that code snippet shows the correct positions of start bytes:
ser =  serial.Serial('COM3', 3000000, timeout=None)

_RawData = ser.read(100000)

for cnt in range(0, 100000, 1):
    #search for start byte and print the position
    if(_RawData[cnt] < 128): print(cnt)

But I need to constantly read the data stream, with that example I loose data between the "ser.read(x)" commands. So I need to compare the data while reading the stream:
ser =  serial.Serial('COM3', 3000000, timeout=None)

_RawData = []
cnt = 0

for c in ser.read():
    cnt += 1
    #search for start byte
    if(c < 128):
        #print start byte position
        print(cnt)

        # -= start thread =-

        _RawData.clear()
    _RawData.append(c)

But found out that reading one single byte is too slow for that baudrate, the start byte position is practically randomly generated. Is there a way I can read my data stream, without loss?

A: I manage to get it to work for me. As suggested in other threads, I implemented the function ser.inWaiting(), which gives the number of bytes waiting in the input buffer (which on my system is limited to 4096 Bytes) and read that amount from uart. Then I looked for the start byte and started a thread to analyse the data:
ser =  serial.Serial('COM3', 3000000, timeout=None)
_RawData = []

while True:
    #get data in input buffer
    bytesToRead = ser.inWaiting()
    Buffer = ser.read(bytesToRead)

    for cnt in range(0,bytesToRead,1):
        #search for start byte
        if(Buffer[cnt] < 128):
            #print bytes between start bytes
            print(len(_RawData))

            # -= start thread =-

            _RawData.clear()

        _RawData.append(Buffer[cnt])

    #wait a short time for the buffer to fill
    time.sleep(0.001)

That seems to work for now. Thanks for the help.


text:
Q: How to fix spaceship interaction with the boundaries and more? #pragma once
#include "Globals.h"
#include "ResourceManager.h"
#include "ResourceIdentifier.h"
#include "Entity.h"
#include <iostream>
#include <cmath>

class Shooter : public Entity{

private:
    bool m_isClicked;
    bool m_ableToMove;
    float m_lastAngle;
    bool m_mouseInBounds;
    sf::Vector2i m_targetPos;

public:
    Shooter();
    void initialize(const TextureManager&);
    void moveShip(float dt);
    void angleShipToMouse(const sf::Vector2i&);
    void handleInput(const sf::Event&, const sf::Vector2i&);
    void update(const sf::Vector2i&, float);
    void adjustingTarget();
};

#include "SpaceShooter.h"

Shooter::Shooter() : m_ableToMove(false), m_isClicked(false), m_lastAngle(0)
{
}

void Shooter::initialize(const TextureManager& text)
{
    m_speed = sf::Vector2i(500, 500);
    this->m_sprite.setTexture(text.get(TextureID::Shooter));
    this->m_sprite.setOrigin(m_sprite.getGlobalBounds().width / 2.0f, m_sprite.getGlobalBounds().height / 2.0f);
    this->m_sprite.setPosition(Globals::_windowWidth / 2.0f, Globals::_windowHeight / 2.0f); //start 50 units out
}

void Shooter::moveShip(float dt) {

    if (m_isClicked && !m_ableToMove) {
        m_ableToMove = true;
        m_isClicked = false;
    }

    if (m_ableToMove) {
        adjustingTarget();
        sf::Vector2f shipComponentDistances(abs(m_targetPos.x - getX()), abs(m_targetPos.y - getY()));
        sf::Vector2f shipVelocity(cos(m_angle * Globals::deg2rad) * dt * m_speed.x,
        sin(m_angle*Globals::deg2rad) * dt * m_speed.y);

        float targetDistance = sqrt(pow(shipComponentDistances.x, 2) + pow(shipComponentDistances.y, 2));
        float distanceToTravel = sqrt(pow(shipVelocity.x, 2) + pow(shipVelocity.y, 2));

        if (targetDistance > distanceToTravel) {
            this->m_sprite.move(shipVelocity);
            m_lastAngle = m_angle;
    //  std::cout << distance << std::endl;
        }
        else {
            this->m_sprite.setPosition(m_targetPos.x - 0.01, m_targetPos.y - 0.01);
            std::cout << m_lastAngle << std::endl;
            this->m_sprite.setRotation(m_lastAngle);
            std::cout << this->m_sprite.getRotation() << std::endl;
            m_ableToMove = false;
            m_isClicked = false;
        }
    }
}

void Shooter::angleShipToMouse(const sf::Vector2i& mousePosition) {

    //position of mouse relative to ship in 0 rotation reference frame(absolute)
    sf::Vector2f mouseRelativeShip(mousePosition.x - getX(), mousePosition.y - getY());

    float rotation = atan2(mouseRelativeShip.y, mouseRelativeShip.x)*Globals::rad2deg; //atan2 produces negative angles if vector is in QUADS 1&2, positive in QUADS 3&4

    this->m_sprite.setRotation(rotation);

    m_angle = this->m_sprite.getRotation();
}

void Shooter::handleInput(const sf::Event& event, const sf::Vector2i& mousePos) {
    if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) {
        if (!m_ableToMove && !m_isClicked) {
            m_isClicked = true;
            m_targetPos = mousePos;
        }
    }
}

void Shooter::update(const sf::Vector2i& mousePosition, float dt) {
    angleShipToMouse(mousePosition);
    moveShip(dt);
}

void Shooter::adjustingTarget()
{
    if (m_targetPos.x < spriteWidth() / 2.0f) {
        m_targetPos.x = spriteWidth() / 2.0f;
    }
    else if (m_targetPos.x > Globals::_windowWidth - spriteWidth() / 2.0f) {
        m_targetPos.x = Globals::_windowWidth - spriteWidth() / 2.0f;
    }
    else if(m_targetPos.y < spriteHeight() / 2.0f){
        m_targetPos.y = spriteHeight() / 2.0f;
    }
    else if (m_targetPos.y > Globals::_windowHeight - spriteHeight() / 2.0f) {
        m_targetPos.y = Globals::_windowHeight - spriteHeight() / 2.0f;
    }
}

The problems with my spaceship are:
1. despite not allowing for changing of targetPos when !moving, clicking while its moving to a different location will cause it to redirect the ship. Holding down the ship causes it to follow the mouse cursor.

*once ship reaches the targetPosition, the rotation of the ship gets set to 0, im trying to make it retain the rotation of the angle just prior to it reaching its destination (e.g. distance to targetPos is 0).

*When it reaches the boundaries sometimes it can go through it despite me adjusting the targetPosition if the mouse is too far into a deadzone the ship cannot enter.


text:
Q: How to use update-alternatives per user Is there any way to use update-alternative "user wide" ? I mean that it would be great to set preferences per user.
Does Debian provide some tools for that?

A: Yes, you can absolutely use update-alternatives for yourself. For example, I have different LLVM versions installed under ~/.local/llvm-VERSION. I can install binary links into ~/.local/bin (which is in my $PATH) like this:
alias update-my-alternatives='update-alternatives --altdir ~/.local/etc/alternatives --admindir ~/.local/var/lib/alternatives'
mkdir -p ~/.local/var/lib/alternatives ~/.local/etc/alternatives
version=3.9.0
slaves=""
for b in llvm-${version}/bin/*; do \
    slaves+=" --slave $HOME/.local/bin/$(basename $b) $(basename $b) $(readlink -f $b)" \
done
update-my-alternatives --install $HOME/.local/bin/llvm-config llvm $(readlink -f $(dirname $b)/llvm-config) ${version//./0} ${slaves}

I can repeat the last command for new versions and use update-my-alternatives --config llvm to choose between versions.
If you want to use the pre-existing system alternatives, you could possibly copy over all the files in /var/lib/alternatives to ~/.local/var/lib/alternatives and change all of the system paths in the first section to be user paths (e.g. change /usr to /home/username/.local).

A: Users who don't want to use the system default for an application that uses the alternatives (and an alternate is indeed installed) can always simply use either the correct name or full path for the non-default alternative or set up an alias overruling the symbolic link.

A: Each user can create their own bin directory for example in ~/bin and put that first in their PATH. Inside that directory they can have symlinks to their preferred alternative.
I don't know whether they can use the update-alternative command to update their own directory of symlinks, or if they have to do that manually.

A: I know this is an old question, but I wanted to chime in with a blatant promotion for the tool I just released that helps you configure per-user (or even per-shell !) alternatives:

*

*https://github.com/TekWizely/my-alternatives
You can initialize a shell-specific setup:
$ eval "$( my-alternatives init)"

Or you can initialize a long-lived user-level setup:
# run this once
$ eval "$( my-alternatives init ~/my-alts )"

# place this in your startup scripts
$ eval "$( my-alternatives shellenv ~/my-alts )"

Once configured, setting up a user-local alternative is as easy as:
# equivalent to 'update-alternatives --config <name>'
$ my-alternatives config <name>

NOTE: At the time of this posting, my-alternatives was just released.  As such, only init and config logic has been built.  Other features will come later.


text:
Q: How can i modify a command in MINIX 3.2.1 so that uses my own system call? Good evening you all!
I'm doing homework on minix 3.2.1, where i'm asked to create an new system call,
my_rmdir, that acts exactly like rmdir but also prints the name of the deleted directory. Also I'm supposed to modify the system's source code so when i give the rmdir command then instead of calling the do_rmdir function the system should call my own do_myrmdir function.
In the past, I have done the same homework with the mkdir command but there everything was simple because mkdir was properly declared minix style and I made changes to
/usr/src/servers/vfs/proto.h
/usr/src/servers/vfs/open.c
/usr/src/servers/vfs/request.c
/usr/src/servers/vfs/table.c
/usr/include/minix/callnr.h

and everything worked allright. But now, I think because of the NETBSD code infusion, I'm a bit lost.
Also the point isn't creating a new system call from scratch because first i don't have the knowledge and second the change i need to make is very small.
The number one problem i have is that i can't find where the original do_rmdir is declared and how it is connected with the rmdir command.
In the /usr/src/servers/vfs/table.c file line 58
do_unlink,  /* 40 = rmdir   */

makes it more confusing
Any help or ideas?
If you need further information please ask.
I'm new to the forum, i tried to ask properly, thanks for your understanding.

A: OK, I got it!
The rmdir command calls the do_unlink function and based on what the user rights are, it requests either the rmdir or unlink command. The difference is that unlink can do some dangerous things so it's only for admin use.


text:
Q: After initializing git clone ASP.NET Core MVC app marked as unloaded
What am i doing wrong here and how can I prevent this kind of problem?

A: Here are the steps that I normally do to overcome it.

*

*Try reloading the webproj.csproj files and check if any reference is
missing.

*check for the version in which the code was built and the version you are using.

*Open the web project part directly. For that you first need to remove the existing we project and re add using the add existing
project.


text:
Q: show that $V = \text{ker}(f) \oplus \text{im}(f)$ when $f^2 = f$ If $f$ is an endomorphism of $V$, and $f^2 = f$, show that $V = \text{ker}(f) \oplus \text{im}(f)$
My answer:
$$
f(v) = w \in \text{im}(f)\\
f(f(v)) = f(w) = w
$$
Then we know that every element that is in our image it's not in our kernel, hence:
$$
\text{ker}(f) \cap \text{im}(f) = \left\{0\right\}
$$
Then:
$$
V = \text{ker}(f) \oplus \text{im}(f)
$$
I don't know if wasn't rigorous enough or I'm wrong... Please correct me if I'm wrong! Thanks

A: So far, you've only shown that $K := \ker(f)$ and $I:= \text{Im}(f)$ were in direct sum, not that their sum makes up for the all space $V$, i.e. $V = K + I$.
Hint: Let $v \in V$. Then write $v = v - f(v) + f(v)$ and conclude!

Note: A mapping $p : V \rightarrow V$ s.t. $p^2 = p$ is called a projection.


text:
Q: Delete string match from another file i have 1.txt:
hi aa my name is bb tom
how are you cc today

and i have 2.txt ( the word that i dont want )
aa
bb
cc

and my expected output is
hi my name is tom
how are you today

what i have tried so far is
sed -e "s/$(sed 's:/:\\/:g' 2.txt)/ /"
or
grep -Fvf 2.txt 1.txt

i have more than 100 words that i dont want, so i have to put it in one sentence, thanks

A: without normalizing spaces...
$ sed -f <(sed 's/.*/s_\\b&\\b__g/' remove_list) file

hi  my name is  tom
how are you  today
aardwark

to handle spaces and word boundaries, one alternative
$ sed -f <(sed 's/.*/s_ &\\b__g;s_\\b& __g;s_\\b&\\b__g/' remove) file

however, at this point it's better to switch to awk

A: gawk solution:
awk 'NR==FNR{ a[$0]; next }{ for(i in a) gsub("\\<"i"\\> *","",$0) }1' 2.txt 1.txt

The output:
hi my name is tom
how are you today

*

*a[$0] - accumulating words which should be removed from each sentence

*gsub("\\<"i"\\> *","",$0) - replacing each "unwanted" word (as a whole word) with empty string


text:
Q: node js express session how to keep same for all path and page reload till the browser is open test.js - express code
var express = require('express');
var session = require('express-session');
const bodyParser = require('body-parser');
var app = express();

app.use(bodyParser());
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
 });

 app.use(session({
   secret: 'somerandonstuffs',
   resave: false,
   saveUninitialized: false
 }));

 app.listen(4000, () => {
   console.log("server running on port....", 4000);
   });

   app.get('/getsession', function(request , response){
     console.log("getsession::", request.sessionID);
     if(request.session.uname){
         response.json({username: request.session.uname});
      } else {
         response.json({username: "no user"});
      }
   });

   app.post('/savesession',  function(request , response){
      request.session.uname = request.body.loginuname;
      console.log("save session::", request.session);
      response.json({username: request.session.uname});
   });

app.js - user/client code
function login(){
           $.ajax({
                url: 'http://127.0.0.1:4000/getsession',
                type: 'get',
                dataType: 'json',
                crossDomain: true,
                success: function(result){
                    console.log( "result::: ", result );
                },
                error: function(xhr, resp, text){
                    console.log("xhr:: ", xhr , "resp::: ", resp , "text::: ", text);
                }
            });

        $("#ahrefbtn").on('click', function(){
           var data = $("#formdata").serializeArray();
           $.ajax({
                    url: 'http://127.0.0.1:4000/savesession',
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function(result){
                     console.log( "result::: ", result );
                   },
                error: function(xhr, resp, text){
                    console.log("xhr:: ", xhr , "resp::: ", resp ,
                    "text::: ", text);
                }
            });

    $(document).ready(function(){
      login();
    });

Above code works fine for postman get and post requests.
But when I use browser-chrome(session cookies allowed) on page reload/refresh it creates new sessionid and each time new session is getting generated.
How do i get same session each time to retrieve last session data.
In app.js on page reload/refresh it calls getsession api and on button click it it calls savesession api.
app.js api calls are executes properly.


text:
Q: Pandas (0.16.2) Show 3 Rows of Dataframe I'm trying to limit the output of the pandas dataframe to the first 3 rows.  However I get a summary of all 500000 data points.  When I run this without specifying "Time [s]" as the index it works properly and I only get 3 rows of data.  I'm running Pandas 0.16.2 and Python 3.
%matplotlib inline
import pandas as pd
from sys import platform as _platform
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier
plt.rcParams['figure.figsize'] = (15, 5)

shot1 = "C:\\Users\ELEC-LAB_1\Documents\GitHub\Black Powder\BlackPowder_Shot-1.csv"
shot1_data = pd.read_csv(shot1, parse_dates=['Time [s]'], index_col='Time [s]') # Read the data using the time as the index.
shot1_data[:3]

Time [s] CH 1 [psi] CH 2 [psi] CH 3 [psi] CH 4 [psi] CH 5 [psi] CH 6 [psi] CH 7 [psi] CH 8 [psi] CH 9 [psi] CH 10 [psi] CH 16 [V]
-0.200000
-0.018311 -0.054932 -0.012207 -0.054932 -0.006104 -0.048828 -0.030518 -0.018311 0.030518 -0.018311 0.011597
-0.199998
0.006104 0.109863 0.048828 0.048828 -0.018311 -0.054932 0.042725 0.054932 -0.042725 0.024414 0.010986
-0.199996
0.012207 -0.042725 0.061035 -0.097656 0.067139 0.006104 -0.054932 -0.067139 -0.097656 -0.134277 0.010986
-0.199994
0.012207 -0.006104 -0.079346 0.036621 -0.036621 0.042725 0.006104 0.067139 0.012207 -0.042725 0.011597
-0.199992
0.006104 0.067139 0.091553 0.091553 0.024414 0.012207 0.097656 -0.030518 -0.024414 0.061035 0.010986
-0.199990
0.036621 0.006104 0.061035 0.109863 0.073242 0.067139 0.109863 -0.054932 0.158691 0.000000 0.011597
500000 rows × 11 columns

A: You're trying to slice a df which has a datetimeindex using integer values that are not valid which is why you get the full df.
Example:
In [34]:
df = pd.DataFrame(index=pd.date_range(start=dt.datetime(2015,1,1), end=dt.datetime(2015,1,10)))
df[:3]

Out[34]:
Empty DataFrame
Columns: []
Index: [2015-01-01 00:00:00, 2015-01-02 00:00:00, 2015-01-03 00:00:00, 2015-01-04 00:00:00, 2015-01-05 00:00:00, 2015-01-06 00:00:00, 2015-01-07 00:00:00]

If you used head or iloc[:3] then you get the desired result:
In [35]:
df.head(3)

Out[35]:
Empty DataFrame
Columns: []
Index: [2015-01-01 00:00:00, 2015-01-02 00:00:00, 2015-01-03 00:00:00]

In [36]:
df.iloc[:3]

Out[36]:
Empty DataFrame
Columns: []
Index: [2015-01-01 00:00:00, 2015-01-02 00:00:00, 2015-01-03 00:00:00]

That is why when you don't pass param index_col='Time [s]' to read_csv your line of code works as a default int64 index is created for you.