text:
Q: Indefinite retention in Office 365 My Director has come to me very late in a 365 deployment to ask to retain all data indefinitely. I have rejected this partially on GDPR grounds. Although we can set retention for GDPR data specifically.
My question then is, how could I possibly retain all data indefinitely?
I can stop deletion, but this becomes impossible to manage any data then, as files will be mis-created or need moving, its just unworkable.
Is it possible to extend the 2nd stage recycle bin time of the SharePoint Online?
I have tried to explain that any data that needs to be kept for regulatory reasons needs to be stored in a specific site with specific permissions and retention.
365 backups are another option, but I know this has GDPR issues, if we retain specific data in backups.

A: This is really not a good idea to keep data retained indefinitely in SPO. You can definitely keep all data undeleted and try using as many libraries/lists as possible to keep them organized, but eventually it will slow down your whole tenant since there are plenty of limits in SharePoint.
Personally I give you a Not possible as the answer. The retention comes with a 93-day time rage, as well as for the second-stage Recycle Bin, which is managed by Microsoft directly and cannot be extended.


text:
Q: FastCGI with Symfony2 on IIS 6 I'm having problems with getting Symfony2 working with FastCGI on IIS with PHP 5.3.10 VC9 Not thread safe, every time I load the page, I get:
FastCGI Error

The FastCGI Handler was unable to process the request.
Error Details:

The FastCGI process exited unexpectedly
Error Number: -2147467259 (0x80004005).
Error Description: Unspecified error
HTTP Error 500 - Server Error.
Internet Information Services (IIS)

I've been searching around the days and having my fast cgi configured as the following in fcgiext.ini:
EnvironmentVars=PHP_FCGI_MAX_REQUESTS:50000
ExePath=C:\path\to\php-cgi.exe
Arguments=-c "C:\path\to\php.ini"
IdleTimeout=9000000
ActivityTimeout=900000
RequestTimeout=900000
InstanceMaxRequests=50000

I have noticed that I can successfully load phpinfo but just not a symfony2 page
Has anyone come across this issue before? Or has any advice for me on what to try?
Thanks

A: Seemed that it was a problem with PHP 5.3.9, I downgraded to 5.3.6 and everything is now running as expected

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Como acomodar la flecha que indica submenus en una aplicacion de Shiny/R-Studio? Buenas mi consulta es la siguiente, me gustaria acomodar la flecha que indica que se despliega un menu en shiny pero no tengo idea de como hacerlo y buscando en internet no encuentro algo tan especifico. Me gustaria poder verlo como en el cuadro verde pero me sale como esta en el cuadro rojo. Agraezco cualquier ayuda.

Ejemplo reproducible:
global.R
library(shinydashboard)
library(shiny)

ui.R
sidebar <- dashboardSidebar(

    tags$head(tags$style(HTML('.content-wrapper { height: 2000px !important;}'))),

    hr(),

    sidebarMenu(id="tabs",
                menuItem("AAAAAAAAAAAAAAAAAAAAA", icon=icon("chart-bar"),
                         menuSubItem("BBBBBBBBBBBBBBB", tabName = "B", icon = icon("angle-right")),selected=TRUE),

                conditionalPanel("input.tabs == 'B'  || input.tabs == 'C'",

                                 fluidRow(column(1),column(10,

                                                           menuItem("CCCCCCCCCCCCC", tabName="C", icon=icon("chart-line"),
                                                                    menuSubItem("DDDDDDDDDDDDDD", tabName = "D", icon = icon("angle-right")))
                                 )))
                                 ),width = 350,hr())

body <- dashboardBody()

dashboardPage(

    dashboardHeader(title = "Titulo", titleWidth=300),

    sidebar,

    body
)

server.R
shinyServer(function(input, output) {})


text:
Q: Issue with Lagrange interpolation in Matlab I'm having an issue completing this Lagrange function and I'm not sure where I'm going wrong.
I keep getting 'Index exceeds matrix dimensions' error. I assume this is because I'm not moving through the array correctly. I've tried a combination of things but seem to continue coming back to this error.
function y = lagrange(X, Y, x)
n = length(X);
if n ~= length(Y)
 error('X and Y must have the same length.');
end
y = zeros(size(x));
for i = 1:n
  L = ones(size(x));
    for j = [1:i-1 i+1:n]
      if (i~=j)
       L(1:i-1, i+1:n) = L(1:i-1, i+1:n).*(x-X(j))/(X(i)-X(j));
      end
    end
  y = y+Y(i)*L(1:i-1);
end

A: I think the function below is what you need.
function y = lagrangian(X, Y, x)
if length(X) ~= length(Y); error('X and Y must have the same length.'); end
y = zeros(size(x));
for i = 1:length(X)
   L = ones(size(x));
   for j = [1:i-1 i+1:length(X)]
       L = L.*(x-X(j))/(X(i)-X(j));
   end
   y = y+Y(i)*L;
end


text:
Q: C++ Trie Data Structure implementation with multiple parameters I need to create a Trie data structure to store first name, last name and age. I will later need to implement a search for records using last name, or first and last names.
I know how to create a Trie, insert, delete and search. However, I don't know how to store multiple values appropriately (first name, last name and age).
Could someone please point me in the right direction?
#include <string>
#include <iostream>

using namespace std;
const int ALPHA_SIZE = 26;

struct Trie
{
    struct Trie* child[ALPHA_SIZE];
    bool endofstring; //It is true if node represents end of word.
};

// Create new node
struct Trie* createNode(void)
{
    struct Trie* tNode = new Trie;
    tNode->endofstring = false;
    for (int i = 0; i < ALPHA_SIZE; i++)
        tNode->child[i] = NULL;
    return tNode;
}

void insert(struct Trie* root, string key)
{
    struct Trie* curr = root;
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!curr->child[index])
            curr->child[index] = createNode();
        curr = curr->child[index];
    }
    curr->endofstring = true; //last node as leaf
}

bool search(struct Trie* root, string key)
{
    struct Trie* curr = root;
    for (int i = 0; i < key.length(); i++) {
        int index = key[i] - 'a';
        if (!curr->child[index])
            return false;
        curr = curr->child[index];
    }
    return (curr != NULL && curr->endofstring);
}

bool isEmpty(Trie* root) //check if root has children
{
    for (int i = 0; i < ALPHA_SIZE; i++)
        if (root->child[i])
            return false;
    return true;
}

Trie* deletion(Trie* root, string key, int depth = 0)
{
    //If tree is empty return null.
    if (!root)
        return NULL;
    if (depth == key.size()) //If last character of key is being processed,
    {
        if (root->endofstring)
            root->endofstring = false; //then that node will be no more end of string after deleting it.
        if (isEmpty(root)) { //If given key is not prefix of any other string,
            delete (root);
            root = NULL;
        }
        return root;
    }
    //If key not last character,
    int index = key[depth] - 'a';
    root->child[index] =
        deletion(root->child[index], key, depth + 1); //Then recur for the child which will be obtained by using ASCII value.
    if (isEmpty(root) && root->endofstring == false) //If root does not have any child leftand it is not end of another word
    {
        delete (root);
        root = NULL;
    }
    return root;
}

int main()
{
    struct Trie* root = createNode();

    insert(root, "joe");
    insert(root, "hanna");
    insert(root, "john");
    insert(root, "jane");

    search(root, "joe") ? cout << "Key is Found\n" :
        cout << "Key is not Found\n";

    search(root, "he") ? cout << "Key is Found\n" :
        cout << "Key is not Found\n";

    deletion(root, "john") ? cout << "Key is deleted\n" :
        cout << "Key is not Deleted\n";

    return 0;
}

A: It depends on what you need to search by. If you need to search by all elements, then you could use a format of
<FIRST NAME>;<LAST NAME>;<AGE>
Example: John;Doe;16
and use this as the key.
If you need to store additional data, like height, then you could add it to your struct Trie.


text:
Q: Why does TensorBoard embeddings need the events.out.tfevents.[...] file? Why does TensorBoard embeddings need the events.out.tfevents.[...] file?
If I place the following files in a folder:

TensorBoard embeddings can view it:

If I remove events.out.tfevents.1490126578.FRANCKY-PC then TensorBoard embeddings cannot view it anymore. Why?


text:
Q: Find the maximum value $\alpha$ for which $\int_{0}^{\frac{1}{\pi}} \frac{1}{x^\alpha} \sin{\frac{1}{x}}dx$ converges. Many calculus or analysis books write improper integrals $\int_{a}^{b} f(x)dx$, where $f(x)$ is a function such that $\lim_{x\to a} f(x)=+\infty$ or $\lim_{x\to a} f(x)=-\infty$ or $\lim_{x\to b} f(x)=+\infty$ or $\lim_{x\to b} f(x)=-\infty$.
But many calculus or analysis books don't write improper integrals $\int_{a}^{b} f(x)dx$, where $f(x)$ has a dicontinuity of the second kind at $x=a$ or $x=b$.
Why?

So, I am interested in an improper integral $\int_{a}^{b} f(x)dx$, where $f(x)$ has a dicontinuity of the second kind at $x=a$ or $x=b$.
$\frac{1}{x^\alpha} \sin{\frac{1}{x}}$ has a discontinuity of the second kind at $x=0$.
Find the maximum value $\alpha$ for which $\int_{0}^{\frac{1}{\pi}} \frac{1}{x^\alpha} \sin{\frac{1}{x}}dx$ converges.
$\int_{0}^{\frac{1}{\pi}} \frac{1}{x^2} \sin{\frac{1}{x}}dx$ diverges.
$\int_{0}^{\frac{1}{\pi}} \frac{1}{x^1} \sin{\frac{1}{x}}dx$ converges.
$\int_{0}^{\frac{1}{\pi}} \frac{1}{x^{1.5}} \sin{\frac{1}{x}}dx$ converges.

A:
But many calculus or analysis books don't write improper integrals $\displaystyle\int_{a}^{b} f(x)\,\text{d}x$, where $f(x)$ has a discontinuity of the second kind at $x=a$ or $x=b$.
Why?

I guess the reason has to do with cases where $f(x)$ is not Lebesgue-integrable on $(a,b]$ but where $\displaystyle\lim_{{t\to a}^+}\int_{t}^b f(x)\,\text{d}x$ exists. In such cases the authors of an introductory calculus text might not want to confuse people.
To take an example you cited, $\displaystyle\lim_{{a\to0}^+}\int_{a}^{\frac{1}{\pi}} \frac{1}{x^1} \sin{\frac{1}{x}}dx$ is exactly such a case.
$\\$
By the way,
$\displaystyle\int_{a}^{\frac{1}{\pi}} \frac{1}{x^c} \sin{\frac{1}{x}}\,\text{d}x=\int_{\pi}^{1/a} y^{c-2}\sin(y)\,\text{d}y$
$\\$
$\displaystyle\lim_{b\to\infty}\int_{\pi}^{b} y^g\sin(y)\,\text{d}y$ exists if $g<0$.
Reference: Prove that $\int_0^{\infty} \frac{\sin x}{x^p}\, dx$ converges for $0<p<2$
However, $\displaystyle\lim_{b\to\infty}\int_{\pi}^{b} y^g\sin(y)\,\text{d}y$ does not exist when $g\geq0$.
Hint: how large is $\displaystyle\int_{n\pi}^{(n+1)\pi}y^g\sin(y)\,\text{d}y$?

A: I assume that $a$ is real.
$$\int_0^{\frac 1 \pi} {x^{a}} \sin \left(\frac{1}{x}\right)\,dx=\int_\pi^{\infty} t^{a-2} \sin(t)\,dt$$ makes clear that something happens around $a=2$ where the integral does not converge. The same for $a>2$.
Now, for $a<2$, in terms of hypergeometric function
$$\int_\pi^{\infty} t^{a-2} \sin(t)\,dt=-\cos \left(\frac{\pi  a}{2}\right)\ \Gamma (a-1)-\frac{\pi ^a}{a}\,\, _1F_2\left(\frac{a}{2};\frac{3}{2},\frac{a+2}{2};-\frac{\pi ^2}{4}\right)$$
What is interesting is that, asking Wolfram Alpha to compute the integral for $a=\frac{19}{10}$, the integral is said to not converge why, using the above formula, its value is $-0.884766$ which is confirmed by numerical integration.


text:
Q: Why are angle brackets '<>' highlighted in red in my code in VSCode? I am working on a project in React using VSCode. Today, when I opened the editor, I noticed that some angle brackets '<>' in my code are highlighted in red. The code is working properly though. I am not sure if this is a syntax error or a bug in VSCode. Can anyone provide any suggestions on how to fix this issue? Thank you in advance.

I have checked my code for any syntax errors and have tried changing the syntax highlighting theme, but the issue persists.


text:
Q: Why do parameters passed by reference in C++ not require a dereference operator? I'm new to the C++ community, and just have a quick question about how C++ passes variables by reference to functions.
When you want to pass a variable by reference in C++, you add an & to whatever argument you want to pass by reference.  How come when you assign a value to a variable that is being passed by reference why do you say variable = value; instead of saying *variable = value?
void add_five_to_variable(int &value) {
    // If passing by reference uses pointers,
    // then why wouldn't you say *value += 5?
    // Or does C++ do some behind the scene stuff here?
    value += 5;
}

int main() {

  int i = 1;
  add_five_to_variable(i);
  cout << i << endl; // i = 6

  return 0;
}

If C++ is using pointers to do this with behind the scenes magic, why aren't dereferences needed like with pointers?  Any insight would be much appreciated.

A: When you write,
int *p = ...;
*p = 3;

That is syntax for assigning 3 to the object referred to by the pointer p.  When you write,
int &r = ...;
r = 3;

That is syntax for assigning 3 to the object referred to by the reference r.  The syntax and the implementation are different.  References are implemented using pointers (except when they're optimized out), but the syntax is different.
So you could say that the dereferencing happens automatically, when needed.

A: C++ uses pointers behind the scenes but hides all that complication from you. Passing by reference also enables you to avoid all the problems asssoicated with invalid pointers.

A: When you pass an object to a function by reference, you manipulate the object directly in the function, without referring to its address like with pointers. Thus, when manipulating this variable, you don't want to dereference it with the *variable syntax. This is good practice to pass objects by reference because:

*

*A reference can't be redefined to point to another object

*It can't be null. you have to pass a valid object of that type to the function

How the compiler achieves the "pass by reference" is not really relevant in your case.
The article in Wikipedia is a good ressource.

A: There are two questions in one, it seems:

*

*one question is about syntax: the difference between pointer and reference

*the other is about mechanics and implementation: the in-memory representation of a reference

Let's address the two separately.
Syntax of references and pointers
A pointer is, conceptually, a "sign" (as road sign) toward an object. It allows 2 kind of actions:

*

*actions on the pointee (or object pointed to)

*actions on the pointer itself

The operator* and operator-> allow you to access the pointee, to differenciate it from your accesses to the pointer itself.
A reference is not a "sign", it's an alias. For the duration of its life, come hell or high water, it will point to the same object, nothing you can do about it. Therefore, since you cannot access the reference itself, there is no point it bothering you with weird syntax * or ->. Ironically, not using weird syntax is called syntactic sugar.
Mechanics of a reference
The C++ Standard is silent on the implementation of references, it merely hints that if the compiler can it is allowed to remove them. For example, in the following case:
int main() {
  int a = 0;
  int& b = a;
  b = 1;
  return b;
}

A good compiler will realize that b is just a proxy for a, no room for doubts, and thus simply directly access a and optimize b out.
As you guessed, a likely representation of a reference is (under the hood) a pointer, but do not let it bother you, it does not affect the syntax or semantics. It does mean however that a number of woes of pointers (like access to objects that have been deleted for example) also affect references.

A: The explicit dereference is not required by design - that's for convenience. When you use . on a reference the compiler emits code necessary to access the real object - this will often include dereferencing a pointer, but that's done without requiring an explicit dereference in your code.


text:
Q: Django Template - Stop processing template I am looking for way to clean up a template in django.  A simple solution would be to break this up into multiple templates, but we do not want to do that.
We basically have the following
{%if data.some_state %}
    Display some markup
{% else %}
   {%if data.some_state_2 %}
       State 2 different html view
   {% else %}
        {%if data.process_data %}
           Display some list of data
        {% else %}
           No Data to display!
       {% endif %}
   {% endif %}
{% endif %}

So that is extremely confusing and hard to read.  If I could do this in a "function" i would use if/else if or returns.
Is there a way in template language to do something like (stop_processing_template would tell the template we are done... ):
{%if data.some_state %}
    Display some markup
{% endif %}
{% django_stop_processing_template %}

{%if data.some_state_2 %}
       State 2 different view
{% endif %}
{% django_stop_processing_template %}

{%if data.process_data %}
           Display some list of data
{% endif %}
{% django_stop_processing_template %}

 No data provided !

A: I am not sure what your stop processing template logic would do; but a cleaner way to do your logic would be to write a custom tag that takes your arguments and then returns only the HTML relevant to your variables.  This way you remove the if/else loops and instead replace all that with a simple {% do_stuff %} tag.
Edit
This is a very simple implementation to give you some idea on how the logic would go.
First, you create templates for each variation and store them somewhere django can find them.
Then, a simple tag that renders the exact template you want (this is non tested, psuedo):
from django import template
from django.db.models import get_model
register = template.Library()

class ProcessData(template.Node):
    def __init__(self, var_name):
        self.obj = get_model(*var_name.split('.'))
    def render(self, context):
        if self.obj.some_state:
           t = template.loader.get_template('some_markup_template.html')
           result = 'something'
        else:
           if self.obj.some_state_2:
              t = template.loader.get_template('some_different_html_view.html')
              result = 'something'
       else:
          if self.obj.process_data:
             t = template.loader.get_template('some_list_data.html')
             result = 'something'
          else:
             t = template.loader.get_template('no_data.html')
             result = 'something'
        return t.render(Context({'result': result}, autoescape=context.autoescape))

@register.tag
def process_data(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires arguments" % token.contents.split()[0])
    return ProcessData(arg)

Finally, in your template:
{% load my_tags %}
{% process_data data.mymodel %}

A: You could use jinaj2 for templating that view (or the whole project), it supports if/elif/else branching:
{% if data.some_state %}
    Display some markup
{% elif data.some_state_2 %}
    State 2 different view
{% elif data.process_data %}
    Display some list of data
{% endif %}

There are a couple different packages which it easy use jinja2 in a django project, I've used both coffin and djinja for this.

A: Though I think @burhan's approach is better, you could also do what you want to do by using a custom tag that sets a context variable to a boolean and than outermost else part could also be converted into a if tag
#Set a context variable nodata to True
{% setnodata True %}
{%if data.some_state %}
    Display some markup
    #Set context variable nodata to False
    {% setnodata False %}
{% endif %}

{%if data.some_state_2 %}
    State 2 different view
    #Set context variable nodata to False
    {% setnodata False %}
{% endif %}

{%if data.process_data %}
    Display some list of data
    #Set context variable nodata to False
    {% setnodata False %}
{% endif %}

{% if nodata %}
    No data provided !
{ % endif %}

The setnodata custom tag simply sets the context variable nodata to True or False depending upon the argument.

A: today I meet the same question.
And I find this tag {% verbatim %} {% endverbatim %} .This works in Django1.5+
An example:
  {% verbatim %}

{{ title }}

      {{ body }}

  {% endverbatim %}

You can also look below for more details:

*

*https://groups.google.com/forum/#!topic/django-users/-_wBLDuzaNs

*Handlebars.js in Django templates


text:
Q: What mean `(value, value)` in JS obfluscated code I try to understand how JS code works, but to the end I'm not sure what to look for. I have:
m = ((146.8E1, 67.60E1) > (71., 4.80E1) ? (0x5C, 'n') : (40., 83.))

The full expression is if(), but I don't know how to understand (arg1, arg2).
My browsers (ff, chrome, edge) always returns 2 "arguments".
It's just a method of onfluscate or syntax I don't know?

A: The comma operator separates expressions. (a, b) simply evaluates to b.
(a, b) > (c, d) ? (e, f) : (g, h)

is equivalent to
b > d ? f : g


text:
Q: todonotes and tikzexternalize In my document I use todonotes and TikZ/pgfplots. After activating the externalization in TikZ I realized that todonotes are all exported as well (because they are based on TikZ).
This behaviour is inconvenient, it would be much better for me to tell tikz-external to ignore all \todo.
I know I can generally disable the externalization with \tikzset{external/export=false} and turn it on only for selected plots, but the inverse would be more convenient.

A: I had this very problem a while ago, just for the \todo command (I never use \missingfigure). Here's how I fixed it (place this in your preamble, somewhere after todonotes and tikz/pgfplots is called):
\makeatletter
\renewcommand{\todo}[2][]{\tikzexternaldisable\@todo[#1]{#2}\tikzexternalenable}
\makeatother

Now, \todo will be ignored by the externalization process.
Hence, for the \missingfigure command you need
\makeatletter
\renewcommand{\missingfigure}[2][]{\tikzexternaldisable\@missingfigure[#1]{#2}\tikzexternalenable}
\makeatother

A: For me neither of the proposed solutions worked. Maybe it is platform-dependent, taking into consideration the significant number of up-votes in favor of the accepted answer.
However, mSSM's approach with \let was close. The reason for it not to work properly with \missingfigure is that the latter consumes an optional argument. The simple \let fails to copy all required information to a new macro. According to this piece, one should use the letltxmacro package. Eventually, my working version is:
\usepackage{letltxmacro}

\LetLtxMacro{\oldmissingfigure}{\missingfigure}
\renewcommand{\missingfigure}[2][]{\tikzexternaldisable\oldmissingfigure[{#1}]{#2}\tikzexternalenable}

\LetLtxMacro{\oldtodo}{\todo}
\renewcommand{\todo}[2][]{\tikzexternaldisable\oldtodo[#1]{#2}\tikzexternalenable}

A: I have played around with \missingfigure, but a simple \renewcommand{\missingfigure}... will not work, as given in the answer by @Frits.
The only solution I found was defining a new command:
\newcommand{\extmissingfigure}[2][]{\tikzexternaldisable\missingfigure[#1]{#2}\tikzexternalenable}

Working with \let, i.e.:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\usepackage{todonotes}

\tikzexternalize

\let\oldmissingfigure\missingfigure
\renewcommand{\missingfigure}[2][]{\tikzexternaldisable\oldmissingfigure[#1]{#2}\tikzexternalenable}

\begin{document}

\missingfigure{Ah!}

\end{document}

unfortunately raises an error:
! TeX capacity exceeded, sorry [input stack size=5000].
<to be read again>
\tikzexternal@orig@tikzfadingfrompicture
l.18 \missingfigure{Ah!}

A: I found another workaround which just modifies the original implementation of the todo command. Just modify
\newcommand{\todo}[1]{%
  % Add to todo list
  \addcontentsline{tdo}{todo}{\protect{#1}}%
  %
  \begin{tikzpicture}[remember picture, baseline=-0.75ex]%
    \node [coordinate] (inText) {};
  \end{tikzpicture}%
  %
  % Make the margin par
  \marginnote{%
    \begin{tikzpicture}[remember picture]%
      \definecolor{orange}{rgb}{1,0.5,0}
      \draw node[draw=black, fill=orange, text width = 3cm] (inNote)
      {#1};%
    \end{tikzpicture}%
  }%
  %
  \begin{tikzpicture}[remember picture, overlay]%
    \draw[draw = orange, thick]
      ([yshift=-0.2cm] inText)
      -| ([xshift=-0.2cm] inNote.west)
      -| (inNote.west);
  \end{tikzpicture}%
  %
}%

by inserting \tikzexternaldisable before and \tikzexternalenable after the tikzpicture envoronment:
\newcommand{\todo}[1]{%
  \tikzexternaldisable
  % Add to todo list
  \addcontentsline{tdo}{todo}{\protect{#1}}%
  %
  \begin{tikzpicture}[remember picture, baseline=-0.75ex]%
    \node [coordinate] (inText) {};
  \end{tikzpicture}%
  %
  % Make the margin par
  \marginnote{%
    \begin{tikzpicture}[remember picture]%
      \definecolor{orange}{rgb}{1,0.5,0}
      \draw node[draw=black, fill=orange, text width = 3cm] (inNote)
      {#1};%
    \end{tikzpicture}%
  }%
  %
  \begin{tikzpicture}[remember picture, overlay]%
    \draw[draw = orange, thick]
      ([yshift=-0.2cm] inText)
      -| ([xshift=-0.2cm] inNote.west)
      -| (inNote.west);
  \end{tikzpicture}%
  \tikzexternalenable
  %
}%


text:
Q: Статусы СМС (правила наименование, не программирование) Извините, если не в тему.
Вопрос не по программированию, а по правилам наименования статусов смс - известно, что статусы СМС должны называться (одним) английским словом, например "SENT", "ERROR", "CREATED".
Вопрос:
Как таким же самым образом назвать следующие статусы:

*

*ожидает доставки

*передано оператору

Спасибо.

A: Предлагаю следующее:

*

*Использовать статус Sent для обозначения состояния "передано оператору".

*Использовать статус Delivered для обозначения состояния "доставлено абоненту"

*Не добавлять статус "ожидает доставку", т.к. он по сути уже есть(sent - передано оператору. В этот момент абонент как раз ожидает доставку).


text:
Q: Check screen coordinate (x,y) touched Matrix4x4 (3d object) I have a 3d object from android KudanAR library that seems to be implemented using OpenGL. Currently, I want to check which 3Dobject is clicked. Therefore, I need to know whether the screen coordinate (x,y) has touched the 3d objects. how do you implement it?

A: Since OpenGL is rendering API there is nothing usefull in there for you. But there is common approach called raycasting. Idea is simple: cast a ray from camera and check which object it intersects. Here is a good tutorial for this approach.
I am nor familiar with kudan, maybe something usefull could be found there, at least bounding boxes and transformation matrix.
Another approach based on rendering objects with unique colors, picking value from frame buffer allow you to find which object is under cursor.


text:
Q: how to cross-compile windows linux macos ubejar for javafx with deps.edn aliases?
*

*Nightcode has this implemented

*https://github.com/oakes/Nightcode/blob/2e112c59cddc5fdec96059a08912c73b880f9ae8/deps.edn#L20

*but for some reason it does not work just by copying code

; does not work
{:paths ["./src" "out/ui" "out/identicon"]
 :mvn/repos {"jitpack.io" {:url "https://jitpack.io"}}
 :deps {org.clojure/clojure {:mvn/version "1.10.3"}
        org.clojure/clojurescript {:mvn/version "1.11.4"}
        org.clojure/core.async {:mvn/version "1.3.618"}

        test.check/test.check {:git/url "https://github.com/clojure/test.check"
                               :sha "b6a318af92e836f1f20960f38a5944168b88d60d"}
        cheshire/cheshire {:mvn/version "5.10.2"}

        cljfx/cljfx {:git/url "https://github.com/cljfx/cljfx"
                     :sha "29aaef956b22cee774524912a3083ed651033f1b"
                     :exclusions [org.openjfx/javafx-controls
                                  org.openjfx/javafx-base
                                  org.openjfx/javafx-fxml
                                  org.openjfx/javafx-graphics
                                  org.openjfx/javafx-media
                                  org.openjfx/javafx-web]}

        org.openjfx/javafx-base {:mvn/version "17.0.2"}
        org.openjfx/javafx-fxml {:mvn/version "17.0.2"}
        #_org.openjfx/javafx-graphics #_{:mvn/version "17.0.2"}
        #_org.openjfx/javafx-web #_{:mvn/version "17.0.2"}}

 :aliases
 {:Ripley {:extra-deps {Ripley/Ripley {:git/url "https://github.com/Empire-Strikes-Back/Ripley"
                                       :sha "becd2573ab55d42933134d346bc46cdd8fa08c04"}}}

  :Genie {:extra-deps {Genie/Genie {:git/url "https://github.com/Empire-Strikes-Back/Genie"
                                    :sha "fe9200d223e3a5c79e88dfa17bc2697c09dae70e"}}}

  :Zazu {:extra-deps {Zazu/Zazu {:git/url "https://github.com/Empire-Strikes-Back/Zazu"
                                 :sha "063ef7649c01284be8f5a1e9814d5bf83025ad76"}}}

  :shadow {:extra-deps {thheller/shadow-cljs {:mvn/version "2.18.0"}
                        nrepl/nrepl {:mvn/version "0.8.3"}
                        cider/cider-nrepl {:mvn/version "0.25.5"}
                        cider/piggieback {:mvn/version "0.5.2"}}}

  :ui {:extra-deps {reagent/reagent {:mvn/version "1.1.1"}
                    sci/sci {:git/url "https://github.com/borkdude/sci"
                             :sha "6c10e494371a37a56bef45c8148435888bae3a45"}}}

  :linux {:extra-deps {org.openjfx/javafx-base$linux {:mvn/version "17.0.2"}
                       org.openjfx/javafx-fxml {:mvn/version "17.0.2"}
                       org.openjfx/javafx-graphics$linux {:mvn/version "17.0.2"}
                       org.openjfx/javafx-web$linux {:mvn/version "17.0.2"}}}
  :windows {:extra-deps {org.openjfx/javafx-graphics$win {:mvn/version "17.0.2"}
                         org.openjfx/javafx-web$win {:mvn/version "17.0.2"}}}
  :macos {:extra-deps {org.openjfx/javafx-graphics$mac {:mvn/version "17.0.2"}
                       org.openjfx/javafx-web$mac {:mvn/version "17.0.2"}}}}}

*

*also there is this anwser https://github.com/openjfx/openjfx-docs/issues/133
how to compile uberjars for each OS with its own classifier?

A: *

*answer found

*

*program - Cara-Dune  - who assembles the uberjar - uses Genie library for it

*he is essentially clojure/tools.build but can be run with clojure -X

*now we can see that tools.build added such api and describes in doc it can also run with clojure -X = but Genie appeared before

*say program runs clojure -X:windows:Genie Genie.core/process - this invokes essentially clojure/build.tool compilation

*https://github.com/clojure/tools.build/blob/a9d0804ce8014088a7388e762034e9013922cacb/src/main/clojure/clojure/tools/build/tasks/create_basis.clj

*which in tern invokes deps create-basis

*but - the :alias we never passed to that function, we incorrectly put it to clojure -X invocation

*should be instead

  OPERATING_SYSTEM=$1
  COMMIT_HASH=$(git rev-parse --short HEAD)
  COMMIT_COUNT=$(git rev-list --count HEAD)
  clojure \
    -J-Dcljfx.skip-javafx-initialization=true \
    -X:Genie Genie.core/process \
    :main-ns Cara-Dune.main \
    :filename "\"out/Cara-Dune-$COMMIT_COUNT-$COMMIT_HASH-$OPERATING_SYSTEM.jar\"" \
    :paths '["src" "out/ui" "out/identicon"]' \
    :create-basis-opts "{:aliases [:$OPERATING_SYSTEM]}"

*

*and still - linux .jar is 80.7mb

*windows 108 mac 112 - because they include javafx jar for linux - they run on linux when they shouldn't


text:
Q: IE7-8 resize filter Why is this not resizing my image in IE7-8????
#carousel ul li #myImage {
  background: url("../img/myImage.png") no-repeat;
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/myImage.png',sizingMethod='scale');
  -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/myImage.png',sizingMethod='scale')";
}


text:
Q: How to start setInterval after object initialization? function Game() {
  this.number = 0;
  const t = setInterval(() => {
      this.number = Math.floor((Math.random() * 10) + 1);
      }, 1000);

  this.checkNumber = () => {
    if (this.number > 5) {
      clearInterval(this.t);
    }
    return this.number > 5;
  }
}

const game = new Game();
console.log(game.number);

I do have something like this and I would like to have my number changed, however setInterval doesnt seem to be initialized after my object initialization. How could I do it without doing additional method?

A: try something like this ..
class Game () {
  constructor(){
   //call set interval function here
 }

  //put methods here

}

Or self calling function
(function () {
  // body
})();

See more @ https://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript-or-immediately-invoked-function-expression/
Arrow Syntax
(() => {
  //body
})()

Arrow Syntax + parameter
((n) => {
  //body
})()

A: function Game() {
  (() => {
    this.t = setInterval (() => {
      this.number = Math.floor ((Math.random () * 10) + 1);
      console.log(this.number);
      this.checkNumber();
    }, 1000);
  })();

  this.checkNumber = () => {
    if (this.number > 5) {
      clearInterval(this.t);
    }
    return this.number > 5;
  };
}

const game = new Game();

Did something like this and it works, thanks above


text:
Q: How to make the message automatically get other that reload page using socket.io, nodejs, and mongodb I'm having a go with the socket.io https://socket.io/get-started/chat, but my problem is that when i send message then the message cant automatically into chat box. i need to reload the page to view the chat that i sent. So how to make the chat automatically insert to chat box?. i already implement into my project. i already used socket.emit as you can see at then html file. is there the right way to put it?
server.js
var express = require('express');
var env = require('dotenv').config()
var ejs = require('ejs');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session)
const cookieParser = require('cookie-parser')

var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')

app.use(cors())
app.use(cookieParser());

// mongodb://localhost:27017 127.0.0.1:27017
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/findaprofessional', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err) => {
  if (!err) {
    console.log('MongoDB Connection Succeeded.');
  } else {
    console.log('Error in DB connection : ' + err);
  }
});

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});

const oneDay = 1000 * 60 * 60 * 24;
app.use(session({
  secret: 'work hard',
  saveUninitialized:true,
    cookie: { maxAge: oneDay },
    resave: true
}));

// ni lain
app.set("view engine", "ejs")

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/css', express.static(path.resolve(__dirname, "asset/css")))
app.use('/img', express.static(path.resolve(__dirname, "asset/img")))
app.use('/js', express.static(path.resolve(__dirname, "asset/js")))
app.use('/vendor', express.static(path.resolve(__dirname, "asset/vendor")))
app.use('/lib', express.static(path.resolve(__dirname, "asset/lib")))
app.use('/scss', express.static(path.resolve(__dirname, "asset/scss")))
app.use('/pic', express.static(path.resolve(__dirname, "asset/img/pic")))

var index = require('./routes/index');
const { Socket } = require('socket.io');
app.use('/', index);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('File Not Found');
  err.status = 404;
  next(err);
});

// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  res.send(err.message);
});

io.on('connection', () =>{
  console.log('a user is connected')
  io.on("disconnect", function () {
    console.log("user disconnected");
  });
})

var server = http.listen(3000, () => {
  console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});

routing
// user chat
var http = require('http').Server(router);
var io = require('socket.io')(http);

// Render Message
router.get('/messages/:id', async function (req, res, next) {
    user = await User.findOne({_id: req.session.userId},  {username: 1})
    return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});

// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
    Message.find({booking: req.params.booking})
    .populate({
        path: "pro",
        model: Pro,
    }).populate({
        path: "user",
        model: User,
    }).exec().then((data) => {
        res.json(data)
    })

})

router.get('/messages', (req, res) => {
    Message.find({}, (err, messages) => {
        res.send(messages);
    })
})

router.post('/messages', async (req, res) => {
    const {booking, user, message} = req.body

    try {
        var msg = new Message({
            booking: booking,
            message: message,
            user: user
        });

        var savedMessage = await msg.save()
        console.log('saved');

        var censored = await Message.findOne({
            message: 'badword'
        });
        if (censored)
            await Message.remove({
                _id: censored.id
            })
        else
            io.emit('message', req.body);
        res.sendStatus(200);
    } catch (error) {
        res.sendStatus(500);
        return console.log('error', error);
    } finally {
        console.log('Message Posted')
    }

})

HTML
<!DOCTYPE html>

<%- include("../header.ejs") %>

  <link href="/css/sb-admin-2.min.css" rel="stylesheet">

  <link href="/css/chat.css" rel="stylesheet">

  </script>

               Chat

          <form class="msger-inputarea">
            <input type="hidden" name="booking" value="<%= booking %>">
            <input type="hidden" id="name" class="form-control" readonly placeholder="Name"
              value="<%= user.username %>">
            <input type="text" name="user" value="<%= user._id %>">
            <input id="message" type="text" class="msger-input" placeholder="Enter your message...">
            <button id="send" type="submit" class="msger-send-btn">Send</button>
          </form>

i tried to automatically get the message without reload the page but it doenst work. Can anyone see where the problem is?

A: From what I know, the default behavior when you click a button with type submit inside a form, it tries to reload the page even though you haven't defined any function or other page for it to go.
You would have to get the submit event from the form and use the preventDefault() funciton for this event, check out this thread for more info:
JavaScript code to stop form submission
So you would stop the form submission and then get new messages for the page, executing the javascript to add the new messages to the page by manipulating the DOM.

A: You can write socker.write() method for accessing real time messages in nodejs.


text:
Q: Dynamic allocation of an array into a function with pointer parameters I am having issues finishing passing an array via pointers through a series of functions.  I create a function using dynamic allocation to create it.  Even though that is successful I cannot get it to pass through functions that take pointers as arguments.  The functions return the mean median and mode and have been completed.  However I cannot pass them when converting them into pointer syntax.  Thanks for the help in advance.
#include <iostream>
#include <cstdlib>

using namespace std;
int students;
int * studentarray;
int  stumode;
double  stuavg;
int  stumed;
int arr;

int mode(int *[], int );
double average(int *[], int);
double median(int *[], int);
void selectSort(int [], int);
void swap(int *, int *);
int makeArray(int*, int);

int main()
{
    studentarray = &arr;
    cout << "How many students are there?" << endl;
    cin >> students;

    makeArray(studentarray, students);

    for (int i = 0; i < students; i++) {
        cout << "How many movies did student " << i + 1 << " view?" << endl;
        cin >> studentarray[i];
    }

    selectSort(studentarray, students);
    stumode = mode(&studentarray, students);
    stuavg = average(&studentarray, students);
    stumed = median(&studentarray, students);

    cout << "The array has been sorted in ascending order." << endl;
    cout << "The mode is " << stumode << "." << endl;
    cout << "The mean is " << stuavg << "." << endl;
    cout << "The median is " << stumed << "." << endl;

    delete[] studentarray;

    return 0;
}

int mode(int *arr, int size)
{
    if (size <= 0) return 0;

    int most = 0, position = 0, most_count = 0;
    int counter = 1;
    for (int i = 1; i < size; i++)
    {
        if (* (arr +  i) != * (arr + position) )
        {
            if (counter > most)
            {
                most = counter;
                most_count = 0;
            }
            else if (counter == most) most_count++;
            position = i;
            counter = 0;
        }
        else counter++;
    }
    if (most_count) return 0;
    else return * ( arr + position );
}

double average(int *arr, int size)
{
    if (size <= 0) return 0;
    int total = 0;
    for (int i = 0; i < size; i++) {
        total += *(arr + i);
    }
    return (double)total / size;
}

double median(int *arr, int size)
{
    if (size <= 0) return 0;
    if (size % 2 == 0)
        return (double) (* (arr + (size + 1) / 2));
    else {
        int mid = size / 2;
        return (double)(* (arr + mid) + * (arr + mid + 1) / 2);
    }
    return 0;
}

void selectSort(int arr[], int size)
{
    int min;
    for (int i = 0; i < size - 1; i++)
    {
        min = i;
        for (int j = i + 1; j < size; j++)
        {
            if ( arr[j] < arr[min])
            {
                min = j;
            }
        }
        swap(&arr[min], &arr[i]);
    }

 }

void swap(int *one, int *two) {
    int temp = *one;
    *one = *two;
    *two = temp;
}

int makeArray(int *arr, int size)
{
    arr = new int[size];
    return *arr;
}

A: Your implementation of makeArray is not right.
int makeArray(int *arr, int size)
{
    // Allocates memory and assigns it to arr.
    // This is a local change to arr. The value of the variable in
    // main remains unchanged.
    arr = new int[size];

    // Returns an uninitialized value.
    return *arr;

    // The memory allocated in the previous line is now a memory leak.
}

You can make it simpler by using:
int* makeArray(int size)
{
   return new int[size];
}

and use it in main as:
arr = makeArray(students);

However, I don't see how that is better than using:
arr = new int[students];

If you do that, makeArray becomes unnecessary. If makeArray needs to have additional code to fill up the array with some values, it will be useful. Otherwise, it does not add any useful functionality to your program.

Having said all of that, it is better to use std::vector instead of managing dynamically allocated memory in your own code. You would use:
std::vector<int> arr(students);

PS
I did not go through rest of your code. There might be other errors.


text:
Q: VSTS ARM Service Endpoint for national cloud environments I am trying to create a Release Definition from my VSTS instance in west Europe to deploy an App in the Azure German Cloud. I tried creating an ARM Service Endpoint but it seems it tried to use by default the service management management.core.windows.net and the endpoint in Germany.
I've also tried using an Azure classic but I keep getting an authentication error: There was an error with the Azure credentials used for the deployment....the user I am using for that has owner role in my subscription. Besides Azure Classic Service Endpoint are deprecated.

*

*Is there any way to change the environment endpoints for the Service Endpoint.

*Any restrictions trying to deploy to the German cloud from a VSTS instance in west Europe?


text:
Q: How to check if file download is complete What I am trying to do is download a file from a web page. Once the file is done downloading, I'll have it print something to the screen.
using HtmlAgilityPack;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication25
{
class Program
{
    static void Main(string[] args)
    {

        Uri remoteUri = new Uri("http://soundcloud.com/dubstep/spag-heddy-the-master-vip/download");
        string fileName1 = "t", myStringWebResource = null;

        // Create a new WebClient instance.
        using (WebClient myWebClient = new WebClient())
        {
            myStringWebResource = remoteUri + fileName1;
            // Download the Web resource and save it into the current filesystem folder.
            myWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Url1_DownloadStringCompleted);
            myWebClient.DownloadFileAsync(remoteUri, fileName1);

        }
}
public static void Url1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error != null)
            return;
        yes();
    }
    public static void yes()
    {
        Console.WriteLine("RRRR");
        Console.Read();
    }
}
}

Where I run in to a problem is with myWebClient.DownloadFileAsync(remoteUri, fileName1); I'm not sure what I should have there instead of what is there. I have also verified that myWebClient.DownloadFile works.

A: Worked when I made these changes to the code: Changed input string to URI, fixed local path, used the correct eventhandler and did Console.Read in the end. I have shortened the code a bit, but you get the idea:
static void Main(string[] args)
{
    using (WebClient myWebClient = new WebClient())
    {
        myWebClient.DownloadFileCompleted += DownloadCompleted;
        myWebClient.DownloadFileAsync(new Uri("http://someUrl"), @"e:\file.mp3");
    }

    Console.ReadLine();
}

public static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
    Console.WriteLine("Success");
}


text:
Q: VBA code is adding unwanted ' in my formula and returning wrong values Ok so it's the first time i'm tinkering with VBA, and I'm trying to create a macro that when activated takes the last entry in another sheet and adds it at the end of the table on my current sheet.
However, when I run the code, what is entered in the A cell is :
=@'Table Informative'!$AI:$AI
And what is entered the B cells is :
=@'Table Informative'!'G35' or =@'Table Informative'!'H35'
So for the B column it does add the right cell info but adds these ' ' symbols around the cell number which fudges everything.
For the A column, I'm super confused by the $AI:$AI, my code, as seen below, is very basic, and I wonder what I missed that is causing these two issues.
Sub Update()
'
' Update Macro
'

'
    Dim wsSheet1 As Worksheet: Set wsSheet1 = Worksheets("Table Informative")

    Dim LastA As Long
    Dim LastB As Long
    Dim LastRow As Long

    LastA = Cells(Rows.Count, "A").End(xlUp).Row
    LastB = Cells(Rows.Count, "B").End(xlUp).Row
    LastRow = wsSheet1.Cells(Rows.Count, "C").End(xlUp).Row

    Range("A" & LastA + 1).Select
    ActiveCell.FormulaR1C1 = "='Table Informative'!" & "C" & LastRow
    Range("B" & LastB + 1).Select
    ActiveCell.FormulaR1C1 = "='Table Informative'!" & "G" & LastRow

    Range("A" & LastA + 2).Select
    ActiveCell.FormulaR1C1 = "='Table Informative'!C" & LastRow
    Range("B" & LastB + 2).Select
    ActiveCell.FormulaR1C1 = "='Table Informative'!H" & LastRow
End Sub

Thanks in advance !


text:
Q: How to get tomorrows datetime with Ecto? I can get the current datetime with Ecto like this:
Ecto.DateTime.utc

But how do I get tomorrows date like
Ecto.DateTime.utc + timedelta 1 day

?

A: Timex.shift(Timex.now, days: 1)

https://github.com/bitwalker/timex

A: How's about an answer for this?
Ecto.DateTime.utc
|> Ecto.DateTime.to_erl
|> :calendar.datetime_to_gregorian_seconds
|> Kernel.+(86400)
|> :calendar.gregorian_seconds_to_datetime
|> Ecto.DateTime.from_erl

A: iex(3)> t = DateTime.utc_now()
#DateTime<2018-07-17 08:22:11.472192Z>
iex(4)> n = %{t | day: t.day + 1}
#DateTime<2018-07-18 08:22:11.472192Z>
iex(5)> n
#DateTime<2018-07-18 08:22:11.472192Z>
iex(6)> m = %{t | day: t.day - 1}
#DateTime<2018-07-16 08:22:11.472192Z>
iex(7)> m
#DateTime<2018-07-16 08:22:11.472192Z>


text:
Q: 'fast-forward' vs 'forced-update' for 'git fetch' command I have a python application which maintains a mirror of a git repo by periodically (every 10 seconds) doing git fetch -v followed by git reset --hard (using GitPython library) on that repo. More specifically it uses the following python code to do this
Popen(['git', 'fetch', '-v', 'origin'], cwd=absolute_path_to_repo, universal_newlines=True, shell=None)
Popen(['git', 'reset', '--hard', 'origin/branch'], cwd=absolute_path_to_repo, universal_newlines=False, shell=None)

I was just exploring git logs (inside .git/logs/refs/remotes/origin/<branch_name> of that repo), and saw 2 different kind of log lines.
remotes/origin/{branch-name}:a6aac37 ca8ab94 Application Server Pseudo-User <app@{hostname}> 1547575486 +0000   fetch -v origin: fast-forward
remotes/origin/{branch-name}:6b92d4f a6aac37 Application Server Pseudo-User <app@{hostname}> 1548703807 +0000   fetch -v origin: forced-update

The first log line says fetch -v origin: fast-forward and the second log line says  fetch -v origin: forced-update. I am trying to understand why does git log them differently when they are output of the same command - specially given the fact that the python application is not making any changes in the git repo (its read-only).
The reason why I trying to answer this question is because in forced-update case I see that the HEAD of my repo moves to an older commit (a6aac37 corresponds to a month old commit). In all other cases the HEAD points to the latest commit.
Another observation was that although forced-update rarely happens but happens only at the time there was a push made to the remote. I have verified that those commits were pretty normal (like any other commits).


text:
Q: "TypeError: Cannot read properties of undefined (reading 'name')" on my node_modules file I'm working on a solid-js project. For some time now, none of the buttons in my application react when clicked. Although I did not make any code changes before the bug appeared. To fix this issue related to my buttons, I deleted then reinstalled my node_modules folder, shut down then restarted my computer, updated my library dependencies. But none of these attempts solved my problem. So I performed tests on one of my buttons. None returned a positive result and I get the same error on both my tests. There she is:
TypeError: Cannot read properties of undefined (reading 'name')
 ❯ devComponent node_modules/.pnpm/solid-js@1.4.8/node_modules/solid-js/dist/dev.js:543:26
    541|   c.observerSlots = null;
    542|   c.state = 0;
    543|   c.componentName = Comp.name;
       |                          ^
    544|   updateComputation(c);
    545|   return c.tValue !== undefined ? c.tValue : c.value;

This error comes from a file contained in my folder
node_modules as specified on the error message. I don't know why I am getting this error yet I have updated all my library dependencies to the latest version. Here is a snippet of my dev.js file where the error is coming from, it is contained in my node_modules folder:
function devComponent(Comp, props) {
  const c = createComputation(() => untrack(() => {
    Object.assign(Comp, {
      [$DEVCOMP]: true
    });
    return Comp(props);
  }), undefined, true);
  c.pending = NOTPENDING;
  c.observers = null;
  c.observerSlots = null;
  c.state = 0;
  c.componentName = Comp.name;
  updateComputation(c);
  return c.tValue !== undefined ? c.tValue : c.value;
}

Here is the content of my test file:
import { screen, render, fireEvent } from 'solid-testing-library';
import { describe, expect,it ,  test } from 'vitest';
import { Messenger } from '../components/header/Messenger';

describe('<Messenger />', () => {
  it('create an instance', async () => {
  const { component } = render(() => <Messenger />);
  expect(await screen.findByRole('button', { name: 'Click me!' }));
  expect(component).toBeInTheDocument();
  });

  it('This changes text on click',async () => {
    const { component } = render(() => <Messenger />);
    expect(component).toBeInTheDocument();
    fireEvent.click(component);
    expect(await screen.findByRole('button', { name: 'Test this!' })).toBeInTheDocument();
    });

})

I use vitest for my tests and the component file to test is here:
import { Link } from "solid-app-router";
import { SiMessenger } from "solid-icons/si";
import { createResource, createSignal, Match, Show, Switch } from "solid-js";

export default function Messenger() {
  const [clicked, setClicked] = createSignal(false);
  const [resource] = createResource(fetchMessenger);

  function toggle() {
    setOpen((o) => !o);
  }

  return (
    <>
      <button
        onClick={() => setClicked(true)}
        className="block p-2 md:p-3 rounded-full bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600  text-black dark:text-white "
      >
        <SiMessenger className="text-xl" />
      </button>
      {clicked() ? 'Test this!' : 'Click me!'}

I don't know how to solve this problem.

A: Try using screen.debug() and see if the input is there. If not, the lifecycle methods might not be completing: this scenario would cause a failure since you're using find. You can add try this:
await waitFor(() => expect(screen.findByRole('button', { name: 'Test this!' })).toBeInTheDocument()));


text:
Q: Pandas - InvalidIndexError on concat I have a simple concat:
df = pd.concat([df1.reset_index(),df2.reset_index()],ignore_index = True)

That throws the following error:

InvalidIndexError: Reindexing only valid with uniquely valued Index
objects

I can't seem to figure out why though (I added the reset_index and ignore_index to try and fix the issue, but no luck).
For info on the indicies:
df1.index = RangeIndex(start=0, stop=5, step=1)
df2.index = RangeIndex(start=0, stop=42, step=1)

Could this be a column specific issue?  There are a lot of overlapping columns between df1 and df2 (but each one does have some unique columns as well).
Thanks!


text:
Q: Returning multiple outputs from function I am not sure that this is possible, but...
I am trying to write a function that will output lists of numbers so that they can be input into another function. I'm at a dead end though, as neither return or yield (used in this context) can give me what I want.
def ITERATOR():
    for number in range(1,3):
        for item in itertools.permutations(range(15),number):
            yield item

Obviously, the function breaks whenever return is used, and yield returns everything at once. What I ideally want it to output is what is printed on each line by:
def ITERATOR():
    for number in range(2,4):
        for item in itertools.permutations(range(15),number):
            print(item)

i.e:
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(0, 7)
(0, 8)
(0, 9)
(0, 10)
(0, 11)
(0, 12)
(0, 13)
(0, 14)
etc...

Is there any way of achieving this?

A: If you want to return a list, you could just do it:
def fct():
    return [item for item in itertools.permutations(range(15),number) for number in range(2,4)]

And for a generator
def fct():
    return (item for item in itertools.permutations(range(15),number) for number in range(2,4))

A: Solution
new_tuples = []
for i in range(0, 5):
    for j in range(1, 16):
        new_tuples.append((i, j))

for i in new_tuples:
    print(i)

Output

(xenial)vash@localhost:~/python$ python3 text_seg.py
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(0, 7)
(0, 8)
(0, 9)
(0, 10)
(0, 11)
(0, 12)
(0, 13)
(0, 14)
(0, 15)
(1, 1)

Comments
Would this approach satisfy your needs? You could interchange the numbers as desired but this, will allow you to have a list with the tuples store and be able to call them to print.

A: You can return the list through the argument of the function, and use the return of the function to indicate the number of permutations founded:
import itertools

permut = []

def ITERATOR(item):
    n_permuts= 0
    for number in range(2,4):
        for item in itertools.permutations(range(15),number):
            permut.append(item)
            n_permuts+= 1
    return n_permuts

print (ITERATOR(permut))
for item in permut:
    print(item)


text:
Q: How to fix the error "failed to parse date field " in Elasticsearch I tried to do a query in Elasticsearch via python. I want to get all values in the last one hour from now. For this I wrote this script:
import time
from elasticsearch import Elasticsearch
from datetime import datetime, timedelta

es = Elasticsearch()
index = "standalone"

filename = "2017-12-22V2.csv"

Timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
one_hour_from_now = datetime.now() - timedelta(hours=1)
one_hour_from_now = one_hour_from_now.strftime('%Y-%m-%d %H:%M:%S')

query = {"query":{"bool":{"must":{"range":{"Time":{"gt":one_hour_from_now,"lt":Timestamp}}},"must_not":[],"should":[]}},"from":0,"size":10,"sort":[],"aggs":{}}

ret = es.search(index, body=query)
print("ret", ret)

When I execute it I get this error:
 es.search exception:  TransportError(400, 'search_phase_execution_exception', 'failed to parse date field [2018-02-12 15:50:26] with format [strict_date_optional_time||epoch_millis]')

This is the structure of my ES index:

Can someone help me please
Thank you

A: From the documentation it seems that your date format is wrong.
According to your screenshot, your data is in this format:
yyyy-MM-dd'T'HH:mm:ss

According to the documentation this format is
date_hour_minute_second or strict_date_hour_minute_second

With datetime library in python you have shaped your date format in this way:
yyyy-MM-dd HH:mm:ss

Try to convert in the range query the strict_date_optional_time - the default date format in es, used in your date field according to the structure of your es index - with the format clause and cast it with the value yyyy-MM-dd HH:mm:ss:
query = {"query":{"bool":{"must":{"range":{"Time":{"gt":one_hour_from_now,"lt":Timestamp, "format": "yyyy-MM-dd HH:mm:ss"}}},"must_not":[],"should":[]}},"from":0,"size":10,"sort":[],"aggs":{}}

or change you line code:
one_hour_from_now = one_hour_from_now.strftime('%Y-%m-%d %H:%M:%S')

in
one_hour_from_now = one_hour_from_now.strftime("%Y-%m-%d"'T'"%H:%M:%S")

and don't specify a format in the query or specify the correct one


text:
Q: pandas data format to preserve DateTimeIndex I do a lot of work with data that has DateTime indexes and multi-indexes. Saving and reading as a .csv is tedious because every time I have to reset_index and name it "date" then when I read again, I have to convert the date back to a datetime and set the index. What format will help me avoid this? I'd prefer something open source - for instance I think SAS and Stata will do this, but they are proprietary.

A: feather was made for this:
https://github.com/wesm/feather

Feather provides binary columnar serialization for data frames. It is
  designed to make reading and writing data frames efficient, and to
  make sharing data across data analysis languages easy. This initial
  version comes with bindings for python (written by Wes McKinney) and R
  (written by Hadley Wickham).
Feather uses the Apache Arrow columnar memory specification to
  represent binary data on disk. This makes read and write operations
  very fast. This is particularly important for encoding null/NA values
  and variable-length types like UTF8 strings.
Feather is a part of the broader Apache Arrow project. Feather defines
  its own simplified schemas and metadata for on-disk representation.
Feather currently supports the following column types:
A wide range of numeric types (int8, int16, int32, int64, uint8,
  uint16, uint32, uint64, float, double). Logical/boolean values. Dates,
  times, and timestamps. Factors/categorical variables that have fixed
  set of possible values. UTF-8 encoded strings. Arbitrary binary data.


text:
Q: How to select HTML elements that do not have a specific attribute value? Basically title, my html looks like this:
 10
 20

and I tried using
x = [td.getText() for td in rows[i].findAll('td') and not rows[i].findAll(attrs={"data-stat":"DUMMY"})]

but that did not work obviously. My desired output would only get the text from data-stat="foo" and  data-stat="bar", which would look like:
x=["10","20"]

A: Use an css selector with pseudo-class :not() to select your elements:
soup.select('th:not([data-stat="DUMMY"])')

Note: In your question you try to find td while there is only th in your example.
Just in addition concerning your approach with list comprehension - You were close to a solution but could use if-statement:
[th.getText(strip=True) for th in soup.find_all('th') if th.get('data-stat') != 'DUMMY']

Note: In newer code avoid old syntax findAll() instead use find_all() - For more take a minute to check docs
Example
from bs4 import BeautifulSoup
html ='''
 10
 20

'''
soup = BeautifulSoup(html)

[e.get_text(strip=True) for e in soup.select('th:not([data-stat="DUMMY"])')]

Output
['10', '20']

A: You can find easily on the documentation
from bs4 import BeautifulSoup

table = """" 10
 20
  	"""
soup = BeautifulSoup(table, "lxml")
value_list = []

value_list.append(soup.find("th", {"data-stat": "foo"}).text.strip())
value_list.append(soup.find("th", {"data-stat": "bar"}).text.strip())
print(value_list)


text:
Q: In JavaScript, why would my "<" and ">" comparisons be reversed? When I run this code through an html page in chrome, and put in, for example, number1 = 1000 and number2 gets 2000, it alerts 1000 is bigger. Why?
var number1 = prompt("Pick a number");
var number2 = prompt("Pick another number");

if (number1 < number2) {
    alert(number1 + "is bigger!");
} else if (number2 < number1) {
    alert(number2 + "is bigger!");
} else if (number1 == number2) {
    alert(number1 + "is equal to" + number2)
}

A: There are two problems above:

*

*Your messages are backward

*You're comparing strings, not numbers
You want to convert the result of prompt to number, and also correct which messages you're displaying.
You have several options for converting strings to numbers; I list your options and their plusses and minuses in this answer.
If you only fix #1 and not #2, you'll end up saying that "20" is less than "3", because comparing strings with < compares them lexigraphically, and "2" comes before "3" (the "0" in "20" never even gets looked at).


text:
Q: Qual o uso apropriado do 'display: table'? Como o próprio nome diz, o display table faz com que o elemento (divs, sections, etc.) tenha um comportamento bem semelhante a de uma tabela com a tag
, onde podemos usar elementos filhos com a propriedade display: table-cell que terão comportamento semelhante a células de uma
.
Por exemplo, posso usar a propriedade vertical-align: middle; numa div filha para centralizar verticalmente um conteúdo, como numa  de uma tabela
:

.tabela{
   display: table;
   height: 200px;
   background: Yellow;
}

.celula{
   display: table-cell;
   vertical-align: middle;
}

      Texto

Minhas dúvidas:
É apropriado usar display: table para criar layouts ou deve ser usada apenas para criar tabelas, como faz a tag
?
Enfim, qual a aplicação apropriada dessa propriedade?

A: O modelo de layout table, é apropriado para exibição de estrutura de dados tabulares, "pois possuem uma estrutura interna complexa, com vários papéis diferentes que seus filhos e descendentes podem preencher".
Ele se torna apropriado quando faz sentido, não faz sentido usá-lo em um elemento img apenas para fazer uso de propriedades de alinhamento, por exemplo.
Achei que uma resposta objetiva e com referências, fosse suficiente, talvez pela relação complexa embutida em seu interior o que segue abaixo seja necessário.

..."o display table faz com que o elemento (divs, sections, etc.) tenha um comportamento bem semelhante a de uma tabela com a tag table...

Quando diz semelhante, me passa a impressão de algo um tanto distante, entretanto é o comportamento de uma tabela.
table

"O elemento gera uma wrapper box de tabela principal que estabelece um contexto de formatação de bloco e que contém um grid box de tabela gerada adicionalmente que estabelece um contexto de formatação de tabela."

Veja um pouco mais sobre a complexidade de modelos de layout:

Alguns modelos de layout, como o table e o ruby , possuem uma estrutura interna complexa...
...
  box com tipos de exibição específicos de layout geram wrapper box anônimas ao redor de si quando colocadas em um pai incompatível, conforme definido por suas respectivas especificações.
Por exemplo, o layout de tabela requer que uma table-cell deva ter table-row como pai.
Se for mal interpretado, assim:

...

Ele irá gerar wrapper box em torno de si, produzindo uma estrutura como:

block box
└anonymous table box
 └anonymous table-row-group box
  └anonymous table-row box
   └table-cell box

Mesmo se o pai for outro elemento da tabela interna , se não for o correto , as wrapper box serão geradas.
Esse "conserto" garante que o layout da tabela tenha uma estrutura previsível para operar.

Faz sentido... x)


text:
Q: unity create dll with editor x64 I need to create a dll using the editor 64bits to reuse in unity 64 bits environment...
to do this I've added this option:
CompilerParameters cp = new CompilerParameters();
cp.CompilerOptions = "/platform:x64";

but i receive this error:
(0,0) : error CS8088: Your .NET Runtime does not support `PE32Plus'. Please use the latest Mono runtime instead.

and If I create a dll 32 bits, when I load with
assembly = System.Reflection.Assembly.Load(mydll.bytes);

it gives me the badimageformat...
where I can definetively resolve this issue?


text:
Q: Scrolling down to div, while hiding first div, makes the page jump down I've got this JSFiddle
The problem is, when I fade out the first div, the page jumps down - so the scrolling is conflicting with the fade out.
Can anyone help me? Thank you.
$(function(){
    setTimeout(function(){
      $('html, body')
      .css({
        'overflow': 'auto'
      })
      .animate({
        scrollTop: $('.second').offset().top
      }, 1500);
    }, 2000);
    return false;
  });

  setTimeout(function() {
      $('.first').fadeOut(0);
  }, 3400);

JSFiddle:
http://jsfiddle.net/em9yycj5/10/

A: The timing wasn't really working. The second timeout would have to start after the initial one has finished - or you could interrupt the animation (or both to be sure) :
setTimeout(function(){
    $('html, body')
    .css({overflow: 'auto'})
    .animate({scrollTop: $('.second').offset().top}, 1500);
}, 2000);

setTimeout(function() {
    $('.first').hide();
    $('html, body').stop().scrollTop($('.second').offset().top);
}, 3400);

http://jsfiddle.net/em9yycj5/16/
Not sure what is meant with 'a click function' in the comment above...


text:
Q: How to remove the login swipe screen using Registry edits in Win 8.1 I want to eliminate the need to swipe the screen before getting to the log in screen on my Win 8.1 Update computer. I do not have the pro version so there is no gpedit.msc utility present.
What registry keys should I modify to remove this nuisance?
Thanks.

A: This works in both Windows 8.1 and Windows 10
You can use the registry editor do disable the lock screen image, which will remove the need to swipe the lock screen every time you want to unlock your computer (so when you press WinKey + L, it only shows your logon image and password field):

*

*In the registry editor, navigate to the following key (if the key does not exist, you will have to create it manually):  HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Personalization

*Select Personalization key and in right-side pane, create a new DWORD NoLockScreen and set its value to 1.

*Close Registry Editor and log off or restart Windows to take effect. It'll completely turn off lock screen.
If you want to restore lock screen in future, just delete the DWORD or set its value to 0.
Source


text:
Q: How to give administrator rights to the local user Windows 10 Pro? Is there way to give local user rwx rights on Windows 10 Pro 20h1?I need to make user possible to execute only 1 file in user directory

A: One solution would be to use a utility such as
RunAsSpc
with which you may call a program that requires a password, but while keeping the
password itself completely secret.
You may run an application as another user or even start program as administrator
from a limited account, just the same as using the command
runas,
but without manually entering the password on each run.
The password and all other details are kept by RunAsSpc in an encrypted database,
so the administrator's password is not visible to the user running the command.
For more details about using it see the article
Pass the password to Runas with RunAsSpc.
RunAsSpc is free for private use.


text:
Q: HMAC implementation in C with SHA384 I need an HMAC implementation with SHA384 in C. It is needed for some API I'm writing.
If anyone can provide at least a starting point I would be happy. Thanks!

A: Use the openssl library.
An example of using openssl to generate an SHA384 hash is here: http://www.askyb.com/cpp/openssl-sha384-hashing-example-in-cpp/
It claims to be in C++ but it's pretty much straight C.


text:
Q: rCharts nvd3 multibar chart I am interested in plotting JVM GC events using thin vertical bars using nvd3 and rCharts. The example data is like this. The time taken is in seconds.
Event         Date         TimeTakenforEvent

FullGC        1/1/2014        10
GCType1       1/1/2014        30
GCType2       1/1/2014        60
GCType3       1/1/2014        20
GCType4       1/1/2014        70

The events will be dynamically added to a R data frame as and when they happen. The chart is cumulative but every event type will cause a bar of a certain color to be plotted. So, for example, Full GC events will plot blue bars. Date is plotted on x-axis and the time taken is plotted on the y-axis.
I know how to use R and add data to a data frame. So this is a question about the rChart plotting function.
I think the solution could be something like this
p2$chart(color = "#! function(d){ return d.y > 12 ? 'red':'blue'} !#")
p2$chart(color = "#! d3.selectAll('rect.nv-bar').style('fill', function(d, i){return d.y > 12 ? 'red':'blue;}  !#")

Can someone guide me ?

Update: I have determined that this example code works.

p2 = nPlot(x = "Var1", y = "Freq", data = bpf3, type = "discreteBarChart")
p2$chart(color = "#! function(d){ return d.Freq > 12.0 ? 'red':'blue'} !#")

But the 'Event' is what determines color in my case.

A: I made some assumptions, and I think I understand the result you would like to achieve.  Let me know if something like this works.  It uses d3's d3.scale.ordinal to provide a translation from an event type to a color.  See this d3 scale tutorial if you want additional details.  Let me know how this works for you.
  require(rCharts)

  bpf3 <- data.frame(
    Var1 = rep(1:20),
    Freq = round(runif(20,1,20)),
    Event = unlist(lapply(1:5,function(x){rep(LETTERS[x],4)}))
  )

  p2 = nPlot(x = "Var1", y = "Freq", data = bpf3, type = "discreteBarChart")
  p2$chart(
    color = "#! function(d){
      var ourColorScale = d3.scale.ordinal().domain(['A','B','C','D']).range(['red','blue','green','purple']);
      return ourColorScale(d.Event);
    }!#")
  p2


text:
Q: How to connect to login from to SQL Server I Have a made a mysql and php login form which connects to an xampp database. I want it to connect to my local SQL server I made with Microsoft SQL 2019. Can you please explain me the code I need to change to connect to it. It would help me alot.
Thanks,
$server = "localhost";

$user = "root";

$pass = "";

$database = "loginform";

$conn = mysqli_connect($server, $user, $pass, $database);

if (!$conn) {

die("");

}


text:
Q: Migrating from apache to nginx So I've been using apache for all of my PHP projects, but now I've been forced to using nginx on the server. I've no clue how to do pretty urls with nginx. So I started converting my .htaccess file into an nginx config script, and tried modifying the nginx config file, but no luck.
This is my .htaccess file:
Options -MultiViews
RewriteEngine On

RewriteBase /wallfly-mvc/public
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

This is my nginx.conf server block:
server {
    listen 80; listen [::]:80;
    server_name  deco3801-superflyz.uqcloud.net;
    root         /var/www/htdocs;

    include "set_cookie.conf";
    rewrite_by_lua_file "etc/nginx/lua/auth_filter.lua";

    location / {
        index  index.html index.htm index.php index.jsp index.aspx;
        try_files $uri $uri/ =404;
    }

    location /wallfly-mvc/public/ {
        if (!-e $request_filename) {
            rewrite ^/wallfly-mvc/public/(.+)$ /wallfly-mvc/public/index.php?url=$1 break;
        }
    }
}

I want every request to point to public/index.php. This is my project structure:
wallfly-mvc/
  app/
  public/
    index.php
    css/
    js/
    img/

How should I change the nginx.conf file? Any help would be appreciated.

A: You can use location ^~ to capture the directory. Its priority is higher location /
server {
    #...

    location ^~ /wallfly-mvc/public/ {
        if (!-e $request_filename) {
            rewrite ^/wallfly-mvc/public/(.+)$ /wallfly-mvc/public/index.php?url=$1 break;
        }
    }
}


text:
Q: Reference request for generic smoothness Consider the following: Suppose that $K$ is a perfect field, $V$ and $W$ are integral $K$-varieties, $V \to W$ is a dominant morphism, and the function field of $V$ is a separable extension of the function field of $W$. Then there is a dense open subvariety $U$ of $V$ such that $U \to W$ is smooth.
I would like a reference for this. I need this for something, and I have a proof, but I think this should be very well known so it's probably silly to write out a proof.
Vakil's notes give a proof in characteristic zero, but he doesn't give a citation. I have seen a sketch of a proof on mathoverflow, but no citation.
I apologize if this is a silly question. I'm doing some algebraic geometry without having any real background in the subject. I think this might be so well-known that you wouldn't need a citation for an algebraic geometry paper, but it's going to be used in a model theory paper, so I want to give references for basically everything from algebraic geometry that we use.

A: Well, thanks everyone, but in the end I found a good reference. I will post it here as this might be useful for someone else.
The following is (a special case of) Corollary 5.4.3 in Mumford and Oda's Algebraic Geometry II: Suppose that $V$ and $W$ are integral $K$-varieties, $W$ is regular, and $f : V \to W$ is a dominant morphism. Then $f$ is smooth on a dense open subset of $V$ if and only if the function field of $V$ is a separable extension of the function field of $W$. The result in the book is written for schemes.


text:
Q: HTML - Replace values on button click I'm trying to make a quiz where it displays one question at a time, and on the "submit answer" button click, the button validates the answer (either right or wrong) and also replaces the previous question with a new one.
What I want to know is; how do you replace the question on button click?
Here is a snippet of my code:

Quiz

Question 01 : this is where the queston will go

                                <form name="feedback">
                                    <input type="radio" name="opt" id="opt_1"> ans 1

                                    <input type="radio" name="opt" id="opt_2"> ans 2

                                    <input type="radio" name="opt" id="opt_3"> ans 3

Select an option

                                    <button id="submit_btn" value="Submit" onClick="submit()"></button>
                                </form>

I've tried using an if statement, but it didnt work. I would greatly appreciate your help as my knowledge on html and js are very basic.
Thank you in advance!

A: This is what your code should look like:

var questions = ["Question 1", "Question 2", "Question 3"]; //Array containing all your questions. Make sure to include the question that's already being displayed

var possibleAnswers = [
  ["answer 1", "answer 2", "answer 3"],
  ["answer 1", "answer 2", "answer 3"]
]; //An array of arrays containing the answers to every question. Make sure the answers are in the same order as the questions

var currentQuestion = 0;

var question = $("#question");
var answers = $(".answer");
var button = $("#submit_btn");
var buttonAction = function() {
  currentQuestion++;
  question.text(questions[currentQuestion]);

  for (var i = 0; i < answers.length; i++) {
    answers[i].textContent = possibleAnswers[currentQuestion][i];
  }
};

button.on("click", buttonAction);

Quiz

Question 01 : this is where the queston will go

      <form name="feedback">
        <input type="radio" name="opt" id="opt_1"> ans 1

        <input type="radio" name="opt" id="opt_2"> ans 2

        <input type="radio" name="opt" id="opt_3"> ans 3

Select an option

        <button id="submit_btn" value="Submit" onClick="submit()"></button>
      </form>

List of changes:

*

*Removed style="display: none;" from form tag

*Added JavaScript to take care of changing the questions and answers

*Placed the answers between span tags and added a class of "answer" to them to make them easily accesible

A: you can replace the content with this :
function replace(){

var obj = document.getElementById("question");
obj.innerHTML="the_next_question";

}

if you need to get the element by the className you can use :
document.getElementsByClassName("question")[0];


text:
Q: Can I stub different responses for subsequent calls to the same endpoint with Nocilla? I want to do something like this:
stubRequest("GET", "http://localhost:8000/api/foo").andReturn(401)
stubRequest("GET", "http://localhost:8000/api/foo").andReturn(200)

let result = service.myServiceCall()

XCTAssertEqual(result, "My Result")

... so that the first call to /api/foo in my test gets a 401 response and the second call gets a 200. Is this possible with Nocilla?
Note that both these calls happen inside myServiceCall() so I can't reset the Nocilla stubs in the middle.


text:
Q: Tutorials and also small Node.js projects to learn the core api Right now I am confident in shell scripting and know a little Python and Ruby.
I am learning to use node.js. First I worked through the Node Beginner Book, and I want to continue learning more about how node itself works. Before starting to use things like Express, Jade, or Socket.IO, I'd like to learn to do things using only the core node API. What tutorials can help me with this? I'd like to work on a few small projects also to understand more.


text:
Q: Fail to send push notification I am trying to follow the tutorial, to send out push notification:
var hubClient = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://xxx-ns.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=xxx=", "xxxapp");
                hubClient.SendGcmNativeNotificationAsync("{ \"data\" : {\"msg\":\"Hello from Windows Azure!\"}}", "xxxapp");
            }

But I get no response? SendGcmNativeNotification is not supported anymore.

A: SendGcmNativeNotification is marked as internal in Service Bus SDK 2.1.
As for your issue, SendGcmNativeNotificationAsync() doesn't return actual result, it returns a task. The following is an example how you would consume it using c# 5 syntax:
private static async Task<NotificationOutcomeState> CallNotificationHub()
{
    var hubClient = NotificationHubClient.CreateClientFromConnectionString(
                "<your connection string with full access>",
                "<your notification hub name>");
    var outcome = await hubClient.SendGcmNativeNotificationAsync(
                        "{ \"data\" : {\"msg\":\"Hello from Windows Azure!\"}}");
    return outcome.State;
}

CallNotificationHub().Wait();


text:
Q: how can i save my image as base 64 into database I'm trying to save an image from a form into database. I tried this but it's not working:
public function store(Request $request)
{
    $article = new article;
    $photo_articles = new photo_articles;
    // $type = new type;

    $article->NOM_ARTICLE = $request->NOM_ARTICLE;
    $article->DESCRIPTION_ARTICLE = $request->DESCRIPTION_ARTICLE;
    $article->id = auth()->user()->id;
    $article->TYPE_ARTICLE = $request->LABEL_TYPE;
    $article->save();

    $photo_articles->PHOTO_ARTICLE = base64_encode(file_get_contents($request->PHOTO_ARTICLE));
    $photo_articles->ID_ARTICLE = $article->ID_ARTICLE;

    $photo_articles->save();

    return;
}

Here is my form:
<form method="post" action="{{ route('addarticle.store') }}" class="contact_form text-center" id="contact_form">
    {{ csrf_field() }}

                <input type="text" class="contact_input" name="NOM_ARTICLE" placeholder="Nom d'article"
                       required="required">

                <select class="contact_input" name="LABEL_TYPE">
                    @foreach($types as $type)
                        <option> {{$type->LABEL_TYPE}}</option>
                    @endforeach
                </select>

                <input type="hidden" name="MAX_FILE_SIZE" value="250000"/>
                <input type="file" class="contact_input uploadFileInput" id="imagearticle" name="PHOTO_ARTICLE"
                       placeholder="Capture de votre article" name="fic" size=50 required="required"/>

upload image

            <textarea class="contact_textarea contact_input" name="DESCRIPTION_ARTICLE" placeholder="Description"
                      required="required"></textarea>

        <button class="contact_button right" type="submit">Valider!</button>

</form>

My image is in $request->PHOTO_ARTICLE.
Can someone show me how to save it as base64? I've searched a lot but without result.

A: When you're submitting a file with a form you have to set add the attribute
enctype="multipart/form-data" to the opening form tag:
<form enctype="multipart/form-data" method="post" action="{{ route('addarticle.store') }}" class="contact_form text-center" id="contact_form">

otherwise it will only submit the name of the file and not the file itself.
Then in your route you would just need:
$photo_articles->PHOTO_ARTICLE = base64_encode(
    file_get_contents($request->file('PHOTO_ARTICLE')->path())
);


text:
Q: Uploading multipart file with Koush Ion library In my last app I'm going to use Koush Ion library. It's so handy but i have a problem with uploading file to my rest server.
note: My server response to success upload Process is 1
My code i like this:
public class MainActivity extends Activity {

    Button upload, login;
    TextView uploadCount;
    ProgressBar progressBar;
    String token, FilePath;

    Future<String> uploading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        upload      = (Button) findViewById(R.id.upload);
        uploadCount = (TextView) findViewById(R.id.upload_count);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        token       = "147c85ce29dc585966271280d59899a02b94c020";
        FilePath    = Environment.getExternalStorageDirectory().toString()+"/police.mp3";

        upload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (uploading !=null && !uploading.isCancelled()){
                    resetUpload();
                    return;
                }

                upload.setText("Uploading...");

                uploading = Ion.with(MainActivity.this)
                            .load("http://myserver.com/api/v1/tone/upload/?token="+token)
                            .setLogging("UPLOAD LOGS:", Log.DEBUG)
                            .uploadProgressBar(progressBar)
                            .uploadProgressHandler(new ProgressCallback() {

                                @Override
                                public void onProgress(int downloaded, int total) {
                                    uploadCount.setText("" + downloaded + "/" + total);

                                }
                            })
                            .setMultipartParameter("title", "police")
                            .setMultipartParameter("category", "7")
                            .setMultipartFile("file_url", new File(FilePath))
                            .asString()
                            .setCallback( new FutureCallback<String>() {

                                @Override
                                public void onCompleted(Exception e, String result) {
                                    // TODO Auto-generated method stub

                                }
                            })
                            ;
            }
        });

But I got TimeoutException from server. my questions are:
1. Is it right way for selecting file that I've done?!
2. Should is use Future Callback as String?!

I check my request to server by fiddler2, when I try to upload file to server...it show me that request send, multipartParameters send but when try to send file...fiddler show me the error:
Protocol Violation Report:
Content-Length mismatch: Request Header indicated 455 bytes, but client sent 387 bytes.

A: I actually works for me, Here is my code:
final File fileToUpload = new File(localFilePath);
Ion.with(context)
            .load(Urls.UPLOAD_PICTURE)
            .uploadProgressHandler(new ProgressCallback() {
                @Override
                public void onProgress(long uploaded, long total) {
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(notificationId, mBuilder.build());
                    mBuilder.setProgress((int) total, (int) uploaded, false);
                }
            })
            .setTimeout(60 * 60 * 1000)
            .setMultipartFile("upload", "image/jpeg", fileToUpload)
            .asJsonObject()
                    // run a callback on completion
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    // When the loop is finished, updates the notification
                    mBuilder.setContentText("Upload complete")
                            // Removes the progress bar
                            .setProgress(0, 0, false);
                    mNotifyManager.notify(notificationId, mBuilder.build());
                    if (e != null) {
                        Toast.makeText(context, "Error uploading file", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Toast.makeText(context, "File upload complete", Toast.LENGTH_LONG).show();
                }
            });
}

Hope it helps someone :)

A: Searched pretty long for this and noticed that the important thing was to include POST in .load()
Ion.with(getBaseContext()).load("POST",url).uploadProgressHandler(new ProgressCallback()
        {
            @Override
            public void onProgress(long uploaded, long total)
            {
                System.out.println("uploaded " + (int)uploaded + " Total: "+total);
            }
        }).setMultipartParameter("platform", "android").setMultipartFile("image", new File(getPath(selectedImage))).asString().setCallback(new FutureCallback<String>()
        {
            @Override
            public void onCompleted(Exception e, String result)
            {

            }
        });


text:
Q: Override soft keyboard layout I want to know if it is possible to change the layout as in the xml file for the keyboard design for the android keyboard in any case. Also if i want to have two keyboards in alternate to the existing android keyboard how should i make the hide and show functions for the same using the KeyboardView and IKeyboardListener.

A: On non-rooted device you have to create your own IME.
You can switch between keyboard layouts by KeyboardView.setKeyboard().
BTW, your custom service can inflate any kind of view and you can modify view hierarchy by user actions.


text:
Q: Files,strings and save I been having trouble trying to figure this out. When I think I have it I get told no. Here is a picture of it.

I am working on the save button. Now after the user adds the first name, last name and job title they can save it. If a user loads the file and it comes up in the listbox, that person should be able to click on the name and then hit the edit button and they should be able to edit it. I have code, but I did get inform it looked wackey and the string should have the first name, last name and job title.
It is getting me really confused as I am learning C#. I know how to use savefiledialog but I am not allowed to use it on this one. Here is what I am suppose to be doing:

When the user clicks the "Save" button, write the selected record to
  the file specified in txtFilePath (absolute path not relative) without
  truncating the values currently inside.

I am still working on my code since I got told that it will be better file writes records in a group of three strings. But this is the code I have right now.
    private void Save_Click(object sender, EventArgs e)
    {

            string path = txtFilePath.Text;

            if (File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {

                    foreach (Employee employee in employeeList.Items)
                        sw.WriteLine(employee);
                }
            }
            else
                try
            {

                StreamWriter sw = File.AppendText(path);

                foreach (var item in employeeList.Items)
                    sw.WriteLine(item.ToString());

            }

    catch
{
    MessageBox.Show("Please enter something in");
}

Now I can not use save or open file dialog. The user should be able to open any file on the C,E,F drive or where it is. I was also told it should be obj.Also the program should handle and exceptions that arise.
I know this might be a noobie question but my mind is stuck as I am still learning how to code with C#. Now I have been searching and reading. But I am not finding something to help me understand how to have all this into 1 code. If someone might be able to help or even point to a better web site I would appreciate it.

A: You have to determine a way of saving that suits your needs. A simple way to store this info could be CSV:
"Firstname1","Lastname 1", "Jobtitle1"
" Firstname2", "Lastname2","Jobtitle2 "

As you can see, data won't be truncated, since the delimiter " is used to determine string boundaries.
As shown in this question, using CsvHelper might be an option. But given this is homework and the constraints therein, you might have to create this method yourself. You could put this in Employee (or make it override ToString()) that does something along those lines:
public String GetAsCSV(String firstName, String lastName, String jobTitle)
{
    return String.Format("\"{0}\",\"{1}\",\"{2}\"", firstName, lastName, jobTitle);
}

I'll leave the way how to read the data back in as an exercise to you. ;-)

A: As you are writing the employee objects with WriteLine, the underlying ToString() is being invoked. What you have to do first is to customize that ToString() methods to fit your needs, in this way:
public class Employee
{
    public string FirstName;
    public string LastName;
    public string JobTitle;

    // all other declarations here
    ...........

    // Override ToString()
    public override string ToString()
    {
         return string.Format("'{0}', '{1}', '{2}'", this.FirstName, this.LastName, this.JobTitle);
    }
}

This way, your writing code still keeps clean and readable.
By the way, there is not a reverse equivalent of ToSTring, but to follow .Net standards, I suggest you to implement an Employee's method like:
public static Employee Parse(string)
{
        // your code here, return a new Employee object
}

A: There are many, many ways to store data in a file. This code demonstrates 4 methods that are pretty easy to use. But the point is that you should probably be splitting up your data into separate pieces rather than storing them as one long string.
public class MyPublicData
{
  public int id;
  public string value;
}

[Serializable()]
class MyEncapsulatedData
{
  private DateTime created;
  private int length;
  public MyEncapsulatedData(int length)
  {
     created = DateTime.Now;
     this.length = length;
  }
  public DateTime ExpirationDate
  {
     get { return created.AddDays(length); }
  }
}

class Program
{
  static void Main(string[] args)
  {
     string testpath = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile");

     // Method 1: Automatic XML serialization
     // Requires that the type being serialized and all its serializable members are public
     System.Xml.Serialization.XmlSerializer xs =
        new System.Xml.Serialization.XmlSerializer(typeof(MyPublicData));
     MyPublicData o1 = new MyPublicData() {id = 3141, value = "a test object"};
     MyEncapsulatedData o2 = new MyEncapsulatedData(7);
     using (System.IO.StreamWriter w = new System.IO.StreamWriter(testpath + ".xml"))
     {
        xs.Serialize(w, o1);
     }

     // Method 2: Manual XML serialization
     System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(testpath + "1.xml");
     xw.WriteStartElement("MyPublicData");
     xw.WriteStartAttribute("id");
     xw.WriteValue(o1.id);
     xw.WriteEndAttribute();
     xw.WriteAttributeString("value", o1.value);
     xw.WriteEndElement();
     xw.Close();

     // Method 3: Automatic binary serialization
     // Requires that the type being serialized be marked with the "Serializable" attribute
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Create))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        bf.Serialize(f, o2);
     }

     // Demonstrate how automatic binary deserialization works
     // and prove that it handles objects with private members
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Open))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        MyEncapsulatedData o3 = (MyEncapsulatedData)bf.Deserialize(f);
        Console.WriteLine(o3.ExpirationDate.ToString());
     }

     // Method 4: Manual binary serialization
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Create))
     {
        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(f))
        {
           w.Write(o1.id);
           w.Write(o1.value);
        }
     }

     // Demonstrate how manual binary deserialization works
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Open))
     {
        using (System.IO.BinaryReader r = new System.IO.BinaryReader(f))
        {
           MyPublicData o4 = new MyPublicData() { id = r.ReadInt32(), value = r.ReadString() };
           Console.WriteLine("{0}: {1}", o4.id, o4.value);
        }
     }
  }
}