text:
Q: How to use Google.Apis.Analytics.v3 API with vb.net service app I have managed to autenticate my self succesfully to google etc. but now I need help how to use Google.Apis.Analytics.v3 or Google.Apis.Analytics.v3.Data dll to retrive data. for example I need last month vistors. So far I have this:
Imports System.Security.Cryptography.X509Certificates
Imports System.Threading
Imports Google.Apis.Auth.OAuth2
Imports MailBee
Imports MailBee.ImapMail
Imports MailBee.SmtpMail
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Imports Google.Apis.Analytics.v3
Imports Google.Apis.Analytics.v3.Data
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Services
Imports Google.Apis.Util

Public Class gaimport

    Inherits System.Web.UI.Page

    Public Shared Sub Main(sender As Object, e As EventArgs)
        Dim serviceAccountEmail As String = "xxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com"
        Dim userEmail As String = "xxxxx@gmail.com"

        Dim certificate As New X509Certificate2("c:\works\gaimport\gaimport\Analyticsdata-xxxxxxxxxxxx.p12", _
            "notasecret", X509KeyStorageFlags.Exportable)

        Dim credential As New ServiceAccountCredential( _
            New ServiceAccountCredential.Initializer(serviceAccountEmail) With { _
            .Scopes = New String() {"https://www.googleapis.com/auth/analytics.readonly"} _
        }.FromCertificate(certificate))

        If credential.RequestAccessTokenAsync(CancellationToken.None).Result Then
            Dim xoauthKey As String = OAuth2.GetXOAuthKeyStatic(userEmail, credential.Token.AccessToken)

            Console.WriteLine("test" & xoauthKey)

        End If

    End Sub

End Class

Now I need somehing to get analytics part working. how do I use Those dll? Can I reguest feed from google (like i didi with clientId logins)?

A: I found a good traight forfard solution to my case (after getting acces token):
Dim webClient As New System.Net.WebClient
webClient.Encoding = System.Text.Encoding.UTF8
Dim requesturl = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A" & domainidid(domainrno) & "&start-date=" & viimekuunalkuset & "&end-date=" & viimekuunloppuset & "&metrics=ga%3Ausers%2Cga%3Asessions%2Cga%3Apageviews&access_token=" & credential.Token.AccessToken

Dim resultb As String = webClient.DownloadString(requesturl)

Then I just handeled JSON to get what I really wanted to get:
Dim myJ = JObject.Parse(resultb)
                Dim totalsForAllResults = Convert.ToInt32(myJ("totalsForAllResults")("ga:sessions"))
                Dim totalsForAllResultsusers = Convert.ToInt32(myJ("totalsForAllResults")("ga:users"))
                Dim totalsForAllResultspgw = Convert.ToInt32(myJ("totalsForAllResults")("ga:pageviews"))


text:
Q: Creating internationalized standard javax.validation error messages I have a small requirement of writing standardized, internationalized javax.validation error messages in this format
@NotNull
private String name;
@Max(10)
private int age;
Then in this case the error message should prop up as
"The field name is not null"
"The field age is not greater than or equal to 10"
How can I achieve this in a more dynamic way instead of hard-coding the message or variable name inside the annotation.

A: @NotNull(message = "{errors.name.missing.msg}")
private String name;

define the value for errors.name.missing.msg in messages.properties (which should be available in your classpath)
You can also make it locale specific by placing it in locale specific property files say in messages_en.properties and messages_fr.properties for i18n.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a single verb that means "to label items in a list with letters"? What SINGLE verb means to list with LETTERS, such as the following?
I seek only 1  SINGLE verb; please exclude verb phrases, verbs containing > 1 word,
and 'to enumerate' itself (it's not precise enough; it can mean 'to number' with numerals or letters).

a)
  b)
  c) ...

A: I would still use 'enumerate'. While it does contain the same root as 'number', what it actually means is "to mention separately as if in counting; name one by one; specify, as in a list." It doesn't specify specifically a numbered list.
You could also just use 'list'.

A: With no context, I don't know of a verb that distinguishes making a list of items with alphabetical labels from a list with numerical labels. The action is creating the list, so most verbs are distinguishing the method of listing not of labeling. How you label the list has so many possibilities that we typically use an adjective to describe the type of list we've created. For example, there are bullet lists, numbered lists, etc.
Some style guides might have names for different types of labeled lists. I'd have to do some research to find out and if you must have a verb, it wouldn't be useful to you.


text:
Q: Is using fold less efficient than standard recursion I'm going through the Learn You a Haskell book right now and I'm curious about how this particular example works.  The book first demonstrates an implementation of findKey using traditional recursion:
findKey :: (Eq k) => k -> [(k,v)] -> Maybe v
findKey key [] = Nothing
findKey key ((k,v):xs) = if key == k
                            then Just v
                            else findKey key xs

The book then follows up with a shorter implementation using foldr
findKey :: (Eq k) => k -> [(k,v)] -> Maybe v
findKey key = foldr (\(k,v) acc -> if key == k then Just v else acc) Nothing

With the standard recursion, the function should immediately return once it hits the first element with the provided key.  If I understand the foldr implementation correctly, it will iterate over the entire list every time, even if it matched the first element it came across.  That doesn't seem like a very efficient way to handle the problem.
Is there something I'm not getting about how the foldr implementation works?  Or is there some kind of magic within Haskell that makes this implementation not quite as inefficient as I think it is?

A:
If I understand the foldr implementation correctly, it will iterate over the entire list every time, even if it matched the first element it came across.

This is wrong. foldr will evaluate the list only as much as needed.
E.g.
foldr (&&) True [True, False, error "unreached code here"]

returns False since the error is never evaluated, precisely as in
(True && (False && (error "unreached code here" && True)))

Indeed, since the end of the list is never reached, we can also write
foldr (&&) (error "end") [True, False, error "unreached code here"]

and still obtain False.

A: Here is code which demonstrates that foldr does indeed "short-circuit" the evaluation of findKey:
import Debug.Trace

findKey :: (Eq k) => k -> [(k,v)] -> Maybe v
findKey key = foldr (\(k,v) acc -> if key == k then Just v else acc) Nothing

tr x = trace msg x
  where msg = "=== at: " ++ show x

thelist = [ tr (1,'a'), tr (2,'b'), tr (3, 'c'), tr (4, 'd') ]

An example of running findKey in ghci:
*Main> findKey 2 thelist
=== at: (1,'a')
=== at: (2,'b')
Just 'b'
*Main>

A: Think of foldr using the following definition (using standard recursion):
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f e [] = e
foldr f e (x:xs) = f x (foldr f e xs)

The third line shows that the second implementation for findKey will return upon finding the first match.

As a sidenote: assume you had the following definition (which does not have identical functionality) for findKey (as an exercise you might want to rewrite the definition using foldr):
findKey :: (Eq k) => k -> [(k,v)] -> [v]
findKey key [] = []
findKey key ((kHead, vHead):rest) = if (key == kHead) then vHead:(findKey key rest) else findKey key rest

Now you might think that this would iterate through the whole input list. Depending on how you invoke this function, it could be the case that it iterates through the whole list, but at the same time this can give you the first match efficiently too. Due to Haskell's lazy evaluation the following code:
head (findKey key li)

will give you the first match (assuming that there's one) with the same efficiency as your first example.

A: foldr f z [a,b,c,...,n]                   ==
a `f` (b `f` (c `f` (... (n `f` z) ...))) ==
f a (foldr f z [b,c,...,n])               ==
f a acc   where   acc = foldr f z [b,c,...,n]

So if your f returns before forcing acc, acc remains not forced, i.e. no part of the list argument beyond its head element a is accessed, like e.g. when you have
f a acc = ...

If, on the other hand, your f does force its second argument, e.g. if it's defined as
f a (x:xs) = ...

then the acc is forced before f starts its work, and the list will be accessed in whole before the processing begins -- in whole, because acc = f b acc2 and that invocation of f must force its second argument, acc2, so its value, acc, can be forced (pattern-matched with (x:xs), that is); and so forth.

A: *

*foldr is written using standard recursion.

*The recursive call to foldr is hidden inside of acc. If your code doesn't use acc, it will never be computed (because Haskell is lazy). So the foldr version is efficient and will also return early.
Here's an example demonstrating this:
Prelude> foldr (\x z -> "done") "acc" [0 ..]
"done"

This expression returns "done" immediately, even though the input list is infinitely long.

If foldr is defined as:
foldr f z (x : xs) = f x (foldr f z xs)
foldr _ z [] = z

, then evaluation goes via
f x (foldr f z xs)
    where
    f = \x z -> "done"
    x = 0
    z = "acc"
    xs = ...  -- unevaluated, but is [1 ..]

which is
(\x z -> "done") 0 (foldr (\x z -> "done") "acc" [1 ..])

which turns into "done" because the first function doesn't use z, so the recursive call is never needed.


text:
Q: Date difference in PHP to update the mysql db I am trying to log the time difference in a mysql-field and when I try on screen the values are correct. After submitting the field to the database the field is empty.
Where do I go wrong?
The field is declared in mysql as timestamp and format current_timestamp.
The code:
$strStart = date("Y-m-d H:i:s");
sleep(5);
$strEnd   = date("Y-m-d H:i:s");
$dteStart = new DateTime($strStart);
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
//$calc = $dteDiff->format("YYYY-%M-%D %H:%I:%S");
$calc = $dteDiff->format("%Y%Y-%M-%D %H:%I:%S");
echo "Difference: " . $calc;

I am submitting the $calc to the db.

A: As MySQL dates have a minimum value of '1000-01-01 00:00:00', you cannot store this value ('0000-00-00 00:00:05 for 5 seconds) as a date/time value.... nor should you, because it isn't a date/time..... date/time is a fixed point in time, not an interval, which is the period between 2 date/times. There is no specific datatype for a date interval.
I would suggest storing the actual date/time value rather than the interval, and only calculating the interval when you need to do so.
Alternatively, if you must store the interval itself, then store a number of seconds as a float rather than trying to force it into a formatted an inappropriate datatype; so store 5.0 seconds instead.


text:
Q: Segmentation Fault when installing my package with pip3 I am currently trying to install my own package using the command: pip3 install --user ., which invokes this setup script. However, when I do that, I get the following output:
cherrybomb@cherrybomb:~/cherrybomb$ pip3 install --user .
Processing /home/cherrybomb/cherrybomb
Collecting twisted>=17.9.0 (from cherrybomb==0.1.0)
Collecting pyopenssl>=17.5.0 (from cherrybomb==0.1.0)
  Using cached pyOpenSSL-17.5.0-py2.py3-none-any.whl
Collecting wheel>=0.30.0 (from cherrybomb==0.1.0)
  Using cached wheel-0.30.0-py2.py3-none-any.whl
Collecting hyperlink>=17.1.1 (from twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached hyperlink-17.3.1-py2.py3-none-any.whl
Collecting constantly>=15.1 (from twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached constantly-15.1.0-py2.py3-none-any.whl
Collecting Automat>=0.3.0 (from twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached Automat-0.6.0-py2.py3-none-any.whl
Collecting incremental>=16.10.1 (from twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached incremental-17.5.0-py2.py3-none-any.whl
Collecting zope.interface>=4.0.2 (from twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached zope.interface-4.4.3-cp36-cp36m-manylinux1_x86_64.whl
Collecting cryptography>=2.1.4 (from pyopenssl>=17.5.0->cherrybomb==0.1.0)
  Using cached cryptography-2.1.4-cp36-cp36m-manylinux1_x86_64.whl
Collecting six>=1.5.2 (from pyopenssl>=17.5.0->cherrybomb==0.1.0)
  Using cached six-1.11.0-py2.py3-none-any.whl
Collecting attrs (from Automat>=0.3.0->twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached attrs-17.3.0-py2.py3-none-any.whl
Collecting setuptools (from zope.interface>=4.0.2->twisted>=17.9.0->cherrybomb==0.1.0)
  Using cached setuptools-38.2.5-py2.py3-none-any.whl
Collecting cffi>=1.7; platform_python_implementation != "PyPy" (from cryptography>=2.1.4->pyopenssl>=17.5.0->cherrybomb==0.1.0)
  Using cached cffi-1.11.2-cp36-cp36m-manylinux1_x86_64.whl
Collecting idna>=2.1 (from cryptography>=2.1.4->pyopenssl>=17.5.0->cherrybomb==0.1.0)
  Using cached idna-2.6-py2.py3-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography>=2.1.4->pyopenssl>=17.5.0->cherrybomb==0.1.0)
  Using cached asn1crypto-0.24.0-py2.py3-none-any.whl
Collecting pycparser (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=2.1.4->pyopenssl>=17.5.0->cherrybomb==0.1.0)
Installing collected packages: hyperlink, constantly, six, attrs, Automat, incremental, setuptools, zope.interface, twisted, pycparser, cffi, idna, asn1crypto, cryptography, pyopenssl, wheel, cherrybomb
  Running setup.py install for cherrybomb ... error
    Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-8wz3oeu9-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-mxvris8y-record/install-record.txt --single-version-externally-managed --compile --user --prefix=:

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-8wz3oeu9-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-mxvris8y-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code -11 in /tmp/pip-8wz3oeu9-build/
Segmentation fault (core dumped)
cherrybomb@cherrybomb:~/cherrybomb$

I am installing this on ubuntu 17.10 x64:
cherrybomb@cherrybomb:~/cherrybomb$ uname -a
Linux cherrybomb 4.13.0-16-generic #19-Ubuntu SMP Wed Oct 11 18:35:14 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
cherrybomb@cherrybomb:~/cherrybomb$ python3.6 --version
Python 3.6.3
cherrybomb@cherrybomb:~/cherrybomb$

Any insight into what I'm doing wrong would be much appreciated. Thank you and have a great day!

A: Though this seems to be an old issue I hope leaving a reply here may be of help.
Try with sudo !!. If you weren't inside a virtual environment, maybe you didn't had the necessary privileges to install the packages system wide.


text:
Q: Where can I find updated source code for Jorge Acetozi book "Continuous Delivery for Java Apps: Kubernetes and Jenkins in Practice" I just started reading the Jorge Acetozi book "Continuous Delivery for Java Apps: Kubernetes and Jenkins in Practice".
For the code examples I use the source code in his github repository:
https://github.com/jorgeacetozi
Unfortunately this code doesn't work for Java 11 and uses old Spring Boot 1.5 version
Also Jenkins, Selenium, Kubernetes and Vagrant tools, described in the book, use very old versions.
Has anyone finished this book lately, could you please, provide the updated source code for this book?
Unfortunately, the old source code, prevents me from learning further.

A: I have managed to finish this book, but did a lot of changes to the source code:

*

*https://github.com/skyglass/notepad - updated source code for Notepad Spring Boot application.

*

*Spring Boot has been updated to version 2.4.2.

*I had to make lots of changes to the front-end code, to make styles displayed correctly with the latest version of Thymeleaf library.

*Also did some other changes, related to update from Java8 to Java11.

*All maven dependencies have been updated to the latest versions

*https://github.com/skyglass/jenkins-kubernetes-cd - This repository corresponds to Jorge Acetozi's "ebook-continuous-delivery-with-kubernetes-and-jenkins" repository.

*

*"docker-images" folder contain "jenkins", "kubectl" and "maven-jdk11-git" docker image files, which are used by Jenkins pipelines

*Kubernetes yaml files have been updated to the latest version of Kubernetes

*Unfortunately, I couldn't manage to make acceptance tests working for "Firefox" browser, with the latest "Selenium Grid" docker images. Therefore, acceptance-tests pipeline code only contains tests with "Chrome" browser

*All Jenkins files have been updated to use the latest docker images, or custom docker images, published by me in Skyglass Docker Hub. Feel free to publish them in your own docker hub, using docker files from "docker-images" folder.

*"docker-images" folder contains custom docker image to run Jenkins. I recommend using this image to run Jenkins on your computer. It uses the latest version of jenkins for jdk11 and all needed plugins with the latest versions

*https://github.com/skyglass/notepad-performance-tests - the performance tests have been updated for the latest versions of Scala, SBT and Gatling.

*https://tferdinand.net/en/create-a-local-kubernetes-cluster-with-vagrant/
https://www.exxactcorp.com/blog/HPC/building-a-kubernetes-cluster-using-vagrant

*

*These articles will help you to install Kubernetes Cluster locally, with Vagrant and VirtualBox.

Of course, I also used lot of other online resources. StackOverflow helped me a lot. :)
Have fun reading this book, hope these examples help you get the best learning experience.
Thank you, Jorge Acetozi, for this wonderful book!


text:
Q: Can i have grub installed on live usb? It's annoying that with grub installed on the laptop itself, everytime I don't have the Ubuntu live / persistent USB plugged in to boot into Ubuntu, i have to choose windows to boot or else i'll get sent to grub command line...
Is it possible to have grub on the usb so that it only gets activated when I want to boot ubuntu?
Thanks.

A: yea ,use gnome-disks,format disk in gpt,create main part leavin 2mb free space.run fdisk (usb) ,type n and then enters,then w.run parted (usb), set 2 bios_grub on (if it's 2.It's about 2mb partition  ).then deploy linux.then run this stuff `
mount (usbpart1) (mount dir)
grub-mkconfig -o (...)/boot/grub/grub.cfg
grub-install --boot-directory=(...)/boot/ (usb)


text:
Q: representation theory and finite order automorphisms Let $\sigma$ a finite-order automorphism of a finite-dimensional complex simple Lie algebra $g$. Denote the order of sigma by $k$ and fix a $k^{th}$ root of unity $\omega$.
It is well know that $k=1,2 \text{ or } 3$ and that $$g=\oplus_{j\in \mathbb Z_k} g_j$$ where $g_j=\{ x \in g \mid \sigma(x)=\omega^jx\}.$
Moreover, $g_0$ is a simple Lie algebra.
QUESTION: Let $\lambda$ a weight of $g$ and $V(\lambda)$ the irreducible representation of weight $\lambda$. Denote by $V(\lambda)_{g_0}$ the $g_0$-module obtained from $V(\lambda)$ by restricting the action of $g$  to $g_0$. Is $V(\lambda)_{g_0}$ reducible as a $g_0$-module for all $\lambda$?
THANKS,
Note: The results mentioned can be found in the Kac book.

A: Yes if $k=1$. No if $k>1$; the adjoint representation is a counterexample.
For the edited question: isn't the vector representation of SL(n) (and its dual) a counterexample for $k=2$?


text:
Q: how to send objects or dataset in tcpclient connection using C#? i want to transfer an object or a data set from one computer and other i am sending strings using streamwriter and reader now i want send an object via this client connection so how do i send this object or a dataset using this connection ?
Consider i want to send a dataset now what you people suggest

A: I think what you want is to use Remoting. This is a huge topic mind, so heres the place to start: http://msdn.microsoft.com/en-us/library/kwdt6w2k(VS.71).aspx
Now, you can speed the process up of devloping an application to send/recieve data via TCP, and thats by using WCF and the netTcpBinding.  This is the approach I would take nowadays as it's a lot simpler and quicker to develop, plus any knowledge gain can be reused to created various types of web services.
netTcpBinding: http://msdn.microsoft.com/en-us/library/ms731810.aspx
wcf site: http://msdn.microsoft.com/en-us/netframework/aa663324.aspx

A: If you have control over both sender and receiver you could try serialization.
Basic implementation of serializing and deserializing

A: If the class definition for the object you want to send is accessible to both the client and server - say, defined in a common class library - you can serialize it to binary data, send it over the connection, and deserialize it. Serializable classes are pretty easy to get into and out of binary, XML and JSON formats.
See http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=209
I haven't tried this with a dataset, but I don't foresee any problems. You may also consider serializing to XML if your application requires it - for instance, if you're communicating with a non-.net application on another platform.
Note: Josiah Peters' linked example code seems much cleaner than the link I referenced.


text:
Q: ¿Cómo editar una variable especifica dentro de un struct (c)? Soy nuevo en c y estoy intentado de realizar un programa para una biblioteca que consiste en guardar una data.csv en un struct para poder trabajar con ella con distintas funciones, como buscar un libro y ver su información: ubicación, autor, año.
También quiero que el programa deje editar información del libro, donde el usuario coloca el nombre del libro que desee editar y lo que desee editar.
#include "header.h"

void main(libros biblioteca[], int numb_rows)
{
    char book[200];
    char edit[200];
    int opcion3, a, found;

    p("Ingresa el nombre del libro que deseas editar: \n");
    fflush(stdin);
    scanf("%[^\n]", book);
    for (int i = 0; i < numb_rows; i++)
    {
        if (strcmp(book, biblioteca[i].titulo) == 0)
        {
            p("No se encuentra el libro. \n");
            found = 1;
            a = i;
        }
        else
        {
            p("No se encuentra el libro. \n");
        }
    }

        if (found == 1)
        {

            p("Que informacion desea editar\n\n");
            p("[1]     Autor. \n");
            p("[2]     Titulo. \n");
            p("[3]     Anio. \n");
            p("Seleccione una opcion: ");
            s("%d", &opcion3);
            p("/n");

            switch (opcion3)
            {

                case 1:
                {
                    p("Ingrese el autor.\n");
                    scanf("%c", edit);
                    strcpy(biblioteca[a].autor, edit);
                }
                case 2:
                {
                    p("Ingrese titulo.\n");
                    scanf("%c", edit);
                    strcpy(biblioteca[a].titulo, edit);
                }
                case 3:
                {
                    p("Ingrese anio. \n");
                    scanf("%c", edit);
                    strcpy(biblioteca[a].anio, edit);
                }
            }
        }
}

En el header.h se debería encontrar el struct y las otras funciones del programa, el código me tira el error de Segmentation fault. Que estaré haciendo mal?
Pd: Libros es el struct principal y Biblioteca es donde se guardan los datos después de haber leído el csv.

A: Le hice unos cambios a tu codigo, a la variable found le faltaba iniciar en cero de manera que si no se encuentra el libro, este valor indica que no ha sido encontrado, en caso contrario (con valor 1) indica que si fue encontrado, el otro error que tenia era que tratabas de ingresar un string usando un especificador para caractrer scanf("%c", edit); asi que despues de la correccion quedo asi scanf("%s", edit); con estos cambios el codigo deberia funcionar.
#include "header.h"

void main(libros biblioteca[], int numb_rows){
    char book[200];
    char edit[200];
    int opcion3, a, found = 0;

    p("Ingresa el nombre del libro que deseas editar: \n");
    fflush(stdin);
    scanf("%[^\n]", book);

    for(int i = 0; i < numb_rows; i++){
        if(strcmp(book, biblioteca[i].titulo) == 0){
            found = 1;
            a = i;
            break;
        }
    }

    if(found == 1){
        p("Que informacion desea editar\n\n");
        p("[1]     Autor. \n");
        p("[2]     Titulo. \n");
        p("[3]     Anio. \n");
        p("Seleccione una opcion: ");
        s("%d", &opcion3);
        p("/n");

        switch(opcion3){
            case 1:
                p("Ingrese el autor.\n");
                scanf("%s", edit);
                strcpy(biblioteca[a].autor, edit);
                break;
            case 2:
                p("Ingrese titulo.\n");
                scanf("%s", edit);
                strcpy(biblioteca[a].titulo, edit);
                break;
            case 3:
                p("Ingrese anio.\n");
                scanf("%s", edit);
                strcpy(biblioteca[a].anio, edit);
                break;
            default:
                printf("Opcion invalida.\n");
                break;
        }
    }else{
        p("No se encuentra el libro.\n");
    }
}


text:
Q: Overcome out of memory Error when loading images into textview Sorry if this sound newb but.. =[
Im working with an application which need to load a large amount of images onto a textview, i didnt use webview becuz sometimes it doesnt lead to mobile view so i decide to parse the content and use html.fromHtml to show it to the Textview.
Problem is:
if i load a page is luckily there not much images, it run pretty smooth.
otherwise it get the error like below...
anyone know if theres a way that i can dispose the source from the system memory after it finished reading the image?...or...any other way will fix my problem?
i used the source from here Android ImageGetter images overlapping text
    05-08 21:30:31.404: ERROR/dalvikvm-heap(25083): Out of memory on a 1920016-byte allocation.
    05-08 21:30:31.404: ERROR/AndroidRuntime(25083): FATAL EXCEPTION: AsyncTask #10
    java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:299)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    at java.lang.Thread.run(Thread.java:856)
    Caused by: java.lang.OutOfMemoryError
    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:527)
    at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:353)
    at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:781)
    at android.graphics.drawable.Drawable.createFromStream(Drawable.java:741)
    at com.vilalab.five.model.URLImageParser$ImageGetterAsyncTask.fetchDrawable(URLImageParser.java:90)
    at com.vilalab.five.model.URLImageParser$ImageGetterAsyncTask.doInBackground(URLImageParser.java:58)
    at com.vilalab.five.model.URLImageParser$ImageGetterAsyncTask.doInBackground(URLImageParser.java:48)
    at android.os.AsyncTask$2.call(AsyncTask.java:287)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    ... 4 more
   05-08 21:30:31.504: ERROR/dalvikvm-heap(25083): Out of memory on a 1920016-byte allocation.

A: Check out this post, it uses the example of getting picutres from the SD Card/Gallery for how to downsample images so that you avoid this problem. Its a pretty easy fix.


text:
Q: Kate: windows (instances) with different tabs, drag tabs to new window I want Kate's tabs to behave as in almost all other tabbed programs I use:

*

*When I open a new window, it opens in a new instance, without duplicating tabs from other open windows

*When I close a tab in a window, it is only closed in that window (not across all windows)

*When I drag a tab out of the window, a new window with that tab is opened

*When I drag a tab out of the window to another window, the tab is moved to that other window

I do not seem to be alone in that (see reddit question here, KDE forums question here), but I have not found an answer yet. Is it straight up impossible? Because it's the reason I stopped using Kate previously, and I'd like to give it another try.
I'm on (K)ubuntu 22.04, using Kate 21.12.3.


text:
Q: Using registerColumntype for hibernate to use mediumtext in MySQL I encountered the following error when trying to insert content to MySQL using hibernate, the error is due to one of the columns being a "mediumtext" data type in MysQL, but in my entity class I declare the field as String.
Initial sessionFactory creation failed.org.hibernate.HibernateException: Wrong column type in db_test.articles for column content. Found: mediumtext, expected: varchar(255)
Exception in thread "main" java.lang.ExceptionInInitializerError

I have found some posts on google search, and have copied the following class into my "src/main/java/persistence directory:
public class MySQLDialect extends org.hibernate.dialect.MySQLDialect
{
    public MySQLDialect()
    {
        super();
        System.out.println("MyMySQLDialect created new instance!");
    }

    protected void registerVarcharTypes() {
        System.out.println("MyMySQLDialect: registering VarCharTypes");
        registerColumnType(Types.VARCHAR, 16777215, "mediumtext");
        registerColumnType(Types.VARCHAR, 65535, "text");
        registerColumnType(Types.VARCHAR, 255, "varchar($1)");
        registerColumnType(Types.LONGNVARCHAR, "longtext");
    }
}

but I don't know how to let Hibernate know this custom data type. thanks

A: I solved my problem by using "columndefinition = mediumtext", because I figured out to use the "update" feature in Hibernate to automatically update MySQL column data types. Everything works now.


text:
Q: Firebase - Inserting unique username in firebase database on Android This is first time i am working with Firebase on Android. I am trying to insert unique username in firebase database. That means if the username is already exist then it will not be inserted. My database structure is users->uid->uid:value, username:value .
My database structure is given here -
{   "users" : {
    "23fcdc28-3d98-4f9a-804f-63e221d78d67" : {
      "uid" : "23fcdc28-3d98-4f9a-804f-63e221d78d67",
      "username" : "bbb"
    },
    "2d72161c-6164-45ea-b1fc-0965b838bf08" : {
      "uid" : "2d72161c-6164-45ea-b1fc-0965b838bf08",
      "username" : "tazimete"
    },
    "751d5c88-ce14-4931-9c79-4eae387878bb" : {
      "uid" : "751d5c88-ce14-4931-9c79-4eae387878bb",
      "username" : "aaa"
    }   } }

And the rules for the database structure is given here
{
    "rules": {
        ".read": true,
        ".write": true,
        "users": {
          "$uid": {
            ".read": true,
            ".write": true,
            "$username": {
                ".read": true,
                ".write": true,
                ".validate": "root.child('users').child($uid).child($username).val() !== newData.child('username').val()"
            }
          }
      }    } }

But its not working. I am trying to solve it by putting rules on admin panel. but if you have any other idea, please share with me with code. Thanks.


text:
Q: Warning: `value` prop on `input` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components React keeps giving me this "Warning" (which registers as an error in the console) whenever I click on the edit row section of the material table. I understand the Warning is happening because there are some parameters of the table that are left undefined and therefore being logged as null. I am wondering how can I avoid this situation please see the code below. My components are uncontrolled as the user can type in the columns of a particular row of material table.
data={props.devices}
                editable={{
                    onRowUpdate: (newData, oldData) =>
                        new Promise((resolve, reject) => {
                            setTimeout(() => {
                                const index = oldData.tableData.id;
                                let newArr = [...props.devices];
                                newArr[index] = newData;

                                setParts(newArr);
                                updatePart(newData, newData.device);
                                resolve();
                            }, 1000);
                        }),

Here is the full error:
index.js:1 Warning: `value` prop on `input` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.
    in input (created by ForwardRef(InputBase))
    in div (created by ForwardRef(InputBase))
    in ForwardRef(InputBase) (created by WithStyles(ForwardRef(InputBase)))
    in WithStyles(ForwardRef(InputBase)) (created by ForwardRef(Input))
    in ForwardRef(Input) (created by WithStyles(ForwardRef(Input)))
    in WithStyles(ForwardRef(Input)) (created by ForwardRef(TextField))
    in div (created by ForwardRef(FormControl))
    in ForwardRef(FormControl) (created by WithStyles(ForwardRef(FormControl)))
    in WithStyles(ForwardRef(FormControl)) (created by ForwardRef(TextField))
    in ForwardRef(TextField) (created by WithStyles(ForwardRef(TextField)))
    in WithStyles(ForwardRef(TextField)) (created by MTableEditField)
    in MTableEditField (created by MTableEditRow)
    in td (created by ForwardRef(TableCell))
    in ForwardRef(TableCell) (created by WithStyles(ForwardRef(TableCell)))
    in WithStyles(ForwardRef(TableCell)) (created by MTableEditRow)
    in tr (created by ForwardRef(TableRow))
    in ForwardRef(TableRow) (created by WithStyles(ForwardRef(TableRow)))
    in WithStyles(ForwardRef(TableRow)) (created by MTableEditRow)
    in MTableEditRow (created by MTableBody)
    in tbody (created by ForwardRef(TableBody))
    in ForwardRef(TableBody) (created by WithStyles(ForwardRef(TableBody)))
    in WithStyles(ForwardRef(TableBody)) (created by MTableBody)
    in MTableBody (created by Droppable)
    in table (created by ForwardRef(Table))
    in ForwardRef(Table) (created by WithStyles(ForwardRef(Table)))
    in WithStyles(ForwardRef(Table)) (created by Droppable)
    in div (created by Droppable)
    in div (created by Droppable)
    in div (created by Droppable)
    in Droppable (created by ConnectFunction)
    in ConnectFunction
    in ConnectFunction (created by MaterialTable)
    in div
    in Unknown (created by WithStyles(Component))
    in WithStyles(Component) (created by MaterialTable)
    in div (created by ForwardRef(Paper))
    in ForwardRef(Paper) (created by WithStyles(ForwardRef(Paper)))
    in WithStyles(ForwardRef(Paper)) (created by Container)
    in Container (created by MaterialTable)
    in Provider (created by App)
    in App (created by ErrorBoundary)
    in ErrorBoundary (created by DragDropContext)
    in DragDropContext (created by MaterialTable)
    in MaterialTable
    in Unknown (created by WithStyles(Component))

A: why are you using setTimeOut?
the mui table receives null at first render, so just remove setTimeOut.
and make sure no value is null, if its null replace it with empty string "".


text:
Q: Automated nicely formated book of lyrics from data.frame using markdown, knitr and glue This is the extension  of previous question: Automating the generation of preformated text in Rmarkdown using R. Here's the task:
You have a collection of song lyrics stored in data.frame, the columns of which are: song lyrics (with many \n at the end of each line),  song title, song album, music author, words author,  year, etc...
Now you want to produce automatically a nicely formatted book of this poetry using markdown (or bookdown) and glue packages, which should generate an html of this kind:

 Album name

 Song name

Music: author_music

Words: author_words

lyrics-line1
...
lyrics-lineN

The challenge is that, if you use the code from Automating the generation of preformated text in Rmarkdown using R, it will print all lyrics as one long line:
    lyrics-line\n...\nlyrics-lineN
In other words, is there a way to print lyrics lines (line\n ... \nlyrics-lineN) line by line, rather than one concatenated line ?
This is code can be used to get the lyrics data to play with :
library(data.table); library(magrittr); library(knitr); library(stringr);library(dplyr)
dt <- fread("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/prince_raw_data.csv")
dt <- dt[301:303,2:6] #take three songs only
dt %>% names
dt %>% kable() # just to view the lyrics in your console.

NB: that kable() function  does not replace \n with
, which we would like to.
So if you use it to generate an html of your poetry, you'll have the same problem - instead of a verse with many lines, you'll get one long concatenated line.
PS. One way to circumvent the problem is to split the original text string into many one-line strings (eg. by  using str_split(dt$text, '\n') and then print each line separately using  a for loop. But there should be a better way of printing verses, I hope.

A:
In other words, is there a way to print lyrics lines (line\n ... \nlyrics-lineN) line by line, rather than one concatenated line ?

It's concatenated because that's a markdown rule, which requires two spaces at the end of each line.
My solution is to add raw html tags
 <\pre> around your dt$text to protect them from being parsed by markdown syntax:
(However I notice that
 will render text as code blocks, uh)
```{r echo=FALSE, results='asis'}
for (i in 1:nrow(dt)){
  album = dt$album[i]
  song = dt$song[i]
  lyrics = dt$text[i]

  cat(glue::glue("# {album}\n\n"))
  cat(glue::glue("## {song}\n\n"))
  cat(glue::glue("<pre>{lyrics}</pre>"))
}
```

output
source rmd
Or, replace \n with \n(insert two spaces before \n), without glue:
```{r echo=FALSE, results='asis'}

dt$text <- gsub("\n","  \n",dt$text)

for (i in 1:nrow(dt)){
  cat(paste0("# ",dt$album[i],"\n\n"))
  cat(paste0("## ",dt$song[i],"\n\n"))
  cat(paste0("> ",dt$text[i]))
  cat("\n\n")
}
```


text:
Q: Estimating Weibull density parameters (error: "...initial value in 'vmmin' is not finite") I am trying to estimate the shape and scale of a data set.
I used two different ways and for both I got an error message:
First, I tried by moments using the survey package:
survreg(Surv(all.ws)~1, dist="weibull")

I got the error message:

invalid survival times for this distribution

Second, I tried using fitdistr() function:
fitdistr(all.ws, densfun=dweibull, start=list(scale=1, shape=2))

I got an error message:

Error in optim(x=c(2.2, 2.1,1.9....:
  initial value in 'vmmin' is not finite

What is wrong with what I am doing?

A: A google search "fitdistr Weibull Error" shows this exact question was discussed a year ago on the R-help mailing list: http://r.789695.n4.nabble.com/Problems-with-fitdistr-td1334772.html
Some points from that link:

*

*zeros in your data will cause problems

*use pelwei() function from package lmom

A: I had a similar problem when using fitdistr() with a Beta distribution. In that case both ones and zeros in the data produced this error.
Additionally I found that when the limit argument is used in the fitdistr() call, a different error is produced:
eg (where x is a vector of samples containing a 1.0 or 0):
fitdistr(x, "beta", list(shape1 = 1, shape2 = 0.2),lower=0.001)
   `Error in stats::optim: L-BFGS-B needs finite values of 'fn'`


text:
Q: ReactJs. Get children component I've component wrapper for Bootstrap Panel:
var Panel = React.createClass({
    render: function () {
        return (

                        {this.props.title}

        );
    }
});

How to output to "panel-body" tag "h1" and component "AvailableActions" on example what you can see below?
var PlayerActions = React.createClass({
    render: function () {
        return (
            <Panel title="Actions">

Some description here...

                <AvailableActions></AvailableActions>
            </Panel>
        );
    }
});

A:

    {this.props.children}

A: Seems you need this.props.children
var Panel = React.createClass({
    render: function () {
        return (

                        {this.props.title}

{ this.props.children }

        );
    }
});

Example


text:
Q: App Engine: The API call file.Create() took too long to respond and was cancelled When I try to write to blobstore using the same example provided in the docs (below), it works every time on dev server, but fails 100% of the time on appspot with this error: The API call file.Create() took too long to respond and was cancelled. Googling show that this is a rare issue although some have reported it. Any idea what's going on here?
I'm using Python 2.6 on dev server so that maybe why I'm not seeing this during dev.
from __future__ import with_statement
from google.appengine.api import files

# Create the file
file_name = files.blobstore.create(mime_type='application/octet-stream')

# Open the file and write to it
with files.open(file_name, 'a') as f:
  f.write('data')

# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)

# Get the file's blob key
blob_key = files.blobstore.get_blob_key(file_name)

Traceback:
The API call file.Create() took too long to respond and was cancelled.
Traceback (most recent call last):
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1516, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1510, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1258, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1082, in __call__
    return handler.dispatch()
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 552, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 550, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/main.py", line 43, in get
    file_name = files.blobstore.create(mime_type='text/html')
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/blobstore.py", line 69, in create
    return files._create(_BLOBSTORE_FILESYSTEM, params=params)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/file.py", line 491, in _create
    _make_call('Create', request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/file.py", line 234, in _make_call
    rpc.check_success()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 558, in check_success
    self.__rpc.CheckSuccess()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_rpc.py", line 133, in CheckSuccess
    raise self.exception
DeadlineExceededError: The API call file.Create() took too long to respond and was cancelled.
Saved; key: __appstats__:082400, part: 41 bytes, full: 5691 bytes, overhead: 0.000 + 0.004; link: http://czongae.appspot.com/_ah/stats/details?time=1328696282404
<class 'google.appengine.runtime.apiproxy_errors.DeadlineExceededError'>: The API call file.Create() took too long to respond and was cancelled.
Traceback (most recent call last):
  File "/base/data/home/apps/s~czongae/1.356669185377832769/main.py", line 72, in <module>
    main()
  File "/base/data/home/apps/s~czongae/1.356669185377832769/main.py", line 69, in main
    app.run()
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1595, in run
    _webapp_util.run_wsgi_app(self)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 98, in run_wsgi_app
    run_bare_wsgi_app(add_wsgi_middleware(application))
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 118, in run_bare_wsgi_app
    for data in result:
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/appstats/recording.py", line 924, in appstats_wsgi_wrapper
    result = app(environ, appstats_start_response)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1524, in __call__
    response = self._internal_error(e)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1516, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1510, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1258, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 1082, in __call__
    return handler.dispatch()
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 552, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/webapp2.py", line 550, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~czongae/1.356669185377832769/main.py", line 43, in get
    file_name = files.blobstore.create(mime_type='text/html')
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/blobstore.py", line 69, in create
    return files._create(_BLOBSTORE_FILESYSTEM, params=params)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/file.py", line 491, in _create
    _make_call('Create', request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/files/file.py", line 234, in _make_call
    rpc.check_success()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 558, in check_success
    self.__rpc.CheckSuccess()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_rpc.py", line 133, in CheckSuccess
    raise self.exception

A: It's not documented to the official manual. but try to add exclusive_lock=True when you open the file. During the migration of my blobstore from M/S to HRD I think I had this problem.
http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/api/files/file.py#402
# Open the file and write to it
with files.open(file_name, 'a', exclusive_lock=True) as f:
  f.write('data')


text:
Q: How do I show that the following map is surjective? Helly I have the following problem.

We have $f:T\rightarrow S$ a map an $\mathfrak{R}$ a relation on $S$. We define a relation $\mathfrak{P}$ with $$x~\mathfrak{P}~y \Leftrightarrow f(x)~\mathfrak{R}~f(y)$$Now we assume that $\mathfrak{R}$ is an equivalence relation and we define $$g:T/\mathfrak{P}\rightarrow S/\mathfrak{R};~~~~~T\supset B\mapsto A\subset S~~~s.t.~~~f(B)\subset A$$I just know that $g$ is always injective and I know want to show that if $f$ is surjective then $g$ is bijective.

So my Idea was the following. I remarked that it is enough to show that if $f$ is surjective then $g$ is surjective. I wanted to assume that $g$ is not surjective then $$\exists A\in S/\mathfrak{R}~~~s.t.~~~\forall B\in T/\mathfrak{P}~~~g(B)\neq A \Rightarrow f(B)\not\subset A$$ In my opinion this shows that $f$ is not surjective and thus the claim follows by contraposition, but I'm not really sure if this is correct so?
Could someone take a look and help me?
Thank you a lot.

A: This is not enough; how do you know there is actually some element $s\in A$ such that $f(t)\neq s$ for all $t\in T$?
To say something here you really need to get your hands on what the elements of $S/\mathfrak R$ look like: an element here has the form $A=[s]$ for $s\in S$, the equivalence class.
How do you proceed for a proof? Suppose $f$ is surjective. Now if $A\in S/\mathfrak R$ then $A=[s]$ for some $s\in S$. But because $f$ is surjective take some $t\in T$ such that $f(t)=s$, and from here show that you can take $B=[t]\in T/\mathfrak P$ and get $g(B)=A$.


text:
Q: Select group by with a max predicate Quite often I have to do queries like below:
select    col1, max(id)
from      Table
where     col2 = 'value'
and       col3 = (    select    max(col3)
                      from      Table
                      where     col2 = 'value'
                 )
group by col1

Are there any other ways to avoid subqueries and temp tables? Basically I need a group by on all the rows with a particular max value. Assuming all proper indices are used.

A: You can use an OLAP function to achieve this. I would say this solution is marginally better in that your predicates are not duplicated between the main query and subquery, so you don't violate DRY:
SELECT *
FROM (
    select    col1, max(id) as max_id,
              RANK() OVER (PARTITION BY col1 ORDER BY col3 DESC) AS irow
    from      [Member]
    where     col2 = 'value'
    group by  col1
) subquery
WHERE subquery.irow = 1


text:
Q: Using sprintf to convert integer to string seems to ignore 0 When I run the following code with an input of '01', value has the value of 1, ignoring the 0. However if i input '301' with the 0 not in the first position the code works.
int input;
printf("Enter an number: \n");
scanf(" %d", &input);

char array[10];
int value = sprintf(array, "%d", input);
printf("%d", value);

A: A way to discern leading '0' digits is to record the scan offset of input.
int n1, n2;
int input;
if (scanf(" %n%d%n", &n1, &input, &n2) == 1) {
  char array[40];
  int width = n2 - n1;
  int text_length = sprintf(array, "%0*d", width, input); // "0" --> Pad with zeros
                                                       // "*" --> Min width in argument list
  printf("%d <%s>\n", text_length, array);
}

" " will consume leading white-space. "%n" will record the scan text offset position.  "%n" does not contribute to the scanf() return value.
Limitations: input like "-123" and "+123" will report 4.

A: The manual page of sprintf() says

int sprintf(char *str, const char *format, ...);

sprintf(), write to the character string str.

Here
int value = sprintf(array, "%d", input);

sprintf() converts the int input into char array.
For e.g if user entered input as integer 123 it conver that into char array 123. Now it looks like
-------------------------
|  1  |  2  |  3  |  \0  |
-------------------------
array

and sprintf() returns return the number of characters printed (excluding
       the null byte used to end output to strings). That means
int value = sprintf(array, "%d", input); /* if input = 123(integer) */
printf("%s: ,%d: \n", array,value);/* array: 123(string), value: 3 */

When I run the following code with an input of '01', value has the value of 1, ignoring the 0. ? input is declared as an integer and when user gives 01 then scanf() considers only 1 as leading 0 ignored and only 1 gets stored into array, the array looks like
--------------
|  1  |  \0  |
--------------
array

However if i input '301' with the 0 not in the first position the code works. If user entered 301 then scanf() stored 301 into input and sprintf() converts that int into char array & stores into array as 301 like
     -------------------------
    |  3  |  0  |  1  |  \0  |
    -------------------------
    array

A: When you read a string as a number using the %d format specifier, any leading zeros are basically lost.
If you want to keep the leading zeros, you need to read the input as a string.  That way you get exactly what the user entered.  If you additionally want to perform numerical operations, you can then use strtol to get the numerical representation.
char array[10];
scanf("%s", array);

int input = strtol(array, NULL, 10);
printf("input as number %d, input as string: %s\n", input, array);


text:
Q: How to use drawable folder in android for Images or icons? How can I use drawable folder in Android Project for different images and icons for different devices?
e.g

*

*drawable-hdpi ?

*drawable-ldpi ?

*drawable-mdpi ?

*drawable-xhdpi ?

*drawable-xxhdpi ?

and What size of images should be placed in particular folder?

A: You dont need to use drawable folder. The android platform does that for you. You only need to place appropriate images at appropriate folders and the system will use the resources from that folder. You can have a look at google iconography for details about sizing.

A: I don't know how your app design looks like and what size of images your are going to put for your app design. In order to get ratio of LDPI,MDPI,HDPI,XHDPI and XXHDPI images, go through this link.


text:
Q: Cannot compile sqlite in Nerves firmware This question has come up a bit by many others in #nerves slack.
Essentially, you try to include sqlite in Nerves firmware (usually via esqlite) and it fails on mix firmware during compilation:
===> Compiling esqlite
===> Compiling /Users/someone/repos/my_firmware/deps/esqlite/c_src/esqlite3_nif.c
===> /Users/someone/my_firmware/deps/esqlite/c_src/esqlite3_nif.c:25:10: fatal error: sqlite3.h: No such file or directory
 #include "sqlite3.h"
          ^~~~~~~~~~~
compilation terminated.

sqlite3.h is definitely in the esqlite project.
Is it possible to get sqlite working in Nerves?


text:
Q: How to overcome Stack Size issue with Visual Studio (running C codes with big array) I am using Visual Studio 13 to compile c codes for the first time. The codes run perfectly O.K. with 2d arays of size 64*64 (there are a few arrays in my programme) but if I increase the array size to 128*128 it does not run (but compile correctly). Instead it gives a message ".exe has stopped working". My machine has 4GB ram and the same programme run with 128*128 array if I run the codes from linux.
Let me provide some more details: I have run the same code from linux using Intel C Compiler (non-commercial version) in the same machine. But due to some problem I am now constrained to work from a Windows environment. I searched and have installed two c- compilers (1) Visual Studio 13 and (2) Borland C. Both work well with a small array. But the moment I increase array size Visual Studio give the message ".exe has stopped working". I compile the programme using 'cl' from "Developers Command Prompt VS 13".
I feel the problem is with stack size.
In the link detailed explanation (as provided below) I have seen a command "ulimit" used in linux environment to increase the stack size. I remember using it a few years ago.
I feel we are close to the solution, but my problem with Windows (and VS 2013) persists as I failed to execute dumpbin /headers executable_file or editbin /STACK:size. Actually I feel I do not know how to execute them. I tried to execute them from "Developer Command Prompt VS 13" as well as using Run (windows start bottom->search (run)->Run (prop up)). I request you kindly to provide more details if possible.
I searched and found this website and think here the solution can be found.
Please help. I want to run using Visual Studio 13 from Windows.

A: It seems that the reason behind this is the stack overflow. The issue can be resolved by increasing the stack size.
In visual studio you can do this by using /STACK:reserve[,commit]. Read the MSDN article.

For more detailed explanation:
Under Windows platforms, the stack size information is contained in the executable files.  It can be set during compilation in Visual studio C++.
Alternatively, Microsoft provides a program editbin.exe which can change the
executable files directly.  Here are more details:
Windows (during compilation):

*

*Select Project->Setting.

*Select Link page.

*Select Category to Output.

*Type your preferred stack size in Reserve: field under Stack
allocations. eg, 32768 in decimal or 0x20000 in hexadecimal.

Windows (to modify the executable file):
There are two programs included in Microsoft Visual Studio, dumpbin.exe and editbin.exe.  Run dumpbin /headers executable_file, and you can see  the size of stack reserve information in optional header values.  Run  editbin /STACK:size to change the default stack size.

A: It sounds like you're trying to declare large arrays on the stack.  Stack memory is typically limited; it sounds like you're overflowing it.
You can fix this by giving your array static duration
static BigStruct arr[128][128];

or by dynamically allocating memory for it
BigStruct (*arr)[128] = malloc(sizeof(*arr) * 128);
// use arr
free(arr);

A:
Visual Studio does not work?

Although I don't regard VS as a valid development tool, I highly doubt that it would cause your problem.
128 * 128 is 16384. If you have too little stack space (on Windows, it's 1MB by default if I'm not mistaken), and you define an array of e. g. big enough structs (sized 64 bytes, more precisely), then this can easily cause a stack overflow, since automatic arrays are typically (although not necessarily) allocated on the stack.


text:
Q: Probability, Statistics

Can anyone please help me with the problem given below.

If you receive on average 2 spam emails per day, what is the probability that you receive at most 2 spam emails on a given day?

Thanks in advance.

A: Note: $X\sim P(2)$. The required probability is:
$$P(X\le 2)=P(X=0)+P(X=1)+P(X=2)=\\
\frac{2^0\cdot e^{-2}}{0!}+\frac{2^1\cdot e^{-2}}{1!}+\frac{2^2\cdot e^{-2}}{2!}=0.6767.$$


text:
Q: Getting/Indexing what Named-Entities have said/quoted I am trying to semi-automatically identify what people/advisers/economists or the like say on the news:
1
But Barclays chief economist Kieran Davies said companies were simply opting against bank funding.
"I don't think there's actually a constraint on corporate credit from the banks. I think it's more the case that corporates in recent years have either had sufficient cash or access to offshore funding to enable them to do their investment," Mr Davies said.
2
The the amount of commercial lending for every dollar of residential property lending has plunged from $3.84 to $1.62 over the past 25 years, says analysis from Industry Super Australia.
"Consistent analysis demonstrates that we have a systematic issue transitioning national savings to real productive capital, such as nation-building infrastructure," chief executive David Whiteley said.
3
Following the settlement, Macquarie's then chief executive in Asia, Alex Harvey, said he was "quite encouraged about SATC, about the risk management framework we've now put in place over the last few years and the sort of opportunities that are in front of the trust."
so with example #1, i would like to get what Mr Davies was saying,
and with example #2, what chief executive David Whiteley was saying,
and with example #3, what Alex Harvey was saying.
what is the best way of getting / indexing what those 3 people said in other 10000 or more articles ?
it feels like a mixed of Name-Entity-Tagging and Relationship-Extraction. Is there a more specific name to what I want to achieve ?


text:
Q: AMPL syntax error that can not be solved I'm struggling with the my AMPL syntax error. In my AMPL model, I have the constraint
subject to conpm_TM{tm in TM, t in T}: barpm_TM{tm,2*t} = pm_TM{tm,t};

here TM,T is the set I have already defined.
And when I run AMPL with Cplex solver, the AMPL says
syntax error
context: subject to conpm_TM{tm in TM, t in T}: >>> barpm_TM{ <<< tm,2*t} = pm_TM{tm,t};

I am just wondering is this caused by my incorrect use of index 2*t here.
Thank you.

A: You should use square brackets, not curly ones for subscripts:
subject to conpm_TM{tm in TM, t in T}: barpm_TM[tm,2*t] = pm_TM[tm,t];


text:
Q: Api call failed Unable to create converter for class Retrofit/Moshi I am implementing retrofit and moshi to make requests to a server (I am newbie using retrofit). I follow some guides that I found on the internet on how to implement it but when launching the app I receive the following error:
Error Api call failed Unable to create converter for class com.example.kvn.data.model.JConfig
     for method ApiClient.getApiConfig

This is the code i use :
AppModule.kt
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun providerDB(@ApplicationContext ctx: Context) =
        Room.databaseBuilder(ctx, AppDB::class.java, DB_NAME).build()

    @Singleton
    @Provides
    fun providerDao(db: AppDB) = db.getDao()

    @Singleton
    @Provides
    fun provideHttpClient(): OkHttpClient {
        return OkHttpClient
            .Builder()
            .readTimeout(15, TimeUnit.SECONDS)
            .connectTimeout(15, TimeUnit.SECONDS)
            .build()
    }

    @Singleton
    @Provides
    fun provideConverterFactory() = MoshiConverterFactory.create()

    @Singleton
    @Provides
    fun provideRetrofit(
        okHttpClient: OkHttpClient,
        moshiConverterFactory: MoshiConverterFactory
    ): Retrofit {
        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(moshiConverterFactory)
            .build()
    }

    @Singleton
    @Provides
    fun providerApi(retrofit: Retrofit) = retrofit.create(ApiClient::class.java)
}

Remote.kt
/*@JsonClass(generateAdapter = true)
data class JConfig(
    @Json(name = "data") val data:List<Config>
)

data class Config(
    @Json(name = "codigo") var codigo: Int,
    @Json(name = "tipo") var tipo: String,
    @Json(name = "empresa") var empresa: Int,
    @Json(name = "sucursal") var sucursal: Int,
    @Json(name = "esquema") var esquema: Int,
    @Json(name = "horainicio") var hini: String,
    @Json(name = "horafinal") var hfin: String,
    @Json(name = "fecha") var fecha: String,
    @Json(name = "seguimiento") var seguimiento: Int
)*/

@JsonClass(generateAdapter = true)
data class JConfig(
    @Json(name = "data") val data:List<Config>
)

data class Config(
    var codigo: Int,
    var tipo: String,
    var empresa: Int,
    var sucursal: Int,
    var esquema: Int,
    var horainicio: String,
    var horafinal: String,
    var fecha: String,
    var seguimiento: Int
)

ApiClient.kt
interface ApiClient {

    @POST(API_CONFIGURACION)
    suspend fun getApiConfig(@Body imei: String): Response<JConfig>
}

WebDataSource.kt
class WebDataSource @Inject constructor(private val web:ApiClient) {

    suspend fun getWebConfiguracion(imei:String): Response<JConfig> {
        return web.getApiConfig(imei)
    }
}

AppViewModel.kt
class AppViewModel @ViewModelInject constructor(private val repository: Repository) : ViewModel() {

    private val _response: MutableLiveData<NetworkResult<JConfig>> = MutableLiveData()
    val response: LiveData<NetworkResult<JConfig>> = _response

    fun fetchConfigResponse(imei:String) = viewModelScope.launch {
        repository.getWebConfiguracion(imei).collect { values ->
            _response.value = values
        }
    }

    fun saveOrUpdateConf(conf:Config) {
        viewModelScope.launch {
            if (isConfigEmpty()) {
                repository.saveConfiguracion(conf)
            }else {
                repository.updateConfiguracion(conf)
            }
        }
    }

    suspend fun setupConfig(T:()->Unit) {
        if (isConfigEmpty()) {
            T()
        }else {
            val cf = repository.getConfiguracion().value!!
            if (yesterday(cf[0].fecha)) {
                T()
            }
        }
    }
}

FBase.kt
@AndroidEntryPoint
class FBase : Fragment() {

    private val viewmodel by activityViewModels<AppViewModel>()
    private var _bind:FragmentFBaseBinding? = null
    private val bind get() = _bind!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _bind = FragmentFBaseBinding.inflate(inflater, container, false)
        return bind.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupObserver("888888882222331")
    }

    private fun setupObserver(imei:String) {
        fetchResponse(imei)
        viewmodel.response.observe(viewLifecycleOwner) { response ->
            when(response) {
                is NetworkResult.Loading -> { /*Notification*/ }
                is NetworkResult.Success -> {
                    val rs = response.data?.data?.get(0)!!
                    viewmodel.saveOrUpdateConf(rs)
                }
                is NetworkResult.Error -> { Log.d("TAG","Error ${response.message}") }
            }
        }
    }

    private fun fetchResponse(imei: String) {
        viewmodel.fetchConfigResponse(imei)
        //add notification
    }
}

Dependencies and plugins
plugins {
   id 'com.android.application'
   id 'kotlin-android'
   id 'kotlin-android-extensions'
   id 'kotlin-kapt'
   id 'dagger.hilt.android.plugin'
}

//  HILT
implementation 'com.google.dagger:hilt-android:2.28.1-alpha'
kapt 'com.google.dagger:hilt-android-compiler:2.28.1-alpha'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha02'
//  TOOLS
implementation 'com.squareup.moshi:moshi-kotlin:1.13.0'
implementation 'com.squareup.moshi:moshi:1.13.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.13.0'
implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'

Before retrofit, I used volley for requests together with moshi without any problem, but with retrofit I don't know how to solve it.
Sorry for my English.
Thanks

A: I found the source of the error, when using moshi with retrofit, all data classes must have the annotation of @JsonClass(generateAdapter = true)
We must change the code:
@JsonClass(generateAdapter = true)
data class JConfig(
    @Json(name = "data") val data:List<Config>
)

data class Config(
    var codigo: Int,
    var tipo: String,
    var empresa: Int,
    var sucursal: Int,
    var esquema: Int,
    var horainicio: String,
    var horafinal: String,
    var fecha: String,
    var seguimiento: Int
)

For this:
@JsonClass(generateAdapter = true)
data class JConfig(
    @Json(name = "data") val data:List<Config>
)

@JsonClass(generateAdapter = true)
data class Config(
    var codigo: Int,
    var tipo: String,
    var empresa: Int,
    var sucursal: Int,
    var esquema: Int,
    var horainicio: String,
    var horafinal: String,
    var fecha: String,
    var seguimiento: Int
)

A: In my case, it was because I was not passing the moshi object into MoshiConverterFactory.create() e.g.
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl(BASE_URL)
.build()

Compiles fine but throws same error OP is seeing at runtime.
Fixed by passing moshi into MoshiConverterFactory
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()

moshi object is defined as
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()

A: Also, ensure that you have enabled KotlinJsonAdapterFactory and have added it to your Moshi.Builder:
//First Build Moshi Object
private val moshi =
    Moshi.Builder()
        .addLast(KotlinJsonAdapterFactory())
        .build()

//Then Build Retrofit Object and passing in moshi object created above
val retrofit =
    Retrofit.Builder()
      .addConverterFactory(MoshiConverterFactory.create(moshi)) //for parsing KotlinObjects i.e.
        // picture of the day
        .baseUrl(BASE_URL)
        .build()

There is also a similar question here

A: In my case I forgot to add these dependencies:
implementation "com.squareup.moshi:moshi:$moshi_version"
kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshi_version"

You can try that if no one from above suggestions works for you.


text:
Q: Inno Setup: restart in the middle of setup process I've made a installer via Inno Setup and now I'm need to restart computer after some files were run.
So, i have code:
....
[Files]
....
[Run]
Filename: firstfile
RESTART
Filename: secondfile
....

Is this possible? I have found one example script github, but i cant understand how to use this DetectAndInstallPrerequisites functions.
If someone can advise or provide some simple example, I would be very gratefull

A: Have a look at the CodePrepareToInstall.iss example script included with Inno.  It shows how to arrange for a reboot and have the installation automatically resume afterwards.  (You may need to make further changes or save further values if your installation is more complex or prompts for further user input.)
The missing link in that example is that you need to fill in the DetectAndInstallPrerequisites function by using ExtractTemporaryFile to retrieve the appropriate files (as it runs before the main [Files] section is processed) and Exec(ExpandConstant('{tmp}\yourfile.exe'), ...) to actually run the file.  If this is a subinstaller you can then check its exit code to determine if a reboot is actually required or not rather than unconditionally requesting a reboot.
Note that this code will be executed again following the reboot, so you also need some way to detect that the subinstall has succeeded and skip trying to run it again.  Typically this is done by trying to detect the version of the installed subcomponent.


text:
Q: Can I use std::function (C++11 lambda) with Boost?
Possible Duplicate:
Using Boost adaptors with C++11 lambdas

I would like to use Boost range adaptors to map (transform) a map to a list, through a C++11 lambda function.
Like this:
  boost::copy(myMap | transformed([](pair<string, string> p){return p.first;}),
              ostream_iterator<string>(cout, ", "));

This won't work, because std::function does not have a value_type-type. I know that this particular transformation can be done with map_keys, but my point is more general. How can I use C++11 lambdas with Boost?
If it cannot be done without boilerplate, are there any plans to fix this issue? I have tried searching for it, but found suprisingly little.

A: I found it myself! Starting with Boost 1.51.0, you add
#define BOOST_RESULT_OF_USE_DECLTYPE

Before including the boost files, and it will magically use decltype instead of ::value_type to infer return type. Now my example works!


text:
Q: A really simple factorization question. Can these equations be factorized?
Expression type: $x^2 + p x + q$
$$ x^2 + 5x - 36\tag{1}$$
$$ x^2 - 7x + 12\tag{2}$$

A: First equation: $q=-36$, $p=5$. The factors of $36$ are
$$(1, 36), (2, 18), (3, 12), \boxed{(4,9)}, (6,6)$$
Which of these pairs has a difference of $5$?
$$x^2 + 5x - 36 = (x-4)(x+9)\tag{1}$$

Second equation: $q=12$, $p=7$. The factors of $12$ are
$$(1,12), (2,6), \boxed{(3,4)}$$
Which of these pairs has sum of $7$?
$$x^2 - 7x + 12= (x-3)(x-4)\tag{2}$$

You see how the game is played. Create your factors list. Stop just before the first number is bigger than the second. For example, in the second list you would not consider $(9,4)$ because that combination is already listed as $(4,9)$.
Then sweep through the factors and look at sum and difference.


text:
Q: Finding accuracy, precision and recall of a model after hyperparameter tuning in sklearn I've a binary classification problem, for which I've chosen 3 algorithms, Logistic Regression, SVM and Adaboost. I'm using grid-search and k-fold cross validation on each of these to find the optimal set of hyper-parameters. Now, based on the accuracy, precision and recall I need to choose the best model. But the problem is I'm not able to find any suitable way to retrieve these information. My code is given below:
from sklearn.model_selection import GridSearchCV
from sklearn.metrics.scorer import make_scorer
from sklearn import cross_validation

# TODO: Initialize the classifier
clfr_A = LogisticRegression(random_state=128)
clfr_B = SVC(random_state=128)
clfr_C = AdaBoostClassifier(random_state=128)

lr_param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000] }
svc_param_grid = {'C': [0.001, 0.01, 0.1, 1, 10], 'gamma' : [0.001, 0.01, 0.1, 1]}
adb_param_grid = {'n_estimators' : [50,100,150,200,250,500],'learning_rate' : [.5,.75,1.0,1.25,1.5,1.75,2.0]}

# TODO: Make an fbeta_score scoring object using make_scorer()
scorer = make_scorer(fbeta_score, beta = 0.5)

# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()
clfrs = [clfr_A, clfr_B, clfr_C]
params = [lr_param_grid, svc_param_grid, adb_param_grid]

for clfr, param in zip(clfrs, params):
    grid_obj = GridSearchCV(clfr, param, cv=3, scoring=scorer, refit=True)
    grid_fit = grid_obj.fit(features_raw, target_raw)
    print grid_fit.best_estimator_
    print grid_fit.cv_results_

Problem is the cv_results_ gives out a lot of info but I'm not able to find anything relevant except mean_test_score. Moreover I don't see any accuracy, precision or recall related metric there.
I can think of one way to achieve it. I can change the for loop to look something like the following:
score_params = ["accuracy", "precision", "recall"]
for clfr, param in zip(clfrs, params):
    grid_obj = GridSearchCV(clfr, param, cv=3, scoring=scorer, refit=True)
    grid_fit = grid_obj.fit(features_raw, target_raw)
    best_clf = grid_fit.best_estimator_
    for score in score_params:
        print score,
        print " : ",
        print cross_val_score(best_clf, features_raw, target_raw, scoring=score, cv=3).mean()

But is there any better way of doing it? It seems I'm doing the  operations multiple times for each model. Any help is appreciated.

A: GridSearchCV is doing what you gave. You gave the f_beta as scorer, so mean_test_score will return results of that f_beta for each parameter combination.
If you want to access other metrics, you need to tell the GridSearchCV explicitly to do so.
GridSearchCV in newer versions of scikit-learn, supports multi-metric scoring. So you can pass multiple type of scorers in that. As per documentation:

scoring : string, callable, list/tuple, dict or None, default: None
...
     ...
For evaluating multiple metrics, either give a list of (unique)
          strings or a dict with names as keys and callables as values.

See this example here:

*

*http://scikit-learn.org/stable/auto_examples/model_selection/plot_multi_metric_evaluation.html#running-gridsearchcv-using-multiple-evaluation-metrics
And change your scoring param as:
scoring = {'Accuracy': 'accuracy',
           'FBeta': make_scorer(fbeta_score, beta = 0.5),
           # ... Add others here as you want.
           }

But now when you do it, you need to change the refit param also. Since different metrics here will give different type of scores for the parameter combinations, so you need to decide which one to select when refitting the estimator. So choose one of the keys from the scoring dict for refit
for clfr, param in zip(clfrs, params):
    grid_obj = GridSearchCV(clfr, param, cv=3, scoring=scorer, refit='FBeta')
    ...
    ...


text:
Q: Using fb_graph to post to Facebook fan page from Rails 3 I hear that fb_graph is the way to go and I already have my app registered with Facebook but I don't know how to get the access token to post things. I have my app ID and secret but I need to get that access token. All I'm trying to do is post to a Facebook fan page (as the page).
How do I get the access token?

A: Get the user:
user = FbGraph::User.me(access_token)
user.fetch

To see the users accounts details:
user.accounts

Select the Facebook page that you want to post to:
account = user.accounts.select {|account| account if account.name == "*Your Page Name*"}.first

(account.access_token => the pages access token)
(account.identifier => page id)

Create new page instance:
page = FbGraph::Page.new(account.identifier)

Post to the page:
note = page.note!(:access_token => account.access_token, :subject => "Hello World", :message => "hey, this is a test from rails")

A: The step-by-step procedure for access token with Oauth 2.0 is found here: http://developers.facebook.com/docs/authentication/. If you require a sample code in Ruby, create a new app and under "Hosting URL", click on "get one" and select Ruby programming language when prompted. It also contains code to pull from Graph API.

A: I highly highly recommend the new gem Koala for working with facebook.

A: If you do a call to  https://graph.facebook.com/me/accounts
and pass in your access_token it will return data listing all the pages you have access to and the access_tokens needed to post to those walls.#
You get your access token by logging in and the access token is passed back by the login process.


text:
Q: Start New Remote X Session In Separate TTY In my home setup, I have two computers on the same local network, both run Ubuntu 20.04. I'm hoping to set up a way to access my secondary computer via my primary, by switching to a new TTY, and starting a remote X session. I don't want to share the screen, or access an existing X session. Additionally, the computer I am using to start the remote X session has two monitors, and I would like to take advantage of both.
I have tried a couple of options. I seems like XDMCP could do what I want, but I have had little luck so far (getting access, but only a black screen with cursor). Additionally it seems like it both uses a high bandwidth and is insecure, so ideally I would use something else.
I have tried X2Go, but I have not been able to find a way to start it in a separate TTY, or to have it take advantage of both of my monitors.
I have heard also of things like xvnc, and NoMachine, but I'm not sure if either of those can be run the way I would like.
Is there any existing ways to do this? Or alternatively, any way to compress and/or secure XDMCP? I have seen it may be possible to have XDMCP go over SSH, is this true?
Thanks!

A: X window sessions don't work the way that you're expecting them to work. You're thinking that there is a "server" on the other side that you're connecting to, and that you want to control.
In reality, it works the opposite. The machine that you're connecting from acts as the server, and when you connect, you tell it to display on a different machine.
So, X needs to be running on the machine that you're connecting FROM, then do the following:

*

*Open an xterm, or whatever your favorite terminal window app is.

*On the local machine, in the terminal, allow connections from the remote host:
xhost + 192.168.1.2
(where 192.168.1.2 is the machine you are connecting to)

*In the same terminal, open a shell to the remote machine (192.168.1.2), using ssh, with X11 forwarding:
ssh -Y login@hostname

*On the remote machine, set your display:
export DISPLAY=192.168.1.1:0.0
(this will be the machine that you are connecting from)

*Now start a program. Just run xeyes, or xcalc, or chrome, or whatever. The program should show up on your local X Window interface, after a while. It's running on the remote machine, but displaying locally.
Note that the remote machine doesn't even need to have an X Window server running on it. It's actually acting as the client, to your local computer's X Window server.
XDMCP is definitely "heavier" than a more optimized protocol for display changes, like VNC. Then again, the goal is different: VNC usually operates on the entire screen. And there's nothing to stop you from installing a VNC server, and going that route. In that case, any VNC client would work.


text:
Q: gradle-4.8 build failed with an exception which could not get the internet resource After I change my OS to Ubuntu-18.04 and upgrade grade to v4.8, I failed to build my android project.
As a comparison, I can build this project on Ubuntu-14.04 with gradle-v3.4.1.
There are some error messages.
Gradle build failed as following:
user@Ubuntu1804 ~/android/im/ocelot $ gradle build

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'ocelot'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:3.1.2.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:3.1.2.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'.
            > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
      > Could not resolve com.android.tools.build:gradle:3.1.2.
         > Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

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

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

BUILD FAILED in 1s

This is the build.gradle:
user@Ubuntu1804 ~/android/im/ocelot $ cat build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is the gradle version:
user@Ubuntu1804 ~/android/im/ocelot $ gradle -version

------------------------------------------------------------
Gradle 4.8
------------------------------------------------------------

Build time:   2018-06-04 10:39:58 UTC
Revision:     9e1261240e412cbf61a5e3a5ab734f232b2f887d

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.11 compiled on March 23 2018
JVM:          1.8.0_171 (Oracle Corporation 25.171-b11)
OS:           Linux 4.15.0-23-generic amd64

OpenJDK-1.8.0:
user@Ubuntu1804 ~/android/im/ocelot $ java -version
openjdk version "1.8.0_171"
OpenJDK Runtime Environment (build 1.8.0_171-8u171-b11-0ubuntu0.18.04.1-b11)
OpenJDK 64-Bit Server VM (build 25.171-b11, mixed mode)

I already imported some cacerts and verified them as following:
user@Ubuntu1804 ~/android/im/ocelot $ keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts | grep google
Enter keystore password:  changeit
google.com, Jun 21, 2018, trustedCertEntry,
debian:googlecom.pem, Jun 21, 2018, trustedCertEntry,
dl.google.com, Jun 21, 2018, trustedCertEntry,
maven.google.com, Jun 21, 2018, trustedCertEntry,

user@Ubuntu1804 ~/android/im/ocelot $ keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts | grep bintray
Enter keystore password:  changeit
jcenter.bintray.com, Jun 21, 2018, trustedCertEntry,

I did some tests to verify the internet connection because there is one HTTPS_PROXY:
user@Ubuntu1804 ~/android/im/ocelot $ wget https://maven.google.com/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom
--2018-06-21 22:21:27--  https://maven.google.com/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom
Resolving proxy.COMPANY.net (proxy.COMPANY.net)... 10.x.x.x
Connecting to proxy.COMPANY.net (proxy.COMPANY.net)|10.x.x.x|:8080... connected.
Proxy request sent, awaiting response... 301 Moved Permanently
Location: https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom [following]
--2018-06-21 22:21:28--  https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom
Connecting to proxy.COMPANY.net (proxy.COMPANY.net)|10.x.x.x|:8080... connected.
Proxy request sent, awaiting response... 200 OK
Length: 2391 (2.3K) [application/octet-stream]
Saving to: 'gradle-3.1.2.pom.1'

gradle-3.1.2.pom.1             100%[====================================================>]   2.33K  --.-KB/s    in 0s

2018-06-21 22:21:29 (17.1 MB/s) - 'gradle-3.1.2.pom.1' saved [2391/2391]

user@Ubuntu1804 ~/android/im/ocelot $ curl https://maven.google.com/com/android/tools/build/gradle/3.1.2/gradle-3.1.2.pom
curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

A: This is most likely a truststore issue.
Try running your build with: ./gradlew --no-daemon -Djavax.net.debug=ssl:handshake:verbose build
And check which truststore gets loaded and which certificates it contains, by looking for lines adding as trusted cert:.


text:
Q: How to create a conditional that works if an int is contained twice in a list This quite simple game asks the user to guess a random number. The program ends when he guesses.
I wanted to add a simple feature, i wanted notitfy the user when he used twice the same number.
The problem is that the conditional that i wrote is always true, it prints "You already tried that number" every time.
I know how to make the program work, i just don't know what to write. It would be smart to say if guess is contained twice in previous_guess.
    # myNumber.py
# This game uses a home made function

def num():
    import random

    # Think a number
    computer_number = random.randint(1, 100)

    def is_same(target, number):
        if target == number:
            result = "Win"
        elif target > number:
            result = "Low"
        else:
            result = "High"
        return result

    # Start the game
    print("Hello.\nI have thought of a number between 1 and 100:")

    # Collect the user's guess as an integer
    guess = int(input("Can you guess it?"))
    # Use our function
    higher_or_lower = is_same(computer_number, guess)
    # run the game until the user is correct
    while higher_or_lower != "Win":
        if higher_or_lower == "Low":
            guess = int(input("Sorry you are too low. Try again"))
        else:
            guess = int(input("Sorry you are too high. Try again"))

        higher_or_lower = is_same(computer_number, guess)

This is the part i wanted to add
previous_guess = [guess]
if guess in previous_guess:
            print("You already tried with that number")

#previous_guess = []
#previous_guess.append(guess)
#I could also write it like this, same thing

A: You need to append it within the while loop and rearrange your code accordingly:
previous_guesses = list()
# Collect the user's guess as an integer
guess = int(input("Can you guess it?"))
previous_guesses.append(guess)

# Use our function
higher_or_lower = is_same(computer_number, guess)
# run the game until the user is correct
while higher_or_lower != "Win":
    if higher_or_lower == "Low":
        guess = int(input("Sorry you are too low. Try again"))
    else:
        guess = int(input("Sorry you are too high. Try again"))

    if not guess in previous_guesses:
        previous_guesses.append(guess)
        higher_or_lower = is_same(computer_number, guess)
    else:
        print("You already tried with that number")


text:
Q: Euphemistic expression: required vs. requested There are four candidates to complete the following sentence.

While the questionnaire was voluntary, we were ______ to fill it out
  before leaving the plane.
(1) required (2) ordered (3) requested (4) forced

I'm not sure which one makes sense.
The following is my reasoning:

Even though the questionnaire was voluntary, someone begged us to fill
  the form out. In other words, we were not rigidly asked to do that,
  instead, somebody politely invited us to do that. So, I think the
  euphemistic expression is the better choice.

I think that (2) and (4) are the rude tones. Maybe (1) or (3) is acceptable.
What do you think and why?

A: Here, the answer will be : We were requested to fill it out before leaving the plane.
Reason lies in the question itself. The Question is ; While the questionnaire was voluntary.
Now, this word voluntary shows that it depends on the person's will whether to fill the questionnaire or not.
If we use other words such as : ordered, forced or required then they make the task mandatory which is not the case here.
We can only request someone to do the voluntary task. No one can be forced to do it and if anyone is forced then that task is not voluntary.


text:
Q: Is it OK to use a forward slash '/' between words other than the obvious 'and/or'? I don't want to get into the proper use of the phrase 'and/or', but rather to investigate the use of the forward slash between other words. Examples:

*

*I have an interview with him/her this afternoon.

*He has a large binder/notebook.

And even separating just letters:

*

*I connected the i/o ports. (input/ouput)

*Mark the field as n/a. (not applicable)

*I did it w/o her help. (without)

It seems as thought the forward slash can be used to indicate an option, display ambiguity, shorten 2 words and shorten 1 word (and others).
Is it OK to use a slash to separate these words/letters (yes, that was intended), or is it better to explicitly say 'his or her'? One more thing, is it correct to 'chain' these phrases together? I'm horrible with examples but here's one:

*

*I don't open letters/mail that aren't/isn't addressed to me.

A: As I often say in response to these questions, it's not obvious what form of "OK"-ness you're looking for in asking this. It's really a stylistic decision. If you're writing to a particular style guide, do what the style guide says in this respect. If what you are writing will be edited by somebody, let them decide what to do. Otherwise (or if your editor/style guide has no opinion on the matter), decide if you like the slash or not and use it if you do...

A: For writing regular texts, you should try to avoid slashes. Use them if you must, but they do put a dent in the flow of the sentence so it's easier to read a sentence without it.
Some uses are well known (at least for a specific target audience), for example i/o for input/output, so using that can actually make the text easier to read.
Others, like w/o as an abbreviation for without is just for saving space or saving keypresses, common in space limited digital communication like SMS messages. You should avoid those, unless you are after that exact impression.

A: Do you want casual, even sloppy, writing, or precise, more elegant writing?  I prefer
precise, if I can't always achieve elegance.

*

*This is sloppy: "He has a large binder/notebook." Well, decide if you want to call it a binder or a notebook. It could even be a binder notebook, in which binder modifies notebook and tells us what kind of notebook it is.

*"They rode the streetcar/tram."  Just plain laziness: is it a streetcar or a tram? You
decide.

*As for and/or, it is used in legal briefs, but not in good writing.  "Do you want apples or oranges or both?"  Not "apples and/or oranges."

*If you want to say "or" use "or" and not a slash.  "He has a large binder or notebook."

Good writing is worth your time. If you are trying to express yourself in words, don't
ever say you "can't be bothered."

A: It certainly would be, if there were such a thing as a "forward slash" :P
(Just call it a "slash")
It's one of the few things that's common to just about all known written languages, probably because it's a natural mark to make by hand for the purpose.


text:
Q: how to add datagridview column1 and column2 into column3 in c# I am trying to add column1 value to column2 and have to insert into column2
my code is
Event is CellLeave
if (dgrVwEmp.Columns[dgrVwEmp.CurrentCell.ColumnIndex].Name == "ol")
 {
    int ol;
    int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                         .Cells["ol"].EditedFormattedValue.ToString(), out  ol);

    int leavs;
    int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                         .Cells["ttlLeaves"].Value.ToString(), out leavs);

    int dys;
    int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                         .Cells["ttlWrkng"].Value.ToString(), out dys);

    dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                         .Cells["ttlLeaves"].Value = (ol + leavs).ToString();
    dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                         .Cells["ttlWrkng"].Value = (dys - ol).ToString();

 }

when I am trying to add like this 1st time is the values are adding and inserting to 3rd field, if I came back to the same cell it is adding again to already added field. How can I add it properly. This is becose I am using Cell leave even. Is there any other way or other event to do this properly

A: Maybe you could introduce a variable that holds the old value and when the event is fired, the old value is subtracted from ttleaves cell at the same time the new value is added. The opposite should happen with the ttlWrkng cell:
private int oldValue = 0;

private void dgrVwEmp_CellLeave(object sender, DataGridViewCellEventArgs e)
{
   if (dgrVwEmp.Columns[dgrVwEmp.CurrentCell.ColumnIndex].Name == "ol")
   {
      int ol;
      int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                     .Cells["ol"].EditedFormattedValue.ToString(), out  ol);

      int leavs;
      int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                     .Cells["ttlLeaves"].Value.ToString(), out leavs);

      int dys;
      int.TryParse(dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                     .Cells["ttlWrkng"].Value.ToString(), out dys);

      dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                     .Cells["ttlLeaves"].Value = (ol + leavs - oldValue).ToString();
      dgrVwEmp.Rows[dgrVwEmp.CurrentCell.RowIndex]
                     .Cells["ttlWrkng"].Value = (dys - ol + oldValue).ToString();

      oldValue = ol;
   }

}


text:
Q: C#: How to keep track of the UID of messages between folders? I'm moving messages from the inbox folder to a new folder. After a while I need to move some of these messages(not all) to a new folder. The problem with this is that everytime I move a message the uid changes. How can I do this without moving the wrong message?

A: If your server supports UIDPLUS (nearly all do), and you yourself are moving or copying the messages, the server will give you the new UID when you copy or move it in the COPYUID response.  You'll need to record this.
An example from the IMAP MOVE RFC6851:
   C: a UID MOVE 42:69 foo
   S: * OK [COPYUID 432432 42:69 1202:1229]
   S: * 22 EXPUNGE
   S: (more expunges)
   S: a OK Done

The COPYUID response includes the UIDVALIDITY of the destination mail box, the UID set of the source messages, and the UID set of the destination messages.
If some other process is doing the moving, there's no way to guarantee the same message, and you'd have to track them based on their content (eg, the Message-ID header, the date time, a hash, etc.)

A: You're "moving" also involves an INSERT into DB to keep track of UIDs? If yes, watch for autogenerated PKs.


text:
Q: Visual Studio 2013 not finding code after I moved it to another file All my code was in one file, say, Form1.cs. The file was getting too big so I decided to break up my code into several new files. I used the solution explorer to add the new files. (right-click > Add > New Item... > Code File)
So for example, I created SomeFolder/ClickHandlers.cs, and cut my someButton_Click() function from Form1.cs and pasted it into said new file. So the new file looks like this:
using blah;
using blah...;

namespace FooApp
{
    public partial class Form1 : Form
    {
        void someButton_Click(object sender, EventArgs e)
        {
            // Do things..
        }
    }
}

And Form1.cs no longer has this function in it. My program runs perfectly fine. But VS didn't seem to get the memo. When I go into the designer, select "someButton" and then go into the events list in the Properties Pane, I see my function "someButton_Click" in the Click event. When I double-click the function, it takes me to the beginning(ish) of Form1.cs, not into SomeFolder/ClickHandlers.cs where the function got moved to.
How can I make VS learn the new locations of my code so I can be taken to it from the designer? I've tried deleting the .suo file and the obj folder. No dice.