How to get gRPC retry logs on client | java gRPC

Question: I'm using gRPC for internal communication b/w 2 java services.
I configured gRPC retry using service config . I am able to get retry count in server using <code>"grpc-previous-rpc-attempts"</code> metadata header. However , I don't find any logs those are getting printed in the client app while retries are happening .

why gRPC is not logging retry attempts which ideally should have
been done when retries are configured
Is there any way to log each
retry attempt in the client app? This is needed for better
observability.

Thanks
Answer: At this moment there is no logging support for retries, but it would be a reasonable thing to add.
You can either file a feature request to get that added, or better yet make a pull request for the change. If you decide to make the change, it should be localized to just RetriableStream.java. Feel free to tag me (@temawi) on it and I'll review it for you.


Convert boto3 BaseCondition to its string representation

Question: I am trying to convert boto3 dynamoDB conditional expressions (using types from boto3.dynamodb.conditions) to its string representation. Of course this could be hand coded but naturally I would prefer to be able to find something developed by AWS itself.
Key("name").eq("new_name") & Attr("description").begins_with("new")

would become
"name = 'new_name' and begins_with(description, 'new')"

I have been checking in the boto3 and boto core code but so far no success, but I assume it must exist somewhere in the codebase...
Comment: for logging, printing and other string representation usages (my use case).
Comment: What does that mean, string representation? for query syntax? what?
Answer: In the boto3.dynamodb.conditions module there is a class called ConditionExpressionBuilder.  You can convert a condition expression to string by doing the following:
condition = Key("name").eq("new_name") & Attr("description").begins_with("new")

builder = ConditionExpressionBuilder()
expression = builder.build_expression(condition, is_key_condition=True)

expression_string = expression.condition_expression
expression_attribute_names = expression.attribute_name_placeholders
expression_attribute_values = expression.attribute_value_placeholders

I'm not sure why this isn't documented anywhere.  I just randomly found it looking through the source code at the bottom of this page https://boto3.amazonaws.com/v1/documentation/api/latest/_modules/boto3/dynamodb/conditions.html.
Unfortunately, this doesn't work for the paginator format string notation, but it should work for the Table.query() format.
Answer: From @Brian's answer with
ConditionExpressionBuilder I had to add the Dynamodb's {'S': 'value'} type notation before the query execution.
I changed it with expression_attribute_values[':v0'] = {'S': pk_value}, where :v0 is the first Key/Attr in the condition. Not sure but should work for next values (:v0, :v1, :v2...).
Here is the full code, using pagination to retrieve only part of data
from boto3.dynamodb.conditions import Attr, Key, ConditionExpressionBuilder
from typing import Optional, List
import boto3

client_dynamodb = boto3.client("dynamodb", region_name="us-east-1")

def get_items(self, pk_value: str, pagination_config: dict = None) -> Optional[List]:

    if pagination_config is None:
        pagination_config = {
            # Return only first page of results when no pagination config is not provided
            'PageSize': 300,
            'StartingToken': None,
            'MaxItems': None,
        }

    condition = Key("pk").eq(pk_value)

    builder = ConditionExpressionBuilder()
    expression = builder.build_expression(condition, is_key_condition=True)

    expression_string = expression.condition_expression
    expression_attribute_names = expression.attribute_name_placeholders
    expression_attribute_values = expression.attribute_value_placeholders

    # Changed here to make it compatible with dynamodb typing
    python expression_attribute_values[':v0'] = {'S': pk_value}

    paginator = client_dynamodb.get_paginator('query')
    page_iterator = paginator.paginate(
        TableName="TABLE_NAME",
        IndexName="pk_value_INDEX",
        KeyConditionExpression=expression_string,
        ExpressionAttributeNames=expression_attribute_names,
        ExpressionAttributeValues=expression_attribute_values,
        PaginationConfig=pagination_config
    )

    for page in page_iterator:
        resp=page
        break

    if ("Items" not in resp) or (len(resp["Items"]) == 0):
        return None

    return resp["Items"]

EDIT:
I used this question to get string representation for Dynamodb Resource's query, which is not compatible (yet) with dynamodb conditions, but then I found a better solution from Github (Boto3)[https://github.com/boto/boto3/issues/2300]:
Replace paginator with the one from meta
dynamodb_resource = boto3.resource("dynamodb")
paginator = dynamodb_resource.meta.client.get_paginator('query')

And now I can simply use Attr and Key
Comment: Thanks for sharing dynamodb_resource.meta.client.get_paginator. That's really helpful!


Can't login to Technic Launcher

Question: So, i'm trying to login to login to Technic Launcher for the first time on a pretty new PC, just a week after migrating my account and changing my name. It refuses to work. I have tried E-Mail, username, my old username, even older passwords. All combinations, and they refuse to work.
Comment: Possible duplicate of [Username and Password not recognized when logging into Minecraft](https://gaming.stackexchange.com/questions/118282/username-and-password-not-recognized-when-logging-into-minecraft)
Comment: And what does it say?
Comment: welcome to stack exchange and ...all that. Someone may vote to close this, something to do with some crap about only supporting vanilla minecraft questions. So my advice would  be to reach out to the technic community through forums. Also google your issue and your operating system. Odds on, someone else, if not many others, have had this issue. So hopefully there exists some solution to this issue.
Comment: It's not a crash dump with a million lines of code about three hundred installed mods and no explanation of the problem.  It's an easily reproducible issue with a common launcher.  There's no call for closing here.
Answer: When I had that problem, it was because I was using my old Minecraft username instead of my email address after creating a Mojang account and linking my Minecraft username to it.
Go log in at Minecraft.net.  If that works, use the exact same name/email and password to log in from the Technic Launcher.  If it doesn't work, hit that "Forgot Password" link and reset your password at minecraft.net.  Then use the new name/email and password at the Technic Launcher.
Comment: @Dragonix I have not heard anyone mention cookies anymore since around 2011.

Can't login to Technic Launcher


How can I minimise the number of people who die?

Question: In Mass Effect, there are times when someone might get killed, for example Wrex on Virmire.
Who are the characters that might/will be killed if not satisfied with something, either their mission was not completed or by actions of Shepard?
Answer: Obviously it goes without saying that the below post is full of spoilers.
Throughout the story multiple NPCs, including squad mates, die. Some of them are unavoidable but many are immune to death.
Mass Effect
Right at the start of the first mission, one of your squad mates Richard L. Jenkins will run off ahead and get shot dead by Geth drones within moments of the mission starting.
Virmire
When you arrive on Virmire, Wrex will throw a tantrum provoked by the breeding of fertile Krogan and slowly build up into a rage over the prospect of destroying the facility. If you don't talk him out of it, he will either be killed by Ashley or through your own actions.
Depending on your choices during the Virmire mission, the Salarian STG squad led by Kirrahe can be ambushed and killed. Choose to provide them backup and pull the enemies towards you rather than sounding the alarms on the far side of the base.
At the end of the Virmire mission, you must choose to sacrifice either Ashley Williams or Kaidan Alenko.
Noveria
During the Noveria mission you will confront Liara's mother, Matriarch Benezia, and be forced to kill her in the ensuing battle. After this encounter, you must choose whether to kill or save (free) the last Rachni queen.
Feros
On Feros as you head out to and back across the Skywalk you will have the opportunity to communicate with a small group of colonists that have escaped from the Exogeni facility. During the conversation that occurs on the return journey you will need to use the correct conversation options to avoid the situation escalating with the leader of this small group,  Ethan Jeong, who will be very protective of the Exogeni corporation. If the situation escalates, you'll end up killing him.
Near the end of the mission on Feros you will approach the Zhu's Hope colony and the Thorian will use the colonists to try and stop you. Using the anti-Thorian grenades to knock out the colonists will allow you to re-enter the colony without killing the colonists.
Shortly after moving through the colony you will meet up with Fai Dan again, who will commit suicide under the influence from the Thorian creature.
At the very, very end of the Feros mission, after melding with Shiala, you will have the opportunity to kill her for her crimes (working with Saren) or spare her.
Major Kyle
During the UNC: Major Kyle mission, it is possible to resolve the situation peacefully, saving everybody.
Encounter with Saren
In the council chambers you can talk Saren into committing suicide with enough renegade or paragon points. He still transforms into the big bad reaper Saren, but it saves having him fly around the room for a bit.
Saving the Citadel Council
During the final battle with Sovereign, you can choose to attack Sovereign directly or protect the Citadel council. Choosing not to protect the Citadel council will result in their deaths.
Mass Effect 2
You must complete Mass Effect 2 ensuring that every available squad member and loyalty mission is completed before doing the Horizon mission. Completion of Horizon starts a five mission countdown before the Illusive Man forces you to investigate a collector ship.
This gives you the opportunity to complete every loyalty mission and get to the collector ship before your auxiliary crew (Doctor Chakwas and Kelly) have been digested.
At the start of Mass Effect 2, during the opening cinematic, the Normandy SR-1 is destroyed by a collector ship, killing nearly everyone on board.
Squad Loyalties
Depending on your loyalty status and role assignment during the suicide mission, every member of your squad can die - including you. Obviously if you die it's game over but it's possible to exit the final mission with just you and your core crew (Joker, EDI) alive.
For Samara's loyalty mission, you must seduce her daughter and kill her in order to gain Samara's loyalty. Failing to seduce Morinth will result in Samara and Morinth being alive but Samara not being loyal. It is possible to ally with Morinth and kill Samara at this point.
For Miranda's loyalty mission you must travel to Illium to help rescue Oriana, Miranda's younger sister, from their father. Miranda's "friend" Niket is killed as a result of his betrayal, either by Miranda or Captain Enyala.
For Jacob's loyalty mission you must go to the planet Aeia to look for his long lost father. Upon finding what he has done, you can execute him or let Jacob execute him, leave him alive for the colonists to deal with, or just give him to the authorities and send him to prison.
For Garrus's loyalty mission, you can talk Garrus into not killing Sidonis and still gain his loyalty.
Once you've made it into Jack's cell during her loyalty mission, Aresh appears - Jack wants to kill him but you can talk her out of it and still get gain her loyalty. She still gets to blow up the facility afterwards regardless.
During Mordin's mission, once you've met up with Maelon, you have choices to make for both Maelon's life and his research (which has ramifications for Eve's life in Mass Effect 3). Upon entering Maelon's lab you'll go into a cutscene in which Mordin confronts Maelon and finally ends up charging him with a gun drawn - at this point you can use a paragon interrupt to save him.
It is possible to complete Zaeed's mission and gain his loyalty without killing Vido, while simultaneously saving the facility. The paragon route through this mission requires a high amount of paragon points. Due to this, it's recommended that if you have the Price of Revenge DLC that you get Zaeed's mission out of the way early on in your play through. Taking the renegade route through this mission will result in the deaths of everybody in the facility, and Vido.
During Thane's loyalty mission, you can paragon interrupt his son Kolyat and prevent him from shooting his target. Alternatively you can wound Kolyat to also prevent the kill from occurring.
Suicide mission
To survive the suicide mission with no deaths, there are a number of tasks you must complete throughout the game. Ensure you scan enough planets to have all of the required materials for the ship upgrades, otherwise you'll suffer losses and major damage on your approach to the final mission.
During the suicide mission after passing through the Alpha Relay, you'll need to use the following squad selections:

Send Legion, Tali or Kasumi through the vents
First Squad leader should be loyal Garrus, Miranda or Jacob
Shield should be Samara/Morinth or Jack
Second Squad leader should be Miranda or loyal Garrus, or Jacob
Escort can be anyone
Final Team - pick any two from Tali, Kasumi, Thane, Samara

Project Overlord
In the Overlord DLC, you can save David Archer from the Project Overlord experiment.
Mass Effect 3
During Mass Effect 3, everybody can die, depending on the options you choose and the ending you select. Literally everybody. Your loyalties are imported from Mass Effect 2 and in the case of Grunt and Zaeed directly influence if they die later in the game.
Once you're reinstated as a SPECTRE, you're able to release Engineers Donnelly and Daniels and allow them to join your crew. If you don't, they perish in a future reaper attack.
The bomb on Tuchanka
After rescuing Lieutenant Victus's squad Tuchanka: Turian Bomb, you're able to rally him into completing his original mission (diffusing the Turian bomb on Tuchanka). Doing so results in him sacrificing his life.
If for some reason you do not complete the mission to defuse the bomb, a large chunk of Tuchanka is wiped out, including Eve, the female Krogan, if she had survived curing the genophage.
The Rachni in the Attican Traverse
During the Attican Traverse: Krogan Team mission, you're given the option to kill or save (again) the Rachni queen. Choosing to save the Rachni queen will wipe out the Krogan commandos, including Grunt if he wasn't loyal in Mass Effect 2.
Curing the Genophage
Mordin or Padok Wiks can die on Tuchanka depending on whether Mordin is alive (replaced by Padok Wiks if not) and whether you choose to cure the genophage. If you choose to sabotage the genophage, Wrex will find out (if Wrex is alive) and confront you, resulting in his death.
If you chose to destroy Maelon's research during Mordin's loyalty mission in Mass Effect 2, Eve, the female Krogan, will die from complications during the creation of the genophage cure.
Thane, Kirrahe and the attack on the Citadel
Thane will always die during Mass Effect 3, if he survived the suicide mission in Mass Effect 2. If you've visited him before Priority: Citadel II, he will die saving the life of the Salarian Councillor. If Thane is not alive but Captain Kirrahe survived the events of Virmire in Mass Effect, Kirrahe will die saving the councillor. If neither Thane or Kirrahe are available, the councillor will be killed by Kai Leng.
Killing Udina during the second Citadel mission after he attempts to seize the Citadel. During this moment you can also end up killing the Virmire survivor if you choose the wrong options.
Samara's convictions
After evacuating the Ardat Yakshi monastery and Samara has found her daughter, you must stop Samara from committing suicide with a quick time event.
Uniting Rannoch
After Priority: Rannoch you're given the opportunity to save Admiral Koris of the Quarian Civilian Fleet. Not saving Admiral Koris will result in his death and give you a hard time in preventing the destruction of the Quarian race.
During the Rannoch missions with the Quarians and Geth, if you choose to side with Legion and allow the Geth to wipe out the Quarian fleet, Tali'Zorah will commit suicide. Legion will "die" regardless during this same set of scenes, as he merges into the Geth conscience. It is possible to keep both the Geth and the Quarians alive.
Saving Oriana (again...)
During Priority: Horizon, you will confront Henry Lawson, Miranda and Oriana's father. If Miranda survived Mass Effect 2 she will die if you don't warn her about Kai Leng. During the confrontation with Henry Lawson you will be given the opportunity to shoot him in addition to a variety of conversation options allowing you to talk him down. If Miranda is alive, she will also get an opportunity to shoot him. If Miranda shoots him without you talking him down first, he will get off a killing shot on Miranda before he dies.
The final missions
After making your way through the Cerberus headquarters space station, you are confronted by Kai Leng and finally get to kill him after the mess he made on Thessia. Following this, you travel back to Earth for the final mission. Any squad mate can be killed during the final mission if your overall readiness is too low.
If Morinth survived Mass Effect 2, she will return as a Banshee on the streets of London during the approach to the Citadel beam.
If you didn't get Jack in her Dossier mission, she will be here as a Phantom.
If you also turned over an inactivated Legion, it will show here as a Nemesis
Upon boarding the Citadel in Earth's orbit, you get to kill the Illusive Man. Anderson dies right at the very end. Depending on your choice at the end-o-matic, everybody died, all machines died, everybody became friends, or technology was enslaved.
Comment: > At the start of Mass Effect 2, during the opening cinematic, the Normandy SR-1 is destroyed by a collector ship, killing nearly everyone on board. This is innacurate, as Jacob explains that nearly everyone got off the Normandy SR-1, but Navigator pressley died in an explosion. A good number still died, as their names are on the memorial on the crew deck in ME3.
Comment: quick question, does being a Paragon saves lives and being a Renegade make you kill them?
Comment: not always but in general, yes.
Comment: and i thought that i could make a badass femshep that will have a good ending and nobody dies.
Comment: You don't have to do all the loyalty missions before Horizon (I'm not even sure if that's possible) to be able to save the crew, but before acquiring the Reaper IFF.
Comment: It's easily possible to do all of the loyalty missions, it's all dependent on the order you execute missions in


How do I pick up the Enter Key being pressed in JavaFX2?

Question: I have a TextField to enter a search term, and a button for "Go". But in JavaFX2, how would I make it so pressing the Enter Key in the TextField would perform an action?
Thanks :)
Comment: Aaah Stack Overflow, as the saying goes:
"Give a person a fish and they eats for a day,
but teach them to fish and and they'll eat for a lifetime."
But a common SO response is more along the lines of:
"I say, good sir, there is a place with books,
look up fishing, study and practice hard,
and 2 months from now you can eat."
Well intentioned, but useless.
Comment: The Javadoc is a good source for such questions: http://docs.oracle.com/javafx/2/api/javafx/scene/control/TextField.html
Answer: I'm assuming you want this to happen when the user presses enter only while the TextField has focus. You'll want use KeyEvent out of javafx.scene.input package and do something like this:
field.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if (ke.getCode().equals(KeyCode.ENTER)) {
            doSomething();
        }
    }
});

Using lambda:
field.setOnKeyPressed( event -> {
  if( event.getCode() == KeyCode.ENTER ) {
    doSomething();
  }
} );

Answer: You can use the onAction attribute of the TextField and bind it to a method in your controller.
@FXML
public void onEnter(ActionEvent ae){
   System.out.println("test") ;
}

And in your FXML file:
<TextField fx:id="textfield" layoutX="29.0" layoutY="298.0" onAction="#onEnter" prefWidth="121.0" />

Comment: yes, the onAction method seems to be the way to go: http://docs.oracle.com/javafx/2/api/javafx/scene/control/TextField.html#onActionProperty -> +1 But you need to annotate the onEnter() method with @FXML when "binding" from FXML and it has to take an ActionEvent argument, AFAIK.
Comment: Note that I had to add `(ActionEvent actionEvent)` as a parameter on `onEnter` before it would work.
Answer: You can try the following:
@FXML
public void buttonPressed(KeyEvent e)
{
    if(e.getCode().toString().equals("ENTER"))
    {
        //do something
    }
}

Comment: better use: `ke.getCode() == KeyCode.ENTER` because it is an enum
Comment: This alone does not work, what is the FXML for this?
Answer: Simply using "lambda expression" :
TextField textField = new TextField();
textField.setOnAction(e -> {
    // add your code to be run here
    System.out.println("textFile");
    });

Answer: This works:
@FXML public TextField txt;

@FXML
public void textAction(KeyEvent e){

    if(e.getCode().equals(KeyCode.ENTER))
        System.out.println(txt.getText());
}

If for some reason .getCode() is not working,
make sure you import the library:
import javafx.scene.input.KeyEvent;

NOT
import java.awt.event.KeyEvent;

I got caught up on this and it was irritating. Im just passing this on for all those in the same boat.
Answer: On some keyboards you have to put additional tests to the '\n' and '\r' characters.
if(event.getCode().equals(KeyCode.ENTER) || event.getCharacter().getBytes()[0] == '\n' || event.getCharacter().getBytes()[0] == '\r') {
        // your action
    }


How should I protect wood gates in a damp climate?

Question: I would like to make a set of external timber yard gates, i.e. both sides of the gates will be exposed to the elements. Since I live in the North of England, it tends to rain. In order to avoid the gates swelling during our damp winter, what sort of things should I aim to do?
The sort of things I'm thinking of are:

Should I specially treat the wood before construction
Should I paint along the bottom of the gates
Answer: "tends to rain" :) Wood will shrink and swell. You can't stop it. Rather, allow for it. You can use wood naturally resistant to decay. Not sure what's available in your locale, examples include redwood, cedar, teak, cypress. You can also use pressure treated lumber, in which case, be sure to apply preservative to cut ends. Field applied preservative will help for a while, but it will not last. You should avoid paint, the shrinking and swelling will quickly cause failure. If you must paint, all surfaces of every piece should at least be primed, if not fully painted.
Use corrosion resistant hardware and fasteners. Stainless steel if possible. At least hot dipped galvanized. Not the much thinner electro-galvanized. For hardware, a durable factory applied finish such as powder coating would be OK. Don't waste time with fine joinery, big and clunky is more appropriate. This is not an excuse to be sloppy, the big and clunky joints must be well made. The frame's primary diagonal should be low at the hinge side so that it's joints are in compression.
Comment: I was told not to paint the bottom (underneath) the door since if water penetrates the door, it needs somewhere to go. Is this sensible? Also when you say primed, do you mean an undercoat? Also, what about the joints - should they be primed?
Comment: Yes, undercoat and prime coat are synonymous. You normally wouldn't prime the joints, it would be detrimental to fine joinery. But with big and clunky joints, it would help. If you have the patience to apply it to every cut, you are indeed a patient worker. I never paint the bottoms of doors out of habit, but as long as there is a weep opening, I'm not sure it matters. The reason for priming the hidden parts is wood that gets more wet on one side will warp big time. When uniformly coated, it gets more uniformly damp.
Answer: Yes, you should paint along the bottom of the gates. Paint and oil keeps the wooden garage doors safe in rainy season and also protects your house.
Comment: Please put links to your company in your profile, not in the answer text. (Link edited out of answer)


How to play Pokémon Go in China?

Question: Just got to China. (Got my game from the American app store.)
Maps are barren. No pokémon. No gyms. No pokéstops.
Forbes says: Want To Play 'Pokémon GO' In China? You'd Better Give Up

For the hit mobile game Pokémon GO to come to China, it would require nothing short of a total game redesign.

How to play Pokémon Go in China?
Answer: Want to play Pokemon GO in China? You'd better give up.
Pokemon GO requires the use of Google's servers and resources for the majority of the game. Google just so happens to be banned in China because political reasons.
Now, in theory, you could set up a VPN to the States or any non-censoring country. From there, you can access Google's servers, and therefore the game. Note that setting up a VPN is not in the scope of this site, so it's left as an exercise to the reader.
Additionally, Niantic will block the game from loading anything in "unsupported" countries at this time. Meaning, if you have a VPN set up and guaranteed working, Niantic may just not be spawning any Pokemon in your vicinity because there's supposed to be nobody there to catch them.
Comment: @user3306356 That is how you get banned.
Comment: VPN still results in a barren pokémon-less map.
Comment: @user3306356 Where are you tunneling to, and what VPN provider (OpenVPN, L2TP, PPTP) are you using? Also, can you see Pokestops and Gyms?
Comment: 12VPN - USA - PPTP. Like I said in the Q: Maps are barren. No pokémon. No gyms. No pokéstops.
Comment: @user3306356 Okay, post edited. I think Niantic just doesnt have any spawns or anything in China yet.
Comment: Time to Location Faker then

How to play Pokémon Go in China?


My lights does not work unless you turn the stove on

Question: The stove controls the lights in the kitchen
Comment: Are you all of a sudden having problems *all over the house*? Because that could be a lost neutral, which would be very serious. Or is this a "just the stove and kitchen lights" problem?
Comment: Is this established behavior or was it always like that? If the first then find the fault, for the second get the lights fed from a different supply prior to the stove.
Comment: This would be really convenient if you needed to bake and didn't have time to turn on the lights.
Answer: Call the power company and report an outage
You lost one of your phases of power.   This is almost always a problem at the power company's end of the wire.
When you turn your oven on, it has the effect of connecting the dead phase to the still-live one.   However this gives very weak power on the dead phase, and this won't hold.
Go to your breaker panel and shut off all your double-wide (2-pole) breakers - oven, dryer, water heater, air conditioner etc.
Then call the power company and report the outage.  They should come out quickly (unless they're busy recovering from the bad weather of late), and the work will be free.
Comment: A dropped neutral and a dead phase are similar, in that both are power outage emergencies that need immediate attention from the utility company. They are different in that a dropped neutral is likely to overvoltage your 120V appliances, while a dead phase rarely might overcurrent the neutral wires in your MWBCs.
Comment: Is this different than a dropped neutral situation? In other questions it seems a dropped neutral is a serious emergency.
Comment: Yeah exactly@whatsisname... if you lose a phase, you can limp the house along for awhile on one leg using only 120V loads... but if you lose a neutral, you are sunk - you dare not use 120V loads or you'll fry stuff or start a fire.
Comment: Worst that could happen is the power company shows up & informs you the busted leg  is on your side of the box (relatively unlikely); then have an electrician fix it.


possible to overload function in matlab class?

Question: Is it possible to overload a function in a Matlab class that you've created?
Like the following:
<code>    function [ sigma_nc ] = sustained_interference( N )
       sustained_interference( N, N.center_freq);
    end

    function [ sigma_nc ] = sustained_interference( N, center_freq )
       ...
    end
</code>
Unfortunately when I try this, I get a redefinition error
Comment: Related : http://stackoverflow.com/questions/8630889/overloading-functions/8631335#8631335
Answer: If you create the function using the latter, then you can pass it just a single parameter which will be interpreted as the first. If you want default values, then you can do something like this:
<code>function [ sigma_nc ] = sustained_interference( N, center_freq )
   if nargin < 2
       center_freq = N.center_freq;
   end
   ...
end
</code>
Comment: a-ha, there we go... I needed the nargin to make this work.  Thanks a bunch!  When it allows me to accept your answer, I will.


Directx 11 - Texture only partially displayed

Question: In an attempt to get a texture on a simple rectangle, I get an odd issue. Only the last column of pixels in the texture are seemingly used.
https://i.stack.imgur.com/H9AgX.png <- The result being the black and white rectangle at the top there.
I've trudged the depths of already asked questions and journeyed the perilous underbelly of Google to no avail. I've compared my code to the tutorial I'd based it off (which, coincidentally, works with my chosen texture) yet still am puzzled.
I was thinking it could be the input layout, perhaps the offsets?
D3D11_INPUT_ELEMENT_DESC ied[] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
};

dev->CreateInputLayout(ied, 3, VS->GetBufferPointer(), VS->GetBufferSize(), &pLayout);
devcon->IASetInputLayout(pLayout);

If not this, then theres a chance it could be the CreateShaderResourceFromViewFile:
 D3DX11CreateShaderResourceViewFromFile(dev,        // the Direct3D device
                                   L"Ptitle.png",    // load Wood.png in the local folder
                                   NULL,           // no additional information
                                   NULL,           // no multithreading
                                   &Ttitle,      // address of the shader-resource-view
                                   NULL);          // no multithreading

Also, just for good measure - although I'm certain it's fine, here are the vertices and their respective texture coordinates
        // Title
    {-200.0f, 100.0f, 0.0f, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), 0.0f, 1.0f},//13 BOTTOM LEFT
    {-200.0f, 200.0f, 0.0f, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), 0.0f, 0.0f},//14 TOP LEFT
    {200.0f, 100.0f, 0.0f, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), 1.0f, 1.0f},//15 BOTTOM RIGHT
    {200.0f, 200.0f, 0.0f, D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f), 1.0f, 0.0f},//16 TOP RIGHT

I have a feeling I'll be kicking myself.
Many thanks for any help I may receive, as well as apologies in case I'm still being too vague.
Answer: Seems you input layout is wrong:
D3D11_INPUT_ELEMENT_DESC ied[] =
{
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
    {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0},
};

For TEXCOORD replace 24 by 28, since color is 16 in size.
Comment: You are a wonderful person. I'd even go far as to say the wonderfullest. Thats a whole lot. Thanks ;)


python AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label'

Question: I can't seem to figure out why I can't update the label text.
But after a day... I figured I'd ask for help
self.balance_label['text'] = "Text updated" gives me: AttributeError: '_tkinter.tkapp' object has no attribute 'balance_label'
I'm using 2 separate script.
file 1
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import os.path

_script = sys.argv[0]
_location = os.path.dirname(_script)

import trade_helper_support

_bgcolor = '#d9d9d9'  # X11 color: 'gray85'
_fgcolor = '#000000'  # X11 color: 'black'
_compcolor = 'gray40' # X11 color: #666666
_ana1color = '#c3c3c3' # Closest X11 color: 'gray76'
_ana2color = 'beige' # X11 color: #f5f5dc
_tabfg1 = 'black'
_tabfg2 = 'black'
_tabbg1 = 'grey75'
_tabbg2 = 'grey89'
_bgmode = 'light'

class root:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''

        top.geometry("600x450+468+138")
        top.minsize(120, 1)
        top.maxsize(3844, 1061)
        top.resizable(1,  1)
        top.title("Trade Helper v1.0")
        top.configure(background="#d9d9d9")

        self.top = top

        self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
        top.configure(menu = self.menubar)

        self.Get_balance_button = tk.Button(self.top)
        self.Get_balance_button.place(relx=0.283, rely=0.689, height=44
                , width=127)
        self.Get_balance_button.configure(activebackground="beige")
        self.Get_balance_button.configure(activeforeground="black")
        self.Get_balance_button.configure(background="#e35e8c")
        self.Get_balance_button.configure(command=trade_helper_support.get_balance)
        self.Get_balance_button.configure(compound='left')
        self.Get_balance_button.configure(disabledforeground="#a3a3a3")
        self.Get_balance_button.configure(foreground="#000000")
        self.Get_balance_button.configure(highlightbackground="#d9d9d9")
        self.Get_balance_button.configure(highlightcolor="black")
        self.Get_balance_button.configure(pady="0")
        self.Get_balance_button.configure(text='''get balance''')

        self.balance_label = tk.Label(self.top)
        self.balance_label.place(relx=0.1, rely=0.711, height=31, width=74)
        self.balance_label.configure(anchor='w')
        self.balance_label.configure(background="#ffffff")
        self.balance_label.configure(compound='left')
        self.balance_label.configure(disabledforeground="#a3a3a3")
        self.balance_label.configure(foreground="#000000")
        self.balance_label.configure(text='''Balance''')

    def settext(self):
        print('here')
        self.balance_label['text'] = "Text updated"

def start_up():
    trade_helper_support.main()

if __name__ == '__main__':
    trade_helper_support.main()

file 2
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import trade_helper

def main(*args):
    '''Main entry point for the application.'''
    global root
    root = tk.Tk()
    root.protocol( 'WM_DELETE_WINDOW' , root.destroy)
    # Creates a toplevel widget.
    global _top1, _w1
    _top1 = root
    _w1 = trade_helper.root(_top1)
    root.mainloop()

def get_balance(*args):
    print('trade_helper_support.get_balance')
    trade_helper.root.settext(root)

    for arg in args:
        print ('    another arg:', arg)
    sys.stdout.flush()

if __name__ == '__main__':
    trade_helper.start_up()

I'd like the label text to change on button click.
It works when my function is inside the class but not the way I have it now.
i want file2 to to hold main code and file 1 to be the GUI only code
Answer: Finally found the solution...
def get_balance(*args):

    print('trade_helper_support.get_balance')
    _w1.balance_label['text'] = "Text updated"


Time Machine for Business Intelligence (PHP/MySQL)

Question: Currently I am developing a time machine for a open-source Business Intelligence software from scratch using PHP/MySQL.
My time-machine table is used by all other tables that need date info (such as orders, products, etc.) and they binding with time_id. So its MySQL table like this:
 time_id |  timestamp   | day  |  week  |  month  |  quarter
 1          1303689654    25      17       4         2
 2          1303813842    26      17       4         2
 ...

Order table binding like this:
order_id    |  time_id  ...
3123           2
...

edit: it's similar to STAR SCHEMA.
The problem is getting TIME (13:45) information as well. Usually I don't need this, but like orders, and sometimes a couple of tables need this HOUR/MINUTE infomation.
How can I solve this problem cleverly? I have a couple of solutions, but first i want to see your opinions..
Comment: Looks like a design flaw. making all other tables dependant on a time keeping table.. Do yourself a favor and replace time_id column with a simple timestamp. and add logic that parses that information to the individual components that you need.
Comment: @dino beytar: I think you don't get it, a date is just that, a date, not an object you would reference in a star schema. A starting point for a star schema would be the number of units sold on a specific date where the date is a timestamp or a datetime, and you store number of units and product id, which will in turn reference your products table, etc.
Comment: I don't understand the purpose of this. Why not just use a `DATETIME` field? You can extract all the other info (day, week, month...) from that.
Comment: @netbrain - I use this table for a real-time analysis (BI). So it's like start schema. So I have to do this.
Comment: @Pekka - it's similar to star schema (http://en.wikipedia.org/wiki/Star_schema)
Comment: +1 @wimvds - I know, you right. I just gave an example. It's not exactly a star schema; more than star schema. Fact tables already use it.
Answer: Why don't you simply store timestamps in your other tables?
Or, if you want to keep the dates table, simply add a TIME field to your other tables which need it.
Comment: +1 According to your solution, I don't need `TIMESTAMP` in my time-machine table anymore. I mean, I can use `Ymd` like (20110403) instead of TIMESTAMP. Because if I need time, I can get it from other tables. Thank you...
Answer: If I understand your timestamp correctly, you can probably just go:
echo date('H:i.s',1303689654);

edit
What are you trying to do? After re-reading your question you may be looking for the JOIN keyword in SQL (brief tute)
Comment: Oh ok.  Typically timestamps are unique to an individual operation, so ThiefMaster's answer is quite appropriate. +1
Comment: The problem is if you have more than one TIME in a day, so you have to create more than one timestamp for a day. But I shouldn't create more than one time for a day. So far, ThiefMaster's solution solve this problem.


Clojure Java Interop of Enum Normalizer.Form

Question: I'm having a heck of a time trying to figure out how to use the Java interop in Clojure to normalize Unicode. I've been trying to to use java.text.Normalizer, but I keep getting ClassNotFoundException when trying to call the enum Normalizer.Form.NFD.  Essentially, I'm just trying to do something like this in Java:
java.text.Normalizer.normalize("Ἑλλάς", java.text.Normalizer.Form.NFD);

I've been trying to do something like this in Clojure, but to no avail:
(import java.text.Normalizer)
(java.text.Normalizer/normalize "Ἑλλάς" java.text.Normalizer.Form/NFD)

Normalizer/normalize seems to be found ok, but getting at Normalizer.Form.NFD seems to be the problem as I keep getting the error:
Caused by java.lang.ClassNotFoundException java.text.Normalizer.Form
I'm working on Windows using: Clojure 1.8.0 and Java HotSpot(TM) 64-Bit Server VM 1.8.0_112-b15
I went ahead and tested it in regular Java and it works fine. So the class is installed on the system.  Can anyone show me what I'm doing wrong here?  Am I calling it incorrectly?  Is there something else I need to import perhaps?  Any advice is greatly appreciated.
Answer: This gives you trouble because Form is an inner class. In bytecode, a class outer.inner is actually represented as outer$inner. See more in this SO question, and this google group post.
(import java.text.Normalizer
        java.text.Normalizer$Form)
(java.text.Normalizer/normalize "Ἑλλάς" java.text.Normalizer$Form/NFD) ;; "Ἑλλάς"

Comment: Thank you so much! Yes, this works exactly as needed. Unfortunately, I didn't think to search for "static inner java class" after banging my head against this.  But in any case, thank you for the quick and clear response!
Comment: Glad I could help! if this answered your question, you should accept the answer :)
Comment: Done. Thank you again!


display none by default and visible on mouseover

Question: This is the CSS for the header DIV:
#header {
  display: block;
  float: left;
  min-width: 100%;
  min-height: 170px;
  height: auto;
  background-color: #030309;
  background-color: #191718;
  position:fixed;
  margin-top: -210px;
  z-index: 999999;
  opacity:.76;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
  top: 0;
}

and this is for the hover state:
#header:hover {
  display:block;
  opacity:1;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

What I want to make it so the header is hidden by default and appears when it's hovered. I've tried to add display: none on #header and display:block; on #header:hover but it's not working.
I've tried also with opacity:0; on #header and opacity:1; on #header:hover but it's not ok because the content beneath the header remains fixed  and it's not visible from top of the page.
Some suggestions?
Answer: "display: none;" means the element is removed from the document flow, so it's impossible to have a :hover state because there's nothing to hover-over.
Are you thinking of visibility: hidden; (effectively the same as opacity: 0;) instead?
Try adding outline: to your CSS to help you see the box in the document viewport so you know you're hovering over it for sure.
Comment: I've tried with visibility:hidden; but it remains that empty space and I don't want this, you can check [here](http://whiteandgold.ro/ipp/)
Answer: First you have a margin-top:-210px that is causing the header to be not visible but you're never moving it down to 0 on hover. Take that out. Then you can just set the opacity to 0 normally and 1 on hover and it'll fade it in on hover.
DEMO
Alternatively, if you want it to slide down, change the transition from just opacity to all and set a top:0 in the :hover state. You also need to set a height that is greater than the negative top margin so part of the element will be visible so the user can hover over it. I set it to 220px.
Relevant changes in CSS:
#header {
    top:-210px;
    height: 220px;
    -webkit-transition:all 1s ease-in-out;
    -moz-transition:all 1s ease-in-out;
    -o-transition:all 1s ease-in-out;
    -ms-transition:all 1s ease-in-out;
    transition:all 1s ease-in-out;
}

#header:hover {
    opacity:1;
    top:0px;
    -webkit-transition:all 1s ease-in-out;
    -moz-transition:all 1s ease-in-out;
    -o-transition:all 1s ease-in-out;
    -ms-transition:all 1s ease-in-out;
    transition:all 1s ease-in-out;
}

DEMO
Comment: I've tried with your code but I have the same problem, it remains empty space between the header and content. you can check [here](http://whiteandgold.ro/ipp/)
Answer: What you are trying to do, doesn't make sense - your header is not visible at first, so it can't be hovered. That's why it won't show up.
What you can do is:

Hide the block initially, like you did.
Wrap the #header element with another element. Lets say you are tagging it with the id #header-container.
Use the CSS: #header-container:hover #header { display: block; }

This will allow you to provide an element for the client to hover on in order to show the #header, while initially hiding it.


A student is applying to PhD program in Computer Sciences at Harvard and MIT.

Question:
A student is applying to PhD program in Computer Sciences at Harvard and MIT. He estimates that he has two to three chances of being accepted at Harvard and two out of five chances at MIT. He further estimates the probability that he will be accepted by both with probability of one to five. What is the probability that he is accepted by MIT if he is accepted by Harvard?

I think that the answer will be P(M|H)=(1/5)/(2/3)=0.3, but I'm confused about the condition of the problem. Why do we need to know that P(M)=2/5 if we don't use it? Or should I prove that the events are not independent before using the formula P(M|H)? So it would be P(M and H)=P(H)·P(M|H)=1/5=0.2
I'd really appreciate a piece of adivce. Thank you in advance!
Comment: Titles are great ways to give a taste of the mathematical content of a post. Yours is currently highly misleading, as it gives the distinct impression that the post is about applying to PhD programs rather than probability. I would strongly recommend rewriting the title.
Comment: You don't need to know independence, because the conditional probability formula is valid whether they are independent or not.
Comment: Moreover, this is a word-for-word copy of another question.  Five seconds with THE GOOGLE would have answered your question. :\
Answer: Notice that you get the same result for $P(M\mid H)$ from
$P(M \& H)=P(H) P(M\mid H)=1/5$
as you do from $P(M\mid H)=(1/5)/(2/3),$
since $P(H)=2/3$ is given in the problem statement.
Sometimes a problem will give you more information than you really need.
In real life you'll usually either have more than you need or not enough.
Don't worry about the "more than you need" case.


Determinate the minimal polynomial of $\sqrt{a}$ where a is an algebraic complex number over $\mathbb{Q}$

Question: I have the following exercise as homework, but is harder than i thought. There is a well know answer to this question?.
Suppose that $a$ is an algebraic complex number over $\mathbb{Q}$, prove that $\sqrt{a}$ is algebraic, and determine its minimal polynomial.
Comment: Welcome to the site. To avoid any mishaps I recommend that you take a look at [our guide for new askers](https://math.meta.stackexchange.com/q/9959/11619). When asking questions closely tied to homework assignments, the expectation is that questions should be accompanied by your own thoughts and/or other relevant context. In this case examples of cases where the procedure in Wuestenfux's answer fails would make a nice addition (given that you clearly are aware of the possibility).
Comment: This may feel unnatural in the sense that you may think it distracts from the question. However, we developed this policy because students copy/pasting their homework, asking for copy/pastable answers, presses the wrong buttons (and gives the site a bad reputation). Please take the measures to avoid giving the impression that you copy/paste assignments. Your questions will be much more warmly welcomed!
Answer: If $a$ is a zero of $f(x) = c_n x^n+\ldots+c_1x+c_0$ over $\Bbb Q$, then
$\sqrt a$ is a zero of $f(x^2)$, since $f((\sqrt a)^2) = f(a)=0$.
Comment: All that remains is the ability to test if $f(x^2)$ is irreducible. Any thoughts on that? :-)
Comment: When $\sqrt{a}$ is rational, the minimal polynomial is of degree 1, and there are cases  where minimal polynomial of $a$ and $\sqrt{a}$ have same degree and  $x$ has some odd exponents
Comment: Summary: This recipe gives the minimal polynomial if and only if $\sqrt{a}\notin\Bbb{Q}(a)$.
Comment: Yes, i have no trouble with that part. Finding the minimal polynomial is where i am stuck.
Comment: For example when $a=(1+\sqrt2)^2=3+2\sqrt2$, the polynomial $f(x^2)$ is not irreducible, because $\sqrt{a}$ also generates a quadratic extension, but $f(x^2)$ is quartic.
Comment: I think that If $a=\sqrt[3]{2}+i$ then, the minimal polynomial is $x^6+3x^4-4x^3+3x^2+12x+5$ but for $a^2$, the minimal polinomial is $x^6+6x^5+15x^4+12x^3+135x^2-114x+25$ and $a\notin Q(a^2)$. Is that correct ?


LXDE desktop installation

Question: How do I install the LXDE desktop environment? I have it installed in Ubuntu, but cannot figure out how to install it so that it can be used.
Comment: Your question isn't clear. You ask about how to install lxde in the first sentence but then say you have it installed in the second sentence. Could you please edit your question to explain what exactly your problem is?
Comment: May be, you have installed LXDE package, but did not install lubuntu-core? In this case, only lxde desktop will be available
Answer: The LXDE page in the Ubuntu Software Center contains 5 useful add-ons for LXDE including GUI login manager for LXDE (lxdm) and Easy-Mode launcher for netbook (lxlauncher). The LXDE add-ons can be installed by putting a check mark in the checkbox to the left of each add-on and then clicking on the Install button.
There are many possibilities for customization in the LXDE desktop including the package used to manage the internet connection, the LXDE Panel, the Desktop wallpaper and icon fonts. Take a look at this illustrated tutorial: How to Customize the LXDE Desktop.
Answer: On the Ubuntu Log In screen you'll see the Ubuntu icon besides (to the right of) your username and on top of the password box, click on the icon and then you'll see the different desktop environments available. Choose the one you prefer to use.

LXDE desktop installation


how to get the index and textview of the selected item in listview?

Question: i have a listview from webservice and i want to get the index and textview of the selected item .my list view is
         company                  symbol

         android                   an
         iphone                    ip
         blackderry                bb
            .                       .
            .                       .
            .                       .

so tell me how to get the index and textview of symbol in the listview from webservice.i used two methods
firstmethod:
protected void onListItemClick(ListView l, View v, int position,long id)
{
        super.onListItemClick( l, v, position, id);

        ID = id;

    int selectedPosition = l.getSelectedItemPosition();
        index=String.valueOf(selectedPosition);
         Log.e("index value","index"+index);

   TextView txt=(TextView)findViewById(R.id.symboltext);
        TextView temp=(TextView)v;
        txt.setText(temp.getText());
        Log.e("text",txt.toString());

}
in above code the logcat shows index is -1 and could not shows the txt.
Second method:
    listview.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
   {
    public void onItemSelected(AdapterView parentView, View childView, int position, long id)
    {
      String text = ((TextView)childView.getText()).toString();
      //The above text variable has the text value of selected item
      // position will reflect the index of selected item
    }
   public void onNothingSelected(AdapterView parentView)
   {
   }
});

in above method the listview didnt get onclick action. so please tell me how to get the index and textview of the selected item in listview.
Best Regards
Thanks in advance
Comment: Thank you for your response. I have search many forums but i didn't find answer. so please tell me the URL for that Forum.
Answer: Try this code. And Check your logcat. It should get you the desired result.
protected void onListItemClick(ListView l, View v, int position,long id)
{
        super.onListItemClick( l, v, position, id);

        ID = id;

       Log.e("index value","index"+position);
       TextView txt = (TextView) v.findViewById(R.id.symboltext);
       Log.e("text",txt.toString());

}

Answer: you can use a hashmap to put your string to a listview
this link will help you to understand how hashmap works and how the strings are saved and retrived from it
Answer: I was trying something like this, on a Custom ListView:

My scenario was:
To fetch three Objects from Server with JSONArrayRequest named as:
ID (tvLvDocID)
Title (tvLvDocTitle)
Sub Title (tvLvDocSub Title)

ID is actually the ID of the column of item in MySQL database.
What I did was:
listViewDoc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                    int myPosition = position;

                                    String id_doc_from_lv = listViewDoc.getItemAtPosition(myPosition).toString();
                                    Toast.makeText(getApplicationContext(), "ID is : " + id_doc_from_lv, Toast.LENGTH_LONG).show();

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

But My problem was that it was returning Title of the Custom ListView.
And I wanted only and only the ID, which I was also showing in ListView above Title. (Its another story I will later apply INVISIBLE property to that ID).
As I wanted only ID. So I did toke help from this answer:
When I add these lines in my code:
String tv_ID_Str= ((TextView)view.findViewById(R.id.tvLvDocID)).getText().toString();

And call this tv_ID_Str as:
Toast.makeText(getApplicationContext(), "ID is : " + tv_ID_Str, Toast.LENGTH_LONG).show();

Aha! Now I can successfully show tvLvDocID and I can retrieve all the information from database on this ID.
Final code looks like this:
listViewDoc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                    int myPosition = position;

                                    String id_doc_from_lv = listViewDoc.getItemAtPosition(myPosition).toString();
                                    // selected item
                                    String tv_ID_Str = ((TextView)view.findViewById(R.id.tvLvDocID)).getText().toString();

                                    Toast.makeText(getApplicationContext(), "ID is : " + tv_ID_Str, Toast.LENGTH_LONG).show();

                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

Purpose of my answer is people like me, who spend lot of time to do this. I hope this will help someone.


Find the volume of the solid bounded below by the circular cone and above the sphere

Question:
I'm asked to find the volume of the solid bounded below by the circular cone
$$z= 1.5\sqrt(x^2+y^2)
$$and above the sphere
$$ x^2+y^2+z^2=7.5z.
$$
I tried to solve this using spherical coordinates, which gave me the bounds
$$
0 <= \rho <= 7.5 cos(\phi)
$$
$$
0 <= \phi <= arccot(1.5)
$$
$$
0<= \theta <= 2\pi
$$
Are my bounds correct?
Answer: The spherical coordinates:
$$x= \rho \cos(\theta)\sin(\phi)$$
$$y= \rho \sin(\theta)\sin(\phi)$$
$$z= \rho \cos(\phi)$$
We have
$$x^2+y^2+z^2\leq7.5z \Rightarrow 0 \leq \rho \leq 7.5 \cos(\phi)$$
$$1.5\sqrt{x^2+y^2}=z \Rightarrow 1.5\sqrt{\rho^2 \sin^2(\phi)}=\rho \cos(\phi)\Leftrightarrow \operatorname{ctg}(\phi)=1.5 $$
We have to find volume of the solid BELOW $z=1.5\sqrt{x^2+y^2}$ and ABOVE $x^2+y^2+z^2\leq7.5z$, so for azimuthal angle $\phi$ we have
$$\operatorname{arcctg}(1.5) \leq \phi \leq \frac{\pi}{2},$$ and
$$0 \leq \theta \leq 2 \pi.$$
P.S In case we have to find volume of the solid ABOVE $z=1.5\sqrt{x^2+y^2}$ and BELOW $x^2+y^2+z^2\leq7.5z$ , then $0 \leq \phi \leq \operatorname{arcctg}(1.5)$.


Override a method in Mapper class or customer mapper or attribute mapping- Spring Boot

Question: I have the following DTO,Entity,Mapper classes that persist value in database.I am facing issues in one of those attributes which is of Date column. I input a string in "DD-MM-yyyy" format. However it fails in the mapper class saying its an unparseable date. Am not sure why there is no default date format in the compile time generated class
Database structure

DTO
public class CcarRepWfInstDTO implements Serializable {

private Long id;

private Long reportId;

private Long workflowInstanceId;

private String cobDate;

private String frequency;

private String runType;

private String reportVersion;

private String workflowStatus;

}

Entity
@Data
@Entity(name = "CcarReportWorkflowInstance")
@Table(name = "CCAR_REPORT_WORKFLOW_INSTANCE")
public class CcarReportWorkflowInstance implements Serializable {
private static final long serialVersionUID = 1L;

@SequenceGenerator(name = "CCAR_REPORT_WORKFLOW_INSTANCESEQ", sequenceName = "SEQ_CCAR_REPORT_WF_INST_ID", allocationSize = 1)
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CCAR_REPORT_WORKFLOW_INSTANCESEQ")
private Long id;

@Column(name = "WORKFLOW_INSTANCE_ID", nullable = false)
private Long workflowInstanceId;

@Column(name = "COB_DATE", nullable = false)
@Temporal(TemporalType.DATE)
private Date cobDate;

@Column(name = "FREQUENCY", nullable = false)
private String frequency;

@Column(name = "RUN_TYPE", nullable = false)
private String runType;

@Column(name = "REPORT_VERSION", nullable = false)
private String reportVersion;

@Column(name = "TERMINATION_STATUS", nullable = false)
private String terminationStatus;

@Version
@Column(name = "VERSION", columnDefinition = "integer DEFAULT 0", nullable = false)
private Long version = 0L;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "REPORT_ID", nullable = false, insertable = false, updatable = false)
private CcarReport ccarReport;

@Column(name = "REPORT_ID")
private Long reportId;

Snippet from the Mapper Implementation class generated during compile time which is failing and throwing back error saying unparseable date
    @Override
 public CcarReportWorkflowInstance ccarRepWfInstDTOToCcarRepWfInst(CcarRepWfInstDTO ccarRepWfInstDTO) {
    if ( ccarRepWfInstDTO == null ) {
        return null;
    }

    CcarReportWorkflowInstance ccarReportWorkflowInstance = new CcarReportWorkflowInstance();

    ccarReportWorkflowInstance.setId( ccarRepWfInstDTO.getId() );
    ccarReportWorkflowInstance.setWorkflowInstanceId( ccarRepWfInstDTO.getWorkflowInstanceId() );
    if ( ccarRepWfInstDTO.getCobDate() != null ) {
        try {
            ccarReportWorkflowInstance.setCobDate( new SimpleDateFormat().parse( ccarRepWfInstDTO.getCobDate() ) );
        }
        catch ( ParseException e ) {
            throw new RuntimeException( e );
        }
    }
    ccarReportWorkflowInstance.setFrequency( ccarRepWfInstDTO.getFrequency() );
    ccarReportWorkflowInstance.setRunType( ccarRepWfInstDTO.getRunType() );
    ccarReportWorkflowInstance.setReportVersion( ccarRepWfInstDTO.getReportVersion() );
    ccarReportWorkflowInstance.setReportId( ccarRepWfInstDTO.getReportId() );

    return ccarReportWorkflowInstance;
}

Code in the service layer which uses mapper class and fails
private void persistWfInst(CcarRepWfInstDTO ccarRepWfInstDTO) {

    try {
        ccarRepWfInstDTO.setWorkflowInstanceId(ccarRepWfInstDTO.getWorkflowInstanceId());
        CcarReportWorkflowInstance ccarReportWorkflowInstance = ccarRepWfInstMapper.ccarRepWfInstDTOToCcarRepWfInst(ccarRepWfInstDTO);
        ccarRepWfInstRepository.save(ccarReportWorkflowInstance);
    } catch (Exception e) {
        log.info("Exception while saving workflow instance information =" + e);
        throw new CustomParameterizedException(e.getMessage());
    }
}

Custom code in the service layer without using mapper which uses explicitly defined simpledate format which is working fine. Please advise as to how to fix this and use Spring boot way stack since my whole applications is designed around it. It wont be good If I do not use the default supplied mapper class and implementation.
private void persistWfInst(CcarRepWfInstDTO ccarRepWfInstDTO) {

    try {
        ccarRepWfInstDTO.setWorkflowInstanceId(ccarRepWfInstDTO.getWorkflowInstanceId());
        CcarReportWorkflowInstance ccarReportWorkflowInstance = new CcarReportWorkflowInstance();
        ccarReportWorkflowInstance.setId(ccarRepWfInstDTO.getId());
        ccarReportWorkflowInstance.setWorkflowInstanceId(ccarRepWfInstDTO.getWorkflowInstanceId());
        if (ccarRepWfInstDTO.getCobDate() != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("DD-MM-yyyy");
                ccarReportWorkflowInstance.setCobDate(sdf.parse(ccarRepWfInstDTO.getCobDate()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        ccarReportWorkflowInstance.setFrequency(ccarRepWfInstDTO.getFrequency());
        ccarReportWorkflowInstance.setRunType(ccarRepWfInstDTO.getRunType());
        ccarReportWorkflowInstance.setReportVersion(ccarRepWfInstDTO.getReportVersion());
        ccarReportWorkflowInstance.setReportId(ccarRepWfInstDTO.getReportId());
        ccarRepWfInstRepository.save(ccarReportWorkflowInstance);
    } catch (Exception e) {
        log.info("Exception while saving workflow instance information =" + e);
        throw new CustomParameterizedException(e.getMessage());
    }
}

Comment: I see cobDate is a String but you have added @Temporal to a String field. Can you change the cobDate to Date and try?
Comment: @Isiva my database column is of date datatype.Updating the question. I cannot make it a string and I am supposed to store it as date
Comment: I was asking if you could change CcarRepWfInstDTO -> cobDate field to Date. The reason I was aking is by documentauion @Temporal annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar.
Comment: @lsiva Earlier I was doing that only. I was parsing the incomoing json using jackson mapper and it was completely breaking my code. Please find a post below which explains the issue I was facing and hence I reverted back to normal string http://stackoverflow.com/questions/38564154/store-date-from-ui-to-database-using-restful-webservice?noredirect=1#comment64523155_38564154
Comment: @lsiva Hope this clarifies and explains.
Answer: The mapping logic missed the date format. This can be defined in mapstruct like this:
@Mapping(target = "cobDate", source = "cobDate", dateFormat = "DD-MM-yyyy")
CcarReportWorkflowInstance convert(CcarRepWfInstDTO ccarRepWfInstDTO);


Is there a more efficient way to store an n-ary tree in a file in C?

Question: Say I'm writing an adventure game.  The map is built of tiles of different types.  I have tiles that form paths, and tiles that form doors, and so on.
I will use a struct to describe the type and content of a tile, and to which other tiles it connects.
Then I'll make a quadruple-linked list to connect them all together.
But a struct that will describe a room will have far more elements than one that will describe a door, so many elements in a door struct will be redundant.  I could make a smaller door struct, but structs can only point to structs of the same type*, so I couldn't connect a room struct to a door struct.  The redundancy may be negligible but I wondered if there's another way.
Another option is using an array of structs, but then I'd have lots of 'padding' structs wasting even more space.  However an array would make reading and re-building a map from file much easier.
Is there any way around the limitation that a struct can only point to a struct of the same type?  Or is there another common solution to this problem that I haven't mentioned?
One idea I had was that each tile could have pointers for every other type of tile.  Some would be redundant, but it would be a lesser redundancy that the option above.
*By this I mean that typically in a linked list, structs contain pointers to struct of the same type that they're in.
Comment: Structs can point to objects of any type. Why do you say that they can "only point to a struct of the same type"?
Comment: @Marc Typically in a linked list, each struct has a pointer to the same type of struct in which it exists.  That's what I meant.  In my case, I have different types of structs.
Answer: Instead of storing elements in a tile, store only a pointer to the linked list of elements.
Answer: You really don't have to have a uniform struct describing everything. Instead, you could do the following (this is somewhat like writing your own C++ virtual tables in C, and is very widely used).
Your basic tile struct can look like this:
struct tile
{
    // common tile stuff
    ...
    enum tile_type type;
    void *type_info;
};

So in this struct you store stuff that's common to every tile type. Then you make other structs for other types: one for a room, one for a path, etc. Within an object of tile, you make the enum describe the actual type, and store a pointer to the concrete type within the void *.

There are many links describing variations of this technique. Here's one.
Comment: That's a good idea.  I'd still need to somehow index elements after reading from a file, but I hadn't even thought about using void pointers.  Thanks! :)


$|f(\frac{1}{2})|\leq \int_{0}^{1}|f(t)|dt+\frac{1}{2}\int_{0}^{1}|f'(t)|dt$

Question: Let $f'\in\mathcal{R}[0,1]$ then prove the above inequality.
Try : What I have found till now is that
$$\left|\frac{f(1)+f(0)}{2}\right|\leq \int_{0}^{1}|f(t)|dt+\frac{1}{2}\int_{0}^{1}|f'(t)|dt$$ and $$\left|\frac{f(1)}{2}\right|\leq \int_{0}^{1}\left|f(t)\right|dt+\frac{1}{2}\int_{0}^{1}|f'(t)|dt.$$
By using the integral $\int tf(t)dt$ and $\int (1-t)f(t)dt$. But I don't understand is that how do I get the $f(\frac{1}{2})$?
Comment: Are you assuming $f$ is continuous? Otherwise we can redefine $f(1/2)$ to be arbitrarily large and this doesn't affect the integrals.
Comment: @LuizCordeiro well it's differentiable, so of course continuous.
Comment: @OpenBall I'm asking since the usual results hold for functions which are only differentiable a.e., or Lebesgue integrable, etc... It wasn't clear that this is the classical derivative. Anyway, from my previous comment we see that there should be some kind of approximation argument involved, maybe something similar to the first inequality you obtained.
Comment: Here $f'$ is riemann integrable and the primitive is $f$. I cant find any inequality that gives $f(1/2)$
Answer: Your idea is essentially right, we just need to use different boundaries and integration by parts:
$$\int_0^{1/2}tf'(t)dt=[tf(t)]^{1/2}_0-\int_0^{1/2}f(t)dt$$
so
$$\frac{f(1/2)}{2}=\int_0^{1/2}f(t)dt+\int_0^{1/2}tf'(t)dt.\tag{1}$$
Now do the same analysis with $g(t)=f(1-t)$:
$$\frac{f(1/2)}{2}=\frac{g(1/2)}{2}=\int_0^{1/2}g(t)dt+\int_0^{1/2}tg'(t)dt=\int_{1/2}^1f(t)dt+\int_{1/2}^1(1-t)f'(t)dt\tag{2}$$
Add (1) and (2):
\begin{align*}
|f(1/2)|&=|\int_0^1 f(t)dt+\int_0^{1/2}tf'(t)dt+\int_{1/2}^1(1-t)f'(t)dt|\\
&\leq\int_0^1|f(t)|dt+\int_0^{1/2}|t||f'(t)|dt+\int_{1/2}^1|1-t||f'(t)|dt\\
&\leq\int_0^1|f(t)|dt+\frac{1}{2}\int_0^1|f'(t)|dt
\end{align*}


I have error in a transformation saying Couldn't get row from result set and Unable to get value 'Date' from database resultset, index 2

Question: 2016/11/14 09:18:07 - installment.0 - ERROR (version 184.108.40.206, build 1 from 2014-06-19_19-02-57 by buildguy) : Unexpected error
2016/11/14 09:18:07 - installment.0 - ERROR (version 188.8.131.52, build 1 from 2014-06-19_19-02-57 by buildguy) : org.pentaho.di.core.exception.KettleDatabaseException:
2016/11/14 09:18:07 - installment.0 - Couldn't get row from result set
2016/11/14 09:18:07 - installment.0 -
2016/11/14 09:18:07 - installment.0 - Unable to get value 'Date' from database resultset, index 2
2016/11/14 09:18:07 - installment.0 - Value '7614399astanton0000-00-00 00:00:00scriptps2016-11-10 13:47:3600ûû12016-11-11 00:00:00  225.490000.00000    225.49000ûOPNû6228638ûEPP

Comment: Whats the question?
Answer: This line is pretty clearly says:
2016/11/14 09:18:07 - installment.0 -
2016/11/14 09:18:07 - installment.0 - Unable to get value 'Date' from database resultset, index 2
2016/11/14 09:18:07 - installment.0 - Value '7614399astanton0000-00-00 00:00:00scriptps2016-11-10 13:47:3600ûû12016-11-11 00:00:00  225.490000.00000    225.49000ûOPNû6228638ûEPP

That you have error converting (values in row starting from 0)
13:47:3600ûû12016-11-11 00:00:00

..to a Date value. You have to specify correct date conversion mask. Also characters like
ûû1

hint that most probably you have also incorrect encoding trouble.


What do you need to know to do the following integral

Question: Integrate $$\int_{-\infty}^{\infty} \cos(\sqrt{2} x)e^{-x^2} dx$$
All i want to know is how to proceed. I have been stuck at this for a very long time now.
I tried writing the $\cos$ term as exponentials using Euler's formula and then to integrate the product term but I don't know how to integrate that either.
Comment: by parts... https://en.wikipedia.org/wiki/Integration_by_parts
Comment: As this is a purely math question, this question might belong better on the math stack exchange.
Comment: Does that square root extend over x, or just over the 2?
Comment: @enumaris just over 2
Comment: @JMLCarter i tried that. couldn't get anywhere. can you please show me how you would do it. i used wofram alpha on this integral and got √(π/e). i have no idea how to connect these two dots.
Comment: @enumaris the only reason i asked it here was because i got this question on a physics entrance exam. i assumed asking a physics person was the way to go. sorry if it caused inconvenience in any way.
Comment: Can you add your attempt or describe where you got stuck. The site has rules about homework like questions
Comment: @JMLCarter i too wanted to describe how i proceeded but i dont know how to type all that here. i am really new to this. i'll try to learn how to and edit my question as soon as i can. thanks
Comment: use Latex, for example as I edited into your post. More here https://tex.stackexchange.com/
Comment: Or by rewriting the cosine using the Euler formula and then completing the square.
Comment: @UjjwalBarman I missed your part about already having used the Euler formula: The next step is to complete the square to write the exponentials as something like $e^{-(a+x)^2 + b}$ ($a$ will be complex) and then using the fact, that we can deform the integration path in the complex plane as long as we do not cross poles so that integrating over $e^{-(a+x)^2}$ is the same as integrating over $e^{-x^2}$ (from $-\infty$ to $\infty$).
Comment: @Sebastian Riese. thanks a looooooooottttttt. You're amazing. i got the answer. hey can you suggest a book so that i can better my integration skills. thanks again.
Comment: Only German ones (if that helps). But even so, I learnt most about integration from doing the exercises in the introductory maths and physics courses. So I can't point to a comprehensive source.
Comment: thanks. i'll try the same. Keep up the good work.
Answer: All you need is the real part of
$$ \int_{-\infty}^{+\infty}\exp\left[-\left(x^2-i\sqrt{2}x\right)\right]\,dx \stackrel{x\mapsto x+\frac{i}{\sqrt{2}}}{=}\int_{-\infty}^{+\infty}\exp\left[-\left(x^2+\frac{1}{2}\right)\right]\,dx=\color{blue}{\sqrt{\frac{\pi}{e}}}.$$


Service fabric stateful service partitioned - well distributed

Question: Imagine we want to have a stateful service partitioned by range of points,
with the goal of sorting each partition by points (in general, we want to divide the sort task among partitions). We would like to have users well distributed among partitions.
The ideal would be to change the range of each partition while users' points change. But it is not possible, because we cannot change the range of a partition dynamically.
One idea would be to have a single stateful service which would manage the ranges of points and would use a map to tell other services which partition should be requested for specific points. But this may mean lots of accesses to this new service, which may overload the service.
Are there any better ideas?
Edit 1:
Goal 1: To have rankings sorted by sorted-blocks (partitions), which would be aggregated by another service.
Goal 2: To provide a provisional position for a given amount of points.
Comment: So this is points like as in earned points in a game? And you want the highest points ones in a single partition? I'm not sure that would work well, as the highest points ones are also likely to be the highest users, so grouping them together seems counterproductive in terms of load balancing
Comment: @EricLizotte Yes, it is like earned points in a game. The highscore is not obtained directly from this service. The complete score table (not only the top users) would be calculated using this partitioned service but provided in another way. The partitioned service will only be accessed to (1) save updated user points and (2) to get the provisional position for specific amount of points.
Comment: I see what you are getting at now, you'd like the partitions to be by score range so that its easier to query against. It would make more sense to have the scores persisted to a sql table that has the user id + score as the only columns with both indexed, and have the servers query + update that. The primary use for partitions is for load spread and scaling, rather than grouping. I don't see any architectural benefit from having the partitions be based on score.
Trying to partition on score would actually slow performance, as users would perpetually be moving from partition to partition.
Comment: The other way, if you're determined to do it this way is to pre-decide your number of partitions, but rather than having them be by actual score #, its by percentage of maximum score. so with 10 partitions it would be top score to 91%, 90% to 81, etc. The compute cost of moving users partition to partition as that changes would be heavy.
Comment: Otherwise you could only really take what you think to be a reasonable grouping of scores, make your initial set with the partition bands that wide and have the score updates flow through another service that would add the next higher group of scores as a new partition. I still think this is an anti-pattern for partitioning though.
Comment: @EricLizotte Thanks for the hints. The possibilities will be analysed and tested. If an interesting decision is taken, I will share.
Comment: It was decided to skip the partitioning in this case. The sort will be handled in a single stateful service.
Answer: I recommend you partition the service by userid. For example, take modulo partitioncount of userid to determine the partition index.
This way a user can always be found in a predictable partition, and your users will be distributed well (provided you have many more users than partitions).
You can use a pub/sub mechanism to publish changing scores to a different (stateless) service, to hold a view of current highscores.
Comment: I just updated the question with the final goals. Partitioning the service by user ID would not fit to my solution.


Xdebug / Vim / getting it to work

Question: So I have tried following multiple tutorials to get xdebug to work on my development server. The best one I have found so far is this.
I have installed xdebug and it shows correctly in my phpinfo(). I have installed https://github.com/joonty/vdebug and when I hit F5 it works great. The problem is I then go to my dev server ip address like so "http:///?XDEBUG_SESSION_START=1" and it doesn't trip anything. My vim xdebug just times out.
I have set up my php.ini file the following way:
zend_extension=/usr/lib/php5/20090626/xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

I can't seem to figure out why this is happening. Any help would be appreciated.
Answer: I have these settings in my debug.ini
0 zend_extension=xdebug.so
1 xdebug.remote_enable=on
2 xdebug.remote_handler=dbgp
3 xdebug.remote_host=localhost
4 xdebug.remote_port=9000
5
6 xdebug.profiler_output_dir="/tmp"
7 xdebug.profiler_append=0
8 xdebug.profiler_enable_trigger=On
9 xdebug.profiler_output_name="%H-%u.trace"
10
11 xdebug.profiler_enable=0
12 xdebug.remote_autostart=1
13 xdebug.max_nesting_level=200

The profiler stuff is non-relevant, but remote_autostart might help you.
Comment: I added that in except i kept my `zend_extension=` since mine is in a different directory and still the same issue. Can't seem to kick off the debug session
Comment: Have you enabled the xdebug mod (OS dependant I guess)? Is the .so file readable by the web-server user (OS dependant)? Does xdebug show on phpinfo as loading correctly? Maybe you should take a step back from vim/vdebug and make sure xdebug is running first.
Comment: This answer actually worked. I forgot to reset my apache server but once I did it worked. I am thinking that it was actually the remote_handler=dbgp setting but I haven't tested it.
Comment: Of course - I forgot the classic 'did you restart apache' ;-)

Xdebug / Vim / getting it to work


Python, how to put 32-bit integer into byte array

Question: I usually perform things like this in C++, but I'm using python to write a quick script and I've run into a wall.
If I have a binary list (or whatever python stores the result of an "fread" in).  I can access the individual bytes in it with: buffer[0], buffer[1], etc.
I need to change the bytes [8-11] to hold a new 32-bit file-size (read: there's already a filesize there, I need to update it).  In C++ I would just get a pointer to the location and cast it to store the integer, but with python I suddenly realized I have no idea how to do something like this.
How can I update 4 bytes in my buffer at a specific location to hold the value of an integer in python?
EDIT
I'm going to add more because I can't seem to figure it out from the solutions (though I can see they're on the right track).
First of all, I'm on python 2.4 (and can't upgrade, big corporation servers) - so that apparently limits my options.  Sorry for not mentioning that earlier, I wasn't aware it had so many less features.
Secondly, let's make this ultra-simple.
Lets say I have a binary file named 'myfile.binary' with the five-byte contents '4C53535353' in hex - this equates to the ascii representations for letters "L and 4xS" being alone in the file.
If I do:
f = open('myfile.binary', 'rb')
contents = f.read(5)

contents should (from Sven Marnach's answer) hold a five-byte immutable string.
Using Python 2.4 facilities only, how could I change the 4 S's held in 'contents' to an arbitrary integer value? I.e. give me a line of code that can make byte indices contents [1-4] contain the 32-bit integer 'myint' with value 12345678910.
Comment: You cannot change the contents since the string is immutable ... you can create a new string, or use a mutable container like bytearray.
Comment: Thanks, I'm happy to create a new string or byte array if that's the case.  How could I create a modifiable byte array with the same contnets, and update the range [1-4] of that to equal the binary representation of my integer?
Comment: I extended my posting below and included a working example for Python 2.4 :-)
Answer: What you need is this function:
struct.pack_into(fmt, buffer, offset, v1, v2, ...)

It's documented at http://docs.python.org/library/struct.html near the top.
Example code:
import struct
import ctypes

data=ctypes.create_string_buffer(10)
struct.pack_into(">i", data, 5, 0x12345678)
print list(data)

Similar posting: Python: How to pack different types of data into a string buffer using struct.pack_into
EDIT: Added a Python 2.4 compatible example:
import struct

f=open('myfile.binary', 'rb')
contents=f.read(5)
data=list(contents)
data[0:4]=struct.pack(">i", 0x12345678)
print data

Comment: +1. I'd suggest to use the built-in `bytearray` to create the mutable buffer instead of `ctypes.create_string_buffer`.
Comment: I'm afraid your 2.4 compatible version can't use `bytearray` as it was introduced in 2.6.
Comment: **For everyone** I tried working it out by reading the pack page and the solutions provided.  I seem to be missing alot since I have python 2.4 instead of 2.5. I provided a greatly simplified version of my problem in an edit to my post above - if you can answer that with a line of code, I'll be completely happy :)
Comment: Hmmm. That's true, I only avoided the pack_into function ... embarassing. Let's see what was there in 2.4 :)
Comment: Ok I think now it works, tried it on a VM with Python 2.4. Other objections?
Answer: Have a look at Struct module. You need pack function.
EDIT:
The code:
import struct

s = "LSSSS" # your string
s = s[0] + struct.pack('<I', 1234567891) # note "shorter" constant than in your example
print s

Output:
L╙☻ЦI

struct.pack should be available in Python2.4.
Your number "12345678910" cannot be packed into 4 bytes, I shortened it a bit.
Comment: *see comment on hochl's answer*
Answer: The result of file.read() is a string in Python, and it is immutable.  Depending on the context of the task you are trying to accomplish, there are different solutions to the problem.
One is using the array module: Read the file directly as an array of 32-bit integers.  You can modify this array and write it back to the file.
with open("filename") as f:
    f.seek(0, 2)
    size = f.tell()
    f.seek(0)
    data = array.array("i")
    assert data.itemsize == 4
    data.fromfile(f, size // 4)
data[2] = new_value
# use data.tofile(g) to write the data back to a new file g

Comment: *see comment on hochl's answer*
Answer: You could install the  numpy module, which is often used for scientific computing.
read_data = numpy.fromfile(file=id, dtype=numpy.uint32)
Then access the data at the desired location and make your changes.
Comment: *see comment on hochl's answer*
Answer: The following is just a demonstration for you to understand what really happens when the four bytes are converted into an integer.
Suppose you have a number: 15213
Decimal: 15213
Binary: 0011 1011 0110 1101
Hex: 3 B 6 D

On little-endian systems (i.e x86 machines), this number can be represented using a length-4 bytearray as: b"\x6d\x3b\x00\x00" or b"m;\x00\x00" when you print it on the screen, to convert the four bytes into an integer, we simply do a bit of base conversion, which in this case, is:
sum(n*(256**i) for i,n in enumerate(b"\x6d\x3b\x00\x00"))

This gives you the result: 15213


aaa_helper.rb is automatically included in aaa_controller.rb?

Question: I have the following question: typing rails new generate controller Comments rails generates a controller file named comments_controller.rb and a file named comments_helpers.rb, now the question is: the module in the comments_helpers file is automatically included in my CommentsController class or not?
Answer: comments_helper.rb will be included in the CommentsController's views, not the controller actions itself.
You can define a method in CommentsController that's also accessible to views with the helper_method method by putting it in your controller:
def super_useful_helper_method
   ...
end

helper_method :super_useful_helper_method


Is there any way to make chrome support VP9 and H.265(HEVC) on WebRTC?

Question: I'm new to WebRTC. As VP9 can decrease the bandwidth, but I don't see any options to choose VP9 with the recent release Chrome 43.0 during a WebRTC session on Windows. The SDP video options don't include VP9 at all. Could someone show me how to enable VP9 for WebRTC? A lot of articles indicate VP9 has been ready.
Another question, is there a way to add H.265 encoder/decoder to the system and let WebRTC stack of Chrome be aware of it?
Comment: You cannot add encoders to chrome that it does not natively support. Even if you enable Vp9 on the browser, you will have to see if you can modify the SDP to include it as an option(edit it manually before setting it as the localdescription and then sending it to the peer) but that may not work as the underlying parser could not support utilizing that encoder.
Answer: You can enable Chrome for VP9 by passing the flag,
--enable-webrtc-vp9-support

To enable flags on Windows,

Right click on Chrome
Select "Properties"
At the end of the target line, add the above flag, so it will be running like, chrome.exe --enable-webrtc-vp9-support

As far as I know, the HEVC/H.265 RTP payload packetization/parsing is not implemented yet for WebRTC.


which client ports are used by rtspsrc if it not specified on the port-range property

Question: I have a request from the network guy which RTSP client ports are used by the rtspsrc?
We didn't set the port-range property on the rtspsrc element.
Can anybody tell me which ports are used the rtspsrc if this property is not set? (TCP/UDP).
Is there any min max by default or is it the whole range from 1 - 65535.
Thank you
Answer: I believe this is just the OS specific, dynamic port range.  For example on Linux this would be:
cat /proc/sys/net/ipv4/ip_local_port_range
32768   60999

I have no idea how up to date this is, but seems to be generally correct:
https://www.ncftp.com/ncftpd/doc/misc/ephemeral_ports.html
Now, your network admin is probably not going to want to map every single high level port (32768->60999) to your one service.  What you'll probably want to do is go ahead and use the port-range property (say 33050->33060) and pass that range over to your network admin.  Ask them to create a firewall rule to map that public range of ports to your machine.  You should probably only need a few ports for each stream you use.
To perhaps kinda visualize this, say you ask for the above port range:
PUBLIC RTSP SERVER "sometestsrv.com"
554 //initial call to handshake for RTSP made here
50000 //RTP port for client 1 (somecompany.com:33050)
50001 //RTCP port for client 1 (somecompany.com:33051)
50100 //RTP port for client 2
50101 //RTCP port for client 2
...

PUBLIC IP FOR YOUR COMPANY "somecompany.com"
33050 //RTP port matching sometestsrv.com:50000
33051 //RTCP port matching sometestsrv.com:50001

YOUR SERVER "192.168.1.33" w/rtspsrc INSIDE "somecompany.com"
33050 //RTP port matching sometestsrv.com:50000
33051 //RTCP port matching sometestsrv.com:50001


Having trouble understanding cmpsb in the following example

Question: I am following a tutorial on operating systems and I came across the following block code which is checking filenames on a disk against my variable "ImageName".
My confusion arises from the push di line before rep cmpsb.
    mov       cx, WORD [bpbRootEntries]
    mov       di, 0x0200
.LOOP:
    push      cx
    mov       cx, 0x000B
    mov       si, ImageName
    push      di
    rep  cmpsb
    pop       di
    je        LOAD_FAT
    pop       cx
    add       di, 0x0020
    loop      .LOOP
    jmp       FAILURE

The documentation I have found for cmpsb states "For legacy mode, compare byte at address DS:(E)SI with byte at address ES:(E)DI. The status flags are set accordingly." Wouldn't pushing di before this call mean that I am always comparing against an empty value? The code works so I am obviously misunderstanding something, but every piece of documentation I can find implies that this code shouldn't work.
Comment: `push di` has no effect on `di`.
Comment: OOOOOH, ive been operating under that assumption for way to long haha, clears up all my confusion, thanks!
Comment: I'd suggest single-stepping it in a debugger (e.g. BOCHS) to find out where your assumptions are wrong.  IDK why you think saving/restoring DI with push/pop would leave it "empty", but that's not what push does.  Registers can't be "empty", they always have some value.
Answer: The rep cmpsb instruction will leave di pointing after the location where the two strings differ.  Since this code does not care about that position (just if the two strings match), we throw out where the difference lies and just check the Z flag to see if we matched.  If we don't match, we advance di far enough to get to the next file name, which is a constant since we reset di back to where we started.
Comment: Most programmers would prefer to see `REPE CMPSB`. Better distinction from `REPNE CMPSB`.
Comment: aren't i comparing si to di though? does pushing a register not clear its value?
Comment: @ouchqt Pushing a register just copies its value to the stack to preserve it, so it can be restored later with a `pop`.
Comment: ahh, i'm not sure where i got that from then but thank you! a lot of things ive seen just started making sense haha


Pandas groupby mark dates less than n months

Question: So in this example, col1 has 2 different categories. How would one be able to compute those categories that satisfy if we say n months = 12, so that a new column would mark category A as True, but cat B as false since it is greater than n=12 months.
d_ex = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'A'],
                     'col2': ['2019-01-01', '2018-02-01',
                             '2015-01-01', '2019-01-01', '2019-05-01']})

d_ex['col2'] = pd.to_datetime(d_ex['col2'])

I tried
d_ex.groupby(['col1'])['col2'].diff()

but this does not work. Also there can be more than two occurences of the category, so if there was a third category A with a date of 2015, I would like that marked as False but the other two still true.
I found this but I am not sure how to change the code to not use idxmax
Calculating the difference in dates in a Pandas GroupBy object
Trying the solution given
(d_ex.groupby('col1')['col2'].diff().apply(lambda x: my_abs(x))
.apply(lambda x: set_condition(x)).bfill())

returns
0     True
1     True
2    False
3    False
4    False

but index 4 should be True
Answer: Create the dataframe:
import pandas as pd

d_ex = pd.DataFrame({'col1': ['A', 'A', 'B', 'B', 'A'],
                     'col2': ['2019-01-01', '2018-02-01',
                              '2015-01-01', '2019-01-01', '2019-05-01']})

d_ex['col2'] = pd.to_datetime(d_ex['col2'])

# Sort the columns
d_ex.sort_values(['col1', 'col2'], inplace=True)

col1       col2
   A 2018-02-01
   A 2019-01-01
   A 2019-05-01
   B 2015-01-01
   B 2019-01-01

Groupby Diff:

diff returns a timedelta object for each group

NaT always for the first occurrence within a group

d_ex['diff'] = d_ex.groupby('col1').diff()

col1       col2      diff
   A 2018-02-01       NaT
   A 2019-01-01  334 days
   A 2019-05-01  120 days
   B 2015-01-01       NaT
   B 2019-01-01 1461 days

Function to return abs of diff

abs doesn't work on NaT, so abs can't just be applied
If you use sort_values on col1 and col2, this step can be skipped

def my_abs(x):
    try:
        x = abs(x)
    except TypeError:
        x = x
    return x

# Apply the function
d_ex['diff'] = d_ex['diff'].apply(lambda x: my_abs(x))

col1       col2      diff
   A 2018-02-01       NaT
   A 2019-01-01  334 days
   A 2019-05-01  120 days
   B 2015-01-01       NaT
   B 2019-01-01 1461 days

A Function to set the condition, None if NaT

Because of using groupby and diff, the first row of any group, should be NaT
Set NaT to None, then it can be backfilled

def set_condition(x):
    if type(x) == pd._libs.tslibs.nattype.NaTType:
        x = None
    elif x <= pd.Timedelta('365 days'):
        x = True
    else:
        x = False
    return x

# Apply the function
d_ex['condition'] = d_ex['diff'].apply(lambda x: set_condition(x))

col1       col2      diff condition
   A 2018-02-01       NaT      None
   A 2019-01-01  334 days      True
   A 2019-05-01  120 days      True
   B 2015-01-01       NaT      None
   B 2019-01-01 1461 days     False

Backfill None:
d_ex.condition.bfill(inplace=True)

col1       col2      diff  condition
   A 2018-02-01       NaT       True
   A 2019-01-01  334 days       True
   A 2019-05-01  120 days       True
   B 2015-01-01       NaT      False
   B 2019-01-01 1461 days      False

Comment: @bbd108 The answer has been updated to sort `col1` and `col2`. This also removes the need to use `my_abs`.


Replacing a Groovy XML Node causes problems in subsequents findAll calls

Question: I use groovy to parse a XML file using XmlParser. Just to avoid the handling of namespace prefixes, I used xmlRoot.'**'.findAll() method to find some nodes. The sample code shows how it works correctly until I just read the nodes, because each item passed to the closure is a Node object. But when I change the contents of a node (in this case, just the text of the node), the next call to findAll does not iterate on Node objects. For each character I put in the text, a String object is passed to the closure. I solved it checking the type with instanceof, but it seems to be that this is a bug.
Am I doing something wrong or it's a bug?
<code> class XmlParserTest {

static final String XML_SAMPLE = """
<ns0:root xmlns:ns0="mycompany.com">
    <ns0:firstParent>
        <ns0:item1>uppercase_me!</ns0:item1>
    </ns0:firstParent>
    <ns0:secondParent>
        <ns0:item2>uppercase_me_too!/ns0:item2>
    </ns0:secondParent>
</ns0:root>
"""

    static void main(String[] args) {
        def xmlRoot = new XmlParser(false, false).parseText(XML_SAMPLE)

        //******* find item1 and capitalize its text ********
        def nds1 = xmlRoot.'**'.findAll {
            it.name().equals("ns0:item1")
        }

        Node nd1 = nds1[0]

        //This changes the text of the node, but something strange happens to the node tree
        nd1.setValue(nd1.value().toString().toUpperCase())

        //The same problem happens using replaceNode() instead of setValue()
        //Node newNode = new Node(nd1.parent(), nd1.name(), nd1.value().toString().toUpperCase())
        //nd1.replaceNode(newNode)

        //******* find item2 and capitalize its text ********
        def nds2 = xmlRoot.'**'.findAll {
            //for each character in the string "uppercase me!" a String is passed instead of Node
            //As String doesn't have a name method, an exception is raised
            it.name().equals("ns0:item2")

            //using instanceof fixes the problem, at least for this case
            it instanceof Node && it.name().equals("ns0:item2")
        }

        Node nd2 = nds2[0]
        nd2.setValue(nd2.value().toString().toUpperCase())

        assert nd1.value().toString() == nd1.value().toString().toUpperCase()
        assert nd2.value().toString() == nd2.value().toString().toUpperCase()
    }

}
</code>
Comment: not clear what do you want to do. uppercase all text in nodes with some names?
Comment: and what does it mean `something strange happens to the node tree` ? what exactly the problem?
Comment: it means that if you think to node.findAll() as a tree traversal, you'll se that, for each character in the string, you receive a call with "it" parameter that is not a node, but a string with the character.
Answer: I've opened an issue on Groovy: this is the explation on what happened


Cannot find symbol: javac no longer compiles my driver file when classes are placed in a package

Question: noob here.
I have a group of class files which are used by a driver file. I originally wrote the files without any package statement and compiled the files using:
javac -d classes src/Driver.java

Driver compiled without a hitch (though I had to add the path to the src directory in my .bash_profile CLASSPATH variable first)
Next, I added a package statement at the top of all my src files. The statement had the form:
package edu.school.course.project;

Every src file got the same package statement. However the javac command now yields 62 "cannot find symbol" errors when executed. Every Driver.java reference to another class file in my src directory fails.
I tried adding this import statement to each class file that extends or implements some parent class in the package:
import edu.school.course.project.*;

Still, javac yields 62 "cannot find symbol" errors.
Do I need to modify my CLASSPATH variable to include the package? What am I doing wrong?
Answer: Delete the old binary class files from your filesystem (the files in classes). Next, re-run the above compile. You do not need the import statement(s) if everything is in the same package. Modify your CLASSPATH to include the classes directory (not your src directory). Finally, run the driver as java edu.school.course.project.Driver.
Comment: Thanks for the fast response. I've removed all the binary files from my classes directory. I even superstitiously deleted and recreated the classes directory. Brand spankin new. I'm running up against the same problem: nothing was fixed.

I removed all the package statements and ran the above javac command to make double sure I remembered the past correctly. Good news is that my memory is correct. The files really do compile when they aren't in a package. :( Where could I be going wrong?
Comment: @Austin Have you moved the files into sub-directories matching their new package structure? The compiler is going to look for the classes with their fully qualified names.
Comment: I haven't. Current path to the files is ~/Project/src Are you saying I should reorganize it like ~/Project/src/edu/school/course/project/
Answer: An alternative is create a directory to hold your Driver class.  For instance:
mkdir -p src/edu/school/course/project
mv src/Driver.java src/edu/school/course/project

Then compile it:
javac -d classes src/edu/school/course/project/Driver.java

You can put all your other related Java files in that same directory.
Assuming Driver has a main() method, to run it:
java -cp classes/ edu.school.course.project.Driver

Comment: Thank you! That fixed all my problems


xterm: Xt error: Can't open display: :0

Question: I have a cronjob that didn't work this morning. The line in crontab -e looks like this:
20 9 * * 1-5 export DISPLAY=:0 && /bin/bash /opt/ibc/twsstart.sh

I couldn't find any errors in /var/log/syslog, but when I try to run that command in my terminal, I get the following error:
taylor@mean-machine:~$ export DISPLAY=:0 && /bin/bash /opt/ibc/twsstart.sh
taylor@mean-machine:~$ xterm: Xt error: Can't open display: :0

Would this have anything to do with me trying to install Nvidia drivers and Cuda last night? That installation gave me trouble and I remember fiddling a lot with adding and removing libraries. I think I remember seeing something about xserver in there.
Comment: Might want to see: https://askubuntu.com/a/1334403/231142 as depending on what DM you are using and how you login can determine if DISPLAY is :0 or :1.
Answer: Per @Terrance's suggestion, somewhere in me messing with things, DISPLAY got changed to :1 from :0.

xterm: Xt error: Can't open display: :0