How to add a reaction role function with custom emojis?

Question: Hello members of the Stack Overflow community,
I have been working on a function that activates when a moderator approves a user using Auttaja's gatekeeper. Basically, the new user gets to choose between two server emoji reactions, which will give him/her the roles. But I have been having difficulties with the role and emoji constants.
Here's my code:
 const ApprovalEmbed = new Discord.MessageEmbed()
.setColor('RED')
.setTitle('Hi there new user!')
.setDescription('Please react to this message with either one of the emojis in order to get a role.')
.addFields(
  { name: '\u200B', value: '\u200B' },
  { name: 'The Boomer emoji gives you the "Les boomers normaux" role, and the rat emoji gives you the "The normal Rat Haven dwellers" role.'},
   { name: '\u200B', value: '\u200B' },
  { name: 'Selecting the Boomer emoji will give you access to only the Boomer Haven compartment, and the rat emoji will give you access to the Rat Haven compartment. '},
  { name: '\u200B', value: '\u200B' },
  {name: 'To get access to both of these compartments, please consider using the command "^AccessToBoth" to receive the "Access to both compartments" role.'},
  )
  .setTimestamp()
  .setFooter('Time to pick a role!');
  const roleOne = guild.roles.cache.find((role) => role.name === "The normal Rat Haven dwellers")
  const roleTwo = guild.roles.cache.find((role) => role.name === "Les boomers normaux")
  const BoomerEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'boomer');
  const RatEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'robincutmoment');

client.on('message', async message => {
  let AdminRole = message.member.roles.cache.find(role => role.name === "Server Moderators")
  let RulerRole = message.member.roles.cache.find(role => role.name === "The Supreme Boomers")
  let RatRole = message.member.roles.cache.find(role => role.name === "Rat Majesty Robin")
  if (message.member.roles.cache.has(AdminRole)) {
  } else if (message.member.roles.cache.has(RulerRole)) {
  } else if (message.member.roles.cache.has(RatRole)) {}
  if (message.content === `-approve`) {
    message.channel.send(BoomerEmoji)
    const reactionMessage = await message.channel.send(ApprovalEmbed);
    message.channel.send(ApprovalEmbed).then(reactionMessage.react(BoomerEmoji), reactionMessage.react(RatEmoji))

  }
  const filter = (reaction, user) => {
      return [(BoomerEmoji), (RatEmoji)].includes(reaction.emoji.name) && user.id === message.author.id;
  };
  message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
    .then(collected => {
      const reaction = collected.first();

      if (reaction.emoji.name === (BoomerEmoji)) {
        message.member.roles.add(roleOne)
      } else if (reaction.emoji.name === (RatEmoji)) {
              message.member.roles.add(roleTwo)
      }
  })

});
Comment: "Having difficulties" is not enough for us to diagnose a problem and give a solution. What's currently going wrong? Are you getting any errors?
Comment: Hi Lioness, I'm getting errors that indicate that the role constants aren't doing their thing when the user clicks on the reaction. The same thing can also be said for the reactions. They just don't show up.
Comment: Do you have [both intents enabled](https://stackoverflow.com/questions/64559390/none-of-my-discord-js-guildmember-events-are-emitting-my-user-caches-are-basica)?
Comment: Yes I do. All intents are enabled.
Answer: Your first problem is occurring in this snippet:
if (message.member.roles.cache.has(AdminRole)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole)) {
 // ...
} else if (message.member.roles.cache.has(RatRole)) {
 // ...
}

Collection.prototype.has() checks if an element exists in the collection. It takes one parameter: the key of the element you wish to check the existence of. Since roles are mapped by snowflakes, you should be passing the role ID, not the entire object.

// `Collection.prototype.has()` is identical to `Map.prototype.has()`
// here's how it works:
const map = new Map();

// 'foo' is the key,
// 'bar' is the value
map.set('foo', 'bar');

console.log(map.has('foo')); // true
console.log(map.has('bar')); // 'bar' is not the key; false

if (message.member.roles.cache.has(AdminRole.id)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole.id)) {
 // ...
} else if (message.member.roles.cache.has(RatRole.id)) {
 // ...
}

If you'd like to be fancy, you could use Collection.prototype.findKey() instead of the normal Collection.prototype.find(). This method is almost the same, except it returns the key of the found element instead of the value. Again, it makes almost no difference; just another option.
let AdminRole = message.member.roles.cache.findKey(
 (role) => role.name === 'Server Moderators'
);
let RulerRole = message.member.roles.cache.findKey(
 (role) => role.name === 'The Supreme Boomers'
);
let RatRole = message.member.roles.cache.findKey(
 (role) => role.name === 'Rat Majesty Robin'
);
if (message.member.roles.cache.has(AdminRole)) {
 // ...
} else if (message.member.roles.cache.has(RulerRole)) {
 // ...
} else if (message.member.roles.cache.has(RatRole)) {
 // ...
}

Your second problem is somewhat along the same lines. BoomerEmoji and RatEmoji are complete GuildEmoji objects. However, in this line:
return (
 [BoomerEmoji, RatEmoji].includes(reaction.emoji.name) &&
 user.id === message.author.id
);

And these lines:
if (reaction.emoji.name === BoomerEmoji) {
 message.member.roles.add(roleOne);
} else if (reaction.emoji.name === RatEmoji) {
 message.member.roles.add(roleTwo);
}

You're comparing it to the name property of another emoji. This fix is fairly simple, just clarify you only need the name properties when declaring each variable:
const BoomerEmoji = message.guild.emojis.cache.find(
 (emoji) => emoji.name === 'boomer'
).name;
const RatEmoji = message.guild.emojis.cache.find(
 (emoji) => emoji.name === 'robincutmoment'
).name;

Comment: Could you elaborate on what that issue is?
Comment: Hey! Thanks for the help! However, there is a slight issue which includes the last part of the script, where the bot is supposed to give the user the role. I still cannot figure that out.
Comment: Basically, where the bot gives the user the role (if (reaction.emoji.name === (BoomerEmoji)) {
        message.member.roles.add(roleOne)
      } else if (reaction.emoji.name === (RatEmoji)) {
              message.member.roles.add(roleTwo)
      } )

It doesn't do anything. It's just that the user clicks on the reaction, but he or she is not given the role.


Convergence of the sequence $na_n$

Question: Suppose $\{a_n\}_{n\geq 1}$ be a sequence of positive real numbers, and the sum
$$ \sum_{k=1}^{\infty} a_k $$
converges, with the limit $\lim_{n} \frac{a_{n+1}}{a_n}=1 $ (*).
The question is:
Is it always true that $\lim_{n} na_n = 0$ ?
We have seen that the statement is true when the sequence is decreasing, but does it still hold under condition (*)? Or are there any counter-examples? Waiting for your help!
Answer: Let's look at a "bump" with $N b_N = 1$ and $|b_n/b_{n+1}-1| \le \epsilon$: say $b_n = (1+\epsilon)^{-|n-N|}/N$.  This has a sum of about $2/(N\epsilon)$. So we should be OK to take a sum of these bumps with $N$ going to $\infty$ faster than $1/\epsilon$.
Thus this ought to do it:
$$ a_n = \sum_{k=1}^\infty 3^{-k} (1+2^{-k})^{-\left| n - 3^k\right|}$$
Answer: Idea for constructing a counter-example:

start with a "barely convergent" series like the one given by $a_n=\frac{1}{n\log^2(n+1)}$
for any $n$ which is a power of $2$, re-define $a_n$ as $\frac{1}{n}$ (this does not affect convergence but leads to $\limsup na_n=1$)
re-define $a_m$ if $m$ is suitably close to a power of $2$, in such a way that $\lim_{n\to +\infty}\frac{a_{n+1}}{a_n}=1$.

Since $n=\prod_{k=1}^{n-1}\left(1+\frac{1}{k}\right)$, given $a_{2^p}=\frac{1}{2^p}$ we just need to tweak the values of $a_m$ for $|m-2^p|\leq 2p$.

Convergence of the sequence $na_n$


KubeMQ Omits Acks / Acknowledgements From Streams

Question: This functionality:
https://kafka.apache.org/10/documentation/streams/developer-guide/config-streams.html#acks
seems to be missing from KubeMQ streams. Are we missing something or have they just omitted it? This would fundamentally change our architectural decisions in choosing an event driven model. Or perhaps we're missing a new way/terminology of guaranteed once delivery using events and persistence with KubeMQ?
Thanks in advance,
Comment: Not sure I understand the question. KubeMQ is not the same as Kafka Streams; the later being a Kafka only client library. I assume you meant to link to the Producer config page directly. Not all messaging systems support acknowledgments. No messaging system is truly 100% guaranteed delivery. The Kafka target does have acks. Source: https://github.com/kubemq-io/kubemq-targets/blob/master/targets/messaging/kafka/client.go#L40
Comment: Thanks for your comment. Perhaps we are being a little naieve. How would you use kubemq for microservice communication where you need best assurance that messages are delivered at least once? Which kmq pattern? Thanks
Comment: I've not used kubemq. I'm only responding with reference to the kafka tag. Perhaps you'll get a more direct answer using their community slack
Answer:
guaranteed once delivery using events and persistence with KubeMQ

According to the docs, that's not (currently?) possible

support for  At Most Once Delivery and At Least Once Delivery models

https://docs.kubemq.io/
If you want to run a Kafka broker in Kubernetes, instead, you can look into the Strimzi Operator, as one example.


Deserializing data sent via TCP

Question: I have problem with sending objects via TCPClient. At first, I serialize them into byte array and then I send them. TCPListener recieves some data, but deserializer is throwing exception "Unexpected end of stream".
Here is reciever code:
    public void start()
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 8090);
        listener.Start();

        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            processClient(client);
        }
    }

    public void processClient(TcpClient client)
    {
        NetworkStream net = client.GetStream();

        ReadData(net);

        byte[] response  = Encoding.UTF8.GetBytes("Hello from the server.");
        net.Write(response, 0, response.Length);
        net.Close();
        client.Close();
    }

void ReadData(NetworkStream netstream)
{
    byte[] buffer = new byte[2048];
    System.IO.MemoryStream memStream = new System.IO.MemoryStream();

    netstream.ReadTimeout = 5000;

    int bytes = -1;

    while ((bytes = netstream.ReadByte()) != -1)
    {
        memStream.WriteByte((byte)bytes);
    }

    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bform = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

    Packet packet = (Packet)bform.Deserialize(memStream);

    OnMessageArrived(this, new MessageEventArgs(packet.From.ToString(), packet.Data.ToString()));

    memStream.Close();
    netstream.Close();

}

And here is sender code:
    public void sendData(string to, Packet data)
    {
        TcpClient client = new TcpClient();

        MemoryStream mstream = new MemoryStream();

        client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8090));
        if (client.Connected)
        {
            NetworkStream stream = client.GetStream();

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bform = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            bform.Serialize(mstream, data);

            byte[] buffer = new byte[2048];
            mstream.Read(buffer, 0, buffer.Length);

            stream.Write(buffer, 0, buffer.Length);
            stream.Flush();
            stream.Close();
            client.Close();
        }
    }

Sender main method:
    static void Main(string[] args)
    {
        SimplestTCPIP.Client client = new SimplestTCPIP.Client();

        Packet packet = new Packet("client", "server", IPAddress.Parse("127.0.0.1"));

        client.sendData("server", packet);

        Console.WriteLine("IP: " + GetIP().ToString());
        Console.Read();
    }

Reciever main method:
    static void Main(string[] args)
    {
        SimplestTCPIP.Server server = new SimplestTCPIP.Server();

        server.OnMessageArrived += new SimplestTCPIP.Server.MessageArrived(server_OnMessageArrived);

        Thread thread = new Thread(server.start);
        thread.Start();

    }

    static void server_OnMessageArrived(object sender, SimplestTCPIP.Server.MessageEventArgs m)
    {
        Console.WriteLine(m.From + " : " + m.Text);
    }

Comment: Did you ever get this sorted out?
Answer: In your sendData method you serialize the object to a memory stream and then read it back into a buffer of 2048 bytes before writing it to the network stream. If the serialzed object is > 2048 bytes you would have a problem. I would try just serializing directly to the network stream or at least using the same kind of code as in your ReadData method where you write byte by byte.
Edit:
The size of the data is probably not the problem. You should still avoid the hard coded buffer size and stick with the code change you mention in the comment. Given your comment the problem lies elsewhere.
In both your sender and your receiver you write to a memory stream and then read from it. You can't do that unless you set the current position in the stream back to zero between the write and read.
So in your sendData method on the client add the line
mstream.Seek(0, SeekOrigin.Begin);

right after
bform.Serialize(mstream, data);

And in the ReadData method of your server add the line
memStream.Seek(0, SeekOrigin.Begin);

right before
Packet packet = (Packet)bform.Deserialize(memStream);

That way the memory stream is set to the beginning before you try and read from it.
I think you could just skip the memory stream all together and just read and write to the network stream, but you might have other reasons for it.
Comment: I tried this code:

                while ((bytes = mstream.ReadByte()) != -1)
                {
                    stream.WriteByte((byte)bytes);
                    stream.Flush();
                }

But it throws another exception :( Something like "Attempt to reconstruct empty stream".

Deserializing data sent via TCP


React typescript forwardref with defaultProps

Question: I was trying to use defaultProps in functional component along with forwardRef, but was getting the error (refer screenshot).
I don't want to destructure the props in function params and assign default value. because got a lot of props in my original usecase.
I also tried assigning the default values JSON directly to ComponentA.defaultProps still same result.

How to resolve this ? Tried surfing but was not able to find any solution.
Also since we are using TS for type check, do we still need prototype JSON ?
#App.tsx
import './App.css';
import ComponentA from './components/A/A';
function App() {
  return (

      <ComponentA>
        <button>Button I am</button>
      </ComponentA>

  );
}

export default App;

#ComponentA.tsx
import React,{forwardRef} from "react"
import PropTypes from 'prop-types';

type Props =  {
    children:JSX.Element | JSX.Element[],
    text:string,
    text1?:string,
}

const ComponentA=(prop:Props)=>{
    return
Hey
        {prop.children}
        {prop.text}
        {prop.text1}

}
ComponentA.prototype = {
    children:PropTypes.element.isRequired,
    text:PropTypes.string.isRequired,
    text1:PropTypes.string
}

ComponentA.defaultProps={
    text: 'done'
} as Partial<Props>
export default forwardRef<HTMLAllCollection,Props>(ComponentA)

Thanks
Comment: can you share the code snippet?
Comment: @YedidyaRashi updated the post with snippet
Answer: Brian Vaughn commmented on the issue of Stateless Component: React.forwardRef make defaultProps invalid

The function passed to forwardRef is not a React component. (React components don't accept a second ref param for example.) It's just a function that "renders" (returns) React elements. So it does not support defaultProps. We have tests that confirm this as expected behavior.
React also logs the following error in the console (as can be seen in your Code Sandbox repro):

Warning: forwardRef render functions do not support propTypes or >defaultProps. Did you accidentally pass a React component?

That is the reason why you can not attach defaultProps before passing the function that "renders" to the forwordRef.
It's also mentioned in the type definitions of react:
// the input of ForwardedRef
interface ForwardRefRenderFunction<T, P = {}> {
    (props: P, ref: ForwardedRef<T>): ReactElement | null;
    displayName?: string | undefined;
    // explicit rejected with `never` required due to
    // https://github.com/microsoft/TypeScript/issues/36826
    /**
     * defaultProps are not supported on render functions
     */
    defaultProps?: never | undefined;
    /**
     * propTypes are not supported on render functions
     */
    propTypes?: never | undefined;
}

In your case just inverse the order of declarations:
import "./styles.css";
import { forwardRef } from "react";
import PropTypes from "prop-types";

type Props = {
  children: JSX.Element | JSX.Element[];
  // NOTE: text is optional since he has default value.
  text?: string;
  text1?: string;
};

const ComponentA = forwardRef<HTMLAllCollection, Props>((prop: Props) => {
  return (

      Hey
      {prop.children}
      {prop.text}
      {prop.text1}

  );
});

ComponentA.prototype = {
  children: PropTypes.element.isRequired,
  text: PropTypes.string,
  text1: PropTypes.string
};

ComponentA.defaultProps = {
  text: "done"
};

export default function App() {
  return (
    <ComponentA>
      <button>Button I am</button>
    </ComponentA>
  );
}

Sandbox Code
Comment: tried your solution, working fine.
Still I am not able to understand why it behaves diff when we wrap forwardRef while exporting vs using forwardRef while declaring.
Comment: does it clearer now?
Comment: thanks for the detailed info, now able to wrap my head around this.


How do I survive as a Solo Elementalist?

Question: I've been trying to play an Elementalist on the Crystal Desert server, and given the fact that the party system is bugged, more often than not, this means going solo, as my friends are elsewhere.
Unfortunately, I've been dying a lot, especially in my personal story. I've been bouncing back and forth between Dagger / Dagger and Staff, and finding neither option particularly amenable. Dagger/Dagger has no real way to avoid damage, as the best protection it offers are Chill, Weakness, and Stun, all of which only reduce the rate of damage, rather than prevent it from occuring (and the stun requires you to be hit in the first place!)
This results in many a time going toe-to-toe with a mob. If it's one vs. one, I can usually win, but I end the fight with half health (or less!) It seems to exist as a "Burst or be bursted" loadout, and I'm spending more time downed than I care to admit.
I've also tried Staff, but I'm finding that too far a swing in the opposite direction; I've got good avoidance and longevity (two heals from Water attunement, an extra dodge roll, etc.) but I have to stand there for ages, plinking the monster to death.
How can I strike a better balance between damage and survivability? Mobs seem to die equally fast (if not faster!) to my guardian, and she rarely takes any damage doing it! Are Solo elementalists simply unfeasible?
Comment: Have you tried other weapon combos?
Comment: @SaintWacko You mean, more than 40% of all weapon combos? :P
Comment: Oh, do they not have many combos? I didn't play much as an ele. I tried it, then started a thief and fell in love.
Comment: @SaintWacko 2 MH options (Dagger / Scepter), 2 OH options (Dagger/Focus), and one 2-H option. No weapon switch in combat.
Comment: Oh, wow, forgot about that. Never mind then! :D
Comment: @RavenDreamer I thought you could switch between two weapon sets in combat but not change your loadouts? Or does that not apply to elementalists due to their attunements?
Comment: @Alex: Elementalists and engineers don't get to have two weapon sets. See [this question](http://gaming.stackexchange.com/questions/81570/how-do-your-f1-f2-ect-skills-work) for a more detailed explanation maybe
Comment: @Alex In combat you cannot switch weapons, even from your inventory, although outside of combat it is possible (ex. quiet parts of the story quest).
Answer: Brian has some basic advice that you should try to follow first. If you are still doing poorly after the fact, it's nothing to be embarassed about since story scaling will pit you against equal skill mobs almost all the time. I remember having a hard time with my story as well from the point where I was trying to find my parents.
Using skills effectively is half of the battle. Although dagger/dagger didn't work out for you, I recommend trying dagger/focus. This combo has two things going for it:

Conditions that help you kite your opponent and reduce their damage.
Mobility and speed of skill use that allows you to stay on your toes. No channeling skills for 5 seconds like staff.

The key to getting the most out of any weapon combo is to switch elements after using skills that have longer cooldowns. These long cooldown skills are typically on your 3-5 keys. Your 1 and 2 key skills, although on low cooldown, don't prevent your opponent from damaging you, which is not going to help you survive. Also, although they can be spammed they typically do low damage, so you end up mashing your 1 key for very little gain (the plinking). By switching elements frequently you ensure that you always have a high value ability to use; while playing around with another element all of your previously used skills are burning through their cooldowns. Elementalists are blessed with lots to do while a particular skill is on cooldown (20 weapon skills versus the average 10) - take advantage of it.
Note that this combo really only applies to solo. In dungeons and group events you can't really serve an up-front role as an elementalist - you will find more success staying back and supporting with staff or scepter, given the massive AoE damage and slow heals. Once you have mastered some dagger combos you can get up close and personal in big events.

To give you an idea of how you can skill cycle, here is a summary of my cycle for dagger/focus:

Lightning, 4/5, 2, 3
Fire, 4, 5, 3, 2
Water, 3, 5, 4, 2
Earth, 1/2 (spam), 4/5 (situational)

Start with lightning. If you are fighting ranged mobs, you can lay down Swirling Winds (4 key) to keep ranged attacks at bay while you lay out your damage. If you are fighting a melee mob, you can start with Gale (5 key) to knock them down while you lay out damage. Alternatively, do damage then knock them down just before they land a blow. Use Shocking Aura (3 key) as well in case they end up hitting you.
Then start to cycle. Switch to fire and burst as you shouldn't be needing water or earth for survivability this early into the fight. Drop a Flamewall and Fire Shield (4 and 5 keys) before doing anything else to start doing damage over time, ensuring you keep the mob in the AoE by standing near it. Then burst by dashing through them with Burning Speed (3 key) and turn around for a Drake's breath (2 key).
Switch to water next as some conditions on your opponent are wearing off. Chill them with Frozen Burst, drop a Comet, then Chill again with Freezing Gust (3, 5, and 4 keys) before using Cone of Cold (2 key). This is a stage where you can lay damage from a distance if staying close is getting you into trouble, as you should be able to kite while they are chilled.
Switch to earth and begin impaling. This is a filler element while you wait for your other cooldowns to finish, because earth does good damage over time that will last long after you switch elements. Now is the time to remove any conditions that you have accumulated using Magnetic Wave (4 key), and if you get into real trouble use Obsidian Flesh (5 key) to go invulnerable for a short time. If you are very good with timing magnetic wave against a ranger-type mob, you can do lots of damage by countering a ranged attack.
If something doesn't fit this cycle then use whatever element will help you the most. Fire is for high finishing damage. Water is for kiting. Lightning is for reducing their attack effectiveness. Earth is for tanking.
Also note that the order of skills while using one element doesn't matter that much: the point is I always have some condition on my opponent while using heavy damage skills.

Your other skill slots (6-0) are also very important. The 6 key is always a decent heal that you should use while you aren't in the thick of things. Remember that if it wouldn't overheal you, now is the time to use it as you want to burn through the cooldown asap before you really need it again.
I also highly recommend Mist Form. While in Mist Form, you are totally invulnerable (although you don't break cc) and you are capable of casting your heal at the same time (6 key), basically resetting the fight. I also recommend Cleasing Fire to break stun, because there are a number of mobs that will stun you before hitting for very heavy damage.
Comment: @Alex Some utility skills have the line, "Breaks Stun", which means, they will remove the stunned condition on activation. Other Crowd Control (CC) like immobilized or cripple, however, remain.
Comment: What is 'breaking cc'?
Comment: Another note, while in Mist Form you can cast *any spell*, meaning spells with a short channeling time can be cast without taking damage and uninterrupted.
Comment: Also keep your gear up-to-date. Remember with level scaling that if you don't have good items for your level, when scaled down they will still not be good for your scaled down level. This doesn't mean that you need legendary gear, just make sure the gear level closely matches your own.
Answer: I haven't seen any bugs with the party system so far, and you don't need to be in the same party as other players to play with them, except for in instanced areas.
Regardless, to survive solo you'll need to

Avoid events or areas that show a recommended level higher than your own.
Get good at knowing when to dodge, when to heal, and when to run for your life.
Use primarily ranged weapons to keep yourself from getting too far into the fray, while giving yourself the option to retreat if needed.
Focus on toughness, vitality, and healing when choosing your equipment and traits.
Use the armor and weapon mods (such as pebbles, runes, jewels, etc) to ensure that your equipment is reaching its maximum potential.
Switch your attunement to Water if you start taking a lot of damage. Water spells specialize in healing and also in slowing enemies down with the Chilled condition.
If you feel that you need an extra boost, try some food from certain merchants or created by the Chef crafting discipline.
Don't go AFK unless you're in a city, you never know when an event or patrol might catch you off guard.

Good luck!
Comment: Yeah, it's the personal story instances which pit 5-6 mobs at me that are the worst offenders.
Comment: When that happens, try balling them up and hitting them with some area of effect spells. Running around them and then back out usually works for me, especially if there's an ally NPC you can run them into to absorb the damage for you.
Answer: Scepter/Dagger
I take down groups of five or more with no problem. I can also kill Veterans in about 4 seconds.
1 on the mob to pull them to you. (Yes, I do this spike damage in close range. If you mess up you die but you pretty much only win if you get the pattern down.)
Once they are near you: 2 (DT) followed swiftly by Ring of Fire so you get the finished from DT. While RofF is up Phoenix and Arcane Blast. You now have a lovely amount of Might stacked. Use your 5 skill and thx to all that might and the fact that your opponent should be burning you will probably finish them off with this move.
If there is a large group-ish. Pull them into you like above but cast Lesser Elemental and Storm Glyphs (placing the circle on yourself) these add the extra damage needed to survive this.
At any time you need healed use the healing Glyph which adds even more might while attuned to fire.
Get this down pat and you won't die. Underwater is a whole different story though.
Answer: I never seriously played or even tried Elementalist in any other games, and I didn't give much thoughts to test one in all the Guild Wars 2 beta I played.
However, with all that said, My Main character now in GW2 is ...
Elementalist - Dual Dagger
Build: Glass Cannon (30, 20, 0, 0, 20)
Utilities: Glyph of Elemental Harmony, Arcane Wave, Arcane Blast, Armor of Earth
After all this while, playing as D/D Ele, and now working on getting legendary dagger, I can say D/D Ele is very fun to play if you know exactly how to play correctly.
For me, D/D Ele is all about "high speed combo" with crazy burst-DPS, with several CC (stun, knockdown, freeze) in between to take down opponent. Once you get used to playing this spec you will be able to take on multiple enemy as well.
Combo example:

Ride the Lightning (From a distance)
Arcane Wave & Arcane Blast (note that arcane skill does not have global cooldown)
Updraft
Burning Speed
Ring of Fire
Drake's Breath or Fire Grab
Earthquake
Churning Earth

The timing of skills and distance between you and enemy also plays a very important role in your strategy.
Vitality and Toughness stats does helps to increase little bit your survival, but then, once you have got the hang of dodging, high speed combo and able to switch to correct attunement at specific moment, you will start replace them with you own preference accordingly.
The rest my friend is for you to experiment and discover!
Answer: I'm having the same problem, mostly with ranged mobs. If they're melee, I will circle strafe to kill them, which works really well. Water helps a lot with heal, but it can be challenging to switch between everything quickly.
Also a further note elementalists and engineers DON'T have weapon swap.
Answer: I'm a solo elementalist too, and have found few difficulties, so here is what I recommend:
Use all your weapon combinations to see what works best for your playstyle. Dagger/Dagger, Scepter/Dagger, Staff, Scepter/Focus, etc.  Also each combination has a set of skills for each element, so do them all.
Do your quests at your level, if your next main quest is marked as 12 and you're 11, go do normal world quests, participate in all events, do crafting, pvp if like that, etc. When you reach 12 then do the main quest.
Pull an elemental, think the skill is called 'glyph of elements' or something, use that one before a tough fight, they last a minute and can offtank for you and/or do damage.
Don't just stand there, move around. Some mobs have slow swings, and they stop to do their big attacks, which will be big 'whooshes' if you're not there when they happen.
Divide and conquer. Move away from where the quest fight starts if there are multiple mobs, hopefully some of the mobs will turn back or attack other targets.
Switch to water when using your heal skill, that will give you a regeneration for a few seconds for extra healing.
If all else fails in a personal quest, 'cheat' (I call it cheating), concentrate on killing a mob or two before you die, when you pop back up in the waypoint it's less mobs to worry about.
Comment: Glyph of Lesser Elementals is a good idea! It had been my first skill pick, actually, but I stopped using him when I realized the cooldown doesn't start until the elemental disappears. I'll have to give him a second look.
Comment: When you die in a personal quest it asks if you want to return to the latest checkpoint. Are checkpoints and waypoints the same thing? In my case no matter how many I killed if I died it was a complete fight reset. It would be super cool if you can slowly whittle a hard fight down!
Answer: I am playing as a solo elementalist currently.  You are having trouble killing stuff with a staff using fire?  I kill stuff absurdly quickly with fire atunement.  In addition to the usual ranged attack on 1, it has a good damage DoT on 2 (with a slight delay), an insta-aoe thing on 3 (you'll want to read it's description to make sure you understand about enemies being ignited or whatever) and Meteor Shower on 5.  I don't have any trouble killing stuff using the fire atunement on staves.
Where are you fighting?  Are you fighting at <=level or > level?  It's hard to fight up (at least until you get very well geared and have lots of extra skill options, I'm sure).
Learn to use dodge to help with avoiding damage, in addition to just moving around.  The suggestion to gear for vit/toughness isn't a bad idea either.  Unlike other MMORPGs, that can make a lot of sense.
Answer: Solo elementalist? Easy.
Use Lightning Hammer.
Spawn a lightning hammer and start spamming skill number one and only skill number one. It hits hard as heck, hits all mobs in an aoe around you, and every third swing does an aoe BLIND (which means the next attack from the mobs will miss, doing no damage to you). Essentially you can kill packs of mobs without them ever hitting you if they attack slow enough.
Some other good things to throw in are mist form when stuff gets too crazy, arcane shield to block a few more attacks and then do damage, and at least 10-15 points in Water so that you can remove conditions easily.
Answer: I started with staff, then fell in love with dagger/dagger. Take Arcane Power (that makes your next five hits critical). AtTune to earth (with 5 in traits, increases your resilience too), get in among the mob, hit 4 (earthquake) then 5 (churning earth) - with both critical, the mob will be in a bad way.
Also get a lot of mileage out of glyph of elemental power (on auto recast) - lots of foes on fire, blinded, bleeding etc.
Suppose what I'm saying is don't neglect Slot and utility skills that really enhance standard skill effects.
Answer: To the poster who said eles don't have weapon swap: they do; or rather it procs every time you change element. So get a good on swap sigil and change, a lot. Be careful about cooldown overlaps (don't take two on swap sigils; make the other weapon sigil of force or something)
Not sure how high level you are. At grandmaster check out arcane evasion traits; every dodge roll does something nasty to mobs (or heals you, in water). Get a sigil of energy, dodge, swap element, dodge, repeat - whilst doing everything the chaps above are suggesting.
If you're staying in one ele, you're doing it wrong. Don't bother with lightning hammers etc - all of the weApon kits restrict you to one set of skills and one set of cooldowns so should be avoided (possible exception of icebow which has good situational uses in some dungeons)
There are some excellent d/d YouTube videos: revolutionised my play style. Traits are key and all too often folks maximise fire for easy power: this is suboptimal.
Comment: Except even if attunement switching counts for weapon change sigils, elementalists and engineers LITERALLY do not have a second weapon set and thus cannot "weapon swap".


query to_date issue

Question: Below query is giving me two different result for two different oracle database. ( database version I am not aware of )
I want to ask like TO_DATE function varies from database version ?
select * from ACC WHERE CHANGE = TO_DATE('01/02/2015','MM/DD/YY');

Note that I am facing issue in only = but < and > working fine.
In 1 db : this query is giving 1 record
In 2 db : this query is giving 0 record.
In DB : CHANGE value is 02-JAN-14
Comment: What is type of CHANGE column, DATE ?
Comment: Yes..it is of type DATE
Answer: As far as I know, to_date() hasn't changed.  More likely is that you have a time component on your column change, which prevents = from working.  Try this:
select *
from ACC
where trunc(CHANGE) = TO_DATE('01/02/2015','MM/DD/YY');

Or, how I would prefer to write this:
where change >= DATE '2015-01-02' and
      change < (DATE '2015-01-02') + 1

Using the date keyword, you can use ISO standard formats.  This version also allows the use of indexes on the change column.
Comment: trunc is working.But I cannot see time component in both the database table value. I am using oracle sql developer.
Comment: @vjs . . . You can use `to_char()` to convert the value to a string and see the time component.
Comment: I did select to_char(change) from...., but there is not time component in both the db table values
Comment: `to_char(change, 'YYYY-MM-DD HH24:MI:SS')` or just look at `change - trunc(change)`.
Answer: if they are on the same server is strange. If you are on two different servers verify that the date format of the server is the same.
You can see it in the settings under NLS

query to_date issue


An elementary perturbation result in C*-algebra

Question: The following question was raised when I read a papaer "MF actions and K-theoretic dynamics". In one of the proofs in that paper, the author utilized a so called "elementary perturbation result in C*-algebra":

Let $\varepsilon>0$, there is a $0<\delta<min\{1, \frac{\varepsilon}{4}\}$ with the following property: if $D$ is any C*-algebra with $d\in D$ satisfying $||d^{*}d-1||<\delta$ and $||dd^{*}-1||<\delta$, there is a $v\in U(D)$ with $||d-v||<\frac{\varepsilon}{4K}$ for some fix number $K$. (Here, the U(D) denotes the set of all unitaries in $D$.)

I think it is an elementary exercise in operator algebra, but I do know how to find such a $v$ in the exercise, could someone give me some hints?
Answer: Something like this should work : Given $\epsilon > 0$, consider $f(x) = x^{-1/2}$. This is uniformly continuous on $[1/2,2]$, so $\exists 1/2>\delta > 0$ such that for any positive invertible $a \in A$ such that $\sigma(a) \subset [1/2,2]$, we have
$$
\|a - 1\| < \delta \Rightarrow \|\sqrt{a}^{-1} - 1\| < \frac{\epsilon}{\sqrt{2}} \qquad\qquad (\ast)
$$
Now suppose $\|dd^{\ast} - 1\| < \delta$ and $\|d^{\ast}d - 1\| < \delta$, then $dd^{\ast}$ and $d^{\ast}d$ are both invertible. Hence, $d$ is left and right invertible - and so it is invertible. Therefore $|d|$ is invertible. Also
$$
\sigma(d^{\ast}d) \subset [1-\delta,1+\delta] \subset [1/2,2]
$$
So we may apply $(\ast)$
$$
\||d|^{-1} - 1\| < \frac{\epsilon}{\sqrt{2}}
$$
Now $\|d\| = \sqrt{\|d^{\ast}d\|} \leq \sqrt{1+\delta} \leq \sqrt{2}$. Hence
$$
\|d|d|^{-1} - d\| < \epsilon
$$
Now check that if $u = d|d|^{-1}$ is a unitary.


Prove that, for a closed subspace $W$ of a vector space $V$, $(W^{\perp})^{\perp} = W$

Question: Prove that, for a closed subspace $W$ of a (infinite dimensional) vector space $V$, (with inner product) $(W^{\perp})^{\perp} = W$.
The notion 'closed' is in relation to the natural metric $d (x,y) = \|x-y\|$ with $\|\cdot\|$ defined as $\sqrt{\langle\cdot,\cdot\rangle}$
This is a basic fact that I have found referenced but not proven. I know that, for all subspaces $U$, $U^{\perp}$ is closed.
Thank you.
Comment: What do you mean by closed subspace?
Comment: @aboat Presumably this is a topological vector space, in which case it means topologically closed.  The OP should be more precise about the nature of the ambient space, e.g. whether it's a Banach space or more general.
Comment: Thanks-edited to be more precise (has inner product)
Comment: See also: [A subspace $X$ is closed iff $X =( X^\perp)^\perp$](https://math.stackexchange.com/q/1051514)
Answer: I will show that for any subspace $W$, $W^{\perp\perp} = W^-$. (Closure)
Observe that
$$ W^{\perp\perp} = \{v \in V\mid \forall w \in W^\perp, \langle v, w \rangle = 0\} = \{v \in V\mid \forall w \in V, (\forall u \in W, \langle u,w \rangle = 0 \implies \langle w,v \rangle = 0)\}
$$
Then $u \parallel v$, so that $W \subseteq W^{\perp\perp}$. Since any orthogonal complement is closed, $W^{\perp\perp}$ is closed. Since $W^-$ is the smallest closed set containing $W$, we have $W^- \subseteq W^{\perp\perp}$.
Conversely, let $w \in W^{\perp\perp}$. Assume that $w \not\in W^-$. By the Hilbert Projection Theorem, ($W^-$ is convex) there exists $ w_0 \in W^-$ and some $w_1\mid w_1\neq 0, w_1 \perp W^-$ such that $w = w_0 + w_1$. Thus,
$$ \langle w, w_1 \rangle = \langle w_0 + w_1, w_1 \rangle = \langle w_1, w_1 \rangle > 0
$$
hence $w \not\in W^{\perp\perp}$. Therefore $W^- \supseteq W^{\perp\perp}$.
Comment: Thank you.  The Hilbert projection theorem was what I was missing; I did not know there was a way to do orthogonal projections on infinite dimensional spaces.


Spring Webflux WebClient

Question: I don't really know how to translate the following call to the spring webflux webclient correctly.
userIds is the List and I was able to call the service using the following syntax but I could not get that working with the Spring WebFlux WebClient.  Please help me if there is any of you know how to do it.
String url = "http://profile.service.com/v1/profiles/bulk";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

ResponseEntity<List<MiniProfile>> responseEntity;
try {
    responseEntity = restTemplate.exchange(url, HttpMethod.POST, new
    HttpEntity(userIds, headers), new
    ParameterizedTypeReference<List<MiniProfile>>() {});
} catch (RestClientException e) {
    responseEntity = new ResponseEntity<List<MiniProfile>>(HttpStatus.OK);
}

return responseEntity.getBody();

This is the way I got it translate to the Webflux WebClient:
Flux<String> flux = Flux.fromIterable(userIds);
return readWebClient.post().uri("/v1/profiles/bulk")
      .body(BodyInserters.fromPublisher(flux, String.class))
      .retrieve().bodyToFlux(MiniProfile.class);

Comment: I got an 500 error code which I could not know where it came from and here is the stack trace.   org.springframework.web.reactive.function.client.WebClientResponseException: ClientResponse has erroneous status code: 500 Internal Server Error.  And I expect our service returns a list of profiles.  Note the old code with RestTemplate worked fine for me.
Comment: what's not working with your current solution? What result are you getting? What were you expecting instead?
Comment: that's an important piece of information that belongs in your question, really. This says that the server responds with HTTP 500. So the requests must be different between RestTemplate and WebClient.
Comment: I agree that the requests must be different between the RestTemplate and WebClient.  I've been trying to see if the requests were different between them but I could only see the request body of the RestTemplate got translated as the array of string like this ["0449b652-0006-0000-0000-000000000000", "0333b652-0006-0000-0000-000000000000"] which worked fine with our dependency service but I could not see the request in Netty WebClient as a json like the RestTemplate so I could not tell what the differences were.  Do you have any idea how I can see the serialized request body in Netty WebClient?
Comment: You can set the logging level like this: `logging.level.reactor.ipc.netty.channel.ContextHandler=debug` `logging.level.reactor.ipc.netty.http.client.HttpClient=debug` in your `application.properties` file
Comment: @BrianClozel After adding debug levels, a large sections of log looks like tcp dump. Is there a way to view the body as text in the log file?
Answer: You should not change your list to flux, you should send it as list like this
return readWebClient.post()
  .uri("/v1/profiles/bulk")
  .syncBody(userIds)
  .retrieve()
  .bodyToFlux(new ParameterizedTypeReference<List<MiniProfile>>() {})
  .flatMapIterable(Function.identity());

this code is not tested but the principe is the same
Comment: thanks for your time to answer my question but there was nothing wrong with your code or my code but the real issue was on our .NET stack when we use Webflux Webclient to put or post on .NET stack we need to handle the raw request in .NET stack.
Answer: It's good to use WebClient for reactive call such this.
@Autowired
private WebClient.Builder webClientBuilder;

webClientBuilder.build().post()
                .uri("http://profile.service.com/v1/profiles/bulk")
                .body(BodyInserters.fromPublisher(Mono.just(new YourBodyClass()),YourBodyClass.class))
                .headers(httpHeaders -> {
                    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                    httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
                })
                .retrieve().bodyToFlux(MiniProfile.class);

Answer: Use .bodyValue(userIds) or .syncBody(userIds) (Deprecated) instead of body with Body inserter
Answer: **you can refer below mentioned code snippets **
WebClient.post().uri(endPointUrl)
           .contentType(MediaType.APPLICATION_XML)
          .body(Mono.just(xmlEntity), String.class)
          .retrieve()

Spring Webflux WebClient


Predicting from list of 120 models with multiples levels

Question: I have a data sets that has potential of being enormous with each Meter data i add. For now, i am only using 5 meters for example purpose. Here is what my data structure looks like:
str(Data1)
'data.frame':   43800 obs. of  7 variables:
 $ METER: Factor w/ 5 levels "10443720001539305",..: 1 1 1 1 1 1 1 1 1 1
 $ LOAD : num  87.7 101.5 96.5 92 185.6 ...
 $ TEMP : num  30.5 34 39 36.5 24.5 31.5 32.5 18.5 26.5 25.5 ...
 $ DAY  : chr  "WD" "WD" "WE" "WE" ...
 $ HDD  : num  34.5 31 26 28.5 40.5 33.5 32.5 46.5 38.5 39.5 ...
 $ CDD  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ HOUR : Factor w/ 24 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...

For each Meter, i am trying to get the 24 different hourly regression models total of 120 models.
Creating Model List & storing Coefficients.
cat1<-dlply(Data1, c("METER", "HOUR"), function(z) lm(LOAD ~ HDD + CDD +  DAY))
cat_COF<-ldply(cat1, coef)

PREDICTING FOR SAME DATA
Predicting for the same data was fairly straight forward.
cat_Pred<-ldply(cat1, predict, type = "response")

PROBLEM WHILE PREDICTING WITH NEW DATA
The real issue is while i try to predict with the new data set that has all the necessary information.
doesn't work
cat_Pred1<-ldply(cat1, predict, type = "response", newdata)

Is there a quick way for me to do the predictions from these list of models?
This is the closest example i came across but this only has one "state" level. It is little confusing to me & I have tried adding c("METER", "HOUR") but never seems to work for me.
Any help will be highly appreciated!!
using predict with a list of lm() objects
Answer: I am not sure if this is a good answer
I have a solution which seems like some manual work.
I noticed that you have an object called cat_COF I assume this is a
4 X 120 matrix. (4 because of the three regression coefficients +
intercept)  Assuming your newx object has an intercept column,
Could you try to multiply newx with cat_coef
If your newx has dimensions n X 4 matrix multiplication will be possible,
Basically the output will be a n X 120 matrix of predicted values.
I just tried thinking about it as Yhat = X beta-hat.
This might give you your predicted values.
Let me know if this helps.


How can I find the Boston Airport settlement?

Question: I see that there is a settlement called Boston Airport, yet I can't seem to find it in order to unlock it. Am I missing something plain, or is it a part of a quest or something like that?
Answer: The settlement area is pretty small, so it's easy to miss.
It is the small rectangular area depicted in the following picture, south-west of the parking garage and north-west of the airport itself:

The workshop is located near the wall at the back, between the two doors. Follow the red carpet.
However it can only be unlocked as part of a quest:

You need to side with the Brotherhood of Steel either during the quest The Molecular Level (so you can build the teleporter there) or wait for the quest Liberty Reprimed (You have some parts to build).

But you're not missing much, as the ground is 100% made of concrete; you can't plant any food, which have been removed from the build bar anyway. There are some sweet spots where you can place water though.
It is also impossible to build a recruitment beacon to gain settlers (You have to move them there manually), guard posts, any type of stores, salvage stations or artillery pieces. Those items are also missing in the build bar.
This settlement is really focused around the two quests mentioned previously instead of being a viable place to build a thriving settlement.
Comment: I think you get access to the Boston Airport as soon as you board the Prydwen.
Comment: I didn't do either of the things you suggest for unlocking this area, and still got access to it. Don't remember what the trigger was though.
Comment: @Iszi have you finished the main quests of the game? I guess it will unlock after the story if you don't side with the faction controlling it before.
Comment: Nope. I'm past both of the points you've mentioned, but I didn't use the one faction in the first quest and I had the settlement unlocked (and cleared for scrap) well before the second. I'm pretty sure I recall having had it unlocked even before the first, but I don't remember the trigger. Maybe the warehouse investigation?
Comment: Nukapedia seems very unclear on the trigger. Claims it can be done before BoS shows up, or as part of a few different quests. The wiki on Fextralife concurs with one of those quests.
Comment: @DCShannon What if you never visit the brotherhood? Would it unlock anyway after the story?
Comment: @Pierre-LucPineault I don't know. Probably. I could check, as I believe I have a couple finished playthroughs where I never joined the Brotherhood. I'll get back to you if/when I remember.
Comment: For me, it was unlocked when I boarded the Prydwen
Answer: It's part of the brotherhood quest line.  At some point they ask you to build some components for a project at the workbench that will be used for:

 Liberty prime

You can't build a radio tower there so you can't attract settlers.  There is a mod that can change that though.
Answer: No food can be placed that I know of. However, I sent a settler there for a supply line and built a beacon to get settlers. Was not able to build much at all. It said the limit was reached.
I was able to unlock it through the Brotherhood quest line after being on the Prydwen or whatever their ship is called.


The announcer keeps mocking me. How do I shut him up?

Question: I am playing Sonic and SEGA All Stars Racing and it seems like the announcer doesn't like me very much. He keeps mocking my racing and being rather annoying.
Is there a way to shut him up so he stops driving me crazy?
Comment: I assume other than mute your TV? :P
Comment: Ullallulloo beat me too it :P
Comment: Yeah, ideally, I would like something other than muting my TV. I like the other in-game sounds.
Comment: Shoot him in his knee with an arrow. ^_^
Comment: i bought him a birthday gift. it was awkward at first - he hadn't had a friend before. we went fishing together. a cold breeze skating over waters. over time, shared failures with helped success, summer chased away the cold. he's only ever been supportive of me since then.
Answer: I don't have the game any more, but I think if you go into Settings > Audio Settings there may be an option to turn off the commentary (maybe depends on which platform?)
Comment: Yeah, there is an option in the audio settings to turn him off completely. Hurrah!


The html page not showing correct link when using htmlunit driver

Question: I have written a selenium script which runs in java :
<code>    String pageName = "my test url which invloves an link to html which has javscript excution";
    logger.log(Level.INFO,"Page name : " + pageName);
    WebDriver driver = new HtmlUnitDriver(true);

    logger.log(Level.INFO,"driver instance created " );
    String str ="";

    logger.log(Level.INFO,"opening the url now.... " );
    driver.get(pageName);
    logger.log(Level.INFO,"url is now opened :: url = "+driver.getCurrentUrl());
    logger.log(Level.INFO,"driver now going to sleep = "+driver.getCurrentUrl());
    Thread.sleep(150000);

    logger.log(Level.INFO,"Wake up from sleep now....");
    logger.log(Level.INFO,"URL ::"+driver.getCurrentUrl());
    logger.log(Level.INFO,"PageSource ::"+driver.getPageSource());
    try {
        logger.log(Level.INFO,"Driver going to wait now...");
        driver.wait(100000);
        logger.log(Level.INFO,"Driver came out of wait now normally...");
    } catch (Exception e) {
        logger.log(Level.INFO,"Driver came out of wait now exception::"+e);
    }

    logger.log(Level.INFO,"driver instance task completed " );
    logger.log(Level.INFO,driver.getCurrentUrl());

    logger.log(Level.INFO,driver.getCurrentUrl());
    logger.log(Level.INFO,str);

    driver.close();
</code>
Now when I debug this code I get my proper result but when I run this piece of code from servlet I get only the html content not the proper content which is excepted to come from the given link.
I also tried using the firefox driver and the same code works fine with it.
I also tried the same code with Web client but the same problem is coming.
Can anyone help me with this exception?
Thanks,
Answer: When you debug the code, you can halt at checkpoints. But you cannot stop browser from loading. It loads itself independently.
Htmlunitdriver pagesource returns all html contents as it cannot execute javascript completely.If the htmlpage contains Ajax, javascript calls then it shows the calls as it is .


Set a child's value after sorting from another child

Question: What I want to do is pull the top 3 under questsLeaderboard, sorted by score, then replace the existing children in questsTop with these new top 3.
So if questsLeaderboard looks like:
- questsLeaderboard
  - uid1
    - score: 12
    ...
  - uid2
    - score: 3
    ...
  - uid3
    - score: 10
    ...
  - etc

And I want questsTop to look like:
- questsTop
  - first
    - score: 12
    ...
  - second
    - score: 10
    ...
  - third
    - score: 3
    ...

I have tried this:
export const updateBoards = functions.https.onRequest((req, res) => {
  let questsArr = [];
  const questsRef = db.ref('questsLeaderboard');
  const questsTopRef = db.ref('questsTop');

  questsRef.orderByChild('score').limitToLast(3).on('child_added', (snapshot) => {
    questsArr.unshift(snapshot);
  });

  if (questsArr.length === 3) {
    questsTopRef.set({
      first: questsArr[0],
      second: questsArr[1],
      third: questsArr[2]
    })
    .then(() => {
      res.status(200).send('top quests set');
    })
    .catch(err => {
      res.status(500).send(err);
    })
  }

})

But it gives a timeout error. What can I do?
Answer: You can't reliably use on() in Cloud Functions, since the listener will remain active. Also: what will happen with your code if there are fewer than 3 scores? The if (questsArr.length === 3) will never be true, and you'll never send a result back to the client.
You'll want to use a once("value" listener instead, like this:
export const updateBoards = functions.https.onRequest((req, res) => {
  let questsArr = [];
  const questsRef = db.ref('questsLeaderboard');
  const questsTopRef = db.ref('questsTop');

  return questsRef.orderByChild('score').limitToLast(3).once('value', (snapshot) => {
    snapshot.forEach(function(child) {
      questsArr.unshift(child);
    })
    return questsTopRef.set({
      first: questsArr[0],
      second: questsArr[1],
      third: questsArr[2]
    })
    .then(() => {
      return res.status(200).send('top quests set');
    })
    .catch(err => {
      return res.status(500).send(err);
    })
  });
})

You'll also note that I added return statements to all the asynchronous database operations, to ensure that Cloud Functions keeps your function alive until the read and write are finished. For more on this, see the second example in this documentation section.
Comment: thanks for the reply, I've changed it to your answer but where it is doing `forEach` it is telling me `Argument of type '(child: DataSnapshot) => void' is not assignable to parameter of type '(a: DataSnapshot) => boolean'.
  Type 'void' is not assignable to type 'boolean'.` Upon removing the forEach and just going with the `unshift(snapshot)`, I get an error in the console `Reference.set failed: First argument contains a function in property 'questsTop.first.node_.children_.comparator_' `
Comment: I just fixed a mistake in that loop (I should push `child` instead of `snapshot`). But I don't think that causes the error you have. I'm not sure where that error comes from.
Comment: Yeah, the `function` part of that forEach loop is underlined, so the error wasn't fixed :/. And I think there is an issue with setting questsArr[num] as a value.


Call it log, History, Events, Activity, etc

Question: I have an application, where everything is logged so that a user, later on, can look through all activity. It is just a small part of app. But what do I call this "log" so that even a child would understand what it's there for, the best I came up with was "What's happened.."
Any suggestions?
Cheers!
Comment: Is this for a child?
Answer: On Facebook, it's called the Activity Log, and you can "View Activity Log" from your Facebook page.
On GNOME, it's called the Activity Journal.
A log or journal is normally a known word to a native English speaker, and the prefix activity should suffice for a native to properly contextualise it.
Do you have a specific user population in mind? If so, you should document it with more details in your question.
Comment: The user could be an experienced IT-manager or a corner shop owner with little to no experience with the terms we use in the digital world.
Answer: We usually like naming things based on the language used by our users. As we're doing user research we pay close attention to the words and phrases they use. There are usually other words that don't come up naturally during the session that we might ask about directly: Shopping Cart, Reporting, etc.
If your app is for general use, you can still talk with likely users. Or just pick a common word (some competitive research can help here).


What Magic Hat does in Escape Goat?

Question: I found a Magic Hat in one of the first 6 levels of Escape Goat. My animal little friend now wear this item but what properties gives to him?
Answer: When you have the magic hat you can press v to switch places with your magical mouse.

Image from the Escape Goat website

What Magic Hat does in Escape Goat?


Contact Detection in Swift

Question: I'm coding a simple game where the player must avoid obstacles as he plays, so I need to be able to check when the player makes contact with an obstacle. After following countless tutorials, I'm still not able to make it work. This is my code right now (I've taken out anything not relating to contact detection):
<code>import SpriteKit

class GameScene: SKScene {

  struct PhysicsCategory {
    static let none      : UInt32 = 0
    static let all       : UInt32 = UInt32.max
    static let MrPig   : UInt32 = 0b1       // 1
    static let obstacle: UInt32 = 0b10      // 2
  }

  let airObstacles = ["spikeRectangle", "spikeSquare", "topSpikes", "bottomSpikes"]

  let mrPig = SKSpriteNode(imageNamed: "mrPig")

  var touching = false

  override func didMove(to view: SKView) {

    mrPig.physicsBody = SKPhysicsBody(circleOfRadius: projectile.size.width/2)
    mrPig.physicsBody?.isDynamic = true
    mrPig.physicsBody?.categoryBitMask = PhysicsCategory.MrPig
    mrPig.physicsBody?.contactTestBitMask = PhysicsCategory.obstacle
    mrPig.physicsBody?.collisionBitMask = PhysicsCategory.none
    mrPig.physicsBody?.usesPreciseCollisionDetection = true

    mrPig.position = CGPoint(x: 100, y: 80)
    mrPig.zPosition = 2
    mrPig.setScale(0.2)
    addChild(mrPig)

    physicsWorld.gravity = .zero
    physicsWorld.contactDelegate = self

    run(SKAction.repeatForever(
      SKAction.sequence([
        SKAction.run(moveDown),
        SKAction.wait(forDuration: 0.1)
      ])
    ))

    run(SKAction.repeatForever(
      SKAction.sequence([
        SKAction.run(createObstacle),
        SKAction.wait(forDuration: TimeInterval(objectSpeed))
      ])
    ))
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
      touching = true
      mrPig.run(SKAction.moveTo(y: size.height - 20, duration: 0.8))
    }
  }

  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
      touching = false
    }
  }

  func moveDown() {
    if touching == false && mrPig.position.x > 80 {
      mrPig.run(SKAction.moveTo(y: 80, duration: 0.5))
    }
  }

  func createObstacle() {
    let airObstacle = SKSpriteNode(imageNamed: airObstacles.randomElement()!)

    airObstacle.physicsBody = SKPhysicsBody(rectangleOf: airObstacle.size) // 1
    airObstacle.physicsBody?.isDynamic = true // 2
    airObstacle.physicsBody?.categoryBitMask = PhysicsCategory.obstacle // 3
    airObstacle.physicsBody?.contactTestBitMask = PhysicsCategory.MrPig // 4
    airObstacle.physicsBody?.collisionBitMask = PhysicsCategory.none // 5

    airObstacle.position = CGPoint(x: size.width, y: 200)
    airObstacle.zPosition = 2
    addChild(airObstacle)
    let moveAirObstacle = SKAction.moveTo(x: 0, duration: 2)
    let moveAirObstacleDone = SKAction.removeFromParent()
    airObstacle.run(SKAction.sequence([moveAirObstacle, moveAirObstacleDone]))
    }
  }
}

extension GameScene: SKPhysicsContactDelegate {
  func didBegin(_ contact: SKPhysicsContact) {
    // 1
    var firstBody: SKPhysicsBody
    var secondBody: SKPhysicsBody
    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
      firstBody = contact.bodyA
      secondBody = contact.bodyB
    } else {
      firstBody = contact.bodyB
      secondBody = contact.bodyA
    }

    // 2
    if ((firstBody.categoryBitMask & PhysicsCategory.obstacle != 0) &&
      (secondBody.categoryBitMask & PhysicsCategory.MrPig != 0)) {
      print("game over")
    }
  }
}
</code>
I'm relatively new to coding, and this is the first game I've ever made with swift. Any help would be much appreciated!
Comment: What do you mean by collision detection?  When it comes to SpriteKit, collision and contact are two different physical phenomena.
Comment: My bad, I guess I meant contact detection. Thanks!
Comment: What's working so far?  If you insert print("") inside didBegin, do you get a call?
Comment: nope, nothing prints. the did begin function isn't being called at all.
Comment: Setting up the contact bit mask and the collision bit mask can be quite confusing especially if you have a lot of characters involved in the game.  I would try setting the contact bit mask of mrPig to 2, the contact bit mask of the obstacle to 0.
Comment: Wait...  Have you added `SKPhysicsContactDelegate` to your game scene?
Answer: Have a read of these previous answers:
My step-by-step guide for collisions and contacts:
https://stackoverflow.com/a/51041474/1430420
And a guide to collision and contactTest bit masks:
https://stackoverflow.com/a/40596890/1430420
Manipulating bit masks to turn individual collision and contacts off and on.
https://stackoverflow.com/a/46495864/1430420

Contact Detection in Swift


Why am I losing power after I fire my weapons?

Question: I've started playing Space Pirates and Zombies, and while I am enjoying it immensely, I've come across an issue that I am sure someone here would be able to shed some light on.
I have found that with one of my ships, once I fire my weapons, I do lose energy for the shot itself, which makes perfect sense, but then I lose even more energy after I've fired my weapons. Here is a video clip demonstrating the issue:

And here is the configuration of the ship in question:

The ship is equipped with a pair of small overload emitters:

I originally thought firing the weapons removes my cloak, so that the additional power draw is for reestablishing it, but after swapping it out for a shield the situation did not change.
So, what's up with this mysterious power draw?
Comment: Does this still happen if you use a regular shield instead of cloak?
Comment: @yx. It does still happen. The plot thickens.
Answer: I tested this with shields instead of cloak, and I had the same result - my energy continued to drain after the emitters were finished firing.  At first I thought that it was perhaps a bug, as switching to other weapon types doesn't yield this behavior.
Then I noticed that the small orange "glow" around the emitters was running in reverse when the second power drain occurred.  This leads me to believe that perhaps the emitters take some energy to fire, and then some energy to recharge for the next shot.
Comment: Yup, I noticed this while playing the game as well. There's no background information to support it, but here's my theory: emitters in SPAZ are analogous to real systems like a camera flash or a railgun, where you need to drop a ton of energy all at once. Normally, your battery or household power won't support something like that, so what you do is you slowly charge up some capacitors, and then let them release the violent burst of energy. If SPAZ emitters used something like that in the fluff, it would be consistent with their reactor usage cycles.
Comment: Yes, I guess this is just how beam weapons act (thanks for the real-world perspective on this, @Tacroy). This is strengthened by the [beam booster module's](http://i.imgur.com/eGLtF.png) description, which talks about recharge and recycle times.
Comment: @Tacroy, this is pretty much exactly what I had in mind.


Error handling in ServiceStack new API

Question: I have simple service stack web service that takes Name as input parameter. From this thread, I understand ResponseStatus property is no longer required when using new API. But when I tried to compose a request with no Name using fiddler, it returns 400 response code as expected but didn't contain any information regarding the exception. So, does new API  provide error description out-of-box especially for non .NET clients. If it doesn't, is there possible way to provide this information.
public object Any(CustomerRequest request)
{
   if (request.Name == null)
   {
     throw new ArgumentException("Name is required");
   }

   var objCustomer = //get customer from DB

   return objCustomer;
}

public class CustomerRequest
{
   public string Name {get;set;}
   public bool IsActive {get;set;}
}

Comment: Using the fiddler composer or Firefox I get the JSON object: `{"ResponseStatus":{"ErrorCode":"ArgumentException","Message":"Name is required","Errors":[]}}`. For brevity I disabled the stacktrace.
Comment: Also here is a link to the test code http://pastebin.com/vqZSRs2n
Comment: What is your service class inheriting from?
Comment: class CustomerService : Service
Comment: I wrote a quick test project based on the information in the question. I receive an 400 http code and an Error response in the body. A 500 error is for internal server errors so I think there could be a bug in your test project.
Comment: I'm sorry, it returns 400 code. And I am testing the service using fiddler customer?format=json, does the response include error status as property.
Comment: When I debug, ArgumentException is thrown but the json is blank. Url is http://localhost:82/api/customer?format=json and GET operation. As mentioned in the OP, response object doesn't have ResponseStatus property. All I receive is blank with status code 400.
Comment: But when I add ResponseStatus property to response object, it is getting populated. So, do I need it per new API?
Comment: Can you upload your test project to dropbox or similar. I'll have a look at it and try to see what the problem is.
Comment: Thanks very much for your followups. As the answer suggested, issue was with response name. It was CustomerResponse, so I had renamed it and it worked just fine.
Comment: But I've problem with naming convention now, I've followed same as ServiceStack tests code. Now I am wondering how to name service, request and response. It is not like Todo's example, where they pass in Todo and receive Todo. My application has only GET operations, so request will have no relation with response. Any feedback appreciated.
Comment: Ok, I've CustomerService, CustomerRequest, Customer (response), do you guys foresee any problems with these names.
Answer: You shouldn't need to add ResponseStaus with the new API. As per penfold's example, you should get {"ResponseStatus":{"ErrorCode":"ArgumentException","Message":"Name is required","Errors":[]}} as a response.
Do you still have a CustomerResponse class in your codebase? If so, try commenting it out or removing it. Even though you are returning object when an Exception occurs ServiceStack will still look for the conventionally-named Response type (see here) and try to fill the ResponseStatus property.
Comment: Thanks for the catch. Now, I am left with naming convention problem  posted in the comments above, can anyone please advise.
Comment: Can you be more specific about the 'naming convention problem'? If you return 'object' for your Service(s) the CustomerResponse class (and other 'Response' classes) is dead code so remove it. Do you have a need for the CustomReponse that I'm missing? If so maybe post another question.
Comment: Yes, I am just sending customer as response so that solves the problem. But if I'd to send custom response, then it should also be the same right, I mean populate the customer into the custom object and return it. Since return type is object.
Comment: I wish the [wiki](https://github.com/ServiceStack/ServiceStack/wiki/Error-Handling) included this!

Error handling in ServiceStack new API


How to cancel navigation when user clicks a link ( element)?

Question: I'm trying to load some stuff using AJAX when a user clicks a link, but I want the link to actually go somewhere so that the app still works when javascript is disabled. Is there any way to just do something with javascript and cancel navigation when a link is clicked?
What's the best practice? Can that be done, or do I need to replace the link using javascript or what?
Answer: If you have HTML like this:
Do Something

You would do something like this with jQuery:
$(document).ready(function() {
    $('#mylink').click(function() {
        doSomethingCool();
        return false; // cancel the event
    });
});

All you have to do is cancel the click event with Javascript to prevent the default action from happening. So when someone clicks the link with Javascript enabled, doSomethingCool(); is called and the click event is cancelled (thus the return false;) and prevents the browser from going to the page specified. If they have Javascript disabled, however, it would take them to no_javascript.html directly.
Comment: +1, but a lot of people will put href="#" in the links they plan on using with javascript.
Comment: @Gromer - The idea is to make it work with or without javascript.
Comment: No as my code is, David. Only if you neglect to return false;
Comment: okay, I'm an idiot. I thought that was the thing to do but it wasn't working. turns out it was just IE caching the javascript so it wasn't executing my new line with return false.
Comment: @Gromer - But, the point of the question that Max asked was if there was a way for the link to work as usual if the user doesn't have javascript enabled. Of course, href='#' would work, but it wouldn't do anything (other than change the URL hash), and hence lead to a poor user experience.
Comment: Try this href: "javascript:void(0)"
Answer: None of this worked for me with the Google Chrome browser.
Here's what did work though (using jQuery):
$(document).ready(function() {
    $('#mylink').click(function(event) {
        doSomethingCool();
        event.preventDefault(); // cancel the event
    });
});

Comment: Returning false does work for IE, but not for Firefox or Chrome; This solution did work for both, Thanks!
Comment: Two additions: 1) One may want to call preventDefault() before doing something cool. 2) Add this in the beginning of the function to support middle mouse button correctly: if(event.which != 1) return;
Comment: `return false;` is not working in my case for chrome, but this solution worked. Thanks.
Answer: why jQuery?
HTML:
Link

...and javascript code:
function doSmth(){
  // your code here
  return false
}

Comment: Javascript frameworks are useful on all size sites that care about browser compatibility. Plus, using inline events is a bad practice overall.
Comment: THANKYOU!!! man... people let go of jQuery ... at least if you do not need its more higher functions! Thanks for the post!
--
This also works

onclick = "return false;"

This is handy if you are using google polymer and using the on-tap="{{func}}" handyness
Comment: +1 for not laming out like an amateur and dumping 70KB of crap that the browser *already* competently handles.
Comment: ok, i see. I think frameworks may be useful to big powerful projects. But for small sites...
Comment: Well I am working with jQuery (like the majority of people on this site it seems), even though I didn't specify... but thank you for the post, it may be useful to somebody.
Comment: there are no needed frameworks at http://4px.ru/ (:

Using inline event isn't bad for one element. And for many similar elements with similar actions we can set event handlers by script.
Answer: What I would do are :
a. for href attribute, javascript:void(); will be set
b. for onclick event, will provide a function to handle the click event and that     function will return false.
eg:

   Link

Answer: Test

with jQuery:

with JavaScript

You assign class .ignore-click to as many elements you like and clicks on those elements will be ignored
Answer: for IE at least, just put this.event.returnValue = false; at the end of the method.
e.g:
function onClickFunction()
 {
  someMethod();
  this.event.returnValue = false;
 }

I had a complex method where this did the trick.
Answer: I use document.location.replace to navigate, but when I want to cancel the navigation, return false (in the same function as document.location.replace) doesn't cancel the navigation.
Answer: The best way should be this.

Answer: I just used
 {
  event.preventDefault()
}}>Take me away

In my use case I wanted to perform some actions before navigation.
Answer: CANCEL CLICK ON LINK tag A

at the moment of holding the click, check the condition data and assign state activity for link

Implemented scrolling of a horizontal slider. Hold down the click and move the content left and right.
There were links inside the content that should remain active when an element is selected, but when you hold the mouse and do move, cancel the event for inner tag a
let linkActive;
let cont = document.addEventListener('.cont');

let toggleActiveEvent = (prop, event, revoke) => {
    if (event.target.tagName === 'A' || linkActive) {
        (linkActive ? linkActive : event.target).style.pointerEvents = prop;
        linkActive = revoke ? null : event.target;
        return event.preventDefault();
    }
};

cont.addEventListener('mousedown', (event) => {
    toggleActiveEvent('none', event);
});
cont.addEventListener('click', (event) => {
    event.preventDefault();
});
cont.addEventListener('mouseup', (event) => {
    toggleActiveEvent('all', event, true);
});

МАКЕТ

Supported BROWSERs for CSS pointer-events (for HTML)
Answer: is simple, use rel="nofollow" attribute
 sign in

Comment: rel=nofollow is completely irrelevant. This is for SEO and not for browsers


How do I move my daughter to my manor?

Question: I'm not married, but I have adopted a daughter and she is staying in Whiterun. I would like to move her to Lakeview Manor. It is completely furnished and everything and I have told her that we were going to move, but all it did was give me the speech option saying "Nevermind, we're staying here," and leaves my daughter (Lucia) upset.
What else do I have to do to make the manor appropriate to move to?
Comment: Just to confirm; you have a fully furnished Main Hall, yes? Also, if you furnished your manor by purchasing from your steward rather than building- That option is notoriously slow, and it might be some time before all the furniture appears. The child's bed and/or the container they require to be present in order to move in might be in the queue to appear.
Answer: You need beds and containers.
Your child or wife won't move if you don't have enough beds / containers.
Comment: Specifically, you need a *child's bed* and a specific container that is often next to said bed.
Answer: In your Falkreath House, make sure in your Bedroom wing you have both child's beds and chests, since you have a child. if you don't have the bedroom wing, furnished the upstairs room where you have to furnish the single beds and the drawer. If you did all of that and you still have a problem, download the Unofficial Hearthfire Patch to fix this problem.

How do I move my daughter to my manor?


Latest record and sum SQL

Question: I'm looking for solution for this problem.
Table:

i want this output (show latest tier based on maximum transaction id)
Comment: Most people here want formatted text, not images (or links to images.)
Comment: Most people consider all caps in a title shouting.
Comment: Tag the DBMS (i.e. `MySQL`, `SQL Server`, etc..) that you are using.
Comment: How do you choose which tier to select for trans_id?
Answer: You can do :
select *, sum(select sum(t1.poin)
              from table t1
              where t1.member_id = t.member_id
             ) as poin,
          sum(select sum(t1.freq)
              from table t1
              where t1.member_id = t.member_id
             ) as freq
from table t
where trans_id = (select t1.trans_id
                  from table t1
                  where t1.member_id = t.member_id
                  order by t1.trans_id desc
                  fetch first 1 rows only
                 );

Most DBMS has support fetch first 1 rows only method.
If, you are working with SQL Server, then you can directly express it as :
select t.member_id, tt.*
from (select *, row_number() over (partition by member_id order by trans_id desc) as seq
      from table
     ) t cross apply (
            select sum(t1.poin) as poin, sum(t1.freq) as freq
            from table t1
            where t1.member_id = t.member_id
     ) tt
where t.seq = 1;

Comment: Thank you so much for your help sir. It works well.
Minor correction, first row, type: select t.member_id, t.tier, tt.* to get tier information.
Really appreciate it. :)

Latest record and sum SQL


Non persistent record and delayed jobs

Question: Is there a way to add a non persistent record to delayed job? I recently updated my Rails version, but now I can't add a non persistent record to delayed job.
This is my class:
<code>class InfoPackDownload

  include ActiveAttr::Model
  include ::NewRelic::Agent::MethodTracer

  attribute :course_id
  attribute :first_name
  attribute :last_name
  attribute :email
  attribute :telephone
  attribute :receive_newsletter, type: Boolean
  attribute :filename
  attribute :course_code
  attribute :programme_instance_code
  attribute :presentation
  attribute :title

  validates_presence_of :first_name, :last_name
  validates :email, presence: true, email: true

  def send_interaction
    body_params = create_request_body
    request = build_request body_params
    send_request request
  end
end
</code>
I am trying to add the following method to delayed job:
<code>@info_pack_download.delay(queue: 'info_pack_download').send_interaction
</code>
But when I call this method, an error is raised for adding a non persistent record to delayed job.
Can anyone offer some advice on this problem?
Comment: Maybe put the error raised in the description? Seems to be kind of important
Answer: Delayed job needs to store the arguments for the job to the database, so that it can retrieve them later once the job gets scheduled.  If it's a simple ruby object, it can serialize it to a string (to_json), and store that.  If it's a database model, it stores the ID and the class name.
When the job gets scheduled to run, it needs to pull the arguments out of the database.  For the simple model, it can deserialize the string (JSON.parse), for the database model, it can load the model from the database using the class name and ID.  You are not providing a way to do either.

Non persistent record and delayed jobs


Convergent sequences transformed into convergent sequences

Question: Problem. Find all the $f: \mathbb{R} \to \mathbb{R}$ (not supposed continuous) such that for every real sequence $(a_n)$ we have : $$\sum  a_k \; \text{is convergent} \Longrightarrow \sum  f(a_k) \; \text{is convergent}$$
I'm trying to prove that the only functions are linear in a neighborhood of $0$. It is clear that those functions work but for the reciprocal it is much harder since $f$ is not supposed of any regularity. I have proven that :

$f(0)=0$
$f$ is continuous in $0$ : if it's not the case we can set $ \varepsilon >0$ and a sequence $(a_n)$ such that $|a_n|  \leqslant 2^{-n}$ and $|f(a_n)| \geqslant \varepsilon$ which is absurd.

Any ideas to show that $f(x+y)=f(x)+f(y)$ near $0$ ? (which would be sufficient to prove the result)
Thanks !
Comment: @Nate River: Take $a_n$ such that $a_{3k}=a_{3k+1}=\frac{1}{b_k}$ and $a_{3k+2}=-\frac{2}{b_k}$ with $b_k$ equal to the cubic root of $k$
Comment: The title should refer to convergent _series_, not sequences...
Comment: @NateRiver Yes it does. The partial sums $s_{3n}$ all vanish; since $a_n\to0$ it follows that the sum is $0$.
Comment: Yes: If $S_n$ is the sum of the $n$ first terms, gouping the terms $3$ by $3$ with the possible exception of the term $a_n$, or the terms $a_n$ and $a_{n-1}$, give $S_n\to 0$.
Comment: This is definitely a duplicate. Let me try to find the earlier post.
Comment: @Kelenner I see, thanks. I stand corrected
Comment: I looked for the question on the site but bever found such a question. Thank you for giving me a thread where the question was debated !
Answer: EDIT: Turns out I found Smith's proof of Wildeberg's theorem. Knew it must be an old question, thought the nice little proof might be interesting. Oh well...
As you point out, it's enough to show that $f(x+y)=f(x)+f(y)$ for all sufficiently small $x$ and $y$. Suppose this is false.
Then there exist sequences $x_k\to0$ and $y_k\to0$ such that $$f(x_k+y_k)-f(x_k)-f(y_k)\ne0.$$
Consider the series that consists of the three terms $(x_1+y_1) - x_1 - y_1$ repeated $N_1$ times, followed by the three terms $(x_2+y_2) - x_2 - y_2$ repeated $N_2$ times, etc. Since $x_k\to0$ and $y_k\to0$ it's easy to see that this sum converges.
But the sum of the first $3N_1$ terms of the series with $f$ applied is $$N_1(f(x_1+y_1)-f(x_1)-f(y_1)),$$which we can make as large as we like by taking $N_1$ large enough. Similarly we can make the sum of the next $3N_2$ terms of the modified series as large as we like. Taking an appropriate sequence $N_k$ we see that the new series diverges.


Swift : Clear UIView

Question: I'm using PNChart in a UIView and overtime my method runs it adds an addition line to the graph rather than recreating the entire graph. How do I clear a UIView, before add[ing]Subview?
     @IBOutlet weak var lineChart: UIView!

    ...
    // in function
    theLineChart.chartData = [actualData]
    theLineChart.strokeChart()
    // want to clear self.lineChart here
    self.lineChart.addSubview(theLineChart)

Answer: If by "clear" you mean remove all previously added subviews from it, you could try something like:
while let subview = lineChart.subviews.last {
    subview.removeFromSuperview()
}

The caveat is that lineChart should remain a plain UIView (or your self-made subclass that you know the implementation of), as otherwise it may have internal subviews that you shouldn't remove.
Then again, if it is nothing but a plain UIView, you could simply replace the whole view with a new one (this might even make it simple to cross-fade between old and new views if such is desired).

Swift : Clear UIView


Returning a Poco session without creating new connection

Question: Depending on if a condition is met I want to return a session but don't want to create a new connection.
Poco::Data::Session initialise(){
 if(some condition){
   Poco::Data::Session temp1('odbc',someSettings1)
   return temp1

  }else{
   Poco::Data::Session temp2('odbc',someSettings2)
   return temp2
   }
}

int main(){
 Poco::Data::Session  sess(initialise());
}

Does the above create a new connection when I pass the function as a constructor argument?
Would it make a difference if I returned it as an anonymous object i.e. return Poco::Data::Session('odbc',someSettings1)
Or is there a better way overall to achieve what I want?
Answer:
yes

no

To prevent the creation of new connection, make one of the sessions in the function static:
Poco::Data::Session initialise()
{
static Poco::Data::Session temp1('odbc',someSettings1);
if(some condition)
return temp1
else
{
Poco::Data::Session temp2('odbc',someSettings2)
return temp2
}
}
int main(){
Poco::Data::Session  sess(initialise());
}
Comment: not sure why code formatting does not work - I selected the code and clicked {}


Compute $\sum\limits_{n=0}^{\infty}\frac{1}{(2n+1) . 4^n} $

Question: $\displaystyle\sum_{n=0}^{\infty}\frac{1}{(2n+1) . 4^n} $
Can anyone tell me how to approach? It must be convergent as $\displaystyle\sum_{n=0}^{\infty}\frac{1}{4^n}$ is convergent. and answer will be less than 4/3.
but how to approach I can not see?
Comment: See also: [Sum of the series $\sum_{n=0}^{\infty} \frac{1}{4^n(2n+1)}$](https://math.stackexchange.com/q/1693720). Found [using Approach0](https://approach0.xyz/search/?q=%24%5Csum%5Climits_%7Bn%3D0%7D%5E%7B%5Cinfty%7D%5Cfrac%7B1%7D%7B(2n%2B1)%20.%204%5En%7D%24&p=1).
Comment: Can you show that $\frac{1}{2n+1}\cdot\frac{1}{4^n}\leq\frac{1}{4^n}$ and use the comparison test?
Comment: Note that this is the same as $\displaystyle\sum_{n=0}^{\infty}\frac{1}{(2n+1)} (\frac 1 4)^n$, which is a power series where $x = \frac 1 4$
Comment: Sorry but the tags (ramanujan-summation) and (summation-by-parts) are offtopic here. The tag (summation) is offtopic as well, but the reason is more subtle. Anyway, please check the meaning of the tags before using them.
Answer: Hint. One may write
$$
\sum_{n=0}^{\infty}\frac{1}{(2n+1)4^n}=2\sum_{n=0}^{\infty}\int_0^{1/2}t^{2n}dt=2\int_0^{1/2}\sum_{n=0}^{\infty}t^{2n}dt=\int_0^{1/2}\frac2{1-t^2}\:dt
$$ the latter may be evaluated by a partial fraction decomposition.
Answer: $$\sum_{n=1}^\infty\dfrac1{(2n+1)4^n}=2\sum_{n=1}^\infty\dfrac{(1/2)^{2n+1}}{2n+1}$$
Now for $1\ge x>-1,$ $$\ln(1+x)=x-\dfrac{x^2}2+\dfrac{x^3}3-\cdots$$
$$\ln(1+x)-\ln(1-x)=?$$
Comment: See also : http://math.stackexchange.com/questions/365516/why-does-the-taylor-series-of-ln-1-x-only-approximate-it-for-1x-le-1
Comment: correct the rang of x @lab
Comment: @sani, Thanks for your observation
Answer: $$\sum_{n=0}^\infty q^n = \frac{1}{1-q}$$
$$\sum_{n=0}^\infty x^{2n} = \frac{1}{1-x^2}$$
$$\int\sum_{n=0}^\infty x^{2n} = \int\frac{1}{1-x^2}$$
$$\sum_{n=0}^\infty \frac{x^{2n+1}}{2n+1} = \tanh^{-1}(x)$$
$$\sum_{n=0}^\infty \frac{x^{2n}}{2n+1} = \frac{\tanh^{-1}(x)}{x}$$
$$\sum_{n=0}^\infty \frac{t^{n}}{2n+1} = \frac{\\tanh^{-1}(\sqrt{t})}{\sqrt{t}}$$
Now evaluate at $t=1/4$
Comment: Note that $\int\frac{1}{1-x^2}=0.5(\log(x+1)-\log(1-x))=arctanh(x)$


New breaker and panel: What's the brown goo where they connect?

Question: I'll be replacing my electrical panel soon and I noticed that the new breakers and panel have a brown goo on them where they connect to one another. I'm guessing it is lubricant .. similar to what goes in the aluminum wires but I rather make sure than end up with fireworks.
Should I leave the brown goo in place before I plug the breakers to the new panel or should I wipe it out? Thanks.
Answer: Leave it there. It's a dielectric grease that prevents corrosion on the metal contacts. It probably does also act as a lubricant for easier installation.
Comment: The contacts aren't steel, but yes -- it's an antioxidant/dielectric material.
Answer: It looks like no-ox-id. This is a special anti oxide lubricating grease.


Installing ubuntu on a parition with usb installation

Question: i have a main windows drive which is full and a 2tb drive which i use for my high storage apps/games, I partitiond 600gb of my 2tb drive which i chose as the location to install ubuntu, on ubuntu installation what device do i use for my boot loader installation.
Comment: Is Windows UEFI? And HDD, gpt partitioned? Only use Something Else install option, but choice of boot loader location only works with BIOS/MBR installs. If UEFI, you want an UEFI install.  https://help.ubuntu.com/community/UEFI Second drive
https://askubuntu.com/questions/1296065/dual-booting-w10-ubuntu-with-2-separate-ssds-in-uefi-mode/1296153#1296153 &
https://askubuntu.com/questions/16988/how-do-i-install-ubuntu-to-a-usb-key-without-using-startup-disk-creator/1056079#1056079 & http://askubuntu.com/questions/743095/how-to-prepare-a-disk-on-an-efi-based-pc-for-ubuntu
Comment: I would unplug your Windows drive and then install to the 2TB drive in the same BIOS/UEFI mode Windows is installed in. After install plug in Windows and run `sudo update-grub` to add windows to the Ubuntu boot menu.
Answer:
Open command prompt
Type diskpart
In the new window type list disk
Identify your 2tb drive
For example let your 2tb drive be disk 1
Type select disk 1
Type list vol (vol means volume present in the selected disk)
Now check for the 600gb volume. Just check the space and you can.

Still if you can't then format the volume to any another type which is not being displayed like fat32. With that you may identify the volume then check where it says it's location
Try using the disk manager of windows.
If you wanted to learn how to boot from live usb then use BIOS/UEFI and make sure that Boot from external device is on and the priority is first.


Is my controller broken?

Question: Whenever I play first person shooters, I push the left stick up, and my gun shoots. Rt is to walk. But when I go to my controls, it is set to default, which is left stick to move, and Rt is shoot. Is it the game, or my controller?
Comment: What other games use the Lt?  If you know what it's supposed to do, you can test if it does the same thing by wiggling the left analog stick.
Comment: Again, does it do that in other games?  This is an easy thing to test.  If it does, it's your controller.  If it doesn't, there's something in your games.
Comment: @Frank It goes away when I press Rt, but comes back after 5 seconds. The controller is 3 days old.
Comment: @Frank Cod and halo 4 are the only first persons I have, but it doesn't do that to gears or gta
Answer: Is your controler an OEM or aftermarket as some aftermarket controllers allow you remap your buttons (ex. Have RT set to jump {A} and A set to shoot  {RT}) if it is an aftermarket I would suggest getting the booklet it came with and finding out if you can remap the controls.

Is my controller broken?


Header breaks when zooming in. How I can fix that?

Question: I have a header which has two list items. When I zoom screen the text breaks. How can I fix that?
Comment: Where is your code?
Comment: it's a big piece of Css with a header component
Answer: If I'm reading this right you want to stop text from wrapping.
in CSS3 you can use the style
<code>white-space: nowrap;
</code>
one possibility is that you could create a class with this:
ref: example on w3
Comment: You need to provide more information and code to illustrate the problem


A haskell "withSubprocess" construct around a do block

Question: I'm working through the Haskell WebDriver selenium package for testing, here.
I have this example:
import Test.WebDriver

firefoxConfig :: WDConfig
firefoxConfig = defaultConfig

main :: IO ()
main = runSession firefoxConfig $ do
  openPage "http://google.com"
  searchInput <- findElem ( ByCSS "input[type='text']" )
  sendKeys "Hello, World!" searchInput
  submit searchInput
  closeSession

The getting started section makes clear that the selenium client requires a selenium server to communicate with
java -jar selenium-server-standalone-*.jar

Without it running, you get this:
ghci    λ> main
*** Exception: FailedConnectionException2 "127.0.0.1" 4444 False connect: does not exist (Connection refused)

I'd like to wrap my whole test script in a function that initializes the selenium-server, records its pid, and kill(pid) after I run the session.  That is, for the duration of my existing main, I'd like to call the java selenium-server into existence, but I'd like it to stop existing as soon as the call finishes.
In python I'd do this by something like defining a __enter__() and an __exit__() with other tear-down stuff, subprocess.Popen, record the id, kill it, then calling
with Browser() as b:
  do_stuff

I get the sense the runSession entity is the kind of thing I would need to replicate to wrap startup and teardown like this in the sense that it takes the firefoxConfig $ do block as an argument and I want to do that, too.
However, I can't quite understand the types from interrogating runSession, how to make this kind of thing:
ghci    λ> :t runSession
runSession
  :: Test.WebDriver.Config.WebDriverConfig conf =>
     conf -> WD a -> IO a

I think I'd be looking for some kind of withMonad I could apply to this which is applied to the do. I think the syntax would be some kind of...
import Test.WebDriver
import System.Process

firefoxConfig :: WDConfig
firefoxConfig = defaultConfig

withBrowser :: Monad a -> Monad a -- maybe this type?
withBrowser = do
  r <- createProcess (proc "java -jar selenium-server-standalone-*.jar" [])
  -- other magic here?

main :: IO ()
main = withBrowser $ runSession firefoxConfig $ do
  openPage "http://google.com"
  searchInput <- findElem ( ByCSS "input[type='text']" )
  sendKeys "Hello, World!" searchInput
  submit searchInput
  closeSession

How would I achieve this?  Is monad right at all?  Is there a more Haskell idiom or strategy for this?
Comment: A `Monad` isn't a type. Also, keep it simple. `createProcess' and `runSession` both use `IO`, so stay in `IO`. `withBrowser :: IO a -> IO a`.
Comment: Why not use a shell script?
Answer: You basically just want bracket from https://hackage.haskell.org/package/base-22.214.171.124/docs/Control-Exception.html#v:bracket .
It allows you to specify setup and teardown IO actions to to run around a third action. It automatically handles feeding the output of the setup action into both the main and teardown actions, do your setup action should just give the PID as it's result, so the teardown action will be told what PID to kill.
Something like:
withBrowser browserAction
  = bracket startSelenium killSelenium (const browserAction)

(Where I've assumed you don't want the main action to have to take an argument for the pid, so I used const to ignore it)
Comment: @Mittenchops Initially I thought that's what you'd want too, but note that the cleanup action doesn't have an argument there either. So you wouldn't have  a way to transport the PID from the startup action to the cleanup one (without sticking it in an IORef or something).
Comment: Is that bracket_ to avoid the arg?


Cannot install JEWEL in ubuntu 20.04

Question: I am trying to install JEWEL on UBUNTU 20.04. As mentioned in the documentation, it has a dependency on LHAPDF. I have succesfully installed LHAPDF and it showed me a message like:
Libraries are installed in /usr/local/

But when I tried to install JEWEL, it showed an error:
Cannot find -lLHAPDF

I visited this related answer, but could not figure out what to do, as I am not a Linux expert. I used:
sudo -H nautilus

and copy pasted the libLHAPDF.so file from /usr/local/lib to /usr/lib/.
After that, I tried to run the make command again, but this time it showed a differnt error:
$ make
gfortran -o jewel-2.2.0-vac -L/usr/local jewel-2.2.0.o medium-vac.o pythia6425mod.o meix.o -lLHAPDF
/usr/bin/ld: pythia6425mod.o: in function `pypdfu_':
/home/aritra/Project/jewel-2.2.0/pythia6425mod.f:39228: undefined reference to `structa_'
collect2: error: ld returned 1 exit status
make: *** [Makefile:10: jewel-2.2.0-vac] Error 1

Can any expert please help me install this?
Comment: Extraordinary well asked question: tagged, researched (incl. links), tried by examples (input + output), almost perfectly formatted  I will love to help with link-formatting and finding an answer!
Answer: I would recommend to use packages from Ubuntu repositories.
The 18.04 LTS have LHPADF packages.
We can download them to Ubuntu 20.04 LTS to install:
cd ~/Downloads
wget http://archive.ubuntu.com/ubuntu/pool/universe/l/lhapdf/liblhapdf0v5_5.9.1-6_amd64.deb
wget http://archive.ubuntu.com/ubuntu/pool/universe/l/lhapdf/liblhapdf-dev_5.9.1-6_amd64.deb

sudo apt-get install ./liblhapdf0v5_5.9.1-6_amd64.deb ./liblhapdf-dev_5.9.1-6_amd64.deb

and then compile JEWEL:
sudo apt-get install gfortran build-essential

cd ~/Downloads
wget https://jewel.hepforge.org/downloads/?f=jewel-2.2.0.tar.gz -O jewel-2.2.0.tar.gz
tar xvzf jewel-2.2.0.tar.gz
cd jewel-2.2.0/
make

to  use it by ./jewel-2.2.0-vac or ./jewel-2.2.0-simple.
Answer: This problem is caused by a typo in fortran continuation. Edit file pythia6425mod.f:
on line 39228 there should be & on col 6 and GLU) on col 9-12 to look like this:
39227|           CALL STRUCTA(XX,QQ,MASS,UPV,DNV,USEA,DSEA,STR,CHM,BOT,TOP,
39228|     &  GLU)

Hope this helps

Cannot install JEWEL in ubuntu 20.04