text:
Q: Why sometimes my_arc_mutex.clone() will be freed before finishing using it? I got this error:
   --> src/client.rs:189:22
    |
189 |         let client = client.clone().lock().unwrap();
    |                      ^^^^^^^^^^^^^^                - temporary value is freed at the end of this statement
    |                      |
    |                      creates a temporary which is freed while still in use

on this function that is too big for me to post a minimum reproducible example:
async fn send_and_expect<T: OnEvent<T>>(
        client: Arc<Mutex<Self>>,
        request: rtsp_types::Message<Body>,
        unauthorized_retry: i32,
    ) -> std::result::Result<rtsp_types::Response<Body>, ClientActionError>
    where
        RtspMachine: OnEvent<T>,
        T: From<Response>,
    {
        let expected_cseq = client_parse_cseq(&request)?;
        let mut client = client.lock().unwrap();

If I simply not clone, that is, do let mut client = client.lock().unwrap();, it compiles. But I was wondering why clone() makes this error happen.
I tried to reproduce the problem to post here:
use std::sync::{Arc, Mutex};
fn main() {
    let a = Arc::new(Mutex::new(0));
    a.clone().lock().unwrap();
}

but this compiles ok.
What is wrong? Why would client.clone() sometimes be freed before finishing using it but sometimes not?

A: Unfortunately, your short example is too short, because it never binds the unwrapped MutexGuard. To reproduce the error, we need to add a binding (playground):
use std::sync::{Arc, Mutex};

fn main() {
    let a = Arc::new(Mutex::new(0));
    let _b = a.clone().lock().unwrap();
}

rustc now yells at use righteously:
error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:5:13
  |
5 |     let _b = a.clone().lock().unwrap();
  |              ^^^^^^^^^                - temporary value is freed at the end of this statement
  |              |
  |              creates a temporary which is freed while still in use
6 | }
  | - borrow might be used here, when `_b` is dropped and runs the `Drop` code for type `MutexGuard`
  |
  = note: consider using a `let` binding to create a longer lived value

So why does the borrow checker yell at us? Remember that Mutex::lock(&self) takes a reference to the Mutex. This reference stems from Arc. However, the cloned variant only lives till the end of the statement: there is no binding to a.clone(), and it passes away into oblivion at the semicolon.
The easy fix is to bind a.clone(). Usually, you would reuse the same identifier, as in Rust's Arc example (playground):
use std::sync::{Arc, Mutex};

fn main() {
    let a = Arc::new(Mutex::new(0));
    let a = a.clone();
    let _b = a.lock().unwrap();
}

While this might seem strange in a single main function, it's much more common when moveing values into closures.
"Now hold on", you might say. "This is a shared reference, why can't I just keep using it? There's still a in the same scope!" While this could be true, it's also a trap. If the .clone().lock() line were to compile, then we could create a use-after-free error:
let a = Arc::new(Mutx::new(0));
let b = a.clone().lock().unwrap(); // reference counter increased and decreased by 1
drop(a);                           // reference counter -> 0: value gets freed
*b = 10;                           // whoops!


text:
Q: Modifing text in pl file with swi-prolog I have the following file in prolog, 1111000011110000.pl :
:- multifile firstname/1.
:- multifile surname/1.
:- multifile cardNumber/1.
:- multifile code/1.
:- multifile balance/1.

% firstname("Martin").
firstname([77, 97, 114, 116, 105, 110]).

% surname("Andersson").
surname([65, 110, 100, 101, 114, 115, 115, 111, 110]).

% cardNumber(card-number)
cardNumber(1111000011110000).

% code(code)
code(1337).

% balance(balance)
balance(3230000).

I want to create a predicate that takes an integer-input (for instance 0) and modifies the 1111000011110000.pl file so that the argument of the balance-predicate is changed to 0. For instance, after using the predicate I am supposed to modify the 1111000011110000.pl file to:
:- multifile firstname/1.
:- multifile surname/1.
:- multifile cardNumber/1.
:- multifile code/1.
:- multifile balance/1.

% firstname("Martin").
firstname([77, 97, 114, 116, 105, 110]).

% surname("Andersson").
surname([65, 110, 100, 101, 114, 115, 115, 111, 110]).

% cardNumber(card-number)
cardNumber(1111000011110000).

% code(code)
code(1337).

% balance(balance)
balance(0).

Is this possible in prolog? :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pycharm having issues installing pandas (using python 2.7) I am trying to install pandas on Pycharm but, I'm having issues installing pandas. I have tried using pip install pandas but it's not working, could someone help, please.
Could not fetch URL https://pypi.org/simple/pandas/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pandas/ (Caused by SSLError(SSLError(1, '_ssl.c:499: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version'),)) - skipping


text:
Q: Question about ternary operator within for loop just having a bit of curiosity about why one bit of code with if /else statement within for loop works and another simplified with a ternary operator, doesn't work.
the instructions are: Define a function takeWhile that takes a callback function and an array as arguments. takeWhile will iterate through the array, passing each array element to the callback as an argument. Every sequential array value that returns true from the callback should be collected in a new array. As soon as an array value returns false from the callback, takeWhile should return this new array.
This code works fine:
const takeWhile = (cb, arr) => {
  // ADD CODE HERE...
  //empty array to push true values into
  const result = [];
  //for loop
  for(let i in arr){
  //if callback yields true, push to result array.
    if(cb(arr[i])){
      result.push(arr[i]);
    // else return result
    } else {
      return result;
    }
  }
  //once loop has concluded, return result
  return result;
};

/*
 * Uncomment the following lines and Run Code to test your work
 */
const isEven = (elem) => (elem % 2 === 0);
console.log(takeWhile(isEven, [2,4,5,6,8])); // -> [2,4]
console.log(takeWhile(isEven, [7, 100, 14])); // -> []
console.log(takeWhile(isEven, [10, 8, 6, 4, 2])); // -> [10, 8, 6, 4, 2]

this code is using(what I think) is identical logic, but is not filling the result array and returning correctly, using ternary operator.
const takeWhile = (cb, arr) => {
  //empty array to push true values into
  const result = [];
  //for loop
  for(let i = 0; i < arr.length; i++){
  //if callback yields true, push to result array, else return result
    return cb(arr[i]) ? result.push(arr[i]) : result;
  }
  return result;
};

/*
 * Uncomment the following lines and Run Code to test your work
 */
const isEven = (elem) => (elem % 2 === 0);
console.log(takeWhile(isEven, [2,4,5,6,8])); // -> [2,4]
console.log(takeWhile(isEven, [7, 100, 14])); // -> []
console.log(takeWhile(isEven, [10, 8, 6, 4, 2])); // -> [10, 8, 6, 4, 2]

for example
console.log(takeWhile(isEven, [2,4,5,6,8])); // -> [2,4]

returns 1, when it should return [2,4]

A: Your logic before was to only return if cb(arr[i]) was falsy. Now you always return after the first loop iteration.
Also array.push returns the length of the new array, not the new array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

A: return cb(arr[i]) ? result.push(arr[i]) : result;
That says: if passing the current array item to the callback returns a truthy value, then return the length of the result array after you've pushed the current item to it, otherwise return the result array.
Array.prototype.push returns the length of the array. And the ternary here will return on the first loop either way.

A: Consider the line of your second example.
return cb(arr[i]) ? result.push(arr[i]) : result;

This will end the function in the first loop regardless of the conditions. Although function will return according to condition but it will return in the first iteration.
Ternary operators can only be used instead of if-else statements if they don't include any statements. return is a statement in above code.
This is not asked but just for information you can use filter() for simpler code.
const getEvens = (arr) => arr.filter(x => x % 2 === 0);

A: This condition:
if(cb(arr[i])){
   result.push(arr[i]);
   // else return result
} else {
   return result;
}

is not the same as:
return cb(arr[i]) ? result.push(arr[i]) : result;

In the first you return only when !cb(arr[i]) wich is not possible using ternary operator because the operands of the ternary operator are expressions. And return is a statement. You should use if else.

A: To achieve expected result, modify ternary as below
cb(arr[i]) ? result.push(arr[i]) : i = arr.length;

*

*Remove return with in for loop to execute

*return of result.push(arr[i]) is the length of values pushed

*second parameter of ternary change i value to length of array to stop for loop

Other issue from ternary and first option from your code , there is no return option available with ternary as below
 cb(arr[i]) ? result.push(arr[i]) : return result; // invalid syntax but equivalent to option 1 logic which you are trying

Please refer this link - Why can't we have return in the ternary operator?
code sample

const takeWhile = (cb, arr) => {
  //empty array to push true values into
  const result = [];
  //for loop
  for(let i = 0; i < arr.length; i++){
  //if callback yields true, push to result array, else return result
    cb(arr[i]) ? result.push(arr[i]) : i = arr.length;

  }
  return result;
};

/*
 * Uncomment the following lines and Run Code to test your work
 */
const pushVal = (val) => {
  result.push(arr[i]);
  return result
}
const isEven = (elem) => (elem % 2 === 0);
console.log(takeWhile(isEven, [2,4,5,6,8])); // -> [2,4]
console.log(takeWhile(isEven, [7, 100, 14])); // -> []
console.log(takeWhile(isEven, [10, 8, 6, 4, 2])); // -> [10, 8, 6, 4, 2]

codepen - https://codepen.io/nagasai/pen/xoGOOQ


text:
Q: Google Account Registering Bot thanks for spending time on my post.
I'm currently experiencing a easier way to create a Google account, and apparently there is no Google account creating bot or such thing like that, so I decided to write one my self.(Well, It's not a actual bot, it asks you to manually enter the Captcha.) Then I had a problem when setting a value of a combo box and when grabbing the captcha image to a picture box.....
Here's a part of my code(where the error occurred):
    'WebBrowser1 has been navigated to "https://accounts.google.com/SignUp?continue=https:%2F%2Faccounts.google.com%2FManageAccount"
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
    Dim r As System.Random = New System.Random
    'Sets the value of other textboxes
    WebBrowser1.Document.GetElementById(":0").InnerText = MonthSelect(r.Next(1, 12))
    WebBrowser1.Document.GetElementById(":d").InnerText = GenderSelect(r.Next(0, 1))
    Captcha.ImageLocation = WebBrowser1.Document.GetElementById("recaptcha_chanllenge_image").GetAttribute("src")
End Sub

Public Function MonthSelect(mon As Integer)
    'Generates a month
End Function

Public Function GenderSelect(gen As Integer)
    'Generates a gender
End Function

And the NullReferenceException occurred in these 3 lines...
    WebBrowser1.Document.GetElementById(":0").InnerText = MonthSelect(r.Next(1, 12))
    WebBrowser1.Document.GetElementById(":d").InnerText = GenderSelect(r.Next(0, 1))
    Captcha.ImageLocation = WebBrowser1.Document.GetElementById("recaptcha_chanllenge_image").GetAttribute("src")

What's wrong?


text:
Q: Weak convergence in Bochner space where Banach space is finite-dimensional Consider the separable Banach space $V$, and let it be finite-dimensional.
Let us now consider the measure space $T$ and consider $L^2(T;V)$.
It is known that weak and strong convergence of a sequence in $V$ are equivalent if $V$ is finite-dimensional.
Does the same hold in the Banach space $L^2(T;V)$? My guess is that it does not, but I struggle to find a counterexample.
I have also tried to prove it using that $L^2(T;V)^*=L^2(T;V^*)$ and tried to use that we can write every element in $\xi \in V^*$ as $\xi = \xi_i e^{i}$, so... we should be able to say that
$$
<\xi,u>=\int_T <\xi(t),u(t) > \mathrm{d}\mu=\int_T <\xi_i(t)e^i,u^j(t)e_ j>\mathrm{d}\mu=\int_T \xi_i(t) u^i(t) \mathrm{d} t,
$$
so if we pick $\xi(t)=e^i$ we will have that $e^i(u(t))=u^i$, and then we should be able to proceed with the standard proof... but this feels... probably not right? I think the problem lies in assuming that I can write an element in the dual of $V$ like I do. Any input would be much appreciated.

A: The answer is: Not if $T$ is arbitrary.
For example if $T=\{ 1,\ldots,n\}$ with the counting measure and $V=\mathbb{R}$, then $L^2(T,V)$ is simply $\mathbb{R}^n$ with the Euclidean norm; so in this case it's actually true.
On the other hand if $T=\{ 1,2,\ldots, n,\ldots\}$, and $V=\mathbb{R}$, then $L^2(T,V)=\ell^2$ is the space of square summable sequences, i.e. x$=(x_i)_{i\in \mathbb{N}}\in \ell^2$ if and only if
$$
\| x\|_{\ell^2}^2:= \sum_{n\in\mathbb{N}} |x_i|^2 <\infty.
$$
The sequence of elements $e^j\in \ell^2$ given by
$$
e^j:=(0,\ldots, 0,1,0,\ldots),
$$
where the lone $1$ is in the $j$-th position, satisfies that $e^j\to 0$ weakly but not strongly.
More generally, whenever $L^2(T;V)$ is inifinite dimensional you'll be able to construct counterexamples simply by taking a countable orthonormal set.


text:
Q: ID3D11DeviceContext::CopyResource with different D3D11_USAGE
I am exporing Nvidia's Flex but I am very new to D3D. I am trying to copy between two ID3D11Buffer which are created using different D3D11_BUFFER_DESC. I wanted to use ID3D11DeviceContext::CopyResource() since it's GPU-GPU copy but the code is throwing exception.

Two buffers are created as below:
//First Buffer:
D3D11_BUFFER_DESC bufDesc;
bufDesc.ByteWidth = numParticles*sizeof(Vec4);
bufDesc.Usage = D3D11_USAGE_DYNAMIC;
bufDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufDesc.MiscFlags = 0;
bufDesc.StructureByteStride = 0;
m_device->CreateBuffer(&bufDesc, NULL, buff0);

//Second Buffer
D3D11_BUFFER_DESC bufDescTemp;
bufDescTemp.ByteWidth = numParticles * sizeof(Vec4);
bufDescTemp.Usage =  D3D11_USAGE_DEFAULT;
bufDescTemp.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufDescTemp.CPUAccessFlags =
D3D11_CPU_ACCESS_READ;//D3D11_CPU_ACCESS_READ;//
bufDescTemp.MiscFlags = 0;
bufDescTemp.StructureByteStride = 0;
m_device->CreateBuffer(&bufDescTemp, NULL, buff1);

Then at each frame I get an updated buff0 from Flex's NvFlexGet. Then I try to copy buff0 to buff1:
context->CopyResource(buff1,buff0);

But this line throws exception. It works fine if both buffers are created using D3D11_USAGE_DYNAMIC. But not when buff1 is D3D11_USAGE_DEFAULT.
Does ID3D11DeviceContext::CopyResource supports copy between buffers with different D3D11_USAGE? Or did I miss something?

A: D3D11_USAGE_DYNAMIC means a resource that is accessible by both the GPU (read only) and the CPU (write only). That's why it cannot be used in CopyResource.


text:
Q: UIDocumentInteractionController not transferring to target application My app is generating an image which I'm attempting to pass to Instagram using a document interaction controller and their hook. Oh, this is using iOS 5.1.
I have the UIDocumentInteraction action sheet showing up properly but the issue is that once the user select "open in Instagram" the sheet is dismissed and nothing happens.
The code:
// Method returns a path to the generated image
NSURL *finalCompositePath = [NSURL fileURLWithPath:[self generateFinalImage:@"instagram"]];
UIDocumentInteractionController *documentInteractionController;
NSURL *instagramURL = [NSURL URLWithString:@"instagram://camera"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    //imageToUpload is a file path with .ig file extension
    documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:finalCompositePath];
    documentInteractionController.UTI = @"com.instagram.exclusivegram";
    documentInteractionController.delegate = self;
    documentInteractionController.annotation = [NSDictionary dictionaryWithObject:@"Caption Test" forKey:@"InstagramCaption"];
    [documentInteractionController presentOptionsMenuFromBarButtonItem:self.ShareButton animated:YES];
}

Thoughts?

A: UIDocumentsInteractionController shows iBooks but doesn't open it has the correct answer for apps using arc. UIDocumentInteractionController must be a property of the class.
BUT ALSO!!!
If you are supporting down to ios5, make sure the image you've saved is a type ".igo" (not .jpg or .png).
IOS6 will open it up in instagram, but IOS less than 6 will just dismiss the UIDocumentInteractionController without proceeding to instagram.


text:
Q: Jackson parse Double from String/Pure Number Format I have a filed, lets say something like this, which is double value boxed to native type or in string.
   { "field1" : 123.00 }

or
{"field1" : "123.00" }

and Corresponding Pojo:
    class Response{
          Double field1;
}

Now, if its in String format, I see an error as shown below:
Caused by: java.lang.NoSuchFieldError: USE_FAST_DOUBLE_PARSER
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$DoubleDeserializer._parseDouble(NumberDeserializers.java:755)
    at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$DoubleDeserializer.deserialize(NumberDeserializers.java:684)

Apparently the same thing works for Int or long for both string or pure numbers. Why does it fail for Double?
Is there any annotation to use to make it work for both formats? Or fix the issue for parsing from string?
Alternatively, it works using @Jsonsetter.
Thanks

A: The Error mentioned was caused by incompatible versions (2.13.x vs 2.14) in Jackson dependencies, as mentioned by @dpr. The fix was to correct versions (keep it same for various dependencies i.e. jackson-core,jackson-databind, etc.,) and it works for both string and number format which is the default behaviour.


text:
Q: Android - FTPS Session Reuse - No field sessionHostPortCache I'm developing an application on Android with Android Studio and I want to use FTP to send files to a server. I need to support session reuse since the server is hosted by an hosting service provider and they obviously have session reuse enabled.

I found this reflection hack in this post used by many to make make this possible:
// adapted from:
// https://trac.cyberduck.io/browser/trunk/ftp/src/main/java/ch/cyberduck/core/ftp/FTPClient.java
@Override
protected void _prepareDataSocket_(final Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        // Control socket is SSL
        final SSLSession session = ((SSLSocket) _socket_).getSession();
        if (session.isValid()) {
            final SSLSessionContext context = session.getSessionContext();
            try {
                final Field sessionHostPortCache = context.getClass().getDeclaredField("sessionHostPortCache");
                sessionHostPortCache.setAccessible(true);
                final Object cache = sessionHostPortCache.get(context);
                final Method method = cache.getClass().getDeclaredMethod("put", Object.class, Object.class);
                method.setAccessible(true);
                method.invoke(cache, String
                        .format("%s:%s", socket.getInetAddress().getHostName(), String.valueOf(socket.getPort()))
                        .toLowerCase(Locale.ROOT), session);
                method.invoke(cache, String
                        .format("%s:%s", socket.getInetAddress().getHostAddress(), String.valueOf(socket.getPort()))
                        .toLowerCase(Locale.ROOT), session);
            } catch (NoSuchFieldException e) {
                throw new IOException(e);
            } catch (Exception e) {
                throw new IOException(e);
            }
        } else {
            throw new IOException("Invalid SSL Session");
        }
    }
}

Here's the code that uses SSLSessionReuseFTPSClient:
System.setProperty("jdk.tls.useExtendedMasterSecret", "false");

String host = "xxxxxxxx";
String user = "xxxxxxxx";
String password = "xxxxxxxx";
String directory = "xxxxxxxx";

ProtocolCommandListener listener = new MyProtocolCommandListener(host);

SSLSessionReuseFTPSClient client = new SSLSessionReuseFTPSClient("TLS", false);
client.addProtocolCommandListener(listener);

try {
    client.connect(host);
    client.execPBSZ(0);
    client.execPROT("P");

    if (client.login(user, password)) {
        Log.w("myApp", "Logged in as " + user + " on " + host + ".");
    }

    if (client.changeWorkingDirectory(directory)) {
        Log.w("myApp", "Working directory changed to " + directory + ".");
    }

    client.enterLocalPassiveMode();

    InputStream input = new FileInputStream(file);

    if (client.storeFile(file.getName(), input)) {
        Log.w("myApp", "File " + file.getName() + " sent to " + host + ".");
    } else {
        Log.w("myApp", "Couldn't send file " + file.getName() + " to " + host + ".");
        Log.w("myApp", "Reply: " + client.getReplyString());
    }

    client.logout();
    client.disconnect();
} catch (Exception e) {
    e.printStackTrace();
}

I first tried in Eclipse, and it worked. Then I tried to implement it in my Android application, but I get this error:
java.io.IOException: java.lang.NoSuchFieldException: No field sessionHostPortCache in class Lcom/android/org/conscrypt/ClientSessionContext; (declaration of 'com.android.org.conscrypt.ClientSessionContext' appears in /system/framework/conscrypt.jar)

I noticed that, when I execute the code in Eclipse and print the context class name, I get this: sun.security.ssl.SSLSessionContextImpl, but in Android Studio, I get: com.android.org.conscrypt.ClientSessionContext.

I've been searching for almost two days straight and I'm just not experienced enough to know what is up. Why is com.android.org.conscrypt.ClientSessionContext use instead of sun.security.ssl.SSLSessionContextImpl ? I check the java.security file and from what I see, sun.security.ssl.SSLSessionContextImpl should be used.
If someone could help me with this, I would be insanely grateful.
Finally, here's some information that could be useful :
Android Studio 3.6.2
commons-net-3.6
openjdk version "1.8.0_212-release"
OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)

Thank you !

A: Based on the same idea of the Java cyberduck's solution, I overrided the "prepareDataSocket" method of the FTPSClient to make it works on Android.
I test it in Android 9.0 and in Android 5.1.1 and it works fine.
The code was:
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;

import org.apache.commons.net.ftp.FTPSClient;

public class TLSAndroidFTPSClient extends FTPSClient
{
    @Override
    protected void _prepareDataSocket_(final Socket socket) throws IOException
    {
        if (socket instanceof SSLSocket)
        {
            final SSLSession sessionAux = ((SSLSocket) _socket_).getSession();
            if(sessionAux.isValid())
            {
                final SSLSessionContext sessionsContext = sessionAux.getSessionContext();
                try
                {
                    // lets find the sessions in the context' cache
                    final Field fieldSessionsInContext =sessionsContext.getClass().getDeclaredField("sessionsByHostAndPort");
                    fieldSessionsInContext.setAccessible(true);
                    final Object sessionsInContext = fieldSessionsInContext.get(sessionsContext);

                    // lets find the session of our conexion
                    int portNumb=sessionAux.getPeerPort();
                    Set keys=((HashMap)sessionsInContext).keySet();
                    if(keys.size()==0)
                        throw new IOException("Invalid SSL Session");
                    final Field fieldPort=((keys.toArray())[0]).getClass().getDeclaredField("port");
                    fieldPort.setAccessible(true);
                    int i=0;
                    while(i<keys.size() && ((int)fieldPort.get((keys.toArray())[i]))!=portNumb)
                        i++;

                    if(i<keys.size())   // it was found
                    {
                        Object ourKey=(keys.toArray())[i];
                        // building two objects like our key but with the new port and the host Name and host address
                        final Constructor construc =ourKey.getClass().getDeclaredConstructor(String.class, int.class);
                        construc.setAccessible(true);
                        Object copy1Key=construc.newInstance(socket.getInetAddress().getHostName(),socket.getPort());
                        Object copy2Key=construc.newInstance(socket.getInetAddress().getHostAddress(),socket.getPort());

                        // getting our session
                        Object ourSession=((HashMap)sessionsInContext).get(ourKey);

                        // Lets add the pairs copy1Key-ourSession & copy2Key-ourSession to the context'cache
                        final Method method = sessionsInContext.getClass().getDeclaredMethod("put", Object.class, Object.class);
                        method.setAccessible(true);
                        method.invoke(sessionsInContext,copy1Key,ourSession);
                        method.invoke(sessionsInContext,copy2Key,ourSession);
                    }
                    else
                        throw new IOException("Invalid SSL Session");

                } catch (NoSuchFieldException e) {
                    throw new IOException(e);
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                throw new IOException("Invalid SSL Session");
            }
        }
    }
}

A: I ran into the same issue in an android project with api 33.
Trying to get the field: sessionsContext.getClass().getDeclaredField("sessionsByHostAndPort")
leads to:
Accessing hidden field (blocked, reflection, denied)
W/Accessing hidden field Lcom/android/org/conscrypt/ClientSessionContext;
->sessionsByHostAndPort:Ljava/util/Map; (blocked, reflection, denied)
W/System.err: java.lang.NoSuchFieldException:
No field sessionsByHostAndPort in class Lcom/android/org/conscrypt/ClientSessionContext;
(declaration of 'com.android.org.conscrypt.ClientSessionContext'
appears in /apex/com.android.conscrypt/javalib/conscrypt.jar)

W/System.err:     at java.lang.Class.getDeclaredField(Native Method)
W/System.err:     at org.apache.commons.net.ftp.FTPSClient._prepareDataSocket_(FTPSClient.java:409)
W/System.err:     at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:310)
W/System.err:     at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:638)
W/System.err:     at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:1988)
W/System.err:     at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2084)
W/System.err:     at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2282)
W/System.err:     at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2248)
W/System.err:     at de.medialux.powerftp.activities.RemoteExplorerActivityFTP$23.doInBackground(RemoteExplorerActivityFTP.java:2186)
W/System.err:     at de.medialux.powerftp.activities.RemoteExplorerActivityFTP$23.doInBackground(RemoteExplorerActivityFTP.java:1978)
W/System.err:     at android.os.AsyncTask$3.call(AsyncTask.java:394)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:264)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
W/System.err:     at java.lang.Thread.run(Thread.java:1012)

Since API level 28 Android forbids access to some hidden API functions
(see: https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces).
Lots of required functions used by the PoC are black listed and threw exceptions
while trying to access them via the Reflection API.
After some time of research I found the
'com.github.ChickenHook:RestrictionBypass' library.
https://github.com/ChickenHook/RestrictionBypass
After adding the library to the project in app gradle file
the access to the fields in ClientSessionContext are granted.


text:
Q: javascript animation, a img move in the screen and every time when they touch the screen limit, they turn direction Hey guys i have been tried to made a code to move a image in the window, the img will keep moving to a same direction until it hits the screen limit, and them it will change the direct in order to keep  moving, The code i have been made is below:
var flySpeed = 5;
var maxWidth = window.innerWidth;
var maxHeight = window.innerHeight;
var xPosition = 0;
var yPosition =0;
var xDirection = "right";
var yDirection = "down";

function movingBug()
{
    var bug = document.getElementById("bugImg");
    bug.style.left = xPosition + "px";
    bug.style.top = yPosition + "px";
    bug.style.position="absolute";

if (xDirection =="right")
    ++xPosition;
else if (xDirection =="left")
    ++xPosition;

if(yDirection =="down")
    ++yPosition;
else if (yDirection =="up")
    --yPosition;

 if(xPosition == screen.availWidth - 100)
 {
    xDirection ="left";
    yDirection = "down";

 }

if(xPosition == screen.availWidth - 10)
{
    xDirection = "right";
    yDirection = "up";

}

if(yPosition == screen.availHeight - 100)
{
    xDirection = "left";
    yDirection = "down";
}

if(yPosition == screen.availHeight - 10)
{
xDirection = "right";
yDirection = "up";
}

}

HTML part:

Now, i think i need to use math random in order to let it move randomly, where should i add it?

A: You're mistakenly using ++ instead of --
if (xDirection =="right")
    ++xPosition;
else if (xDirection =="left")
    --xPosition;//here

Also, you're missing:
if(yPosition == screen.availHeight - 10)
   {
    xDirection = "right";
    yDirection = "up";
   }


text:
Q: Dynamic SQL Concatenation with PHP MySQLi Prepared Statements I am writing a PHP prepared statement using MySQLi prepared statements where the first bound parameter is a user's ID and the second parameter can be one of 5 different pieces of SQL code (the $redeemLimitCheckRange variable) based on other conditions represented as a string.  I am having trouble binding the second parameter.
I have tried binding the SQL code as a string, have tried using the SQL CONCAT() function, but neither seem to work.
<?php
    if($dbRedeemStart != '' && $dbRedeemEnd != ''){
        $redeemLimitCheckRange = "AND DATE(chg_date) >='$dbRedeemStart' AND DATE(chg_date) <= '$dbRedeemEnd'";
    else if($dbRedeemStart != '' && $dbRedeemEnd == ''){
        $redeemLimitCheckRange = "AND DATE(chg_date) >= '$dbRedeemStart'";
    else if($dbRedeemStart == '' && $dbRedeemEnd != ''){
        $redeemLimitCheckRange = "AND DATE(chg_date) <= '$dbRedeemEnd'";
    }else{
        $redeemLimitCheckRange = "";
    }

    $sql = "SELECT COUNT(recId) totalRedeem FROM transactions WHERE userId = ? AND `type` = 'Redeemed' ?";
    $stmt = mysqli_stmt_init($connection);

    if(!mysqli_stmt_prepare($stmt, $sql)){
        error_log("mysqli_stmt_prepare failure", 0);
    }else{
        mysqli_stmt_bind_param($stmt, "is", $usrId, $redeemLimitCheckRange);
        mysqli_stmt_execute($stmt);
        $rslt = mysqli_stmt_get_result($stmt);
        mysqli_stmt_close($stmt);
    }
?>

Currently, php is failing on the mysqli_stmt_prepare($stmt, $sql) line and throwing an error.


text:
Q: When querying SQL, time that passed to query is less 2 hours of the time I set. Why? please advise.
Working with ExtJS, and Oracle SQL. Situation is this:
I have to get documents from DB, between two dates, dateFrom and dateTo.
My dateTo is set to end of Current day, eg 2018-02-09 23:59:59.
let dateTo = new Date()
dateTo = Ext.Date.clearTime(dateTo);
dateTo.setHours(23, 59, 59, 999);

When I query, dates passed are both less 2 hours of what I have set (2018-02-09 21:59:59). Why is this happening, someone? Is it because of this GMT+2 business?
capture1.png is from SQL query, capture2.png is console.log(dateTo)
And how to cure it.
Many thanks in advance!

A: Calculate the date by subtracting the GMT Diff

*

*gmtDiff = Ext.Date.format(dateTo, 'Z') * 1000

and then to see the result:

*

*Ext.Date.format(dateTo, 'Y-m-d H:i:s')


text:
Q: Toggle not have error but not run I am using toggle() for 'slideshow pack information of travelle' check code here:
HTML:
www2.mappaturismo.com.br
JAVASCRIPT:
function rota() {
  $(".col-a div.row-a-dois:last").toggle(
    function(){ $(this).fadeIn("slow") }, function(){ $(this).fadeOut("slow") }
  );
  $(".col-a div.row-a-tres:last").toggle(
    function(){ $(this).fadeIn("slow") }, function(){ $(this).fadeOut("slow") }
  );
  $(".col-a div.row-a-dois:first").toggle(
    function(){ $(this).fadeIn("slow") }, function(){ $(this).fadeOut("slow") }
  );
  $(".col-a div.row-a-tres:first").toggle(
    function(){ $(this).fadeIn("slow") }, function(){ $(this).fadeOut("slow") }
  );
}
$(function() {
  setInterval( "rota()", 5000 );
});

A: I think you have misunderstood what the jQuery "toggle()" function does. It does not make things happen right away. Instead, it binds event handlers to your elements.
Therefore, calling "toggle()" over and over again like that is pointless.
I'm not sure what it is that you want to happen on your page, so it's hard to say what your code should look like.


text:
Q: JUnit gives no information regarding "errors" I'm using Junit 4.4 and Ant 1.7.  If a test case fails with an error (for example because a method threw an unexpected exception) I don't get any details about what the error was.
My build.xml looks like this:
<target name="test" depends="compile">
<junit printsummary="withOutAndErr" filtertrace="no" fork="yes" haltonfailure="yes" showoutput="yes">
  <classpath refid="project.run.path"/>
  <test name="a.b.c.test.TestThingee1"/>
  <test name="a.b.c.test.NoSuchTest"/>
</junit>
</target>

When I run "ant test" it says (for example) 2 Test runs, 0 failures, 1 error.  It doesn't say "There is no such test as NoSuchTest" even though this is completely reasonable and would let me figure out the cause of the error.
Thanks!
-Dan

A: If you're going to have a lot of tests there are two change you might want to consider:

*

*run all the tests rather than stopping at the first error

*create a report showing all the test results

And it is pretty easy to do with the junitreport task:
<target name="test">
    <mkdir dir="target/test-results"/>
    <junit fork="true" forkmode="perBatch" haltonfailure="false"
           printsummary="true" dir="target" failureproperty="test.failed">
        <classpath>
            <path refid="class.path"/>
            <pathelement location="target/classes"/>
            <pathelement location="target/test-classes"/>
        </classpath>
        <formatter type="brief" usefile="false" />
        <formatter type="xml" />
        <batchtest todir="target/test-results">
            <fileset dir="target/test-classes" includes="**/*Test.class"/>
        </batchtest>
    </junit>

    <mkdir dir="target/test-report"/>
    <junitreport todir="target/test-report">
        <fileset dir="target/test-results">
            <include name="TEST-*.xml"/>
        </fileset>
        <report format="frames" todir="target/test-report"/>
    </junitreport>

    <fail if="test.failed"/>
</target>

A: Figured it out :)
I needed to add a "formatter" inside the junit block.
<formatter type="plain" usefile="false" />

What a PITA.
-Dan


text:
Q: Excel VBA Textbox resets to 0 when i press a button i have a userform with 2 textboxes, 2 labels and a log in button.
On my excel sheet i have a sort of database with id, name, pin and balance.
the problem is whenever i click the login button my ID textbox resets its value to 0, but my pin textbox works fine!
i will paste my complete code:
Dim ID As Integer
Dim PIN As Integer
Dim PINField As String
Dim Balance As Double
Dim Attempts As Integer
Dim BalanceField As String

Private Sub btnLogin_Click()
    txtID.Text = ID
    Call SetId
    Call Authenticate
End Sub

Sub Authenticate()
    If txtPin.Text = PIN Then
        Call Welcome
    ElseIf Attempts > 3 Then
        Call Bye
    Else
        lblWelcome.Caption = "Wrong Pin"
        lblWelcome.ForeColor = RGB(255, 0, 0)
        Attempts = Attempts + 1
    End If
End Sub

Sub SetId()
    PINField = "C" & Str(ID)
    PINField = Replace(PINField, " ", "")
    MsgBox (PINField)
    BalanceField = "D" & Str(ID)
    BalanceField = Replace(BalanceField, " ", "")
    MsgBox (BalanceField)
End Sub

Sub Welcome()
    MsgBox ("Login Successful. Welcome")
End Sub

Sub Bye()
    MsgBox ("Max Pin Attempts reached. Contact Your Bank")
    Unload frmLogin
End Sub

A: The reason it does this is because you are using a variable which has no value. Since it is an Integer it returns 0.
I'm guessing you probably actually want to have ID = txtID.Text - that is, take the value of the txtID textbox and store the value in the ID variable.
This will probably error though because the Text property of a textbox is a String. You will need to use ID = CInt(txtID.Text). You should also do some checking to make sure that txtID.Text evaluates to an Integer before assignment.

A: Please make sure there's no reset for the txtID anywhere in the code that you have not shown here. Looking at your code, it doesn't say anything how you are setting values to either ID or PIN...  You said it's working fine for PIN, so it makes me very curious...
It could be the case Nick pointed out given this is a Form with textboxes allowing people to enter ID and PIN.. And then you are comparing it against PIN. But what are you comparing against? As you said you have a database kind of a structure in the sheet. You need to assing ID and PIN using it.
Here is the visualization I have for your Sheet, which is my best blind guess:
User needs to enter a value via the Form into txtID. That number is infact the cell number for column C which contains the relevant PIN. Then you compare that PIN with the txtPIN value. Next return the balance from column D based on that PIN.
Try this:
Private Sub btnLogin_Click()
    If txtID.Text <> "" Or txtID.value > 0 or txtPIN.Text <> "" Then
      ID = CInt(txtID.Text)
      Call SetID
      Call Authentication
    Else
      MsgBox "ID and PIN" can't be empty!"
    End If
End Sub

Sub Authenticate()
    If CInt(txtPin.Text) = PIN Then '-- here
        Call Welcome
        '-- idealy Blance can be shown at this point...
    ElseIf Attempts > 3 Then
        Call Bye
    Else
        lblWelcome.Caption = "Wrong Pin"
        lblWelcome.ForeColor = RGB(255, 0, 0)
        Attempts = Attempts + 1
    End If
End Sub

Sub SetId()
      PIN = CInt(Trim(Sheets(1).Range("C" & ID).value))
      '-- NOT sure why you are showing this PIN here since you want to authenticate...?
      MsgBox PIN
      BalanceField = Sheets(1).Range("D" & ID).value
      BalanceField = Trim(BalanceField) '--here
      '-- doesn't make sense to show Balance before authentication...
      MsgBox BalanceField
End Sub

*

*Trim is clearner and faster than Replace..


text:
Q: It it possible to get httrack to wait N seconds between each transfer? I've limited the concurrent connections, and I noticed there is something called --advanced-wait, but the manual does not describe if this might do what I want to do.
The site in question that I want to download have a limit on page loads within a given timeframe, and thus many of the pages downloaded only contains a single error message.

A: --advanced-wait is not what you are looking for: http://forum.httrack.com/readmsg/14145/14143/index.html?q=httrack+advanced-wait
Also I did not find option which can set how much time to wait between connections.


text:
Q: selectively grab portion of query string from url via url rewriting in htaccess I have this in my .htaccess file:
RewriteEngine On
RewriteCond %{THE_REQUEST} /index\.php\?p=(?!admin)(?!superadmin)((?![^&]*?edit)[^\s&]+) [NC]
RewriteCond %{THE_REQUEST} /index\.php\?p=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=301,L,QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]

This rewrites in both directions. One way from:
domain.com/index.php?p=Home&l=en&m=0

to:
domain.com/Home

and vice versa. What I would like to do is preserve the query string part of the URL that comes after the value of 'p' and pass it along BOTH WAYS.
I was able to do one way, with this code:
RewriteEngine On
RewriteCond %{THE_REQUEST} /index\.php\?p=(?!admin)(?!superadmin)((?![^&]*?edit)[^\s&]+) [NC]
RewriteCond %{THE_REQUEST} /index\.php\?p=([^\s&]+)&p=([^\s&]+) [NC]
RewriteRule ^ /%1?%2? [R=301,L,QSA]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]

but I can't get the other way right. Can you guys help? I basically want the value of p to be written as part of the URL after the domain and I don't want it to reappear again but I want all the other variables to be appended.
Right now what I get is:
domain.com/Home?m=0?&p=Home&ms=m0&l=en

A: This should work for you:
RewriteEngine On

RewriteCond %{THE_REQUEST} /index\.php\?p=((?!(?:admin|superadmin|[^&]*?edit))[^\s&]+)(?:&(\S+))? [NC]
RewriteRule ^ /%1?%2 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]


text:
Q: Ubuntu Studio 21.10 Live iso not detecting keyboard When I launch U.Studio 21.10 Live ISO from a Ventoy USB Flash key, my french azerty keyboard is not detected as french and set to a default qwerty US keyboard.
How to have either

*

*detection of the language/input method

*prompt for language/input method

at the launch of the live ISO?
As it is done when installing U.Studio 21.10 on the hard drive.


text:
Q: json_decode returning empty array I have a curl command which outputs the following:
"{"meta":{"code":200},"data":{"username":"monstore","bio":"Art clothing line with our life scary tales as the imagination. info@heymonstore.com \/ +6281213162069 \/ BB PIN 293A4565","website":"http:\/\/www.heymonstore.com","profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_4472462_75sq_1354349840.jpg","full_name":"Monstore","counts":{"media":547,"followed_by":6472,"follows":129},"id":"4472462"}}"

Here's the curl command:
  $output = curl_exec($ch);

Basically the above is what $output prints out. So I tried to decode this by doing:
$userinfo = json_decode($output, false);

however it returns an empty array. Any idea why?

A: $userinfo = json_decode($output, true);

you need to specify you want an associative array instead of an object from json_decode:

A: $userinfo = json_decode($output, true); //could you set this to true and try? It worked for me.
From http://php.net/manual/en/function.json-decode.php, When TRUE, returned objects will be converted into associative arrays.


text:
Q: Where can I learn about the lattice of partitions? A set $P \subseteq \mathcal{P}(X)$ is a partition of $X$ if and only if all of the following conditions hold:

*

*$\emptyset \notin P$

*For all $x,y \in P$, if $x \neq y$ then $x \cap y = \emptyset$.

*$\bigcup P = X$

I have read many times that the partitions of a set form a lattice, but never really considered the idea in great detail. Where can I learn the major results about such lattices? An article recommendation would be nice.
I'm also interested in the generalization where condition 3 is disregarded.

A: G. Birkhoff, Lattice Theory. Providence, Rhode Island, 1967,
Chapt.4, sec.9.

A: George Grätzers book General Lattice Theory has a section IV.4 on partition lattices,
see page 250 of this result of Google books search. A more recent version of the book is called Lattice Theory: Foundation.

A: The Logic of Partitions: Introduction to the Dual of the Logic of Subsets
I just stumbled upon it a couple of days ago, but it looks to be a great reference.


text:
Q: How do I mix underscore functions to use a custom comparison algorithm for _.contains()? Ideally, I want to pass a custom comparison function to _.contains() as a third argument, but it only accepts a collection and a value.
Code
I want to do this:

_.contains(['apples', 'oranges'], 'applesss', function (element, value) {
  return new RegExp(element).test(value);
});

... but I can't, so what's the next best thing?

A: It sounds like you're looking for _.some, which returns true if the test passes for at least one element in the array:
_.some(['apples', 'oranges'], function (element) {
  return new RegExp(element).test('applesss');
});

You can easily wrap it in your own function:
function test_regexes(arr, value) {
  return _.some(arr, function (element) {
    return new RegExp(element).test(value);
  });
}

test_regexes(['apples', 'oranges'], 'applesss');


text:
Q: Problema CSS alineamiento de label inputs - HTML Estoy realizando un formulario de registro, el típico de páginas webs, pero tengo un problema en cuanto a la disposición de los elementos.
Mi formulario debe contener los siguientes campos, los cuales se ven en la imagen, pero deben estar en la siguiente distribución:
Nombre - Apellidos (deben ocupar la mitad y mitad)
Email (debe ocupar todo el ancho)
DNI Teléfono (deben ocupar la mitad y mitad)
Contraseña1 Contraseña2 (deben ocupar la mitad y mitad)
Registrar (centrado)
¿Ya tienes una cuenta? Ingresa aquí. (centrado)

Os dejo el  que he generado: (estoy sujeto a modificaciones siempre y cuando sea para mejorar y aprender).

*{
     box-sizing: border-box;
    }

    body{
     margin: 0;
     font-family: sans-serif;
     background: #204862;
    }

    h1{
     color: #fff;
     text-align: center;
    }

    .form-register{
     width: 85%;
     max-width: 600px;
     margin: auto;
     background: white;
     border-radius: 4px;
    }

    .form-titulo{
     background: deepskyblue;
     color: #fff;
     padding: 20px;
     text-align: center;
     font-weight: 100;
     font-size: 30px;
     border-top-left-radius: 7px;
     border-top-right-radius: 7px;
     border-bottom: 5px solid red;
    }

    .contenedor-inputs{
     padding: 2px 20px;
     display: flex;
     flex-wrap: wrap;
     justify-content: space-between;
    }

    .input{
     margin-bottom: 8px;
     padding: 8px;
     font-size: 16px;
     border-radius: 3px;
     border: 1px solid darkgray;
    }

    .input-2{
     width: 40%;
    }

    .input-1{
     width: 100%;
    }

    .enviar{
     background: crimson;
     color: #fff;
     margin: auto;
     padding: 10px 40px;
     cursor: pointer;
     font-size: 12px;
    }

    .enviar:active{
     transform: scale(1.05);
    }

    .form-link{
     width: 100%;
     margin: `px;
     text-align: center;
     font-size: 14px;
    }
<!DOCTYPE html>

      <meta charset="UTF-8">
      <title>Formulario de registro</title>
      <link rel="stylesheet" href="estilos.css">

Formulario de registro

      <form action="registrar.php" method="POST" class="form-register">

CREA UNA CUENTA

        Nombre: <input type="text" name="nombre" id="nombre" placeholder="Nombre" tabindex="1" class="input-2" required>
        Apellidos: <input type="text" name="apellidos" id="apellidos" placeholder="Apellidos" tabindex="2" class="input-2" required>

        Email: <input type="text" name="email" id="email" placeholder="Email" tabindex="3" class="input-1" required>

        DNI: <input type="text" name="dni" id="dni" placeholder="DNI" tabindex="4" class="input-2" required>
        Teléfono: <input type="text" name="telefono" id="telefono" placeholder="Teléfono" tabindex="5" class="input-2" required>

        Contraseña: <input type="password" name="password1" id="password1" placeholder="Contraseña" tabindex="6" class="input-2" required>
        Repetir contraseña: <input type="password" name="password2" id="password2" placeholder="Repetir contraseña" tabindex="7" class="input-2" required>

        <input type="submit" value="Registrar" class="enviar" tabindex="8"/>

¿Ya tienes una cuenta? Ingresa aquí

      </form>

A: Introduce cada pareja label-input dentro de un div para que en cada fila solo exista una pareja de elementos:

        Nombre: <input type="text" name="nombre" id="nombre" placeholder="Nombre" tabindex="1" class="input-2" required>

        Apellidos: <input type="text" name="apellidos" id="apellidos" placeholder="Apellidos" tabindex="2" class="input-2" required>

        Email: <input type="text" name="email" id="email" placeholder="Email" tabindex="3" class="input-1" required>

        DNI: <input type="text" name="dni" id="dni" placeholder="DNI" tabindex="4" class="input-2" required>

        Teléfono: <input type="text" name="telefono" id="telefono" placeholder="Teléfono" tabindex="5" class="input-2" required>

        Contraseña: <input type="password" name="password1" id="password1" placeholder="Contraseña" tabindex="6" class="input-2" required>

        Repetir contraseña: <input type="password" name="password2" id="password2" placeholder="Repetir contraseña" tabindex="7" class="input-2" required>

        <input type="submit" value="Registrar" class="enviar" tabindex="8"/>

¿Ya tienes una cuenta? Ingresa aquí

De esta forma solo te quedaría centrar el contenido de estos divs usando una clase con los estilos necesarios.

A: Aquí tienes un ejemplo de cómo podría quedar basándome en tu código

CSS:
*{
    box-sizing: border-box;
}

body{
    margin: 0;
    font-family: sans-serif;
    background: #204862;
}

h1{
    color: #fff;
    text-align: center;
}

.form-register{
    width: 85%;
    max-width: 600px;
    margin: auto;
    background: white;
    border-radius: 4px;
}

.form-titulo{
    background: deepskyblue;
    color: #fff;
    padding: 20px;
    text-align: center;
    font-weight: 100;
    font-size: 30px;
    border-top-left-radius: 7px;
    border-top-right-radius: 7px;
    border-bottom: 5px solid red;
}

.contenedor-inputs{
    padding: 2px 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.input{
  min-height: 25px;
    border-radius: 3px;
    border: 1px solid darkgray;
  padding-left:5px;
}

.input-2{
    width:35%;
  max-width:150px;
}

.input-1{
    width: 80%;
  max-width: 450px;
}

.enviar{
    background: crimson;
    color: #fff;
    margin: auto;
    padding: 10px 40px;
    cursor: pointer;
    font-size: 12px;
  border-radius: 5px;
}

.enviar:active{
    transform: scale(1.05);
}

.form-link{
    width: 100%;
    margin: `px;
    text-align: center;
    font-size: 14px;
}

/* Contianers */
.container{
  width: 100%;
  margin-bottom: 10px;
}

HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Formulario de registro</title>
        <link rel="stylesheet" href="estilos.css">

Formulario de registro

        <form action="registrar.php" method="POST" class="form-register">

CREA UNA CUENTA

                  Nombre: <input type="text" name="nombre" id="nombre" placeholder="Nombre" tabindex="1" class="input input-2" required>
          Apellidos: <input type="text" name="apellidos" id="apellidos" placeholder="Apellidos" tabindex="2" class="input input-2" required>

                  Email: <input type="text" name="email" id="email" placeholder="Email" tabindex="3" class="input input-1" required>

                DNI: <input type="text" name="dni" id="dni" placeholder="DNI" tabindex="4" class="input input-2" required>
                Teléfono: <input type="text" name="telefono" id="telefono" placeholder="Teléfono" tabindex="5" class="input input-2" required>

                Contraseña: <input type="password" name="password1" id="password1" placeholder="Contraseña" tabindex="6" class="input input-2" required>
                Repetir contraseña: <input type="password" name="password2" id="password2" placeholder="Repetir contraseña" tabindex="7" class="input input-2" required>

                <input type="submit" value="Registrar" class="enviar" tabindex="8"/>

¿Ya tienes una cuenta? Ingresa aquí

        </form>

Te sugiero aprendas a usar Frameworks como Bootstrap ya que esos ayudan mucho a hacer más rápido el trabajo


text:
Q: How to propogate a bool value in a Class and a object of a class in C#
Possible Duplicate:
Keeping boolean values in sync between two threads

I have a created a new object of my Class Form1 in a thread, although I change a Boolean value called CheckSuccess in the new object - "Form1Object", how do I set the value of CheckSuccess to the GUI / Form?
I.E. I have effectively two copies of a boolean value and I want to set the value of this to the main thread / non object (GUI / Form)
I can't explain it too well, so please let me know if I need to clarify myself

A: Why in the world are you creating a new form object?
If you create two objects, you will have two copies of all the data members those objects contain. There's no good way to synchronize them.
It's not clear why you can't just work with a single form object (instance of the Form1 class). That way, when you modify members on that instance, they will be available to any code that has a reference to that object.
Creating a new form does not accomplish anything with respect to threading. Creating a new form object does not create a new thread. If you provide more information about what problem you're trying to solve and why you think you need to create a new thread in the first place, we could probably give better advice. Perhaps investigate using the BackgroundWorker component? The MSDN page gives an excellent sample of how it might be used.


text:
Q: GNAT Ada runtime Exception = message EXCEPTION_STACK_OVERFLOW I'am trying to run my application after compiling it with AdaCores GPS (Gnat Programming Studio).
I get the run time error
Exception name: STORAGE_ERROR
Message: EXCEPTION_STACK_OVERFLOW

I get these run time errors despite setting the stack size in the binder options using
-d65535 (task stack size) and
-D65535 (secondary stack size)
(I also have tried 65535k on both as well as 655m).
The application runs well when compiling it with the Aonix Object Ada compiler. In the Aonix compiler I set the
- stack size to 65535,
- the secondary stack size to 65535
- and the Task stack size to 46345.
My main aim is to port the application to the GNAT Ada compiler.
I notice -d sets the task stack size and -D the secondary stack size but I can't see where to set the main stack size, and I am assuming that this is the issue with the application, but please correct me if I am looking in the wrong direction.
Any pointers would be greatly appreciated appreciated.
Bearslumber

A: If the problem is indeed the main task, a workaround is to move the main procedure to the body of a helper task.

A: First, compile for debug (-g) (there may be other relevant options; posting wrong information is the fastest way to find them ;-) and you should get more information : the source line and file that raised the exception. Or a stack trace which you can analyze via addr2line.
That should help understand why it is raising...

*

*Are you allocating hundreds of MB on the stack? I've got away with about 200MB in the past...

*Is the raise within one of the container classes or part of the RTS?

*Is the message actually misleading and a new() heap allocation failed? Other things than the stack can raise Storage_Error, and I'm not clear how or if the default handler distinguishes the cause...

We can't proceed further down this path without further information : edit it into the question and I'll take another look.
Setting stack size for the environment task is not directly possible within Gnat. It's part of gcc's interaction with the OS, and supposed to use the system's ulimit settings for the resulting executable (on Linux; other OS may vary)...
Unfortunately, around the gcc/gnat 4.5 timeframe I found evidence these were being ignored, though that may have been corrected, and I haven't revisited that problem.
I have seen Alex's answer posted elsewhere as a viable workround if the debug trace and ulimit settings don't provide the answer, or if you need to press on instead of spending time debugging. To keep the codebase clean, I would suggest a wrapper, simply creating the necessary task and calling your current main procedure. For Aonix you simply don't need to include the wrapper file in your build.


text:
Q: Implement low-frequency live card in google glass I try to implement low-frequency Live Card using the instruction provided in the GDK guides.
I have a layout that I want to render and the LiveCard service class (that extends Service). I also have the Menu: activity to handle menu callbacks, making the menu transparent, and provide a PendingIntent for the card's action using setAction() in the LiveCard service.
I also got a successful message when loading the app into Glass but it doesn't show up in my Glass.
I'm not sure what else is missing.
[2014-04-22 00:45:01 - MyApp] Installing MyApp.apk...
[2014-04-22 00:45:04 - MyApp] Success!
[2014-04-22 00:45:04 - MyApp] /MyApp/bin/MyApp.apk installed on     device
[2014-04-22 00:45:04 - MyApp] Done!

Below is my LiveCardService:
public class LiveCardService extends Service {
private ArrayList<FeedItem> feedItems = new ArrayList<FeedItem>();
//private FeedAdapter feedAdapter = null;

// NYC: 40.758895, -73.985131
private double latitude = 0;
private double longitude = 0;

private LocationManager mlocManager;
private LocationListener mlocListener;
/******/

private static final String LIVE_CARD_TAG = "LiveCardDemo";

//private TimelineManager mTimelineManager;
private LiveCard mLiveCard;
private RemoteViews mLiveCardView;

private int homeScore, awayScore;
private Random mPointsGenerator;

private final Handler mHandler = new Handler();
private final UpdateLiveCardRunnable mUpdateLiveCardRunnable =
    new UpdateLiveCardRunnable();
private static final long DELAY_MILLIS = 30000;

@Override
public void onCreate() {
    super.onCreate();
    //mTimelineManager = TimelineManager.from(this);
    mPointsGenerator = new Random();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (mLiveCard == null) {

        // Get an instance of a live card
       // mLiveCard = mTimelineManager.createLiveCard(LIVE_CARD_TAG);
        mLiveCard = new LiveCard(this, LIVE_CARD_TAG);

        // Inflate a layout into a remote view
        mLiveCardView = new RemoteViews(getPackageName(),
            R.layout.score);

        mLiveCard.setViews(mLiveCardView); // !!!

      // Set up initial RemoteViews values
        homeScore = 0;
        awayScore = 0;
        /**/
        mLiveCardView.setTextViewText(R.id.homeTeamNameTextView,
                /*getString(R.id.home_team)*/"HOME TEAM");
        mLiveCardView.setTextViewText(R.id.awayTeamNameTextView,
                /*getString(R.id.away_team)*/"AWAY TEAM NAME");
        mLiveCardView.setTextViewText(R.id.footer_text,
                /*getString(R.id.game_quarter)*/"FOOTER_TEXT");
        /**/

        // Set up the live card's action with a pending intent
        // to show a menu when tapped
        Intent menuIntent = new Intent(this, MenuActivity.class);
        menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
            Intent.FLAG_ACTIVITY_CLEAR_TASK);
        mLiveCard.setAction(PendingIntent.getActivity(
            this, 0, menuIntent, 0));

        // Publish the live card
        mLiveCard.publish(PublishMode.REVEAL);

        // Queue the update text runnable
        mHandler.post(mUpdateLiveCardRunnable);
    }
    return START_STICKY;
}

@Override
public void onDestroy() {
    if (mLiveCard != null && mLiveCard.isPublished()) {
      //Stop the handler from queuing more Runnable jobs
        mUpdateLiveCardRunnable.setStop(true);

        mLiveCard.unpublish();
        mLiveCard = null;
    }
    super.onDestroy();
}

/**
 * Runnable that updates live card contents
 */
private class UpdateLiveCardRunnable implements Runnable{

    private boolean mIsStopped = false;

    /*
     * Updates the card with a fake score every 30 seconds as a demonstration.
     * You also probably want to display something useful in your live card.
     *
     * If you are executing a long running task to get data to update a
     * live card(e.g, making a web call), do this in another thread or
     * AsyncTask.
     */
    public void run(){
        if(!isStopped()){
          // Generate fake points.
            homeScore += mPointsGenerator.nextInt(3);
            awayScore += mPointsGenerator.nextInt(3);

            // Update the remote view with the new scores.
            mLiveCardView.setTextViewText(R.id.home_score_text_view,
                String.valueOf(homeScore));
            mLiveCardView.setTextViewText(R.id.away_score_text_view,
                String.valueOf(awayScore));

            // Always call setViews() to update the live card's RemoteViews.
            mLiveCard.setViews(mLiveCardView);

            // Queue another score update in 30 seconds.
            mHandler.postDelayed(mUpdateLiveCardRunnable, DELAY_MILLIS);
        }
    }

    public boolean isStopped() {
        return mIsStopped;
    }

    public void setStop(boolean isStopped) {
        this.mIsStopped = isStopped;
    }
}

@Override
public IBinder onBind(Intent intent) {
  /*
   *  If you need to set up interprocess communication
   * (activity to a service, for instance), return a binder object
   * so that the client can receive and modify data in this service.
   *
   * A typical use is to give a menu activity access to a binder object
   * if it is trying to change a setting that is managed by the live card
   * service. The menu activity in this sample does not require any
   * of these capabilities, so this just returns null.
   */
    return null;
}

and here is my Manifest file
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.coeverywhere.google_glass"
android:versionCode="5"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="15" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.glass.permission.DEVELOPMENT" />

<application
    android:allowBackup="true"
    android:icon="@drawable/mylogo"
    android:label="@string/app_name">
    <activity
        android:name="com.myapp.google_glass.MenuActivity"
        android:theme="@style/MenuTheme"
        android:enabled="true"
        >
    </activity>

    <!--  android:icon="@drawable/ic_lap" -->
    <service
        android:name="com.myapp.google_glass.LiveCardService"
        android:label="@string/app_name"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
        </intent-filter>
        <meta-data
            android:name="com.google.android.glass.VoiceTrigger"
            android:resource="@xml/voice_trigger_start" />
    </service>

</application>

</manifest>

and here's my voice_trigger_start.xml. I put them under res/xml
<?xml version="1.0" encoding="utf-8"?>
<trigger command = "basketball" />

A: Below is original answer, I have since made a reference project that takes the Google documentation and updates it for XE16 using the StopWatch project as a reference.  Check the code and commit history to learn a lot more:
https://github.com/mscheel/GoogleGlass-XE16-LowFrequencyLiveCardBasketballScore
One way is to declare a voice trigger to start the service/livecard.
This is mentioned in this pattern explanation:
https://developers.google.com/glass/develop/patterns/ongoing-task
The technique is described here:
https://developers.google.com/glass/develop/gdk/starting-glassware#unlisted_commands
I tested it out with your code and it worked if the manifest has these items (modify for your package name of course) ... this first one goes inside the application tag:
        <service
        android:name="com.example.lowfrequencylivecardexample.LiveCardService"
        android:enabled="true"
        android:exported="true"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.google.android.glass.action.VOICE_TRIGGER" />
        </intent-filter>
        <meta-data
            android:name="com.google.android.glass.VoiceTrigger"
            android:resource="@xml/voice_trigger" />
    </service>

You also need:
    <uses-permission android:name="com.google.android.glass.permission.DEVELOPMENT" />

You will also need this file ... res/xml/voice_trigger.xml:
<?xml version="1.0" encoding="utf-8"?>
<trigger keyword="basketball" />

I found the Timer project to be helpful in coming up with this, here is its manifest:
https://github.com/googleglass/gdk-timer-sample/blob/master/AndroidManifest.xml
Optionally you can make the home team the Celtics and the away team the Lakers.  Larry Legend forever!


text:
Q: C++ Chudnovsky Formula for Pi I am trying to make a C++ application calculate pi for me. I have tried to implement the Chudnovsky formula with no luck.
Here is my code:
#include <iostream>
#include <cmath>

long fac(long num) {
    if (num == 1)
        return 1;
    return fac(num - 1) * num;
}

int main() {
    using namespace std;
    double pi;
    for (long k = 0; k < 10; k++) {
        pi += (pow(-1, k) * fac(6 * k) * (13591409 + (545140134 * k))) / (fac(3 * k) * pow(fac(k), 3) * pow(640320, 3 * k + 3/2));
    }
    pi *= 12;
    cout << 1 / pi << endl;
    system("pause");
    return 0;
}

The goal of this was to have the program output 10 iterations of the Chudnovsky formula. Instead, I got this:
call of overloaded `pow(int, long int&)' is ambiguous

A: You never initialize pi, so your code has undefined behaviour.
Your fac function does not correctly handle 0 (fac(0) should be 1).
3/2 evaluates to 1 (because it uses integer division, which truncates), and this makes your formula evaluate to the completely wrong answer.

A: You almost certainly want to do all the math on doubles, to avoid lot of time-killing conversions. You probably also want to use an iterative implementation of fac instead of a recursive one (not that recursion is going to be a big problem, but this is a prime example of when recursion should really be avoided because it gains you nothing). Of course you also need to initialize pi as others have already pointed out.
#include <iostream>
#include <iomanip>
#include <cmath>

double fac(double num) {
    double result = 1.0;
    for (double i=2.0; i<num; i++)
       result *= i;
    return result;
}

int main() {
    using namespace std;
    double pi=0.0;
    for (double k = 0.0; k < 10.0; k++) {
        pi += (pow(-1.0,k) * fac(6.0 * k) * (13591409.0 + (545140134.0 * k)))
            / (fac(3.0 * k) * pow(fac(k), 3.0) * pow(640320.0, 3.0 * k + 3.0/2.0));
    }
    pi *= 12.0;
    cout << setprecision(15) << 1.0 / pi << endl;
    return 0;
}

A: pow(-1, k) is ineffective as it is a direct translation from math formula to the code.
Use this instead:
      (k%2==1?-1.0:1.0)*fac(...

Edit:
Also your fac code is far from optimal too.


text:
Q: Reflexion principle equivalence of statements $B_t$ is a Brownian motion, $S_t$ is defined as
$$ S_t := \sup_{0 \leq s \leq t} B_s $$
I want to show that
$$ P(S_t\geq b , B_t \leq a) = P(B_t \geq 2b-a) $$
for $a \leq b$ implies
$$ P(S_t \geq a) = 2 P (B_t \geq a).$$
I have tried posing $b=a$, however this leads to
$$ P(S_t\geq a) =  P(S_t\geq a , B_t \leq a) = P(B_t \geq a) $$
Which is different from the second statement.
One of those four must be wrong:

*

*My one-line conclusion

*The first statement (page 2 of https://www.ceremade.dauphine.fr/~mischler/Enseignements/ProcContM1/PrincipeReflexion.pdf)

*The second statement (page 2 of https://ocw.mit.edu/courses/sloan-school-of-management/15-070j-advanced-stochastic-processes-fall-2013/lecture-notes/MIT15_070JF13_Lec7.pdf)

*Mathematics (we are still unsure whether mathematics is consistent, right?).

A: Your (my) one-line conclusion is wrong:
$$ P(S_t \geq a) = P(S_t \geq a, B_t > a) + P(S_t \geq a, B_t\leq a).$$
I don't know why on earth you (I) assumed that $P(S_t \geq a, B_t > a) = 0$.
Since $B_t > a$ implies $S_t >a$, then
$$ P(S_t \geq a, B_t > a) = P(B_t \geq a).$$
Hence
$$ P(S_t \geq a) = P(S_t \geq a, B_t > a) + P(S_t \geq a, B_t\leq a) = 2  P(B_t \geq a). $$
The consistency of mathematics is saved... at least for now...


text:
Q: Number subsections and subsubsections, but not sections I'm working on an article and I don't want to number my sections. However, I do want my subsections and subsubsections to be numbered.
Right now my document has this numbering, but the 0 in 0.X.Y should not be there. How can I fix that?
Currently:
Section
0.1 subsection
0.2 subsection
0.2.1 subsubsection
0.3 subsection

Should be:
Section
1. subsection
2. subsection
2.1 subsubsection
3. subsection

This is my code:
\documentclass{article}

\begin{document}

\section*{Section}

\subsection{subsection}

\subsection{subsection}

\subsubsection{subsubsection}
blah
\subsection{subsection}

\end{document}

PS: I did search a on the web and found a lot on this topic, but not a solution to this particular thing.

A: Does this works for you:
\documentclass{article}

\begin{document}

\part*{Section}

\section{subsection}

\section{subsection}

\subsection{subsubsection}
blah
\section{subsection}

\end{document}

Or is there a special reason, why you need sections as sections and subsections as subsection?

Alternative:
\documentclass{article}

\renewcommand{\thesection}{}
\renewcommand{\thesubsection}{\arabic{subsection}}

\begin{document}

\section{Section}

\subsection{subsection}

\subsection{subsection}

\subsubsection{subsubsection}
blah
\subsection{subsection}

\section{Section 2}

\subsection{subsection 2}
This subsection starts again with 1.

\end{document}

A: If you're interested in printing \section{<heading>} in a similar way that \section*{<heading>} would print (that is, flush left and not indented), then titlesec provides an easy interface:

\documentclass{article}
\usepackage{titlesec}% http://ctan.org/pkg/titlesec
\titleformat{\section}%
  [hang]% <shape>
  {\normalfont\bfseries\Large}% <format>
  {}% <label>
  {0pt}% <sep>
  {}% <before code>
\renewcommand{\thesection}{}% Remove section references...
\renewcommand{\thesubsection}{\arabic{subsection}}%... from subsections
\begin{document}

\section{First section}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\subsection{First subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\subsection{Second subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\subsubsection{First subsubsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\subsection{Last subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\section{Second section}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\subsection{First subsection}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin rutrum tellus,
eu luctus dolor commodo eu. Integer pellentesque mollis congue.

\end{document}

This just sets the label separator between the section number and title to 0pt, as well as not printing the number. \normalfont\bfseries\Large is the default formatting for article.

A: Note: I rewrote this answer significantly after becoming aware of Ulrike Fisher's comment to @knut's answer.
There are two steps that need to be taken. The first, straightforward step consists of redefining the \thesubsection macro. The second, less obvious step involves a redefinition of the LaTeX internal macro \@seccntformat, as is explained in the book The LaTeX Companion, 2nd ed. The following MWE applies both steps:

\documentclass{article}

\renewcommand{\thesubsection}{\arabic{subsection}}
\makeatletter
\def\@seccntformat#1{\@ifundefined{#1@cntformat}%
   {\csname the#1\endcsname\quad}%    default
   {\csname #1@cntformat\endcsname}}% enable individual control
\newcommand\section@cntformat{}     % section level
\makeatother

\begin{document}
\section{First Section}
\subsection{First subsection}
\subsection{Second subsection}
\subsubsection{First subsubsection}
\subsection{Third subsection}
\section{Second Section}
\subsection{A new subsection}
\end{document}

Addendum to address @Adam's follow-up question: To (a) add dots after the subsection (and subsubsection) numbers in the sectioning headers and (b) replace the implicit \quad spacing directive with \space, you would need to provide the following two directives in the preamble, immediately before \makeatother:
\newcommand\subsection@cntformat{\thesubsection.\space}
\newcommand\subsubsection@cntformat{\thesubsubsection.\space}

A revised MWE:

\documentclass{article}

\renewcommand{\thesubsection}{\arabic{subsection}}
\makeatletter
\def\@seccntformat#1{\@ifundefined{#1@cntformat}%
   {\csname the#1\endcsname\quad}%    default
   {\csname #1@cntformat\endcsname}}% enable individual control
\newcommand\section@cntformat{}     % section level
\newcommand\subsection@cntformat{\thesubsection.\space} % subsection level
\newcommand\subsubsection@cntformat{\thesubsubsection.\space} % subsubsection level
\makeatother

\begin{document}
\section{First Section}
\subsection{First subsection}
\subsection{Second subsection}
\subsubsection{First subsubsection}
\subsection{Third subsection}
\section{Second Section}
\subsection{A new subsection}
\end{document}


text:
Q: Weird Postgres Xlog I have question about Postgres xlog. According the Postgres documentation, the Postgres xlog should be in this format 0000000100000044000000FE, i don t understand why the xlog format is my database is 000000010000004400000**5**FE.  The additional 5 from where it comes...
Here real database xlogs for postgres 9.4
cat PG_VERSION
9.4
ll pg_xlog/ | tail -n 10
-rw——- 1 postgres postgres 2097152 May 12 03:24 0000000100000044000005FE
-rw——- 1 postgres postgres 2097152 May 12 03:24 0000000100000044000005FF
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000600
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000601
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000602
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000603
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000604
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000605
-rw——- 1 postgres postgres 2097152 May 12 03:24 000000010000004400000606
drwx—— 2 postgres postgres 45056 May 12 15:10 archive_status/

Thank you in advance

A: There is nothing "weird" about the filenames. You correctly stated that the filename should be in that format (the actual names will be very different in reality).
Quote from the manual:

Segment files are given ever-increasing numbers as names, starting at 000000010000000000000000. The numbers do not wrap, but it will take a very, very long time to exhaust the available stock of numbers.

So the filename reflects an increasing number that has some structure in it. You can't expect any specific values in there, on a busy system they will simply keep increasing.
The first 8 digits (the 00000001) reflect the timeline of the WAL record if I am not mistaken, the rest the sequence number of the WAL record for that timeline.


text:
Q: Price of the product includes taxes, but actual price is reduced by the Tax Rule TL;DR: my Magento 1.9 shop handles product prices including taxes. But a new Tax Rule reduces the price to be paid by the customer. Why??? Complete issue description follows.
I'm the developer with a multi-website Magento 1.9.2.1 instance. Prices for the whole catalog are managed "including taxes" => if we insert a 100 € price, the customer is expected to pay 100 € for the product.
Every product has the same Tax Class. It's called IVA 22%, but that's just a label. It actually means "it's a product with the standard tax rate".
Up until today, we had a standard "Tax Rates" table: one entry for every country we ship to, with the same Rate Percent set to 22% for every country. This is the one for France:

This is the related rule:

This worked great! On the frontend, said product with a 100 € price tag could be purchased for 100 €. Under the hood, the sale was handled as 81.96 € + 22%.
Now we must change the tax rate depending on the shipping country. So the same Tax Rate for France was updated like this (note the Rate percent now set to 20 instead of 22):

We must keep the prices unchanged. The product with a 100 € price tag must continue to be sold for 100 €. Under the hood, we expect to be managed correctly based on the shipping country. For France, this would be 83.33 € + 20%.
Unfortunately, it doesn't work as expected. When the customer tries to buy said 100 € product and selects one of the country with a different tax, the price... gets lower. I understood that:

*

*the 100 € price still gets handled as "81.96 € + 22%" (22% being the original tax rate)

*the system takes the 81.96 € price and adds the country-specific tax

*results: the customer pays "81.96 € + 20%" = 98,35 € instead of 100 €

I've already tried to remove the original 22% tax rule, re-index everything and also to ask God for mercy. Nothing works.
What am I doing wrong?

A: Solution found! set Enable Cross Border Trade


text:
Q: Count mutual items My sql table is below
create table t (id1 varchar(10),id2 varchar(2))
insert into t values
('a','b'),
('a','c'),
('a','d'),
('b','a'),
('b','c')

I'm trying to get below output
a b 1

1 because item 'C' is common to both a and b
I have tried below sql which gives count of items but not common item count
select  t1.id1,t2.id2,count(*) from t t1 join t t2
on  t1.id1=t2.id2
group by t1.id1,t2.id2

A: The id2 of the self-join is equal, both 'c'.
And this would get (a, b) and (b, a).
So to get only (a, b) you can take the one where id1 is lower than the other id1.  This also avoids tupples like (x,x).

select t1.id1, t2.id1, count(*)
from t t1
join t t2
  on t1.id2 = t2.id2 and t1.id1 < t2.id1
group by t1.id1, t2.id1

id1 | id1 | count
:-- | :-- | ----:
a   | b   |     1

db<>fiddle here


text:
Q: Cannot display the proper value using Django and Python I could not fetch and display the value using Django and Python. My code is below:
    def viewbook(request):
        doc = minidom.parse("roomlist.xml")
        staffs = doc.getElementsByTagName("location")
        root = []
        for staff in staffs:
            lname=staff.getAttribute("name");
            roomname=staff.getElementsByTagName("roomname")[0]
            seat=staff.getElementsByTagName("noseats")[0]
            project=staff.getElementsByTagName("projectorscreen")[0]
            video=staff.getElementsByTagName("videoconf")[0]
            root.append({'lname':lname,'roomname':roomname,'seat':seat,'project':project,'video':video})
return render(request,'booking/viewbook.html',{'people': root})

Here I am fetching the data from my .xml sheet and the sheet is given below.
<?xml version="1.0" ?><roomlist>
  <location name="Bangalore">
    <room id="1uy92j908u092">
      <roomname> Aquarius </roomname>
      <noseats> 10 </noseats>
      <projectorscreen>yes</projectorscreen>
      <videoconf>yes</videoconf>
    </room>
  </location>
<location name="Bhubaneswar"><room id="131198912460"><roomname>cottage</roomname><noseats>5</noseats><projectorscreen>Yes</projectorscreen><videoconf>Yes</videoconf></room></location></roomlist>

Here I am trying to display the values in tabular format and the code is given below.

            Location Name
            Room Name
            seats
            Projector screen
            Video Conference

    {% for person in people %}

            {{person.lname}}
            {{person.roomname}}
            {{person.seat}}
            {{person.project}}
            {{person.video}}

But in my case I am getting the below kind of output.
Location Name       Room Name    seats   Projector screen    Video Conference
Bangalore   <DOM Element: roomname at 0x7fcc35275440>   <DOM Element: noseats at 0x7fcc35275560>    <DOM Element: projectorscreen at 0x7fcc35275290>    <DOM Element: videoconf at 0x7fcc352757a0>
Bhubaneswar <DOM Element: roomname at 0x7fcc35262cf8>   <DOM Element: noseats at 0x7fcc374fb6c8>    <DOM Element: projectorscreen at 0x7fcc36579128>    <DOM Element: videoconf at 0x7fcc352756c8>

Here I need to get all proper value from the XML sheet.

A: you have to get the element value by firstChild.nodeValue or firstChild.data of the xml, try this:
def viewbook(request):
    doc = minidom.parse("roomlist.xml")
    staffs = doc.getElementsByTagName("location")
    root = []
    for staff in staffs:
        lname=staff.getAttribute("name");
        roomname=staff.getElementsByTagName("roomname")[0].firstChild.nodeValue.strip()
        seat=staff.getElementsByTagName("noseats")[0].firstChild.nodeValue.strip()
        project=staff.getElementsByTagName("projectorscreen")[0].firstChild.nodeValue.strip()
        video=staff.getElementsByTagName("videoconf")[0].firstChild.nodeValue.strip()

A: Based on what's an example from the docs, node.data is the way you get data from a node that only contains text.
def getText(nodelist):
  rc = [] for node in nodelist:
  if node.nodeType == node.TEXT_NODE:
    rc.append(node.data)
  return "".join(rc)

docs

A: you can get
from xml.dom.minidom import parse
doc = parse("dd.xml")
staffs = doc.getElementsByTagName("location")
root = []
for staff in staffs:
    lname=staff.getAttribute("name");
    roomname=staff.getElementsByTagName("roomname")[0].firstChild.wholeText
    seat=staff.getElementsByTagName("noseats")[0].firstChild.wholeText
    project=staff.getElementsByTagName("projectorscreen")[0].firstChild.wholeText
    video=staff.getElementsByTagName("videoconf")[0].firstChild.wholeText
    root.append({'lname':lname,'roomname':roomname,'seat':seat,'project':project,'video':video})
print root

output
[{'lname': u'Bangalore', 'roomname': u' Aquarius ', 'video': u'yes', 'project': u'yes', 'seat': u' 10 '}, {'lname': u'Bhubaneswar', 'roomname': u'cottage', 'video': u'Yes', 'project': u'Yes', 'seat': u'5'}]


text:
Q: Replace Lamp with Xampp I have installed Lamp. Now I would like to remove it and replace it with Xampp. I'm a bit worried about Apache and MySql. Lamp is located in the var folder, Xampp in the opt folder. What's the correct procedure to do that?

A: LAMP stands for Linux Apache MySql (MariaDB) PHP (Perl, Python) while XAMPP stands for Cross-Platform (X) Apache MariaDB Php Perl. If you're using Ubuntu you can easily uninstall MySQL, PHP, and Apache using apt.
sudo apt-get remove php5 mysql-client mysql-server apache2

The XAMPP people have a binary you can install from.
UNRELATED:
It's fair to say that it's redundant to use XAMPP as you can achieve the same thing by simply using the packages that are in apt. Simply install Apache, Perl, PHP, and MariaDB and that's XAMPP (You're on "askubuntu" so I'm assuming that you're on Ubuntu. XAMPP is more logical to use if you're using Windows or Mac OS X.
sudo apt-get install php5 perl mariadb-server mariadb-client apache2 # The same thing as XAMPP

As far as graphical interfaces for managing Apache refer to this question.


text:
Q: Textfield material design objective-c How can I show a textfield with material design?
I need this like floating labels without CocoaPods.

A: you have to use two images for custom UITextfield First image for editing UITextfield and second image for not editing image which will be your default custom UITextfield image.
you can achieve this by simply setting first image as a Background image of  UITextfield while editing textFieldDidBeginEditing
set second background image of UITextfield on textFieldShouldEndEditing

A: You can just download & import two files of SkyFloatingLabelTextField.swift and UITextField+fixCaretPosition.swift
Thereafter, associate SkyFloatingLabelTextField class to the textfield where you want such floating.
Download File from this url link:
https://github.com/Skyscanner/SkyFloatingLabelTextField


text:
Q: Custom Share, Login Button for Facebook SDK iOS Im sharing image to Facebook to using Facebook SDK. problem is i dont know how to change those buttons to custom buttons. ex: if i trigger button then it shares with facebook.
here my code. this is the one Facebook give as default
let button : FBSDKShareButton = FBSDKShareButton()
        button.shareContent = content

        self.view.addSubview(button) // how can i trigger with my button
        button.center = self.view.center // i dont want this in center either

A: I found a way of doing this. just need to hide the button that FBSDK gives and insert following code in action button
button.sendActionsForControlEvents(.TouchUpInside)

it will Programmatically fire the SDK button if we click that UIButton

A: What I did to customize the FBSDKLoginButton view is add a view in the interface builder and changed its class to FBSDKLoginButton, then I added a subView in it then customized it in the way I want.
what happens is that the Facebook SDK will always add a subView on top on all views in the view of type FBSDKLoginButton, so I took an outlet of the view which has the type FBSDKLoginButton and in viewDidLoad function I added this line of code:
facebookLoginButton.subviews[facebookLoginButton.subviews.count-1].removeFromSuperview()

I think it's the same principle for the share button.


text:
Q: Heroku & Rails - Varnish HTTP Cache Not Working My heroku website's root page is essentially static, it has some ruby code in the view when its generated, but there's nothing specific to a single user, so I'd like to have it cached by Varnish and served up without hitting my dyno (note that there are other pages that are dynamic in the application).
Heroku makes it seem very simple here. Just add  response.headers['Cache-Control'] = 'public, max-age=300' and it'll cache for 5 minutes before regenerating.
To test this I made the changed and outputted the date (Time.now) to the page, to see if it would remain the same for 5 minutes, but every time I access the page on a new browser it updates. Refreshing on the same browser works fine, but I think that's because of the browser caching, not Heroku.
If it's any help, when I do a curl -i to get the HTTP headers, I get this:
HTTP/1.1 200 OK^M
Server: nginx/0.7.67^M
Date: Thu, 29 Dec 2011 02:03:33 GMT^M
Content-Type: text/html; charset=utf-8^M
Connection: keep-alive^M
Cache-Control: public, max-age=300^M
X-Ua-Compatible: IE=Edge^M
Etag: "8a1b58f048968803980417a2914764d0"^M
X-Runtime: 0.038393^M
Content-Length: 8310^M
X-Varnish: 1040651825^M
Age: 0^M
Via: 1.1 varnish^M

Basically, I'd like to make sure that it's generated once and then cached in Varnish, am I missing any options, do I have to configure something more? If you have other suggestions for serving a fast static page I'd love those as well.
Thanks!

A: I beleive that there is something in your application causing this issue (possibly the headers aren't being set correctly?).
To test this I put up an application that contains one cached, and one un-cached page (nothing other than rendering the text to the output.
http://morning-earth-1972.heroku.com/base/cache
http://morning-earth-1972.heroku.com/base/no_cache
Notice that the cache version will not change within five minutes of the time printed.
The source can be found here:  https://github.com/neilmiddleton/heroku_varnish_test_SO_8663326
Therefore, Heroku is working as you would expect.  I would initially look at your auth system to check that that isn't doing something, as this is quite a common scenario (to ensure that cached pages are fully secured)

A: Maybe you are sending cookies when testing with your browser ? What are your request headers ?
What do you get if your run curl -I http://host.com/ twice ?

A: The problem turned out to be that Heroku has a number of Varnish servers, so it takes about 10-15 page refreshes until the page was cached on all of the servers, after that it would stay cached. It was working all along, I just gave up after a few refreshes didn't work.
I also increased the max_age so that I could see it more clearly, a 5 minute cache has almost no effect.


text:
Q: Expected class, delegate, enum, interface, or struct (CS1518) simple code here and the answers I find don't seem to work.
I'm using
SharpDevelop Version : 3.2.1.6466
.NET Version         : 2.0.50727.5485
The problem is the error code
Expected class, delegate, enum, interface, or struct (CS1518).
Any ideas?
Program.cs codes:
using System;
using System.Threading;

namespace Threshold
{
public class Class1
{
    public Class1()
    {
        Heritage YOLO = new Heritage();
        YOLO.Fractal();
    }
}
    static void Main()
    {
       //do nothing
    }
}

The cs file it calls is:
using System;
using System.Threading;

namespace Threshold
{
public class Heritage
{
int Fractal()
{
    //Do stuff.
}
}

internal partial class DefineConstants
{
    public const string DRIVERPATH = "d:\\tc\\bgi";
}

}

Please help with a fix.
Thanks.

A: Your main method is outside the class. Put it inside.


text:
Q: Prove or disprove: If $f$ is increasing and differentiable on $(a,b)$ then $f'(x)\ge 0$ on $(a,b)$ Here's the question again:

Prove or disprove: If $f$ is increasing and differentiable on $(a,b)$
  then $f'(x)\ge 0$ on $(a,b)$.

I could not find any counterexamples to it so here's my attempt at a proof:
Suppose there is a point $c\in (a,b)$ such that $f'(c)<0$. Let $\varepsilon = - f'(c)/2$. Then there exists a $\delta > 0$ such that $\frac{f(x)-f(c)}{x-c} < f'(c)/2 < 0$ for all $0<|x-c|< \delta $.
Let $x_1 \in (c-\delta , c )$ then $x_1 -c<0$ thus we have that $\frac{f(x_1)-f(c)}{x_1-c} <0$ implies $f(x_1) > f(c)$. Now, let $x_2 \in (c, c+\delta )$ then in a similar way, $f(x_2) < f(c)$. We note that $x_1 < x_2$ but we obtain $f(x_2)< f(c) < f(x_1)$, a contradiction since $f$ is increasing on $(a,b)$.
Is this attempt correct? Could there be any direct proofs?

A: Your proof is correct. A direct proof goes like this:
For any $c\in (a,b)$, since $f$ is differentiable at $c$, we have
$$\lim_{x\to c}\frac{f(x)-f(c)}{x-c}=f'(c).$$
The expression inside the limit is always nonnegative since $f$ is increasing. Thus, the limit has to be nonnegative.

A: Your proof is correct and almost a direct proof, let me rephrase it: Let $x<y$. Then
$ f(y)-f(x) > 0$. Therefore
$$ \frac{f(y) - f(x)}{y-x} > 0.$$
Sending $y\to x$ yields
$$ f'(x) \ge 0.$$


text:
Q: Where does one go if a question is not good enough for Stack Overflow? Stack Site for New Users? I have noticed that many questions get down voted or closed so often it's very intimidating for new users. I understand that Stack Overflow is for high quality questions that are helpful to everyone and not just the OP.
So my question is this:
Is there a list of other sites that are for the basic/trivial questions?
Maybe we have other sites within the Stack family of sites that are more useful for this kind of question? Maybe we don't have a site (might be a good idea to have a Stack site for new users who need basic help and understanding?).
And you may say "Learn the basics first" or "Read the documentation". I find that many users have read the documentation or have searched for documentation with no luck. Maybe they found the documentation but just don't understand what is happening or how to apply the information to their code.
Sometimes it takes a veteran of the language to explain what's going on in order for the new user to understand.
Rather than down voting the user out of existence, maybe leave a link to a help site for basic questions and then have the post locked. Down voting because you think the question is not helpful to Stack Overflow is fine; however you end up scaring off people who might become useful contributors to the Stack family in time.
I propose (if we don't have yet) either a link to a list of useful sites for new users who need basic help or a Stack site to fill that need.
I believe this would kill two birds with one stone. Veteran users will be able to maintain the integrity of Stack Overflow as a high level resource for coders and provide new users with the help they need and guide them to being better coders instead of scaring them off from coding to start with.
I think it would be cool if we had a Stack site where "unworthy" questions could be asked and users could be helped by people who want to help with those kind of question.
Edit: rephrasing as this is being taking wrong:
I see many questions being down voted (rightfully) but also seeing rude/negative comments on the OP's question. Sometimes indirectly rude, sometimes more to the point.
EDIT:
After reading and responding to many comments I read a comment that basically sums up why my question is not valid in this context. I do not want to delete my question as I believe others will find it and come to the same conclusion I have with reading this single comment.
Thanks to fbueckert I have now a clear understanding of what SO is. As I came to StackOverflow believing it was one of the many Q&A sites for programmers turns out I was wrong (more often than I would like to admit).
This sums up what for me is the answer for my question:

SE is not for learning, in the tutorial or teaching sense. It's meant to create a repository of knowledge. If you're trying to learn a topic, this isn't the place to start.

A: There is endless guidance on how to actually ask a good question, that is on topic.
That is the Learning you mentioned.
An unworthy site, if you think about it, would be the worst of all worlds. It would attract terrible questions, and so you would not get high quality answers or answerers.

A: If a question cannot be edited by others to be made useful to more than one person, it's not worth the time it takes to edit or answer. This is a basic economic reality: one-on-one tutoring is vastly less cost-effective than compiling general teaching material, because it costs the same (or sometimes slightly less) but benefits many fewer people.
So no, there is not likely to ever be any site, Stack Exchange or otherwise, that can do this. If you want one-on-one tutoring for programming, try something like HackHands (disclaimer: I am registered as an expert there), and pay real money-dollars for it, to the tune of $60/hour or more. Expecting a site to provide that kind of value for free is just unrealistic.
All that said, it is often possible for a poorly-written question to be fixed up as long as there's something there to work with. For example. If a question can't be fixed, consider how terrible it must be by comparison.


text:
Q: How do I make the indoor svg drawing for OSM Buildings? How do I make the indoor svg drawing?
I could not find the source.
Can you tell me how to do?
http://osmbuildings.org/examples/indoor/

A: The source can be found at http://osmbuildings.org/download.php and at the GitHub project page.


text:
Q: Evaluate $\sum_{r=0}^{100} {(-1)^{r} {100 \choose r} {r^{50}}}$ The problem is to the evaluate the following sum:
$$\sum_{r=0}^{100} {(-1)^{r} {100 \choose r} {r^{50}}}$$
I don't see how I can get started on this, since the function attached to the combination is polynomial, not an exponential.
I also tried to look for a combinatorial approach, using the inclusion exclusion principle. I guess it can be interpreted as the arrangement of 100 distinct items in 50 places, however the answer doesn't seem to be correct.
Would love some help on this one!

A: HINT:
You can show that for any $0\le k \le 50$ we have
$$\sum_{r\ge 0} (-1)^r \binom{100}{r}\cdot \binom{r}{k} = 0$$
Then check that you can write $r^{50}$ uniformly in $r$ as a linear combination of $\binom{r}{k}$ for $0\le k \le 50$.

A: Evaluating
$$\sum_{r=0}^{2n} (-1)^r {2n\choose r} r^n$$
we find
$$\sum_{r=0}^{2n} (-1)^r {2n\choose r} n! [z^n] \exp(rz)
\\ = n! [z^n] \sum_{r=0}^{2n} (-1)^r {2n\choose r} \exp(rz)
\\ = n! [z^n] (1-\exp(z))^{2n}$$
Note however that $1-\exp(z) = - z + \cdots$ and hence $(1-\exp(z))^{2n}$
starts with $z^{2n}$, showing that the sum is zero.


text:
Q: How to check if datatable has any row containing a string and get row index of it I have a table in my html with columns username and password. how can I get index of the row which has username="abc" using jquery in my javascript?
var myTable = document.getElementById('usersTable');

A: Use filter() function. Don't use :contains if you are looking for exact match.
$allRows = $('#usersTable tr');
row = $allRows.filter(function(){
    return $.trim($(this).find('td').eq(INDEX_OF_USERNAME_COLUMN).text()) == "abc";
});
index = $allRows.index(row);


text:
Q: Singular homogeneous polynomial Let $p$ be a homogeneous polynomial in $\mathbb{K}[x_1, \dots, x_n]$,
where $\mathbb{K}$ is an algebraically closed field. If $\frac{\partial p}{\partial x_1}, \dots, \frac{\partial p}{\partial x_1}$
vanishes on the vanishing set of $p$,
is it true that $p$ is a product of linear forms?

A: No: take $n=3$, $\operatorname{char}(\mathbb K)=5$  and $p=y^{10}z^{5}-x^{15}= (y^2z-x^3)^5$ .
More general counterexamples
Over any field $k$, of any characteristic, algebraically closed or not, take a homogeneous irreducible polynomial $f\in k[x_1,...,x_n]$ of degree at least $2$.
Then $p=f^2$ (or any higher power of $f$) will give a counterexample.
Remark
Over an algebraically closed field $\mathbb K$ of any characteristic it is impossible that all the partial derivatives $\frac {\partial p}{\partial x_i}$  of an irreducible polynomial $p$ vanish on $V(p)$, the vanishing locus of $p$.
This is the geometric fact that the singularities of the variety $V(p)\subset \mathbb P^{n-1}$ form a strict closed subset $\operatorname {Sing}V(p)\subsetneq V(p)$ of that variety: Hartshorne page 33.