text:
Q: Learning rate of a Q learning agent The question how the learning rate influences the convergence rate and convergence itself.
If the learning rate is constant, will Q function converge to the optimal on or learning rate should necessarily decay to guarantee convergence?

A: Learning rate tells the magnitude of step that is taken towards the solution.
It should not be too big a number as it may continuously oscillate around the minima and it should not be too small of a number else it will take a lot of time and iterations to reach the minima.
The reason why decay is advised in learning rate is because initially when we are at a totally random point in solution space we need to take big leaps towards the solution and later when we come close to it, we make small jumps and hence small improvements to finally reach the minima.
Analogy can be made as: in the game of golf when the ball is far away from the hole, the player hits it very hard to get as close as possible to the hole. Later when he reaches the flagged area, he choses a different stick to get accurate short shot.
So its not that he won't be able to put the ball in the hole without choosing the short shot stick, he may send the ball ahead of the target two or three times. But it would be best if he plays optimally and uses the right amount of power to reach the hole. Same is for decayed learning rate.

A: The learning rate must decay but not too fast.
The conditions for convergence are the following (sorry, no latex):

*

*sum(alpha(t), 1, inf) = inf

*sum(alpha(t)^2, 1, inf) < inf
Something like alpha = k/(k+t) can work well.
This paper discusses exactly this topic:
http://www.jmlr.org/papers/volume5/evendar03a/evendar03a.pdf

A: It should decay otherwise there will be some fluctuations provoking small changes in the policy.


text:
Q: Erro no Pycharm ao ler planilha do excel Boa noite pessoal, estou tentando fazer a leitura de uma planilha do excel, mas sempre recebo esse erro, alguém pode me ajudar por favor?

O programa faz a primeira leitura da planilha, ou seja, importa e abre, quando tento fazer qualquer outro comando depois disso, não consigo, sempre tenho esse erro!

A: Boa noite Rodrigues!
Creio que pelo tipo de erro (KeyError/Erro de Chave) a linha/coluna "Prod A" informada na planilha "Dados Tear 18" não existe com esse nome.
Tente olhar se não colocou com outro nome, como "ProdA", "Prod a", "Produto A", etc.
Espero que consiga resolver.
Abraço

redpajama_set_name: RedPajamaStackExchange


text:
Q: continued fractions and cusp non-excursions Consider the modular surface $X:=\mathbb{H^2}/PSL_2(\mathbb{Z})$.
Fix a width-of-cusp parameter $w, 0<w<<1$.
Let $B_w$ be the cusp neighborhood of width $w$. (So $w=1$ corresponds to the quotient of $\{\Im(z)>1\}$.)
Let $\gamma$ be a geodesic joining the cusp to itself. It leaves $B_w$, winds around, may re-enter $B_w$ several times, and eventually re-enters $B_w$ for good.  We may lift $\gamma$ to a vertical geodesic joining $\infty$ to a point $p/q$ in $[0,1)$.
Let $(l_1, l_2, \ldots, l_n)$ be the sequence of hyperbolic lengths of maximal subsegments of $\gamma$ lying outside $B_w$. Let $[0; a_1, a_2, \ldots, a_m]$ be the continued fraction expansion of $p/q$.
What, if any, is the relationship between these two sequences? I am aware of a relationship between the continued fraction expansion and ``cusp excursions'' expressed in terms of intersections with Farey edges having a common endpoint [R. Moeckel, Ergod. Thy. and Dynam. Sys. (1982), 2, 69-83.] But here I seek information on the geometry {\bf outside} the cusps.


text:
Q: How do I mock an overloaded function with const/non How do I mock the following code?
class ISomeClass
{
public:
   virtual ~ISomeClass() {} = 0;
   virtual const MyType & getType() const = 0;
   virtual MyType & getType() = 0;
};

I have tried the following, but it doesn´t work. Can you please help me?
class MockSomeClass : public ISomeClass
{
public:
    using MyTypeConstRefType = const MyType&;
    using MyTypeRefType = MyType&;

public:
    MOCK_METHOD0(getType, MyTypeConstRefType(void) const);

    MOCK_METHOD0(getType, MyTypeRefType(void));
};

A: They provide a separate set of macros for const member functions ("methods"): MOCK_CONST_METHOD#. So in your case, it would be:
MOCK_CONST_METHOD0(getType, MyTypeConstRefType());

The usage is otherwise identical to MOCK_METHOD#, taking the function name in the first argument and function type in the second.


text:
Q: How to insert many db records from Hibernate I have entity class
@Data
@NoArgsConstructor
@Entity
@Table(name = "tx")
public class Tx{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private int id;
    @Column(name = "aaa")
    private String aaa;
}

and i try to insert 100 template records into db.
Tx tx = applicationContext.getBean(Tx.class);
Session session = sessionFactory.openSession();
session.beginTransaction();
IntStream.range(0, 100).forEach(index -> session.save(tx));
session.getTransaction().commit();
session.close();

but as a result, only 1 record is inserted into the database. What am I doing wrong?

A: Tx tx = applicationContext.getBean(Tx.class); makes no sense.
Beans managed by the Application Context are Controller, Services, Repositories... Things that do something.
An Entity represents Data. I'm wondering why this even working
try something linke this:
Session session = sessionFactory.openSession();
session.beginTransaction();
IntStream.range(0, 100).forEach(index -> {
   Tx tx = new Tx();
   tx.setAaa(index);
   session.save(tx);
});
session.getTransaction().commit();
session.close();

A: Use CrudRepository<Model, Id> and Call its saveAll(List) Method for this
UserRepository
public interface UserRepository extends CrudRepository<User, Integer> {

    public List<User> findByName(String name);

    public List<User> findByCity(String city);

    public List<User> findByNameAndCity(String name, String city);

}

Main Method
public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(BootJpaExampleApplication.class, args);
    UserRepository userRepo = context.getBean(UserRepository.class);

    //save Single user
    userRepo.save(new User(101, "Aniruddh", "Delhi", "I am Java Developer"));

    // save Multiple Users

    User user = new User();
    user.setName("Rahul");
    user.setCity("Bhopal");
    user.setStatus("Python Developer");

    User user1 = new User();
    user1.setName("Ram");
    user1.setCity("Jabalpur");
    user1.setStatus("Database Developer");

    Iterable<User> users = List.of(user, user1);
    userRepo.saveAll(users);

}


text:
Q: Throwing an error will stop the execution of the code [Javascript] In this exercise I just did, throw an error still let the last console.log("This is still runs normally!") runs successfully but why the this question it is answer that throwing error stop the execution and no execution for console.log
Question I am confused about:
throw new Error();
console.log("Hello");

function addTwoNums(a, b) {
  try {
    if (typeof a != "number") {
      throw new ReferenceError("The First argument is not a number");
    } else if (typeof b != "number") {
      throw new ReferenceError("The Second argument is not a number");
    } else {
      console.log(a + b);
    }
  } catch (error) {
    console.log("Error:", error.message);
  }
}

addTwoNums("100", 100);
console.log("This is still runs normally!");

A: I dont really understand your question easily but i will try to answer two things :
in this first code you don't put throw error in a try catch, so if you execute it, the error stops the code before your console log.
throw new Error(); //-> stop the code and goodbye
console.log("Hello");

in the second code, you catch the error and tell the program to console log the error message when and error is caught :
} catch (error) { // <- if there is an error
    console.log("Error:", error.message); // <- then console log the error.message

so the program does the console log, and continues (and gets to your next console log "This is still runs normally!")
so the answer of your question about "why the error stops the code execution" is "becase its not caught or handled by a try-catch"


text:
Q: Changing terminal settings from Putty client I' using Putty client to connect to ssh server running on Virtualbox Linux machine. I'm trying to change the prompt color by setting the PS1 variable like so:
export PS1="\u@\h:\e[0;1m\w\$\e[m"

but it's apparently not working - the prompt is still the same color. When i type the command directly on my Virtualbox Linux machine it does work. Moreover i've noticed that also changing the TERM variable doesn't has an effect when running in Putty.

A: Try setting the terminal-type string prior to connecting.
Setting the "xterm-color" type lets bash (and others) know that your tty supports color.
You can also do some fun things with the environment variables... but that is another discussion for another day.

A: ... it looks like your color choices don't exist.
Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37

Perhaps you meant something more like this for red:
export PS1="\u@\h:\e[0;31m\w\$\e[00m"


text:
Q: Using isinstance() versus duck typing I'm writing an interface to matplotlib, which requires that lists of floats are treated as corresponding to a colour map, but other types of input are treated as specifying a particular colour.
To do this, I planned to use matplotlib.colors.colorConverter, which is an instance of a class that converts the other types of input to matplotlib RGBA colour tuples. However, it will also convert floats to a grayscale colour map. This conflicts with the existing functionality of the package I'm working on and I think that would be undesirable.
My question is: is it appropriate/Pythonic to use an isinstance() check prior to using colorConverter to make sure that I don't incorrectly handle lists of floats? Is there a better way that I haven't thought of?
I've read that I should generally code to an interface, but in this case, the interface has functionality that differs from what is required.

A: Why not write two separate functions, one that treats its input as a color map, and another that treats its input as a color?  This would be the simplest way to deal with the problem, and would both avoid surprises, and leave you room to expand functionality in the future.

A: It's a little subjective, but I'd say: in general it's a not a good idea, but here where you're distinguishing between a container and an instance of a class it is appropriate (especially when, say, those classes may themselves be iterable, like tuples or strings and doing it the duck-typing would get quite tricky).
Aside: coding to an interface is generally recommended, but it's far more applicable to the Java-style static languages than Python, where interfaces don't really exist, unless you count abstract base classes and the abc module etc. (much deeper discussion in What's the Python version for "Code against an interface, not an object"?)
Hard to say without more details, but it sounds like you're closer to building a facade here than anything, and as such you should be free to use your own (neater / tighter / different) API, insulating users from your underlying implementation (Matplotlib).


text:
Q: Starting a template with  tag in Sencha Touch I am confused as to why would one want to start the a template for dataview.List with a  tag. Is it because it is expected that Sencha architecture would have a  tag before it, and we want to compensate for that?

Ext.define("NotesApp.view.NotesList", {
    extend: "Ext.dataview.List",
    alias: "widget.noteslist",
    config: {
        loadingText: "Loading Notes...",
        emptyText: '

No notes found.

',
        onItemDisclosure: true,
        itemTpl: '

{title}

{narrative}

',
    }
});


text:
Q: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 6 column 17 path $.ErrMsgDtl Getting JsonSyntax Exception while parsing data from server. I checked my model class and server response. It looks good to me. Any idea how to resolve this issue? Error says expected string but was begin_object. Dont know where i am doing wrong.
Below is response from server
 {
        "Data": {
            "Transactions": [
                {
                    "Earns": [
                        {
                            "Description": "",
                            "EarnId": "46723912",
                            "Earned": 10000.0
                        }
                    ],
                    "Expires": "2021-12-31 00:00:00",
                    "Store": "QATes",
                    "StoreTrans": "107884927",
                    "TranDate": "2021-02-01 12:26:34"
                }
            ]
        },
        "Status": "SUCCESS",
        "ErrCde": null,
        "ErrMsg": null,
        "ErrMsgDtl": null
    }

Below is my Model class
class BonusSummaryDataResponse {
        @SerializedName("Transactions")
        var transactions: ArrayList<BonusTransData>? = null

        class BonusTransData {
            @SerializedName("Earns")
            var earns: ArrayList<BonusEarnsData>? = null

            @SerializedName("Expires")
            var expires: String? = null

            @SerializedName("Store")
            var store: String? = null

            @SerializedName("StoreTrans")
            var storeTrans: String? = null

            @SerializedName("TranDate")
            var tranDate: String? = null
        }

        class BonusEarnsData {
            @SerializedName("Description")
            var description: String? = null

            @SerializedName("EarnId")
            var earnId: String? = null

            @SerializedName("Earned")
            var earned: Double = 0.0
        }

}

ResponseWrapper

data class ResponseWrapper<T>(
        @SerializedName("Data")
        var data: T?,
        @SerializedName("Status")
        val status: String? = null,
        @SerializedName("ErrCde")
        val errorCode: String? = null,
        @SerializedName("ErrMsg")
        val errorMessage : String? = null,
        @SerializedName("ErrMsgDtl")
        val errorMessageDetail: String?= null)

Like below we are calling the function:
 @POST("services/abc/summary")
    fun getBonusCashSummary(@Body tBonusSummaryRequest: BonusSummaryRequest):
 Observable<ResponseWrapper<BonusSummaryDataResponse>>

Above ResponseWrapper is the generic class where we are passing BonusSummaryDataResponse data class.


text:
Q: Boxes and arrows connecting the steps in a solution? Can someone please help me how to achieve this kind of solutions in Latex?
Thank you for your time.
I have been using Latex for quite a while now in writing solutions for my math classes. I usually use color coding and other nice features. I recently came across some writings as shown in the picture. They are more elaborate and helps my students understand each and every step. I would like to implement this and I do not know where to begin. How do I draw boxes with connecting arrows to the steps?


text:
Q: How can I proof that all $\mu^*$ measurable set is a $\sigma$ algebra Hi according to wiki a $\mu^*$ measurable set satisfy $\forall A\subset X\rightarrow\mu^*(A)=\mu^*(A\cap S)+\mu^*(A\setminus S)$
I would like to prove that all set that is $\mu^*$ measurable is a $\sigma$ algebra of $X$
More specifically, I would like to prove if $S_1,S_2$ is $\mu^*$ measurable sets of $X$ then $\forall A\subset X\rightarrow\mu^*(A)=\mu^*(A\cap (S_1\cup S_2))+\mu^*(A/(S_1\cup S_2))$
Can anyone help me on that..... Thanks a lot


text:
Q: Do electric cars need friction brakes to stop really fast? If regenerative braking can't stop an electric car fast enough, can't we actively slow it down by applying a reversed voltage to the DC motor?
EDIT: By really fast, I mean in emergency situations where you are about to hit something or someone and want to stop as fast as possible.

A: reversing the voltage to the motor while it is running in the opposite direction is regenerative braking. And friction brakes are necessary in electric cars, both to hold them in position while parked and also to hold them in position when stopped on a slope.

A:
Do electric cars need friction brakes to stop really fast?

It depends on how fast you're already travelling. Regenerative braking is not as effective as conventional braking methods like friction-based braking at lower speeds. The efficiency of regenerative braking increases with increase in speed whereas it remains fairly constant for friction-based braking.
As you say, we can produce an opposite torque by reversing the polarity of the DC motor to bring it to a stop. But there is always a danger of burning the coils of the motor due to the high surge in the reverse current as the applied current reinforces the induced current. There must be some kind of electronic controllers to limit the current in the coils to prevent such events.
Friction-based braking is effective but it comes at the cost of rubbing mechanical parts which would need regular maintenance or replacement. Regenerative braking can store the energy in useful forms (which can be used later) other than simply dissipating it as heat.  I feel the good way to bring a moving electric car to rest is using more regenerative braking (and less friction-based braking) at higher speeds and more friction-based braking  (and less regenerative braking) at lower speeds.

A: Let me first go over some necessary background knowledge.
Today's cars have anti-lock braking. If the brakes do lock the wheels stops rolling, which gives significant loss of grip, in many cases catastrofic loss of grip.
About the amount of power that an electric propulsion system can bring to the wheels:
With a high-performance electric car, when the safety features are disabled, hitting the accelerator hard results in a burn-out. Of course, with standard settings the car will dutifully maintain traction control.
Presumably you can put a driving car in reverse and then send maximum power to the wheels. I assume that would result in the wheels spinning backwards, with catastrofic loss of grip.

How much power the battery pack can absorb
Generally the limiting factor to how hard you can brake using purely regenerative braking is how much power the battery pack can absorb. If the battery pack is very large, hence a large overall capacity, the power generated by the regenerative braking can be distributed over a comparatively large amount of battery cells.
If you exceed the rate of current that the battery pack can absorb then the battery suffers irreversible damage. Therefore when you make an electric car brake as hard as possible the regenerative braking is always supplemented with friction braking by the friction brakes.
Dependence on temperature
A cold battery pack has much less capacity to absorb current from regenerative braking. To absorb the power atoms must migrate through a fluid. The lower the temperature of that fluid the slower that migration rate.
For the batteries: the process of delivering power generates a bit of heat in the battery. Once the battery has reached optimum working temperature the battery management system starts maintaining that temperature.


text:
Q: Julia: How to obtain the types of every column of a DataFrame/Table? There must be an easy way to obtain the column types of every column of a DataFrame. Currently, I do
using DataFrames
a = DataFrame(a = [1,2,3], str = ["a","b","c"], f = [0.0, 1.0, 5.0])
[eltype(Array(col)) for col in eachcol(a)]

Is the best way? Appreciate more efficient and elegant solutions

A: You can broadcast eltype over the columns of the data frame:
df = DataFrame(
    x = [1, 2, 3],
    y = ["a", "b", "c"],
    z = [0.0, 1.0, 5.0]
)

julia> eltype.(eachcol(df))
3-element Array{DataType,1}:
 Int64
 String
 Float64

Note: Older versions of DataFrames.jl had an eltypes function, but it has been deprecated and removed from the package.


text:
Q: Как получить данные об авторизованном пользователе Yii в Websocket? Я использую https://github.com/walkor/Workerman
В связке с Yii2

Мне необходимо сделать следующее: чтобы на сервере можно было определить авторизован пользователь или нет и получить данные о нем, например логин, но... веб сокет запущен через консоль. а в кжонсоле пользователь не авторизован, он авторизован в web.
Как можно это реализовать ?
Передавать по сокету данные о пользователе(типа id) не вариант. И токен тоже, так как можно же его перехватить, и дальше использовать


text:
Q: Add headers to outgoing smtp message that will exist in reply I need to create a correlation between an outgoing e-mail to a reply e-mail without changing the subject or body.
I've tried to add some headers to an SMTP outgoing mail:
var outgoingMessage = new System.Net.Mail.MailMessage();
mail.Headers.Add("Tag","MyNewTag");
mail.Headers.Add("CorrelationID","MyNewCorrID");

Unfortunately, when replying to that email message - those headers are gone.
Is there any way to correlate between outgoing and incoming message without interfering subject or body ?

A: For the headers you should probably use X-headers instead:
mail.Headers.Add("X-Tag","MyNewTag");
mail.Headers.Add("X-CorrelationID","MyNewCorrID");

To correlate between outgoing and incoming message without interfering subject or body, you could also check the References: header (only with reply, not with forward).
This header contains the Message-ID('s) of the originating messages:
References: <some-id@domain>

There is also the In-Reply-To header.
To add more information you could even customize the outgoing Message-ID.
Maybe the Thread-Index header could be helpful too.


text:
Q: Session Hijacking Protection in ASP.NET I'd like to find out what session ID hijacking protection is built into the current version of ASP.NET.
I recently saw this very informative article that explains how session security can be enhanced by implementing an additional layer that encodes the IP address and user agent header into the session id.  These details are then verified on each subsequent request.
It seems that this article was written for ASP.NET 1.1 so I'd like to know if anything similar is now built into ASP.NET.  Is it still of any benefit to implement such an additional layer?
Thanks.

A: Check out this snippet from the Session Overview documentation:
System.Web.SessionState.HttpSessionState.SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious user could get access to the session of another user by obtaining the SessionID  value and including it in requests to the server. If you are storing sensitive information in session state, it is recommended that you use SSL to encrypt any communication between the browser and server that includes the SessionID  value.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
It seems to me that this means that there is no security baked into Session, so you probably shouldn't use Session as a security measure.  Instead, I would recommend relying on ASP.NET security (authentication, authorization).
Here is an article from the Patterns & Practices group on general security recommendations for ASP.NET.
http://msdn.microsoft.com/en-us/library/ff649100.aspx

A: Hey, I have also been looking for ways to reduce the risk of session ID hijacking. I read Jeff Prosise's article as well and I thought it could be useful; however, just like you, I was looking to see if the same approach applies for modern versions of the framework (his email wicked@microsoft.com doesn't work btw)
jkohlhepp, I don't agree with your post (or maybe I don't understand it):

you probably shouldn't use Session as a security measure. Instead, I would recommend relying on ASP.NET security (authentication, authorization)

As far as I'm concern asp.net authentication relies on Session IDs (except cookieless which seems to be worse: See Dino Esposito's opinion)
So, that pretty much put us where we started.


text:
Q: Confusion in Begin Tran and commit Tran As per my knowledge if we start statement with begin tran/ commit tran it will be completely done or nothing. But when I am executing below TSQL code it updates the record for first table n do nothing neither commit not rollback.I have also tried if @@error<> 0 but its also not working..Please help me out.
BEGIN TRAN

UPDATE A SET NAME ='ABC' WHERE ID=2

INSERT INTO TTT VALUES('GJ')

COMMIT TRAN

TABLE TTT DOES NOT EXIST.

I have used this table to throw an error in this block of code.

A: Your understanding is partially correct, partially incorrect.
A transaction remains open until it is committed or rolled back. You can commit or roll back manually (COMMIT or ROLLBACK), and there are some cases where transactions are rolled back automatically. You're not rolling back manually, and there isn't anything to force an automatic rollback on your particular system.
For code like yours, the SET XACT_ABORT ON option is useful: this causes errors to automatically roll back the current transaction.


text:
Q: Bitwise XOR operator not working in python I am trying to do this :
print 17593028247552 ^ 909522486
The result must be 67450422(as is in javascript) but I am getting 17592253494838L
Please help me ! Thanks in advance :)

A: Python 2's long type (or int in Python 3) can grow as large as they need to, but it looks like you want a 32 bit result.
You just need to mask the result so you only get the low 32 bits of the result. And I guess that since you're on Python 2 you should also convert it from long to int.
>>> int((17593028247552 ^ 909522486 ) & 0xffffffff)
67450422

A: I just used Windows calculator:
100000000000000110010001100110000000000000000  = 17593028247552d
000000000000000110110001101100011011000110110  =      909522486d
100000000000000000100000001010011011000110110  = 17592253494838d

Looks like JavaScript is wrong. It's probably narrowing to 32 bit or something before doing XOR. Python is arbitrary precision on integers.
Edit: As the other answer points out, if you're still using Python 2 (don't do that!) only long is arbitrary precision; the precision of int can vary but it's usually 64 bit. In Python 3 there is only one integer type and it's always arbitrary precision.


text:
Q: pickable objects disappearing (invisible) and reappearing on the world, how to fix? Sometimes, after I pickup or move some object like a book or a cup or anything, one other object near it will vanish (completely invisible) and when I move items again it reappear, it is usually only a single (any) object that disappear...
What can be causing that and how to fix it as it is very annoying?

A: It's normally glitched out since items are can actually float unless one of the items or taken or holded. This also occurs it it's appearance. I would recommend trying to take items instead of holding the items [if that doesn't work, take the item near it].

A: The problem with this in Skyrim is the physics engine itself, sometimes the items you place either do one of two things:

*

*De-spawn due to placement error whilst re-loading and implementing the game code (basically there's an original copy or code for each room and area, then there's a new copy based on what you alterd in the world, and sometimes the game gets confused and over-rides the new copy causing items to "disappear". It's an engine stability issue.)

*The game sometimes uses texture overlays instead of using physical barriers (it's easier) so the items don't actually "disappear", they fall through the maps visually perceived area. There are some mods for the PC that add more physical barriers under visual ones as a preventive measure. But other than that there is no resolve to this. It's something only the DEVs can fix.


text:
Q: DNS Not Resolving For All Users I recently transferred one of my domains to a new server, and ever since I am having intermittent issues accessing the site. taxiwayalpha.com does not work, www.taxiwayalpha.com occasionally works, and email also does not work.
Despite trying a couple of DNS testing utils online, it appears that the domain is not resolving to the server correctly.
A Whois check shows the following nameservers:
Primary Name Server Hostname: NS1.GAVINCOATES.COM
Secondary Name Server Hostname: NS2.GAVINCOATES.COM

The domain gavincoates.com is configured on the same server, and this website resolves fine.
The domain gavincoates.com is configured as follows with the registrar (simplynames.com)

Within plesk on the server, the configuration for gavincoates.com is as follows:

The hosting settings in Plesk for taxiwayalpha.com domain is as follows:

Thanks in advance.

A: First, check the .com servers:
% dig @a.gtld-servers.net. taxiwayalpha.com ns
...
;; AUTHORITY SECTION:
taxiwayalpha.com.   172800  IN  NS  ns1.gavincoates.com.
taxiwayalpha.com.   172800  IN  NS  ns2.gavincoates.com.
...
;; ADDITIONAL SECTION:
ns1.gavincoates.com.    172800  IN  A   69.65.102.34
ns2.gavincoates.com.    172800  IN  A   205.234.100.228

These appear to be the old server addresses?
Let's also check ns1.gavincoates.com.:
% dig @ns1.gavincoates.com. taxiwayalpha.com ns
...
;; ANSWER SECTION:
taxiwayalpha.com.   86400   IN  NS  ns.taxiwayalpha.com.
...
;; ADDITIONAL SECTION:
ns.taxiwayalpha.com.    86400   IN  A   212.67.209.138

Uh oh, we have a mismatch.  Your records at the .com registry are inconsistent both in name and in the glue records.
You need to have your domain updated with your registrar to use the right name (ns.taxiwayalpha.com. ) and because the NS is in its own zone you'll need to send them the right IP address for its glue record too.

A: One issue is that delegation to taxiwayalpha.com is set to ns1.gavincoates.com and ns2.gavincoates.com however querying the zone returns only ns.taxiwayalpha.com.
A second issue is that both ns1.gavincoates.com and ns2.gavincoates.com resolve to the same address. This is the same address that ns.taxiwayalpha.com resolves to.
$ host ns1.gavincoates.com.
ns1.gavincoates.com has address 212.67.209.138
$ host ns2.gavincoates.com.
ns2.gavincoates.com has address 212.67.209.138

I have performed a dig against your DNS server and it seems to respond with the records correctly:
; <<>> DiG 9.5.0-P2 <<>> @ns1.gavincoates.com. taxiwayalpha.com. any
; (1 server found)
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1716
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 10, AUTHORITY: 0, ADDITIONAL: 1

;; QUESTION SECTION:
;taxiwayalpha.com.              IN      ANY

;; ANSWER SECTION:
taxiwayalpha.com.       86400   IN      MX      20 alt1.aspmx.l.google.com.
taxiwayalpha.com.       86400   IN      MX      20 alt2.aspmx.l.google.com.
taxiwayalpha.com.       86400   IN      MX      30 aspmx2.googlemail.com.
taxiwayalpha.com.       86400   IN      MX      30 aspmx3.googlemail.com.
taxiwayalpha.com.       86400   IN      MX      30 aspmx4.googlemail.com.
taxiwayalpha.com.       86400   IN      MX      30 aspmx5.googlemail.com.
taxiwayalpha.com.       86400   IN      MX      10 aspmx.l.google.com.
taxiwayalpha.com.       86400   IN      SOA     ns.taxiwayalpha.com. contact.gavincoates.com. 1323190098 10800 3600 604800 10800
taxiwayalpha.com.       86400   IN      NS      ns.taxiwayalpha.com.
taxiwayalpha.com.       86400   IN      A       212.67.209.138

;; ADDITIONAL SECTION:
ns.taxiwayalpha.com.    86400   IN      A       212.67.209.138

;; Query time: 36 msec
;; SERVER: 212.67.209.138#53(212.67.209.138)
;; WHEN: Mon Dec 19 15:21:40 2011
;; MSG SIZE  rcvd: 315

Did you leave enough propagation time after changing server before running your tests?

A: Looks like your Nameservers are not responding correctly.
http://www.intodns.com/taxiwayalpha.com
Not the items in red. These will typically result in odd DNS behavor.
Appears your nameservers are not returning NS records for your domain.  You need to have NS records for your domain.


text:
Q: JAX-RS Request specific media type Lets say I have the following REST method:
@GET
@Path("get/{id}")
@Produces({"application/json", "application/xml"})
public Entity getEntity(@PathParam("id") int id) {
    //do stuff
    Entity entity = find(id);
    return entity;
}

When I hit the rest endpoint with any browser by default I get back XML. Is there a way I can specify at the request which media type I want returned? or must I somehow include that information in the path?

A: You have to specify the Accept header with the media type you want in addition to the Content-Type header that states what is the content type of your request.
So use the Accept header instead of Content-Type header:
Accept: application/xml

A: You should manually prepare your response. For example if you want JSON answer, you should convert your Entity class to Json and return String.
You can use https://code.google.com/p/google-gson/ for conversion.
In fact it is your decision and your work to prepare the answer. The only thing to take in consideration that Rest works on top of HTTP, so some sort of text(JSON, XML, Plain  text) is the most "friendly" format of information.

A: May be this example can help
RestClientWithAcceptHeader
RestClient client = new RestClient();
    ClientResponse response = client.resource("http://example.com/resources/resource1").header("Accept", "application/json;q=1.0, application/xml;q=0.8").get();
    // find what format was sent back
    String contentType = response.getHeaders().getFirst("Content-Type");

    if (contentType.contains("application/json")) {
        JSONObject entity = response.getEntity(JSONObject.class); /* or use a String, InputStream, or other provider that supports the entity media type */
    } else if (contentType.contains("application/xml") {
        String entity = response.getEntity(String.class); /* or use a JAXB class, InputStream, etc. */

More here  and here


text:
Q: Como somar dois arrays de inteiros com aritmética de ponteiro? Estou fazendo um exercício em que passo por parâmetro dois arrays de inteiros já definidos pelo usuário. Preciso agora, em um terceiro array, armazenar a soma dos dois arrays recebidos, nas mesmas posições, utilizando aritmética de ponteiro.
Ex:
vet 1 [1,2,3]
vet 2 [1,2,3]

Aqui no terceiro vetor tenho que receber a soma utilizando aritmética de ponteiro.
vet 3 [2,4,6]

Minha tentativa:
#include <stdio.h>
#define MAX 100
int soma_ponteiro(int *vet1,int *vet2,int num);
int main(){

    int vet1[MAX],vet2[MAX];
    int num,i;

    printf("Digite qtd de numeros:\n");
    scanf("%d",&num);

    for(i=0;i<num;i++){
        printf("\nDigite numero %d vetor 1\n",i+1);
        scanf("%d",&vet1[i]);
        printf("\nDigite numero %d vetor 2\n",i+1);
        scanf("%d",&vet2[i]);
    }

    soma_ponteiro(vet1,vet2,num);
    printf("\n%d",soma_ponteiro(vet1,vet2,num));

    return 0;
}
int soma_ponteiro(int *vet1,int *vet2,int num){
    int vet3[MAX];
    int *last_pos=vet1+num;
    int *ptr = vet1;
    int *ptr2= vet2;
    int *ptr3= vet3;

    while(ptr<last_pos){
        *ptr3 = *vet1+*vet2;
    ptr++;
    }
    return ptr3;
}

A: Veja se é isto o que deseja:
int vet1[3]={1, 2, 3}, vet2[3]={1, 2, 3}, vet3[3], *p1, *p2, *p3, i;
p1 = vet1;
p2 = vet2;
p3 = vet3;
for (i=0; i<3; i++) {
    *p3 = *p1 + *p2;
    p1++;
    p2++;
    p3++;
}
for (i=0; i<3;i++)
    printf("\tvet3[%d] = %d", i, vet3[i]);

A: Para conseguir fazer operações entre dois vectores numa função tem que cumprir estas "regras":

*

*Passar os vectores por parâmetro

*Passar a dimensão dos vectores por parâmetro

Depois disso é só percorrer o vector num ciclo, pode usar um contador i, e usar o array sem ponteiros, desta forma: vector[i] = 1 + 2; ou então *(vector + i) = 1 + 2


text:
Q: Form in jQuery UI Dialog Cached. I'm a C/C++ programmer and new to javascript. The following code is giving me grief and I don't really know what I'm doing wrong. I've searched and can't find where others have had the same problem.
I've taken my project and cut out my problem code to try and understand and fix it. The short version is when I click my "Enter data" image on an HTML page, it creates a dialog box with a form and table of inputs (with default data) and I enter/change some data. When I click the dialog box save button, it goes through JSON.stringify($('#form').jsonify()) to collect the form data and brings up an alert box showing the data that I entered. This part works fine.
If I click the "Enter data" image again, the dialog box comes up and I enter/change new data. When I click the dialog box save button, it brings up an alert box showing the previous data that I saved (in this case showed in the alert box).
No matter how many times I try it, it always returns the data form the very first entry and never any of the new(er) data.
What am I doing wrong?
Some references:

<link href="~/Content/jquery/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" />

My HTML code

My test.js file.
$.fn.jsonify = function (options) {
    var settings = $.extend({
        stringify: false
    }, options);
    var json = {};
    $.each(this.serializeArray(), function () {
        if (json[this.name]) {
            if (!json[this.name].push)
                json[this.name] = [json[this.name]];
            json[this.name].push(this.value || '');
        } else
            json[this.name] = this.value || '';
    });
    if (settings.stringify)
        return JSON.stringify(json);
    else
        return json;
}

function addstuff(obj) {
    var strHtml = "";
    var strHtml = "
"
                     + "
Please enter the following information.
"
                     + "<form id=\"form\">
"

                     + "
" + "Data 1" + ":	"
                     + "<input type=\"text\" name=\"" + "data1" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 1 data" + "\" />" + "
"
                     + "
" + "Data 2" + ":	"
                     + "<input type=\"text\" name=\"" + "data2" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 2 data" + "\" />" + "
"
                     + "
" + "Data 3" + ":	"
                     + "<input type=\"text\" name=\"" + "data3" + "\" style=\"border:0; color:#f6931f; font-weight:bold; align=right;\" VALUE=\"" + "Data 3 data" + "\" />" + "
"

                     + "
</form>"
                     + "
";

    $(strHtml).dialog({
        autoOpen: false,
        width: 400,
        modal: true,
        buttons: {
            "Save": function () {
                alert("Add information " + JSON.stringify($('#form').jsonify()));
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        open: function () {
            $(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
        }
    }).dialog('open');
}

A: This seems to be a known problem of forms in ui dialogs being cached. But you need to remove the form onClose of the dialog.
I added close event function to your code. You should be fine now.
    $(strHtml).dialog({
        autoOpen: false,
        width: 400,
        modal: true,
        close: function( event, ui ) {
            $('#form').remove(); // this where the problem is
        },
        buttons: {
            Save: function () {
                alert("Add information " + JSON.stringify($('#form1').jsonify()));
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        open: function () {
            $(this).siblings('.ui-dialog-buttonpane').find("button:contains('Cancel')").focus();
        }
    }).dialog('open');
}


text:
Q: How to calculate the amplitude of a matter wave of debroglie equation? I studied the formula that to calculate the wavelength of a matter wave we have to calculate $h/p$ where $h$ is plancks constant and $p$ is the momentum of the particle for which we want to calculate the wave length
wikipedia-link: https://en.wikipedia.org/wiki/Matter_wave. And I am wondering how to calculate the amplitude of that wave.

A:
And I am wondering how to calculate the amplitude of that wave.

You are essentially asking how to calculate the wave
function $\Psi(\vec{r},t)$ of a particle.
Based on de Broglie's hypotheses ($\vec{p}=\hbar\vec{k}$
and $E=\hbar\omega$) Schrödinger found the equation
$$i\hbar\frac{\partial}{\partial t}\Psi(\vec{r},t)
=\left(-\frac{\hbar^2}{2m}\vec{\nabla}^2+V(\vec{r})\right)\Psi(\vec{r},t)$$
where $m$ is the mass of the particle and $V(\vec{r})$ is its
potential energy at position $\vec{r}$.
Although Schrödinger's equation was a speculation (guided by
de Broglie's speculation), it turned out to be a direct hit.
It correctly predicts the facts experimentally found.
You can find the wave function $\Psi(\vec{r},t)$
by solving this differential equation.
Some examples:

*

*A single electron flying through a double slit.
Here we have
$$V(\vec{r})=\begin{cases}
  0, &\text{ in free space} \\
  +V_0, &\text{ within the walls}
  \end{cases}$$

*The hydrogen atom (a single electron in the electrical field
of the atomic nucleus).
Here we have $$V(\vec{r})=-\frac{e^2}{4\pi\epsilon_0 r}.$$
Then the interpreation of the wave function is that
$|\Psi(\vec{r},t)|^2 d^3r$ gives the probability
of finding the particle within a volume element $d^3r$
at position $\vec{r}$.

A: As far as I know, in de Broglie's theory the amplitude was just not considered at all. Later, when quantum mechanics has been developed and made formal, particles have been described by wavefunctions $\psi$. Their amplitude is fixed such that the total probability of finding the particle anywhere is
$$\int |\psi(\vec x)|^2 d^3 x=1$$


text:
Q: Sending arraylist to another activity in android i have set of values in android listview. when i click submit button i want to get whole list in another activity. i tried with intent.putExtra(); but i am getting following error .
java.lang.RuntimeException: Parcel: unable to marshal value com.example.technical14.recyclers.Planet@4011368

My Code is -
proceed.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        ArrayList<Planet> apl = planetsList;
        Intent intent = new Intent(MainActivity.this, Proceed.class);
        intent.putExtra("QuestionListExtra", apl);

        startActivity(intent);
    }
});

i am new to the android. so please help me on this.

A: Make Planet Parcelable using http://parcelabler.com/
and then send using
intent.putExtra("QuestionListExtra", apl);

and in Proceed activity
ArrayList<Planet> list = getIntent().getParcelableArrayListExtra("QuestionListExtra");

A: Find the solution

*

*Your model class should be implements Parcelable :
 public class Planet implements Parcelable {

// Your setter and getter methods
 }

*Put your arralist to putExtra() :
ArrayList<Planet> contactList = // planets data;
Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", contactList);
startActivity(intent);

3.In second Activity:
    ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");


text:
Q: How to draw this tree of extensive game model? How is it possible to draw this figure?

There are some posts on how to draw a tree of an extensive game model, but I don't know how to modify them such that the following figure is produced.
Nth Problem with TikZ and Extensive Form Games
Game theory trees, solid node size

A: Here is my attempt:
\documentclass[border=0.2cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture}[thick, node distance=3cm,on grid,
    Rec/.style = {
        draw,
        minimum size = 1cm,
        outer sep=0},
    Circ/.style= {
        draw,
        circle,
        minimum size=1cm}]
 % Rectangles and circle
 \node[Rec,fill=gray] (rec1) {};
 \node[Rec,right=of rec1] (rec2) {};
 \node[Circ,right=of rec2] (circle) {};
 \node[Rec,above right=2cm and 3cm of circle] (rec3) {};
 \node[Rec,below right=2cm and 3cm of circle] (rec4) {};

% Directed lines
    \draw[-latex] (rec1) -- (rec2) edge node[above left](Nbuy){Buy}(circle);
    \draw[-latex] (circle) |- (rec3) node[pos=0.71,above]{Match}node[pos=0.71,below]{$m$}   (circle) |- (rec4) node[pos=0.71,below]{Mismatch}node[pos=0.71,above]{$1-m$} ;

    \draw (rec3) |- ++(2,1) node[pos=0.71,above]{Keep} node[right]{$v-P$} (rec3) |- ++(2,-1)node[pos=0.75,below]{Return}  node[right]{$v-h$};

\draw (rec4) |- ++(2,1) node[pos=0.71,above]{Keep}  node[right]{$s-P$}(rec4) |- ++(2,-1)node[pos=0.75,below]{Return} node[right]{$-h$};

\draw (rec2) |- ++(8,-4) coordinate(Nnbuy)node[right]{$0$} ;
\node[above] at (Nbuy|-Nnbuy) {Don't buy} ;

 \node[below right,align=left,inner xsep=0,inner ysep=5pt]at (rec1.south west){Retailer \\ announces \\ $P$ and $T$};
 % Red dashed lines
 \draw[dashed,red] (2,4) -- (2,-5)(5,4) -- (5,-5)(10.75,4) -- (10.75,-5);

 % Top and bottom labels
 \node at (0.75,-4.75){\textbf{Retailer}};
 \node at (3.5,-4.75){\textbf{Consumer}};
 \node at (7.875,-4.75){\textbf{Consumer}};
 \node at (0.75,3.75){\textbf{Stage I}};
 \node at (3.5,3.75){\textbf{Stage II}};
 \node at (7.875,3.75){\textbf{Stage III}};
 \node at (11.5,3.75){\textbf{Utility}};
\end{tikzpicture}

\end{document}

Which yields the following result:

You can check this tutorial about drawing block diagrams .

A: A solution that uses child nodes.
\documentclass[tikz,border=3.14159cm]{standalone}
\usetikzlibrary{arrows.meta,positioning}

\begin{document}

\begin{tikzpicture}
    [grow=right, scale=1.,font=\normalsize,
    edge from parent path={(\tikzparentnode) |- (\tikzchildnode.west)},
    edge from parent/.style={draw,-{Stealth[scale=2]}},
    level distance=3cm,
    sibling distance=3cm,
    level 4/.style={sibling distance=1.5cm},
    auto,transform shape,
    on grid]

    \tikzset{every node/.style={rectangle,minimum width=1cm,minimum height=1cm,draw}}
    \tikzset{edgenode/.style={draw=none,minimum height=0pt,rectangle,inner sep=3pt,pos=.75}}
    \tikzset{legend/.style={draw=none,minimum height=0pt,rectangle,inner sep=3pt}}

    \node[fill=gray](retailer) {}
        child { node (consumer){}
            child { node[circle,fill=white] { }
                child { node {}
                    child { node[draw=none] {$-h$}
                    edge from parent node[edgenode,below] {Return}}
                    child { node[draw=none] {$s-P$}
                    edge from parent node[edgenode,above] {Keep}}
                edge from parent node[edgenode,below] {Mismatch} node[edgenode,above] {$1-m$}}
                child { node {}
                    child { node[draw=none] {$\nu c-h$}
                    edge from parent node[edgenode,below] {Return}}
                    child { node[draw=none] {$\nu-P$}
                    edge from parent node[edgenode,above] {Keep}}
                edge from parent node[edgenode,above] {Match} node[edgenode,below] {$m$}}
            edge from parent node[edgenode,above] {Buy}}
        };

    \draw[edge from parent] (consumer) --++ (0,-4) --++ (8.5,0) node[edgenode,pos=.12,above] {Don't buy} node[anchor=west,draw=none,at end] {0};
    \draw[dashed]   (2,4) --++ (0,-9)
                    (5,4) --++ (0,-9)
                    (11,4) --++ (0,-9);
    \node[legend] at (0,-4.5) {Retailer};
    \node[legend] at (3.5,-4.5) {Consumer};
    \node[legend] at (8,-4.5) {Consumer};
    \node[legend] at (0,3.5) {Stage I};
    \node[legend] at (3.5,3.5) {Stage II};
    \node[legend] at (8,3.5) {Stage III};
    \node[legend] at (12,3.5) {Utility};
    \node[legend,text width=2cm,align=center] at (0,-1.3) {Retailer announces P and T};
\end{tikzpicture}
\end{document}

EDIT
I edit my post without deleting the first version. Here's an improved version without the flaws of the first rapid script.
\documentclass[tikz,border=3.14159mm]{standalone}
\usetikzlibrary{arrows.meta,positioning}

\begin{document}

\begin{tikzpicture}
    [line width=.5pt,
    grow=right, scale=1.,font=\normalsize,
    edge from parent path={(\tikzparentnode) |- (\tikzchildnode.west)},
    edge from parent/.style={draw,-{Stealth[scale=1.5]}},
    level distance=3cm,
    sibling distance=3cm,
    level 4/.style={sibling distance=1.5cm},
    auto,transform shape,
    on grid]

    \tikzset{every node/.style={rectangle,minimum width=1cm,minimum height=1cm,draw}}
    \tikzset{edgenode/.style={draw=none,minimum height=0pt,rectangle,inner sep=3pt,pos=.75}}
    \tikzset{legend/.style={draw=none,minimum height=0pt,rectangle,inner sep=3pt}}

    \node[fill=gray](retailer) {}
        child { node (consumer){}
            %
            child { node[circle] { }
            %
                child { node {}
                    %
                    child { node[draw=none] {$-h$}
                    edge from parent[-] node[edgenode,below] {Return}}
                    %
                    child { node[draw=none] {$s-P$}
                    edge from parent[-] node[edgenode,above] {Keep}}
                    %
                edge from parent node[edgenode,below] {Mismatch} node[edgenode,above] {$1-m$}}
                child { node {}
                    %
                    child { node[draw=none] {$\nu c-h$}
                    edge from parent[-] node[edgenode,below] {Return}}
                    %
                    child { node[draw=none] {$\nu-P$}
                    edge from parent[-] node[edgenode,above] {Keep}}
                    %
                edge from parent node[edgenode,above] {Match} node[edgenode,below] {$m$}}                   %
            edge from parent node[edgenode,above] {Buy}}
        };

    \draw (consumer) |- (11.5,-4) node[edgenode,pos=.56,above] {Don't buy} node[anchor=west,draw=none,at end] {0};

    \draw[dashed]   (2,4) --++ (0,-9)
                    (5,4) --++ (0,-9)
                    (11,4) --++ (0,-9);

    \node[legend] at (0,-4.5) {Retailer};
    \node[legend] at (3.5,-4.5) {Consumer};
    \node[legend] at (8,-4.5) {Consumer};
    \node[legend] at (0,3.5) {Stage I};
    \node[legend] at (3.5,3.5) {Stage II};
    \node[legend] at (8,3.5) {Stage III};
    \node[legend] at (12,3.5) {Utility};
    \node[below = 1.2cm of retailer,legend,text width=2cm,align=center] {Retailer announces P and T};
\end{tikzpicture}
\end{document}

A: This is my try of drawing the figure using the istgame package.

\documentclass[tikz]{standalone}

\usepackage{istgame}
\usepackage{makecell}

\begin{document}

\begin{istgame}[edge from parent path={(\tikzparentnode) |- (\tikzchildnode.west)}]

\setistgrowdirection'{east}
\setistmathTF001
\setxtarrowtips{latex}[very thick]

\setistNewNodeStyle{init}[rectangle,fill=gray]{1cm}
\setistNewNodeStyle{rect}[rectangle]{1cm}
\setistNewNodeStyle{circ}{1cm}

\tikzset{RR/.style={edge from parent path={(\tikzparentnode.east)--(\tikzchildnode.west)}}} % (added)

\xtdistance{25mm}{30mm}
\istroot(0)[init]<[xshift=3mm]-90>{\makecell[l]{Retailer\\announces\\$P$ and $T$}}
  \istb<RR>[->-=.75]
  \endist
\istrooto(1)(0-1)[rect]
  \istb<grow=0,RR>[->-=.75]{Buy}[above,pos=.3]
  \istb<sibling distance=60mm,level distance=65mm>{Don't buy}[above,pos=.57]{0}
  \endist
\xtdistance{25mm}{30mm}
\istrooto(2)(1-1)[circ]
  \istB[->-=.93]{Match}[above,pos=.72]{$m$}[below,pos=.72]
  \istB[->-=.93]{Mismatch}[below,pos=.72]{$1-m$}[above,pos=.72]
  \endist
\xtdistance{15mm}{15mm}
\istrooto(3a)(2-1)[rect]
  \istb{Keep}[above,pos=.75]{v-P}
  \istb{Return}[below,pos=.75]{vc-h}
  \endist
\istrooto(3b)(2-2)[rect]
  \istb{Keep}[above,pos=.75]{s-P}
  \istb{Return}[below,pos=.75]{-h}
  \endist

\xtTimeLineV[dashed]([xshift=-7mm]1){3.5}{-4}{Stage I}[left=5mm]
\xtTimeLineV[dashed]([xshift=-7mm]2){3.5}{-4}{Stage II}[left=5mm]
\xtTimeLineV[dashed]([xshift=-1.5mm]3a-1){3.5}{-4}{Stage III}[left=15mm]
\xtTimeLineV[draw=none]([xshift=-1.5mm]3a-1){3.5}{-4}{\underline{Utility}}[right=2mm]
\xtTimeLineV'[draw=none]([xshift=-7mm]1){3.5}{-4}{Retailer}[left=5mm]
\xtTimeLineV'[draw=none]([xshift=-7mm]2){3.5}{-4}{Consumer}[left=5mm]
\xtTimeLineV'[draw=none]([xshift=-1.5mm]3a-1){3.5}{-4}{Consumer}[left=15mm]

\end{istgame}

\end{document}


text:
Q: How do I check if a tokenizer/model is already saved I am using HuggingFace Transformers with PyTorch. My modus operandi is to download a pre-trained model and save it in a local project folder.
While doing so, I can see that .bin file is saved locally, which stands for the model. However, I am also downloading and saving a tokenizer, for which I cannot see any associated file.
So, how do I check if a tokenizer is saved locally before downloading? Secondly, apart from the usual os.path.isfile(...) check, is there any other better way to prioritize local copy usage from a given location before downloading?

A: I've used this code in the past for this purpose. You can adapt it to your setting.
from tokenizers import BertWordPieceTokenizer
import urllib
from transformers import AutoTokenizer

def download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=False):
    vocab_files_map = tokenizer.pretrained_vocab_files_map
    vocab_files = {}
    for resource in vocab_files_map.keys():
        download_location = vocab_files_map[resource][model_type]
        f_path = os.path.join(output_path, os.path.basename(download_location))
        if vocab_exist_bool != True:
            urllib.request.urlretrieve(download_location, f_path)
        vocab_files[resource] = f_path
    return vocab_files

model_type = 'bert-base-uncased'
#initialized tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_type)
#will do this part later

#retrieve vocab file if it's not there
output_path = os.getcwd()+'/vocab_files/'
vocab_file_name = 'bert-base-uncased-vocab.txt'
vocab_exist_bool = os.path.exists(output_path + vocab_file_name)

#get vocab files
vocab_files = download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=vocab_exist_bool)


text:
Q: Greedy Scheduling in Multi-threading programming in cilk I am having problem understanding the complete step and incomplete step in greedy scheduling in Multi-threaded programing in cilk.
Here is the power-point presentation for reference.
Cilk ++ Multi-threaded Programming
The problem I have understanding is in from slide # 32 - 37.
Can someone please explain especially the how is
Complete step>=P threads ready to run
incomplete steps < p threads ready

Thanks for your time and help

A: First, note that "threads" mentioned in the slides are not like OS threads as one may think. Their definition of a thread is given at slide 10: "a maximal sequence of instructions not containing parallel control (spawn, sync, return)". To avoid further confusion, let me call it a task instead.
On slides 32-35, a circle represents a task ("thread"), and edges represent dependencies between tasks. And the sentences you ask about are in fact definitions: when P or more tasks are ready to run (and so all P processors can be busy doing some work) the situation is called a complete step, while if less than P tasks are ready, the situation is called an incomplete step. To simplify the analysis, it is (implicitly) assumed that all tasks contain equal work (of size 1).
Then the theorem on the slide 35 provides an upper bound of time required for a greedy scheduler to run a program. Since all the execution is a sequence of complete and incomplete steps, the execution time is the sum of all steps. Since each complete step performs exactly P work, the number of complete steps cannot be bigger than T1 (total work) divided by P. Then, each incomplete step must execute a task belonging to the critical path (because at every step at least one critical path task must be ready, and incomplete steps execute all ready tasks); so the overall number of incomplete steps does not exceed the span T_inf (critical path length). Thus the sum of T1/P and T_inf gives an upper bound on execution time.
The rest of slides in the "Scheduling Theory" section are rather straightforward.


text:
Q: ZipTransformer compress a list of files My goal is to create multiple zip files, each containing a certain number of entries. I am using an Aggregator for grouping files before transofrmation.
Is it possible to use a ZipTransformer to compress a Message<List<File>>?
EDIT:
I am getting circular dependency exception when declaring ZipConverter as a bean. What can be a solution?
EDIT 2 The problem with circular dependency is solved by removing @Bean annotation from the @Transformer, and providing current ApplicationContext to zipTransformer.setBeanFactory(appContext)

A: According ZipTransformer source code that is exactly what you have to do - send a message with List<File>:
protected Object doZipTransform(Message<?> message) throws Exception {
   ...
   if (payload instanceof Iterable<?>) {
        ...

        for (Object item : (Iterable<?>) payload) {

            final ZipEntrySource zipEntrySource = createZipEntrySource(item, lastModifiedDate, baseName + "_"
                    + counter + fileExtension, this.useFileAttributes);
            ...
        }
   }

...
private ZipEntrySource createZipEntrySource(Object item,
        Date lastModifiedDate, String zipEntryName, boolean useFileAttributes) {

    if (item instanceof File) {
        final File filePayload = (File) item;

        final String fileName = useFileAttributes ? filePayload.getName() : zipEntryName;

        if (((File) item).isDirectory()) {
            throw new UnsupportedOperationException("Zipping of directories is not supported.");
        }

        return new FileSource(fileName, filePayload);

}

There is a test class in the project to confirm that: https://github.com/spring-projects/spring-integration-extensions/blob/master/spring-integration-zip/src/test/java/org/springframework/integration/zip/transformer/ZipTransformerTests.java


text:
Q: Error when trying to call data from a JSON file in Google Maps I'm trying to open Google Maps with data coming from a JSON file. I made the code and the map is working correctly. But there's a mistake that I cannot solve.
Below is the code with the link to the example.
Where am I going wrong? I can not locate the error and fix it.

$(document).ready(function() {
    $.ajax({
        url: 'dados.json',
        dataType: 'json',
        type: 'get',
        cache: false,
        success: function(data){
            $(data).each(function(index, value) {});
                meuMapa(data);
        }
    });
        function meuMapa(data){
            var map = new google.maps.Map(document.getElementById('mapa'),{
                center: new google.maps.LatLng(-23.6124627,-46.7972198),
                zoom: 15,
                zoomControl: true,
                zoomControlOptions:{
                    style:google.maps.ZoomControlStyle.SMALL,
                    position:google.maps.ControlPosition.RIGHT_BOTTOM
                    },
                mapTypeId:google.maps.MapTypeId.ROADMAP
            });
            for (i=0; i<data.imoveis.length; i++){
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(data.imoveis[i].latitude, data.imoveis[i].longitude),
                        map: map,
                        icon: ''
                    });
                }
        }
        meuMapa();
});

Link to example that displays an error in the console.

A: You have two places in your code where you're calling meuMapa: once in the success handler:
success: function(data) {
  $(data).each(function(index, value) {});
  meuMapa(data);
}

and once at the bottom of your $(document).ready(function() {:
  meuMapa();
});

But meuMapa depends on its argument, data, being defined and having an imoveis property:
function meuMapa(data) {
  // ...
  for (i = 0; i < data.imoveis.length; i++) {

If the function is not provided an argument, the above will throw an error. Because the map is working already, just remove the superfluous meuMapa(); call from the bottom.
It would also probably be beneficial not to implicitly create a global variable named i, as well: change your
for (i=0;

to
for (let i=0;

or use forEach instead.


text:
Q: Random num in a label-iPhone What am I doing wrong here? I'm not getting the randomNum value displayed when I run in simulator.. (I've already linked everything in IB). (Edit: Actually the program just crashes now)
.m file:

randomNum=arc4random() % 100;
randomNumLabel.text=randomNum;

.h file:
int randomNum;
int guess;
IBOutlet UITextField *numberField;
IBOutlet UILabel *randomNumLabel;

A: You'll need to convert the number to a string by using NSString's stringWithFormat: method.
randomNumLabel.text = [NSString stringWithFormat:@"%i", randomNum];


text:
Q: Flask-Restless order_by related model I have these two models (defined using Flask-SQLAlchemy):
class BankAccount(db.Model):
    id            = db.Column(db.Integer, primary_key=True)
    customer_id   = db.Column(db.Integer, db.ForeignKey('customer.id'))
    created_at    = db.Column(db.DateTime)

class Customer(db.Model):
    id            = db.Column(db.Integer, primary_key=True)
    name          = db.Column(db.String(128), index=True)

I have no issues using Flask-Restless API endpoint for BankAccount with the following query parameters:
http://mywebsite.com/api/bank_account?q={"order_by":[{"field":"created_at","direction":"asc"}]}

However, I'd like to order these results (bank accounts) by customer name -- and Customer is a related model, so there is no such field as customer_name in the BankAccount model.
Is there any easy way to have this ordering work? In some known Python ORMs, this would be achieved by using a "double underscore", something like:
http://mywebsite.com/api/bank_account?q={"order_by":[{"field":"customer__name","direction":"asc"}]}

I have also tried:
{"field":"Customer","direction":"asc"}
{"field":"customer","direction":"asc"}
{"field":"customer.name","direction":"asc"}

For all these attempts, I get this response:
{
  "message" : "Unable to construct query"
}

Any ideas of how to make this query? Or is this simply not possible using Flask-Restless? Thanks!

A: Your best bet is probably to use a post processor:
https://flask-restless.readthedocs.org/en/latest/customizing.html?highlight=order#request-preprocessors-and-postprocessors


text:
Q: Continuity of a random variable and of its cumulative distribution function Could you help me to understand if the following statements are correct?
Let $X$ be a random variable with cdf $F$ (so $F$ is, by definition, non-decreasing, right continuous, $\lim_{x\rightarrow-\infty}F(x)=0$, $\lim_{x\rightarrow\infty}F(x)=1$)
1) $X$ is a continuous random variable if and only if $F$ is a continuous functions
2) $F$ is a continuous function strictly monotone (increasing) if and only if $F^{-1}$ exists
3) $X$ is a continuous random variable and $F$ strictly monotone function (increasing) if and only if $F^{-1}$ exists

A: The first statement: $\implies$: $X$ being a continuous random variable means that it has a density. Just write $F$ as an integral of this density to see that $F$ is continuous. $\impliedby$: If $F$ is continuous, then it is absolutely continuous with respect to the Lebesgue measure so then by the Radon-Nikodyn theorem $X$ has a density.
The second statement: This has nothing to do with probability. $\implies$ is obvious I hope. For $\impliedby$ note that $F$ has an inverse if and only if it is bijective. Since $F$ is nondecreasing, it must be strictly increasing. A strictly increasing (or decreasing) bijective function has to be continuous. See this for a proof.
The third statement is just the first two combined.

A: I saw the accepted answer has an error in it (and I don't have enough reputation to comment on that), so I'll note the following.
Statement 1) is false -- usually "$X$ is a continuous random variable" means "there is an integrable function $f$ (called the density of $X$) such that $\mathbb{P}(X \leq t) = \int_{-\infty}^t f(x)\,dx$". Since $f$ is integrable, this expression (which gives the cdf) is continuous. But the converse need not be true. The Cantor function is the classic example of a continuous cdf which is not absolutely continuous (i.e. cannot be expressed as a cumulative integral of some other function).
Statement 3) is false for basically the same reason as statement 1) is; there are continuous and strictly increasing (i.e. invertible) cdfs  which are not absolutely continuous -- for an explicit example, take the sum of any continuous and strictly increasing cdf (say, that of the normal distribution, for example) and the Cantor function, and divide by 2 (this is just a trick to get a variant of the Cantor function which is strictly increasing).


text:
Q: JS function to update captcha image I don't know why but my function to reload an image don't work on prod, but on dev, it's fine.
Url: http://www.gifolio.com/user/register
Click on the link "Unable to read captcha? Click here !"
The image stay the same... But on my dev, it updates fine.
Any idea?

A: Add a cache-buster to the URL to prevent caching:
function reloadCaptcha() {
    jQuery('#captcha_img').attr('src', '/user/generate_captcha?cb='+(new Date().getTime()));
}

A: When you change the src of the image, the browser does not get the new image because the URL is the same. To fix, you need to make sure that the URL is unique. In your reloadCaptcha function, set change the line to this:
jQuery('#captcha_img').attr('src', '/user/generate_captcha?' + Date.now());

Notice the change to the end of the URL. That way the browser always thinks it's getting a new image and it'll work as expected.


text:
Q: Need a very simple example for parsing and writing XML docs in C or in C++ I work on a C project and need to implement some interactions with XML files.
I need a very simple example for parsing and for writing an XML file.
I really prefer a small library (like one .h file and one .c file), and not a library that requires installation
I'll be very glad if someone can show me:

*

*how to parse the data in the following example

*how to generate the data in the following example

XML data:
<root>
    <source name = 'source1' isReadOnly = 'false'>
        <view name = 'view1' />
        <view name = 'view2' />
    </source>
    <source name = 'source2' isReadOnly = 'true'>
        <view name = 'view1' />
        <view name = 'view2' />
    </source>
</root>

A: There are many articles regarding this on internet. Assuming you are on windows find below example for your reference:-
<?xml version="1.0" encoding="UTF-8"?>
<Car>
    <Wheels>
        <Wheel1>FL</Wheel1>
        <Wheel2>FR</Wheel2>
        <Wheel3>RL</Wheel3>
        <Wheel4>RR</Wheel4>
    </Wheels>
</Car>

Below is the code :-
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#import <msxml6.dll> rename_namespace(_T("MSXML"))

int main(int argc, char* argv[])
{
    HRESULT hr = CoInitialize(NULL);
    if (SUCCEEDED(hr))
    {
        try
        {
            MSXML::IXMLDOMDocument2Ptr xmlDoc;
            hr = xmlDoc.CreateInstance(__uuidof(MSXML::DOMDocument60), NULL, CLSCTX_INPROC_SERVER);
            // TODO: if (FAILED(hr))...

            if (xmlDoc->load(_T("input.xml")) != VARIANT_TRUE)
            {
                printf("Unable to load input.xml\n");
            }
            else
            {
                printf("XML was successfully loaded\n");

                xmlDoc->setProperty("SelectionLanguage", "XPath");
                MSXML::IXMLDOMNodeListPtr wheels = xmlDoc->selectNodes("/Car/Wheels/*");
                printf("Car has %u wheels\n", wheels->Getlength());

                MSXML::IXMLDOMNodePtr node;
                node = xmlDoc->createNode(MSXML::NODE_ELEMENT, _T("Engine"), _T(""));
                node->text = _T("Engine 1.0");
                xmlDoc->documentElement->appendChild(node);
                hr = xmlDoc->save(_T("output.xml"));
                if (SUCCEEDED(hr))
                    printf("output.xml successfully saved\n");
            }
        }
        catch (_com_error &e)
        {
            printf("ERROR: %ws\n", e.ErrorMessage());
        }
        CoUninitialize();
    }
    return 0;
}

You can also consult following links:-
http://codeproject.com/Articles/587488/Streaming-XML-parser-in-Cplusplus
http://msdn.microsoft.com/en-us/library/ms765540(v=vs.85).aspx
Contrary to this if you're on linux platform then go for TinyXml:-
http://grinninglizard.com/tinyxml/

A: I find pugixml to be very easy to use. It comes as a small source file that you can compile in to your project.
Example C++03:
#include <fstream>
#include <iostream>
#include "pugixml.hpp"

int main()
{
    using namespace pugi;

    // Load XML file from fstream

    std::ifstream xml_file("test.xml");

    if(!xml_file)
    {
        std::cerr << "ERROR: opening XML file: " << std::endl;
        return 1;
    }

    xml_document doc;

    xml_parse_result res = doc.load(xml_file);

    if(!res)
    {
        std::cerr << "ERROR: " << res.description() << std::endl;
        return 1;
    }

    // get all children of <root><source>

    xml_object_range<xml_named_node_iterator> sources =
        doc.child("root").children("source");

    // Iterate through <root><source> children

    xml_named_node_iterator s;
    for(s = sources.begin(); s != sources.end(); ++s)
    {
        // get all children named <root><source><view>

        xml_object_range<xml_named_node_iterator> views =
            s->children("view");

        // Iterate through <root><source><view> children

        xml_named_node_iterator v;
        for(v = views.begin(); v != views.end(); ++v)
            std::cout << v->attribute("name").value() << '\n';
    }
}

Example C++11:
#include <fstream>
#include <iostream>
#include "pugixml.hpp"

int main()
{
    using namespace pugi;

    std::ifstream xml_file("test.xml");

    if(!xml_file)
    {
        std::cerr << "ERROR: opening XML file: " << std::endl;
        return 1;
    }

    xml_document doc;

    xml_parse_result res = doc.load(xml_file);

    if(!res)
    {
        std::cerr << "ERROR: " << res.description() << std::endl;
        return 1;
    }

    auto sources = doc.child("root").children("source");

    for(auto&& s: sources)
    {
        auto views = s.children("view");

        for(auto&& v: views)
            std::cout << v.attribute("name").value() << '\n';
    }
}


text:
Q: on key press check pattern for HH:MM:SS I have a input which is of type text. On its keypress I am calling the below code:
         function checkHHMMformat(evt, a)
         {
           var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
           var isValid = /^(?:(?:([01]?\d|2[0-3]):)([0-5]?\d):)?([0-5]?\d)$/.test(key);
           if (!isValid)
           {
             event.preventDefault();
             return false;
           }
           return true;
         }

But I'm not able to validate it properly

A: Regular Expression to Validate Time Format HH:MM:SS 24-hour should be as shown below:
 /(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/gm


text:
Q: Multicharacter delimiter cut My file looks like:
19-04-05 08:45:22,643: INFO  [ByrioThread] [] kks.connectorLog: Very important information

I want to cut it using a two character delimiter ": ", but with field definition "field 2 and all next". This would be a cut command as:
cut -f2- -d': '

so the output would be:
INFO  [ByrioThread] [] kks.connectorLog: Very important information

however cut does not support multicharacter delimiter. Therefore answer given here  How to use cut with multiple character delimiter? unix with awk does not work.
Any help appreciated!

A: This grep might work for you:
grep -Po ': \K.*' file

Or a pure bash solution using parameter expansion:
while IFS= read -r line; do
   printf '%s\n' "${line#*: }"
done < file

A: You can use 'awk' with a multi-character delimiter.
awk -F": " 'BEGIN {OFS=FS} {$1=""; print $0}'  < input.txt | cut -c 3-

As you require your delimiter to appear in the output you'll need to set your output field separator (OFS), otherwise you'll have your delimiter replaced with a space.  This is done by BEGIN {OFS=FS}.  We're then dropping the first field with $1="" and then printing out what remains, having dropped the unnecessary field separator (with cut)
Alternatively, we can remove the first field and the field separator and do this directly with:
awk -F": " 'BEGIN {OFS=FS} {sub($1 FS,"")}1' < input.txt

The removal is done by substituting the empty string for the first field and the field separator.  The additional 1 then triggers the printing of the remaining text.

A: As the first part 19-04-05 08:45:22,643: is always fixed in size, why don't you go for:
$ echo '19-04-05 08:45:22,643: INFO  [ByrioThread] [] kks.connectorLog: Very important information' | sed -E 's/^.{23}//'
INFO  [ByrioThread] [] kks.connectorLog: Very important information

Or via grep
grep -oP '(?<=\d{2}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}: ).*'

or via awk
$ echo '19-04-05 08:45:22,643: INFO  [ByrioThread] [] kks.connectorLog: Very important information' | awk -F '\([0-9]{2}[:-] ?\)*,[0-9]{3}: ' '{print $2}'
INFO  [ByrioThread] [] kks.connectorLog: Very important information


text:
Q: Object.get() throws exception if Nothing is found Is there a possibility to return none if no results are found by a object.get() function call?
I know it throws an exception by default, but I want to return none from it.

A: You can do it with exceptions like:
 try:
     object = Model.objects.get(foo='bar')
 except Model.DoesNotExist:
     object = None


text:
Q: Definition of absolute value of complex number The definition I see everywhere for the absolute value of a complex number is: Let $z=x+iy$ then $|z| := \sqrt{x^2+y^2}$.
But the square root operation is multivalued in complex analysis.  So while this does show that the absolute value is a real number, it does not in fact indicate which square root we want.  Of course it should be the nonnegative one, but what is the best way to express that?  Would I just need to note "$|z| \ge 0$" in the definition?  That's a little less than satisfying.

A: We usually take it as a convention that $\sqrt{x} \geq 0$, but if you wanted to make it explicit, you could say something like "$|z| : = \sqrt{x^2 + y^2}$, where in the definition we adopt the convention that $\sqrt{r} \geq 0$."


text:
Q: Spyder 4.0.1(python 3.7) cannot import class Ui_MainWindow from Qt designer autogenerated module I am still very new to python and trying to write a small program that contains a Main Window and a couple of pop-up dialog boxes. The older version of spyder (3.x.x, python 3.6.x) seems to work well with the code, but after I switched to the newest version of spyder 4.0.1(python 3.7) by installing the newest anaconda. It doesn't seem to import the main window UI class (Ui_MainWindow) that was automatically generated by the code generator and saved under the same folder where my logic python files and the rest of the automatically generated files are. Instead it looks for a different path under c:\Users\myusername
The files under my current working folders are
enter image description here
My question is why the code doesn't have a problem import the autogenerated UI_Dialog saved in DatabaseLogin.py, but have a problem importing the Ui_Mainwindow saved in the same folder and named AnalysisDatabase.py
Any clue would be appreciated. Thank you.
The logic code started as the following
import sys
import struct

import mysql.connector
from mysql.connector import errorcode

from DatabaseLogin import Ui_Dialog # this line works
from AnalysisDatabase import Ui_MainWindow # problematic line

Error code:
ImportError: cannot import name 'Ui_MainWindow' from 'AnalysisDatabase' (C:\Users\myusername\AnalysisDatabase.py)

A: Found an answer right after this was posted. It turned out there is a python file named exactly the same in the C:\Users/myusername. After deleting that file, python is again searching the current folder as a higher priority.


text:
Q: Method to convert all 'overlapping' points to exact same geometry in QGIS 3.4 I have a point vector layer with approximately 2.5 million points, many of which share the same or a very similar geometry (within 1 m of each other).
I would like to know if I can bulk amend the geometry of these points so they are exactly the same if they are within that 1 meter threshold in the X-Y plane?
The majority of 'overlapping' points do share the exact same geometry so ideally I would want to amend those points that fall outside the majority to have the same geometry.
I am familiar with PyQGIS but not confident in it's use.

A: The tool "Snap geometries" in the processing toolbox can help you.
Give two times your layer (input and reference layer), set the tolerance to 1 meter and select the best snapping behavior for your case (i.e. align nodes, don't add new).

A: this might be of help - try using the calculator and referencing the  field and updating the X & Y to specific locations
geom_from_wkt('POINT('||'31.797788'||' '||'30.729471'||')')
further info at -
QGIS update feature geometry from attribute fields


text:
Q: Docker container hangs in status Created In an ubuntu terminal, I run:
sudo strace -f -p `pidof containerd` -o strafce_log

In another temrinal I run
docker run ubuntu

The result, both terminals hang :(
If I stop the docker service, then I cannot start it anymore
The container stays in status created, and any command I issue against it hangs (docker logs, docker rm, system prune)
Docker commands against other containers or images works fine. Docker ps also works
I also found online that i should look at cat /var/log/syslog | grep docker. Unfortunately nothing over there neither.
Can you guide me on where i could get more logs or some info on what is docker or that container doing?

A: Analysis of logs produced by sudo strace -ff -p $(pidof containerd) -o strace_log shows that it stalls when execve() is called by a
process named runc init.  This led me to this bug report on runc GH
page that
explains that it's a kernel bug that can be reproduced with every
program that uses pthreads and execve() and presents a short Go
program that can be used to reproduce the problem:
package main

import (
    "os"
    "syscall"
)

func main() {
    syscall.Exec("/bin/echo", []string{"/bin/echo", "Hello"}, os.Environ())
}

Knowing it's a kernel bug I used Raspberry Pi for testing so that I
could build and replace Linux kernel quickly without risking making my
main machine unbootable or playing around with virtual machines and as
Go is not installed by default in Raspbian I used the following C
program for testing:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdint.h>

void *foo(void *p)
{
  (void) p;
  while(1)
    {
      puts("in thread");
      sleep(2);
    }
}

int main(void)
{
  printf("pid: %jd\n", (intmax_t) getpid());
  pthread_t tid;
  pthread_create(&tid, NULL, foo, NULL);

  char *envp[] = {"var"};
  char *ls_args[] = { "/bin/ls" , "-l", NULL};
  if (execve(ls_args[0], ls_args, envp) < 0) {
    perror("execve error");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

Build with gcc strace-test.c -o strace-test -pthread and see that
strace -f ./strace-test gets stuck as well.
Patch that was supposed to fix strace was sent to Linux kernel
mailing list in
2016
but it has not been accepted, you can read the entire discussion to
get the idea why.  Nonetheless, I applied this patch to my local
Linux kernel tree for Raspberry
Pi against rpi-5.6.y branch and
after rebuilding and replacing the kernel on Raspberry Pi strace -f ./strace-test doesn't get stuck any more. Linux source code has
changed a bit since 2016 and the patch doesn't apply cleanly. FWIW,
the full patch I applied is:
diff --git a/kernel/fork.c b/kernel/fork.c
index 60a1295..c26aaa1 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -1224,7 +1224,7 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
        struct mm_struct *mm;
        int err;

-       err =  mutex_lock_killable(&task->signal->cred_guard_mutex);
+       err =  mutex_lock_interruptible(&task->signal->cred_guard_mutex);
        if (err)
                return ERR_PTR(err);

diff --git a/kernel/signal.c b/kernel/signal.c
index 9ad8dea..ea7c7b5 100644
--- a/kernel/signal.c
+++ b/kernel/signal.c
@@ -108,6 +108,10 @@ static bool sig_ignored(struct task_struct *t, int sig, bool force)
        if (sigismember(&t->blocked, sig) || sigismember(&t->real_blocked, sig))
                return false;

+       /* Do not ignore signals sent from child to the parent */
+       if (current->ptrace && current->parent == t)
+               return 0;
+
        /*
         * Tracers may want to know about even ignored signal unless it
         * is SIGKILL which can't be reported anyway but can be ignored


text:
Q: Set cover approximation in R I'm trying to solve or implement an approximation to the set cover problem in R. Given a data frame like this.
  sets n
1   s1 1
2   s1 2
3   s1 3
4   s2 2
5   s2 4
6   s3 3
7   s3 4
8   s4 4
9   s4 5

The unique number of elements in column n are:
unique(d$n)
[1] 1 2 3 4 5

I'd like to calculate the smaller number of sets (column sets) that cover all the unique elements in n (universe). In this example two sets: s1 {1, 2, 3} and s4 {4, 5}. I've read about it in wikipedia and on the Internet, and I know a greedy algorithm could be applied to find an approximation. I've checked too this link in which they mention two packages to solve such problems, LPsolve and Rsymphony, but I don't know even how to start. In my real life example, I have more than 40,000 sets and each set between 1,000 and 10,000 elements and a unviverse or unique elements of 80,000.
Any help or guide about how to start or proceed will be very much appreciated.
data
d <- structure(list(sets = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 3L,
4L, 4L), .Label = c("s1", "s2", "s3", "s4"), class = "factor"),
    n = c(1, 2, 3, 2, 4, 3, 4, 4, 5)), .Names = c("sets", "n"
), row.names = c(NA, -9L), class = "data.frame")

A: The lpSolve package is available on CRAN for linear programing problems. Using your link which had a response from the very reputable Hans Borchers, as well as a slightly more complex example (starting on pg 4/5) in http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf as templates to understand teh proper structure of the setup, and then following along with modifications to the first example in ?lp:
library( lpSolve)
?lp
# In Details: "Note that every variable is assumed to be >= 0!"
# go from your long-form rep of the sets to a wide form for a matrix representation
( items.mat<- t(table(d$sets,d$n))  )  # could have reversed order of args to skip t()
#---------
> dimnames(items.mat) = list( items=1:5, sets=paste0("s", 1:4) )
> items.mat
     sets
items s1 s2 s3 s4
    1  1  0  0  0
    2  1  1  0  0
    3  1  0  1  0
    4  0  1  1  1
    5  0  0  0  1
#---------
f.obj <-  rep(1,4)  # starting values of objective parameters by column (to be solved)
f.dir <- rep(">=",5) # the constraint "directions" by row
f.rhs <- rep(1,5)    # the inequality values by row (require all items to be present)

lp ("min", f.obj, items.mat, f.dir, f.rhs)$solution
#[1] 1 0 0 1

So sets s1 and s4 are a minimal cover. The "column coefficients" determine choice of "sets".


text:
Q: The two extreme cases of the product measure Let's start off with two measure spaces, $ (X,\mathcal{A},\mu) $ and $ (Y,\mathcal{B},\nu) $, and suppose that we want to form their product measure space. It can happen that more than one product measure exists: One has the measures arising from the Carathéodory construction on the $ \sigma $-algebra $ \mathcal{A} \times \mathcal{B} $ corresponding to the outer measures
$$
\pi(M) \stackrel{\text{df}}{=}
\inf
\left( \left\{
\sum_{n \in \mathbb{N}} \mu(A_{n}) \nu(B_{n}) ~ \middle| ~
M \subseteq \bigcup_{n \in \mathbb{N}} A_{n} \times B_{n}
\right\} \right)
$$
and
$$
p(M) \stackrel{\text{df}}{=}
\sup(\{ \pi(M \cap A \times B) \mid \mu(A),\nu(B) < \infty \}).
$$
Now, in this question, one exercise is to show that any measure $ \lambda $ on $ \mathcal{A} \times \mathcal{B} $ such that
$$
\forall A \in \mathcal{A}, ~ \forall B \in \mathcal{B}: \qquad
\lambda(A \times B) = \mu(A) \nu(B)
$$
satisfies $ p(M) \leq \lambda(M) \leq \pi(M) $ for all $ M \in \mathcal{A} \times \mathcal{B} $.
One direction is easy: $ \displaystyle M \subseteq \bigcup_{n \in \mathbb{N}} (A_{n} \times B_{n}) $ implies that
$$
     \lambda(M)
\leq \sum_{n \in \mathbb{N}} \lambda(A_{n} \times B_{n})
=    \sum_{n \in \mathbb{N}} \mu(A_{n}) \nu(B_{n}).
$$
I also know that for sets $ W \in \mathcal{A} \times \mathcal{B} $ such that $ \pi(W) < \infty $, one has $ p(W) = \pi(W) $. What I cannot show is the reverse, i.e., $ \lambda(W) \geq \pi(W) = \lambda(W) $, which would then imply the above inequality. Does someone have a hint for me?
Thanks in advance.

A: I am a bit surprised to see this question remain unanswered for so long. Since its twin question also has no answer, let me add my answer here.
The OP has already shown correctly that $\lambda(M)\leq \pi(M)$. So I shall show that $p(M)\leq \lambda(M)$ for every $M\in\mathcal A\rtimes \mathcal B$ where I am using the symbol $\rtimes$ to denote the product $\sigma-$algebra.
Take any $M\in\mathcal A\rtimes\mathcal B$ and any $A\in\mathcal A,B\in\mathcal B$ with $\mu(A)<\infty,\nu(B)<\infty$. Therefore, using the fact that $\pi(A\times B)<\infty$ and that $\pi$ is a measure on $\mathcal A\rtimes \mathcal B$ (that $\pi$ is a measure on $\mathcal A\rtimes \mathcal B$ follows from the definition of $\pi$ as an outer measure and is standard), we have:
$\pi(M\cap A\times B)=\pi(A\times B)-\pi(M^c\cap A\times B)$
Using the inequality that for any $M\in\mathcal A\rtimes \mathcal B$, $\lambda(M)\leq\pi(M)$ we obtain :
$\pi(A\times B)-\pi(M^c\cap A\times B)\leq \pi(A\times B)-\lambda(M^c\cap A\times B)=\lambda(A\times B)-\lambda(M^c\cap A\times B)=\lambda(M\cap A\times B\leq \lambda(M)$
We used $\pi(A\times B)=\lambda(A\times B)$ which is something you can readily check.
In the above, we could do all the subtraction because $\pi(A\times B)<\infty$ is given.
So we got for any $A\in\mathcal A,B\in\mathcal B$ with $\mu(A)<\infty,\nu(B)<\infty$ that $\pi(M\cap A\times B)\leq\lambda(M)$.
Take supremum over all possible $A,B$ on LHS to conclude the result.


text:
Q: Getting elements of a 1 dimensional array Numpy Python How would I be able to print the last value of element_val numpy arrays. It is the second index of [ 2.  2. 30.] which is 30. So the values will go like 30,40,50...670,680. How would I be able to do that since the numpy array is 1 dimensional?
input.csv file:
element,LNPT,SNPT,NLP,NSP,TNT,TPnL,MxPnL,MnPnL,MxU,MxD
[ 2.  2. 30.],0,0,4,4,8,-0.1,-0.0,-0.1,17127,-3
[ 2.  2. 40.],0,0,2,2,4,0.0,-0.0,-0.0,17141,-3
[ 2.  2. 50.],0,0,2,2,4,0.0,-0.0,-0.0,17139,-3
[ 2.  2. 60.],2,0,6,6,12,0.5,2.3,-1.9,17015,-3
[ 2.  2. 70.],1,0,4,4,8,0.3,0.3,-0.0,17011,-3

Code:
import numpy as np
import pandas as pd

my_data = pd.read_csv('input.csv').to_numpy()
element_vals = my_data[:,0]
print(element_vals)

Output:
['[ 2.  2. 30.]' '[ 2.  2. 40.]' '[ 2.  2. 50.]' ... '[  6.    7.5 660. ]'
 '[  6.    7.5 670. ]' '[  6.    7.5 680. ]']

A: Use str.strip(), str.split(), and to_numpy() to manually convert the df.element column into a real numpy array:
df = pd.read_csv('input.csv')
element_vals = df.element.str.strip('[]').str.split(expand=True).astype(float).to_numpy()

# array([[ 2.,  2., 30.],
#        [ 2.,  2., 40.],
#        [ 2.,  2., 50.],
#        [ 2.,  2., 60.],
#        [ 2.,  2., 70.]])

Then you can index as expected:
element_vals[:, 2]

# array([30., 40., 50., 60., 70.])


text:
Q: On a positivity of a matrix with trace entries. Some basic observations lead me to ask the following quesiton
Let $A_1, \cdots, A_m$ be $n\times n$ complex matrices. For positive integer $k\ge 1$, show
$$\left(\begin{array}{cccc}Tr\{(A_1^*A_1)^k\}&Tr\{(A_1^*A_2)^k\}&\cdots &Tr\{(A_1^*A_m)^k\}\\Tr\{(A_2^*A_1)^k\}&Tr\{(A_2^*A_2)^k\}&\cdots &Tr\{(A_2^*A_m)^k\}\\\cdots&\cdots&\cdots&\cdots\\Tr\{(A_m^*A_1)^k\}&Tr\{(A_m^*A_2)^k\}&\cdots &Tr\{(A_m^*A_m)^k\}
\end{array}\right)$$
is positive semidefinite.
Remark
1). When $m=2$, it suffices to show $|Tr\{(A_1^*A_2)^k\}|^2\le Tr\{(A_1^*A_1)^k\}\cdot Tr\{(A_2^*A_2)^k\}$, which is a consequence of a unitarily invariant norm inequality appeared in p.81 of X.Zhan, Matrix inequalities, Springer, 2002.
2).  It is easy to show $$\left(\begin{array}{cccc}(Tr\{A_1^*A_1\})^k&(Tr\{A_1^*A_2\})^k&\cdots &(Tr\{A_1^*A_m\})^k\\(Tr\{A_2^*A_1\})^k&(Tr\{A_2^*A_2\})^k&\cdots &(Tr\{A_2^*A_m\})^k\\\cdots&\cdots&\cdots&\cdots\\(Tr\{A_m^*A_1\})^k&(Tr\{A_m^*A_2\})^k&\cdots &(Tr\{A_m^*A_m\})^k
\end{array}\right)$$
is positive semidefinite, since it is $k$ Hadamard product of a Gram matrix.

A: It seems that this is not true. Here is a counterexample. Consider a regular $d$-gon, where $d\ge 3$ is an odd number. Let $S,T$ be the permutation matrices on the vertices of this $d$-gon, induced by reflections in two adjacent symmetry axes. Let $A_1=1, A_2=S, A_3=T$, which are $d$ by $d$ matrices. We have $S^2=T^2=1$, and $ST$ is a rotation of order $d$
(so $(ST)^2$ has no fixed points).
Let $k=2$. Then the matrix in the question seems to be the following:
$$
\left(\begin{matrix} d & d & d\\ d & d & 0\\ d & 0 & d\\ \end{matrix}\right)
$$
The determinant of this matrix is $-d^3$.


text:
Q: Need help regarding nodejs restful task My task is a nodejs backend task which contains restful service which contains endpoints for adding and removing bulletins and also use sequlizejs for database.
After reviewing this project, the reviewer says that I do not know restful service and also project is not scalable without giving any details so may I know what is the problem with project.
Project is on github https://github.com/mregydev/testrest

A: I believe it is your route... to do CRUD, you usually use a standard way of routes for your endpoints. for example,
To create a bulletin, you use POST /bulletins
To read the bulletin list, you use GET /bulletins
To read a specific bulletin, you use GET /bulletins/:bulletinId
To update a specific bulletin, you use PUT (or PATCH) /bulletins/:bulletinId
To delete a specific bulletin, you use DELETE /bulletins/:bulletinId

You may read https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4


text:
Q: Local hosted page Good day,
I am not a programmer by profession and I didn't study formally, I am currently self learning. So my Question might seem stupid or don't understand the answers. Please forgive me.
Okay the question:
My example will be for an internal team lunch roster it will be local page where users can set there lunch times and will not be changed but will reset at the end of the day.
All changes can be viewed by openning up the page.
I would like to know should it be a java and html or what language should I create such page on.
Kind regards

A: From your requirement, it's better to create a local website @ intranet developed using PHP with automated script to reset the data for lunch at the end of the week. You can use Xampp, Wamp or any web server software of your choices.
Xampp
WampServer
ps: you can use this guide to create an automated script
Run Cron Job on PHP Script, on localhost in Windows


text:
Q: Bounds not working, does not even display markers when trying to add bounds The current code below does not even show markers, but when the bounds are removed, the markers start appearing. I dont know where I am going wrong. All I want to do is zoom the map to include all of the 3 markers. Currently it is zooming to 0,0 .
I do provide my api key, so that is not the problem.
Code:

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

A: You have an error when you create the array on this line (I've truncated the code for  readability):
var LatLngList = array (new google.maps.LatLng (markers[0].lat,markers[0].lng) );

Change it to:
var LatLngList = Array (new google.maps.LatLng (markers[0].lat,markers[0].lng) );

or
var LatLngList = [ new google.maps.LatLng (markers[0].lat,markers[0].lng) ];


text:
Q: Catch return value of bulk insert in SQLite room Let's say I have the following insertAll function:
@Insert
void insertDogs(List<Dog> dogs);

And
public long[] insertDogs(List<Dog> dogs) {
    return appDatabase.dogDao().insertDogs(dogs)
            .subscribeOn(Schedulers.io()) //causes Cannot resolve method 'subscribeOn(io.reactivex.Scheduler)'
            .observeOn(AndroidSchedulers.mainThread());
}

What is the correct return value of bulk insert should be?
If I want to receive the new created ids of the dogs, I receive the above mentioned error.
Is it enough to just put try catch outside insertDogs function, as subscribeOn does not work as it seems for bulk inserts.

A: Try using :-
@Insert
long[] insertDogs(List<Dog> dogs);


text:
Q: Refresh scope on every x time using $timeout I am a newbie to angular. I want to use $timeout of angular to refresh scope after few minutes. I am working on an social app where i need to refresh notification scope after few minutes. Getting notification from a http request using service.
JS:
App.factory('MyService' ,function($scope,$timeout){
return{
 notification:return function(callback){
      $timeout(function(){
       $http.get("notification/get").success(callback)
      },100000);

}
});

function Controller($scope,MyService){

 MyService.notification(function(result){
  $scope.notification =data;
 });

}
Now how can i make http request after few minutes let'say 1 minute and refresh notification scope. I tried using $timeout but things are not working fine.

A: But i would suggest to move the $interval to the controller.
 App.factory('MyService' ,function($scope,$timeout){
  return{
    notification: function(){
        return $http.get("notification/get").success(function(response){
           return response.data;
        });
    }
  });

function Controller($scope,MyService,$interval){

   /**
   * Loads and populates the notifications
   */
   this.loadNotifications = function (){
      MyService.notification().then(function(data){
        $scope.notification =data;
      });
   });
   //Put in interval, first trigger after 10 seconds
   var theInterval = $interval(function(){
      this.loadNotifications();
   }.bind(this), 10000);

    $scope.$on('$destroy', function () {
        $interval.cancel(theInterval)
    });

   //invoke initialy
   this.loadNotifications();
}

This seems like a better architecture there.
Passing, resolving or rejecting promises will $digest the scope.
You want to get the notifications every x milliseconds and pass them into the scope.

A: You want to instantiate the timeout after it finishes. Try changing your $timeout function to something like:
var timer = $timeout( function refresh(){
    $http.get("notification/get").success(callback)
    timer = $timeout(refresh, 100000);
}, 100000);


text:
Q: Mac OS X: Increase mouse speed on login screen I have an iMac 27" and it takes so much time to move the mouse pointer from the upper left corner to the center of the screen to click my account entry on the login screen.
Isn't there a way to increase the mouse speed on the login screen?
(Also, I think I'll file a bug or suggestion for Apple to start Mac OS X with the mouse cursor centered rather than in the upper left corner.)

A: I'm fairly certain that you're not going to be able to do this without some sort of third party software. There are a few tweaks that can be made to the loginwindow app which is running before login, but modifying the mouse speed isn't one of them.
You might try USB Overdrive which says it's a device driver in addition to a preference pane. The speed setting you set in it may affect the device driver prior to login.
The other thing you could try is playing with this code or this code to create a daemon that could be run at boot time which would modify the mouse speed.
Good luck!

A: I tried Jon Grant's answer and didn't work for me.
One possible workaround is this:
Since Tab doesn't focus on your user, what you can do instead is hitting your user's first letter. That will focus on it, so then you can just hit Enter and then you are able to type your password. Even better than using the mouse
EDIT: Oops, didn't notice it was 6 years old. I just noticed this with El Capitan 10.11.5

A: Well, this isn't a complete solution, but maybe someone can expand on it...
The Terminal command you want is:
defaults write -g com.apple.mouse.scaling 3.0

(or some higher number for faster)
I don't know what user's defaults I need to change (via su/sudo) for the login screen though.