text:
Q: Is it okay to let a range view own a shared_ptr containing state it needs? Basically I am trying to get around the fact that the following does not work with range-v3 ranges: (this is a toy example but illustrates the problem.)
namespace rv = ranges::views;

auto bad_foo() {
    std::vector<int> local_vector = { 23, 45, 182, 3, 5, 16, 1 };
    return local_vector |
        rv::transform([](int n) {return 2 * n; });
}

int main() {

    for (int n :bad_foo()) {
        std::cout << n << " ";
    }
    std::cout << "\n";
    return 0;
}

The above doesn't work because we are returning a view that references data that will go out of scope when bad_foo returns.
What I want to do is store the vector in a shared pointer in such a way that the range view will keep the shared pointer alive. Note that the obvious version of this idea does not work i.e.
auto still_bad_foo() {
    auto shared_vector = std::make_shared<std::vector<int>>(
        std::initializer_list{ 23, 45, 182, 3, 5, 16, 1 }
    );
    return *shared_vector |
        rv::transform([](int n) {return 2 * n; });
}

still fails because shared_vector is not actually getting captured by the range view. What we want to do is force the range view to own the shared pointer.
The following seems to work to me.
auto good_foo() {
    auto shared_vector = std::make_shared<std::vector<int>>(
        std::initializer_list{ 23, 45, 182, 3, 5, 16, 1 }
    );
    return rv::single(shared_vector) |
        rv::transform([](auto ptr) {  return rv::all(*ptr); }) |
        rv::join |
        rv::transform([](int n) {return 2 * n; });
}

We use single to turn the shared pointer into a single item range view, turn the single item into a range of ints by dereferencing the pointer in transform and wrapping the vector in a range with all, yielding a composition of range views, which we then flatten via join.
My question is is the above really safe and if so is there a less verbose version of the same idea?
Edit: updated the question to just be about range-v3 ranges as @康桓瑋 has alerted me that this issue is not a problem with C++20 ranges as long as it is not a requirement for the owning range views to be copyable.

A:
Basically I am trying to get around the fact that the following does
not work: (this is a toy example but illustrates the problem. I'm
using range-v3 but this question applies to standard ranges too)

If you are using the standard <ranges> then you don't have to worry about this, just move the vector into the pipe, which will move the ownership of the vector into owning_view
auto not_bad_foo() {
  std::vector<int> local_vector = { 23, 45, 182, 3, 5, 16, 1 };
  return std::move(local_vector) | // <- here
    std::views::transform([](int n) {return 2 * n; });
}

Demo

A: How about capturing the vector in a lambda to extend its lifetime?
auto create_foo() {
    std::vector<int> local_vector = { 23, 45, 182, 3, 5, 16, 1 };
    return [captured_vector = std::move(local_vector)]() {
        return captured_vector | rv::transform([](int n) {return 2 * n; });
    };
}

int main() {
    for (int n : create_foo()()) {
        std::cout << n << " ";
    }
    std::cout << "\n";
}


text:
Q: How do you embed a tflite file into an Android application? What are the step-by-step instructions for using a TFlite file and embedding it in an actual Android application? For reference, this is regression. Input will be an image, output should be a number. I have already looked at the TensorFlow documentation but they do not explain how to do it from scratch.

A: The following steps are required to use TFLite in Android:

*

*include the dependency 'org.tensorflow:tensorflow-lite:+' to your build.gradle

*Make sure files of type .tflite will not be compressed using the aaptOptions in your build.gradle

*Make the model .tflite file available by putting it into your apps assets folder (To create one, right click res folder, click res > New > Folder > Assets Folder)

*In your java class that will handle the inference, import the tflite interpreter

*Load the model file as a MappedByteBuffer in your java class

*Load the MappedByteBuffer into your TFLite interpreter

*Convert input image to float ByteBuffer

*Define output array matching the size of your output layer

*Use the loaded TFLite interpreter to forward pass the input ByteBuffer through your model and write the prediction to your output array.

Let me know if something is unclear!

A: For Android applications, here is a quick example of using TF Lite for classification. You may be able to follow a similar structure as here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/android/app/src/main/java/org/tensorflow/demo/TFLiteImageClassifier.java

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get system error 115(operation in progress) on blocked socket connect() In general, system error 115 occurs on a non blocking socket connect(), and the connection needs to be further checked through the select() interface.
But I didn't use fcntl() to set socket to O_NONBLOCK, just set a send timeout as shown below:
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len);
So, In my scenario, is the cause of the 115 error in connect() the same as that of a non block socket?  And how do I know how long the connect interface is blocked when I get a 115 error?
Code example:
socklen_t len = sizeof(timeout);
ret = setsockopt(real_fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len);
if (-1 == ret)
{
    LOG(" error setsockopt");
    return SOCKET_FAIL;
}

ret = connect(fd, (struct sockaddr *) &dest, sizeof(dest));
if (0 != ret)
{
    LOG("error connect = %s", strerror(errno));
    return ret;
}

Result:
Sometimes get system error "Operation now in progress".
The error number is 115, which is also defined as EINPROGRESS.

A: Thank you for your ideas. I found the answer in the man socket(7). EINPROGRESS errors can also occur in blocked sockets.
   SO_RCVTIMEO and SO_SNDTIMEO
          Specify  the  receiving  or  sending timeouts until reporting an
          error.  The argument is a struct timeval.  If an input or output
          function  blocks for this period of time, and data has been sent
          or received, the return value  of  that  function  will  be  the
          amount  of data transferred; if no data has been transferred and
          the timeout has been reached, then -1 is returned with errno set
          to  EAGAIN  or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just
          as if the socket was specified to be nonblocking.  If the  time‐
          out  is set to zero (the default), then the operation will never
          timeout.  Timeouts only have effect for system calls  that  per‐
          form   socket   I/O   (e.g.,   read(2),   recvmsg(2),   send(2),
          sendmsg(2)); timeouts have no  effect  for  select(2),  poll(2),
          epoll_wait(2), and so on.


text:
Q: Deviation bound for the maximum of the norm of Wiener process Let $W(t)$ be an $n$-dimensional Wiener process. Denote by $\chi_n^2$ a chi-squared random variable with $n$ degrees of freedom. I have recently found the following inequality given without proof:
$$
{\mathbf P} \left\{ \max_{t\in[0,2]} \|W(t)\|> x\right\}\leqslant 2 {\mathbf P} \bigl\{\chi_n^2>x^2/2\bigr\}.
$$
Why is this bound true? What other deviation inequalities for the Bessel processes are known?

A: A general bound that's sometimes useful is given by Fernique's theorem.  It's a general fact about Gaussian measures on Banach spaces, but in this case it gives the following: there are constants $C, \epsilon > 0$ (depending on the dimension $n$) such that
$${\mathbf P} \left\{ \max_{t\in[0,2]} \|W(t)\|> x\right\}\leqslant C e^{-\epsilon x^2}.$$
You can find a proof in these lecture notes of mine (see Section 4.2).


text:
Q: Safe way to use batch listener I am trying to use spring-kafka 1.3.x (1.3.3 and 1.3.4).  What is not clear is whether there is a safe way to consume messages in batch without skipping a message (or set of messages) when an exception occurs eg network outage.  My preference is also to leverage the container capabilities as much as possible to remain in Spring framework rather than trying to create a custom framework for dealing with this challenge.
I am setting the following properties onto a ConcurrentMessageListenerContainer :

.setAckOnError(false);
.setAckMode(AckMode.MANUAL);

I am also setting the following kafka specific consumer properties:

enable.auto.commit=false
auto.offset.reset=earliest

If I set a RetryTemplate, I get a class cast exception since it only works for non-batch consumers.  Documentation states retry is not available for batch so this may be OK.
I then setup a consumer such as this one:
```java
@KafkaListener(containerFactory = "conatinerFactory",
                   groupId = "myGroup",
                   topics = "myTopic")
    public void onMessage(@Payload List<Entries> batchedData,
            @Header(required = false,
                    value = KafkaHeaders.OFFSET) List<Long> offsets,
            Acknowledgment ack) {
        log.info("Working on: {}" + offsets);
        int x = 1;
        if(x == 1) {
            log.info("Failure on: {}" + offsets);
            throw new RuntimeException("mock failure");
        }

        // do nothing else for now

        // unreachable code
        ack.acknowledge();

   }

```
When I send a message into the system to mock the exception above then the only visible action to me is that the listener reports the exception.
When I send another (new) message into the system, the container consumes the new message.  The old message is skipped since the offset is advanced to the next offset.
Since I have asked the container not to acknowledge (directly or indirectly) and since there is no other properties that I can see to notify the container not to advance, then I am confused why the container does advance.
What I noticed is that for a similar consideration, what is being recommended is to upgrade to 2.1.x and use the container stop capability that was added into the ContainerAware ErrorHandler there.
But what if you are trapped in 1.3.x for the time being, is there a way or missing property that can be used to ensure the container does not advance to the next message or batch of messages?
I can see an option to create a custom framework around the consumer in order to achieve the desired effect.  But are there other options, simpler, and more spring friendly.
Thoughts?

A: From @garyrussell (spring-kafka github project)
The offset has not been committed but the broker won't send the data again. You have to re-seek the topics/partitions.
2.1 provides the SeekToCurrentBatchErrorHandler which will re-seek automatically for you.
2.0 Added consumer-aware listeners, giving you access to the consumer (for seeking) in the listener.
With 1.3.x you have to implement ConsumerSeekAware and perform the seeks yourself (in the listener after catching the exception). Save off the ConsumerSeekCallback in a ThreadLocal.
You will need to add the partitions to your method signature; then seek to the lowest offset in the list for each partition.


text:
Q: PDF Filling and saving in PHP i have 5 PDF's that are editable, if i open it on the website, i can still write on it. What i wanted to know is, after the user fills the pdf, how can i make it save what the user filled and "update" the pdf to save it on the database?
Is there something that does it?
Am i suposed to open the pdf it self in the browser? or a page that includes the pdf as a frame or something
I've already researched a bit but i only find building the form into a PDF, i wanna edit the pdf and save the pdf. It goes in blank and then the user saves it with all the information.


text:
Q: retain unique combinations from a list of tuples in python I have a list of tuples that contain int and str values in them:
Listex:
[23,'item1','item2']
[23,'item2','item1']
[67,'item3','item2']
[55,'item3','item4']
[67,'item2','item3']
[55,'item4','item3']

What I need is to get unique tuples:
Listex output:
[23,'item1','item2']
[67,'item2','item3']
[55,'item3','item4']

I have tried sort() but I get the error that '<' cannot be used with str and int.
Appreciate any help in this regard.
Thank you in advance.

A: First of all use frozenset so that comparisons wont take into account the order of the strings, then use a set to remove duplicates, finally convert back to list of lists:
In [1]: data = [[23,'item1','item2'],
   ...: [23,'item2','item1'],
   ...: [67,'item3','item2'],
   ...: [55,'item3','item4'],
   ...: [67,'item2','item3'],
   ...: [55,'item4','item3']]

In [2]: list(map(list, set(map(frozenset, data))))
Out[2]: [[67, 'item2', 'item3'], ['item1', 'item2', 23], ['item3', 'item4', 55]]

You cannot directly apply set to your original collection because set requires its elements to be hashable, which lists are not. Converting the inner lists into frozenset makes them hashable and has the added bonus of being order-independent. Using a tuple would make the elements hashable but order of the elements would matter.
Depending on what you want to do with the data maybe you can simply use a set of frozensets and avoid the lists altogether:
In [3]: set(map(frozenset, data))
Out[3]:
{frozenset({67, 'item2', 'item3'}),
 frozenset({23, 'item1', 'item2'}),
 frozenset({55, 'item3', 'item4'})}

If you want to keep the number as the first element you can replace list with some function like:
In [5]: def keep_number_first(seq):
   ...:     return sorted(seq, key=lambda x: 1 if not isinstance(x, (int, float)) else 0)
   ...:

which sorts by type:
In [6]: list(map(keep_number_first, set(map(frozenset, data))))
Out[6]: [[67, 'item2', 'item3'], [23, 'item1', 'item2'], [55, 'item3', 'item4']]

This said: if you have to keep data structured in this way, IMHO, it's probably better to come up with your own class or use a namedtuple and give some meaning to the different pieces. For example instead of having [23, 'item1', 'item2'] why not (23, ['item1', 'item2'])?


text:
Q: What is wrong with locking non-static fields? What is the correct way to lock a particular instance? Why is it considered bad practice to lock non-static fields?
And, if I am not locking non-static fields, then how do I lock an instance method without locking the method on all other instances of the same or derived class?
I wrote an example to make my question more clear.
public abstract class BaseClass
{

    private readonly object NonStaticLockObject = new object();
    private static readonly object StaticLockObject = new object();

    protected void DoThreadSafeAction<T>(Action<T> action)
        where T: BaseClass
    {
        var derived = this as T;
        if(derived == null)
        {
            throw new Exception();
        }
        lock(NonStaticLockObject)
        {
            action(derived);
        }
    }
}
public class DerivedClass :BaseClass
{
    private readonly Queue<object> _queue;
    public void Enqueue(object obj)
    {
        DoThreadSafeAction<DerivedClass>(x=>x._queue.Enqueue(obj));
    }
}

If I make the lock on the StaticLockObject, then the DoThreadSafeAction method will be locked for all instances of all classes that derive from BaseClass and that is not what I want.  I want to make sure that no other threads can call a method on a particular instance of an object while it is locked.
Update
Thank you all for your help :  I have posted a another question as a follow up to some of the information you all provided.  Since you seem to be well versed in this area, I have posted the link: What is wrong with this solution to locking and managing locked exceptions?

A: You are locking an object that is used as a lock.
The difference therefor is where the lock is contained (or its accessibility).
If you have it as a static member, it is accessible to all the objects of the same class. So you get a single lock, that will lock them all.
If you have it as member of the class (non static) then it is only accessible to that object. So you will get a single lock per object instance.
There's no good-bad practice in this case. It's just a question of what you want to achieve.
Just remember to avoid locking this in an object.

A: It is not bad to lock on instance fields. Some consider it bad to lock the instance itself, which is implicitely done by using synchronised on instance methods, but this is another story.
Locking on the instance (or "this") can have side effects if other classes also use the instance for locking. You just can be sure if you hold your own personal lock.

A: It's not about it being bad-practice, it's about what is your purpose.
Static fields are accessed (or, "common to") all the instances of that type. So locking such an static field enables you to control concurrency between all the instances of that type, or, the scope of concurrency control  achieved is all the instances of that type.
However, if you lock a non-static field, the lock will only be active for that instance, so you control concurrency only within that instance, or, the scope of concurrency control achieved is the instance.

Now, whenever locking an object I go like this. What is the resource that I'm concurring for? Maybe it's database, maybe it's a bunch of instance fields that can't be changed while I doing a certain processing, etc. Once I know what is I'm locking myself out of, I check it's scope.

*

*If it's an entity outside my application, then it's application scope. Everything must be locked out simultaneously.

*If it's a bunch of instance fields, then it's instance scope.

*If it's a bunch of static fields, then it's type scope.

So, for 1 and 3, use a static field. For 2, use a instance field.
Now, another thing: usually, for 1, you will have a single class that wraps around that resource. And, usually you will design that class as a singleton. Now, with singletons, this is funny: you are guaranteed, by design, to have only a single instance, so it doesn't matter whether you are locking a instance or static field.
PS.: If you are using a lock to protect the instantiation of the singleton, of course it should be static. (why?)


text:
Q: AJAX Cascading DropDown JavaScript event onready I'd like to fire a JavaScript function when AJAX returns the values of drop down items.
The scenario is:
function 1 fires -> ajax gets items from database -> the dropdown items are filles -> my javascript function is called.
Does any of you have idea how to make a handler for such event ?

A: As you've tagged the question with jQuery, I'll show you a jQuery solution:
$.post("someScript.php", function(data) {
    /*This callback function is executed when the AJAX call returns successfully
    You would do something with your dropdown items here
    and then call your next function.*/
});

The various jQuery AJAX methods (post, get, load for example) all provide a way to pass a callback as an argument. The callback is executed upon a successful response from the server. Inside that callback function you can execute whatever code you need to, to deal with data which contains the response.
If you're not using jQuery, I'll assume you already have an XMLHttpRequest object. XMLHttpRequest has a property called onreadystatechange to which you can assign a function that runs when the state changes:
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {
        //This will be reached if the call returns successfully
    }
}

The idea is the same as the jQuery method shown above.


text:
Q: Functional Programming For Embedded Software I was discussing F# and Functional Programming with a friend last night and he brought up an interesting question to me.  How would you do embedded software in functional?  I mean this seems like a fairly natural fit in terms of stateless code but embedded also entails being very frugal with memory and I'm not sure of the story for functional in that regard.
Any suggestions about languages or packages for embedded with functional?

A: Forth is an excellent choice for embedded systems programming. Being a stack language, it can be analysed in terms of function composition (concatenative programming). I see no reason why such a language with more functional aspects could not also be implemented efficiently, but as yet no such thing (to  my knowledge) exists.

A: One option is Erlang. From the wikipedia page:

Erlang is a general-purpose concurrent, garbage-collected programming language and runtime system. The sequential subset of Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing. For concurrency it follows the Actor model. It was designed by Ericsson to support distributed, fault-tolerant, soft-real-time, non-stop applications. It supports hot swapping, so that code can be changed without stopping a system.
While threads are considered to be a complicated and error-prone topic in most languages, Erlang provides language-level features for creating and managing processes with the aim of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using message passing instead of shared variables, which removes the need for locks.
The first version was developed by Joe Armstrong in 1986.2 It was originally a proprietary language within Ericsson, but was released as open source in 1998.


text:
Q: How to automate Docker container's package update I have a container which gets built off of a Dockerfile and every time a new container gets built, I am not able to run apt-get update. I would get an error like There is no public key available for the following key IDs: [some IDs] which I know how to fix manually:
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys [some IDs above].

But is there any way I could get something added to my Dockerfile to fix this issue so I could have the RUN apt-get update in my Dockerfile run properly
Thanks


text:
Q: Two variables Diophantine equation $x^3 - 2y^2 =54$ How  can  we  solve  $x^3 - 2y^2 =54$  Diophantine  equation  in  natural  numbers? Modular  arithmetic  method  is  not  useful  maybe?

A: Since $x$ must be even, $x=2z$, we have:
$$ 4z^3- y^2 = 27 \tag{1}$$
or:
$$z^3 = \frac{y+3\sqrt{-3}}{2}\cdot\frac{y-3\sqrt{-3}}{2}=w\cdot\overline{w},\tag{2}$$
where $w$ lies in the ring of integers of $\mathbb{Z}[\sqrt{-3}]$, that is a UFD.
 This implies that, if $w$ and $\overline{w}$ are coprime, $w=\frac{y-1}{2}+3\omega$ must be a cube in the Eisenstein integers $\mathbb{Z}[\omega]$ (notice that $y$ must be odd, so $\frac{y-1}{2}\in\mathbb{Z}$), but:
$$ (a+b\omega)^3 = a^3+3a^2 b\omega + 3ab^2\omega^2 +b^3 = (a^3+b^3-3ab^2)+3ab(a-b)\omega\tag{3}$$
and $3ab(a-b)=3$ has no integer solutions. The only possibility left is that $w=\sqrt{-3} u^3$ and $\overline{w}= -3v^3$ with $\gcd(u,v)=1$. This happens for $(x,y)=(6,9)$.


text:
Q: Scala apply cannot return Option I recently tried using apply like a factory function:
class X() {
    def apply() : Option[X] = if (condition) Some(new X()) else None
}

val x : Option[X] = X() // <- this does not work; type is mismatched

For some reason apply always returns X. Would I need to create a Factory method?

A: First, you need to define apply in the companion object. Then, you need to specify specifically new X() in order to the compiler to know to use the original apply method, instead of trying to create X recursively.
case class X()

object X {
  def apply(): Option[X] = {
    if (Random.nextBoolean()) Some(new X()) else None
  }
}

Code run at Scastie.


text:
Q: openGL and vector I am using openGL and am currently passing it a vertex array.
It is run successfully when I pass OpenGL a vertex array with an array like
    GLfloat vertices[] = {
    0.500000000f, 0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, -0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, 0.500000000f, -0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f};

The problem is that when I passing it with a vector instead of the array like
    std::vector<GLfloat> vertices = {
    0.500000000f, 0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, -0.500000000f, 0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f,
    0.500000000f, 0.500000000f, -0.500000000f, 1.00000000f, 0.000000000f, 0.000000000f};

then I can't see the triangle in my window.
My code is almost like this
    https://learnopengl.com/code_viewer.php?code=getting-started/coordinate_systems_with_depth
And I changed this line
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

into
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices[0], GL_STATIC_DRAW);

And I changed these lines
    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

into
    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // NormalVector attribute
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(3);

because I need the normal vector information to do something else.
Does anyone know how to use std::vector correctly?
Thanks.

A: If you are using a vector, you need to use vertices.size() * sizeof(GLfloat) instead of sizeof(vertices). The sizeof operator will give you the number of bytes of memory the vector occupies on the stack, not the size of the dynamically allocated array it contains.


text:
Q: Fragment Layout keeps jumping up & down when main activity thread active A very strange problem. I've created a main layout with a fixed toolbar and inserted a fragment placeholder right under it. The layout holds together and works perfectly, complete with screen rotation, soft-keyboard resizing, input, etc.

The main layout structure:
<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"...

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"...

        <include layout="@layout/global_header"/>

        <fragment
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

The code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    if (savedInstanceState != null) {
        ...
    } else {
        Fragment newFragment = new fragment_code();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragment_frame, newFragment).commit();
    }

    final TextView g_header_date = (TextView) findViewById(R.id.global_header_date);
    final TextView g_header_time = (TextView) findViewById(R.id.global_header_time);

    Thread headerClock = new Thread() {
        SimpleDateFormat header_date = new SimpleDateFormat("EEE, dd MMM yyyy");
        SimpleDateFormat header_time = new SimpleDateFormat("hh:mm aa");

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Date dt = new Date();
                            g_header_date.setText("Date:  " + header_date.format(dt));
                            g_header_time.setText("Time:  " + (header_time.format(dt)).replace(".", ""));
                        }
                    });
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                // ...
            }
        }
    };

    //headerClock.start();

}

public static class fragment_code extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_layout, container, false);
    }

    @Override
    public void onClick(View v) {

    }
}

But if I uncomment the headerClock.start(), the fragment (pink area) keeps jumping up and down to the tick of the timer.
The toolbar is part of the main layout, but shares a vertical linear layout with the fragment so that they will fill the screen.
Might anyone have any idea?
EDIT: Opening and closing the soft-keyboard stops the jumping.

A: hi @iSofia the issue might be that you set wrap_content has height to toolbar and fragment is placed below it. So when ever time changes the height of the toolbar should be varying by a small margin to accompany varied height of numbers and so fragment is pushed up and down.
The Possible solution is to set a fixed height to your Global Header/Tool bar so that it don't changes its height for every time change.
Hope it helps you.


text:
Q: Error: Type mismatch: inferred type is Activity? but Activity was expected - Flutter When starting the application I get the following errors in the console:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
lib\main.dart:1
e: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\flutter_app_restart-1.0.0\android\src\main\kotlin\com\example\flutter_app_restart\FlutterRestartPlugin.kt: (55, 18): Type mismatch: inferred type is Activity? but Activity was expected

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_app_restart:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 42s

How can I solve it? Thank you in advance for the help.

A: Goto the FlutterRestartPlugin.kt file and replace all the Activity with Activity? except package name and comment.

A: This clearly seems to be an issue in the flutter_app_restart package that you are using. Maybe check the package's issue page for a solution here.
Also, that package seems to be a very new pakcage with no real documentation. If it is pragmatic restart of the app you are seeking, you are better off using something like flutter_phoenix package. You can find it here.


text:
Q: timestamp(int) to date(string) in php This my code to generate current date.
$now= Time();
$dt=date("d", strtotime($now));
echo $dt;

It outputs 01 as d-m-Y outputs 01-01-1970 instead of current date.
$dt is string and $now is integer type. What should I do to get correct date and get it as integer type.

A: You don't need to convert time() to strtotime(). strtotime() accepts date as string. time() will return the current time in integer only.
Try with
$date = date('d', time());

A: You can try this if you want to get current date
$dt=date("d-m-Y", strtotime('today')); //dd-mm-yyyy
echo $dt;

OR
$current_date_in_int = Time();
$current_date_in_string = date('d-m-Y', $current_date_in_int); //dd-mm-yyyy
echo $current_date_in_string;


text:
Q: How to parameterize write_disposition on a BigQueryOperator? I'm a trying to adapt a current pipeline on jenkins to be orchestrated by airflow.
One of our needs, is to be able to reprocess historical data, over a loop of dates, by a manual trigger.
Assuming I just added a new stage on my pipe/dag, and I would like to execute it for the past n days, not changing already created tables, I could just set all BigQueryOperators to work on write_disposition: 'WRITE_EMPTY'
I understand that if write_disposition was a templatable field, it would be just simple as that:
BigQueryOperator(
            task_id="table_x",
            bql='sql_folder/my_query.sql',
            destination_dataset_table="project_id.dataset_id.my_table_{{ dag_run.conf["date_suffix"] }}",
            write_disposition='{{ dag_run.conf["write_disposition"] }}',
            params={
                 'event_date': "{{ dag_run.conf["event_date"] }}"
            }
        )

Calling the dag on a loop of dates:
airflow trigger_dag 'example_dag_conf' -r 'run_id' --conf '{"date_suffix":"20191213", "event_date":"2019-12-13", "write_disposition": ""}'

But it is not.
Is there any workaround on that? Or a different approach?

A: You could just create a CustomBigQueryOperator that inherits from BigQueryOperator for your use case.
Example:
class CustomBigQueryOperator(BigQueryOperator):
    template_fields = ('sql', 'destination_dataset_table', 'labels', 'write_disposition')

and use that in your DAG.


text:
Q: Конструкция PHP Есть такой массив шаблонов отправки email:
<?
    $mail_templates = array(
    'register' => array(
    'email' => strtolower($options['Login']),
    'subject' => ...
    )
    );
    ?>

И функция:
function MailTemplate($name, $options) {
     return $mail_templates[$name];
    }

А вызов такой:
$options_mail = array('Login' => 'Your Login is');
MailTemplate('register', $options_mail);

Хочу чтобы в массив $mail_templates подставилось переданное значение Login и был возвращен новый массив с набором полей для отправки письма
A: Вопрос, насколько я понял, такой: как передать в функцию глобальную переменную и наоборот. Вроде как всегда было так(в теле функции):
global $mail_templates


text:
Q: Android: Detecting application backgrounding I have an application that has many screens. Is it possible to detect if the screen NOT belonging to the application (not defined in my android manifest) comes into visibility?

A: onPause() will be called when an Activity loses focus (to any screen, be it your own or someone elses). When your user launches another activity from your app, you can set a flag when they do so and check for it in onPause(). If the flag isn't there, you can assume another app has gained focus.

A: If it's something like go back to login screen, try to read about android:finishOnTaskLaunch
http://developer.android.com/guide/topics/manifest/activity-element.html#finish
It solved my similiar problem ;-)


text:
Q: Value of Covariance term too high : multiple attempts to solve it I have a first array 5x1 Bias_sp_fid and a second one 5x1 Bias_ph_fid (fid for fiducial). I am working in astrophysics
context on an observable called 'O' and defined by the ratio Bias_sp on Bias_ph (which are assimilated to random variables in the following).
$O = \dfrac{Bias_{sp}}{Bias_{ph}}$
To compute errors on this new observable 'O' that I assimilate to f(x,y)=O(Bias_sp,Bias_ph), I am doing a Taylor expansion up to second derivative and express the general formula for Variance on this ratio :
$$
\begin{equation}
\begin{aligned}
f(x, y) &=f(a, b)+f_{x}(a, b)(x-a)+f_{y}(a, b)(y-b) + \dfrac{f_{x x}(a, b)(x-a)^{2}}{2} \\
&+f_{x y}(a, b)(x-a)(y-b)+\dfrac{f_{y y}(a, b)(y-b)^{2}}{2}
\end{aligned}
\end{equation}
$$
with convention :
$$
\begin{equation}
\begin{aligned}
f_{x} &=\frac{\partial f}{\partial x} \\
f_{y} &=\frac{\partial f}{\partial y} \\
f_{x y} &=\frac{\partial^{2} f}{\partial x \partial y} \\
f_{y x} &=f_{x y} \\
f_{x x} &=\frac{\partial^{2} f}{\partial^{2} x} \\
f_{y y} &=\frac{\partial^{2} f}{\partial^{2} y}
\end{aligned}
\end{equation}
$$
Then, by applying the generale formula of Variance :
General formula :
By taking the random variable $z$ :
$$
z=\sum_{i=1}^{n} a_{i} x_{i}
$$
We get the following Variance for $z$ :
$$
\operatorname{Var}(z)=\sum_{i=1}^{n} a_{i}^{2} \operatorname{Var}\left(x_{i}\right)+2 \sum_{i<j} a_{i} a_{j} \operatorname{cov}\left(x_{i}, x_{j}\right)
$$
Application in my issue : with $x\equiv Bias_{sp}$ and $y\equiv Bias_{ph}$
You can remark easily that $f_{xx}=\dfrac{d^2 O}{d^2\text{Bias$_{sp}$}} = 0$.
Here the final computation for a second order derivative :
$$
\begin{equation}
\begin{aligned}
\operatorname{Var}(f(X, Y)) &=f_{x}(a, b)^{2} \operatorname{Var}(\mathrm{X})\\
&+ f_{y}(a, b)^{2} \operatorname{Var}(\mathrm{Y}) \\
&+\frac{f_{x x}(a, b)^{2}}{4} \operatorname{Var}\left((X-a)^{2}\right) \\
&+\frac{f_{y y}(a, b)^{2}}{4} \operatorname{Var}\left((Y-b)^{2}\right) \\
&+2 f_{x}(a, b) f_{y}(a, b) \operatorname{Cov}((X-a),(Y-b))\\
&+ f_{y}(a, b) f_{yy}(a, b) \operatorname{Cov}((Y),(Y-b)^2)\\
&+ f_{x}(a, b) f_{yy}(a, b) \operatorname{Cov}((X),(Y-b)^2)\\
\end{aligned}
\end{equation}
$$
So now, I try to code the computation of each $\operatorname{Cov}$ term.
I get an anomaly on the term $f_{x}(a, b) f_{yy}(a, b) \operatorname{Cov}((X),(Y-b)^2)$. Indeed, I tried using np.cov function that computes the covariance between 2 1D vectors :
 covar_x_yy = 2*Bias_sp_fid[i]/Bias_ph_fid[i]**4 * np.cov((Bias_sp_fid,(Bias_ph_fid\
               - np.mean(Bias_ph_fid))**2))[0][1]

index $i$ can vary on the dimension of Bias_sp and Bias_ph, i.e from $0$ to $4$ (recall 5x1 vectors).
Here an example of values obtained for all others covariance terms (for $i=4$) :
var_x = 0.0003385243601431576
var_y = 1.7817901190793067e-05
var_yy = 8.528664540893595e-05
cov_x_y = -0.00015529784692005954
cov_x_yy = 0.00021074696618330292
cov_y_yy = -0.0001016068736330265
rho_correlation =  0.9997978601532392

You can remark the higher value for the term cov_x_yy = 0.00021074696618330292 : that is not consistent with the following of my computation, at the level of final results (to summarize, this high value puts the mess).
Finally 2 questions : I don't have values of Bias_sp and Bias_ph, I have only the known values $\sigma_{\text{sp}}$ and $\sigma_{\text{ph}}$ that come from a complex code.

*

*Is there a way to make appear $\sigma_{sp}$ or $\sigma_{ph}$ in the expression of covariance term cov_x_yy or in another covariance terms.

As you can see, for the moment, I use the fiducial Bias_sp_fid and Bias_ph_fid as random values but I think this is not correct : that's why I would like to insert $\sigma_{sp}$ and $\sigma_{ph}$ in my calculation since they represent characteristics (moment 2) of random variables Bias_sp and Bias_ph.

*Do you think the covariance term used cov_x_yy is correct, I mean this term :
covar_x_yy = 2*Bias_sp_fid[i]/Bias_ph_fid[i]**4 * np.cov((Bias_sp_fid,(Bias_ph_fid\
                - np.mean(Bias_ph_fid))**2))[0][1]

Are there others alternativs to compute this covariance term if my expression is not correct ?
Any help is welcome.


text:
Q: sorting by class color in angular2 I'm tryin to sort a table depending on the color of a radio button (element.IsOnline). I'm tryin to sort by date last seen but, even though the format seems to be ok, doesn't sort. That's why I'm trying to do it bu green or red, but no idea how can i do it.
How can I do it?
my .html

              <ng-container matColumnDef="online">

                  radio_button_checked
                  radio_button_checked

              </ng-container>

 <ng-container matColumnDef="deviceName">
                 Device Id
                 {{element.deviceName}}
              </ng-container>

 <ng-container matColumnDef="lastSeen">
                 Last seen
                 {{element.telemetryUtc | date: 'medium'}}
              </ng-container>

my .ts
import { Component, OnInit, OnDestroy, ViewEncapsulation, ViewChild } from "@angular/core";

import { MatSort } from '@angular/material/sort';

@Component({
  selector: "app-provisioned-list",
  templateUrl: "./provisioned-list.component.html",
  styleUrls: ["./provisioned-list.component.scss"],
  encapsulation: ViewEncapsulation.None,
  animations: fuseAnimations
})
export class ProvisionedListComponent implements OnInit, OnDestroy {
  deviceList: DeviceModel[];
  displayedColumns: string[] = ["checkbox", "online", "deviceName", "tags", "actualVersion", "status", "runningApps", "appVersion", "lastSeen"];

 @ViewChild(MatSort) sort: MatSort;
 devices: any;

private getDeviceList() {
    this.provisionedService.getProvisionedDevicesList().then(response => {
      this.deviceErrorMessage = null;
      this.dataSource.data = response;

this.dataSource.data.map(device => {
        this.provisionedService.getIsDeviceAlive(device._id).then(response => device.isOnline = response);

  }


text:
Q: Found a Customizer setting that did not have a sanitization callback function error on theme-check plugin Getting the error on my WordPress theme in theme-check plugin.
"Found a Customizer setting that did not have a sanitization callback function. Every call to the add_setting() method needs to have a sanitization callback function passed"
I know what does it mean but can't figure out the location of the add_setting() function. In fact I don't have any as far as I can see.
Redux had an issue, the latest version should resolve it.
I'm using underscore as boilerplate.
Does any know how to fix this?
Thanks in advance


text:
Q: SQL Server Service Broker POISON_MESSAGE_HANDLING(STATUS = ON) We are hosting one of our solutions which was originally built on SQL Server 2008 R2 and this instance is hosted on a SQL Server 2008 instance (not R2). The database created fine but for some reason the service broker queues were created with:
POISON_MESSAGE_HANDLING(STATUS = OFF)

I have tried setting this to on but with no luck, we have always declared the queue like this:
CREATE QUEUE QueueName WITH STATUS=ON, ACTIVATION
(STATUS = ON, MAX_QUEUE_READERS = 1,
PROCEDURE_NAME = QueueProcedureName,   EXECUTE AS OWNER);

Is there a way to create the queue as about with the defaults of R2?
EDIT - More Info:
This is the error message which makes no sense as works fine on 2008 R2.
GO
ALTER QUEUE [Store].[UpdateStoredPublishingSegmentUsersSendQueue]
    WITH POISON_MESSAGE_HANDLING(STATUS = ON);
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'POISON_MESSAGE_HANDLING'.

A: This is an issue with the version of sql server. The POISON-MESSAGE_HANDLING is not supported in version less than 2008 R2. Hope this helps!

A: DISCLAIMER: I haven't tried the following commands, as I am running on 2005 which doesn't support the POISON_MESSAGE_HANDLING option.
Have you tried the ALTER QUEUE command after executing the CREATE?
ALTER QUEUE <queue name> WITH
    POISON_MESSAGE_HANDLING ( STATUS = ON )

In alternative try modifying your CREATE command like this:
CREATE QUEUE <queue name> WITH
    STATUS=ON,
    ACTIVATION (
        STATUS = ON,
        MAX_QUEUE_READERS = 1,
        PROCEDURE_NAME = <activated sproc name>,
        EXECUTE AS OWNER
    ),
    POISON_MESSAGE_HANDLING ( STATUS = ON );


text:
Q: SSJS updateDE returns null According to the documentation updateDE should return the number of rows modified
<script runat="server">
var rows = Platform.Function.UpdateDE("CustomerData",["Company","Country","Region"],["exampleCompany","USA","West"]);

However it seems to always return null? However checking in the DE the field has been updated.

A: I think you miss something in documentation. link for reference
Note: UpdateDE : It don't returns value.
As mentioned in documentation :

UpdateDE
  Updates an existing row in a data extension for the specified number of columns used to build the where clause listed in name value pairs followed by a list of columns to be updated in name value pairs.Returns no value.Use this function with email messages at send time only.
Syntax
UpdateDE(1, 2, 3, 4, 5, 6)

Function Properties

*

*string
  Required
  Name of data extension from which to update the specified row

*numeric
  Required
  Number of columns used to build WHERE clause

*string
  Required
  Column name to build WHERE clause

*string
  Required
  Value used to build WHERE clause

*string
  Required
  Column name to build INSERT clause

*string
  Required
  Value used to build INSERT clause

  Usage
UpdateDE('SendDE',1,'_SubscriberKey',_SubscriberKey,'DateSent',NOW())

A: I know this topic is old but for the record:
@Kumar Akhil
Your answer is based off the AMPScript function not the SSJS as asked by M4rcster.
SSJS is suppose to return the number of rows modified as per SSJS documentation here

Updates existing information into a data extension as indicated by the
  array containing the listed column name and value pairs. You can
  include multiple column name and value parts in a single call. You can
  use this method in sendable contexts, such as email messages. This
  call returns the number of rows modified.

However, as the comment by Christopher states, this seems not to work. Either the documentation is wrong OR the method is not working as intended.


text:
Q: Place imageview to center I want to place an arrow to my listview.
I am trying but,I didn't do it.Here is my result:

Expected result:

This is a lisview.And this is my source code of items:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:paddingBottom="4dp"
              android:paddingTop="4dp"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <ImageView
            android:id="@+id/image"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:src="@drawable/twitter"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:paddingLeft="4dp"
        android:paddingRight="4dp" >

        <TextView
            android:id="@+id/tweet"
            style="@android:style/TextAppearance.Medium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#0A0A14"
            android:layout_marginLeft="8dp"
            android:textSize="15sp"
            android:fontFamily="sans-serif-condensed"
            />

        <TextView
            android:id="@+id/handle"
            style="@android:style/TextAppearance.Small"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form"
            android:textColor="#474747"
            android:layout_marginLeft="8dp"
            android:textSize="10sp"
            android:layout_marginTop="4dp"/>

            <ImageView
                android:id="@+id/image1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_weight="1"
                android:src="@drawable/anchor" />

    </LinearLayout>
</LinearLayout>

How can I place the arrow to center ? And  I have one more question.Why arrow looking big and blurry in above image ?

A: The arrow should be in the outer LinearLayout. You put it in the vertical LinearLayout, but is should be part of the horizontal LinearLayout
<ImageView
 android:id="@+id/image1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="right|center_vertical"
 android:src="@drawable/anchor" />


text:
Q: How to set IsHitTestVisible to false when Messagebox shows in main Window I have a requirement that when there is a messageBox shown at top of the mainWindow in WPF the mainWindow hittest should be set to False. and by clicking on the ok of the MessageBox the ishittestVisible should be true automatically. I am pretty new to WPF but I have tried the below code. But unable to figure how do I proceed.
<Grid>
   <Grid.Style>
       <Style>
          <Setter Property="Control.IsHitTestVisible" Value="False"/>
             <Style.Triggers>
                < />
                </Style.Triggers>
            </Style>
        </Grid.Style>
        <local:ShareCtrl x:Name="shareCtrl" Width="700" Height="725" />
    </Grid>

I don't know how to achieve this. Do I set any member value in the viewModel to false in viewmodel when MessageBox pops up. But then how do I set it to True when I click on the Ok button of the Messagebox? Please suggest and help me.
Edit:
In ViewModel I have the following code.
{
...
    else if(ErrorCase)
    {
       string str = "Error Message"
       ShowMessage(str);
       return;
    }
    ...
}
    private void ShowMessage(string str)
    {
        MessageBox.Show(str.ToString());
    }


text:
Q: Does pointwise convergence against a continuous function imply uniform convergence? Let $(f_n)_{n\in\mathbb{N}}$ be a sequence of functions with $f_n:\mathbb{R}\rightarrow[0,1]$ for all $n\in\mathbb{N}$ and $f:\mathbb{R}\rightarrow[0,1]$ continuous such that $\lim_{n\rightarrow\infty}f_n(x)=f(x)$ for all $x\in\mathbb{R}$.
Is it now possible to show that $f_n$ converges uniformly to $f$?

A: That's not necessary true, standard example is $f_n(x) = x^n$ for $x\in[0,1)$ and $f_n(x) = 0$ otherwise. They converge point-wise to $f\equiv 0$ but not uniformly. What you have instead is Dini's theorem:

If $(f_n)$ are continuous functions, and they converge to a continuous function $f$ point-wise and monotonically on a compact set, then they converge uniformly to that function.

A: Your example,
$$
f_n(x) = \begin{cases}
 e^{1-1/({1-((n+1) x-1)^2})} & 0<x<\frac{2}{n+1} \\
 0 & \text{otherwise,}
\end{cases}
$$
behaves something like so:

I think it's crystal clear that this is a continuous (even differentiable, I think) sequence of functions that converges pointwise to zero. The convergence clearly can't be uniform, since there's always a point where the value of $f_n$ is $1$.
The example I had in mind looks something like this:

Note that the graph consists of just straight line segments, so it's quite simple to write down a piecewise formula for this.  In fact:
$$
f_n(x) = \begin{cases}
 (n+1) x & 0<x<\frac{1}{n+1} \\
 2-(n+1) x & \frac{1}{n+1}<x<\frac{2}{n+1} \\
 0 & \text{otherwise}.
\end{cases}
$$
I emphasize, though, that (in my approach, at least) the picture comes first.


text:
Q: Returning derived class as base generic class I'm writing unity scripts on C#. I've got my base class:
BaseMonoBehavior<T> : MonoBehaviour where T : BasePresenter

Some scripts extend this class, f.e.:
MyMonoBehaviour : BaseMonoBehaviour<MyPresenter>
// MyPresenter extends BasePresenter

Then I have a type class with method, which adds this scripts as components to GameObject according to it's value:
void addComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script = gameObject.AddComponent<MyMonoBehaviour>();
    }
}

It's okay, but what can I do, if I want to return created script as base class? I want but can't write something like this:
BaseMonoBehaviour addComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script = gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

So, my question is simple - how can I do this? I want to use some methods of base class in the method, which calls addComponentTo...
P.S. Afterwards I'd like to get MyMonoBehaviour as BaseMonoBehaviour from GameObject, if it's possible, but it's yet another question.

A: Since BaseMonoBehaviour is generic on a presenter class, you could make AddComponentTo generic as well:
BaseMonoBehaviour<TP> AddComponentTo(GameObject gameObject) where TP : BasePresenter {
    if (myType == TYPE_A) {
        var script gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

Then the caller would be able to call it as follows:
var component = AddComponentTo<MyPresenter>(gObj);

This requires all generic instances returned by AddComponentTo to be generic on the same type that you can specify at invocation point.
Note: If AddComponentTo creates generic instances that are generic on the same presenter, you could even make it non-generic, like this:
BaseMonoBehaviour<MyPresenter> AddComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

and call it like this:
var component = AddComponentTo(gObj);


text:
Q: Phonegap + DB storage In my app i need to import Facebook contacts. What is the best practice ro store contacts information?
I have two options:

*

*Local storage

*External database (mysql for example)

Thank you!

A: I will suggest this SQLite wrapper
It's use is very simple. Similar use like web sql
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});
  // ...
}

Example:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});

  db.transaction(function(tx) {
    tx.executeSql('DROP TABLE IF EXISTS test_table');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');

    // demonstrate PRAGMA:
    db.executeSql("pragma table_info (test_table);", [], function(res) {
      console.log("PRAGMA res: " + JSON.stringify(res));
    });

    tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
      console.log("insertId: " + res.insertId + " -- probably 1");
      console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");

      db.transaction(function(tx) {
        tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
          console.log("res.rows.length: " + res.rows.length + " -- should be 1");
          console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
        });
      });

    }, function(e) {
      console.log("ERROR: " + e.message);
    });
  });
}

See more at plugin documentation.


text:
Q: Fixed html form input value that cannot be deleted How can I make my input value permanent? I mean user can delete/change it.
<!DOCTYPE>

Mobile Number(Required)
<input type ="integer" name="contact" id ="contact" value="+63" maxlength="13"/>

please help thanks a lot

A: you can use javascript:
SEE FIDDLE DEMO
 $('input.number').keyup(function(){
        if (
            ($(this).val().length > 0) && ($(this).val().substr(0,3) != '+63')
            || ($(this).val() == '')
            ){
            $(this).val('+63');
        }
    });

html:
Mobile Number(Required)
<input type ="integer" class="number" name="contact" id ="contact" value="+63" maxlength="13"/>


text:
Q: Finding possible prefix palindromes We are given a string S of length N. We have to calculate number of prefixes which can be rearranged into palindromes. E.g: Consider string "abba"- "a", "abb" and "abba" are the prefixes which can be rearranged into palindromes.
My approach:
I tried to use XOR for solving this problem. For example a string containing even number of characters can be made palindrome if the xor of all characters in the string is 0.In case of strings having odd characters, the xor of all characters should be between 97 and 122, i.e a single character.
Here's a part of my code-
    string s;
    cin>>s;
    int a,n;
    int ans=1;
    n= s.length();
    a=s[0];
    for (int i=1;i<n;i++)
        {
            a=a^(s[i]);
            if (i%2)
            {
                if (a==0)
                {
                    ans++;
                }
            }
            else
            {
                if ((a>=97)&&(a<=122))
                {
                    ans++;
                }
            }
        }
    cout<< ans<< "\n";

I tried to run and it runs successfully for some test cases but fails for others. Any idea of what's wrong in this approach?

A: Better solution, based on the comments from OP:
#include <string>
#include <iostream>
#include <cctype>

int main() {
    std::string input;
    std::cin >> input;

    unsigned char_xor   = input[ 0 ];
    unsigned pal        = 1; // number of palindromes (initialized to 1,
                             // since a singular letter is always a
                             // palindrome)

    for ( std::string::size_type i = 0; input.size() >= i; ++i ) {
        char_xor ^= input[ i + 1 ];

        // check whether length of current prefix is:
        //   - odd: check whether it is a lowercase character
        //   - even: check whether it is equal to 0
        if ( ( i % 2 && std::islower( char_xor ) ) ||
             ( !( i % 2 ) && !char_xor ) ) {
            ++pal;
        }
    }

    std::cout << "Amount of possible palindromes: " << pal << std::endl;

    return 0;
}

The following assumption is incorrect (see comments below).
As having understood from

a string containing even number of characters can be made palindrome if the xor of all characters in the string is 0.In case of strings having odd characters, the xor of all characters should be between 97 and 122

you're making a mistake in checking whether the computed XOR is equal to 0/between 97 and 122 on each iteration (after XORing each character), whereas you should be checking it after iterating over the whole std::string. The following works with your given example of "abba" and, for instance, "aaaadcasdasdaffaaa" (having produced 12):
#include <string>
#include <iostream>
#include <cctype>

bool can_be_palindrome( const std::string& str ) {
    unsigned char_xor = str[ 0 ];

    // compute the xor of all characters
    for ( std::string::size_type i = 1; str.size() != i; ++i ) {
        char_xor ^= str[ i ];
    }

    // determine whether the input string has an even number of characters;
    // if so, return whether char_xor is equal to 0;
    // if not, return whether char_xor is a lowercase letter.
    return !( str.size() % 2 ) ? !char_xor : std::islower( char_xor );
}

int main() {
    std::string input;
    std::cin >> input;

    unsigned pal = 1; // number of palindromes (initialized to 1, since a
                      // singular letter is always a palindrome)

    for ( std::string::size_type i = 2; input.size() >= i; ++i ) {
        // extract a prefix from the range [0; i) and determine whether it
        // can become a palindrome
        if ( can_be_palindrome( input.substr( 0, i ) ) ) {
            ++pal;
        }
    }

    std::cout << "Amount of possible palindromes: " << pal << std::endl;

    return 0;
}


text:
Q: Mingw64 cannot link with glfw because gdi32 functions are missing I'm trying to compile the following program in Main.c:
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

int main()
{
    glfwInit();

    return 0;
}

I compile it with:
gcc -m64 -c -g -I"libs/vulkan/include" -I"libs/GLFW/include"  -std=c11 -MMD -MP -MF "bin/main.o.d" -o bin/main.o src/Main.c

and link it with:
gcc -m64 -o bin/vulkanfirsttest.exe bin/main.o -L"libs/vulkan/lib" -L"libs/GLFW/lib" -L"C:/msys64/mingw64/lib" -lvulkan-1 -lglfw3 -lgdiplus

It compiles successfully but when I try to link it, it spits out the following errors:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0x8e): undefined reference to `__imp_CreateDCW'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xc8): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0x123): undefined reference to `__imp_DeleteDC'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0x263): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0x88b): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0x9db): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xdaa): undefined reference to `__imp_CreateDCW'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xdb9): undefined reference to `__imp_GetDeviceGammaRamp'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xdc2): undefined reference to `__imp_DeleteDC'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xf37): undefined reference to `__imp_CreateDCW'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xf46): undefined reference to `__imp_SetDeviceGammaRamp'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_monitor.c.obj):(.text+0xf4f): undefined reference to `__imp_DeleteDC'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x21a): undefined reference to `__imp_CreateDIBSection'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x253): undefined reference to `__imp_CreateBitmap'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x304): undefined reference to `__imp_DeleteObject'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x397): undefined reference to `__imp_DeleteObject'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x432): undefined reference to `__imp_CreateRectRgn'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(win32_window.c.obj):(.text+0x4ab): undefined reference to `__imp_DeleteObject'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0x16a): undefined reference to `__imp_SwapBuffers'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0x42d): undefined reference to `__imp_ChoosePixelFormat'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0x43b): undefined reference to `__imp_SetPixelFormat'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0xc97): undefined reference to `__imp_DescribePixelFormat'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0xe81): undefined reference to `__imp_DescribePixelFormat'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0xe9b): undefined reference to `__imp_SetPixelFormat'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: libs/GLFW/lib/libglfw3.a(wgl_context.c.obj):(.text+0x1498): undefined reference to `__imp_DescribePixelFormat'

I found a post that had a similar problem, and the answer was to also link gdi32, but there isn't a gdi32 package in mysys2. There is gdiplus (mingw64/mingw-w64-x86_64-libgdiplus 5.6.1-1), but as you can see that doesn't help.


text:
Q: Why need to rebind Crystal Report I have created a Crystal Report. It is working fine. Then I tried to use it in Asp.Net using
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
DisplayGroupTree="False"  />

The first time, it works fine but when I click on the print button, the report disappears and gives an error. When I move my BindReport method out of if(!IsPostBack) then it starts working fine.
Below gives error when print button is clicked:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        BindReport();
    }
}

But this works fine
protected void Page_Load(object sender, EventArgs e)
{
     BindReport();
}

Can someone help me understand what is the reason?

A: Insofar as only the mouse click events of the CrystalReportViewer control can be serialized into ViewState, binding to a report class that can be serialized generates an insoluble problem when reloading pages:
1   If the report binding code is placed in a Not IsPostBack conditional block the mouse click events from ViewState are retained, but the binding of the report does not take place, and an exception is thrown.
2     If the report binding code is placed outside the conditional block, the report is bound correctly, but the contents of ViewState is crushed in the process, and mouse click events are lost.
Nota :     This situation occurs most often when clicks are made in a report to several pages at the CrystalReportViewer control. The report continues then mysteriously back on page 1.
Solution

Put the binding code CrystalReportViewer control in the Init event
Link : http://msdn.microsoft.com/fr-fr/library/ms225455%28v=vs.90%29.aspx


text:
Q: client.get_channel(channelid) returns None I have searched the web several times for this issue, and there seem to be a lot of people having this problem.
However, they all seemed to have fixed it by putting the expression in the on_ready() event.
But I want to use it in a command, where the user passes a channel id, which will be a string, and I made this code:
@client.command()
async def send_message(ctx,channel,*,msg):
    channelid = int(channel)
    channel = client.get_channel(channelid)
    await channel.send(msg)

When I run the code, and execute the command, it says:

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'

Does anyone know how to fix this?

A: You're making it a little complicated for yourself. You can make it much simpler.
In itself, there's not much wrong with the code for now, but it's best to use the tools at our disposal.
To get a channel you can use discord.TextChannel as an argument.
It will look like this:
channel: discord.TextChannel

Here you can use either the ID, the name of the channel or a mention.
The rest of your code looks right to me at first.
Your new code:
@client.command()
async def send_message(ctx, channel: discord.TextChannel, *, msg):
    await channel.send(msg) # send the "msg" to your specified "channel".

A: I think the channel = client.get_channel(channelid) line is not returning a channel class.


text:
Q: Redirect 301 URL using Nginx server how to redirect 301 url
from STRING?page=NBR
to  STRING/NBR/
in NGINX server.

A: Try it. I think that the ideas will help you.
location = STRING {
    if ($arg_page) { return 301 STRING/$arg_page/; }
}

or
location = STRING {
    if ($arg_page) { rewrite STRING STRING/$arg_page/ permanent; }
}

$arg_name - argument name in the request line

Added as example for random STRING:
server {
    if ($arg_page) { return 301 $uri/$arg_page/; }
}

$uri - current URI in request, normalized. The value of $uri may change during request processing, e.g. when doing internal redirects, or when using index files.
return ... As a special case, a redirect URL can be specified as a URI local to this server, in which case the full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives.

Or:
server {
    if ($arg_page) { return 301 $scheme://$server_name$uri/$arg_page/; }
}

$scheme - request scheme, "http" or "https"
$server_name - name of the server which accepted a request
if ($arg_page) - false if the value of a variable is an empty string or "0"


text:
Q: A puzzle about vector space When beginning to study the notion of vector space using the book"linear algebra and its applications" of D.C.Lay,the book give an example of vector space.It says all continuous functions on the interval [a,b] could be a vector space. Shouldn't a element of vector space be a vector?Why a function in the case above?

A: I suppose it depends on your definition of a vector. I assume when you think of a vector you think about something like $(1,2)$ or $(1,\pi,6,3.3)$ and the associated geometric meanings.
Another way to define a vector is a vector is any element of a vector space. Look at the definition of a vector space does it specify that the vectors must be like the form above? No it doesn't and there is no reason why they should be.
For example we can define vector spaces over sets of polynomials where the vectors are polynomials and similarly we can define vector spaces of matrices.
You must get used to thinking about vectors in this new way and appreciate it.
It is often more convenient and meaningful to think about vectors this way as it becomes easier to work with. For example if we considered only the geometrical interpretation then we would not really be able to interpret any vectors above $3$ dimensions.

A: In linear algebra, an important concept is abstracting concepts of its fundamentals. Typically, you may have thought of a vector to have specific magnitude and length and fit some sort of pre-conceived definition. In the study of linear algebra, this notion does not typically exist. We can abstract this idea and apply it to many objects, so long as it fits with our well-defined rules for what is a "vector space" and a "vector" (in the most basic terms, a set of mathematical objects that abide by certain properties we have decided on).
A matrix is a vector, a number ($5, 2.1, 4$) is a vector. In fact, the real numbers $\mathbb{R}$ are a vector space. The well-defined rules (axioms) can be found here:
https://en.wikipedia.org/wiki/Vector_space

A: You can also think of a (continuous) real-valued function on $[a,b]$ as an 'uncountable-tuple' where each 'component' is indexed by a real number in $[a,b]$.
Or conversely, you can think of a vector in $\mathbb{R}^n$ as a function from $\{1,2,\dots,n\}$ to $\mathbb{R}$, where $f(i)=$ the $i$-th component of the vector.


text:
Q: needs guidance on distributing data on multiple GPUs I'm currently developing a machine learning toolkit for GPU clusters.
I tested logistic regression classifier on multiple GPUs.
I'm using a Master-Worker approach , where a master CPU creates several POSIX threads and matrices are divided among GPUs.
But the problem I have is how to store large matrices which can't be stored on a single machine. Are there any libraries or approaches to share data among nodes?

A: I'm not sure how big are your matrices but you should check CUDA 4.0 that was released a couple of weeks ago. One of the main features is shared memory across multiple CUDA devices/GPUs


text:
Q: How to prepare a Mac installer for my java swing application Can anybody give me suggestions about preparing a custom Mac Installer for a Java swing application. I have tried Xcode but of no use. Any suggestions would be really helpful.
Thanks in advance...

A: Take a look at http://izpack.org.

IzPack-generated installers only require a Java virtual machine to run. It is fully cross-platform and generates a single installer. As such, it is an alternative to native solutions like as platform-specific installers and package managers.

Or for a more Mac-specific option, see this 10-step tutorial:

*

*http://www.centerkey.com/mac/java (Updated for Mac OS X 10.6 — Snow Leopard)

A: Do you actually need an installer? Unless you need to put files in very specific locations and need admin privileges for that, installers are uncommon on the Mac. Typically, you'd use a disk image with a self-contained application bundle. See my answer to this question. That answer also mentions how to create a standard OS X installer.


text:
Q: Ubuntu 64 bit Machinarium: error while loading shared libraries: libgtk-x11-2.0.so.0 I just downloaded Ubuntu 13.10 final beta 64 bit and every program that I use work flawlessly with the exception of "Machinarium" a very cool flash game. The game doesn't have a .deb package and I used to be able to play it before. I tried installing lib32 and ia32 and it says it is installed to the last version or if I try lib32-dev it says that is no longer available. Here is my ldd command result:
fz@Unknown:~/Games/Machinarium$ ldd Machinarium
    linux-gate.so.1 =>  (0xf77c8000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xf76c0000)
    libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0xf76a5000)
    libX11.so.6 => /usr/lib/i386-linux-gnu/libX11.so.6 (0xf756f000)
    libXext.so.6 => /usr/lib/i386-linux-gnu/libXext.so.6 (0xf755c000)
    libXt.so.6 => /usr/lib/i386-linux-gnu/libXt.so.6 (0xf7500000)
    libfreetype.so.6 => /usr/lib/i386-linux-gnu/libfreetype.so.6 (0xf7461000)
    libfontconfig.so.1 => /usr/lib/i386-linux-gnu/libfontconfig.so.1 (0xf7427000)
    libgtk-x11-2.0.so.0 => not found
    libgdk-x11-2.0.so.0 => not found
    libatk-1.0.so.0 => not found
    libgdk_pixbuf-2.0.so.0 => not found
    libpangocairo-1.0.so.0 => not found
    libpango-1.0.so.0 => not found
    libcairo.so.2 => not found
    libgobject-2.0.so.0 => /usr/lib/i386-linux-gnu/libgobject-2.0.so.0 (0xf73d3000)
    libgmodule-2.0.so.0 => /usr/lib/i386-linux-gnu/libgmodule-2.0.so.0 (0xf73ce000)
    libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0xf73c9000)
    libglib-2.0.so.0 => /lib/i386-linux-gnu/libglib-2.0.so.0 (0xf72c4000)
    libnss3.so => not found
    libsmime3.so => not found
    libssl3.so => not found
    libplds4.so => not found
    libplc4.so => not found
    libnspr4.so => not found
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xf7280000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xf7263000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf70b0000)
    libXrender.so.1 => /usr/lib/i386-linux-gnu/libXrender.so.1 (0xf70a4000)
    /lib/ld-linux.so.2 (0xf77c9000)
    libxcb.so.1 => /usr/lib/i386-linux-gnu/libxcb.so.1 (0xf7083000)
    libSM.so.6 => /usr/lib/i386-linux-gnu/libSM.so.6 (0xf707a000)
    libICE.so.6 => /usr/lib/i386-linux-gnu/libICE.so.6 (0xf7060000)
    libz.so.1 => /lib/i386-linux-gnu/libz.so.1 (0xf7046000)
    libexpat.so.1 => /lib/i386-linux-gnu/libexpat.so.1 (0xf701c000)
    libffi.so.6 => /usr/lib/i386-linux-gnu/libffi.so.6 (0xf7015000)
    libpcre.so.3 => /lib/i386-linux-gnu/libpcre.so.3 (0xf6fd4000)
    libXau.so.6 => /usr/lib/i386-linux-gnu/libXau.so.6 (0xf6fd0000)
    libXdmcp.so.6 => /usr/lib/i386-linux-gnu/libXdmcp.so.6 (0xf6fc9000)
    libuuid.so.1 => /lib/i386-linux-gnu/libuuid.so.1 (0xf6fc2000)

A: apparently you have to install the libgtk2.0-0:i386 package.
sudo apt-get install libgtk2.0-0:i386

A: There are 2 options to run Machinarium on Ubuntu 13.10 64bits.
Deb Package
If we have the .deb package (and yes! it is a 32bit package).
You must to install it with Ubuntu Software Center (not using dpkg -i), so simply double click the file.
To remove the game
sudo dpkg -r machinarium

TAR.GZ version
If you have the tar.gz version.
You need to install all those libraries.
sudo apt-get install libgtk2.0-0:i386 libnss3:i386 libcurl3-gnutls:i386 libidn11:i386 libpango1.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 librtmp0:i386 libxft2:i386

Run it on STEAM
In both cases if you want to run it with STEAM as a NO Steam game, you must to install also this last library.
sudo apt-get install libxtst6:i386

A: I have the same problem here. This is not exactly a solution, but I'll try to add some information.
I tried @AdamOutler solution but after installing libgtk2.0-0:i386 another dependencies were need which I solved installing libnss3:i386 and gtk2-engines-murrine:i386. The problem was when the next step required a package called unity-gtk2-module:i386 that depends on unity-gtk-module-common:i386 which doesn't exists anymore.
I abandoned this approach and found that I could install the game directly from the Software Center (as I bought it from Humble Bundle). It worked like a charm! The crazy part is that there's no apparent difference between installations (.TGZ vs .DEB) - files inside folder looks to be the same (used file and md5sum commands to check).
Here is the list of dependencies from the installed package: libatk1.0-0 (>= 1.12.4), libc6 (>= 2.4), libcairo2 (>= 1.2.4), libfontconfig1 (>= 2.8.0), libfreetype6 (>= 2.2.1), libgcc1 (>= 1:4.1.1), libgdk-pixbuf2.0-0 (>= 2.22.0), libglib2.0-0 (>= 2.12.0), libgtk2.0-0 (>= 2.24.0), libnspr4 (>= 1.8.0.10), libnss3 (>= 3.12.0~1.9b1), libpango1.0-0 (>= 1.14.0), libstdc++6 (>= 4.1.1), libx11-6, libxext6, libxrender1, libxt6, libcurl3-gnutls
One last thing is that I'd suggest to try to create a launcher for the game because I still have no success starting the game from bash.


text:
Q: Get static instance name in Java via reflection during construction I am not sure if this is the right way to reduce number of characters written, but still.
Right now I have the following piece of code that maps to two settings sources: database and .properties file:
import lombok.*;

@Getter
@ToString
@EqualsAndHashCode
public final class Setting<T> {
    private String id;
    private Class<T> clazz;

    private Setting(final String id, final Class<T> clazz) {
        this.id = id;
        this.clazz = clazz;
    }

    public static final Setting TOKEN_LENGTH = new Setting("TOKEN_LENGTH", Integer.class);
    // lots of other settings
}

The thing is, I want to avoid explicit passing of the first argument to the constructor, e.g. like variable named TOKEN_LENGTH has id TOKEN_LENGTH passed to it. In other way, when these static final variables are instantiated, their first argument is always the name of the said variable.
In this case there are only ~60 instances of this class are created and this happens only at application startup, so any overhead caused by reflection is acceptable.
I wonder if there any way to rewrite the constructor to look something like
    private Setting(final Class<T> clazz) {
        this.id = /* some crazy reflection magic */
        this.clazz = clazz;
    }

So, the question is:
➥ By chance, is there any way to get name of static variable for which the object is being instantiated and assigned to?
UPD:
There is a solution that first instantiates all variables and then sequentally sets id field. I'm still looking for the way to do it "atomically" in constructor.

A: It's relatively easy to do so, the problem is knowing which field to use. You can mark it with an annotation which would make it easier. Something like
public String getFieldName(){
    Field[] fields = getClass().getDeclaredFields();
    for(Field f: fields){
        if(f.isAnnotationPresent(YourAnnotation.class)){
             return f.getName();
        }
    }
    // do whatever if a valid field wasn't found
}

If you don't want an annotation then you'll have to find some other way to identify it, such as the only static field. But that's very bad practice and using an annotation is better.


text:
Q: Is it always possible to extend a closed (1, 1)-form on a divisor to a closed (1, 1)-form on a tubular neighbourhood? Let $X$ be a compact Kahler manifold, let $D$ be a smooth divisor in $X$, and let $U$ be a tubular neighbourhood of $D$ in $X$. Suppose that $D$ is Fano. Is it possible to extend every closed (1, 1)-form on $D$ to a closed (1, 1)-form on $U$?

A: Yes. For the proof, see e.g. http://arxiv.org/abs/math/0609617
Theorem 4.1. Here a stronger result is actually proven:
Theorem: Let $(M, \omega)$ be a compact Kahler manifold,
and $Z\subset M$ a closed complex submanifold.
Denote by $[\omega]\in H^2(M)$ the Kahler class of $M$.
Consider a Kahler form $\omega_0$ on $Z$ such that
its Kahler class coinsides with the restriction
$[\omega]| Z$. Then there exists a
Kahler form $\omega'$ on $M$ in the same Kahler
class as $\omega$, such that $\omega|
Z=\omega_0$.
An additional cohomological assumption is needed, because we build a global extension, and for an extension to a local neighbourhood you don't need it; the positivity (needed in assumption) is achieved by adding a big multiple of a Kaehler form.


text:
Q: Salesforce <-> Whatsapp integration Currently me and my team are having a demand to create an Whatsapp <-> Salesforce integration for customer service.
For example, when a client sends a message to the company's Whatsapp number, a case will be opened and the agent can reply and view messages through a Lightning Component displayed at the case page.
Is there any links or documentation that instructs how to do such development?
Thanks in advanced!


text:
Q: Webscraping - Python - "Nonetype Object has no attribute text" Im scraping a product page with following script:

The area i try to scrape (Containing the producer, ean ecetera) doesnt seem to be scrapable, unliek price and title. What am i doing wrong?

A: It looks like the product details table you're after is populated by JavaScript after the page loads, so it's not in the HTML retrieved by r = s.get(link). As explained in rayt's answer, this is why you get None returned.
However, the data that the table contains is on the page, inside a <script> tag near the bottom:
<script> window.__NUXT__ = (function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, _, $, aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az, aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM, aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ, a_, a$, ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm, bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz, bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM, bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ, b_, b$, ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm, cn, co, cp, cq, cr, cs, ct, cu, cv, cw, cx, cy, cz, cA, cB, cC, cD, cE, cF, cG, cH, cI, cJ, cK, cL, cM, cN, cO, cP, cQ, cR, cS, cT, cU, cV, cW, cX, cY, cZ, c_, c$, da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm, dn, do0, dp, dq, dr, ds, dt, du, dv, dw, dx, dy, dz, dA, dB, dC, dD, dE, dF, dG, dH, dI, dJ, dK, dL, dM, dN, dO, dP, dQ, dR, dS, dT, dU, dV, dW, dX, dY, dZ, d_, d$, ea, eb, ec, ed, ee, ef, eg, eh, ei, ej, ek, el, em, en, eo, ep, eq, er, es, et, eu, ev, ew, ex, ey, ez, eA, eB, eC, eD, eE, eF, eG, eH, eI, eJ, eK, eL, eM, eN, eO, eP, eQ, eR, eS, eT, eU, eV, eW, eX, eY, eZ, e_, e$, fa, fb, fc, fd, fe, ff, fg, fh, fi, fj, fk, fl, fm, fn, fo, fp, fq, fr, fs, ft, fu, fv, fw, fx, fy, fz, fA, fB, fC, fD, fE, fF, fG, fH, fI, fJ, fK, fL, fM, fN, fO, fP, fQ, fR, fS, fT, fU, fV, fW, fX, fY, fZ, f_, f$, ga, gb, gc, gd, ge, gf, gg, gh, gi, gj, gk, gl, gm, gn, go, gp, gq, gr, gs, gt, gu, gv, gw, gx, gy, gz, gA, gB, gC, gD, gE, gF, gG, gH, gI, gJ, gK, gL, gM, gN, gO, gP, gQ, gR, gS, gT, gU, gV, gW, gX, gY, gZ, g_, g$, ha, hb, hc, hd, he, hf, hg, hh, hi, hj, hk, hl, hm) {
    return {
        layout: cG,
        data: [{}],
        fetch: {},

            ...

                },
                description$: {
                    descriptionHtml: "\u003Cp\u003E\u003Cb\u003EIm System sind folgende komponenten verbaut:\u003C\u002Fb\u003E\u003C\u002Fp\u003E\u003Cul\u003E\u003Cli\u003E\u003Cb\u003EGehäuse:\u003C\u002Fb\u003E Systemtreff Mini Tower Nero ST-401\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EProzessor: \u003C\u002Fb\u003EIntel Core i5-10400F 6 x 2.9 GHz (bei Bedarf bis zu 4.3 GHz Turbotakt durch Intel Turbo-Boost Technik)\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EArbeitsspeicher:\u003C\u002Fb\u003E 16 GB DDR4 2666 MHz \u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EMainboard:\u003C\u002Fb\u003E Gigabyte H510M H, Intel Sockel 1200 (1 x PCIe 4.0\u002F3.0 x16 (x16 mode), 1 x PCIe 3.0 x1, 1 x PS\u002F2 keyboard \u002F PS\u002F2 mouse, 1 x VGA 1 x HDMI,  1 x LAN (RJ45), 2 x USB 3.2, 4 x USB 2.0, 1 x M.2 (Key M), 4xSATA) - max. 64 GB DDR4 - 3200 MHz\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003ENetzwerk:\u003C\u002Fb\u003E 1 x Gigabit LAN Controller(s)\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003ESound:\u003C\u002Fb\u003E Realtek® ALC887 8-Channel High Definition Audio CODEC\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EFestplatte:\u003C\u002Fb\u003E 512GB M.2 SSD SATA III\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EGrafik:\u003C\u002Fb\u003E NVIDIA GeForce GT 730 mit 2048 MB \u002F 2GB RAM \u003Cul\u003E\u003Cli\u003ETechnik: ( GDDR3 \u002F DirectX 11 \u002F PCI Express 2.0 \u002F ) \u003C\u002Fli\u003E \u003Cli\u003EGeeignet für Heimvideos - Blu-ray FULL HD - Videobearbeitung \u002F World of Warcraft, Spore oder Sims3, sowie die Anschlussmöglichkeiten von bis zu 2 Monitore\u003C\u002Fli\u003E\u003C\u002Ful\u003E\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003ENetzteil:\u003C\u002Fb\u003E 400-500Watt Marken Netzteil\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003ELaufwerk:\u003C\u002Fb\u003E Kein Laufwerk verbaut\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003EBetriebssystem:\u003C\u002Fb\u003E Windows 10 Pro\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cbr\u003E\u003C\u002Fli\u003E\u003Cli\u003E\u003Cb\u003ESKU:\u003C\u002Fb\u003E 20192420\u003C\u002Fli\u003E\u003Cli\u003EMarkennamen -  Markenlogos sind registrierte Handelsmarken, deren Nutzung hier nur zur Produktbeschreibung eingesetzt werden - das Eigentumsrecht liegt beim jeweiligen Markeninhaber.\u003C\u002Fli\u003E\u003C\u002Ful\u003E",
                    attributes: {
                        default: [{
                            name: "Hersteller",
                            id: "manufacturer",
                            values: [{
                                text: "SYSTEMTREFF",
                                link: "\u002Fmanufacturer\u002F1428338\u002F",
                                isMasked: a
                            }],
                            isCategoryRelevant: d,
                            isDefaultRelevant: d
                        }, {
                            name: "Betriebssystem",
                            id: "operating_system",
                            values: [{
                                text: "Windows 10 Pro",
                                link: "\u002Fcategory\u002F39251\u002Fref-381=1388287\u002F",
                                isMasked: a
                            }],
                            isCategoryRelevant: d,
                            isDefaultRelevant: a
                        }, {
                            name: cJ,
                            id: cK,
                            values: [{
                                text: cL,
                                link: cM,
                                isMasked: a
                            }],
                            isCategoryRelevant: a,
                            isDefaultRelevant: a
                        }, {

I hope you'll forgive my use of BeautifulSoup in this example, I'm more familiar with it than requests_html, but here's how you might fetch the <script> tag content:
import requests
from bs4 import BeautifulSoup

def get_products(link):
    r = requests.get(link)
    html = r.text
    soup = BeautifulSoup(html, 'html.parser')
    title = soup.find('h1').text.strip()
    price = soup.find('div', {'class':'rd-buybox__price'}).text.strip().replace(' €', '').replace(',', '.')
    descriptiontable = extract_description(soup)
    print(title, price, descriptiontable)

def extract_description(soup):
    product_data = soup.find_all('script')[2] # 3rd script tag
    product_data = str(product_data).partition('return {')[-1]
    product_data = '{' + product_data.split('}(')[0] + '}'
    product_data =  # You'll need to parse this content here to find the bits you need
    return product_data

if __name__ == '__main__':
    link = "https://www.kaufland.de/product/358005366/"
    get_products(link)

A: It seems like the .find method returns None if no match was found. You should test for None first. You could do something like this:
...
def get_products(link):
    ...
    title_tag = r.html.find("h1", first=True)
    if title_tag is None:
        return
    title = title_tag.text
    ...

If you expect .find to actually find something and it doesn't, you should check your logic and selectors. Also, try saving the raw html and reading the output. Web pages sometimes return something different when you are attempting to scrape them.
You can save the output to a file in Python like this:
with open("output.html", "w", encoding="utf-8") as fid:
    fid.write(r.text)

I'm assuming .text attribute/property exists on the Response object, but Requests-HTML documentation does not seem very complete.


text:
Q: A value of type X cannot be used to initialize an entity of type X struct Value {
    struct Array;
    struct Dict;
    struct Primitive;

    Value() {}
    virtual ~Value() {}

    virtual Array * asArray() { assert(false); }
    virtual Dict * asDict() { assert(false); }
    virtual Primitive * asPrimitive() { assert(false); }

    int asInt();
    double asDouble();
    std::string asDate();
    std::string asString();
};

struct Value::Array : public Value {
    std::vector<Value> m_data;

    Array() {}
    ~Array() {}

    Value::Array * asArray() {
        Value::Array * result = this;
        return result;
    }
};

The statement Value::Array * result = this; is giving me this error...
E0144  a value of type "Value::Array *" cannot be used to initialize an entity of type "Value::Array *".

A: The problem can be seen in much simpler code
enum SPELLSTATUS { NEW, FAIL, OK } spellStatus = SPELLSTATUS::NEW;

or
enum SPELLSTATUS { NEW, FAIL, OK } spellStatus = NEW;

E0144   a value of type "SPELLSTATUS" cannot be used to initialize an entity of type "SPELLSTATUS"  NcEdit  D:\Systems\Editor2019\Spell.cpp 30

VS2019.

Compiles and runs just fine.


text:
Q: how many ways are there to arrange $8$ pennies and $5$ nickels in a How can you arrange a line of $8$ pennies and $5$ nickels, so that no $2$ nickels are next to each other (pennies are indistinguishable and nickels are too)?
Answer: I set nickels and pennies next to each other so I get ${9 \choose 5}*8!*5!=609638400$. Is this correct?

A: If you first lay out the $8$ pennies, there are $9$ spaces where the nickels can go ($7$ spaces between adjacent pennies and $2$ spaces at the two ends).  So the answer is simply $9\choose5$.  You would multiply this by $8!5!$ only if the pennies and nickels were all distinguishable.

A: _ N _ N _ N _ N _ N _
assume this is the placement which you are looking for .
The blanks have to be filled by 8 pennies and no blank space should be empty except for the first and the last blank.
the sequence then becomes
_ N p N p N p N p N _
now you are remaining with 4 pennies and 6 potential places where they an come.
Since the pennies and the nickels are indistinguishable internal rearrangements do not count.
Can you take it from here?

A: Imagine a "base" Line of ()N(p)N(p)N(p)N(p)N() and you have have to put the remaining 4 pennies into the six () pots.  This is then what others irritatingly call "stars and bars".
There are four pots in which to put the leftmost of the four pennies.  Call it n where 6 is the left most pot and 1 is the right most pot.  There are n pots to put the second most left penny  and so on.
SO there are $\sum_{n=1}^6\sum_{m=1}^n\sum_{k=1}^m m$ ways to place the pennies.
$\sum_{n=1}^6\sum_{m=1}^n\sum_{k=1}^m k=$
$\sum_{n=1}^6\sum_{m=1}^n \frac{m(m+1)}2=$
$\frac 12 [\sum_{n=1}^6(\sum_{m=1}^nm^2 + \sum_{m=1}^n m)]=$
$\frac 12 [\sum_{n=1}^6(\frac{n(n+1)(2n+1)}{6}+ \frac{n(n+1)}2   ]=$
$\frac 14 [\sum_{n=1}^6(\frac{2n^3 + 3n^2 + n}{3}+ n^2 + n   ]=$
$\frac 14 [\sum_{n=1}^6(\frac{2n^3  }{3}+ 2n^2 + \frac 43 n   ]=$
$\frac 14 [\frac 23\frac{6^2(6+1)^2}4+ 2\frac{6(6+1)(2*6+1)}6 + \frac 43 \frac {6(6+1)}2   ]=$
$\frac 14 [2* 3*7^2+ 2(7)(13) +  4*7   ]=$
$\frac 74 [2* 3*7+ 2*(13) +  4   ]=$
$\frac 74 [72   ]= 7*18  = 126$
====
Which as others point out I could have simply solved by ${9 \choose 5}$... oh, well.


text:
Q: Command to get to the Container Prompt After Entrypoint What command can be added at the bottom of the Dockerfile to get to container prompt after the ENNTRYPOINT? The Dockerfile runs okay. Just that it goes back to the prompt from where it was executed.
 # Pull base image
From ubuntu:18.04
LABEL maintainer="tester@gmail.com"

# Install dependencies
RUN apt-get update -y
RUN apt-get install -y build-essential python3.6 python3.6-dev python3-pip python3.6-venv
RUN apt-get install -y vim
RUN python3.6 -m pip install pip --upgrade
RUN pip3 install pytest pytest-cache
RUN pip3 install pylint
RUN pip3 install requests

# Create working directory
RUN mkdir /testsuite

# Copy project
COPY comments_categories_api  /testsuite/comments_categories_api
COPY comments_posts_api  /testsuite/comments_posts_api/
RUN chmod -R a+rwX testsuite/
# Set working directory

WORKDIR /testsuite
# Set Python version
RUN echo alias python='/usr/bin/python3' >> ~/.bashrc
# RUN echo cd testsuite/ >> ~/.bashrc

# Define ENTRYPOINT
COPY ./docker-entrypoint.sh /testsuite/docker-entrypoint.sh
RUN ["chmod", "+x", "/testsuite/docker-entrypoint.sh"]
ENTRYPOINT ["sh", "/testsuite/docker-entrypoint.sh"]

A: End your docker-entrypoint.sh with "$@". This is an example:
#!/bin/bash

echo Hello

$@

=== UPDATE
Based on your comment, the file should be:
#!/bin/bash

pytest -v

$@

A: After the ENTRYPOINT, definitionally, the container exits.
It sounds like what you're saying is that you want a container that first runs some test, then launches an interactive shell.  You need to make a shell script that does that
#!/bin/sh
pytest -v
sh

and then make that script be the main process of the image.

I have two style comments here, which reading other comments also might matter to you.  You mention trying to run an interactive shell with
docker run -it vip_app:v0.1 /bin/bash

If you declare the process command with CMD, your /bin/bash command replaces CMD and you will get an interactive shell.  If you declare it with ENTRYPOINT, /bin/bash is passed as an argument to the ENTRYPOINT (and probably gets totally ignored).  I tend to prefer CMD to ENTRYPOINT if I don't clearly need both.
You also try to change the default python command using a .bashrc file.  .bashrc doesn't get read in many common cases.  For example, if you
docker run --rm vip_app:v0.1 python myapp.py

the .bashrc will not get read and you will run /usr/bin/python (which is probably Python 2.7).  I just wouldn't install "convenience" things like this in an image at all.