text:
Q: Espelhar inputs com seus valores É possível o jquery entender os elementos de um valor array vindo do html? ps: não sei se é correto dizer que no html tem uma array.
Estou criando com html e jquery um input dinâmico que está tendo o valor do name como se fosse uma array, somando 1 pra cada inserção ;
name="nome=[]", name="nome=[1]", name="nome=[2]"...
isso é para faciltar o PHP selecionar os dados.
Esses inputs criados são espelhados numa outra <fieldset>.
Quero espelhar os values chamando o elemento pelo name consegui isso usando o .keyup() do jquery, mas ele funciona só para o primeiro input, que em tese seria o nome[].

A partir desse jeito que imaginei, tentei criar um for pra chamar cada elemento da "array ". Pelo jeito, da maneira que pensei o seletor só fica no nome[].
Botei na cabeça fazer desse jeito que talvez não esteja enxergando outras maneiras de resolver isso. Tentei tbm com um .click em um botão, aonde os values dos inputs do primeiro <fieldset> copiassem nos values dos inputs do outro <fieldset>, pensei isso por ambos terem o mesmo name.
O que seria indicado ?
Código estudo - Edit#1
Na parte do Java Script está comentado duas maneiras, uma sugerida pelo @Matheus Cuba e uma maneira que fiz pegando pelo #ID, mas gostaria de usar a tag name
https://jsfiddle.net/10nkpt2x/5/

A: Tente este Snippet:
Assim, você coloca uma trigger global nos elementos cuja o atributo name comece com nome (Trocadilho Maravilhoso)

$('input[name^="nome"]').keyup(function() {
  var identificador = $(this).attr('name');
  var valor = $(this).val();
  $('input[name="' + identificador + '"]').val(valor);
});
hr {
  margin: 10px 0;
  border: none;
}

Campo 2:<input name="nome=[2]">
 Campo 2:<input name="nome=[2]">
 Campo 2:<input name="nome=[2]">

 Campo 4:<input name="nome=[4]">

 Campo 3:<input name="nome=[3]">
 Campo 3:<input name="nome=[3]">
 Campo 3:<input name="nome=[3]">

A: Seu problema parece ser de delegação. Ao usar $("seletor").keyup, os elementos adicionados de forma dinâmica não estão incluídos no evento.
Para solucionar, use:
$(document).on('keyup','input[name^="nome"]', function() {

Desta forma, os novos elementos serão escutados pelo evento:

/*-- Essa é a maneira sugerida por @Matheus Cuba ---*/
var soma = 0;

$(document).on('keyup','input[name^="nome"]', function() {
  var identificador = $(this).attr('name');
  var valor = $(this).val();
  $('input[name^="' + identificador + '"]').val(valor);
});

$('#botao').click(function(){
      soma++;

      $('<input id="clone'+soma+'" class="f" name="nome=['+soma+']">').appendTo('.box0');
      $('<input id="clonec'+soma+'" class="f" name="nome=['+soma+']">').appendTo('.box');

      });

$('#x').click(function(){
  if ( soma > 0 ){
    $('.f:last-of-type').remove();

    --soma;
}
    });

contador = function(){
    alert(soma);
}
div {

display: flex;

}

p {

width: 100%;
margin:0 0;
color:grey;

}

#x {

color: lightblue;

}

#botao {

color:coral;}

#x, #botao {

text-align: center;
font-size: 3em;

}

#botao:hover, #x:hover {

cursor: pointer;

}

h1:hover{

cursor: pointer;

}

.box0, .box {

margin: auto;
color:grey;

}

fieldset {

text-align: center;
width:15em;
border: none;

}

input {

text-align: center;
margin-top: 15px;

}

.cont {

display: flex;
justify-content: space-around;

}

+

ALERT DA SOMA

-

 <fieldset class="box0"><input name="nome=[]" placeholder="nome" id="clone0"></fieldset>

 <fieldset class="box"><input name="nome=[]" placeholder="espelho" id="clonec0"></fieldset>


text:
Q: Does Python not reuse memory here? What does tracemalloc's output mean? I create a list of a million int objects, then replace each with its negated value. tracemalloc reports 28 MB extra memory (28 bytes per new int object). Why? Does Python not reuse the memory of the garbage-collected int objects for the new ones? Or am I misinterpreting the tracemalloc results? Why does it say those numbers, what do they really mean here?
import tracemalloc

xs = list(range(10**6))
tracemalloc.start()
for i, x in enumerate(xs):
    xs[i] = -x
print(tracemalloc.get_traced_memory())

Output (Try it online!):
(27999860, 27999972)

If I replace xs[i] = -x with x = -x (so the new object rather than the original object gets garbage-collected), the output is a mere (56, 196) (try it). How does it make any difference which of the two objects I keep/lose?
And if I do the loop twice, it still only reports (27992860, 27999972) (try it). Why not 56 MB? How is the second run any different for this than the first?

A: Short Answer
tracemalloc was started too late to track the inital block of memory, so it
didn't realize it was a reuse. In the example you gave, you free 27999860 bytes
and allocate 27999860 bytes, but tracemalloc can't 'see' the free. Consider the
following, slightly modified example:
import tracemalloc

tracemalloc.start()

xs = list(range(10**6))
print(tracemalloc.get_traced_memory())
for i, x in enumerate(xs):
    xs[i] = -x
print(tracemalloc.get_traced_memory())

On my machine (python 3.10, but same allocator), this displays:
(35993436, 35993436)
(36000576, 36000716)

After we allocate xs, the system has allocated 35993436 bytes, and after we run
the loop we have a net total of 36000576. This shows that the memory usage isn't
actually increasing by 28 Mb.
Why does it behave this way?
Tracemalloc works by overriding the standard internal methods for allocating
with tracemalloc_alloc, and the similar free and realloc methods. Taking a
peek at the source:
static void*
tracemalloc_alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
{
    PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
    void *ptr;

    assert(elsize == 0 || nelem <= SIZE_MAX / elsize);

    if (use_calloc)
        ptr = alloc->calloc(alloc->ctx, nelem, elsize);
    else
        ptr = alloc->malloc(alloc->ctx, nelem * elsize);
    if (ptr == NULL)
        return NULL;

    TABLES_LOCK();
    if (ADD_TRACE(ptr, nelem * elsize) < 0) {
        /* Failed to allocate a trace for the new memory block */
        TABLES_UNLOCK();
        alloc->free(alloc->ctx, ptr);
        return NULL;
    }
    TABLES_UNLOCK();
    return ptr;
}

We see that the new allocator does two things:
1.) Call out to the "old" allocator to get memory
2.) Add a trace to a special table, so we can track this memory
If we look at the associated free functions, it's very similar:
1.) free the memory
2.) Remove the trace from the table
In your example, you allocated xs before you called tracemalloc.start(), so
the trace records for this allocation are never put in the memory tracking
table. Therefore, when you call free on the initial array data, the traces aren't removed, and thus your weird allocation behavior.
Why is the total memory usage 36000000 bytes and not 28000000
Lists in python are weird. They're actually a list of pointer to individually
allocated objects. Internally, they look like this:
typedef struct {
    PyObject_HEAD
    Py_ssize_t ob_size;

    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     */
    Py_ssize_t allocated;
} PyListObject;

PyObject_HEAD is a macro that expands to some header information all python
variables have. It is just 16 bytes, and contains pointers to type data.
Importantly, a list of integers is actually a list of pointer to PyObjects
that happen to be ints. On the line xs = list(range(10**6)), we expect to
allocate:

*

*1 PyListObject with internal size 1000000 -- true size:

sizeof(PyObject_HEAD) + sizeof(PyObject *) * 1000000 + sizeof(Py_ssize_t)
(     16 bytes      ) + (    8 bytes     ) * 1000000 + (     8 bytes    )
8000024 bytes

*

*1000000 PyObject ints (A PyLongObject in the underlying implmentation)

1000000 * sizeof(PyLongObject)
1000000 * (     28 bytes     )
28000000 bytes

For a grand total of 36000024 bytes. That number looks pretty farmiliar!
When you overwrite a value in the array, your just freeing the old value, and updating the pointer in PyListObject->ob_item. This means the array structure is allocated once, takes up 8000024 bytes, and lives to the end of the program. Additionally, 1000000 Integer objects are each allocated, and references are put in the array. They take up the 28000000 bytes. One by one, they are deallocated, and then the memory is used to reallocate a new object in the loop. This is why multiple loops don't increase the amount of memory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: sort from the central of file I have a file full of random string, like below, I would like to sort the file from the middle to start and end.
If the total lines are odd, I would like to start from the central line, then central-1, central+1, central-2, central+2.
If the total lines are even, I would like to start from the floor of the total lines/2, vice versa.
The file is about 100MB, I'm running on a VPS with 2G ram.
I can use tools under unix-like platform. How do I do that?
Please let me know if there's a name for such number sequence.
Thanks.
-----------------BEFORE
line1
line2
line3
line4
line5
line6
line7
-----------------

-----------------AFTER
line4
line3
line5
line2
line6
line1
line7
-----------------

A: If there are an even number of lines, N, in the input, you start with line N÷2, then add +1, -2, +3, -4, … to get the next entries in the sequence.  If N = 8, the sequence is 4, 5, 3, 6, 2, 7, 1, 8.
If there are an odd number of lines, N, in the input, you start with line (N+1)÷2, then add -1, +2, -3, +4, … to get the next entries in the sequence.  If N = 7, the sequence is 4, 3, 5, 2, 6, 1, 7.
This can be implemented fairly simply in awk by slurping the lines of input into an array, and then printing them in the sequence demonstrated.

$ cat script.awk
{ line[++N] = $0 }
END {
    if (N > 0)
    {
        j = (-1) ** (N % 2)
        n = int((N + 1) / 2)
        for (i = 1; i <= N; i++)
        {
            print line[n]
            n += j * i
            j = -j
        }
    }
}
$ seq -f "line%.0f" 1 7 | awk -f script.awk
line4
line3
line5
line2
line6
line1
line7
$ seq -f "line%.0f" 1 8 | awk -f script.awk
line4
line5
line3
line6
line2
line7
line1
line8
$


text:
Q: Incorrect double values returned from mysql to java So I was trying to read some double values from mysql to java.
I am using a mybatis mapper to read my values and return the value as a map.
When I run my query in sql, my value comes out to be -42295.8451869851 but when I use mybatis to pick the same from a query and put it in a java Hashmap the value changes to  {Double@25327}-42295.84518699004 . Why is this anomaly and what can I do to prevent it?
This is the mybatis query line I am using:
I am using the class org.apache.ibatis.session.SqlSession;
List<Map<String, Object>> myListMaps =  getSqlSession().selectList(QUERY_NAME, queryParameters);

Edit: After looking at few responses, I realize that I need to somwhow use bigDecimal instead of Double/Float. So I will reframe my question to solve my purpose here. Is there any way to tell mybatis that a certain sql type is to be mapped to BigDecimal instead of Double/Float in a HashMap?
I also have other values being picked up from sql like integer and varchar that are being converted to the required types of integer and string in java automatically and I want them picked as it is. Just need to change the doubles to bigdecimal.

A: This behavior is expected for the floating point number. You can read how the IEEE 754 works https://en.wikipedia.org/wiki/IEEE_754.
But I think there is another issue happening. You say that the number is double (64-bit), but based on the result it look that it gets converted to float(32-bit)
-42295.8451869851 -> 0xC0E4A6FB0BC59380 (64bit) - 0xC72537D8 (32bit)

-42295.84518699004 -> 0xC0E4A6FB0BC59627 (64bit)- 0xC72537D8 (32bit)

If you want to keep the precision correct then you need to define it correctly both in DB and then in Java use https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

A: Use BigDecimal if you need precision doc.


text:
Q: How do I log into another Battle.net account in Diablo 3? I can't find a "log out" option in-game—how can I switch accounts? Is there some feature to check that will make this easier for me to switch next time?

A: Blizzard recently introduced the Battle.net launcher. This means you cannot switch accounts in any of the blizzard games by simply clicking a "logout" button in-game.
You basically have to Leave the game completely and then you have to switch accounts in the Battle.net Launcher.

A: You can connect with an other account following these steps :

*

*Go to the main menu (the one where you select your character)

*Hit the escape key to show the menu

*Click on "Disconnect" button

You will be back on the login screen, where you can connect with another account.

A: You can disconnect from internet while in-game, you will get a message that you are disconnected and when you press the button to proceed you will be dropped to the login screen, where you can change your login.


text:
Q: Firestore error 'Updating a non-existent query' Sorry for my poor English.
When executing code like the following, an error like the image appears.
@firebase/firestore: - "Firestore(5.5.0): FIRESTORE(5.5.0) INTERNAL ASSERTION FAILED: Updating a non-existent query"

@firebase/firestore: - "Firestore(5.5.0): INTERNAL UNHANDLED ERROR: "

Unhandled Promise Rejection: Error: FIRESTORE(5.5.0) INTERNAL ASSERTION FAILED: Updating a non-exixtent query

Error: FIRESTORE(5.5.0) INTERNAL ASSERTION FAILED: Updating a non-existent query

firestore_error
const db = firebase.firestore();
const dammyRef = db.collection('dammy');

dammyRef.where('num', '>=', 18).where('num', '<', 30).get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      console.log(doc.data());
    })
  });

However, this error occurs only when using iPhone's Safari or Chrome.
There is no error in Chrome on the PC version.
The version of Firebase,
"firebase": "^ 5.5.0",
Please tell me the reason why this error occurs.
Thank you.

A: For me, this error occurred when I had an invalid data type as the third parameter of the Firestore 'where' query. Check your data type and make sure the value matches what is in the database.


text:
Q: Rails production mode 'end' error? I've been trying to get my project on Cloud Foundry for a while now, and eventually narrowed my problem down to this project going into production mode. Of all the errors to get when switching from development mode to production mode, I somehow managed to get an 'unexpected end' error. The culprit is in a controller, seen below:
  companiesController < ApplicationController
  skip_before_filter :require_login
  end
   #def new

There are a load of comments below this section of code, but nothing else. The skip_before_filter refers to a before filter in the application controller, which looks like this:
  class ApplicationController < ActionController::Base
  protect_from_forgery
  include SessionsHelper

  before_filter :require_login

 def current_company
   Company.find_by_subdomain! request.subdomain
 end
 helper_method :current_company

 def scope_current_company
   Company.current_id = current_company.id
   yield
 ensure
   Company.current_id = nil
 end

def require_login
  if current_user == nil
    flash[:failure] = "You must log in to access that resource"
     redirect_to signin_path
   end
 end
end

Just for the sake of completeness, I should also mention that this application also includes multi-tenancy based on subdomains. The subdomains are based on a tenant table in the database. I only say this to clear up any confusion over my code though, but if it somehow helps to shed some light on this problem, then that's great too! I have taken out all references to multi-tenancy and sub-domains for the moment, and simply want to get this project into production mode, so that shouldn't affect it.
The exact error states is your average "unexpected keyword_end, expecting $end' in the companies controller for that single end in the code shown. It doesn't make any sense to me though, I mean it NEEDS to have an end there. Why it would complain is beyond me...
Any help would be greatly appreciated.

A: Is that really the code for CompaniesController? Do you know that the class should be defined like this instead?
class CompaniesController < ApplicationController
  skip_before_filter :require_login
end

Also, if you're doing multitenancy stuff with Rails, you might want to check out my book about doing that: Multitenancy with Rails.


text:
Q: Got com.google.inject.ProvisionExceptionerror when using PostgreSQL JDBC on GraphDB - dependency issue? I'm getting a provision error when using PostgreSQL JDBC on GraphDB. Actually, I created a connection between postgresql and Graphdb by a virtual repository, and I made a ODBC file which includes the RDF mapping information.
Expected: Normaly I can browse PostgreSQL data's hierarchy and so on in GraphDB.
Error: The connection was fine and the repository was created successfully, but when I tried to browse the data, I got this error:

Actions that I did: I did go /opt/graphdb-free/app/lib/plugins/dependencies-plugin/dependencies-plugin.jar to modify the dependency parameter, but it didn't change anything. I did checked the syntax of ODBC file and I don't see anything wrong there.
Anyone have been though this? Was I in the right place to modify the dependency? Or it's something else?


text:
Q: Created a python code using the bootstrap to generate html but unable to add colours to it I have written the below code to generate html report but i am failing to make it look good likewise adding colours, making borders and alphabets bold etc.. i did try adding the tags like "table-bordered .table-dark" etc but nothing is happening. Not sure where I am going wrong. Can someone help me?
    doc = dominate.document(title='###########')
        with doc.head:
            link(rel='stylesheet', href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css")
        with doc:
            with div(cls='container'):
                h1("Sjsdhsdss")
                with table(id='main', cls='table table-striped table-bordered .table-dark .table-hover'):
                    with thead(id='main', cls='thead-dark'):
                        with tr():
                            th("Host")
                            th("Status")
                            th("Reason")
                        with tbody():
                            for i in server_list:
                                for j in iwfhjcn:
                                    if re.search(i, j[0]):
                                        with tr():
                                            td(j[0])
                                            td(j[1])
                                            td(j[2])


text:
Q: JSSC sometime doesn't write to serial port I wrote a java program using JSSC library to communicate with a usb serial device in linux.but I encountered several problems when going to communicate.

*

*Sometimes when going to write data to the port.but serial device didn't read   data.but my java program indicate that write is success.(only sometimes happened)

*Before I write to the port first I check for garbage data and Read them if available and give a purge also. but program didn't detect any garbage data before write.but after write and wait for device response(read) garbage data read by the program.

This is my code snippet for writing to the port:
serialPort.readBytes(); //for check garbage data

//purge the port
serialPort.purgePort(PURGE_RXCLEAR );
serialPort.purgePort(PURGE_TXCLEAR);
serialPort.purgePort(PURGE_RXABORT);
serialPort.purgePort(PURGE_TXABORT);

//write to port
serialPort.writeString(s);

System.out.println("Write: "+s);
return true;

please help me to solve at least any problem of above.


text:
Q: Trying to get property of non-object in php/ Creating default object from empty value in php As a newbie in PHP, I tried to make my own site and faced 2 errors, here's the code:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db name";

$conn = new mysqli($servername, $username, $password, $dbname);
$num = $_GET['id'];
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT date, point, reason, teacher, giver FROM penalty WHERE studentid=$num";
$result = $conn->query($sql);

if ($result->num_rows > 0)
{
    echo "
";
    echo "
";
    echo "date	";
    echo "score	";
    echo "reason	";
    echo "giver	";
    echo "teacher	";
    echo "
";
    while($row = $result->fetch_assoc())
    {
        echo "
";
        echo "".$row["dated"]."	";
        echo "".$row["point"]."	";
        echo "".$row["reason"]."	";
        echo "".$row["giver"]."	";
        echo "".$row["teacher"]."	";
        echo "
";
    }
    echo "
";
}

else if ($result->num_rows = 0)
{
    echo "0!";
}

else
{
    echo "empty";
}

$conn->close();
?>

and the results:

Notice: Trying to get property of non-object in view.php on line 16
  Warning: Creating default object from empty value in view.php on line
  39  empty

What can be the problem to cause this error, and how should I fix it?
Thanks in advance


text:
Q: Prove that the total weighted mean sum of $n$ rationals within $[0,1]$ tends to $\frac{1}{2}$ as $n \to \infty$ This question has been raised because of my initial confusion concerning this question on the upper Darboux sum of $f$:

Again consider $f : [0,1] \mapsto \mathbb R$ be a function defined as
$$
f(x)
= \begin{cases}
   x & \text{if x is rational} \\
   0 & \text{if x is irrational}
   \end{cases}
$$

However in this case I don't want to consider this function as continuous and integrate it, I want to consider it a discrete function consisting of an infinite number of discrete rational fractions and create a suitable weighted mean sum over the interval $[0,1]$.
I wish to calculate the limit of the following weighted mean sum as $n$ tends to infinity:
$$S_n=\frac{1}{n}\sum _{m=2}^n \frac{1}{m-1}\left(\sum _{k=1}^{m-1} \frac{k}{m}-\frac{\sigma _1(m)-m-1}{m}\right)\tag{1}$$
where $\sigma _1(m)$ is the sum of all the divisors of $m$ and $(\sigma _1(m)-m-1)$ is equivalent to Chowla's function for $m>1$
Now using the approximation $$S_n <\frac{1}{n}\sum _{m=2}^n \frac{1}{m-1}\sum _{k=1}^{m-1} \frac{k}{m}=\frac{1}{2}-\frac{1}{2 n}$$
in the limit $n \to \infty$
$$S_{n \to \infty} < \frac{1}{2}$$
However is it seems that in actual fact for my sum $(1)$
$$S_{n \to \infty}=\frac{1}{2}$$
which would mean
$$\lim_{n \to \infty} \frac{1}{n}\sum _{m=2}^n \left(-\frac{\sigma _1(m)-m-1}{(m-1)m}\right)=0 \,.\tag{2}$$
However I'm not sure how to prove this last statement and the relation of the weighted sum formula (1) to the notional Riemann Integral over rational $f$ assuming continuity?
Presumably  I need to first obtain an upper bound somehow for Chowla's function for $m>1$
The discrete plot of
$$\frac{1}{n}\sum _{m=2}^n \left(\frac{\sigma _1(m)-m-1}{(m-1)m}\right) \tag{3}$$
is shown below:

Compared with a discete plot below using a bounding function from Jeffrey Lagarias assuming the Riemann Hypothisis is true:
$$\frac{1}{n}\sum _{m=2}^n \frac{H_m+e^{H_m} \log \left(H_m\right)-m-1}{m (m-1)}$$

I'm not sure the bound needs to be this good to prove $(2)$, even though it seems a better bound to (3) might conjecturally be
$$\frac{1}{e\, n}\sum _{m=2}^n \frac{H_m+e^{H_m} \log \left(H_m\right)-m-1}{m (m-1)}$$
As a further note; numerically it appears that
$$\lim_{n \to \infty} \frac{1}{n}\sum _{m=1}^n \frac{\sigma _1(m)}{m}\approx \frac{\pi^2}{6}$$
which may help with finding a bounding function for $\sigma _1(m)$.
The conjecture of course is that:
$$\lim_{n \to \infty} \frac{1}{n}\sum _{m=1}^n \frac{\sigma _1(m)}{m}= \frac{\pi^2}{6}$$
Update 2:
I can get a very good approximation to
$$\frac{1}{n}\sum _{m=2}^n \frac{\sigma _1(m)}{m (m-1)}$$
using for example
$$\frac{\pi ^2}{6 n} \sum _{m=2}^n \frac{\left(m-\frac{1}{10}\right)^2}{m^2(m-1)}$$
where $\frac{1}{10}$ is a constant added to help give a bounding curve fit. However how do I justify making use of this (admittedly in a sightly modified form) or similar approximation, to prove the limit in $(2)$.


text:
Q: VertexDeclaration is not included OGRE::VES_DEFFUSE I have loaded an entity in my Ogre program. Then list Elements in vertexDeclaration like below.
Ogre::VertexDeclaration::VertexElementList lst = vertex_data->vertexDeclaration->getElements();

In the list i have seen VES_POSITION and VES_NORMAL only. Therefor when i run below code,
const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_DIFFUSE);

posElem is contained nothing or null. How to access this kind of element that is not exist? is it possible?then i have added material like below to my entity. This time model loaded successfully with material and diffuse property. but the problem persists. This means that VertexDeclaration does not contain an element with VES_DEFFUSE semantic (only VES_POSITION and VES_NORMAL). Also i loaded some another models, but none of them had such an element with VES_DEFFUSE semantic.
material base_mesh
{

technique
{
pass
{
lighting on
ambient 0.3 0.3 0.3 1
diffuse 0.1 0.7 0.2 1
emissive 0 0 0 1

}
}
}

A: I convert my mesh file with OgreXmlConverter to xml file. Then edit xml file and add colour_diffuse tag to each vertex tag like below (example):
<vertex>
<position y="2.779611" x="0.272802" z="0.245147"/>
<normal y="-0.291635" x="0.955870" z="0.034669"/>
<colour_diffuse value="1 1 1 1" /></vertex>
<vertex>

Then convert back to mesh file.Now in VertexDeclaration we have VES_DEFFUSE semantic element.


text:
Q: Why use WebMatrix Facebook helpers verus just using facebook generator? I am wondering why would you use the html helper for something like the like button
then using the generator from facebook

A: Why use the Twitter helper, or the Gravatar helper for that matter? Or any helper?
WebMatrix is targeted at an audience of learners. This group is barely assumed to know HTML (although I realise that description covers a lot of experienced Web Forms developers too), so providing a reasonably consistent set of APIs to help make use of social networking widgets makes sense to me. It means that the learner can have Twitter feeds and Like buttons on their first site in a few seconds, rather than having to trawl all over the Internet to find out how these things are done, and then potentially getting confused by the developer material offered by these sites. If they achieve a degree of success early on, they will more likely persist with the framework.


text:
Q: bidirectional dependency between web applicaton context and service context I have 2 spring contexts: "webapplication" context and a "core" context. The context "core" is initialized at server startup and attached to a Singleton class that holds the context. The "webapplication" context is initialized when the webapplication is started.
I want to inject bean dependencies from beans in one context to the other (bidirectional access). The webapplication beans are to be "session" scoped beans.
I'm testing this proof of concept with:  webapp bean --> (that depends on) core bean --> (that depends on another) webapp bean.
At the webapplication context initialization i could inject "core" beans to the "webapplication" beans (a BeanFactory that acceses the singleton do the magic), but can't figure out how to do the inverse; because the Spring ThreadLocal that holds the WebApplicationContext is not yet initialized.
The question is.  Is it what i'm trying to do possible?  If the answer is "yes", how would you do that?
Thank's in advance.
EDIT:
I'd realized i'm doing something wrong. The fact is that i'm trying to inject in the service layer a dependency to a session bean, at the wrong time; that is, at the web initialization time when i have no current user session.

A: This looks to me like an architectural issue, not a technical (and certainly not Spring) one. Your separation between core context and web context is very good. The former handles business processes while the latter is responsible for representation, maybe some API.
The dependency from web (representation, access) to core is understandable and required - after all you are building an interface over business routines. This is how spring-mvc works by default, creating separate child (web) application context of core context.
I can hardly imagine a use case for inverted dependency. Why is your business logic depending on web layer? What if you try to migrate your application one that to a different representation technique (desktop, mobile)? Can you justify the reason for this inverted dependency? What do you mean by session bean?
Bidirectional dependencies, as well as static singletons holding a class-loader wide reference to application context should indicate that something is wrong with the design.


text:
Q: Why are there holes in the Unicode table? Given this area of the Unicode table, for instance:
  ...
    U+1D44E Dec:119886       MATHEMATICAL ITALIC SMALL A 𝑎
    U+1D44F Dec:119887       MATHEMATICAL ITALIC SMALL B 𝑏
    U+1D450 Dec:119888       MATHEMATICAL ITALIC SMALL C 𝑐
    U+1D451 Dec:119889       MATHEMATICAL ITALIC SMALL D 𝑑
    U+1D452 Dec:119890       MATHEMATICAL ITALIC SMALL E 𝑒
    U+1D453 Dec:119891       MATHEMATICAL ITALIC SMALL F 𝑓
    U+1D454 Dec:119892       MATHEMATICAL ITALIC SMALL G 𝑔
    U+1D456 Dec:119894       MATHEMATICAL ITALIC SMALL I 𝑖 # what?!
    U+1D457 Dec:119895       MATHEMATICAL ITALIC SMALL J 𝑗
    U+1D458 Dec:119896       MATHEMATICAL ITALIC SMALL K 𝑘
    U+1D459 Dec:119897       MATHEMATICAL ITALIC SMALL L 𝑙
    U+1D45A Dec:119898       MATHEMATICAL ITALIC SMALL M 𝑚
    U+1D45B Dec:119899       MATHEMATICAL ITALIC SMALL N 𝑛
    U+1D45C Dec:119900       MATHEMATICAL ITALIC SMALL O 𝑜
  ...

I would naturally expect u+1d455 to be MATHEMATICAL ITALIC SMALL H. But it seems not defined on any table I look around.
Why are there holes in Unicode table? (also U+1d49d, u+1d53a, etc.)
Is there any way I can fill them?

[EDIT]: These links do state:

The "holes" in the alphabetic ranges are filled by previously defined characters in the Letter like Symbols block shown below.

and

The Unicode Consortium adds new codepoints to the standard all the time. Visit their website to find out about pending codepoints and whether this one is in the pipe. The following table shows typical representations of how the codepoint would look, if it existed. This may help you when debugging, but is not of real use otherwise.

But I just... don't understand what they mean :\

A: From the comments (cheers guys), I have learnt that these holes are due to some characters being already assigned in Unicode when the whole alphabet had been added.
For instance: before U+1D4* MATHEMATICAL ITALIC SMALL * identifiers were defined, ℎ was already known in the table as
ℎ    U+210E Dec:008462        PLANCK CONSTANT ℎ # here it is

So in order to keep consistency in numbering but NOT to duplicate ℎ id, a hole has been inserted at U+1D455 position.

Similarly, ℬ is known as U+212C SCRIPT CAPITAL B rather than U+1D49D - - - reserved in the MATHEMATICAL SCRIPT CAPITAL letters family.
Similarly, ℂ from MATHEMATICAL DOUBLE-STRUCK CAPITAL letters family is not U+1D53A because it was already known as U+2102 DOUBLE-STRUCK CAPITAL C.
This was a difficult choice, having to deal with retro-compatibility, consistency and reliability altogether :)

A: First of all, sorry for necroposting, but I believe that if I ended up here through a Google search where it was the first or second result, many other people might, too, and they will be as confused as I was.
I don't have a final answer, but I wanted to point out that iago-lito's answer is not completely right—it seems to be a legitimate mistake, whether from the Unicode Consortium, the operating systems I've used to check, or the typeface designers. Well, at least in the case of that specific h: there is the ℎ that's used for the Plack constant, but there is no glyph that would fit what we would consider the mathematical italic small h—that is, a regular width italic serif lowercase h, actually.
My suspicions are that, at the time, most people used serif typefaces everywhere, as Times New Roman is both the default typeface for LaTeX and for many scientific writing guides, such as APA—not to mention browsers, which usually have Times New Roman as the default serif and default typeface. So it could be that the Planck constant h was always rendered as serif, but now, since we use sans-serif typefaces, it's displayed as sans-serif, and there seems to be no way to get a proper, regular weight serif small letter h. Bear in mind that the Planck constant address doesn't have a specific glyph; font files just "redirect" the address to the glyph of whatever letter h they use, so that's why I think that's a possibility, even if it doesn't make so much sense when you think about it.
It's also important to note that many characters have various identical versions throughout Unicode, and, in fact, there is the entire sans-serif alphabet under between 0x1D5A0 - mathematical sans-serif capital a, and 0x1D5D3 - mathematical sans-serif small z, so it's puzzling why they decided not to add this one letter—though people have speculated that it's because of how 'famous' the other one was, and you do want backwards-compatibility. But that doesn't answer it for me, as that actually wouldn't break compatibility. It would just mean that they used the wrong one, and now there is a right one.
Of course, I'm not entirely sure it is a problem in the Unicode Consortium's standard. It could be a mistake in the typeface; maybe the typefaces should have used a serif h as Planck's constant. But this seems to be wide-spread regardless of font file, and, at the very least, there isn't clarity on what typeface designers should have done.
I have, now, submitted a request for information to the Unicode Consortium as to whether they plan to add the letter. Hopefully, they will add it, as the byte number does exist. At least they were this smart.
Meanwhile you can use the mathematical bold italic small h, , which is represented in 8-bit as 0x1D489, or in html as 𝒉. That's all for now, at least.


text:
Q: Embeddings from L-ranks into themselves It is well-known that the existence of a (nontrivial) elementary embedding from a rank $V_\lambda$ (from the von Neumann hiearchy) into itself (i.e. $j:V_\lambda\to V_\lambda$) is a very powerful axiom, as its critical point would be n-huge for all n.
I was wondering what would be the strength of:
(L) There is a nontrivial elementary embedding $j: L_\lambda\to L_\lambda$ (such that $\lambda$ is the supremum of the critical sequence $\{j^n(\kappa)|n\in\mathbb{N}\}$)
I know that the critical point of such an embedding cannot be measurable (as IIRC "there is a measurable" implies that there exists $j:L\to L$).
EDIT: I wrote "as its critical point would be super-n-huge for all n."
This is plain false (it's only n-huge for all n) and I'm sorry if I misinformed anyone.

A: Over ZFC, the statement "There is a nontrivial elementary embedding $j: L_\lambda\rightarrow L_\lambda$ for some $\lambda$" follows immediately from a measurable. To see this, we argue as follows:

*

*If $j:V\rightarrow M$ is an elementary embedding of $V$ into some inner model $M$, then for each $\alpha$ we have $j\upharpoonright V_\alpha: V_\alpha\rightarrow V_{j(\alpha)}^M$ is also elementary.

*If we set $\lambda=j^\omega(\kappa)$, then $j(\lambda)=\lambda$.

*Since $L$ is definable and absolute between inner models, we also have that $j\upharpoonright L: L\rightarrow L$ is elementary (and with the same critical point).
Combining these facts, we get that $j$ restricts to an elementary embedding $L_\lambda\rightarrow L_\lambda$.
More precisely, I suspect that over ZFC it's equivalent to $0^\sharp$. (You certainly get a sequence of $L$-indiscernibles out of it!)
But your last sentence suggests to me that you're interested in this principle over ZFC+V=L. In that case, the answer is that it is inconsistent. This is via the usual construction of a measure on $\kappa= crit(j)$ from an embedding: $$\mathcal{U}_j=\{x\subseteq\kappa: \kappa\in j(x)\}.$$

Let me elaborate on the construction of $\mathcal{U}_j$. The more general context is the following. Suppose $M, N$ are inner models and $j:M\rightarrow N$ is nontrivial elementary with critical point $\kappa$. Then we can form the set $$\mathcal{U}^M_j=\{x\in\mathcal{P}^M(\kappa): \kappa\in j(x)\}.$$ Obviously there's no reason to believe $\mathcal{U}^M_j\in M;$ e.g. if $M=L$, then it never will be. But regardless of what $M$ is, $\mathcal{U}^M_j$ will be a $\kappa$-complete nonprincipal ultrafilter "relative to $M$," in the following sense:

*

*No finite set is in $\mathcal{U}_j^M$.

*If $x\in\mathcal{P}^M(\kappa)$, then $x\in\mathcal{U}^M_j$ or $\kappa\setminus x\in\mathcal{U}_j^M$.

*If $x\subset y$ are subsets of $\kappa$ in $M$ and $x\in\mathcal{U}^M_j$, then $y\in\mathcal{U}_j^M$.

*If $\langle x_\eta\rangle_{\eta<\mu}$ is a sequence in $M$ of subsets of $\kappa$ (that is, the whole sequence is in $M$, not just each individual term) with $\mu<\kappa$, and $x_\eta\in\mathcal{U}_j^M$ for all $\eta$, then $\bigcap_{\eta<\mu} x_\eta\in\mathcal{U}^M_j$.
The first three points are immediate. The last one's a bit subtle. The idea is that since $\mu<\kappa$, $j$ will commute with basic set operations: in particular, we'll have $$(*)\quad j(\bigcap_{\eta<\mu} x_\eta)=\bigcap_{\eta<\mu} (j(x_\eta)).$$ The right hand side clearly contains $\kappa$, so if we can show this we'll have $\bigcap_{\eta<\mu} x_\eta\in \mathcal{U}^M_j$.
To see why $(*)$ is nontrivial, the point is that if a sequence has length $\kappa$ then it "stretches" when we hit it with $j$ - it gains "nonstandard" terms. To understand this, think about the following: if we let $x_\eta=\kappa\setminus\eta$, then each $x_\eta$ is in $\mathcal{U}^M_j$ but $\bigcap_{\eta<\kappa} x_\eta=\emptyset\not\in\mathcal{U}^M_j$.

A: The existence of $0^{\#}$ suffices to produce an elementary embedding $j:L_\lambda\to L_\lambda$, where $\lambda$ is the $\omega$-th Silver indiscernible $i_\omega$. The embedding $j$ sends each of the previous Silver indiscernibles $i_n$ to the next one, $i_{n+1}$, and it is automatically defined on all other elements of $L_{i_\omega}$ because it has to commute with the definable Skolem functions.
(If I remember correctly, the existence of such an elementary embedding is in fact equivalent to the existence of $0^{\#}$.)


text:
Q: How to re-enable notifications for python after disabling it in windows? I made a simple python program to show a system notification and I decided to disable notifications for python for some time and enable it again afterwards in Windows settings > System > Notifications & Actions, however python was not in the list of apps that show notifications.
HOW DO I ENABLE IT AGAIN?
Is possible to do it with the code itself or with command prompt or by any other means?
Code:
from win10toast import ToastNotifier
notif = ToastNotifier()
notif.show_toast("ALERT", "TEST1", icon_path="C:/Windows/SystemApps/Microsoft.Windows.SecHealthUI_cw5n1h2txyewy/Assets/Device.contrast-white.ico", duration=5)

A: 6 Steps to solve this problem:
1 - Open both Settings > System > Notifications & Actions and wherever you run your program (Example - Terminal or IDE)

2 - Increase the time of the notification to be shown by python to a large number like 50 seconds, by changing the duration argument in *.show_toast()

3 - Run your script and quickly refresh the app list found in the Settings window you
opened in step 1 by going to another tab such as Sound and coming back to the previous tab

4 - Now that your program is running and trying to display a notification, Python will be added to the list in until the time duration is elapsed, quickly turn on Python just like how you would for any other app.

5 - Close settings and terminate your script.

6 - Run your script again and the notification you were trying to display should now come as usual.


text:
Q: Upload Images With Aurelia to Express/Multer Api Implementing an Image/File-Upload into my aurelia App. The Express Api works and successfully receives Files and Images using Multer Plugin, tested with Postman.
Now I'm trying to figure out, how to attach the files ot the Aurelia Http/Fetch-Call. Somehow the request is made to the Api, but the images seem not attached. Any Ideas?
Some questions:

*

*Is it correct to attach - in whatever way - the files to the body-key of the request, or do the files need to go seperately?

*Is it correct/neccessary to create FormData and to attach the files - in whatever way - to that Obejct?

*In what part of the HTTP-Request are the files/images stored, how to identify them serverside (in case my middleware is not working correctly)?

This is my approach so far:
Aurelia-Service:
uploadImagesApi(images) {
    let formData = new FormData()
    formData.images = images;
    return http.fetch(url+"/", {
      method: 'put',
      body: formData, // <-- Is this correct?
    }).then(response => {
      return response
    }).catch(error => {
      console.log("Some Failure...");
      throw error.content;
    })
}

Input-Element
<input class="input" type="file" files.bind="images" multiple>
<a click.delegate="uploadImagesApi(images)">Upload</a>

A: uploadImagesApi(images) {
        let formData = new FormData()

        for (let i = 0; i < images.length; i++) {
            formData.append('images', images[i]);
        }

        return http.fetch(url + "/", {
                method: 'put',
                body: formData,
            })
            .then(response => {
                return response
            })
            .catch(error => {
                console.log("Some Failure...");
                throw error.content;
            })
    }

make sure your url variable is defined looks like a global

A: Change formData.images = images; to formData.images = images.item(0);
It might also be required to use 'file' key in formData instead of 'images': formData.file = images.item(o)


text:
Q: Server call from android activity I am working on android app. I need to get data from my server.I was making the server call from acitivity and  got java.lang.reflect.invocationtargetexception because I was doing it on main android thread. To over come this ,I simply create a new thread and called thread.join for it to complete.I want to know is there any side effect of using such code? I tried using handler and async executor but the code became messy.
Would Appreciate help. Thanks!
   Runnable runnable=new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            nearCars=getNearCars();
        }
    };
    Thread t=new Thread(runnable);
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

A: You may use AsyncTask in Android SDK to accomplish such operations. For example:
private class GetNearCarsAsyncTask extends AsyncTask<Void, Void, NearCarReturnType> {
     protected Long doInBackground(Void... arg)
     {
          nearCars=getNearCars();
          return nearCars;
     }

     protected void onPostExecute(NearCarReturnType result) {
         // DO something on UI Thread
     }
 }

However there are pitfalls and gotchas associated with AsyncTask, if you google something like "Problems with AsyncTask" etc. So developers now prefer using a HTTP library like loopj Async Library or Retrofit  to avoid common pitfalls.


text:
Q: Laravel 4 eloquent create doesn't work and fill does I want to create an instance of model called Property using method create with Input::all() as parameter. Input contains only fillable fields. When using create method laravel raise this exception:
alpha.ERROR: exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`propathai`.`properties`, CONSTRAINT `properties_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `properties` (`slug`, `updated_at`, `created_at`) values (, 2014-07-30 10:21:42, 2014-07-30 10:21:42))' in /home/ricardo/CHH/propathai/vendor/laravel/framework/src/Illuminate/Database/Connection.php:555

This exception is happening because insert query is not populated with all input params.
{"bedrooms":"4","title":"ricardo","room_type":"apartment","type":"rent","furnished":"fully_furnished","aging":"new","user_id":"3"}

I tried creating new Property object and using fill() method and it does work.
Code not working
public function store()
{
    $input = Input::all();
    $input['user_id'] = Auth::user()->id;

    $property = Property::create($input);

    return Response::json(array('success' => true, 'redirect' => '/dashboard/properties/'.$property->id.'/edit-details'));
}

Code working
public function store()
{
    $input = Input::all();
    $input['user_id'] = Auth::user()->id;

    $property = new Property;
    $property->fill($input);
    $property->save();

    return Response::json(array('success' => true, 'redirect' => '/dashboard/properties/'.$property->id.'/edit-details'));
}

Model
protected $guarded = array('id','services');

protected $fillable = array('user_id','bedrooms','title','room_type','type','furnished','aging');

If anyone knows why it's happening let me know please.
Thanks.

A: Your slug is not being filled.
 SQL: insert into `properties`
     (`slug`, `updated_at`, `created_at`) values (, 2014-07-30 10:21:42, 2014-07-30 10:21:42)

It may be one of those:
1- Your slug has a different name attribute on your input form.
2- It's not on your fillable array.
3- It's either empty, null or being filtered.
ex: to filter empty inputs I do:
$input = array_filter(Input::all(),'strlen');

By the way, the way you are doing this is not the nicest of ways. Check this out:
http://laravel.com/docs/eloquent
Click on "one to many"
What it would look like on your app?
Your model User
public function properties(){
    return $this->hasMany('Property');
}

Your model Property
public function user(){
    return $this->belongsTo('User');
}

On your controller:
$user = Auth::user();
$input = Input::all();
$input['user_id'] = $user->id;
$user->properties()->create($input);

That would be a more 'Laravel' way to approach it.
Also, if you really wanna go PRO watch Laracasts by Jeffrey Way.
It's the best online resource for Laravel4 I've seen online.


text:
Q: How to run process inside loop after previous process is finished? Java Long story short, i want to upload multiple images to my server using Retrofit 2. i want to loop the process of sending single image based on the size of List image but asynchronously, so second upload only run if the first upload is succeeded. Some people tell me i should send an Array of File to my server instead and parse the array there, but i want to know if there is an error while uploading in client side or not. that way if there is an error (network problem) on first loop, second loop will stop running.
I really don't have clear idea as for how to do the task above, but here is a start.
public class UploadAllImages extends AsyncTask<Void, Void ,Void>{
    @Override
    protected Void doInBackground(Void... params) {
        doSingleUpload(image);
        return;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(upload == succeeded){
          new UploadAllImage().execute();
        }
    }
}

A: I would probably solve it like this:
public class UploadImages extends AsyncTask<Image, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(Image... images) {
        List<Image> remainingImages = new ArrayList<>(Arrays.asList(images));

        while (!remainingImages.isEmpty()) {
            boolean success = doSingleUpload(remainingImages.remove(0));
            if (!success) {
                return false;
            }
        }

        return true;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        // Handle the result of all uploads
    }
}


text:
Q: Secure Connection Failed when run asp.net mvc application with ssl I set using in my asp.net mvc application SSL Enabled = true (so now is https://localhost:63892/ and http://localhost:12555/, but when I run application via Debug, it said "Secure Connection Failed". What I'm doing wrong?

A: Make sure the self-signed certificate that Visual Studio generated is trusted. The certificate is called IIS Express Development Certificate
http://blogs.msdn.com/b/robert_mcmurray/archive/2013/11/15/how-to-trust-the-iis-express-self-signed-certificate.aspx

A: Adding this in case if helps anyone: Using VisualStudio 2015, Windows 10, and IIS10 Express, even though I added the certificate I still wasnt able to access localhost over HTTPS. I resolved by uninstalling IIS10 Express and install IIS8 Express. I was then able to access localhost over HTTPS.


text:
Q: Prevent Modification of PayPal Orders from JavaScript I'm starting to integrate PayPal checkouts with a server workflow.
My basic need is to create an order on the server and ensure that the client can not modify it in any way.
Because of this requirement, I have already ruled out using the "simple" JavaScript-only solution, and I'm instead going for a server integration, calling my own URL endpoints for creating and capturing orders.
However, I have found that the client can just ab-use the actions.order.patch() method to modify almost every aspect of the order, including the amount and the custom_id that I'm attaching to the purchase_item.
Basically, It looks like I have absolutely no guarantee on the order contents, even if I created it on the server,  is this correct?
In that case, it means I have to check each order's contents against the orders database of my application. It is possible, but I was hoping to not have to do that.
Any clues? How do you deal with this issue?
Thanks!

A: If you are particularly concerned about this scenario of patching down the total or other details before capture, the only way to ensure it has not changed is to do a server-side 'get details' call before the capture and at least validate the total amount value, as well as any other field you're concerned about.
Otherwise, the usual general safety solution in ecommerce (for this as well as other potential issues that might crop up) is to simply capture and validate the total in the capture response. If the capture has a total you don't expect, issue an immediate refund or flag the occurrence for review before fulfilling anything.


text:
Q: Can I use a custom UIImageView setter with SDWebImage? When my image finishes downloading with SDWebImage, and it sets my table view cell's image view property, I want to be notified of this in the most transparent way possible.
My first idea was to use a custom setter for my image view, but as SDWebImage sets the .image propety of the image view, I don't have access to that setter to customize.
Right now I just use a didFinishDownloading custom delegate in the completion block of SDWebImage's downloader, but I'd rather it happen automatically. Is there any better way I can be doing this?

A: Try to use this function of SDWebImage:
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock;

In completedBlock you can (for example) post some NSNotification
Set observer with needed selector for corresponding notification and handle it.


text:
Q: The problem with the IPM.Schedule.Meeting.Request and the organizer in Outlook Outlook displays the following text: "As the meeting organizer, you do not need to respond to the meeting," and this happens when Outlook opens my IPM.Schedule.Meeting.Request message.
The message store owner is not the organizer, and I really don't know why Outlook can display this text. Can you help me find out the reason for the behavior of Outlook?

A: If the user/account from which the meeting request was sent has the same display name as the invited attendee then Outlook thinks the meeting organizer is the same person as the attendee. In such cases, Outlook will not let you ACCEPT the meeting request, but instead shows:
As the meeting organizer, you do not need to respond to the meeting.
As a workaround, you need to ensure the display names are not exactly the same. Change one of the display names and the other, so they look different.


text:
Q: authentication for GCP STT Quickstart problem I am following the GCP Speech-to-Text Quickstart.  As best as I can tell, I have followed all setup criteria.

*

*Enabled STT for my project.

*Generated Service API keys and downloaded the JSON file.

*Installed SDK and initialized.

*In Windows CMD shell, I set GOOGLE_APPLICATION_CREDENTIALS to the downloaded JSON file.

*In Windows CMD shell, I executed gcloud auth activate-service-account <my service email generated by GCP>  --key-file= "mypath/JSON key file".

*I executed gcloud auth list and I see my project account identifier.

I executed the example curl command:
curl -s -H "Content-Type: application/json" -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) https://speech.googleapis.com/v1/speech:recognize -d @sync-request.json

And get this error:
{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

No where in the Quickstart steps does it mention OAuth
As a test, I executed:
gcloud auth application-default print-access-token

And got this:
(gcloud.auth.application-default.print-access-token) File "mypath/JSON key file" was not found.

Even though the file exists in the folder I specify.
Trying something else, I tried executing the Java example in the SDK.  It creates a very simple SpeechClient with no credentials, which seems suspect.  I made the GOOGLE_APPLICATION_CREDENTIALS env variable available to the example.  I think the example uses gRCP, but not sure.
The example hangs at:
RecognizeResponse response = speech.recognize(config, audio);

Looking online, I found the likely suspect is bad authentication, which is the same as trying the CMD line example.
Any and all guidance is appreciated.

A: Did you run the curl command from the same directory where your JSON key file is located?
Google's documentation states the following:

Note that to pass a filename to curl you use the -d option (for
"data") and precede the filename with an @ sign. This file should be
in the same directory in which you execute the curl command.

A: I have the answer to the CLI issue.  A dumb mistake on my part.  When I set GOOGLE_APPLICATION_CREDENTIALS I wrapped the pathname in double quotes.  Sigh.  I reset the env variable without the double quotes.
I could successfully run gcloud auth application-default print-access-token and it printed out the token.
I tried the curl command again with $(gcloud auth....) and got same error.  Next, I tried the curl command replacing the $(gcloud auth....) with the token returned above and it worked!
Next, I need to resolve the Java example and I am good.

A: No need to be suspicious:

If you don't specify credentials when constructing the client, the client library will look for credentials via the environment variable GOOGLE_APPLICATION_CREDENTIALS.

In your java code try to print System.getenv("GOOGLE_APPLICATION_CREDENTIALS"), to verify it's set . Probably it's not, depending on how you are setting it in your IDE, or terminal.


text:
Q: Toggle pass by reference parameter based on template type C++ I am implementing a "starts_with" function to check if a string starts with some prefix. I want the function to be able to compare std::string and std::string_view interchangeably. The issue I'm running into is when a std::string is passed as an argument I want it to be passed by reference and a std::string_view to be passed by value.
Currently I have this setup:
#include <string_view>
#include <utility>

template <typename String>
struct string_type {
  using type = const String&;
};

template <>
struct string_type<std::string_view> {
  using type = const std::string_view;
};

template <typename String>
using string_type_t = typename string_type<String>::type;

template <typename String, typename Prefix>
bool string_starts_with(string_type_t<String> str, string_type_t<Prefix> pre) {
  if (pre.length() > str.length()) {
    return false;
  }

  for (auto ch = std::pair{str.begin(), pre.begin()};
       ch.second != pre.end();
       ++ch.first, ++ch.second) {
    if (*ch.first != *ch.second) {
      return false;
    }
  }

  return true;
}

int main() {
  using namespace std::string_view_literals;

  return string_starts_with("hello"sv, "hel"sv) ? 0 : 1;
}

However gcc and clang (tested here) are unable to deduce the template parameters and I have to specify the types explicitly string_starts_with<std::string_view, std::string_view>(..., ...).
One obvious solution would be to provide overloads for std::string_view but then I need to implement 4 different functions with essentially the same body (string_starts_with(std::string, std::string), string_starts_with(std::string, std::string_view), string_starts_with(std::string_view, std::string_view), string_starts_with(std::string_view, std::string)). This might still be manageable but what if there is another string-like object such as std::vector<char> or std::array<char> that I want to introduce to the API it just becomes unmanageable.

A: Nesting a type-aliase disables deduction. Because the compiler has no way to guess which class the nested parameter is possibly defined in. You can define a traits template and/or use meta-programming constructs (enable_if, if constexpr, concept/requires, static_assert...) to constraint the template:
template<typename >
struct str_ref_traits: std::false_type{};
template<>
struct str_ref_traits<std::string&>: std::true_type{};
template<>
struct str_ref_traits<std::string_view>: std::true_type{};

template <typename S, typename P>
bool string_starts_with(S str, P pre) {
    static_assert(str_ref_traits<S>::value);
    static_assert(str_ref_traits<P>::value);
    if (pre.length() > str.length())
        return false;
    return std::equal(begin(pre), end(pre), begin(str));
};

Of course as mentioned in the comments, std::string_view can handle std::string - by design. But I wanted to mention the general rule that nested type-aliase cannot be deduced.
In fact, the design goal of std::type_identity is to be used as a deduction disabler on purpose.
regards,
FM.


text:
Q: Normalizing 3D position data I have a training set with 4 different 3D position vectors as some of the features. I have defined a new 3D coordinate system based on the first 3 of these position vectors to achieve translational and rotational invariance. Then transformed the original points to this new system. Since the last point also originally resides in the same coordinate system, I have transformed that one also. To explain the situation better:
Training data was before (Here assume first 3 vectors are used to describe the new coordinate system and $(x_s,y_s,z_s)$ is the last position vector which will also be converted):
$x_1, y_1, z_1, x_2, y_2, z_2, x_3, y_3, z_3, x_s, y_s, z_s\ldots$  (and other features)
Applying my coordinate system transformation it became
$x_{t1}, x_{t2}, z_{t2}, x_{t3}, x_{ts}, y_{ts}, z_{ts}\ldots$  (and other features)
Number of features decreased in the second case because in the new coordinate system some values are always zero ($y_{t1},y_{t2},z_{t1}$ etc) or equal to another value ($z_{t2} = -z_{t3}$)
The new features are not in similar value ranges, generally $x_{ts}, y_{ts}, z_{ts}$ are much larger than the others $x_{t1}, z_{t2}$ etc. So I want to introduce normalization, but at the same time I don't want to lose semantic relation between the points described in the same new coordinate system.
How should I do it? My initial thought is to look at min-max values of all $x_{t1}, x_{t2}, z_{t2}, x_{t3}, x_{ts}, y_{ts}, z_{ts}$ features and apply min-max normalization with same paramaters to each of them. So $z_{ts}$ for example will be much larger than $x_{t1}$ even after normalization. Does it make sense to do so?


text:
Q: Unable to rename folders in Windows Vista SP2 When logged in as a particular user (an Administrator) on a Windows Vista machine I cannot rename new or existing folders under Windows anywhere on the system, including external USB drives, NAS etc.
When I try to rename a folder it just reverts back to its original name. No error message is displayed. No system events / errors are logged - the system event viewer shows nothing unusual.
Bizarrely I can create new folders, which simply appear as the default "New Folder". Trying to rename the folder at the time of creation just reverts back to "New Folder". I can also delete new and existing folders.
I can create/rename files OK.
This obviously causes all sorts of problems when trying to install new software. Incidentally, the user account in question is only used for installing Windows Updates and new software.
The two 'standard' users on the system can rename folders OK.
I had this exact same problem (on the same machine) a year ago. At the time the only fix that worked (I tried numerous registry fixes as I recall) was to simply create a new Administrator user and delete the old! But it has happened again.
What can cause this problem? How is it better solved?
Thanks.
EDIT#1:
The system appears to be virus/malware free having scanned using Avast!, Spybot Search & Destroy and Windows Defender. HijackThis does not throw up any nasties as far as I can tell either.
I can rename folders from the command prompt (cmd.exe)! It is just within Windows I can't!
EDIT#2:
As requested by @wullx... HT-logfile and running-process-list:
http://pastebin.com/JVbDyDn8
Exported registry-settings under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ 1,142KB (too big for pastebin):
RegExport_VistaSP2_HKCU-ExplorerBranch.reg.txt
UPDATE (2011-05-06):
I ended up deleting the troublesome 'administrator' user account (as I did last year!) and creating a new 'administrator' account and the system now appears to be working fine. The only caveat with deleting the user account as far as I can see is that the 'standard' users on the machine have lost the majority of their desktop shortcuts. I assume the majority of these shortcuts were created as a result of installing software whilst logged in as the deleted 'administrator' account!?

A: Have you already scanned for viruses and malware?
Can you rename folders over cmd.exe?
(I would post that as comment, but I haven't yet the permission to do that - sorry ;))


text:
Q: Summing terms in Table I have a table that looks like
Table[m, {k, 10}, {j, k}, {i, j}]

where, m is a square matrix that depends on the indices $i, j$, and $k$. I want to add all of the m matrices in the table. What is the most efficient way to do it?
If there are only two indices, I can do
Total[Apply[Join, Table[m, {k, 10}, {j, k}]]]

But this is not very fast.
I am trying to avoid nested sums, any suggestions are greatly appreciated!

A: Total takes a second argument which specifies the levels to sum together. In your case you want to preserve the lowest two levels so you need to total down to level -3:
Total[Table[m, {k, 10}, {j, k}, {i, j}], -3]

This will work if you have more indices.


text:
Q: How can you prevent ::-webkit-scrollbar from pushing over elements I'm attempting to use webkit's custom scrollbar and I'd really like to prevent it from pushing over the div's next to it. I've tried hacking it by using an image sprite positioned to the right, but it goes under the scrollbar's trackbar. I've also attempted to hide the trackbar, set the opacity, negative margins/padding, and z-index—nothing appears to be working.
The desired effect would be to have the element (grey bar in image below) to continue to the edge of the container and not stop at the scrollbar track.
How can you prevent ::-webkit-scrollbar from pushing over elements?

The same question has been asked, but no proper answer has been found yet (do not flag as a duplicate).

A: It can be done by overflow: overlay. It is alternative for overflow: auto


text:
Q: Copy Parameter Context NiFi I'm using NiFi UI and NiFi Registry, I created group of processors with parameter context and started version control. Now I want to clone this processors group with different parameter context. I found next:

Import Flow

The following story depicts the steps required to import the flow that was developed above into a new environment and make use of it.
Drag Process Group onto Canvas
Choose 'Import...' and select "Replicate DB to Kafka" flow
User will be prompted to select a local Parameter Context to use for the Process Group:

*

*Select an existing local context

*Create new context, with values initially populated from the values saved in Flow Registry

*Create new context, by copying values from an existing local context

I done this step, but I don't see this options, what i'm doing wrong? How can I create various parameter contexts based on existed?

A: As one of the options, download NiFi CLI and execute 2 commands:
nifi export-param-context -o your_path_to_save -pcid your_pc_id -u your_nifi_url
nifi import-param-context -u your_nifi_url -i your_path_from_load -pcn name_pc


text:
Q: make output redirection I want to redirect the output and error stream of make command to file.
The following command
make 1>&2 ~/tmp/build.log

throws the following error
make: Nothing to be done for `/Users/m/tmp/build.log'.

EDIT:-
Tried
make 2>&1 ~/tmp/build.log

and
make ~/tmp/build.log 2>&1

which gave the same above error message.
I am using mac-leopard os
$ bash --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0)
Copyright (C) 2007 Free Software Foundation, Inc.
Tietos-iMac-2:qt-build ptools$ sh --version
GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin10.0)
Copyright (C) 2007 Free Software Foundation, Inc.

A: Should be
make 2>&1 > ~/tmp/build.log

A: you can also just do:
make &> build.log

"&>" means send stdout and stderr to this file

A: Realize that this is a bit old, but here's one for posterity.
I often find it useful to pipe the stderr to a file:
make > error.log 2>&1

You can then open up the file in vim while passing the -q flag, this will allow you to rattle forward and backward along the list of errors.
vim -q error.log


text:
Q: Defining additional information for custom roles inside Azure active directory We have an issue with App registration custom role functionality within Active directory in Azure. When a user is added to a custom role we need a way to somehow specify additional information that we need to send from azure to client application. Precisely in our case we have entity "restaurants" within our client application. We need to somehow inform the client app from Azure that certain roles can access only certain restaurants or multiple restaurants. So in a way we need to add additional information to the role-user relationship (which is many to many) and specify for which restaurant the role is added to the user.
Currently the only way for me to do this is to add a pattern in the custom app role value field and to specify restaurant ID (or IDs) for each role but that means we need to add a custom role for each role and restaurants. If we have 50 restaurants and 3 roles that would result us in having to make 150 custom app roles inside azure. Please let us know if this is somehow possible to set up this relationship more elegantly.
Please let me know if further clarification is needed.
Thank you.


text:
Q: How to interrupt GLSurfaceView rendering phase and start a new one? Hi Android Developers,
What is the best way to interrupt a current rendering phase of GLSurfaceView and start a new one when mode is equal to "Render_when_dirty"? I artificially stop rendering in "onDraw" method by checking a flag and returning from actual rendering method which is called in "onDraw" method; then, in main thread's context i call "requestRender()" to refresh the scene. However, due to a reason that i am not aware of, some of the intermediary old frames are displayed for a very very short period of time(on the other hand, they endure for so long period of time that users can realize the transition); before actual scene is rendered by opengl es 2.x engine. It doesn't affect anything at all; but troublesome to be fixed. What do you suggest?
P.S. Throwing InterruptedException within onDraw method is useless due to the destruction of actual rendering thread of GLSurfaveView.
Kind Regards.

A: When you say some of the old frames are drawn - do you mean part of the frame that is drawn is old or multiple calls of onDraw() still lead to some of the old information being shown on the display.
There are a few things I can see happening here.  If you have a onDraw() like this:
  onDrawFrame(){
  ... stuff ...
  if (stateVariableSet)
     return;
  ... stuff ...

my understanding is that when the function is done being run, that the back/front buffer get swapped and drawn.  One thing that could be happening here is that you see a few calls of onDrawFrame() being rendered while you try to update the state/State variable.
On the other hand, if you have something like this:
   onDrawFrame(){
   ... stuff..
   semaphore.acquire(); // lock the thread waiting for the state to update
   ... stuff ...

then the things that have been drawn before the lock will be stale (for that frame only though - at least that's what I'd anticipate).
Also are you running on a multi-core system?


text:
Q: How to identify incremental patterns in a string in Python I have a one-column data frame that contains randomly generated characters.
I am hoping to write some code that can identify if any of the characters are following an incremental pattern of some sort.
Example:
ebe120xg21
ebe121xg22
vpq17laos
fvut10hals
ebe122xg23

Some of this numbers are clearly incrementing e.g. 120 and 121
There's also 21,22 and 23.
How would I efficiently identify such kind of incrementation?
The tricky part is that this patterns can appear on any section of the string.

A: Try this:
df['nums']=df.yourcolumn.apply(lambda x: [int(i) for i in re.findall(r'\d+', x)])

df['text']=df.yourcolumn.apply(lambda x: ''.join(k for k in x if not k.isdigit()))

d={}
for i in set(df.text):
    dftemp=df[df.text==i]
    ltemp=[(k, z) for k,z in zip(dftemp.index, dftemp.nums)]
    for p in itertools.combinations(ltemp, 2):
        if any(x>y for x in p[0][1] for y in p[1][1]):
            d[(p[0][0], p[1][0])]=(p[0][1], p[1][1])

This will result to a dictionary with all pairs of rows and the respective numbers where there is an increment in numbers. Applied on your data, it gives the following result:
{(0, 1): ([120, 21], [121, 22]), (0, 4): ([120, 21], [122, 23]), (1, 4): ([121, 22], [122, 23])}

which indicates that there is an increment between rows (0,1) (0,4) and (1,4)


text:
Q: Reading an excel file with read_excel This is my where I got my data set from here.
When I fist read in the data set, and do the head function to double check and this is the output I get the first 7 variable shown, but then I'll get
Variables not shown: Status 11/18 (chr), Location 11/18 (chr), Age 11/18 (dbl), age grp (chr), Gender (chr),
  Ethnic (chr), Prev Relig Aff (chr), Adult/Minor (chr), Resident US Pre-Guyana (chr), Occup US Pre Guyana
  (chr), Govt Income (chr), JT Residence (chr), Occup in JT ~77 (chr), Occup JT ~Aug 78 (chr)

Here is my code
library(readxl)
require(mosaic)
Jonestown = read_excel("C:/Users/Deborah/Desktop/School/STA 418/Homework/jonestown.xls", sheet = 1, col_names = TRUE, skip=0)
head(Jonestown)

Next, I need to create a data set named minors that includes only
(a) people identified as a minor
(b) who were born in the United States and
(c) has only the variables Birth State, Guyana Entry, Status 11/18, Age 11/18, Gender and Ethnic.  You should end up with 293 observations and 6 variables. This is what I have so far
minor = Jonestown$`Adult/Minor`=="Minor" & Jonestown$`Birth Country`=="USA"
Minors = Jonestown[minor,]

I am not show where to go next. Can someone help me?

A: Use this package instead. Works for me:
install.packages("xlsx")#Excel
require("xlsx")#Excel
read.xlsx("C:/Users/Deborah/Desktop/School/STA 418/Homework/jonestown.xls",1)

A: First, the output you first question ("Variables not shown") is perfectly normal and expected when dealing with read_excel. More the point, you may notice (with experimentation) that read_excel returns a class tbl_df, something from the Hadleyverse of packages that intends to provide a more intuitive/graceful presentation and handling of data.frames. It tries very hard to limit the output or "peek" at the contents of a data.frame based on the width (number of characters) of your current window. (Of course, it only does this if you have previously done library(dplyr).)
Second, for filtering, since you're already using one component of the Hadleyverse, I'll suggest a second (though it is not strictly necessary here):
library(dplyr)
dat %>%
    filter(`Adult/Minor` == 'Minor', `Birth Country` == 'USA') %>%
    select(`Birth State`, `Guyana Entry`)
## Source: local data frame [293 x 2]
##    Birth State Guyana Entry
##          (chr)       (time)
## 1           CA         <NA>
## 2           MI   1977-09-23
## 3           MS   1977-08-28
## 4           CA         <NA>
## 5           CA   1977-07-23
## 6           CA         <NA>
## ...

This is just a start, you should be able to bring in the other variables you want. I strongly recommend a dplyr tutorial, such as the vignette that comes with it.
NB: because the column names are not strictly legal (too harsh a word?) for R (see ?data.frame and ?make.names), you need to use the backtick instead of single or double quotes.


text:
Q: Asana and SVN Integration Asana has an API out which they are calling their "REST" api.
https://blog.asana.com/2012/04/announcing-the-asana-api/
Some people have made a post-commit script for git which allows you to add a "#task-id" into the message section when you make a commit and that will add a comment into the Asana task which adds your message from the commit and also provides a link to the code file.
Has anyone done this for SVN? I can't seem to find anything online however I thought I would ask first before spending a ton of time trying to make something for SVN and/or trying to learn git and adding their post commit script.

A: If you haven't found a solution yet, bugify wrote a py script that creates a JSON object they send to their API (which comments/closes... bugs). You need to download their product to see what they've done (the script comes with the tar - basic account is free). I don't think their license authorizes you to use their code but if you know some python you can look at the script and then write your own that connects to asana API instead, with the correct parameters.  Really from what I see it is really simple, and the example gives you the name of the  functions to call to get the POST data (Mostly they are using subprocess.Popen). http://support.bugify.com/kb/integrations/getting-started-with-scmvcs-integration.


text:
Q: Why I can't debug PHP with Xdebug in Sublime Text? My operating system is Ubuntu 18.04
My stack is XAMPP (LAMPP).
I have installed Xdebug as indicated by the official page. I also have the extension to debug in Chrome.
When I try to debug PHP code (Tools > Xdebug > start debugging and then F5 in Chrome where my file is on my local server) it doesn't interrupt at breakpoint. I can see Xdebug windows but nothing happens.
If I go to Tools > Xdebug > Restart session I get a window that says:

Unable to start xdebug session, another application is already listening on configured port (9000)

I don't know if it has to do with the real error.
I have investigated that I have to configure an Xdebug.sublime-settings file, there is one default and another user, in the user I have nothing, and the default looks like this:
{
// For remote debugging to resolve the file locations
// it is required to configure the path mapping
// with the server path as key and local path as value.
//
// Make sure to use absolute path when defining server path,
// because Xdebug debugger engine does not return symbolic links.
//
// Example:
// "/absolute/path/to/file/on/server" : "/path/to/file/on/computer",
// "/var/www/htdocs/example/" : "C:/git/websites/example/"
"path_mapping": {

},

// Determine which URL to launch in the default web browser
// when starting/stopping a session.
"url": "",

// An IDE key is used to identify with debugger engine
// when Sublime Text will start or stop a debugging session.
//
// This package does not filter sessions by IDE key,
// it will accept any IDE key, also ones that do not match this configured IDE key.
// It is merely used when launching the default web browser with the configured URL.
"ide_key": "sublime.xdebug",

// Host address of network interface which Sublime Text
// should listen to connect with debugger engine.
//
// By specifying "" or "0.0.0.0" as host address, Sublime Text
// will listen on all the configured network interfaces.
// This is the desired configuration when debugging
// a script that is located on a remote server.
//
// Otherwise it is recommended to use "127.0.0.1" or "localhost"
// as configuration, when debugging a script on your local machine.
// Due to the fact that by listening on all the configured
// network interfaces raises a security concern as anyone
// can access Sublime Text through the configured port.
//
// When specifying host address of network interface,
// be sure to specify an IPv4 address as Sublime Text
// will listen for connections through an IPv4 socket.
"host": "",

// Which port number Sublime Text should listen
// to connect with debugger engine.
"port": 9000,

// Maximum amount of array children
// and object's properties to return.
"max_children": 32,

// Maximum amount of
// variable data to initially retrieve.
"max_data": 1024,

// Maximum amount of nested levels to retrieve
// of array elements and object properties.
"max_depth": 1,

// Break at first line on session start, when debugger engine has connected.
"break_on_start": false,

// Break on exceptions, suspend execution
// when the exception name matches an entry in this list value.
"break_on_exception": [
    // E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR
    "Fatal error",
    // E_RECOVERABLE_ERROR (since PHP 5.2.0)
    "Catchable fatal error",
    // E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING
    "Warning",
    // E_PARSE
    "Parse error",
    // E_NOTICE, E_USER_NOTICE
    "Notice",
    // E_STRICT
    "Strict standards",
    // E_DEPRECATED, E_USER_DEPRECATED (since PHP 5.3.0)
    "Deprecated",
    // 0
    "Xdebug",
    // default
    "Unknown error"
],

// Always close debug windows and restore layout on session stop.
"close_on_stop": false,

// Show information about super globals in context view.
"super_globals": true,

// Display property by fullname in context view.
"fullname_property": true,

// Do not show possible password values in context view.
"hide_password": false,

// Render evaluated result as parsed output instead of raw XML.
"pretty_output": false,

// Always launch browser on session start/stop.
// Note: This will only work if you have the 'url' setting configured.
"launch_browser": false,

// When launching browser on session stop do not execute script.
// By using parameter XDEBUG_SESSION_STOP_NO_EXEC instead of XDEBUG_SESSION_STOP.
"browser_no_execute": false,

// Do not use the debugging window layout.
"disable_layout": false,

// Window layout that is being used when debugging.
"debug_layout" : {
    "cols": [0.0, 0.5, 1.0],
    "rows": [0.0, 0.7, 1.0],
    "cells": [[0, 0, 2, 1], [0, 1, 1, 2], [1, 1, 2, 2]]
},

// Group and index positions for debug views.
"breakpoint_group": 2,
"breakpoint_index": 1,
"context_group": 1,
"context_index": 0,
"stack_group": 2,
"stack_index": 0,
"watch_group": 1,
"watch_index": 1,

// Custom gutter icons for indicating current line or enabled/disabled breakpoints.
//
// Do not use same icon for following values, because Sublime Text is unable
// to use the same icon for different scopes, in case there are duplicate icons
// detected it will fall back to the corresponding icon in the package.
"breakpoint_enabled": "circle",
"breakpoint_disabled": "dot",
"breakpoint_current": "",
"current_line": "bookmark",

// Path to Python installation on your system.
// Which is being used to load missing modules.
//
// It is recommended to configure your Python path for Sublime Text 2
// especially on older UNIX systems, where some modules (xml.parsers.expat)
// might be missing and could improve performance of package.
//
// Example:
// "python_path" : "/usr/lib/python2.7"
"python_path" : "",

// Show detailed log information about communication
// between debugger engine and Sublime Text.
// Log can be found at Packages/User/Xdebug.log
"debug": false

I am a noob in backend, I have no idea how to configure that file, also, I am new in Linux, I had never had to configure a debugger (since I simply used Visual Studio).
Any other technical detail that I need to give, I update it immediately.

A: Check your "php.ini" and confirm that  xdebug is set to port 9000...
In some environments port 9000 may already be in use by some other application (e.g. if you're running PHP-FPM it is also on port 9000).
Try configuring PHP-XDebug and Sublime to use another port (such as 9003).

A: On XDebug 3, the default port is now 9003. However, it was still not working for me.
xdebug.start_with_request = yes did the trick for my Windows setup
My configuration:
zend_extension="<path/to/xdebug/extension>" # A dll on Windows
xdebug.mode = debug
xdebug.show_local_vars=0
xdebug.log_level=7
xdebug.profiler_output_name=trace.%H.%t.%p.cgrind
xdebug.use_compression=false
xdebug.client_enable=1
xdebug.client_handler=dbgp
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.start_with_request = yes


text:
Q: Fomantic ui toast not showing up because of zindex I am trying to use Fomantic ui "toast".  How can i provide z-index to the setting of the Toast?
I have tried this 'it works normally but not on the site i am working on'

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.8.6/dist/semantic.min.css">
    <script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.8.6/dist/semantic.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('body')
                .toast({
                    message: 'I am a toast, nice to meet you !'
                });
        });
    </script>
</head>
<body>

</body>
</html>

A: Give id to your body and handle via CSS like below.

#yourID {
  background-color:rgba(255, 0, 0, 0.4);
  z-index: 9999;
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/fomantic-ui@2.8.6/dist/semantic.min.css">
  <script src="https://cdn.jsdelivr.net/npm/fomantic-ui@2.8.6/dist/semantic.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#yourID')
        .toast({
          message: 'I am a toast, nice to meet you !'
        });
    });
  </script>
</head>

<body id="yourID">

</body>

</html>

Note: work with id , not with class.

A: The z-index for toast is given by the toast-container which already got z-index:9999 by default.
You can override this according to your needs (check your sites code for the highest z-index and add 1) by
.ui.toast-container {
  z-index: 999999;
}

Every toast inside this container will inherit the z-index. To be even more sure you might add the z-index for every single toast as well
.ui.toast-container .toast-box {
    z-index:999999;
}


text:
Q: Lower bound for the inverse matrix function Let $X$ be a compact metric space and $A :X \to GL(d, \mathbb{R})$ be a continuous function over a homemorphism $T: X \to X.$ We denote $A^{n}(x)= A(T^{n-1}(x)) \ldots A(x).$ Assume that there is $C>0$ such that for all $x \in X$, and $n \in \mathbb{N}$,$$ \|A^{n}(x)\| \leq C,$$
where $\| .\|$ is an operator norm.
Is it true that $\|A^{n}(x)^{-1}\| \geq 1/C$ for all $x$ and $n$?
Attempt: $\|A^{n}(x)^{-1}\|^{-1} \leq \|A^{n}(x)\| \leq C.$ Is it true?


text:
Q: Can't insert single row in Excel spreadsheet in a VBA loop The following code should insert a single row between every 5th row of my spreadsheet but instead inserts 5 blank rows. Single stepping shows that when the Rows(i).select is executed, it selects 5 rows and then does the insert. Very simple code below:
for i = 126 to 1 step -5
   Rows(i).Select
   Selection.Insert Shift := xlDown
next i

A: your code is running well- it does insert blank row after the 5th row, however, your code will insert row on the first loop right after the first row before it will insert blank row after the 5th row. You may try this code
For i = 6 To 126 Step 5
   Rows(i).Select
   Selection.Insert Shift:=xlDown
Next i

or if you want to start from the bottom
   For i = 122 To 1 Step -5
       Rows(i).Select
       Selection.Insert Shift:=xlDown
    Next i

I started from row 6 since row 1 is a header. Then it will start inserting blank row every after the 5th row.

A: Don't use the select command. If the corresponding cells are merged, as many rows as the merged cells are inserted.
Sub test()
    For i = 126 To 1 Step -5
        'Rows(i).Select
        Rows(i).Insert Shift:=xlDown
    Next i
End Sub

Original image if there are merged cells on the sheet

Resut of your code

Resut of my code


text:
Q: How to remove the channel dimension within a Pytorch Model I'm trying to create a GAN that generates audio data. Using a standard GAN that consists only of Conv2d layers has not provided good results, so I'm trying to add an LSTM layer to the model. However, the output of my last Conv2d layer shape is (None, 1 ,256, 64). This is not a valid shape for the LSTM layer and I'm trying to drop the "1" dim of the previous layer, as I don't think it is needed.
I've tried torch.reshape, torch.squeeze, and just indexing the tensor to remove that dim, but all result in shape errors.
How can I add an LSTM layer to this model, and input the correct shape?
class Generator(nn.Module):
    def __init__(self, channels_noise, channels_img, features_g):
        super(Generator, self).__init__()
        self.net = nn.Sequential(
            # Input: N x channels_noise x 1 x 1
            self._block(channels_noise, features_g * 16, (16,4), 1, 0),  # img: 4x4
            self._block(features_g * 16, features_g * 8, 4, 2, 1),  # img: 8x8
            self._block(features_g * 8, features_g * 4, 4, 2, 1),  # img: 16x16
            self._block(features_g * 4, features_g * 2, 4, 2, 1),  # img: 32x32
            nn.ConvTranspose2d(
                features_g * 2, channels_img, kernel_size=4, stride=2, padding=1
            ),

            # Output: N x channels_img x 64 x 64
            nn.Tanh(),
        )
        self.lstm = nn.LSTM(input_size=64, hidden_size=10)

    def _block(self, in_channels, out_channels, kernel_size, stride, padding):
        return nn.Sequential(
            nn.ConvTranspose2d(
                in_channels, out_channels, kernel_size, stride, padding, bias=False,
            ),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(),
        )

    def forward(self, x):
        x = self.net(x)
        x = x[:,0,:,:]
        lstm_out, _ = self.lstm(x)
        return lstm_out


text:
Q: WPF/ASP.NET, Entity Framework ,DbContext и нужно ли вызывать Dispose? Вот и меня настиг этот довольно спорный вопрос. Когда я начал изучать этот вопрос то мне везде попадались примеры с использованием using.
Например как здесь Enitity Framework и Using.
Я являюсь програмистом wpf приложений и когда начал изучать Entity у меня был опыт с его предшественником с DataSet и TableAdapter. Тут было достаточно просто так как DataSet/DataTable может жить отдельно от TableAdapter и все изменения фиксируются в нем. То есть я могу привязать DataTable напрямую к любому DataGrid и вызывать TableAdapter для обновлений в любое время тут же его уничтожая чтобы закрывать соединения и! при этом не писав репозитории на каждый чих изменений. DataGrid меняя строки вызывал события изменений данных в DataSet, а он сам уже создавал TableAdapter и сохранял изменения в базу.
Но в Entity все не так, и у меня это вызывает большой дискомфорт. В большинстве примерах пишутся репозитории в которых оборачивается DbContext который тут же уничтожается. И это повлекло за собой что я писал на каждый чих CRUD обработку событий DataGrid где он бы вызывал этот репозиторий для сохранения изменений.
Начав копать глубже я нашел пару статей. В которых это опровергалось. И утверждалось что DbContext сам закрывает соединения когда запрос выполнился.
Номер один
Номер два
Еще немного поискав я нашел, что и для ASP.NET MVC так же не требуются репозитории, так как контроллер уничтожается после обработки запроса и в некоторых фреимворках так же есть подобные DataGrid. Они отправляют события изменения данных и самому почти ничего не нужно писать для большинства случаев.
Попробовав написать без репозитория - создав один раз DbContext и не закрывающем его на всем протяжении работы приложения это сильно облегчило работу. Коллекции не уничтожаются, они связаны с контекстом который сам отправляет изменения. Но возникла небольшая проблема когда приложение работает очень долго при возобновлении работы вылетает исключение. Незнаю чем это вызвано. Думаю нужно просто отловить исключение, заного создать контекст и привязать все коллекции.
Вопрос в том - как же всё-таки удобнее и правильнее использовать контекст?
С репозиториями/без или есть еще вариант по вашему?


text:
Q: Static Website on AWS s3 - Ajax Post to Formspree.io I'm currently trying to host a simple static website on AWS S3. I have just made a simple form which emails the form information to the client using http://formspree.io. The form is functional locally but from what I can find AWS only can handle GET and HEAD requests so I keep receiving a '405 Method Not Allowed' error with my ajax post.
Is there a way I can still use form spree even though I'm hosting on AWS S3? If not what is the best method of having a functional form on a website hosted on AWS S3?
Form code atm:
     <form id="contactform" role="form">

                        <input type="hidden" name="_subject" value="Website contact - PT Enquiry" />

                            Name
                            <input id="name" type="text" name="name" class="form-control">

                            Email Address
                            <input id="email" type="email" name="_replyto" class="form-control">

                            Phone Number
                            <input id="phone" type="tel" name="phone" class="form-control">

                        <input type="text" name="_gotcha" style="display:none" />

                            Message
                            <textarea id="message" name="message" class="form-control" rows="6"></textarea>

                            <button id="submitForm" class="btn btn-default">Submit</button>

             </form>

Ajax Script:
     $("#submitForm").on("click", function() {
        if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "" || $.trim($("#message").val()) === "") {
            swal({   title: "Missing Information", text: "Please fill in each field before submiting.", type: "error", confirmButtonText: "Back" });
            return false;
        }
       else{
           message = $("#contactform").serializeArray();
           var o = {};
           var submitTime = new Date();
           $.each(message, function() {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
           $.ajax({
               url: "http://formspree.io/example@gmail.com",
               data: {o,submitTime},
               header{

               }
           });
           swal({   title: "Success", text: "Thank you for your enquiry", type:"success", confirmButtonText: "Close" });
           document.getElementById('contactform').reset();
           return false;
       }
   });

A: The Ajax request is being posted to formspree.io not S3, so this is a non issue.


text:
Q: Can't remove group after upgrading to gitlab 6.0 I'm running gitlab on RHEL 6, 5.4 was running fine for the past month or so -- I upgraded to 6.0 and things appeared ok, but users can no longer remove their groups from the groups settings. I get a 500 error.
I thought the error was part of the upgrade process, so deployed 6.0 as a new install, and everything works fine except for users can not remove groups from the groups settings. Administrators can remove groups via the admin panel, but not the groups settings.
odd thing, the logs look exactly the same, same auth token, same GET request. Beyond reading the log files, i'm not sure where to start debugging this issue. Any Ideas?

A: Maybe related is the following issue on the issue tracker: https://github.com/gitlabhq/gitlabhq/issues/4870


text:
Q: Passing data to "unknown" viewcontroller I have lots of viewcontrollers, spread over many storyboards.
Is there any way to pass data to a viewcontroller, when only knowing the viewcontroller identifier.
The viewcontroller identifier and storyboard name is is read from a plist, and the viewcontroller is loaded like this:
let storyboard = UIStoryboard(name: plistdata.storyboard, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: menuItem.identifier)
navigationController?.pushViewController(vc, animated: true)

Since i cant cast the viewcontroller as the proper class, i cant set the data. Can a class be casted from a string, something like
let vc = storyboard.instantiateViewController(withIdentifier: menuItem.identifier) as! ClassFromString("MyDestinationViewController")

Or would it be a better approach to have the datamodel keep track of which viewcontroller is being pushed, and fetch the necessary data in the destination viewcontroller as soon as it loads?

A: When you don't know the class of something, but you want to be able to talk to it anyway, that's what a protocol is for. If every one of your anonymous view controller classes adopts MyProtocol, and if MyProtocol requires a takeData method, then you can cast vc to a MyProtocol and call takeData with no further information about what class this view controller is.

A: I think Best approach is Segue... Because Segue make Array of your ViewControllers so it is easy to push, pop, and send data.


text: Q: How to add text below dates in showdatepicker flutter how can I add text below each date in showdatepicer in the flutter mobile app. Just like price in flight booking apps. And then select a particular date. Is it possible with syncfusion datepicker or any other?


text:
Q: change the values of rows according to an specific condition in R spark I have a dataset with information about health insurances. Im working with dplyr in R spark and I have to do this exercise:
analyze the age group from 14 to 64 years old, assigning people younger than 14 years old to 14 years and people older than 64 years old to 64. Show a graphical representation of the relationship between Age and average individual insurance rates.


text:
Q: API separate requests laravel Im trying to get multiple request of same function.
Im using this lib - https://github.com/uldisn/sharkscope
Important part for me is this:
$client = new SharcScopeClient($domain, $appName, $userName, $password, $appKey);

        if($client->requestPlayerStatistic('username')) {
            $playergames = $this->client->responseData;
        }

API can request only one player, and I need to make this function on repeat with different usernames.
I tried this:
$client = new SharcScopeClient($domain, $appName, $userName, $password, $appKey);
$users = User:all();
foreach ($users as $user) {
        if($client->requestPlayerstatistic($user->name)) {
            $playergames = $this->client->responseData;
        }
}

but still getting only one (first user) response data.
dd($groupList) image
I need to created functions for each users? Maybe is it possible to do something with cronjobs, or maybe you have better ideas? Thanks


text:
Q: Setting up DKIM for Additional Domains on Google Apps to remove "via" message on Gmail I have a Google Apps account on primary.com. Recently I added secondary.com as an additional domain to primary.com's Google Apps account.
I then added an address @secondary.com to my account @primary.com and set it up as a "Send mail as" address in Gmail using smtp.gmail.com and user@primary.com to authenticate via SMTP.
DKIM is set up for both primary.com and secondary.com for Google Apps.
When I send an email from user@secondary.com in Gmail the recipient sees: from user@secondary.com via primary.com. The message also says "mailed-by: primary.com" rather than secondary.com and there is no "Signed by" showing.
Can anyone point me in the right direction?

Edit:
I have removed the setting which uses the explicit Gmail SMTP server. Now messages are "Signed by" secondary.com as they should be but are still showing as "mailed-by: primary.com".