text:
Q: How does faster than light travel violate causality? Let's say I have two planets that are one hundred thousand lightyears away from each other. I and my immortal friend on the other planet want to communicate, with a strong laser and a tachyon communication device.
I record a message on the tachyon communication device and release the message at exactly the same time as I activate the laser, both of which are directed to the other planet which is one hundred thousand lightyears away. Say it is the year 0 for both of us at the time I did this.
If tachyons existed, then the message would arrive to my friend before the photons in the laser. It would arrive, say, a thousand years earlier. From my vantage point, that message will arrive to her at year 99,999; the same would be true for my friend's vantage point. However, she will only see the laser at year 100,000.
So since she got the message at year 99,999, she immediately sends me a reply back going through the same procedure as I did. She records a message and releases it at the same time as the laser. The tachyons will arrive 1,000 years earlier than the laser, so for me, I will receive the message at year 199,998. I will receive the laser, however, at year 199,999.
It seems to me that communication this way does not violate causality. I will still have received the message after I had sent it.
If tachyons truly violated causality, though, I realize it should arrive at year -1 for her, and so she can reply to me at year -2, which would mess me up by year 0 as I will ask her how she knew I was planning on sending her a message before I sent it. I could send her a different message, which she would end up receiving at year -1, and will end up confusing her as she would have received one message asking her out, and the other asking her how did she know I was asking her out. She then decides I am crazy and sends me a message at year -2 that she does not want to date me, and so she will have both turned me down and entertained me before I have even asked her out.
On the other hand, let's go back to year 0 and add a third device to our list: an Alcubierre drive. After I send out the message and the laser, I get impatient and do not feel like waiting 99,999 years, so I get on my Alcubierre drive spaceship and arrive on her planet at the same year 0. My friend is not in her office, so I leave a note to her also immortal secretary saying I dropped by and that she should expect a message for her in year 99,999.
I then get back on my Alcubierre drive and land back on my planet, still on year 0. Meanwhile, the tachyons and photons I sent out are still racing to arrive to her. By year 99,999, she receives the message just as I Alcubierre drive back to her, and I pick her up for dinner.
But the point of my question is, it seems to me that just going faster than light, if that alone was what you had, would not violate causality. It must be something else. I understand time dilation and that things with mass cannot travel at the speed of light, but using the Alcubierre drive, hypothetically speaking, I was still able to outpace the photons while also having mass. It still did not produce causality problems. Alcubierre drives are also valid solutions to GR.
It seems circular to me to say that what makes traveling faster than light violate causality is because it violates causality (if faster than light communication was divorced from causality problems, then the causality problem would cause itself -- thereby violating causality and, hence, we would scrap it and conclude that there is no causality problem after all).
What is it that I am missing? If someone could help me out, that would be excellent. I've been itching to ask my friend out for a few millenia now. :)

A: For the tachyon case, you implicitly assume that the tachyons ultimately travel forward in time, just going faster than light.  But there exist Lorentz transformations (that is, other inertial frames) in which such a particle would travel backward in time as it traverses space.
You may have trouble believing this, so consider a 1+1 spacetime.  This spacetime has four distinct regions:  future timelike, +x spacelike, -x spacelike, and past timelike.  These regions are cut by two diagonal, lightlike lines, which divide spacelike from timelike and represent the asymptotes of hyperbolas.
Most massive objects have four-velocities in the future timelike region, and a Lorentz transformation will keep them in that region no matter what.  They are, however, quite free to move around in that region, provided that they maintain an overall magnitude of $c$.
A tachyon is the same, except it occupies either the +x-spacelike or -x-spacelike regions.  This means that, even if you think your tachyon travels forward in time, there exists some reference frame in which it travels backward in time.  You may not see causality violated, but someone else will.
The Alcubierre drive gets around this problem by changing the geometry of spacetime itself so the above notions get much more complicated.  The basic idea is this: inside the bubble, you can fire off a photon and it will, assuredly, go away from you along a well-defined trajectory, one that is "faster" than yours.  Causality is not violated because all observes will agree that you merely took a timelike trajectory in a very unusual spacetime--events before and events after your trip are still well-defined.
The danger here in thinking about the Alcubierre drive is that we often take the perspective of a distant observer and naively think that our coordinates (our measures of time and space) will not be affected by the drive, but they are.  The geometry of the drive itself will warp and distort coordinate lines around it, resolving any seeming causality violations.

A: There is a simple answer; faster than light travel does not violate causality.
What faster than light travel does, is contradicts the usual axiomization of relativity; and hence allows you to derive all kinds of paradoxial 'conclusions'. But shifting the blame on causality is more fashionable convention than anything else.
What would happen 'in practice' in the case of faster than light travel, is that itd become possible to triangulate a 'special' reference frame. The inability to triangulate such a frame really need not be taken as an axiom; it can infact be derived from the apparent empirical fact that all fundamental forces travel at the unfortunately named 'speed of light'. If they wouldnt, triangulating a special 'rest' frame really wouldnt be that hard.
However, to see that our inability to triangulate a 'rest' frame probably doesn't make for all that good an axiom, it is easier to just consider a spherical universe. If I flash a spherical light in a topologically euclidian universe, no set of contraptions or mirrors will allow me to triangulate a rest frame.
But in a spherical universe, different observers that flash a spherical light might see that light come back to them in different ways. Some, in a 'special', 'preferred', or 'rest' frame, if you will, will see the flash come back at them from all directions at the same time. If you want to call it a 'rest' frame; whatever. But it sure is a 'unique' or 'special' frame. Any change in momentum from that state will make the roundtrip time of your lightflash a function of direction.
Note that this argument does not require the universe to be spherical; it can even be flat, like a toroidal topology. The same conclusions follow for all topological scenarios that allow multiple independent geodesics between two points in spacetime, like wormholes. They either force you to believe in timetravel (kindof a friendly way of saying blatant-self-contradiction); or alternatively youd be forced to come to the conclusion you can indeed triangulate a 'special' frame.
And so what? You still cant do it with local measurements using fundamental forces all traveling at the same speed though, and thats all thats needed to be consistent with all our current experimental evidence.
Not that anyone has observed a wormhole or light going around the universe; but it seems wrong to axiomatically throw the latter under the bus at least until we have experimentally excluded it. And should we find any such topological feature, id neither get out my disproving-relativity-contraption or my time-traveling-gear, but rather dust off my rest-frame-triangulating-apparatus. But your opinion may vary.
Disclaimer: I would not be surprised if someone has argued this case better before, but this specific line of argumentation is original to me. So I am aware it is not orthodoxy, and I am aware my argument leaves some things as an exercise to the reader; but feel free to give your prediction of what a lightflash going around a spherical universe would look like. Or maybe it is better explained in terms of 'time travel' after all?

A: (There's a couple of these questions kicking around, but I didn't see anyone give the "two boosted copies" answer. Generically, I'd say that's the right answer, since it gives an actual causality violation.)
In your scenario, the two planets remain a hundred thousand light years apart. The fact is, you won't get any actual causality violations with FTL that way. The trouble comes if the two planets are moving away from each other. So, let's say that your warp drive travels at ten times the speed of light. Except if the two endpoints of the trip are moving, then what does that mean? Ten times the speed of light relative to which end?
Let's say Tralfamadore is moving at a steady 20% of $c$ (the speed of light), away from Earth. (So, Earth is moving at a steady 20% of $c$ away from Tralfamadore.)
If I leave Tralfamadore (in the direction of Earth) and I am travelling at anything less than 20% of $c$ relative to Tralfamadore, then I am still moving away from Earth. I'll never get home.
Let's say instead I am travelling at 60% of $c$ relative to Tralfamadore. I will catch up to Earth. Relative to Earth, how fast am I approaching? You might guess the answer is 40% of $c$, but it's 45.45%.
Generally, the velocity subtraction formula of relativity is: $$w = (u-v)/(1-uv/c^2)$$
Let's say instead I am travelling at 100% of $c$ relative to Tralfamadore. Plug $u=c, v=0.2c$ into the formula and get $w=c$. Relative to Earth, I am approaching at 100% of $c$! The speed of light is the same for everyone.
So finally, let's say instead I am using your warp drive to travel at 1000% of $c$ relative to Tralfamadore. Relative to Earth, I am approaching at -980% of $c$. In Earth's reference frame, I will arrive on Earth before I leave Tralfamadore. Now you may say this in itself isn't a causality violation, because we've applied Earth's calendar to Tralfamadore. And that's true, but I'll make a round trip:

*

*In the futuristic Earth year of 3000, Tralfamadore is 98,000 light years away, and receding at 20% of $c$. I leave Earth at 1000% of $c$, relative to Earth.

*In Earth year 13000 Tralfamadore is 100,000 light years away, and I catch up to it. I turn around and leave Tralfamadore at 1000% of $c$, relative to Tralfamadore.

*In Earth year 2796, I arrive home.

Earth's calendar certainly applies to Earth, and I arrived home two centuries before I left. No two ways about it, I'm a time traveller!
There is nothing special about ten times the speed of light. Given a warp drive that moves a certain amount faster than light, you can make the above time machine using two endpoints that are moving apart a certain amount slower than light, provided that the warp drive can move faster than light relative to either end. This time machine works for any form of FTL: tachyons, warp drives, wormholes, what have you.

A: What everyone else said, but note that this STILL violates causality if you use general relativity to create one of these "warp drive" scenarios--the "warp drive" can always be restricted to an arbitrarily small region of spacetime, and then special relativity will be true over the rest of spacetime, and the problems will still arise.

A: There are a few misconceptions in your scenario that cause the misunderstanding. First of all, by definition, causality means that if the time interval between two events is positive in one reference frame, then it is positive in any other reference frame of your choice and viceversa, provided the velocity the events propagate to be smaller than $c$. If, on the other hand, you allow events to propagate faster than light, then there might be reference frames wherein the orders of the events is switched. This does not imply, as you assume, that travelling faster than light makes things arrive back to you earlier than when you sent them. Violation of causality means that this might happen in at least one other reference frame; in yours things will stay as they are.
Most important: notice that for events to go "back and forth" you need to change sign to the velocity ($a \neq 0$), which implies that the notion of time itself depends on the space-time path that you follow and on the point in the space-time you are in. The time that you hence measure has in principle nothing to do with the notion of "biological" time that you have in mind, but it is a mere parameter in the metric. In the case at hand you would have to solve the Alcubierre metric and integrate between the two points you are considering along the path you want to follow. This in general will give you something that is totally unrelated to the notion of biological time, to which all your concepts apply.
Last but not the least, besides the violation of causality, travelling at $v>c$ will produce diverging physical observables (energy, momentum and so on) violating all the other conservation laws that must nevertheless hold true.

A: Since I haven't seen this example, I'll add to the pile. As has been said, the problem occurs once you have relative motion between two objects. I had a hard time pinning down special relativity until I went back to the original premise: The result of any experiment has to be the same in all non-accelerating reference frames and looked at this example experiment.
Let's say that 2 ships, ship A and ship B, leave the surface of a non-accelerating planet going opposite directions at 0.8c. Each ship is equipped with a device that will emit a unique signal once it receives an initializing signal from the planet. The planet will detect whether the signals from the ships are received at the same time or not.
In the reference frame of the planet:
After one year the planet emits the initializing signal. 4 years later each ship receives that signal at the same time. 5 years after that, the people on the planet receive signal A and signal B at the same time.
In the reference frame of ship A:
The planet will be moving away at a speed of 0.8c while ship B is moving away even faster than that (let's not worry about the exact speed of ship B in this frame.) After some amount of time, t, in reference frame A, the planet emits the initializing signal. This signal has to travel a distance of 0.8ct to reach ship A. However, the signal will have to catch up to ship B, and since it's moving close to the speed of light (definitely over 0.8c), that will take quite a while. The numbers here get complicated, but conceptually I would say it's pretty easy to see that the initializing signal will reach ship B after it reaches ship A. However, since the planet is also moving, this won't be a problem, because now signal A has to catch up to the planet while signal B is going to head back towards the planet, which will take less time. It's still true in this reference frame that the planet receives both signals at the same time.
Now, imagine the people on ship A had a way to communicate at faster than the speed of light. In the reference frame of A, after they received the signal, they could contact ship B and tell them to turn their machine off. Meaning that the planet would only receive a signal A, and there's our violation of causality.
The issue is that things happening simultaneously in one reference frame don't necessarily happen simultaneously in another frame, and, as we see in this example, if you could affect things faster than the speed of light, you could change the result between reference frames.


text:
Q: In "the" heaven and in "the" earth, but in hell There is this famous short-story by Poe called "The Tell-Tale Heart" in which a man tries to convince the reader he is not mad by narrating the way he killed his master.
My question has to do with the very first words of the story that read as follows:

True! --nervous --very, very dreadfully nervous I had been and am; but why will you say that I am mad? The disease had sharpened my senses --not destroyed --not dulled them. Above all was the sense of hearing acute. I heard all things in the heaven and in the earth. I heard many things in hell. How, then, am I mad? Hearken! and observe how healthily --how calmly I can tell you the whole story.

Would you know why Poe uses the definite article "the" for both "heaven" and "earth", but nor for "hell"? Is it a matter of grammar or there is some type of interpretation behind it?
Most translators of this text to my language (Portuguese) overlook this detail and translate as if they were all the same, but I do not think it is something that trivial.
I was thinking it could mean that the man hears things "from" heaven and earth (the places he is distant from), but hear things in hell, where he actually is at, although he says he is not mad. What do you think about this interpretation?

A: It is not clear that Poe had a single thing in mind. He was a poet as well as a writer of short stories so it is quite possible that he had multiple meanings in mind.

in the heaven

is an odd phrase. The usual way of speaking would be to say "in Heaven" or "in the heavens."

In Heaven

means the singular place where, according to the Christian Bible, the souls of believers will reside after the Day of Judgment and has a strongly religious connotation. That first phrase is mirrored in the phrase "in Hell."

In the heavens

is a somewhat infrequent way to say "the sky" and has a physical, non-religious connotation.

in the earth

is a standard phrase that means inside the earth: "He dug for gold in the earth" or " "In the earth is a molten core." It is physical.
Thus, the narrator is conflating the physical (the sky) and the religious (Heaven), and the odd phrase indicates his confusion of mind. It is a complex play on words designed to help characterize the narrator. Unless Portuguese has phrases corresponding to

In heaven

singular, without an article, and with a religious connotation, and

In the heavens

plural, with an article, and without a religious connotation, the subtle bit of characterization implied by Poe by using the singular with a definite article may be impossible to render concisely in Portuguese.

A: I believe Edgar Allan Poe is trying to invoke a passage from the Bible. (Credit goes to Gareth Rees for locating the passage)

Thine, O Lord is the greatness, and the power, and the glory, and the victory, and the majesty: for all that is in the heaven and in the earth is thine; thine is the kingdom, O Lord, and thou art exalted as head above all. (1 Chronicles 29:11)

This passage is from the King James Bible, a version that dominated American Christian worship during much of U.S. history. And by invoking this phrasing from the Bible, Poe is conjuring religion connotations. As Jeff Morrow explains, "in the earth" can be taken to mean inside the earth. You can also imply understand "in the heave" roughly as "in the sky". But the most important reason that Poe uses the definite article in "in the heave and in the earth" but not "in hell" is because he is drawing directly from scripture and conjuring religious imagery.

redpajama_set_name: RedPajamaStackExchange


text:
Q: lifting trouble with ResourceT I'm adapting this example, in particular, the client. I'll tel you what I think the trouble is, following the code and the error it generates.
> {-# LANGUAGE OverloadedStrings #-}
> import Network.HTTP.Conduit
> ( http, parseUrl, newManager,def, withManager, RequestBody (RequestBodyLBS)
> , requestBody, method, Response (..)
> )
> import Data.Aeson (Value (Object, String))
> import Data.Aeson.Parser (json)
> import Data.Conduit
> import Data.Conduit.Attoparsec (sinkParser)
> import Control.Monad.IO.Class (liftIO)
> import Control.Monad.Trans.Class (lift)
> import Data.Aeson (encode, (.=), object)

> main :: IO ()
> main = withManager $ \manager -> do
>    value <- makeValue
> -- We need to know the size of the request body, so we convert to a
> -- ByteString
>    let valueBS = encode value
>    req' <- parseUrl "http://10.64.16.6:3000/"
>    let req = req' { method = "POST", requestBody = RequestBodyLBS valueBS }
>    Response status version headers body <- http req manager
>    resValue <- body $$ sinkParser json
>    handleResponse resValue

> -- Application-specific function to make the request value
> makeValue :: ResourceT IO Value
> makeValue = return $ object
>    [ ("foo" .= ("bar" :: String))
>    ]

> -- Application-specific function to handle the response from the server
> handleResponse :: Value -> ResourceT IO ()
> handleResponse foo = do
>    _ <- lift (print foo)
>    return ()

No instance for (Control.Monad.Trans.Class.MonadTrans ResourceT)
  arising from a use of `lift'
Possible fix:
  add an instance declaration for
  (Control.Monad.Trans.Class.MonadTrans ResourceT)
In a stmt of a 'do' block: _ <- lift (print foo)
In the expression:
  do { _ <- lift (print foo);
       return () }
In an equation for `handleResponse':
    handleResponse foo
      = do { _ <- lift (print foo);
             return () }

Here's the problem, the error says there is no instance for Control.Monad.Trans.Class.MonadTrans ResourceT
But I think there is, due to this documentation. So where have things gone wrong?
As mentioned below there is something janke going on with Control.Monad.Trans.Resource
Here's the results of the ResourceT introspection.
*Main Control.Monad.Trans.Resource> :i ResourceT
newtype ResourceT m a
  = Control.Monad.Trans.Resource.ResourceT (GHC.IORef.IORef
                                              Control.Monad.Trans.Resource.ReleaseMap
                                            -> m a)
    -- Defined in `Control.Monad.Trans.Resource'
instance Monad m => Monad (ResourceT m)
  -- Defined in `Control.Monad.Trans.Resource'
instance Functor m => Functor (ResourceT m)
  -- Defined in `Control.Monad.Trans.Resource'
instance MonadBaseControl b m => MonadBaseControl b (ResourceT m)
  -- Defined in `Control.Monad.Trans.Resource'
instance MonadThrow m => MonadThrow (ResourceT m)
  -- Defined in `Control.Monad.Trans.Resource'

version of resourcet is
[mlitchard@Boris Boris]$ ghc-pkg list resourcet
WARNING: there are broken packages.  Run 'ghc-pkg check' for more details.
/usr/lib/ghc-7.4.1/package.conf.d
/home/mlitchard/.ghc/x86_64-linux-7.4.1/package.conf.d
   resourcet-0.3.2.1

Any ideas on how to proceed?
Where's the instance for MonadTrans ResourceT?

A: If I were a betting man, I would say you have multiple versions of some library installed. For example, say you have version 0.2 and 0.3 of transformers, and resourcet is built against version 0.2. When you write the code import Control.Monad.Trans.Class (lift) you're importing version 0.3 of lift, but there are no instances for it involved.
Easiest way to test this is to cabalize your code. Cabal will make sure you have the right versions of the libraries involved.

A: EDIT: This answer does not solve the problem, the import does still not resolve the instances, even though it should. This seems to be a bug in either GHC or some other system.
The Data.Conduit module only re-exports ResourceT as a convenience; the resource monad transformer is defined in a separate package resourcet. conduit does for that reason not re-export class instances (apparently?). You need to manually import Control.Monad.Trans.Resource to gain access to the associated class instances. This can of course be done with the following syntax:
import Control.Monad.Trans.Resource () -- Only import instances


text:
Q: cloudinary.exceptions.Error: Empty file using Flask Im using cloudinary for upload file from my flask app.
I followed this basic sample code by pycloudinary for flask : https://github.com/cloudinary/pycloudinary/tree/master/samples/basic
but I still get the same error.
cloudinary.exceptions.Error
cloudinary.exceptions.Error: Empty file

My file post request with multipart-form and key name "image".
Before this, I already successfully upload file to static folder.
What should I do ?
def upload_files():
    upload_result = None
    file_to_upload = request.files['image']
    if file_to_upload:
        upload_result = upload(file_to_upload)
        return "Success!"
    else:
        return "Failed!"

A: Should file_to_upload = request.files['image'] be
file_to_upload = request.files['file']?
request.files is a ImmutableMultiDict() that file is the key and not image.
Best,
Mo


text:
Q: Для чего нужен этот параметр? Подскажет что означает, или для чего нужна запись:
<script src="js/name.js?<?php echo time();?>"></script>
Или
$.get('tiles.json?'+Math.random(),function(data){});

Зачем к именам файлов добавляются эти числа? Внутри файлов нет ничего связанного с ними.

A: Эта «соль» используется для борьбы с кешированием в браузере.
Браузер кеширует вообще всё, до чего может добраться. Притом делает это чуть ли не случайно. Притом кеширует даже то, что ему указывается не кешировать (например, http-заголовком).
Браузер узнаёт, что файл не надо второй раз загружать, когда проверяет «а не загружал ли я уже этот url когда-то?». Чтобы он всегда получал уникальный url придумали такой хак: добавлять любую соль в get-параметр.
Для человека это примерно одни и те же запросы, а для браузера абсолютно разные
/index.php
/index.php?rand=12039

A: решил ответом написать для пользователя @higimo
если в ответе установлен заголовок
Cache-Control: private, max-age=0, no-cache

то ничего и не где не будет кэшироваться. Хак есть но не такой грубый смысла нет каждый раз обновлять кэшь обычно ставят какой то cache-key для этого который не меняеться пока нет необходимости отдать новую страницу. Да и так как браузер запрашивает по отдельности статику то грамотнее просто отдать last-modified
Last-modified: Sat, 07 Feb 2015 14:14:55 GMT

или expires
Expires: Thu, 31 Dec 2037 23:55:55 GMT

разница лишь в том что первый заголовок показывает когда в последний раз был изменён фаил, а второй когда стоит обновить кэшь.
Всё остальное на подобие
/index.php
/index.php?rand=12039

Кастыли обусловленые нежеланием читать документацию, бональной "нехваткой времени" что сравнимо с не желанием читать и ошибками в архитектуре приложения, или бональным "непонимаем как настроить apache или nginx" что сравнимо с "Нехваткой времени", что в свою очередь сравнимо с "нежеланием читать документацию". К сожалению это замкнутый круг, у веб девелоперов нет желания читать спецификации, легче закастылять.
Статику лучше кашировать на клиенте так как при высоких нагрузках обработка статики занимает больше процессорного времени чем обработка php. Так как apache в корне не умеет работать со статикой, используйте nginx который не замарачиваеться с определением статичный это фаил или нет и отдаёт его как вам хочеться. В нём же в две строки настраиваем и last-modified и cache-control и другие заголовки для статики, можем так же сконфигурировать чтобы last-modified был такой же как у файла на диске, т.е. залили изменения nginx отдал нужный заголовок, кэш обнавился. И не надо ничего делать...
Для разработчиков можно отключить кэш заголовком описаным выше cache-control и писать спокойно скрипты.Но скорее всего мало кто дочитал до конца, и эту строку никто не прочитал...


text:
Q: Do I need to terminate a thread if its detached? I have a weird question that I can't find an answer to. Let's suppose I launch a thread that contains a while(1) (i.e. thread never returns) using pthread_create(...) but as soon as I create it I detach the thread. Later on, the object that initiated this thread is destroyed.
What happens to that thread? Is this a forever taken resource?

A: Thread belongs to process. As soon as your process terminates, all threads within the process terminate as well. Destroying the object who initiated the thread doesn't affect running state of the thread. But if the thread has access to the destroyed object, you might encounter core dump problem.


text:
Q: Nested ApolloProviders in React I'm working on a micro-frontend application. We're building a library to manage all of our user data, permissions, roles, etc.
<ApolloProvider client={userManagementClient}>
  {children}
</ApolloProvider>

This will be used in many applications and it looks something like this:
<ApolloProvider client={appClient}>
  <UserManagementProvider><App /></UserManagementProvider>
</ApolloProvider>

The issue is that the application's ApolloProvider doesn't work cause the Queries are being done against the library's data source and not the application.
Does anyone know a way of having nested, or multiple, ApolloProviders?

A: For anyone interested:
You are only allowed one Provider per application, no matter where this provider is being fetched from. What you can do is define the client which you want to use for your queries, mutations, subscriptions:
const link = ApolloLink.from([ /* ... */ ]);

const apolloClient = new ApolloClient({ link, cache: new InMemoryCache() });

const status = useQuery<GetUserQuery>(
  userQuery,
  {
    variables: {
      email
    },
    client: apolloClient, // <<--
  }
);


text:
Q: $_POST from checkbox with the same name and different values I have SQL database which has a table (results) that is gonna save all of the results of my survey.
One of the questions is checkbox (multiple answer), so I made a code that should gather the results of checkbox questions and put its values into the database.
But, something's missing, it overwrites the last value in the array so obviously there is an easy solution which I cannot see. To clarify, I want to store all values of one checkbox question if user checks everything.
HTML FORM
<input type="checkbox" name="checkbox1" value="This is the first value">
<input type="checkbox" name="checkbox1" value="This is the second value">
<input type="checkbox" name="checkbox1" value="This is the third value">

PHP SCRIPT
for($i=1;$i<101;$i++) {
    if(isset($_POST['checkbox'.$i])) {
        $q[$i] .= $_POST['checkbox'.$i].'; ';
    }}

<?php
$db =& JFactory::getDBO();
$query = "INSERT INTO jos_results(question1) VALUES ('$q[1]')";
$db->setQuery($query);
$db->query();
?>

A: If the name of check box type is same then use array then only it will work.
like here
<input type="checkbox" name="checkbox1[]" value="This is the first value">
<input type="checkbox" name="checkbox1[]" value="This is the second value">
<input type="checkbox" name="checkbox1[]" value="This is the third value">


text:
Q: Downloading csv files with zip? I have this codes, the problem is, whenever I press the download button, it gives an error indicating Directory Not Found. I have already an upload function with the following fileUpload.PostedFile.SaveAs(Server.MapPath("~/Upload")); Below is my codes:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var files = Directory.GetFiles(@"~/Upload");
        gvFiles.DataSource = from f in files
                             select new
                             {
                                 FileName = Path.GetFileName(f)
                             };
        gvFiles.DataBind();
    }

}

protected void btnDownload_Click(object sender, EventArgs e)
{

    string fileName = string.Empty;
    string filepath = Request.MapPath("~/Upload");
    string downloadFileName = "Attendance.zip";
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "filename=" + downloadFileName);

    using (ZipFile zip = new ZipFile())
    {
        foreach (GridView row in gvFiles.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("chkSelect");
            if (cb != null && cb.Checked)
            {
                fileName = (row.FindControl("lblFileName") as Label).Text;
                zip.AddFile(Server.MapPath(Path.Combine(filepath, fileName)), "");
            }
        }
        zip.Save(Response.OutputStream);
    }
}

Can anyone help me with this please? When I use Directory.GetFiles(@"~/Upload"), I get the mentioned error

A: Directory.GetFiles expects an existing local path, die ~ Syntax is not possible here. Use MapPath before:
var files = Directory.GetFiles(Request.MapPath("~/Upload"));


text: Q: Is there an R function to find duplicated IDs from a large dataset? I have an SAS table imported to R Studio, there are around 2500 observations (patient ID). This is a table with data from different experiments (3 experiments or readings), and for some observations/patients, more than one experiment was conducted. I want to know which of those observations have more than one experiment in order to filter the data and just choose an experiment. Also, this will help me see the exact number of observations.


text:
Q: prevent autocomplete in chrome address bar IS there a way to prevent automatic autocomplete in the Chrome address bar? If I start typing an address and an autocomplete suggestion appears it overrides my original typing.  Is there an option to make the user hit Tab or another key to actually select it? I would still like autocomplete to appear, but not select it by default.

A: I don't think there's a way to totally prevent autocomplete in the omnibar. You might already be aware, but you can just press backspace or delete to remove the suggested text. And pressing enter will accept the suggestion. This is probably the best way and is simple enough for most.

A: To do that.

*

*Go to settings. (hamburge menu on top right corner)

*Then navigate to advanced settings.

*In the privacy section uncheck the box of Use a prediction service to help complete searches and URLs typed in the address bar. And you are done.

Also the autocomletion depends on your search history. So making it clear will also help you.


text:
Q: Xamarin.Ios does not deploy to iphone-simulator I have a notebook with windows installed and a virtual machine of MacOs Catalina.
Connecting the Mac to Visual Studio on windows works without a problem but when I want to run the Xamarin.Ios Project the simulator boots and after some seconds the error

"could not launch the app (bundle_name) on the device iOS 13.3 - iPhone 11: The request to open (bundle_name) failed.

occures.
Here is the error
The latest version of XCode (11.3.1) and Visualstudio 2019 are both installed on the virtual machine.
Sometimes another error occures on the virtual machine which says that springboard quit unexpected. Don't know if it has something to do with this problem
Here is the error for the springboard error
Does anyone know how to solve this? I looked it up online but I can't find a working solution.

A: I had same problem. I changed my provisioning profile from distribution to development and it fixed .


text:
Q: Close/cancel open X509Certificate2UI certificate selection and pin dialog programmatically without further user interaction I have a function that is executed in a C# Task object (part of a Winforms .NET 4.7.2 application) that asks the user to select a certificate from the windows certificate store using the X509Certificate2UI class.
There can be a situation where the corresponding selection dialog is open and waiting for user input when the task is canceled using the cancellation token. My expectation was that the selection dialog would then be automatically closed/canceled too, but it remains open.
The same problem applies to the dialog for entering the PIN securing the private key of a certificate.
Is there any clean way to cancel the dialog programmatically or to assure that it closes with the task?
The following code demonstrates the problem. One task opens the selection dialog. A second task simulates an event triggered after the dialog is opened. Once DoSomethingDifferent is done, the certificate is not required anymore and the selection dialog should therefore be closed. It however stays open until the program exits.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CancelCertificateDialog
{
class Program
{

    private static X509Certificate2 SelectCertificate()
    {
        // Selecte certificate from store
        var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection selectedCertificate = (X509Certificate2Collection)collection.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);// (X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, true);

        selectedCertificate = X509Certificate2UI.SelectFromCollection(
        store.Certificates,
        "Certficates",
        "Select a certificate for signing the document",
        X509SelectionFlag.SingleSelection);

        return selectedCertificate[0];
    }

    private static void DoSomethingDifferent()
    {
        Thread.Sleep(4000);
        Console.WriteLine("I'm done");
    }

    static void Main(string[] args)
    {

        Console.WriteLine("Start");
        CancellationTokenSource tokenSource = new CancellationTokenSource();
        CancellationToken token = tokenSource.Token;
        Task<X509Certificate2> t1 = new Task<X509Certificate2>(() => SelectCertificate(), token);
        Task t2 = new Task(() => DoSomethingDifferent(), token);

        t1.Start();
        t2.Start();

        try
        {
            Task.WaitAny(t1, t2);
        }
        catch (AggregateException e)
        {

            for (int j = 0; j < e.InnerExceptions.Count; j++)
            {
                Console.WriteLine(e.InnerExceptions[j]);
            }

        }
        Console.WriteLine("The certificate is not required anymore. Get rid of the dialog");
        tokenSource.Cancel();
        Console.WriteLine("Press Key");
        Console.ReadKey();

    }
}
}


text:
Q: Using jquery or javascript to dynamically change select options using bootstrap? I am trying to dynamically change select options which uses selectpicker from bootstrap.  It doesn't seem to work with bootstrap but without it, it works just fine.
Here's my code:
HTML
            <select name="proj" id="project" class="selectBox"  style="width:270px" data-size="5" onchange="tasklist()">
                <option>Select Project...</option>
            </select>
        <select name="tsk" class="selectBox" id="task" style="width:270px" data-size="5">
            <option>Select Task...</option>
        </select>

Javascript
$(document).ready(function() {
    $('.selectBox').selectpicker();
});

if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","projectList.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

var project=xmlDoc.getElementsByTagName("project");
for (var i=0;i<project.length;i++)
{
    $('#project').append($('<option>', {
        value: i+"|" + project[i].getElementsByTagName("title")[0].childNodes[0].nodeValue,
        text:project[i].getElementsByTagName("title")[0].childNodes[0].nodeValue
    }));
}

function tasklist()
{
$('#task').empty();
if (window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","projectList.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var project=xmlDoc.getElementsByTagName("project");
var x=document.getElementById("project").options.selectedIndex;
for(var j=0;j<project[x-1].getElementsByTagName("task").length;j++)
{
    $('#task').append($('<option>', {
        value: j+"|" + project[x-1].getElementsByTagName("task")[j].childNodes[0].nodeValue,
        text:project[x].getElementsByTagName("task")[j].childNodes[0].nodeValue
    }));

}
}

XML
<projectlist>
<project>
    <title>Project 1</title>
        <task>task 1</task>
        <task>task 2</task>
        <task>task 3</task>
</project>
<project>
    <title>Project 2</title>
        <task>task 4</task>
        <task>task 5</task>
</project>
<project>
    <title>Project 3</title>
        <task>task 6</task>
        <task>task 7</task>
</project>
</projectlist>

When I select an option from project, it should load up a set of options for task as defined in the xml file.  So for example, if I click Project 2, it should load task 4 and task 5 in the task option.  This does work if I remove the selectpicker but is there a way I can keep the selectpicker and do this at the same time?
Thanks for the help.

A: From the bootstrap-select website:
To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.
   $('.selectpicker').selectpicker('refresh');

A: TypeError: $(...).selectpicker is not a function

$('.def_lang').selectpicker('refresh')

A: TypeError: $(...).selectpicker is not a function
$('.list_doc').selectpicker('refresh');


text:
Q: How to get records randomly from the oracle database? I need to select rows randomly from an Oracle DB.
Ex:  Assume a table with 100 rows, how I can randomly return 20 of those records from the entire 100 rows.

A: SAMPLE() is not guaranteed to give you exactly 20 rows, but might be suitable (and may perform significantly better than a full query + sort-by-random for large tables):
SELECT *
FROM   table SAMPLE(20);

Note: the 20 here is an approximate percentage, not the number of rows desired. In this case, since you have 100 rows, to get approximately 20 rows you ask for a 20% sample.

A: In summary, two ways were introduced
1) using order by DBMS_RANDOM.VALUE clause
2) using sample([%]) function

The first way has advantage in 'CORRECTNESS' which means you will never fail get result if it actually exists, while in the second way you may get no result even though it has cases satisfying the query condition since information is reduced during sampling.
The second way has advantage in 'EFFICIENT' which mean you will get result faster and give light load to your database.
I was given an warning from DBA that my query using the first way gives loads to the database
You can choose one of two ways according to your interest!

A: In case of huge tables standard way with sorting by dbms_random.value is not effective because you need to scan whole table and dbms_random.value is pretty slow function and requires context switches. For such cases, there are 3 additional methods:

1: Use sample clause:

*

*https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6

*https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6
for example:
select *
from s1 sample block(1)
order by dbms_random.value
fetch first 1 rows only

ie get 1% of all blocks, then sort them randomly and return just 1 row.

2: if you have an index/primary key on the column with normal distribution, you can get min and max values, get random value in this range and get first row with a value greater or equal than that randomly generated value.
Example:
--big table with 1 mln rows with primary key on ID with normal distribution:
Create table s1(id primary key,padding) as
   select level, rpad('x',100,'x')
   from dual
   connect by level<=1e6;

select *
from s1
where id>=(select
              dbms_random.value(
                 (select min(id) from s1),
                 (select max(id) from s1)
              )
           from dual)
order by id
fetch first 1 rows only;

3: get random table block, generate rowid and get row from the table by this rowid:
select *
from s1
where rowid = (
   select
      DBMS_ROWID.ROWID_CREATE (
         1,
         objd,
         file#,
         block#,
         1)
   from
      (
      select/*+ rule */ file#,block#,objd
      from v$bh b
      where b.objd in (select o.data_object_id from user_objects o where object_name='S1' /* table_name */)
      order by dbms_random.value
      fetch first 1 rows only
      )
);

A: To randomly select 20 rows I think you'd be better off selecting the lot of them randomly ordered and selecting the first 20 of that set.
Something like:
Select *
  from (select *
          from table
         order by dbms_random.value) -- you can also use DBMS_RANDOM.RANDOM
 where rownum < 21;

Best used for small tables to avoid selecting large chunks of data only to discard most of it.

A: SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

A: SELECT *
FROM   (
    SELECT *
    FROM   table
    ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum < 21;

A: SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

A: Here's how to pick a random sample out of each group:
SELECT GROUPING_COLUMN,
       MIN (COLUMN_NAME) KEEP (DENSE_RANK FIRST ORDER BY DBMS_RANDOM.VALUE)
         AS RANDOM_SAMPLE
FROM TABLE_NAME
GROUP BY GROUPING_COLUMN
ORDER BY GROUPING_COLUMN;

I'm not sure how efficient it is, but if you have a lot of categories and sub-categories, this seems to do the job nicely.

A: -- Q. How to find Random 50% records from table ?
when we want percent wise randomly data
SELECT *
FROM   (
SELECT *
FROM   table_name
ORDER BY DBMS_RANDOM.RANDOM)
WHERE  rownum <= (select count(*) from table_name) * 50/100;


text:
Q: Why Gaussian Elimination only works over field? When I was solving system of linear congruences (n variables, n equations), like this:
$AX \equiv b \pmod p$
I was told that ordinary Gaussian Elimination works if $p$ is prime. And I figured out that when $p$ is prime, integers $\pmod p$ form a field, otherwise it doesn't form a field, but a ring.
Here comes my problem, why Gaussian Elimination does not work over a ring? AFAIK, the difference between a ring and a field, is that elements in a field are multiplicatively invertible, but does it have something to do with the applicability of Gaussian Elimination? If yes, how?

A: You need to be able to invert the element on the main diagonal (as long as it is non-zero).  If $p$ is not prime, you may not be able to do this.  For example, let $p=6$, then $2,3$ have no inverse.  So try $$\begin {pmatrix} 2&0\\0&3 \end {pmatrix}\begin {pmatrix} X_1 \\ X_2 \end {pmatrix}=\begin {pmatrix} 1 \\ 1 \end {pmatrix}\pmod 6$$
If you complain that the Gaussian elimination is done, change the $0$'s to $1$'s.  If $p$ is prime you are guaranteed an inverse of any non-zero element and the equation will be soluble.  Do it $\pmod 7$ and you will succeed.

A: There is a form of Gaussian elimination which works over a PID which is described in this article. The normal form you get from this algorithm (Smith normal form) consists of only diagonal entries which divide successively and is useful for getting information about the structure of f.g. modules over a PID.

A: To ensure that the solution set is preserved, the row operations should be reversible.  In a ring, the following operations are reversible:

*

*interchange two rows;

*add a multiple of one row to another row;

*multiply a row by a unit, that is, by an invertible element of the ring.

In a PID these suffice to put the matrix in row echelon form, but it is not always possible to put the matrix in reduced row echelon form since it is not always possible to obtain $1$ as a leading coefficient.  In particular, if a leading coefficient is not invertible, then one cannot obtain $1$ as a leading coefficient.  In a field, of course, all non-zero elements are invertible.
Example: Reduce the matrix
$$\begin{bmatrix}6 & 3\\ 4 & 8\end{bmatrix}$$
modulo $10.$
We subtract row $2$ from row $1$ to obtain
$$\begin{bmatrix}2 & 5\\ 4 & 2\end{bmatrix},$$
and then subtract twice row $1$ from row $2$ to obtain
$$\begin{bmatrix}2 & 5\\ 0 & 2\end{bmatrix}.$$
In general, one may have to repeat several times, Euclidean-algorithm style, until all but one element in the first column is $0$.  There's not much more we can do at this point.  We can reduce the size of the element $5$ as much as possible by subtracting twice row $2$ from row $1$ to obtain
$$\begin{bmatrix}2 & 1\\ 0 & 2\end{bmatrix}.$$
One also needs to worry about the right side of the equation.  If the reduced equation is
$$\begin{bmatrix}2 & 1\\ 0 & 2\end{bmatrix}\begin{bmatrix}x\\ y\end{bmatrix}=\begin{bmatrix}a\\ b\end{bmatrix}$$
then there is no solution if $b$ is odd.  If $b$ is even, then there are two solutions.  For example, if $(a,b)=(5,6)$ then the solutions are $(x,y)\in\{(1,3),(6,3)\}.$
Another example:  Reduce the matrix
$$\left[\begin{array}{cc|c}5 & 3 & 8\\ 10 & 4 & 6\end{array}\right]$$
modulo $12.$
Subtract twice row $1$ from row $2:$
$$\left[\begin{array}{cc|c}5 & 3 & 8\\ 0 & 10 & 2\end{array}\right].$$
Multiply row $1$ by the multiplicative inverse of $5,$ which is $5:$
$$\left[\begin{array}{cc|c}1 & 3 & 4\\ 0 & 10 & 2\end{array}\right].$$
Again there's not a lot we can do from here.  We are free to multiply row $2$ by an invertible element, such as $5,$ as well.  This is useful since it reduces the size of the coefficient:
$$\left[\begin{array}{cc|c}1 & 3 & 4\\ 0 & 2 & 10\end{array}\right].$$
We can now subtract row $2$ from row $1$ to reduce the size of the element $3:$
$$\left[\begin{array}{cc|c}1 & 1 & 6\\ 0 & 2 & 10\end{array}\right].$$
There are two solutions:
$$\begin{bmatrix}1\\ 5\end{bmatrix},\quad\begin{bmatrix}7\\ 11\end{bmatrix}.$$


text:
Q: INSERT INTO a table comparing two other tables using Not EXISTS I have 3 tables:

*

*Server_db_relation

*DatabaseList

*DatabaseList_Archive

The goal is to compare table Server_db_relation and DatabaseList based on the values in column ServerName and DatabaseName. If the values do not exists in the table Server_db_relation, but do exist in DatabaseList, then it should insert the entire row from DatabaseList into DataList_Archive (those two tables are identical in structure).
In addition, if possible ones the row has been inserted to DatabaseList_Archive then delete the record from DatabaseList.
INSERT INTO DatabaseList_Archieve (Column1, Column2...)
    SELECT *
    FROM DatabaseList
    WHERE NOT EXISTS (SELECT 1
                      FROM DabaseList, Server_db_relation
                      WHERE DatabaseList.ServerName = Server_db_relation.ServerName
                        AND DatabaseList.DatabaseName = Server_db_relatio.[Database])

I do not get any syntax errors but no rows are affected. I have added 2 test rows that I know exist in DatabaseList and not in Server_db_relation.

A: You need correlate the sub-query :
INSERT INTO DatabaseList_Archieve (Column1, Column2...)
    SELECT dbl.col1, dbl.col2, . .
    FROM DatabaseList dbl
    WHERE NOT EXISTS(SELECT 1
                     FROM Server_db_relation sdb
                     WHERE dbl.ServerName = sdb.ServerName AND
                           dbl.DatabaseName = sdb.[Database]
                    );

Note : I have declared the table alias to make the query easy to ready & write column name or table name (where it comes from).


text:
Q: How to publish package for use in a AoT angular2 app I have a code written in angular2 typescript , this is a module exported with services and components

@NgModule({
    declarations:[
        ...DECLARATIONS
    ],
    imports: [
        CommonModule,
        ChartModule
    ],
    exports:[
        ...DECLARATIONS,
        CommonModule,
        ChartModule
    ],
    providers:[
        AlertErrorHandleService
        , AuthenticationModelService
        , AuthConnectionBackend
    ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class MyModule {
    static forRoot():ModuleWithProviders {
        return {
            ngModule: StmsModule,
            providers: [AlertErrorHandleService
                , AuthenticationModelService
                , AuthConnectionBackend
            ]
        };
    }
}

I want to use this MyModule in different angular2 applications , so I've published it with this tsconfig and scripts

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "removeComments": true,
    "module": "es2015",
    "target": "es5",
    "moduleResolution": "node",
    "sourceMap": true,
    "declaration": true,
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "lib": ["dom", "es2015"],
    "outDir": "dist",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "scripts"
  ],
  "angularCompilerOptions": {
    "genDir": "aot"
  }
}

packages.json

"name": "my-lib",
  "version": "0.2.1",
  "description": "Shared lib angular2",
  "main": "index.js",
  "typings": "index.d.ts",
  "scripts": {
    "ngc": "ngc",
    "lint": "tslint src/**/*.ts",
    "copyPackage":"node ./scripts/copy-package",
    "build": "rimraf -rf aot dist && npm run ngc && npm run copyPackage",
    "publishPackage": "npm run build && cd dist && npm publish"
  },
  "keywords": [
    "angular",
    "angular2"
  ],
  "author": "Haddar Macdasi",
  "license": "MIT",
  "dependencies": {
    "@angular/core": "2.1.1",
    "@angular/common": "2.1.1",
    "@angular/compiler": "2.1.1",
    "@angular/compiler-cli": "2.1.1",
    "@angular/http":"2.1.1",
    "@angular/platform-browser": "2.1.1",
    "rxjs": "5.0.0-beta.12",
    "angular2-highcharts": "0.4.1",
    "highcharts": "5.0.2"
  },
  "devDependencies": {
    "@types/chai": "^3.4.34",
    "@types/node": "^6.0.41",
    "typescript": "^2.0.3"
  }

in other angular2 app that was created using seed from angular2 seed I've installed the package , trying to use it all works as I run the app not in AOT but in AoT it has error

Error: Unexpected value 'MyModule' imported by the module 'AboutModule'

I have couple of questions :

*

*how should I publish the package / what is the differents inside
tsconfig "module" = es2015 / systemjs / commonjs

*Is the module
publishe type has anything to do with how the package can be used
inside angular2 - i.e , If i use systemjs publish can I this package
in an angular2 AoT app ?

*Is there any kind of best practice how to
publish an angular2 shared module and use it in diff apps ?

A: IMHO, it's still very early to adopt AoT. I just tried it in my project. I think tools for AoT are not ready yet.
However, I think I have made it work in my project. You can use the same setting to make yours work.
Here is the github for ngx-clipboard
This project is actually pretty small but it shows how to use 3rd party library (pure javascript) with angular and be AoT compatible.
There are a lot of things that can upset AoT build.
Webpack, ngTool, angular, Typescript. I would suggest you try to use exact same versions I used first.
1.use es2015 because AoT doesn't take "require"
https://angular.io/docs/ts/latest/cookbook/aot-compiler.html#!#rollup

*I think it depends. But if you wanna make your package AoT compatible, I think you better use es2015.

*I haven't found one.
But I found this post useful.

A: I plead ignorance of the actual issue, but recognised the error message from a blog post I was just reading for a different reason.
This appears to be related to needing to include the *.metadata.json files in your npm package.
https://medium.com/@isaacplmann/getting-your-angular-2-library-ready-for-aot-90d1347bcad#.p7i6p63e8


text:
Q: How do i set the data context in XAML to global static variable? In my App.xaml.cs I have a global view model
public partial class App : Application
{
    public static ViewModel viewModel = new ViewModel();
}

and I've always set data context in the code behind like this
public MainWindow(){
  ...
  DataContext = App.viewModel;
  ...
}

However I want to try doing the same thing but in the XAML.  How do I select the class and static property from the XAML?
So far I have in my UserControl
<UserControl ...
         xmlns:global="clr-namespace:MyMainNamespace"

(App would be under that namespace like this  MyMainNamespace.App)
and then I can select 'App' just fine from global like this
<UserControl.Resources>
    <global:App x:Key="test"></global:App>
</UserControl.Resources>

<UserControl.DataContext>
   ??
</UserControl.DataContext>

And further down in the user control I have a combo box that I want to bind to an observable collection inside the viewModel
<Grid>
    <ComboBox Width="150" Height="25" HorizontalAlignment="Left" VerticalAlignment="Top" ></ComboBox>
</Grid>

Edit: I was trying to model my solution after this answer
 https://stackoverflow.com/a/23714054/1462656
But I could not find a way to select the viewModel object from App without it giving me syntax errors

A: You can bind to your resource using a StaticResource binding for the Source, and grab a property off of it using the binding's Path, like this:
<UserControl ...Existing attributes... DataContext="{Binding Source={StaticResource test},
                                                             Path=viewModel}">

If you really want the DataContext in the "attached" format, you could do it like this:
<UserControl.DataContext>
    <Binding Path="viewmodel" Source="{StaticResource test}" />
</UserControl.DataContext>

...but you will have to make viewModel an actual property, it won't work as a field.  Your code may also generate an InvalidOperationException

InvalidOperationException: Cannot create more than one
  System.Windows.Application instance in the same AppDomain.

if App is your application class generated from App.xaml.cs, as the format you use to declare the resource will create a new instance of it.  This will happen even with the "inline" syntax above.  It isn't caused by the binding, but by the resource declaration.

My preferred way of doing this, would be to just create a view-model class for the control that implements INotifyPropertyChanged, let's just call it MyControlVm for this example.  Then set the DataContext like this:
<UserControl.DataContext>
    <local: MyControlVm />
</UserControl.DataContext>

This would allow you to have multiple instance of your UserControl without them all sharing the same state (as your static property of App would).


text:
Q: How to handle inserting SQL queries that conflict with Trino SQL syntax? I want to insert a variety of SQL queries into a Trino table as a VARCHAR.
There are a multitude of items that throw errors for example single quotes, keywords like "table" being a column name, -- SQL comments that throw errors when Trino is reading the SQL INSERT query.
Is there a data type where I can just dump string type data that may contain things like keywords, SQL comments, single quotes? Trying VARCHAR doesn't seem to be the answer.


text:
Q: How to use Retrofit's suspend functions with AS 4.0 and compose enabled? I'm working on an experimental project where I'm using jetpack compose in Android Studio 4.0 and Retrofit's coroutine support.
Here is my top-level gradle.build:
buildscript {
    ext.kotlin_version = "1.3.61"
    ext.compose_version = '0.1.0-dev03'

    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-alpha06'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
}

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

And here is the app module build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 29
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }

}

dependencies {
    def room_version = "2.2.2"
    def lifecycle_version = "2.2.0-rc03"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'

    implementation "androidx.compose:compose-runtime:$compose_version"
    implementation "androidx.ui:ui-framework:$compose_version"
    implementation "androidx.ui:ui-layout:$compose_version"
    implementation "androidx.ui:ui-material:$compose_version"
    implementation "androidx.ui:ui-foundation:$compose_version"
    implementation "androidx.ui:ui-animation:$compose_version"
    implementation "androidx.ui:ui-tooling:$compose_version"

    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.fragment:fragment-ktx:1.2.0-rc03"

    implementation "com.squareup.retrofit2:retrofit:2.6.2"
    implementation "com.squareup.retrofit2:converter-moshi:2.4.0"
    implementation 'com.squareup.okhttp3:okhttp:4.2.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
    compileOnly 'org.glassfish:javax.annotation:10.0-b28'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

And finally my problematic retrofit api service interface:
import com.example.test.data.response.SnapshotResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Header

interface ApiService {
    @GET("/login")
    suspend fun login(@Header("Authorization") credentials: String): SnapshotResponse
}

Whenever I try to call this login method I get:
java.lang.IllegalArgumentException: HTTP method annotation is required (e.g., @GET, @POST, etc.)

But when I try to change my login method to non-suspending traditional versions like this:
@GET("/login")
fun login(@Header("Authorization") credentials: String): Call<SnapshotResponse>

Then everything works fine.
This seems to be related to AS4.0's IR compiler. Did anybody found some workaround for this?
Edit: I've probably found a related issue on Retrofit's tracker https://github.com/square/retrofit/issues/3233
and google's tracker
https://issuetracker.google.com/issues/143468771

A: You can create a module without compose enabled where you place all your Retrofit services, it doesn't matter that the App module (that depends on your "services" module has Compose enabled as long as your "services" module doesn't have it enabled)
This workaround is working fine for me in Android Studio 4.0 canary 7.


text:
Q: Why is this returning the wrong modulo answer?     private int mCurrentIndex = 0;
    mPrevButton = (Button)findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mCurrentIndex = (-33 % 5);
            Log.i("IndexClick", String.valueOf(mCurrentIndex));
        }
    });

This is returning -3 instead of a 2. It does the math right with a positive number. Please help can't seem to find a solution.

A: With the % operator, the sign of the remainder must match the sign of the dividend (or be 0), according to the JLS, Section 15.17.3:

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

And in fact, (-33/5)*5 + (-33%5) becomes -6*5 + (-3) which equals -33.
To get a positive result, you must have a positive dividend.

A: According to the JLS:

The remainder operation for operands that are integer ... produces a result value such that (a/b)*b+(a%b) is equal to a.

In your example, a = -33 and b = 5. Therefore:
(a/b)*b+(a%b) = -33
(-33/5)*5+(-33%5) = -33
(-6)*5+(-33%5) = -33
-30+(-33%5) = -33
(-33%5) = -3, as expected


text:
Q: How to ignore .txt for cin for output file in C++? This is my C++ code and I wish to create an output file. In order to create the output file, I request the user to include .txt at this input,  cin  >> accnum ; , hence, when output file is produced, it will show accnum.txt as plain text. My question is, what should I do in order to ignore .txt to be appeared in the text file, provided that I must input .txt(this is to produce txt file, without .txt at the input, no output file will be produced). I have put a comment line, kindly refer to that line. Thanks for your help!
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <iomanip>
    using namespace std;

    int main ()
    {
        double withdraw,deposit,number,transfer,num,amt;
        string name,first_name,middle_name,last_name;
        int x=0;
        int option;
        int A = 300;
        int B = 500;
        int C,W,y;
        string accnum;
        ifstream infile;
        ofstream outfile;

        do {
            cout <<"                          Welcome to ATM Machine                         "<<endl;
            cout <<"\n\t****Menu****";
            cout <<"\n\t*                 1.Creating a new account                     *";
            cout <<"\n\t*                 2.Cash Deposit                               *";
            cout <<"\n\t*                 3.Cash withdrawal                            *";
            cout <<"\n\t*                 4.Fund transfer between two account          *";
            cout <<"\n\t*                 5.Exit                                       *";
            cout <<"\n\t*                                                              *";
            cout <<"\n\t********";
            cout <<"\n\t                  Please choose an option: ";
            cin>>option;

            switch(option){
                case 1:
                    cout <<"Press 1 to Confirm" << endl << "Press 0 to exit " << endl ;
                    cin >> C ;
                    {
                        if( C == 1 )
                        {
                        cout << "Enter first name: " << endl;
                        cin >> first_name;
                        cout << "Enter middle name: " << endl;
                        cin >> middle_name;
                        cout << "Enter last name: " << endl;
                        cin >> last_name;

                        name = first_name + " " + middle_name + " " + last_name;
                        cout << "enter a 4 digit number : " << endl << "gentle reminder : please add .txt at the end of your number" << endl << "e.g 1234.txt" << endl;
                        cin  >> accnum ; //how to ignore .txt
                        cout << "What is your primary balance: " << endl;
                        cin >> amt;
                        infile.open(name);
                        outfile.open(name);
                        cout << "your account has been created " << endl ;
                        outfile << "name" << name << endl;
                        outfile << "account no. : " << accnum << endl ;
                        outfile << "current balance : RM" << amt << endl ;
                        }else {
                        cout << "Bye, have a nice day";
                        }
                    infile.close();
                    outfile.close();
                    }
                    break;

                case 2:
                    cout<<"Deposit amount: "<<endl;
                    cin>>deposit;
                    if(deposit<10) {
                        cout<<"The smallest note acceptable is RM10."<<endl;
                    }else {
                        x=static_cast<int>(deposit)%10;
                        if(x!=0)
                        {
                        cout<<"Invalid deposit amount"<<endl;
                        cout<<"Example of deposit amount: RM10, RM20, RM50, RM320..."<<endl;
                        }else {
                        A+=deposit;
                        cout<<"current balance: RM"<< A <<endl;
                        }
                    }
                    break;

                case 3:
                    cout<<"Amount you want to withdraw"<<endl;
                    cin>>withdraw;
                    if(A < withdraw || withdraw < 10) {    // A is balance
                    cout <<"Failed to withdraw money! Please try again."<<endl;
                    }else {
                    A-=withdraw;
                    cout <<"current balance: "<< A <<endl;
                    }
                    break;

                case 4:
                    infile.open("1212.txt");

                    infile >> x;
                    cout<<"Enter Details of transfering Account(Account A)"<<endl;
                    cout<< "Your account number is:"<<endl;
                    cin>>W;
                    cout<< "What is your name:"<<endl;
                    cin.ignore();
                    getline(cin,name);
                    cout<<"Enter Details of receiving Account(Account B)"<<endl;
                    cout<<"Enter account number:"<<endl;
                    cin>>W;
                    cout<<"Enter name:"<<endl;
                    cin.ignore();
                    getline(cin, name);
                    cout <<"your account balance is : " << x << endl << "how much do you want to transfer ? ";
                    cin >> num ;

                    outfile.open("1212.txt");
                    outfile << x - num ;
                    cout << "your account balance is : " << x - num ;

                   infile.close();
                   outfile.close();

                   infile.open("2121.txt");

                   infile >> y ;
                   outfile.open("2121.txt") ;
                   outfile << y + num ;

                   infile.close();
                   outfile.close();
                        break;

                case 5:
                    cout<<"Thank you for using ATM machine. Bye, have a nice day !"<<endl;
                    return 0;

                default:
                    if(option != 5) cout<<"Invalid option.Please try again!"<<endl;
                    break;
            }
        }while(option != 5);

        system("pause");
        return 0;
    }

A: You asked about how to remove the .txt part from accnum and here's one way to do that:
cin  >> accnum ; //how to ignore .txt

// check that the length/size of the entered accnum is at least 4 characters
// and
// that the last 4 characters is ".txt"

if(accnum.size() >= 4 && accnum.substr(accnum.size() - 4) == ".txt") {
    // extract a substring from accnum without the last 4 characters
    accnum = accnum.substr(0, accnum.size() - 4);
}

However, I have my doubts about the requirement that the user should actually add .txt to the account number, because seeing this at an ATM would be really confusing:
enter a 4 digit number :
gentle reminder : please add .txt at the end of your number"
e.g 1234.txt

It's especially confusing since the only thing you want to do with .txt is to remove it. I would consider changing this user interface.
Suggestions:

*

*Let the user add the account number without .txt

*Instead of saving the account information in a file with the account holders name as the filename, save it in a file named accnum + ".txt". This makes it possible for a person to have more than one account - just as in real life.

A: Just create the file without a format, the name will be the file_name content exactly, be aware that in windows has reserved names such as CON.
#include <iostream>
#include <fstream>
#include <string>

int main (void) {
    std::string  file_name = "1234";
    std::fstream f_handle;

    f_handle.open(file_name, std::fstream::out);
    if (f_handle.is_open()){
        f_handle << "Some text" << std::endl;
        f_handle.close();
    }

    f_handle.open(file_name, std::fstream::in);
    if (f_handle.is_open()){
        std::cout << f_handle.rdbuf() << std::endl;
        f_handle.close();
    }

    return 0;
}


text:
Q: Data binding from a method in Flex I have the following mxml (Omitted some parts for brevity purpose):
<fx:Script>
    [Bindable]
    private var _dataSet:IDataSet;

    public function set dataSet(value:IDataSet)
    {
      _dataSet = value;
    }

    private function getColorItem(itemName:*):String
    {
      if (itemName == "Research")  return "#31e5fc";
      ...
      else {
        trace("Unknown item : " + itemName);
        return #ffffff;
      }
    }
</fx:Script>
<spark:RichText color="{this.getColorItem(this._dataSet.name)}" ... />

Does anyone knows why the color is not being applied?  If I change the binding to the method, for a constant String (i.e. #31e5fc), it works allright?
I need the color to change according to the data received by this component.  Any help on where I am doing a mistake is much appreciated.

A: You've got a couple of odd things here.  First, your getColorItem function should return a uint rather than a String.  Second, why not just call getColorItem from your dataSet setter?  Something like this:
public function set dataSet(value:IDataSet)
{
    _dataSet = value;
    myRichText.setStyle("color", getColorItem(_dataSet.name);
}

Hope that helps.


text:
Q: Can TypeScript extend an instance's type after calling the instance's method? I have a JS library that I'm trying to create types for, imagine the following class:
class Table {

  register(...fields) {
    fields.forEach(field => {
      Object.defineProperty(this, field, {
        get: () => {
          console.log(`Accessed ${field}`);
          return 1;
        },
      })
    })
  }

}

and then you could use Table this way:
let table = new Table();
table.register(["uuid", "name", "url"]);
table.name; // has a value of 1 and prints "Accessed name"

Writing a declaration for the class seems easy
class Table {
  register(...fields: string[]): void;
}

However, I don't know whether it's possible for TypeScript to extend the instance's type after calling table.register().
let table = new Table();
table.register(["uuid", "name", "url"]);
table.name; // TypeScript error, `name` is not a field of Table

I know it's possible to change the JS code to return the instance itself and then TypeScript could simply return a different type, but in the case the function doesn't return anything, is it possible to tell TypeScript that the instance's type has slightly changed after the call?

A: You can turn void-returning functions and methods into assertion functions by annotating their return type with an asserts predicate.  This allows the compiler to interpret a call to that function as a narrowing of the apparent type of one of the arguments (or this in the case of an assertion method).
Adding properties to an existing type is considered a narrowing, according to  TypeScript's structural type system.  That's because object types are open/extensible and not sealed/exact; given types interface Foo {x: string} and interface Bar extends Foo {y: string}, you can say that every Bar is a Foo but not vice versa, and therefore that Bar is narrower than Foo. (Note that there is a longstanding open request to support exact types at microsoft/TypeScript#12936, and people often are confused into thinking that TypeScript types are exact because of excess property warnings on object literals; I won't digress further here, but the main point is that extra properties constitute a narrowing and not an incompatibility).
So, because register() is a void-returning method which serves to add properties to this, you can get the behavior you're looking for by making register() into an assertion method.

Here's one way to do it:
class Table {
  register<P extends string>(...fields: P[]
  ): asserts this is this & Record<P, 1> {
    fields.forEach(field => {
      Object.defineProperty(this, field, {
        get: () => {
          console.log(`Accessed ${field}`);
          return 1;
        },
      })
    })
  }
}

The return type asserts this is this & Record<P, 1> implies that a call to table.register(...fields) will cause the type of table (the value called this in asserts this) to be narrowed from whatever it starts as (the type called this in this & Record<P, 1>) to the intersection of its starting type with Record<P, 1> (using the Record<K, V> utility type), where P is the union of string literal types of the values passed in as fields.
That means that by starting with table of type Table, a call to table.register("x", "y", "z") should narrow table to Table & Record<"x" | "y" | "z", 1>, which is equivalent to Table & {x: 1, y: 1, z: 1}.

Let's see it in action, before exploring some important caveats:
let table: Table = new Table();
// ----> ^^^^^^^ <--- this annotation is REQUIRED for this to work
table.register("uuid", "name", "url");
table.name; // has a value of 1 and prints "Accessed name"
table.hello; // error
table.register("hello");
table.hello; // okay

That's more or less what you wanted, I think.  The compiler allows you to access table.name after the call the table.register("uuid", "name", "url").  I also add a "hello" field, and you can see that the compiler is unhappy about accessing it before it is created, but happy afterward.

So, hooray. Now for the caveats:
The first one is shown above; you are required to annotate the table variable with the Table type in order for its assertion method to behave.  If you don't, you get this awful thing:
let table = new Table();
table.register("uuid", "name", "url"); // error!
//~~~~~~~~~~~~ <-- Assertions require every name in the
// call target to be declared with an explicit type annotation

This is a basic limitation with assertion functions and assertion methods.  According to microsoft/TypeScript#32695, the PR that implemented assertion functions (emphasis mine):

A function call is analyzed as an assertion call ... when ...
each identifier in the function name references an entity with an explicit type ... An entity is considered to have an explicit type when it is declared as a function, method, class or namespace, or as a variable, parameter or property with an explicit type annotation. (This particular rule exists so that control flow analysis of potential assertion calls doesn't circularly trigger further analysis.

And microsoft/TypeScript#33622 is the PR that implemented the particular error message above (before this it would just silently fail to narrow).  It's not great, and it bites people every so often.
It would be great if it could be fixed, but according to this comment on the related issue microsoft/TypeScript#34596:

The issue here is that we need the information about the assertness of a function early enough in the compilation process to correctly construct the control flow graph. Later in the process, we can detect if this didn't happen, but can't really fix it without performing an unbounded number of passes. We warned that this would be confusing but everyone said to add the feature anyway

So I guess if you want this to work, you're going to need an explicit type annotation.

Also, a general problem with control flow analysis is that its effects do not cross function boundaries.  You can read all about it at microsoft/TypeScript#9998.  This implies that closures over narrowed values will lose their narrowing, perhaps surprisingly:
let table: Table = new Table();
table.register("hello");
table.hello; // okay

function doSomething() {
  table.hello; // error!
}

Inside doSomething(), the type of table has been widened back to Table.  The standard workaround for such cases is to "save" the narrowed state by assigning the narrowed value to a new const variable, and then use the const inside the function:
const _table = table;
function doSomething2() {
  _table.hello; // okay
}

This works because _table is assigned from table, whose apparent type at the time of the assignment contains a hello property.  And therefore _table will always and forever have such a property, even inside closures.
And so, that's great, but... well, it's not very much different from having the register() function return a new value of the narrowed type and having you use the new value instead of the old one, which is the approach you mentioned in the question.

So depending on how you use Table instances, assertion methods might be more trouble than they're worth.  Still, they do exist, and are exactly what you were asking about in your question, and they do kind of sort of work sometimes, so you should keep them in mind!
Playground link to code


text:
Q: rails and rmagick and webfaction I am having a problem loading imagemagick and rmagick on webfaction.
I have installed a rails app called Balderapp that organizes images.
I can't seem to upload the image through balder.
Balder uses imagemagick and rmagick
when i use the console and do this I get a nill as a return making me think rmagick is not working
irb(main):003:0> require 'RMagick'
=> nil
thx
sg

A: The general steps are:

*

*Install ImageMagick from source in your home directory.

*Install the RMagick gem, linked to the ImageMagick libraries that you built in step 1.

Detailed steps are available in WebFaction's procedure for installing ImageMagick and RMagick.

A: On Web faction make sure your are in the correct folder cd  $HOME/webapps/app app is the name of your app. Make sure the rmagick gem is installed ./bin/gem list
in ./bin/irb then this should work:
require 'rubygems'
require 'RMagick'

if you are using ruby 1.8.* then do not forget to do the require 'rubygems'


text:
Q: Insertar datos en comboBox Tengo el siguiente codigo,el resultado del cursor me devuelve los datos correcto, el problema que el comboBox no los muestra, es correcta la forma de llenarlo?
print([str(x[0]) for x in cursorUsuario])

['1', '4', '5', '6', '9']

self.dlg.comboLote.addItems([str(x[0]) for x in cursorUsuario])

Funcion donde lleno el comboBox
 def obtenerUsuario(self,doc):

        with open(doc, 'r') as searchfile:

                for line in searchfile:
                    if "url=https://test/ows/wfs" in line:
                        nombreConexion = line.split('\\')[1]
                        nombreUsuario = nombreConexion+"\\username"
                        passwordUsuario = nombreConexion+"\\password"

                        for linea in searchfile:
                            if nombreUsuario in linea:
                               usuario = linea.split("=")[1]
                               usuarioSiena = usuario.rstrip()

                sqlLote = ("select lot.idLote from [inf].[Lote] lot \
                                  inner join [dbo].[Usuario] u on lot.idUsuario = u.idUsuario \
                                  where u.userName = '%s'") % \
                                    (usuario)

                self.dlg.comboLote.clear()

                cursorUsuario = connUsuario.execute(sqlLote)

                print([str(x[0]) for x in cursorUsuario])

                self.dlg.comboLote.addItems([str(x[0]) for x in cursorUsuario])

Llamo a la funcion:
def run(self):

    self.dlg.comboLote.clear()

    self.obtenerUsuario("C:\Users\usuario\AppData\Roaming\QGIS\QGIS3\profiles\default\QGIS\QGIS3.ini")

A: Si el adaptador como cabe esperar sigue las especificaciones de PEP 249 -- Python Database API Specification, Cursor debe implementar el conocido como protocolo iterador, lo que significa que retorna las filas de la consulta una a una hasta que se agotan, en cada iteración nos genera y retorna una nueva tupla con el contenido de la fila siguiente hasta que no queda ninguna, momento en el que genera un error StopIteration.
Esto tiene un razonamiento muy lógico, los iteradores/generadores son en esencia perezosos, no generan nada antes de que se les pida. En teoría, una buena implementación de un adaptador de base de datos debería obtener filas en lotes desde el servidor, no obtener toda la consulta de golpe con el consiguiente consumo de memoria al tener que mantener almacenado el conjunto completo de resultados simultáneamente.
Esto sería lo ideal, pero lo cierto es que depende del adaptador y de la base de datos, hay casos en los que la consulta se almacena al completo en el cliente (ya sea usando contenedores de Python o de C), en los que se almacena en el servidor... Esto no nos importa en realidad para lo que nos concierne, lo que hay que tener claro es que cuando se itera sobre un cursor ya sea mediante un for in, fethone, fetchall o cualquier otro método que implique iterar sobre el mismo (p.e list(cursor)) este se va "consumiendo".
Tu problema se debe en realidad al "inocente" print seguramente con fines de depuración:
print([str(x[0]) for x in cursorUsuario])

donde iteras sobre el cursor al completo para generar una lista que imprimes y dejas a merced del recolector de basura. Cuando vuelves a iterar en:
self.dlg.comboLote.addItems([str(x[0]) for x in cursorUsuario])

el cursor no tiene nada que retornar porque fue consumido en el anterior for. Podemos emularlo con:
>>> cursor = iter((("a", ), ("b", ), ("c", ), ("d", )))
>>> print([row[0] for row in cursor])
['a', 'b', 'c', 'd']

>>> [row[0] for row in cursor] # Genera una lista vacía
[]

Si eliminas ese print todo irá bien, ten en cuenta que QComboBox.addItems acepta cualquier iterable mientras que este contenga cadenas, por lo que puedes hacer simplemente:
 self.dlg.comboLote.addItems(str(x[0]) for x in cursorUsuario)

Si necesitaras realmente una lista, itera sobre el cursor una sola vez y asigna la lista a una variable, por ejemplo:
ls = [row[0] for row in cursorUsuario]
print(ls)
self.dlg.comboLote.addItems(ls)

Como apunte aparte, no deberías usar la barra diagonal inversa  en las rutas sin escapar. La razón es que \ se usa para determinar secuencias de escape, por lo que en "C:\fichero\registro" \r es tomado como un retorno de carro... Usa la barra inclinada / o puedes normalizarla con os.path.normpath("C:\...").


text:
Q: Why is `ref.current.clientHeight` always possibly null? I'm trying to find the height of the component in pixels as its height will be set to 100% in CSS
import React, { useState, useLayoutEffect, useRef } from "react";

function Scale() {
  const [height, setHeight] = useState(0);
  const ref = useRef(null);
  useLayoutEffect(() => {
    if (ref && ref.current && ref.current.clientHeight) {
//                              ^ error: Object is possibly 'null'
      const height = ref.current.clientHeight;
      setHeight(height);
    }
  });
  return (
    <div className="scale" ref={ref}>
      {height}
    </div>
  );
}

export { Scale };

A: ref is never going to be null, as it is const and not null to begin with, so if (ref) is useless.
The type of useRef<T>(x: T | null) is a MutableRefObject<T>. Here, T is null, so the type of ref.current is null.
To fix this, specify the type that it will be after it is set:
  const ref = useRef(null as null | HTMLDivElement);
  // Or manually specify the type parameter
  const ref = useRef<HTMLDivElement>(null)
  useLayoutEffect(() => {
    if (ref.current && ref.current.clientHeight) {
      const height = ref.current.clientHeight;
      setHeight(height);
    }
  });

A: if (ref && ref.current && ref.current.clientHeight) {
   //                        ^ error: Object is possibly 'null'
   const height = ref.current.clientHeight;
   setHeight(height);
}

This statement should work, but TypeScript often doesn't infer as we expect it to be.
So, best solution (not just some hacky workaround) is to use Babel Optional Chaining plugin.
Add it to your .babelrc.js and you can replace that statement with
if (ref?.current?.clientHeight) {
   const height = ref.current.clientHeight;
   setHeight(height);
}

It's actually a native TypeScript 3.7 feature, so it works like a charm.


text:
Q: Rails: Two tables has_many a single table What's a better way to achieve this?
class Opf < ActiveRecord::Base
    has_many :budget_items, dependent: :destroy, foreign_key: 'budget_id'
end

class Voucher < ActiveRecord::Base
    has_many :budget_items, dependent: :destroy, foreign_key: 'budget_id'
end

class BudgetItem < ActiveRecord::Base
    belongs_to :opf
    belongs_to :voucher
end

Opf and Voucher could has_many BudgetItem:
Opf.budget_items.build
Voucher.budget_items.build

The problem I get with this setup is they share the same foreign key.

A: For such cases you should consider polymorphic associations. They are easy to establish and maintain.


text:
Q: Qt - MainWindow.cpp hangs/crashes I turn on the PC, the code compiles, the application runs.
I close the application, and run again, but it crashes with error A
I close and run again, it just hangs while trying to create MainWindow.
I restart PC, and back to top, the application runs one time.
Even if I remove the members initialization list, it doesn't change.
The error might be something strange. I am using boost::interprocess to create shared memory, but I tried commenting this out, and still the same.
I am compiling against Qt 4.8.6.
so from the point of constructor parameters, should be fine.
ideas?
main.cpp:
...
cout<< "something"; //this prints
MainWindow w(ce); //hangs when reaching this line
cout<< "whatever"; //this does NOT print
...

mainwindow.h:
explicit MainWindow(CreateEvents *ce, QWidget *parent = 0);

MainWindow.cpp:
//includes etc
...
//MainWindow constructor here:

MainWindow::MainWindow(CreateEvents *ce, QWidget *parent) :
 QMainWindow(parent),
 ui(new Ui::MainWindow),
 shWriter() {

 qDebug("MainWindow CONSTRUCTOR!"); //this does NOT print
...


text:
Q: Why does SciPy return negative p-values for extremely small p-values with the Fisher-exact test? I've noticed that the Fisher-exact test in SciPy returns a negative p-value if the p-value is extrememly small:
>>> import scipy as sp
>>> import scipy.stats
>>> x = [[48,60],[3088,17134]]
>>> sp.stats.fisher_exact(x)
(4.4388601036269426, -1.5673906617053035e-11)

In R, using the same 2x2 contingency table:
> a = matrix(c(48,60,3088,17134), nrow=2)
> fisher.test(a)
p-value = 6.409e-13

My question is 1) why does SciPy return a negative p-value? 2) how can I use SciPy to generate the correct p-value?
Thanks for the help.

A: Fisher's exact test uses the hypergeometric distribution.
The version of scipy you are using uses an implementation of the hypergeometric distribution that is not very precise. This is a known problem and has been fixed in the scipy repository.


text:
Q: SwiftUI: Sign-in with Apple button crashes the app when shown inside NavigationLink or Sheet We are developing a SwiftUI watchOS application and we want to support sign-in with Apple functionality. Because there is no SwiftUI component for it, we are using WKInterfaceObjectRepresentable to show. Initially, this was shown as a first view with other sign-in options and we had no issue but then we decided to add these to some navigation flows and it started to crash.
Just to clarify, the below code works:
struct QWSplashScreenView: View {
    @State var showLogin: Bool = true

    var body: some View {
        QWSignInView(showEmailLogin: self.$showLogin)
    }
}

While this one, does not:
struct QWSplashScreenView: View {
    @State var showLogin: Bool = true

    var body: some View {
        NavigationLink(destination: QWSignInView(showEmailLogin: self.$showLogin), label: { Text("Login") })
    }
}

Crash is completely at system level, just to show initial part of it:
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.SwiftUI               0x010d33d2 static PlatformViewRepresentableAdaptor.platformView(for:) + 50
1   com.apple.SwiftUI               0x010d3c8c protocol witness for static PlatformViewRepresentable.platformView(for:) in conformance PlatformViewRepresentableAdaptor<A> + 28
2   com.apple.SwiftUI               0x011d7d5b PlatformViewHost.representedView.getter + 27
3   com.apple.SwiftUI               0x011e68f4 PlatformViewHost.init(_:host:environment:viewPhase:) + 340
4   com.apple.SwiftUI               0x011e2a8e PlatformViewHost.__allocating_init(_:host:environment:viewPhase:) + 46
5   com.apple.SwiftUI               0x011e235e closure #1 in PlatformViewChild.update(context:) + 1662
6   com.apple.SwiftUI               0x011ddaa9 PlatformViewChild.update(context:) + 553
7   com.apple.SwiftUI               0x011e4057 protocol witness for static UntypedAttribute._update(_:graph:attribute:) in conformance PlatformViewChild<A> + 39
8   com.apple.AttributeGraph        0x035c0791 partial apply + 33
9   com.apple.AttributeGraph        0x035a8d99 AG::Graph::UpdateStack::update() + 461

Does anyone have seen this behaviour? (Same crash happens if I use sheet as well)
The code of QWSignInView:
struct QWSignInView: View {
    @Binding var showEmailLogin: Bool

    var body: some View {
        VStack {
            Text("Record and save your blood pressure measurements")

            VStack() {
                QWSignInWithAppleButton()
                    .frame(height:40)

                Button(action: {
                    self.showEmailLogin = true
                }) {

                    Text("I have an account")
                }
            }
        }
    }
}

And the QWSignInWithAppleButton:
final class QWSignInWithAppleButton: WKInterfaceObjectRepresentable {
    typealias WKInterfaceObjectType = WKInterfaceAuthorizationAppleIDButton

    func makeWKInterfaceObject(context: WKInterfaceObjectRepresentableContext<QWSignInWithAppleButton>) -> WKInterfaceAuthorizationAppleIDButton {
        WKInterfaceAuthorizationAppleIDButton(target: context.coordinator, action: #selector(Coordinator.buttonPressed))
    }

    func updateWKInterfaceObject(_ wkInterfaceObject: WKInterfaceAuthorizationAppleIDButton, context: WKInterfaceObjectRepresentableContext<QWSignInWithAppleButton>) {
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }

    class Coordinator {
        @objc func buttonPressed() {
            appStore.loginStore.beginAppleIDSignIn()
        }
    }
}


text:
Q: Can't commit with SVN because I foolishly renamed the files in Visual Studio 2010 I didn't realize this at the time, but I committed a terrible mistake when I used Visual Studio 2010 to rename a winform. Now, SVN will not commit the files and I can't figure out how to fix this problem. All the other files (over 1,000) in the project commit without a problem. It's just this one winform, Messenger.
These are the files:

And this is the error:

I cannot use the SVN 'move fix' because the option doesn't appear (probably because it needs to pair a missing file with an unversioned file).
I asked this question previously, but now we're narrowing the problem down.
Any ideas?

A: As I see it, you have two choices. To be honest, I didn't even read the details of your problem. These two choices solve a great variety of similar situations without you having to think about it or understand wtf svn has gone bonkers, I'm confident they'll solve your problem, and it's how I would solve that problem if I encountered it:
Plan A:

*

*Make a fresh checkout

*Paste the contents of your old bolloxed checkout over the fresh checkout

*Perform a commit while adding all the new files.

*At some point in the future, or maybe right now, think of what the no-longer-used filenames are and delete them

*Resign yourself to having lost proper svn tracking of the rename.

Or plan B, if you didnt also edit the files:

*

*Make a fresh checkout

*Replicate your work using svn which you mistakenly did with VS

And advanced plan C combines the two by executing plan B and then pasting over the final edited sources from the bolloxed checkout.


text:
Q: Binding HTML radio buttons with Spring controller, Am developing this web app using Spring with a HTML view, filled with radio buttons, In each category, a user selects their option and finally submit their choices, How do I transfer or rather bind this values to the controller so that they are stored into a database.
Am using thymleaf for rendering.
<form th:action=${/submit} >
<input type="radio" name="check1" value="a"/>
<input type="radio" name="check1" value="b"/>

<input type="radio" name="check2" value="c"/>
<input type="radio" name="check2" value="d"/>

<input type="radio" name="check3" value="e"/>
<input type="radio" name="check3" value="f"/>

<input type="button" value=submit />
</form>

A: I'm building with Thymeleaf too. Make controller method of this prototype.
My form
<form action="submit" method="post" >
<input type="radio" name="check1" value="a"/>
<input type="radio" name="check1" value="b"/>

<input type="radio" name="check2" value="c"/>
<input type="radio" name="check2" value="d"/>

<input type="radio" name="check3" value="e"/>
<input type="radio" name="check3" value="f"/>

<input type="submit" />

And controller method:
@RequestMapping(value = "submit", method = RequestMethod.POST)
public ModelAndView page(
        @RequestParam(name = "check1") String check1,
        @RequestParam(name = "check2") String check2,
        @RequestParam(name = "check3") String check3)
{
    return new ModelAndView("index").addAllObjects(createModel());
}

In the debugger i get next values :


text:
Q: There are twenty different books which will be put on three different shelves. There is no restriction of the number of books in each shelf. How many ways to arrange the books?
I tried to compute by using combination with repetitions that is the 3C22 but I am not so sure.

A: If the books are distinguishable (and you should expect that from books) then see the answer of Nemo.
If not then this can be solved with Stars and Bars. You are actually looking for the number of ways number $20$ can be written as a sum of $3$ nonnegative integers and the answer is: $$\binom{22}{2}$$ Choosing $2$ spots out of $20+2=22$ to contain a bar corresponds with discerning $3$ shelves.

A: We have to count the linear arrangements of the set
$$\{1,2,\ldots,20, S_1,S_2,S_3\}$$
fulfilling the extra conditions that $S_1$ comes before $S_2$, and $S_3$ comes last. There are
$${22!\over2}=562\,000\,363\,888\,803\,840\,000$$
such arrangements.