text:
Q: Criar sistema operacional em batch (.bat) É possível criar um sistema operacional de verdade em batch (.bat)?
Pois vi alguns vídeos do Youtube em que o título era alguma coisa "OS in batch"(inglês).

A: Não é possível por uma simples razão, para rodar um script batch precisa de um interpretador que precisa de um sistema operacional.
Uma simulação, algo complementar a um básico feito com outras tecnologias mais baixo nível, meio de brincadeira, até é possível.
Um sistema operacional tem que fazer acesso ao hardware, não é possível com algo tão primitivo. Claro que você pode chamar de sistema operacional algo que opera alguma coisa em mais alto nível de forma mais específica, mas não é o SO que a computação define.
O que eu achei pesquisando é uma simulação do que seria um sistema operacional, mesmo assim de forma muito incipiente, ou seja, é só uma brincadeira, não um SO de verdade.


text:
Q: Why does ant build fail with sudo even though it succeeds when run as root user? I am compiling an Android app on server with java build tool ant.
When I run the following as root user the build succeeds:
export ANT_HOME=/usr/local/ant
export JAVA_HOME=/usr/local/jdk
export PATH=${PATH}:${ANT_HOME}/bin
cd /path/to/android/file
/usr/local/ant/bin/ant release

However, when I run the following as netuser (or any other user which I've tested):
export ANT_HOME=/usr/local/ant
export JAVA_HOME=/usr/local/jdk
export PATH=${PATH}:${ANT_HOME}/bin
cd /path/to/android/file
sudo /usr/local/ant/bin/ant release

I get the following error:
BUILD FAILED
/path/to/android/file/build.xml:83: The following error occurred while executing this line:
/usr/share/android-sdk/tools/ant/build.xml:206: Class org.apache.tools.ant.taskdefs.condition.And doesn't support the nested "matches" element.

I have tried changing sudoers file to even give netuser all permissions with netuser ALL=(ALL) ALL but I get same results... Can someone tell me what I am doing wrong?
Thanks in advance for any help.

A: I suspect that you're not picking up the environment variables when running as sudo.  The error message suggests it is using an older version of the Ant tasks than you expect.
To see if this is the case, try the following (after the exports) and see if it is what you are expecting:
sudo env

To preserve the environment variables, either modify the sudoers file or use the -E option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I detect and handle my app when the device is connected as Mass Storage? I developing a game with SD resources. When I connect the device as MASS STORAGE the device crash. It's because when I plug my device in the PC as Mass Storage the device doesn't have access to the SD card. So I tried different ways to solved.
Currently I'm implementing a BroadcastReceiver and I'm handling the actions ACTION_MEDIA_BAD_REMOVAL (if the SD card is removed manually) and ACTION_MEDIA_SHARED (it supposed to handle the action if the device is connected as Mass Storage, but it doesn't).
When both of these actions is detected I send an error message and I finish the app.
When I remove the SD card manually it works, but not as mass storage.
Also on every frame I check if the SD card is on the device on every frame with this method.
 public int hasSDCard()
 {
    String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
                return 1;
    return 0;
 }

When is 0 it doesn't have SD card and that where I also send the error message and finish the app.
But stills doesn't work on USB Mass Storage mode.
My question are: How can I detect when the device is connected as USB Mass Storage ?
What classes should I use?
Which listeners I can implement to call my error message activity and finish my app?

A: You should use BroadcastReceiver class. At the begining register a BroadcastReceiver for ACTION_MEDIA_MOUNTED or ACTION_MEDIA_UNMOUNTED intent. Create a class that will override onReceive() method, which is the method where you handle the mounting/unmounting.
http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_MOUNTED
As an extra info read the deprecation of ACTION_UMS_CONNECTED
http://developer.android.com/reference/android/content/Intent.html#ACTION_UMS_CONNECTED


text:
Q: UFW reload and disable/enable work but not just enable I have a test linode server (Ubuntu 17.10) for playing around. If the server is rebooted I need to either run
sudo ufw disable
sudo ufw enable

or
sudo ufw reload

to be able to see the web pages on that server.
If I just run:
sudo ufw enable

I cannot see the web pages from a remote computer.
I'm also curious why I have to do anything with ufw after a reboot as the rules are there. Why do they need a kick start.
Thanks!


text:
Q: Temperature dependency of charge carrier mobility and resistance in MOSFETs I am a little bit confused about this. I used to think that in regular conductors the resistance increases with an increase in temperature because the charge carriers collide more frequently and thus the mean velocity of them decreases.
In semiconductors we learned that an increase in temperature can lead to electrons in the valence band to gain sufficient thermal energy to move into the conduction band and therefore decreasing the resistance with increasing temperature.
I was looking into the temperature dependency propagation delay of CMOS logic. I found that the delay goes up with an increase in temperature. Can anyone explain why this is happening?

A: The temperature dependency of the propagation delay in CMOS logic is a complex phenomenon that is influenced by a number of different factors. In general, an increase in temperature can lead to an increase in the delay of CMOS logic gates for several reasons, including the following:

*

*Increased thermal noise: As the temperature increases, the thermal
energy of the electrons in the circuit also increases, which can
lead to an increase in the level of thermal noise. This noise can
interfere with the signals in the circuit and cause delays in the
propagation of the signals.

*Reduced device performance: As the temperature increases, the
performance of the transistors in the CMOS logic gates may decrease,
which can lead to slower switching times and longer delays in the
propagation of the signals.

*Increased leakage current: As the temperature increases, the leakage
current in the transistors may also increase, which can
cause additional delays in the propagation of the signals.
Overall, the temperature dependency of the propagation delay in CMOS logic is a complex phenomenon that is influenced by a variety of different factors. While an increase in temperature can sometimes lead to a decrease in resistance in semiconductors, it can also have negative impacts on the performance of CMOS logic gates and lead to increased delays in the propagation of signals.

A: Applying the statement about the resistance of intrinsic semiconductors to the CMOS device operation, the OP underestimates their confusion (I am a little bit confused ...).
The temperature dependency of the MOSFET channel resistance can be measured directly, or, the better approach, it can be derived from simulation, because the MOSFET device models are well established to correctly represent these values for a wide temperature range.
Let us simulate a 0.18um CMOS inverter, with NMOS (l=0.18u w=0.18u) and PMOS (l=0.18u w=0.45u).
The plots of drain-to-source resistance (RDSON) for both NMOS and PMOS devices have positive temperature coefficients. The resistance values grow almost linearly from 75KOhm @ 0°C to 109KOhm @125°C for NMOS and from 30KOhm @0°C to 42KOhm @125°C for PMOS.

This experimentally confirmed positive temperature coefficient in no way is at odds with the negative temperature coefficient of intrinsic semiconductors: the MOSFET channel is anything but pure semiconductor. The NMOS channel is doped with acceptor atoms, creating a p-type bulk; the PMOS channel is doped with donor atoms, creating an n-type bulk.
The behavior of doped (extrinsic) semiconductors in the electric field is different than the behavior of intrinsic semiconductors. Let us consider the behavior of an n-type doped semiconductor.
At low temperatures, when the donor sites do not receive enough energy to migrate to the conduction band, the extrinsic semiconductor behaves similarly to the intrinsic semiconductor. As the temperature is rising, typically at 200°K, the donors become ionized, and at room temperature all the donors are ionized.
Now, the quantity of donor-generated carriers in the conduction band is independent of temperature (all the donors are ionized), but the number of "intrinsic"-generated carriers (from the valence band) is still negligible in comparison with the dopant-generated carriers: the majority carrier concentration is made up of the donor electrons, and the resistivity is fully defined by mobility. The mobility of carriers decreases with increase in temperature because of phonon scattering. The mobility in silicon semiconductor is dominated by acoustic phonon interaction, and this time it is identical behavior for both the intrinsic and extrinsic semiconductors.
As the temperature rises higher, above ~500°K, thermally generated electrons from the valence band overweigh the quantity of donor-generated electrons and the semiconductor again behaves as intrinsic.
For a p-type semiconductor (doped with acceptors) the consideration is similar, only the carriers are holes. Note that the hole mobility in silicon is also dominated by acoustic phonon interaction.


text:
Q: What would be the best way to send some XML to server using AJAX? There is one more parameter to send with the request.
So this is my code so far:
   $.post(url + "/SaveProfile", { xml: XML, configName: name}, function() {
      alert("Saved");
   });

I got this error :
A potentially dangerous Request.Form value was detected from the client

A:
A potentially dangerous Request.Form value was detected from the client

That is the serverside framework protecting you from people trying to do injections. There are ways to disable that for the page or for the entire site [I would not recommend doing that.] Easiest thing to do to get around it is to encode the string and unencode it on the server.

A: It's a server feature to protect against injection attacks.
If you're using ASP.NET MVC, you can use the ValidateInput attribute to decorate the controller receiving your XML data:
[ValidateInput(false)]
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult
SaveEdits (string xmlData)
{
     ....
}

If you're using classic ASP.NET, use the directive in your .aspx page (not recommended, might open security issues):
<%@ Page ValidateRequest="false" ... %>


text:
Q: How can i compare two columns to see if the value in the B cell appears anywhere in column A? I have 2 columns like this (yep, Porn)
A                           B
menshealthbase.com          XVIDEOS.COM
dailyrx.com                 ASHLEYRNADISON.COM
puzzleovergames.com         PORNHUB.COM
adventuregamesland.com      DOUBLEPIMP.COM

and i'd like to see if the value in cell B1 appears anywhere in column A (the actual column is over 20,000 values). If yes, then I'd like it to print either a 'yes' or 'no' in column C
Any suggestions? my experience with vlookup is limited

A: Try this in column C:
=IF(ISNUMBER(MATCH(B1, A:A, 0)), "Found", "")

This will search column A for the value in B1 and return "Found" if it's found or leave it blank otherwise.

A: Step 1 Uppercase Column A

Step 2 MATCH them


text:
Q: How to use errno the same way in C++11 as it was in C++03 Trying to understand :

C.2.9 Clause 19: diagnostics library [diff.cpp03.diagnostics]
19.4
Change: Thread-local error numbers
Rationale: Support for new thread facilities.
Effect on original feature: Valid but implementation-specific C++ 2003 code that relies on errno being the same across threads may change behavior in this International Standard.

I understand <error.h> content is in header <cerrno> but we have to define errno as a macro. Can anyone explain what we can do so that errno would act the same way as it was in C++03 during multi-threading?

A: You don't need to change anything.
The change in the standard is purely because C++03 had no notion of threads, and the abstract machine model used by the standard to describe the semantics of standard C++ code needed to be updated for C++11 to support threads.
But the observable behaviour of errno in conforming C++ code stayed roughly the same, with the sole exception that errno is now defined thread-locally, and if your code assumes that the value of errno is the same across threads it will break.

A: C++11 us the first official standard that has a notion of multi-threading. This implies that if you use multiple threads in C++03 or C++98 you are using undefined behavior.
The whole idea about this change is about the following code:
functionThatSetsErrNo();
if (errno == something)
    ...

If you run this code and the execution results in functionThatSetsErrNo of thread 1, followed by functionThatSetsErrNo of thread 2, followed by the if-statements these if-statements do the right thing in C++11 and gave you a race condition in C++03 possibly combined with the errno of the second execution.
So what did change? If you after calling functionThatSetsErrNo started a thread, that thread no longer can read the errno value. Or similarly, if you have synchronization between threads and one calls the function and the other reads errno.
I hope this indicates that this change ain't too much to worry about as this delayed requesting of errno is something that is barely done and relying on transfer over threads is even done less.
If you do end up with this situation, you need to put a global std::atomic in your program and after execution assign errno into it while reading it from another thread. Although, I actually would recommend getting rid of such strange behavior.


text:
Q: AWS Cognito login to return as JSON I have this link :
https://{application}.auth.us-east-1.amazoncognito.com/oauth2/authorize?response_type=token&client_id={clientid}&redirect_uri=http://localhost
Above link will direct me to login page of Cognito.
How do I return the respond as JSON so I can set up the token in cookie or indexedDB ?

A: I've been researching Cognito.
The OpenId URLs like /oauth2/authorize are part of the Hosted UI.  The redirected requests are meant to go to a browser, and you can't configure these to use JSON.
What you will be more interested in is Cognito's API.  Requests and responses are all JSON; for example, the InitiateAuth endpoint is analogous to the /authorize endpoint of the Hosted UI.
The part I'm struggling with is that the Hosted UI supports OIDC features like PKCE for sending an authorization code to a server to securely pass the identity.  The API doesn't seem to have anything like this.


text:
Q: Google API : is there a more 'flexible' way to specify redirect URIs? I am using the Google API to allow users to upload videos to their YouTube channel using my web app.
While working on the app and testing it on my local machine, I have been using redirect URIs like this one :
https://localhost:5001/Youtube?handler=authorize.

The thing is, when the app gets deployed, the redirect URIs should not, of course, contain localhost:5001 but another host name. Without changing the URIs in the Google Console, I get the

"redirect_uri_mistmatch" error.

Is there any way I can add a redirect URI to the Google Console that would make my app work in both situations?
Thanks a lot for your help!

A: Redirect uris need to match exactly the location in your app that is capable of processing the authorization.
If your app is being hosted on a web server then you will need to add this redirect uri in google developer console as a valid redirect uri.  For security reasons you cant run localhost in production.   You will need to supply the redirect uri of your host when you deploy it for it to work.
There is no way to do this without changing it in developer console it must be configured as part of your app.
How to fix redirect uri miss match error


text:
Q: If $D\subset \Bbb R^p$ dense and f is a continuous function such that it cancels out in D, then f=0 I just wanted to show you my proof in order to check if i am correct or not, or if a am making big assumptions about certain stuff.

Being f a continuous function such that cancels out in D, a dense set. Then it follows that:
\begin{align*}
   &\ \lim_{x\to v}f(x)=f(v)=0-\forall v\in D\subset \Bbb R^p
   \\
  =&\ \lim_{h\to 0}f(v+h)=f(v)=0-\forall v\in D\subset \Bbb R^p
\end{align*}
Lets suppose that $f(x)\neq 0$. Then, it exists an $x_o \in \Bbb R^p$ such that
\begin{align*}
   &\ \lim_{h\to 0}f(x_o+h)=f(x_o)\neq0
\end{align*}
Then lets take an A$\subset \Bbb R^p$ and A being dense in $R^p$, in which $x_o\in A$. So, because D and A are dense then the union both are dense, then we have that $x_o\in A\cup D$ and from the hypothesis we conclude that:
\begin{align*}
   &\ \lim_{h\to 0}f(x_o+h)=f(x_o)=0
\end{align*}
That is a contradiction from the assumption that it was not zero. Then f(x)=0 for all x in $\Bbb R^p$.

My idea is that it doesn't matter which subset of $\Bbb R^p$ you take, you can always find a bigger subset that is dense and contains the one you propose, and from the hypothesis it would conclude that it is zero.

*Also I don't completely understand why it needs to be a continuous function, maybe because the only functions that cancel out elements from a certain vectorial space are always continuous? I would like some ideas about why?

A: For your last question: Consider the function that's zero on the rationals and 1 on the irrationals. It's zero on a dense set, but not zero everywhere. Hence continuity is necessary.
As a more extreme case, consider the function on the reals that's zero everywhere except at $\pi$, where it takes the value $1$.

A: if $|f(x_0)|\ne 0$ then $|f(x_0)|>\epsilon>0$ on a neighborhood of $x_0$
But $D$ is dense, so you can find a point $x_1$ in the neighborhood that belongs to $D$, so $f(x_1)=0$ contradiction.
A direct way: for $x\in \mathbb R^n$ construct the sequence $\{x_n:n\in \mathbb{N}\}\subset D$, $x_n\rightarrow x$ by choosing $x_n$ in the ball centered in $x$ and of radius $1/n$.
Then $f(x)=\lim_{n\rightarrow \infty}f(x_n)=0$

A: One of many equivalent def'ns of the continuity of a function $f:X\to Y$ is that whenever $A\subset X$ and $p\in cl_X(A)$ we have $f(p)\in cl_Y(\{f(a):a\in A\}).$  More briefly, $f:X\to Y$ is continuous iff  $$\forall A\subset X\;(\; f(cl_X(A))\subset cl_Y(f(A)\;).$$ In particular if $f$ is continuous and $f(A)=\{0\}$ then $f(cl_X(A)\}\subset cl_B(\{0\}).$
When $B=\mathbb R$ with the usual topology we have $cl_B(\{0\}=\{0\}.$ So if $A$ is dense in $X$ and $f:X\to \mathbb R$ is continuous, with $f(A)=\{0\},$  then $$\{0\}\subset f(X)=f(cl_X(A))\subset cl_{\mathbb R}f(A)=cl_{\mathbb R}\{0\}=\{0\}.$$


text:
Q: Grep-like tool to find matches in a JSON file returning the matched context I'm looking for a tool that, like grep, allows me to not only find matches to a json file, but it also returns the context of the match.
I'm aware that with:
cat json_file | grep -C30 properties

I would get the 30 lines around all matches with 'properties', but I'd like something that would give the surrounding body of the match, at different depth levels.
The following is an example of data.
It would be inside a file called json_file
{
"dataitem-1":{
    "aliases":{
        "dataitem-morning":{

        },
        "dataitem-evening":{

        }
    },
    "mappings":{
        "dataitem-temp":{
            "properties":{
                "dataset":{
                    "index":"not_analyzed",
                    "type":"string"
                },
                "fields":{
                    "properties":{
                        "channel":{
                            "index":"not_analyzed",
                            "type":"string"
                        }
                    }
                }
            }
        }
    }
},
"dataitem-2":{
    "aliases":{
        "dataitem-morning":{

        },
        "dataitem-evening":{

        }
    },
    "mappings":{
        "dataitem-temp":{
            "properties":{
                "dataset":{
                    "index":"not_analyzed",
                    "type":"string"
                },
                "fields":{
                    "properties":{
                        "channel":{
                            "index":"not_analyzed",
                            "type":"string"
                        }
                    }
                }
            }
        }
    }
}

I would like the tool to do something like:
cat json_file | json_grep -depth=4 'fields'

And it should return:
{
"dataitem-2":{
    "aliases":{
        "dataitem-morning":{

        },
        "dataitem-evening":{

        }
    },
    "mappings":{
        "dataitem-temp":{
            "properties":{
                "dataset":{
                    "index":"not_analyzed",
                    "type":"string"
                },
                "fields":{
                    "properties":{
                        "channel":{
                            "index":"not_analyzed",
                            "type":"string"
                        }
                    }
                }
            }
        }
    }
}


text:
Q: How can I view the Entity Framework LINQ query plan cache? I'm having issues with slow LINQ query compilation in EF6. I know EF caches the compiled query plans for LINQ queries, but that there are some gotchas (e. g. Enumerable.Contains prevents caching). I'd like to view the cache for debugging purposes to validate whether or not I'm getting proper caching for my queries. How can I do this?
Note: since this is purely for debugging, I'd be happy with an answer using reflection or other means that wouldn't be used in production.

A: You can reflect down to the cache using something like this (in EF 6.1.3):
var method = context.Database.GetType().GetMethod("CreateStoreItemCollection", BindingFlags.Instance | BindingFlags.NonPublic);
var storeItemsCollection = method.Invoke(context.Database, null);
var queryCacheManagerField = storeItemsCollection.GetType().GetField("_queryCacheManager", BindingFlags.Instance | BindingFlags.NonPublic);
var queryCacheManager = queryCacheManagerField.GetValue(storeItemsCollection);
var cacheField = queryCacheManager.GetType().GetField("_cacheData", BindingFlags.Instance | BindingFlags.NonPublic);
var cacheData = cacheField.GetValue(queryCacheManager) as ICollection;
foreach (var item in cacheData)
{
    Console.WriteLine(item.ToString());
}

Unfortunately, all the items in the cache are of internal types (in the System.Data.Entity.Core.Common.QueryCache namespace), so getting useful information out of them will require a bunch more reflection and poking around. Luckily, CompiledQueryCacheKey overrides ToString so it gives up a little (cryptic) information about itself. After running a single query (Table.Count()), the code above spits out these two entries:
[System.Data.Entity.Core.Common.QueryCache.ShaperFactoryQueryCacheKey`1[System.Int32], System.Data.Entity.Core.Common.QueryCache.QueryCacheEntry]

[FUNC<Edm.Count(In Transient.collection[Edm.Int32(Nullable=True,DefaultValue=)](Nullable=True,DefaultValue=))>:ARGS(([Project](BV'LQ1'=([Scan](DashboardAutoContext.Organizations:Transient.collection[DashboardAuto.Organization(Nullable=True,DefaultValue=)]))(1:Edm.Int32(Nullable=True,DefaultValue=)))))|||AppendOnly|True, System.Data.Entity.Core.Common.QueryCache.QueryCacheEntry]

Good luck figuring out what that means, or correlating things when you have a bunch of entries.
A different tactic I've had some success with is to create a class with a method I can assign to DbContext.Database.Log during testing. The class starts a timer when it sees an "Opened connection..." message, then stops the timer when it sees an "-- Executing at...". That time roughly corresponds to the time it takes EF to compile your LINQ query down to SQL. If your query is being cached, that time will shrink to almost nothing after the first time the query is executed; if it's not cached, the time will stay consistently high.
(It should go without saying that you'd only want to do this in a testing context.)

A: You can inject an IDbCommandTreeInterceptor implementation for logging any query tree creation. I used it successfully in a combination with a call stack keyed dictionary for spotting multiple compilations of "bad" queries.


text:
Q: Write a program that takes a character as input (string length 1) the output is the next character in the alphabet. If input is 'Z', output is 'A' Write a program that takes a character as input (a string of length 1), which you should assume is an upper-case character; the output should be the next character in the alphabet.
If the input is 'Z', your output should be 'A'.
Here's what i've done so far but I'm not getting A when I input Z. I'm getting [.
Please help, what am I doing wrong?
input = (input()).upper()
for character in input:
   number = ord(character) + 1
   number1 = chr(number)
   if ord('z'):
       new_number = ord(character) - 25
        number2 = chr(new_number)

print(number1)

A: A way of doing this may be via a match statement:
match (letter):
    case 'A':
        print('B')
    case 'B':
        print('C')

But you will need around 30 cases...

A better idea is to use a list:
letters = ['A', 'B', 'C'...]

then to get the letter
letter = input().upper()

and then to get the next element in the list:
print(letters[letters.find(letter)+1])

but there will be an error raised for 'Z', so you will need a try/except block for IndexError:
try:
    print(letters[letters.find(letter)+1])
except IndexError:
    print('A')

A: I have figured it out!! Thanks to everyone for reaching out with an alternative method! I'm ever grateful.
input = (input()).upper()
encrypted = ""
for character in input:
    if character == "":
        encrypted += ""
elif ord(character) + 1 > ord("Z"):
    encrypted += chr(ord(character) + 1 - 26)
else:
    encrypted += chr(ord(character) + 1)

print(encrypted)


text:
Q: Is C++ still considered as a statically typed language? I used to know that C++ is a statically typed language, but the newer C++ specification introduces a newer syntax auto which can determine the variable type by itself. So can C++ still be considered as a statically typed language?

A: C++ is still a statically typed language with the auto type specifier because auto denotes that the type will be inferred by the compiler at compile time. Rather then at run time in dynamically typed languages.

A:
So can C++ still be considered as a statically typed language?

Yes, because this code snippet still won't compile:
auto i = 42;   // 42 is an int -> i is an int
i = "test";    // can't assign a string to an int

A: No, this does not make C++ a dynamically typed language. auto is just a compile-time type inference method. The resulting code is exactly the same as without auto and the type cannot change at run-time.


text:
Q: How to give a file name to uploadFile EF C# I am uploading a file and wish to name it with one of the input fields which I wille be typing in my view. For ex: I type "Test" in my "Designation Commerciale" field. However, it gives me the NullReferenceException as it does not find any. Would appreciate your help. Thanks.
Controller:
public async Task<string> UploadFile(IFormFile file)
        {
            //bool iscopied;

            string resp = String.Empty;
            try
            {
                if (file.Length > 0)
                {
                    var model = new IdentificationProduitViewModel();
                    string x = model.DesignationCommerciale;
                    string filename = x + Path.GetExtension(file.FileName);
                    string path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "UploadFds"));
                    using (var filestream = new FileStream(Path.Combine(path, filename), FileMode.Create))
                    {
                        await file.CopyToAsync(filestream);
                    }
                    //iscopied = true;
                    resp = filename;
                }
                else
                {
                   // iscopied = false;
                    resp = String.Empty;
                }
            }
            catch(Exception)
            {
                throw;
            }
            return resp;
        }

HTTPPOST:
      string tryupload = await UploadFile(file_fds);
                if (!String.IsNullOrEmpty(tryupload))
                {
                    TempData["uploadok"] = "Fichier chargé avec success !";
                    model.Fds_Filepath = tryupload;
                }


text:
Q: php odbc_execute on stored procedure returns "wrong number or types of arguments" Executing php odbc_execute for an Oracle stored Procedure that always fails returning PLS-306: wrong number or types of arguments in call.
Paaram 1 is IN and params 2 and 3 are OUT. No matter what parameter types I try for params 2 and 3, always get the same error. I've searched the web but everything jsut regurgitates what's in the php manual.
$a = '05/11/2019';
$b = '';
$c = '';

$conn = @odbc_connect(dsn, userid, pwd);
$stmt    = odbc_prepare($conn, "CALL name(?,?,?)");
$success = odbc_execute($stmt, array($a, $b, $c));

Anyone have any idea how to resolve this?

A:
Paaram 1 is IN and params 2 and 3 are OUT. No matter what parameter types I try for params 2 and 3, always get the same error. I've searched the web but everything jsut regurgitates what's in the php manual.

That is your problem, you are providing the wrong number of arguments. Please review Oracle's documentation on Stored Procedures. https://docs.oracle.com/cd/B28359_01/appdev.111/b28843/tdddg_procedures.htm
Your stored procedure has 3 parameters - 1 IN parameter, and 2 OUT parameters. In your call to the procedure, you should only be providing 1 parameter - the IN parameter.
The 2 OUT parameters will be what are returned to you by the procedure. You do not provide values for these OUT parameters - the values will be calculated by the procedure.


text:
Q: Why my SQLite request in java code output only months from October(&&/10/&&)? Case: In my SQLite database date store as DATE type. Iam trying to show records from current month and if that month is 10, 11 or 12 everything is working but month from 1 to 9 is giving empty output.
'''
    LocalDate ld = LocalDate.now();
    int yearNumber = ld.getYear();
    int monthNumber = ld.getMonth().getValue();

    String queryString = "SELECT " +
            " *, " +
            "strftime('%m', DAY_DATE) as Month, " +   //  getting number of month from 01 to 12
            "strftime('%Y', DAY_DATE) as Year   " +   // getting number of year
            " FROM " + DAYS_TABLE +
            " WHERE "+"Month" +
            " LIKE "  + monthNumber +
            " AND " + "Year"+
            " LIKE " + yearNumber +
            " ORDER BY " + COLUMN_DAY_DATE +
            " DESC " ;

'''
What should i use to see records from each month?

A: The function strftime() returns a string and not a number, so strftime('%m', DAY_DATE) may return 05 and not 5.
If you want to compare it with a number you must convert it and this can be done implicitly by adding 0.
So change to:
 " WHERE (Month + 0) = "  + monthNumber +
 " AND (Year + 0) = " + yearNumber +
 " ORDER BY " + COLUMN_DAY_DATE +
 " DESC " ;


text:
Q: Google Analytics Regex error trying to specify number of matching digits in URL I am writing a Google Analytics query in JavaScript to get page views for pages of a certain URL structure.  The below works:
'filters': 'ga:pagePath=~some/path/here/\\d{4}$'

But I get an "invalid value for filter parameters" error when I specify that 1-4 digits at the end should match, like so:
 'filters': 'ga:pagePath=~some/path/here/\\d{1,4}$'

I'm not sure what I need to change to match URLs that end with 1-4 digits.  Thanks.


text:
Q: What is the relation between auto-layout and viewAnimation? override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    UIView.animate(withDuration: 0.5, animations: {
        self.animateLabel.center.x += 30
    })
}

Upper Label: Center for horizontal, and vertical.
Lower Label: Align leading to upper label, vertical space to upper label.
Then I put above code in ViewController to animate the upper label:
Then Run the simulator.
As you can see, these two label no longer aligned. Does that mean the auto-layout rule I set previously has been broken?
Yet, When I rotate the simulator, the upper label goes back to centre.
What is the relation between auto-layout and viewAnimation?

A: It isn't animation per se that is the issue, it is changing the view's frame directly that is causing your problem.
Essentially auto layout uses the constraints you have set to calculate the frame for each view.  When you modify the frame directly (or implicitly by modifying the center property) then you are effectively overriding the results of the auto layout process and the view is repositioned.
Anything that causes the auto layout process to run again will result in the frame  being recalculated according to the constraints.  Rotating the device will cause such a recalculation, as would calling self.animateLabel.setNeedsLayout.
When you are using auto layout you should never reposition views directly; you should modify the constraints and then trigger auto layout to move the views.
Assuming you are using a storyboard, you should create an @IBOutlet for the upper label's horizontal center constraint.  You can then animate this constraint:
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.animateLabel.layoutIfNeeded()   // Ensure auto layout is complete
    self.labelCentreConstraint.Constant = 30
    UIView.animate(withDuration: 0.5, animations: {
        self.animateLabel.layoutIfneeded()   // Recalculate auto layout
    })
}


text:
Q: (k)ubuntu 14.10 - graphic artifacts on intel today i have tried ubuntu and kubuntu 14.10.
I've experienced some graphical artifacts around the cursor.
Following issues have been observed:

*

*the cursor leaves a line of cursors on fast movement

*cursor disappeared if a input fields cursor is blinking

*moving araund the cursor shows rendering rectange around the cursor

(k)Ubuntu 14.04 works correctly in this cases.
Disabling the Desktop-Effects in KDE fixes the artifacts.
What could i do to fix that?
Thanks for the help.


text:
Q: Where are binaries that Visual Studio compile under CoreCLR? I want to write application and run it under Linux. So I wrote CoreCLR ConsoleApp and build it with Visual Studio 2015, but I can't find binaries. Literally there are no any binaries in any folder of my ConsoleApp solution.

A: In your project properties, check "Produce output on build" and the binaries will appear on disk.
By default, the compilation happens on the fly and it doesn't emit binaries.


text:
Q: Bugcheck error D1 I have a Dell PowerEdge R210 II Server, which is running Windows Server 2012 R2 SP1, and it is randomly rebooting with this error :
Bugcheck 0x000000D1 (0x000000000000000C, 0x0000000000000002, 0x0000000000000000, 0xfffff80001b04a16).
I tried to look up this error code and debug the dump file, although i am not familiar with this kind of practices, and i found that the error is due to bxnd60a.sys, which is a driver for an NIC adapter (Broadcom BCM5716C NetXtreme II GigE - client NDIS VBD in my case), according to what i found on some forums.
But when trying windows auto upgrade, it says that the driver is up to date, and also after trying to manually install the driver, the problem is still here.
Any help would be greatly appreciated,
thanks in advance.

A: I think i found a solution, because my server stopped rebooting.
All you have to do is to change some properties of the NIC adapter :
 1. Disable Large Send Offload in the adapter configuration pan
 2. Disable TCP Chimeny by entering this command : **netsh int tcp set global chimney=disabled**

A: When I disabled the LSO, the NIC became immediately disabled and would not re-enable.  I had to re-enable LSO to bring the NIC back online.


text:
Q: Upload file to firebase with angular / angularjs I'm using the following to upload images on my firebase storage via angular / angularfire:
<form ng-submit="uploadFile(file)">
  <input type="file" accept="txt" file-model="file" class="form-control">
  <button type="submit" class="btn btn-primary">Upload File</button>
</form>

and js:
app.directive('fileModel',['$parse', function ($parse){
 return {
restrict: 'A',
link: function (scope, element, attrs) {
  element.bind('change', function () {
    $parse(attrs.fileModel)
    .assign(scope, element[0].files[0])
    scope.$apply();
  })
}
}
}]);

app.controller('myController', ['$scope', '$firebaseStorage', function($scope,     $firebaseStorage) {

 // Create a Firebase Storage reference
 var storage = firebase.storage();
 var storageRef = storage.ref();
 var filesRef = storageRef.child('files');

 $scope.uploadFile = function(file) {
console.log("Let's upload a file!");
console.log($scope.file);
var storageRef = firebase.storage().ref("files");
// var storageRef = firebase.storage().ref("files");
$firebaseStorage(filesRef).$put($scope.file);
};

 }]);

The problem is if I upload another image after, it will replace the previous one uploaded ( I suppose it's due to the fact the file name is being taken as 'files', and so replace it automatically)
Is there a way to avoid this? For example, to upload the image with the name of the file instead?
How the path should be?
Thanks a lot for your help

A:    app.controller('myController', ['$scope','$firebaseStorage',function($scope,     $firebaseStorage) {

 // Create a Firebase Storage reference
 var storage = firebase.storage();
 var storageRef = storage.ref();
 var filesRef = storageRef.child('files');

 $scope.uploadFile = function(file) {
console.log("Let's upload a file!");
console.log($scope.file);
storageRef.child(file.name).put(file);
    storageRef.on('state_changed', function(snapshot) {
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;

            }, function() {
                //handle error
            }, function() {
           //url of storage file
                var downloadURL = storageRef.snapshot.downloadURL;
                console.log(downloadURL)
                //you will get url of snapshot
            });
     };

 }]);

you can use filename or timestamp .so everytime it will be unique.
<form ng-submit="uploadFile(file)">
  <input type="file" accept="txt" file-model="file" class="form-control">
  <button type="submit" class="btn btn-primary">Upload File</button>
</form>

let me know if you have any problem facing


text:
Q: Can't use resizebox with tikzpicture \documentclass[border=2mm,tikz]{standalone}
\usepackage{pgfplots}
\usepackage{tikz}

\begin{document}

    \begin{figure}[!htp]
%       \resizebox{0.4\textwidth}{!}{
        \begin{tikzpicture}
            \draw (0,0) circle (2cm);
            \node at (0,0) {Me};
        \end{tikzpicture}
%       }

    \label{fig:figure1}
    \end{figure}

\end{document}

This code works, but if I remove the comments (so that resizebox becomes active) I get a lot of errors:
Improper \prevdepth. }
Missing \endgroup inserted. }
Missing \endgroup inserted. }
Missing } inserted. }
\begin{figure} on input line 8 ended by \end{tikzpicture}. }
Too many }'s. }
Package graphics Error: Division by 0. }
Extra \endgroup. }
\begin{document} ended by \end{figure}. \end{figure}
Extra \endgroup. \end{figure}
running in backwards compatibility mode (unsuitable tick labels; missing features). Consider writing \pgfplotsset{compat=1.16} into your preamble.
Overfull \hbox (15.0pt too wide) in paragraph
Label(s) may have changed. Rerun to get cross-references right.

Even using \pgfplotsset{compat=1.16} there's an error.
What could it be wrong?

A: The option tikz of class standalone makes every tikzpicture environment captured to create a single cropped page, which is loosely equivalent to \standaloneenv{tikzpicture} and requires that tikzpicture is the outer most environment. Hence using tikzpicture as argument to other command/environment is buggy.
In your case, removing class option tikz and (manually) loading tikz do the work. Also, floating environment figure is unnecessary here.
\documentclass[border=2mm]{standalone}
\usepackage{tikz}

\begin{document}

\resizebox{0.4\textwidth}{!}{%
  \begin{tikzpicture}
    \draw (0,0) circle (2cm);
    \node at (0,0) {Me};
  \end{tikzpicture}%
}

\end{document}

Note the two % added to remove the space characters converted from newlines.


text:
Q: Using inline variables in visual studio I am currently using Visual Studio 2017 Community Edition and I tried to declare this in my header file:
inline static int counter{1};

Now VS underlines it red and tells me that 'inline' can only be used for functions, although it should be possible since C++17.
Is there a way to still use it in VS or do I have to work around?

A: As of Nov. 15, 2017, inline variables are scheduled to be supported in Visual Studio 15.5.  You can see the "current" status of features here
 or here .


text:
Q: MongoDB Write Issue: Different DBs showing different count for same documents I am trying to BulkInsert certain documents in different collections in 2 Databases in MongoDB.
MongoClient mongoClient2 = this.getMongoClient();
MongoDatabase currentDB = mongoClient2.getDatabase(splits[0]);
MongoCollection<Document> currentCollectionNew = currentDB.getCollection(splits[1])
                        .withWriteConcern(WriteConcern.MAJORITY.withJournal(true))
                        .withReadConcern(ReadConcern.MAJORITY);

BulkWriteOptions bulkWriteOptions = new BulkWriteOptions();
bulkWriteOptions.ordered(true);
bulkWriteOptions.bypassDocumentValidation(true);
try {
     BulkWriteResult bulkWriteResult = urrentCollectionNew.bulkWrite(listDoc,
                            bulkWriteOptions);

   logger.info("bulkWriteResult inserted count in MAIN: " + bulkWriteResult.getInsertedCount());
   logger.info("bulkWriteResult modified count  in MAIN: " + bulkWriteResult.getModifiedCount());
   logger.info("bulkWriteResult matched count in MAIN : " + bulkWriteResult.getMatchedCount());
   logger.info("bulkWriteResult deleted count in MAIN : " + bulkWriteResult.getDeletedCount());
    logger.info("bulkWriteResult upserted count in MAIN : " + bulkWriteResult.getUpserts().size());
    logger.info("bulkWriteResult was acknowledged in MAIN : " + bulkWriteResult.wasAcknowledged());

    mongoClient2.close()
 } catch (Exception e) {
    logger.warn("Error in bulkWriting main DB: {} ", e.getMessage());
    logger.error(e.getMessage(), e);
                }

    MongoCollection<Document> mongoStageCollection = objFactory.getCollectionObject(resourceType, true);
    String[] splitsStage = mongoStageCollection.getNamespace().getFullName().split("\\.");
    MongoClient mongoClient3 = this.getMongoClient();
    MongoDatabase newStageDB = mongoClient3.getDatabase(splitsStage[0]);
    MongoCollection<Document> stageCollectionNew = newStageDB.getCollection(splitsStage[1])
                        .withWriteConcern(WriteConcern.MAJORITY.withJournal(true))
    .withReadConcern(ReadConcern.MAJORITY);

    logger.info("mongoStageCollection.getWriteConcern(): {} ", mongoStageCollection.getWriteConcern());
    logger.info("mongoStageCollection.getReadConcern(): {} ",
      mongoStageCollection.getReadConcern().toString());
    logger.info("mongoStageCollection.getReadPreference(): {}",
                        mongoStageCollection.getReadPreference().getName());

    try {
          BulkWriteResult bulkWriteResult = stageCollectionNew.bulkWrite(listDoc, bulkWriteOptions);

          logger.info("bulkWriteResult inserted count in STAGING: " + bulkWriteResult.getInsertedCount());
          logger.info("bulkWriteResult modified count  in STAGING: " + bulkWriteResult.getModifiedCount());
           logger.info("bulkWriteResult matched count in STAGING: " + bulkWriteResult.getMatchedCount());
           logger.info("bulkWriteResult deleted count in STAGING: " + bulkWriteResult.getDeletedCount());
           logger.info("bulkWriteResult upserted count in STAGING: " + bulkWriteResult.getUpserts().size());
           logger.info("bulkWriteResult was acknowledged in STAGING: " + bulkWriteResult.wasAcknowledged());
          mongoClient3.close();
                } catch (Exception e) {
                    logger.warn("Error in bulkWriting STAGING DB: {} ", e.getMessage());
                    logger.error(e.getMessage(), e);
                }

e.g.
2 DBs are FHIR and FHIR_Stage.
Identical Collections are created inside both the DBs.
FHIR.Condition  and FHIR_STAGE.Condition
FHIR.Observation and FHIR_STAGE.Observation
and so on...
FHIR is supposed to have all the data while FHIR_Stage is supposed to have only the incremental data.
However, in the initial load both the DBs should contain exactly the same data.
What I am seeing is that the counts in the Collections in these 2 DBs does not match
i.e. count in FHIR.Condition is not same as in FHIR_STAGE.Condition
The issue here is this mismatch occurs randomly, i.e. it matches sometimes and sometimes it doesn't ( when I cleanup everything and re-run the initial load)
And this happens for different Collections in those 2 DBs.
And there is NO pattern to it, randomly some collection count wont match and sometimes everything would match.
I have not be able to wrap my head around this for a week now.
Any help is greatly appreciated.
MongoDB Setup:
We have a 3 node (VM) cluster. We have 3 shards running, each shard is a 3 member replica set. Each node is a primary for one of the replica set.
The cluster is secured using x509 certificates.
I see no errors either in sh.status() or rs.status().
There is also NO replication lag.
The DBs and the Collections are created dynamically from the Java code depending on some business logic. And I am also enabling sharding on the DB and then on the collections from the code.
WriteConcern - Majority
ReadPreference - Primary
ReadConcern - Majority
Mongo-version : 3.4.15
Mongo Java Driver : 3.4.2
FYI -- the same code base works as expected on a standalone MongoDB.
Thanks in anticipation.
I will be happy to share more information if needed.
P.S.
If it makes any difference, the process writing to MongoDB is a Kafka Consumer

A: We found the issue a few days after posting this -
Ours is sharded MongoDB cluster.
This was because we weren't using the count() function from the aggregation pipeline instead relying on db.collectionName.count()
Moving to aggregation pipeline, we could see equal documents in both DBs.
Reference points it out.


text:
Q: Can one make an A4 printer print on longer seamless paper strips? Some printers marketed as A3 printers (29.7cm x 42cm), like the Epson Stylus T1110 in Latin America, are reported to print pages up to 111cm.
A friend of mine needs to print teaching materials on 15cm x 50cm strips, has anyone managed to do anything similar on cheap A4 inkjet printers?
The point is to save time from lots of cutting & pasting he currently does.


text:
Q: Best Android Scheduler to Update UI I am new to Android and working on this chat app where I want to change an Activity element based on a predetermined data on predetermined exact times. It doesn't have to work when app or phone is closed but I want to send notifications as well with the change. There is AlarmManager, JobScheduler, Handler, Timer, WorkManager but I am extremely confused about how they compare to each other. Which is the best option in this case?

A: In fact, WorkManager under the hood uses all of these scheduling APIs depending on the API level. This means that you won't have to deal with finding the best API for devices, because WorkManager will pick up the appropriate API for you.
You can also read the official documentation for more info and comparison: https://developer.android.com/topic/libraries/architecture/workmanager

The WorkManager API is a suitable and recommended replacement for all
previous Android background scheduling APIs, including
FirebaseJobDispatcher, GcmNetworkManager, and Job Scheduler.


text:
Q: Is it possible to convert external Ubuntu installation from CSM to EUFI? I'm dual booting Windows 10 (on internal SSD) and Ubuntu 21.04 (on external SSD). Grub is only installed on external SSD, so when it's unplugged PC boots directly into Windows.
I switched from CSM to UEFI booting (this was required to enable SAM on my AMD GPU) and Ubuntu does not boot anymore. However, if I run Ubuntu live from USB stick, it tells me it's is already installed on my external SSD.
Is there a way to boot my external Ubuntu installation? I wouldn't want to reinstall because everything is set up the way I like it.

A: You can reinstall Grub2 using your Ubuntu live stick.
Mount the partition your Ubuntu Installation is on. If you are not sure which it is, launch GParted (included in the Live CD) and find out. It is usually a EXT4 Partition. Replace sda1 with the drive and partition number your installation is on, for example:

sudo mount -t ext4 /dev/sda1 /mnt

Now bind the directories that grub needs access to to detect other operating systems, like so.

sudo mount --bind /dev /mnt/dev &&
sudo mount --bind /dev/pts /mnt/dev/pts &&
sudo mount --bind /proc /mnt/proc &&
sudo mount --bind /sys /mnt/sys

Now we need to mount chroot:

sudo chroot /mnt

Now install, check, and update grub.
This time you only need to add the drive letter (usually a) to replace , for example:

grub-install /dev/sda
grub-install –recheck /dev/sda
update-grub

Now grub is back, all that is left is to exit the chrooted system and unmount everything.

exit &&
sudo umount /mnt/sys &&
sudo umount /mnt/proc &&
sudo umount /mnt/dev/pts &&
sudo umount /mnt/dev &&
sudo umount /mnt

Shut down, take out the usb-stick and turn your computer back on, and you will be met with the default Grub2 screen.
If you want to put grub on your internal SSD ( where your Windows is installed ) you need to set it to your internal drive.
Although I don't see the point in this ( without the external disk it cannot boot into Ubuntu. ( see gparted ).
In my case nvme0n1. see picture
If you want to put grub on your external SSD use that drivename. In my case
sda ( external usb-stick ). see picture
If you put grub2 on your external disk and want to boot from it you have to change your settings in your ( what many people still call ) BIOS to boot from usb first.
And Nixie has a video on youtube about this: enter link description here
This should get you booting into Ubuntu again.


text:
Q: How to make float navbars with JS and CSS? How can I make my lower navbar to stay in the top when I scrolling down? I mean I want to hide only upper navbar? The lower navbar should take place of upper nav.
I tried to affix function:
$('.navbar-lower').affix({
    offset: {top: 50}
});

But my code doesn't work.
Here is my try on jsFiddle: http://jsfiddle.net/hw3gxhhf
How can I fix it?
PS
Also I use jquery.bootstrap-autohidingnavbar.min.js
$("div.navbar-fixed-top").autoHidingNavbar({
    "showOnBottom": false,
    "showOnUpscroll": false
});

A: You can always listen for the scroll event, and check the scrollTop value. Once you've reached the 50px threshold, you change the margin-top value:
window.addEventListener('scroll', function(){
    if (document.body.scrollTop >= 50) {
        $('.navbar-lower').css('margin-top','0px');
    } else {
        $('.navbar-lower').css('margin-top','50px');
    }
})

A: Try using the .scroll function to addClass of position:fixed;
and z-index:10;
script-
$(window).scroll(function () {
var scrolled = $(window).scrollTop();
var elemTop  = $('#move').offset().top;

if (scrolled >= elemTop) {
  $('body').addClass('nav-is-fixed');
}
else {
  $('body').removeClass('nav-is-fixed');
}
});

css-
.nav-is-fixed #move {
 position: fixed;
top: 0;
z-index:10;
}


text:
Q: How to convert this queryto Laravel ORM Hi guys I'm new learner Laravel.
I can not  convert belowed SQL query, please help me to solve the problem.
SQL query is worked fine just I want to convert it Laraver Eloquent ORM.
select distinct u.*, d.user_id, r.region_name from users as u
                left join devices as d on d.user_id = u.id
                left join region as r on r.region_id = u.region_id
                where d.user_id is null and u.`role` = 3
                order by u.id asc

A: Here you go:
DB::table('users as u')
        ->select('u.*', 'd.user_id', 'r.region_name')
        ->distinct()
        ->leftJoin('devices as d', 'u.id', '=', 'd.user_id')
        ->leftJoin('region as r', 'u.region_id', '=', 'r.region_id')
        ->whereNull('d.user_id')
        ->where('u.role',3)
        ->oldest('u.id')
        ->get();


text:
Q: Fantasy book help, read back in the early 1990's I've been searching the net in vain for a long time now and got nowhere, well until I found this site. Here is to hoping you can help me.
Back when I was in Secondary school (UK) in the early 1990's I borrowed from the school library a fantasy style book. Now sadly I cannot remember much about it other than it had your typical "assembled group" of young boy/hero, a warrior, a magician etc etc.
All I can remember of the book was when they fight the main villain/antagonist at the end the fight is desperate and the hero seems to think that his magician friend has been killed yet notices his hand twitching. Then a Demi-God appears who was summoned by the magician who was actually carving runes with his hand on the floor of the battle area.
I may be remembering wrong but I think the magician had a twin brother, the boy had/met a girl companion with a possible romantic link developing. They travel to the enemies castle/cave/domain and attempt to battle him and as said the magician summons a demi-god to defeat the evil antagonist. Any help would be greatly appreciated.
That is all I can remember unfortunately so any help, assistance or nudges in the direction of will be most appreciated.

A: Per Chris Green's comment in another answer, the book he was seeking was Douglas Hill's Master of Fiends, which is the sequel to his Blade of the Poisoner. The same series has been previously asked about and self-answered here at:
Magic similar to psychic abilities, including hiding the group and starting fires
and also perhaps in the following posts without accepted answers:
1) Elemental novel where a boy discovers he has the power over fire and later over all elements
2) Book ID: YA fantasy novel, possibly from the 80s, where main characters have special abilities
3) Book identification - quest to defeat impending magical death

A: I remember reading some Dragonlance books by Weis and Hickman which included a magician called Raistlin and I'm sure there was a quest etc (which is most fantasy books I know) https://en.wikipedia.org/wiki/Raistlin_Majere#Publication_history I can't remember the specifics but it sounds similar I guess..... and if its not then you could read them as they are great books from what I remember.


text:
Q: how to check if xml file has more than one child values using php i have xml file $file.xml which includes the following
<?xml version="1.0"?>
<names><name>name1</name><name>name2</name><name>name3</name></names>

i need a way to check if <names> has more than one child <name> meaning that if the file has more than <name>name1</name> whick means that if <name>name2</name> or more exist to call a function.
i have tried the following
    $file = "file.xml";

    $result = file_get_contents($file);

    if(@count(file($result)) > 1) {

    //perform a function
    }

the file_get_contents already gave me the values name1 name2 and name3
but the if(@count(file($result)) > 1) { did nothing
Thanks in advance

A: Yes its quite possible, you could use xpath in conjunction with this case:
$file = "file.xml";
$xml = simplexml_load_file($file);
$names = $xml->xpath('/names/name');
if(count($names) > 1) {
    //perform a function
    echo 'perform!';
}

Or an alternative with DOMDocument with xpath as well:
$dom = new DOMDocument();
$dom->load($file);

$count = $xpath->evaluate('count(/names/name)');
if($count > 1) {
    echo 'perform!';
}


text:
Q: Import json with missing keys into postgres with Flask-Sqlalchemy I have a question you guys might be able to answer.
I have a json file that looks something like this:
[
{
        "address": "some address",
        "full_time_school": false,
        "name": "some name",
        "official_id": "722154",
        "school_type": "Grundschule",
        "school_type_entity": "Grundschule",
        "state": "BW"
    },
    {
        "address": "some other address",
        "name": "some other name",
        "official_id": "722190",
        "state": "BW"
    }
]

The point is that not every entry has all keys.
I have a flask-sqlalchemy model that looks like this:
class School(db.Model):

    __tablename__ = "school"  # pragma: no cover

    address = db.Column(db.String)
    full_time_school = db.Column(db.Boolean)
    name = db.Column(db.String)
    official_id = db.Column(db.Integer)
    school_type = db.Column(db.String)
    school_type_entity = db.Column(db.String)
    state = db.Column(db.String)

    def __repr__(self):
        return f"<name {self.name}"

And I have a python script to add the json entries into my postgresql database that looks like this:
from my_project import db
from my_project.models import School

import json
import os

# insert data
for filename in os.listdir("datamining"):
    if filename.endswith(".json"):

        file = open(os.path.join("datamining", filename))

        print(f"Add schools from {filename.strip('.json')}")

        data = json.load(file)

        cleaned_data = {school["official_id"]: school for school in data}.values()
        print(f"Adding {len(data)} schools to the database.")

        for school in cleaned_data:
            entry = School(
                    id=school["official_id"]
                )
            for key, value in school.items():
                entry.key = value

            db.session.add(entry)
            db.session.commit()
        file.close()

print("Added all schools!!!")

I don't know why but somehow every cell is NULL except the official_id field. How so and how can I fix that? I'm at the end of my wits right now. Every pointer or help is much appreciated.
EDIT:
What I found out so far is, that entry.key is not interpreted as entry.state for example, but actually creates a reference entry.key = "BW" for example. Why is that?

A: Your problem is
entry.key = value

You are just writing your values over and over into the attribute 'key' within your School model. I'm actually surprised SQLAlchemy doesn't raise some kind of error here...
Just pass all your values into the constructor and you should be fine:
school["id"] = school.pop("official_id")
entry = School(**school)

EDIT: It's "BW" because this happens to be the last value that is written into the attribute.

A: You can do this much easier and faster all in one go by executing this native parameterized query passing the text contents of the JSON file as parameter jsontext:
insert into school
 select * from jsonb_populate_recordset(null::school, :jsontext::jsonb);


text:
Q: Sorted PHP Array to New Array I have an array that looks like this:
Array
(
    [0] => Array
        (
            [0] => A
            [1] => -1
            [2] => -1
        )

    [1] => Array
        (
            [0] => B
            [1] => 0
            [2] => 1
        )

    [2] => Array
        (
            [0] => C
            [1] => -1
            [2] => 0
        )

)

My objective is to sort this array by each nested array, meaning that I want to sort the array by the values of [1] in each, then by the values of [2] in each, etc. My current code is below, and I can understand why it doesn't provide the result that I want. Each time the loop passes through, it overrides $csvarray and I get just multiples of the same thing.
I want to put each sorted array into its own array so I can display them in an HTML table later. I've tried setting variables using $i but have had no success.
for ($i = 1; $i < count($csvarray); $i++) {
    uasort($csvarray, function($a, $b) {
        return $b[$i] <=> $a[$i];
    });

    echo "
";
    print_r($csvarray);
    echo "
";

}

User AbraCadaver gave me the correct answer for what I was looking for, with the following:
for ($i = 1; $i < count($csvarray); $i++) {
    array_multisort(array_column($csvarray, $i), SORT_DESC,
                    $csvarray, SORT_DESC);

    echo "
";
    print_r($csvarray);
    echo "
";

}

A: I would just extract those columns, sort them and then sort the original:
array_multisort(array_column($csvarray, 1), SORT_DESC,
                array_column($csvarray, 2), SORT_DESC,
                $csvarray, SORT_DESC);

If you want SORT_ASC (ascending), then you can omit those arguments entirely as that is the default.
For a dynamic number of columns you could try this:
foreach($csvarray as $row) {
    array_shift($row);
    $values[] = implode('|', $row);
}
array_multisort($values, $csvarray);


text:
Q: Does sockets.io emit sometimes fail? I have a web based multiplayer game. It happens from time to time that someone is kicked out because server did not get expected message from client. It seems from my logs that client did not disconnect, just did not send message or server did not receive it. My question here is "Does this things happen normally from time to time?" Should i use some kind of callback mechanism to ensure message is delivered and if not send it again or is there some issue that i am not aware?

A: socket.io already provides ACKs and message ID tracking, on top of TCP.
Also, socket.io uses pings to check the connection. So, if you say that the client is not disconnected, and the server tells that the client is not disconnected, then the connection is still there.
The problem must be situated elsewhere.
Are you sure there is not a bug in either part of the implementation? Showing some code snippets could help, as well as the environment you are using.


text:
Q: Activity missing data on return So I have my main activity which holds a list view and has a map which holds all my data for the list. Upon clicking on an item you are taken to a details display. When I press the back button to get back to the main activity from the detail activity, if I set a break point, my map keys are still intact, but all the strings in the objects are "" and the ints are -1. Here is what my main activity looks like:
public class MainActivity extends Activity {
    private Map<String, Stunt> stunts = new LinkedHashMap<String, Stunt>();
    private StuntsDao stuntsDao;
    private ListAdapter listAdapter;

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

        stuntsDao = new StuntsDao(getApplicationContext());

        stunts = stuntsDao.getAllStunts();

        listAdapter = new ListAdapter(this, R.layout.list_layout, new ArrayList<Stunt>(stunts.values()));
        ListView listView = (ListView)findViewById(R.id.listView);

        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String stuntName = (String)((ViewHolder)view.getTag()).stuntName.getText();
                Intent myIntent = new Intent(getApplicationContext(), StuntDetails.class);
                getStuntDetailsIfNeeded(stuntName);
                Stunt stunt = stunts.get(stuntName);
                myIntent.putExtra("STUNT", stunt);
                startActivity(myIntent);
            }
        });
    }
...

}

Why would the objects in my map be basically empty?

A: onCreate() doesn't get called when you click back. You need to init your data again in onStart or onResume. See: http://developer.android.com/training/basics/activity-lifecycle/starting.html


text:
Q: Trouble with adding ServiceReference I try to add some ServiceReference in Windows 8.1 app (Windows-Store app). ServiceReference can be created, but the file Reference.cs in my Reference folder is empty. What this problem is connected with? Should I apply some special settings when I add this reference?

A: Solutions:
Right-click on your service reference and click configure and uncheck "Reuse Types in Referenced Assemblies"
If that doesn't help, try running svcutil.exe


text:
Q: Android WebRTC supported codec I just read in a thread on google that is not possible for Honor and Huawei to encode to H264 when using webrtc :
https://groups.google.com/forum/#!searchin/discuss-webrtc/huawei$20h264%7Csort:date/discuss-webrtc/EA14U8FMT_k/Jn3CEG7YCQAJ
Is that true ???
That seem really strange, that we couldn't do that...
also, I read that thread because, I arrive to encode my stream with a Samsung but not with a Huawei P20. (with Huawei the stream created stay PV8 instead with other device I tested who are H.264)
Here it's the code in WebRTC that prove to the guy that is not supported buy Huawei and Honor :
final ArrayList<MediaCodecProperties> supported_codecs = new ArrayList<MediaCodecProperties>();
    supported_codecs.add(qcomH264HwProperties);
    supported_codecs.add(exynosH264HwProperties);
    if (PeerConnectionFactory.fieldTrialsFindFullName("WebRTC-MediaTekH264").equals("Enabled")) {
      supported_codecs.add(mediatekH264HwProperties);
    }
    return supported_codecs.toArray(new MediaCodecProperties[supported_codecs.size()]);
 }

I can add piece of my code if needed.
Thanks for reading.

A: Yes its bad, if you look in the source code here (function isHardwareSupportedInCurrentSdkH264()) there are no mention of hisilicon just qualcomm exynos.
I've seen people solve this problem in this issue just forcing the sdp in the offer but it doesnt work for me.

A: I dont know if it will be fixed, i think not...
You can switch to vp8 codec, it has sw encode/decode fallback and it works on huawei devices.


text:
Q: What is the best practice for doing httpclient call parallelly/sequentially with very good performance and without loosing data We got a requirement to execute bulk API request(more than 1000 calls) and save response data in database.
Initially we got 10-20 API calls requirement. For these requests we used simple 'for loop' with single instance of HTTPClient to fetched data and saved it to database.
Later we got 100-200 API calls requirement. For these requests we used Parallel.ForEach with single HTTPClient instance but we are getting socket issues. so we created new instance for each request. even this approach causing issue on server .
Now requirement is to execute 1000+ API calls.
With single HTTPClient instance using 'await' taking hours to complete the operation.
Is there any way or good practice for doing 1000+ api call with very good performance and without loosing data in C#?

A: You can try a combination of the solution in the comments with the when all: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=net-5.0
private static HttpClient Client = new HttpClient();
public static async Task Main(string[] args)
{
    var tasks = new List<Task>();
    Console.WriteLine("Starting connections");
    for(int i = 0; i<10; i++)
    {
        tasks.Add(Client.GetAsync("http://aspnetmonsters.com"))
        Console.WriteLine(result.StatusCode);
    }
    Task t = Task.WhenAll(tasks);
    try {
       t.Wait();
    }
    catch {}
    Console.WriteLine("Connections done");
    Console.ReadLine();
}


text:
Q: Best way to remove CSS rounded-corner halo? I'm getting a tiny rounded corner halo effect that I'd like to get rid of. In this example, look for the effect in the red circle. Here's a zoom in of the effect:

I seem to recall a while back reading an article on just this problem. Anyone have a link to that article? Otherwise, any good ways to get rid of the halo?
It is being caused because the dl has all four corners rounded. This allows the bottom of the dl to be rounded. The dt sits over the dl and has its top left and top right corners rounded. But there is a slight overflow of the dl curve behind the dt curve, causing the halo.
My solution is to increase the border-radius of the dl so that it is hidden behind the dt corner. But it seems like a hack and adds a fair amount more CSS. I'm wondering if there is a better solution. Here it is without the halo:

A: If you don't mind a 2 pixel discrepancy you could add...
div.content dt.top {
  position: relative;
  top: -2px;
}

But I think your solution is good, it can be improved by using the shorthand version of border radius:
http://jsfiddle.net/DAjWS/
border-radius: [topleft] [topright] [bottomright] [bottomleft]

The article you are mentioning probably has to do with the combination of border with border-radius (it produces a halo similar to yours), but in your case it's expected. The same thing would happen in a vector editing app if you overlapped two boxes with rounded corners. you just have to find an elegant way of covering the anti-aliasing of the bottom box.

A: I just came across the article that I mentioned in my question. It was linked to from html5boilerplate.com. Essentially, the following webkit CSS will get rid of the bleed (or halo as I called it):
-webkit-background-clip: padding-box;


text:
Q: What does "type=1" mean in a .wav file? If you unpack the data in a wav file between bytes 20 and 35 inclusive (I think) you get different values for type, channels, samplerate, bytespersec, alignment and bits.
[type] => 1
[channels] => 1
[samplerate] => 8000
[bytespersec] => 16000
[alignment] => 2
[bits] => 16

What does type=1 mean? Is there a type = 2? If there is, is that still a wav file? I'm trying to ask Google and I keep getting results like "What is a wav file?" that don't mention anything I'm asking here.

A: 1 seems to imply the data is in the PCM format. Other values would indicate some other format.
http://soundfile.sapp.org/doc/WaveFormat/
20        2   AudioFormat      PCM = 1 (i.e. Linear quantization)
                               Values other than 1 indicate some
                               form of compression.


text:
Q: Move Minute hand in Android clock I am trying to write a simple proof of concept app that allows a user to rotate minute hand of a clock. I am having hard time coming up with the right logic for OnTouchEvent.
So far I have the following code:
    public boolean onTouchEvent(MotionEvent e) {

       float x = e.getX();
       float y = e.getY();

    switch (e.getAction()) {
    case MotionEvent.ACTION_MOVE:
        //find an approximate angle between them.

        float dx = x-cx;
        float dy = y-cy;
        double a=Math.atan2(dy,dx);

        this.degree = Math.toDegrees(a);
        this.invalidate();
    }
    return true;
    }

protected void onDraw(Canvas canvas) {
    super .onDraw(canvas);

    boolean changed = mChanged;
    if (changed) {
        mChanged = false;
    }

    int availableWidth = getRight() - getLeft();
    int availableHeight = getBottom() - getTop();

    int x = availableWidth / 2;
    int y = availableHeight / 2;

    cx = x;
    cy = y;

    final Drawable dial = mDial;

    int w = dial.getIntrinsicWidth() + 100;
    int h = dial.getIntrinsicHeight() + 100;

    boolean scaled = false;

    if (availableWidth < w || availableHeight < h) {
        scaled = true;

        float scale = Math.min((float) availableWidth / (float) w, (float) availableHeight / (float) h);

        canvas.save();
        canvas.scale(scale, scale, x, y);
    }

    if (changed)
    {
        dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
    }

    dial.draw(canvas);

    canvas.save();
    float hour = mHour / 12.0f * 360.0f;

    canvas.rotate(hour, x, y);

    final Drawable hourHand = mHourHand;

    if (changed) {

        w = hourHand.getIntrinsicWidth() + 30;
        h = hourHand.getIntrinsicHeight() + 30;

        hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y  + (h / 2));
    }

    hourHand.draw(canvas);
    canvas.restore();

    canvas.save();
    float minute = mMinutes / 60.0f * 360.0f;

    if (bearing == 0)
    {
        canvas.rotate(minute, x, y);
    }
    else
    {
        canvas.rotate((float)bearing, x, y);
    }

    final Drawable minuteHand = mMinuteHand;

    if (changed) {

        w = minuteHand.getIntrinsicWidth() + 30;
        h = minuteHand.getIntrinsicHeight() + 30;

        minuteHand.setBounds(x - w, y - h, x + w, y  + h);
    }

    minuteHand.draw(canvas);
    canvas.restore();

    if (scaled) {
        canvas.restore();
    }
}

Then based on that, my OnDraw method rotates the minute hand to the specified "this.degree"(just calls canvas.rotate). I am assuming my math is off here.  I tried to follow the example here: Calculate angle for rotation in Pie Chart, but that's still not rotating the minute hand correctly. Any help would be appreciated.

A: The math looks correct. Your calculations should give you the angle of the touch event, where a touch that is to the exact right of the center point should give you 0 degrees.
A few things to watch out for

*

*Make sure that you're rotating in the correct direction. It is hard to keep this straight, and thus easy to screw it up

*Make sure that you're taking into account that a value of 0 means that the minute hand should be pointing to the right. For example, if you start out with a minute hand that is pointing upwards, you would have to add/subtract 90 degrees to the result of your calculation (depending on the direction of rotation - not sure which is correct offhand)

*Make sure that (cx, cy) is the center point around which you want to calculate the angle

*When rotating, you'll need to either use the 3 arg Canvas.rotate(float, float, float) method, or add an additional translation seperately, to make sure that you are rotating around the correct point. Without any translation, it will rotate around (0,0) (the top left corner of the view)

More on rotation:
Rotation always happens around the "current" (0,0) point. By "current", I mean the (0,0) point after the current matrix has been applied. When you first enter onDraw, the (0,0) point should be the upper-left corner of the view. Whenever you apply a translation/scaling/etc, you will potentially change where the (0,0) point is, relative to the view.
I think something like the following should work, in regards to setting the correct center of rotation:
//first we save the initial matrix, so we can easily get
//back to this state after we're done rotating
canvas.save();
//I *think* you need to negate the center offsets here,
//because you are conceptually moving the canvas, rather
//than moving the center directly
canvas.translate(-cx, -cy);
//<perform the rotation and draw the clock hand>
//...

//and now restore the matrix back to the initial state
canvas.restore();

A:
Your calculation is good for measuring angle for minutes hand to
  rotate in corresponding quadrants in analog clock... here with little
  bit changes can make either minutes or hours hand to rotate at the
  touch position....call the below method in onTouch() method for action move

public float getRotationAngle(float x, float y) {
        float dx = x - cx;
        float dy = y - cy;
        double a = Math.atan2(dy, dx);

        double degree = Math.toDegrees(a)+90;
        if(angle<0){
            degree=degree+360;
        }
        return (float) degree;
}

i have this approach with as vectors concept for calculating the angle but if little bit more than your code if u want i will give that logic....


text:
Q: Use sed to modify xml file I need to search an xml file for some text that resides within a start/end tag and if found, to write a line of text just before the end tag.
Eg, in the XML file I need to search MyTag for "MyText1". If found, add FoundIt right before the end tag as shown below
 <MyTag>
 <Tag1>MyText1</Tag1>
 <Tag2>MyText2</Tag2>
 <Tag3>MyText3</Tag3>
 <Tag4>MyText4</Tag4>
 <FoundTag1>FoundIt</FoundTag1>
 </MyTag>

I was able to use sed to search for the range and print MyText1. But what I really want to be able to do is add the "FoundIt" tag right before the end tag.
Sed Script
/<MyTag>/,/<\/MyTag>/{
/<Tag1>MyText1</Tag1>/p
}

XML File Contents
<XmlFile>

<BeginTag>
<SomeTag>Text</SomeTag>
</BegingTag>

<MyTag>
<Tag1>MyText1</Tag1>
<Tag2>MyText2</Tag2>
<Tag3>MyText3</Tag3>
<Tag4>MyText4</Tag4>
</MyTag>

<EndTag>
<SomeTag>Text</SomeTag>
</EndTag>

</XmlFile>

A: This might work for you (GNU sed):
sed '/<MyTag>/!b;:a;/<\/MyTag>/!{$!{N;ba}};/MyText1/s/.*\n/&<FoundTag1>FoundIt<\/FoundTag1>\n/' xml_file

Look for a line containing <MyTag> if not bail out. Once found, collect lines until the line </MyTag> occurs, then check if those lines contain MyText1 and if so substitute  <FoundTag1>FoundIt</FoundTag1> followed by a new line before the last line collected.

A: You can try this:
sed -n '
    /<MyTag>/,/<\/MyTag>/!{p;};
    /<MyTag>/,/<\/MyTag>/{H;};
    /<\/MyTag>/{s/.*//;x;};
    /.*MyText1.*/{s/<\/MyTag>/<FoundTag1>FoundIt<\/FoundTag1>\n&/;};
    /<\/MyTag>/{p;};
' \
xml_file


text:
Q: How to return the result based on Queryset in django rest framework? I am writing a Django Rest API and my use case is like this:
Here is my endpoint: http://127.0.0.1:8000/api/v1/totalclinic/slug=abc&date=9-10-21
This will return all the query result of the doctor ABC who worked on this particular date.

{
        "doctor_name": "ABC",
        "slug": "abc",
        "working_date": "2019-10-21T07:32:24Z",
        "clinic": "xyx",
}

I am using Generic ListAPIView for this and my requirement is to count the number of clinics visited by a doctor using the result of a query set and print it.
Is there any way to print my own count result instead of queryset result when user types http://127.0.0.1:8000/api/v1/totalclinic/slug=abc&date=9-10-21.

A: The response for ListView is controlled by the pagination class, so you need to customise that class. The solution for this case is well documented:
https://www.django-rest-framework.org/api-guide/pagination/#custom-pagination-styles


text:
Q: New record for for lower bound of non-trivial cycle lengths of Collatz sequences? This is an indirect follow-up of the previous post I did on the Collatz conjecture. After a few responses, we managed to get to the fact that if we have $n\in\mathbb N$ and cyclic $(e_n)$ such that $e_0\equiv1~(\textrm{mod}~2)$, $e_{n+1}=e_{min}=e_0$ and that for all $k\in\mathbb N$ we have the relation $e_{k+1}=\frac{3e_k+1}{2^{\nu_2(3e_k+1)}}$, then
$$\sum_{k=0}^{n-1}\nu_2(3e_k+1)>n\log_23$$
and I found out that for $n\le108$, this inequation was violated. I asked if this inequation was violated for all $n$ such that for all $k < n \implies e_0< e_k$, which would henceforth imply the inexistence of cyclic sequences. However, I know realize this might be a bit out of reach, so we could rather interpret this result as a way to say that all non-trivial cycles have length $>108$, as it's basically the number of steps to get from $e_0$ to $e_n$ in $(a_n)$ such that $a_n=\left\{\begin{array}{cc}(3a_n+1)/2&a_n~\text{odd}\\a_n/2&\rm otheriwse\end{array}\right.$. However, I manage to get way higher recently, and I don't really know what the current record holder is (I only know Lagaria's $301\;994$...), so I'll put this here anyway to know whether it is a correct lower bound or if someone points out an error... ^^' Anyway, first off, we know that since $e_0$ is minimal, then for all $n\in\mathbb N^*$ we'd have
$$\sum_{k=0}^{n-1}\nu_2(3e_k+1) < n\log_2\left(3+\frac1{e_0}\right)$$
However, since LHS is an integer, we would have
$$\sum_{k=0}^{n-1}\nu_2(3e_k+1) < n\log_23$$
as long there no integer $m$ between $n\log_23$ and $n\log_2(3+1/e_0)$... Hence, we have
$$\sum_{k=0}^{n-1}\nu_2(3e_k+1) \ge n\log_23$$
$$\iff\exists~m\in\mathbb N^*:n\log_23 < m < n\log_2\left(3+\frac1{e_0}\right)$$
$$\iff\exists~m\in\mathbb N^*:2^{m/n} < 3+\frac1{e_0}$$
We can get the minimal value of $m$ with $m=\lceil n\log_23\rceil$. Hence,
$$\iff 2^{\lceil n\log_23\rceil/n} < 3+\frac1{e_0}$$
$$\iff 2^{\lceil n\log_23\rceil/n}e_0 < 3e_0+1$$
So what I did is, I made an algorithmic which computes for larger and larger values of $n$ if $\lfloor2^{\lceil n\log_23\rceil/n}e_0\rfloor < 3e_0+1$ because the programming language I used works better with integer values. Despite all of this, I only managed to get up to $n=225\;640\;000$ until it crashed (it's numerically correct though, since I have set precision to 50 digits after the decimal point, despite the amount needed being only 21). Using Wolfram Alpha, the first instance of $\lfloor n\log_2(3e_n+1)\rfloor\ne\lfloor n\log_23\rfloor$ I managed to check manually was $n=10^{18}+283$ (by descending from $10^{20}$), so all I can say is that there exists a lower bound of $(e_n)$ (and definitely $(a_n)$ as well) cycle lengths between $225\;640\;000$ and $10^{18}+283$ (or between $357\;630\;939$ $(10^{18}+283)\log_23$ in $(a_n)$ dynamics if I'm correct). It would take me 20 million years with the algorithm I did to get to $10^{18}+283$ because my programming skills are kind of weak... Anyway, if there is no higher lower bound yet, mine is gonna have to be $225\;640\;000$, I guess ! And if there's higher, then... I'm going to have to do it in another programming language or something to get more efficient results, I don't know...

A: Using Pari/GP and hoping I understand you correctly I show programming and results.
(Pari/GP is interpreted and easily programmed like python. You can obtain it for free at website)
fmt(200,12)    \\ user routine. Sets "float" precision to 200 dec digits, display 12 dec digits

[l2=log(2),l3=log(3),ld3=l3/l2]   \\ setting three logarithmic constants in one command

%1409 = [0.693147180560, 1.09861228867, 1.58496250072]  \\ output of Pari/GP
          \\ the leading "%1409 = " means the line number in protocol

Now we use the convergents of the continued fraction of $\log_2(3)$ because they give us the numbers $n$ (I use $N$ for the numbers of steps, and $S$ for the sum-of-the-exponents)
cf = contfrac(ld3)   \\ continued fraction
cvgts=Mat(vector(26,k,contfracpnqn(vecextract(cf,Str(1,"..",k)))[,1]))
       \\ this is a bit complicated to compute the first 26 convergents of the cf...

%1410 =  \\ output of Pari/GP; lower row  are N and upper row are S (best approx)
[1 2 3 8 19 65 84 485 1054 24727 50508 125743 176251 301994 16785921 17087915 85137581 272500658 357638239 630138897 9809721694 10439860591 103768467013 217976794617 1193652440098 8573543875303]
[1 1 2 5 12 41 53 306  665 15601 31867  79335 111202 190537 10590737 10781274 53715833 171928773 225644606 397573379 6189245291  6586818670  65470613321 137528045312  753110839881 5409303924479]

Now we use your limit-value from your earlier posting (you should this reminder include in your current OP!):
e0=87*2^60    \\ your lower bound for numbers unknown whether they converge to 1

%1411 = 100304170900795686912  \\ output from Pari/GP

Now I show, how the formula and the computation of the comparision can be much much improved. You wrote
$$ \left \lfloor 2^{\left \lceil n \log_2 3 \right \rceil /n } e_0 \right \rfloor \lt 3 e_0 +1   \tag 1
$$
First improvement: in Pari/GP you don't have the need to transform this into integers. We can stay with
$$ 2^{S/N} < 3 + 1/e_0 \qquad \qquad \text{where } S=\lceil N \log_2 3 \rceil \tag 2 $$
but $S$ can also be taken from the first row of the convergents of the cont.frac, however only of each second one. (The other one leads to $2^S< 3^N$ and thus to $e_k$ from the negative numbers).
 fmt(,30)  \\ show more decimal digits
           \\   prec=200 display=g0.30
           \\ loop to display criteria and comparision for N from continued fractions
{ for(k=1,cols(cvgts),
       N=cvgts[2,k];
       S=cvgts[1,k];
       if(S<N*ld3 ,next());  \\ we want only cases where S>N*ld3, means e_k positive
       print(  2^(1.0*S/N),"  N= ", N );
       print(  3.0+1/e0 );
       print();
      );}

4.00000000000000000000000000000 N= 1
3.00000000000000000000996967515

3.03143313302079616469451960261 N= 5
3.00000000000000000000996967515

3.00083886611481518899588149777 N= 41
3.00000000000000000000996967515

3.00001002196901356242295120757 N= 306
3.00000000000000000000996967515

3.00000000349873502617377443634 N= 15601
3.00000000000000000000996967515

3.00000000013857896295306787581 N= 79335
3.00000000000000000000996967515

3.00000000000101566891635377643 N= 190537
3.00000000000000000000996967515

3.00000000000000339671808197166 N= 10781274
3.00000000000000000000996967515

3.00000000000000003122018752529 N= 171928773
3.00000000000000000000996967515

3.00000000000000000079867134488 N= 397573379
3.00000000000000000000996967515

3.00000000000000000000461062882 N= 6586818670   \\ from here lhs < rhs
3.00000000000000000000996967515

3.00000000000000000000001960302 N= 137528045312
3.00000000000000000000996967515

3.00000000000000000000000003656 N= 5409303924479
3.00000000000000000000996967515

Now we improve the computation even more.
$$ 2^{S/N} < 3 + 1/e_0 \qquad \qquad \text{where } S=\lceil N \log_2 3 \rceil $$
Taking logarithms to base $2$ and improving the rhs:
$$    S/N < \log_2(3 + 1/e_0) \\
 S /N < \log_2 3 + \log_2(1 + 1/3/e_0)   \tag 3 $$
improving the lhs
$$  S/N = ( 1 + N \log_2 3 - \{ N \log_2 3 \})/N \\
   \qquad  = \log_2 3 + ( 1 -  \{ N \log_2 3 \} )/N $$
comparing lhs and rhs and reduce then by the equal summand
$$( 1 -  \{ N \log_2 3 \})/N <  \log_2(1 + 1/3/e_0) \tag 4 $$
making constants $\text{ld}_3 = \log_2(3)$ and $\chi^* = \log_2(1 + 1/3/e_0)$
$$( 1 -  \{ N \text{ld}_3 \})/N <  \chi^*   \tag 5 $$
chi_Star=log(1.0+1/3/e0)/l2

%1412 = 4.79440029905249893136461986232 E-21

\\ improved Pari/GP-program for disproving cycles of length N from convergents of cont.frac
{ for(k=1,cols(cvgts),
          N=cvgts[2,k];
          S=cvgts[1,k];
          w = (1.0 - frac(N*ld3))/N
          print(  w ,"  N= ",N,  "   +++ ",if(w>=chi_Star,"disproved","open") );
          print( chi_Star);
          print(" ");
      )}

\\ output from Pari/GP

0.415037499278843818546261056052  N= 1   +++ disproved
4.79440029905249893136461986232 E-21

0.415037499278843818546261056052  N= 1   +++ disproved
4.79440029905249893136461986232 E-21

0.415037499278843818546261056052  N= 2   +++ disproved
4.79440029905249893136461986232 E-21

0.0150374992788438185462610560522  N= 5   +++ disproved
4.79440029905249893136461986232 E-21

0.0817041659455104852129277227189  N= 12   +++ disproved
4.79440029905249893136461986232 E-21

0.000403352937380403912114714588769  N= 41   +++ disproved
4.79440029905249893136461986232 E-21

0.0188110841845041959047516220899  N= 53   +++ disproved
4.79440029905249893136461986232 E-21

0.00000481954028172704299308219597434  N= 306   +++ disproved
4.79440029905249893136461986232 E-21

0.00150366469237765313272722146572  N= 665   +++ disproved
4.79440029905249893136461986232 E-21

0.00000000168253588956734944782194184006  N= 15601   +++ disproved
4.79440029905249893136461986232 E-21

0.0000313800959900827066777880947353  N= 31867   +++ disproved
4.79440029905249893136461986232 E-21

6.66423942064362624554103142061 E-11  N= 79335   +++ disproved
4.79440029905249893136461986232 E-21

0.00000899259730931377116708292220381  N= 111202   +++ disproved
4.79440029905249893136461986232 E-21

4.88433502936137532420925439318 E-13  N= 190537   +++ disproved
4.79440029905249893136461986232 E-21

0.0000000944221279922539076532625570469  N= 10590737   +++ disproved
4.79440029905249893136461986232 E-21

1.63347611071945930958784064302 E-15  N= 10781274   +++ disproved
4.79440029905249893136461986232 E-21

0.0000000186164849196346496509009313455  N= 53715833   +++ disproved
4.79440029905249893136461986232 E-21

1.50137365727884077414999137880 E-17  N= 171928773   +++ disproved
4.79440029905249893136461986232 E-21

0.00000000443174785029608272030238054669  N= 225644606   +++ disproved
4.79440029905249893136461986232 E-21

3.84079729520257921847371693669 E-19  N= 397573379   +++ disproved
4.79440029905249893136461986232 E-21

1.61570587825310461883851635414 E-10  N= 6189245291   +++ disproved
4.79440029905249893136461986232 E-21

2.21724377580880245586537661225 E-21  N= 6586818670   +++ open
4.79440029905249893136461986232 E-21

From here on, $N \ge 6586818670 $ , cycles are possible (regarding our type of criteria!).
However, this does not mean, that not for some larger $N$ our criteria still might allow to disprove specific cycles, as we see in the following list.
For instance, the longest cycle whis is disproved by this criteria and where $N$ is from the continued fractions is for $N=127940101513462006853$. Actually, there are some higher $N$ disprovable this way, but not for further $N$ from the convergents (I found some higher $N$ manually searching). But no disproof of this type can be occur for $N>1/\chi^* \approx 208\, 576\, 659\, 774\, 868\, 320\, 450$ (my manually found maximum $N$ that this criteria can disprove was $N=208\, 576\, 659\, 753\, 891\, 832\, 997$ - see here). Here we need stronger criteria than the one given.
The remainder of the list (extended to 46 entries of the convergents):

1.52740282894614545643017767007 E-11  N= 65470613321   +++ disproved
4.79440029905249893136461986232 E-21

9.42705847903078657986891870021 E-24  N= 137528045312   +++ open
4.79440029905249893136461986232 E-21

1.32782579541391230724574727457 E-12  N= 753110839881   +++ disproved
4.79440029905249893136461986232 E-21

1.75836152824309303355344172158 E-26  N= 5409303924479   +++ open
4.79440029905249893136461986232 E-21

1.62274049741567319299982905114 E-13  N= 6162414764360   +++ disproved
4.79440029905249893136461986232 E-21

1.60788390515943963706344567958 E-27  N= 11571718688839   +++ open
4.79440029905249893136461986232 E-21

1.90660351962268614687947584369 E-14  N= 52449289519716   +++ disproved
4.79440029905249893136461986232 E-21

4.46286637099820690608297508035 E-30  N= 431166034846567   +++ open
4.79440029905249893136461986232 E-21

2.06775912510707543956324804591 E-15  N= 483615324366283   +++ disproved
4.79440029905249893136461986232 E-21

2.66807050886181425836726167850 E-32  N= 5750934602875680   +++ open
4.79440029905249893136461986232 E-21

1.60396502020215512124342997941 E-16  N= 6234549927241963   +++ disproved
4.79440029905249893136461986232 E-21

1.98336779805857882248899248678 E-35  N= 130441933147714940   +++ open
4.79440029905249893136461986232 E-21

3.74365801557610602086544275817 E-18  N= 267118416222671843   +++ disproved
4.79440029905249893136461986232 E-21

5.50451147090702793445498120988 E-37  N= 397560349370386783   +++ open
4.79440029905249893136461986232 E-21

2.35697748103720150130917411168 E-19  N= 4242721909926539673   +++ disproved
4.79440029905249893136461986232 E-21

8.38468541211917799755153138845 E-39  N= 4640282259296926456   +++ open
4.79440029905249893136461986232 E-21

4.38522424269110917875827159797 E-20  N= 22803850947114245497   +++ disproved
4.79440029905249893136461986232 E-21

5.32219084759873058139274402469 E-40  N= 27444133206411171953   +++ open
4.79440029905249893136461986232 E-21

1.99012958797440558462332360040 E-20  N= 50247984153525417450   +++ disproved
4.79440029905249893136461986232 E-21

6.32183491799512388608448125404 E-41  N= 77692117359936589403   +++ open
4.79440029905249893136461986232 E-21

7.81615762509598159480940019684 E-21  N= 127940101513462006853   +++ disproved
4.79440029905249893136461986232 E-21

6.24468066969273566590611166850 E-43  N= 205632218873398596256   +++ open
4.79440029905249893136461986232 E-21

1.29260219722994359535744048756 E-22  N= 7736332199829210068325   +++ open
4.79440029905249893136461986232 E-21

1.84835867266999428811637397830 E-47  N= 31150961018190238869556   +++ open
4.79440029905249893136461986232 E-21


text:
Q: Create a text menu in Python3x that is always available I am new to python and learning quickly. Thank you all for the help.
I am attempting to create a text menu that will always run in the background of a storytelling text rpg. I have searched and cannot find an explanation of how to create an "always on" menu or how one would work.
I would like the player to be able to hit "m" at any time in the game and have the menu prompt show up.
So far, I have created a "userinput" function as well as a "menu" function that will be deployed each time the game prompts the user/player for input.
def menu():
    print('Press "1" for map >>> "2" for stats >>> "3" for exit')
    choice = input()
    if choice == '1':
        print('map needs to be made and shown')
    elif choice == '2':
        print('stats need to be made and assinged to choice 2 in def menu')
    elif choice == '3':
        print('You are exiting the menu. Press "M" at any time to return to the menu')
        return
    else:
        print('I did not recognize your command')
        menu()

def userinput():
    print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
    print('Press "M" for menu at any time')
    inputvalue = input()
    if inputvalue == 'm':
        menu()
    elif inputvalue == '1':
        print('attack function here')
    elif inputvalue == '2':
        print('search function here')
    elif inputvalue == '3':
        exit
    else:
        userinput()

This does not appear to be an ideal solution because the user cannot choose to view a map or exit the game at any time they want.
Is there a way to have a menu always running in the background?
I thought of using a while loop that would never close and all of the game would be held within that while loop but that doesn't seem economical by any means.
Any thoughts or help would be appreciated.

A: I took a stab at it.  This is perhaps not the best structure for doing what you're looking for but I don't want my reply to get too complicated.
The "standard" approach for anything with a UI is to separate the model, the view and the control.  Check out MVC architecture online.  While it adds complexity at the start it makes life much simpler in the long run for anything with a non trivial UI.
Other points of note are:

*

*you're not stripping whitespace from your input (potentially problematic "3 " won't do what you want)

*you're input is case sensitive (you ask for "M" but check for "m") .. maybe use choice = choice.strip.lower()??

*there's a difference between the way raw_input and input work between Python 2 and Python 3 which means your code doesn't work in python 2.  What's the difference between raw_input() and input() in python3.x?  I've changed my example to use raw_input.  You may want to use this work around http://code.activestate.com/recipes/577836-raw_input-for-all-versions-of-python/ near the top of your code for portability.

Some code
# flag we set when we're done
finished = False

def finish():
    # ask the user for confirmation?
    global finished
    finished = True
    return

def handle_menu_input(choice):
    handled = True

    if choice == '1':
        print('map needs to be made and shown')
    elif choice == '2':
        print('stats need to be made and assinged to choice 2 in def menu')
    else:
        handled = False

    return handled

def menu():

    finished_menu = False
    while not finished_menu:

        print('Press "1" for map >>> "2" for stats >>> "3" for exit')
        choice = raw_input() # NOTE: changes behaviour in Python 3!

        if handle_menu_input(choice):
            # done
            pass
        elif choice == '3':
            print('You are exiting the menu. Press "M" at any time to return to the menu')
            finished_menu = True
        else:
            print('I did not recognize your command')
            menu()
    return

def userinput():
    print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
    print('Press "M" for menu at any time')
    choice = raw_input() # NOTE: changes behaviour in Python 3!

    if choice == 'm':
        menu()
    elif choice == '1':
        print('attack function here')
    elif choice == '2':
        print('search function here')
    elif choice == '3':
        finish()

    # elif handle_menu_input(choice):
    #     # delegate menu functions?? ..
    #     # do this if you want to see maps anytime without going through the menu?
    #     # otherwise comment this elif block out.
    #     # (Problem is 1, 2 etc are overloaded)
    #     pass
    else:
        print('I did not recognize your command')
    return

def main():
    # main loop
    while not finished:
        userinput()
    return

if __name__ == "__main__":
    main()


text:
Q: QGIS throws errors in Project after updating to QGIS 3.20 After updating QGIS in Version 3.20.3-Odense, I get following three errors when opening projects that were running without problems before.

-Loading layer fnk_get: Font "Dingbats" not available on system

-Cannot use project transform between EPSG:31467 and EPSG:25832

-Cannot use project transform between EPSG:5677 and EPSG:25832

I do not use dingbats anywhere nor the projections 5677 and 31467. Who can help?

A: The problem with Dingbats, in my case, the problem comes when I use a Font Marker My solution was: in Font Marker change Font MS Shell Dlg 2 to MS Serif.

A: Seems the issue with symbology and CRS are unrelated but solution by @RBenet worked for me as long as I applied the change in the general symbol settings rather than just in the categorized symbol settings (if using categorized symbols)