Angular 1.5 directive with one-way binding updates parent scope

Question: I have a directive with an isolated-scope and one-way binding variable.
yet when i change that variable in the directive controller it updates the parent scope as well.
Example code:
function someDirective() {
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        bindToController: {
            parentVar: '<'
        },
        templateUrl: templateUrl,
        controller: directiveController,
        controllerAs: 'vm'
    }
}

function directiveController($scope) {
    var vm = this;

    $scope.$watchCollection('vm.parentVar', doSomething);

    function doSomething(newCollection) {
        var some_object = {
            property1: 1,
            property2: 2
        };

        newCollection.unshift(some_object);
    }
}

After I update the passed variable in the directive, I see some_object in other parts of my app.
Thank you.
Answer: parentVar is an array reference, so the items that to add to it can be accessed from both parent controller.
If you do not want the changes from directive controller to be reflected, you will have to clone the array before you operate on it.
function directiveController($scope) {
    var vm = this;

    $scope.$watchCollection('vm.parentVar', doSomething);

    function doSomething(newCollection) {
        var clonedCollection = newCollection.slice();
        var some_object = {
            property1: 1,
            property2: 2
        };

        clonedCollection.unshift(some_object);
    }
}

Comment: Thank you, that's exactly what i did.
Is this intended behavior?
Comment: Yes. '<' - one way binding ensures that watcher is not set for this variable in parent scope.


Want to create new table from the findings from original table

Question: I am quite new to Postgresql.I have a Postgres table like this:

createdat
pageTitle
sessionId
text
device
deviceserial

Wed Sep 02 2020 08:55:10 GMT+0000
submit option
null
launchComponent
Android
636363636890

Wed Sep 02 2020 09:05:11
quick check
88958d89c65f4fcea56e148a5a2838cfhdhdhd
hi
Android
6625839827

Wed Sep 02 2020 08:59:10 GMT+0000
submit option
null
launchComponent
Android
636363636890

Wed Sep 02 2020 09:07:11
quick check
88958d89c65f4fcea56e148a5a2838cfhdhdhd
hi
Android
6625839827

Wed Sep 02 2020 09:01:10 GMT+0000
submit option
null
launchComponent
Android
636363636890

Wed Sep 02 2020 09:09:11
quick check
88958d89c65f4fcea56e148a5a2838cfhdhdhd
hi
Android
6625839827

Wed Sep 02 2020 09:03:10 GMT+0000
submit option
null
launchComponent
Android
636363636890

Wed Sep 02 2020 09:09:11
quick check
88958d89c65f4fcea56e148a5a2838cfhdhdhd
hi
Android
6625839828

Wed Sep 02 2020 09:03:10 GMT+0000
submit option
null
launchComponent
Android
636363636891

Wed Sep 02 2020 09:13:11
quick check
88958d89c65f4fcea56e148a5a2838cfhdhdhd
hi
Android
6625839828

Wed Sep 02 2020 09:06:10 GMT+0000
submit option
null
launchComponent
Android
636363636891

I grouped by this table by deviceserial with this command :
SELECT
    deviceserial,
    DATE_PART('minute', max(createdat)::timestamp - min(createdat)::timestamp) AS time_difference
FROM
    devices
GROUP BY deviceserial;

Then the result is this bellow.Now I want to create a new table named "device_usage" from this columns deviceserial,device and usage values from below  and another column for id.After that I want to copy "device_usage" table to another database.How can I do that?I could not find a good solution.

deviceserial
device
usage

636363636891
Android
3

636363636890
Android
8

6625839827
Android
29

6625839828
Android
4
Comment: You can insert the rows into a table or use `create table as`.
Comment: Not understanding this: '...finding with index to another database'? Can you provide more information?
Comment: @AdrianKlaver Thank you.More information added.
Comment: You can't do that directly. You would need to do `CREATE TABLE AS ...` as GordonLinoff suggested. Then you could do `pg_dump -d the_db -t the_table -f the_table.sql` and then `psql -d other_db -f the_table.sql`.  Another option would be to setup [postgres_fdw](https://www.postgresql.org/docs/current/postgres-fdw.html) on the other database and link to the table in the first database.
Comment: Thanks everyone :)
Answer:
connect to both databases

Run a CREATE TABLE statement with the appropriate column definitions on the second database. The id column is created as
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY

Run your query on the first database and fetch the results row by row.

For each row, run an appropriate INSERT statement on the second database. That statement won't insert to id so that the column is filled with the autogenerated value.

These steps are for a solution with a program.
If you want to do it by hand (i.e., a one time task), move the data with COPY. Using psql, moving the data could look like
\connect db1
\copy (SELECT /* your query */) TO 'datafile'
\connect db2
\copy newtable (deviceserial, device, usage) FROM 'datafile'


how to get the metadata of files stored in alfresco content management system?

Question: Hi i have stored some files(pdf, html,doc) in alfresco cms, my requirement is to classify these files using metadata "content-type" filed in the alfresco cms, is it possible to do it by using only alfrensco or do i need to integrate any other crawlers(tika, nutch, lucene) with alfresco to get it. please suggest me a way to do it
Comment: Classify in what manner? And how do you want information out? Ie. do you want that the documents go to specific folders on import, depending on content-type, or ie. you want to know how many PDF docs do you have in the repository?
Comment: Does Alfresco already pull out the metadata you want? e.g. if you go into Share, look at the document details page, and view the document properties / metadata, does that have all you want?
Comment: yes i can view the metadata from file properties, i have changed my question, i need to classify the files using this metadata
Comment: thanks for the reply, i have stored different types of docs(html,pdf,doc) in cms so by using the docs metadata i want to store all pdf files in my local system folder and all html files in another folder like that i want to clasify based on file type
Answer: Hi This is a simple Rule to move an HTML file to another folder.
If you need more flexibility and just 1 rule instead of a rule for each type, you'll need to write some JavaScript and check on the mime-type field.
Answer: The "content-type" metadata are based on the extension of filename put in Alfresco (.pdf, .doc). Files with un-recognized extensions have no valid content-type.
You can simply use "Rules" in Alfresco to organize your files.


Creating branches using VisualSVN server

Question: I am learning SVN and was trying to create a branch on my SVN server, and I found option to create same using command line only.
Is there a way to create a branch using VisualSVN server GUI?
Answer: You should use Subversion client for this task. For example, use Subversion command-line client and run svn copy, use TortoiseSVN client and run the corresponding copy command in its graphical interface or use any other Subversion client you prefer.
And don't forget to read the documentation:

SVNBook | Branching and merging
TortoiseSVN Manual | Branching and tagging


How long does it take for Epic Projects to show up?

Question: I bought the department of special projects a few days ago and still no epic projects have shown up, am I missing something? Is there other requirements to start building epic projects?
Comment: Have you built the Department of Epic Projects? You will need that before you get any projects. You'll see a winged helmet icon over a building when it's ready. The first one (for me) started right away, after you complete your first, it takes about 12 hours before you get another one.
Comment: Yes I have built the department of epic projects when the update came out and im level 46. Still no winged helmet icons have shown up.
Comment: Looks like you also have to have specialty areas... so for example, you may get an education epic project in a zone near a school. So make sure you've got residential buildings near speciality areas.
Comment: Also, the project tasks come from the specialization buildings themselves. So, if you get the education project, the more schools you have (particularly the more 3-star schools you have), the more tasks you can get. The number of stars indicates the number of points you get for each completed task.
Comment: I have all specialist education buildings surrounded by residential buildings. Not sure what else the problem might be.
Comment: Yeah, those are pretty much all the things I can think of. Try contacting their support people, I guess.
Comment: Yeah I think that's really my only option left. Thanks anyway!
Comment: how did this work out for you? Has it started working yet?
Answer: You have to be Level 24 to unlock your first Epic Project. Tap on the building and it will say so.
Comment: I'm level 46 though
Answer: You need to also have transportation, education, beach, mountain items because that is where you get the tasks to show up. For instance if you choose transportation, tasks will show only on bus station, balloon, helicopter pads etc.
Answer: To start epic project. first you need Deptt of Epic Project. A regular residential building (not tokyo, london , paris or omega). that regular building must be close to one specialization building (Education, Gambling, Landmark etc)
Answer: Epic projects appear after you have any specialisation apart from parks and landscape that benefits a fully upgraded residential zone. Once you have completed an epic project, there is a 12 hour cooldown until you can start another one. Start an epic project by taping on the winged gold helmet.
You can read more on EA's Help Pages: Simcity Buildit Epic Projects
Answer: Click the blue floating icon over government building. Once you clicked them all tap on epic projects building, then your projects will start.
Answer: I have the same problem but I solved it, the residential building has to be in the green affected area of a building. I had moved my mountain buildings away from my residential buildings because I couldn't see over them but you can't do that obviously.
Answer: In my case, I had been ignoring the blue bubble over the TOWN HALL - the lady kept talking to me about "building a park" and seeing as I didn't want to build a park, I never passed that message. Once I did build a park at lvl 30, the next town hall message came through, then the next, etc. After a few more messages about the airport and Vu's tower, the message to create your first epic building shows up.
Hope that helps!
Answer: There seems to be an issue with seasonal items like "Santa's workshop" and EP. Until I boxed it up and removed it EP's never spawned for me and I was level 28. I had every service, beach and mountains opened. The second I removed the workshop I got an epic project.


jQuery DataTable not working using ajax in javascript

Question: I am using jQuery datatable to display table which is in-built responsive and has pagination.
I am using javascript in which has ajax call for dynamic
my table looks like

var xmlhttp = new XMLHttpRequest();
var url = '/../view_history/' + userId + '/' + networkId ;

  xmlhttp.open('GET', url, true);
  xmlhttp.send();

  xmlhttp.onreadystatechange = function() {

  if (xmlhttp.readyState === 4) {

    if (xmlhttp.status === 200) {
      var json_data = JSON.parse(xmlhttp.responseText);

      var result = json_data.result;
      if (result == 'success') {
      /* Proceess using for loop data and then append that dynamic data in
 */
       document.getElementById('deposit').innerHTML += sr + emaili + coini + address + '	' + txnhash.substring(0, 12) + '...' + '	' + amount + '	' + txn_fee + '	' + Net_bal + '	' + time + '
'
     }
    }
   }
   }

  #
  Email Id
 Network
 Type
 Address
 Transaction
 Amount
 Txn Fee
 Net_Bal
 Time

and call jquery DataTable function as below.

it displays all record but its not responsive,pagination,sorting not working at all. please help me to sort this case.
Comment: Press `F12` to open browser console window. Check your browser console for more information. If you find any errors logged do post here. That would help to understand your issue better.
Comment: can u post wt is coming in json_data or console.log(json_data ); wt it comes
Comment: My json_data contain "{result: "success", deposit_data: Array(27)}"
Answer: Try calling the DataTable() after updating the table with data (inside API response).

var xmlhttp = new XMLHttpRequest();
var url = '/../view_history/' + userId + '/' + networkId ;

  xmlhttp.open('GET', url, true);
  xmlhttp.send();

  xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState === 4) {

      if (xmlhttp.status === 200) {
        var json_data = JSON.parse(xmlhttp.responseText);

        var result = json_data.result;
        if (result == 'success') {
          /* Proceess using for loop data and then append that dynamic data in
 */
          document.getElementById('deposit').innerHTML += sr + emaili + coini + address + '	' + txnhash.substring(0, 12) + '...' + '	' + amount + '	' + txn_fee + '	' + Net_bal + '	' + time + '
';

          // call the DataTable();
          $('#example1').DataTable();
        }
      }
    }
  }
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">

  #
  Email Id
 Network
 Type
 Address
 Transaction
 Amount
 Txn Fee
 Net_Bal
 Time

Comment: Have you added `CSS` for jQuery DataTable(), e.g. `https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css` ?


What is the difference : BasicDataSource and JOnASDataBaseManagerService

Question: We have a web site using spring.
I found in the code 2 ways of connecting to the oracle database, both use a bean called phareDataSource :
1st method :
<bean id="phareDataSource"
    class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName"
        value="oracle.jdbc.driver.OracleDriver" />
    <property name="url"
        value="${hibernate.connection.url}" />
    <property name="username" value="${hibernate.connection.username}" />
    <property name="password" value="${hibernate.connection.password}" />
</bean>

and 2nd method :
<bean id="phareDataSource"
    class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>jdbc/PHARE</value>
    </property>
</bean>

In Jonas Directory : jonas.properties
jonas.service.dbm.class    org.ow2.jonas.dbm.internal.JOnASDataBaseManagerService
jonas.service.dbm.datasources    PHARERH

PHARERH.properties :
datasource.name     jdbc/PHARE
datasource.url      jdbc\:oracle\:thin\:@blabla\:1521\:R59A001
datasource.classname    oracle.jdbc.driver.OracleDriver
datasource.username         bla
datasource.password         bla

The first method or the second one is picked when we are building (maven active profile).
The first uses a simple configuration file, the second uses a configuration file located in jonas conf directory.
Since we use tomcat in our dev environment, we picked the first method.
But in our int and prod environment with Jonas installed, shouldn't we use the second method ?
Is it better in performance ?
Answer: Both will use a JDBC connection pool to manage your connections so I would not expect there to be a major difference in performance.
Method 1 doesn't use any of the JOnAS features to create or manage the JDBC connections + pool. The same configuration will work outside of the application server. This is useful for testing without the requirement to deploy to the application server.
Method 2 will use the JDBC connection pool configured and managed by JOnAS (the application server).
Typically, if you have made the decision to go with an application container (e.g. JOnAS, JBoss, Websphere, etc) it is usually a good idea to let the container manage the resources that you use. That's what they are designed to do, and you may require some of the advanced features for managing the configured resources. There is also the benefit that your application doesn't have to know what implementation/driver is being used (or username/password, so you can deploy your EAR/WAR to different application servers without having to change your application configuration. These details are configured in the server instance instead.
If using Method 1 inside an application server, the server will have no control over the threads being created, because it knows nothing about them.
Comment: Thanks for your answer, jonas handle our datasource connection now.


Advice on installing bar top on half wall

Question: I am preparing to attach a piece of butcher clock (about 42" L x 18" W) to the top of a half wall that w recently built partially across the entryway to our kitchen. I'm trying to figure out the best way to securely attach the butcher block to the top of the wall, which is only about 5" wide. Attached a pic of the bar top being held in place.
From my research so far, it seems like my options are either corbels or steel brackets, and drilling up into the butcher block through the brackets or corbels. I was planning to use construction adhesive to secure the board to the top of the wall, but from what I've read glue is not recommended to allow the board to expand and contract (otherwise can split/crack).
Any advice on whether the brackets/corbels will be enough, or if something else is needed to make sure the cbar top is secure? ('m sure ideally attaching the butcher block before finishing the half wall is ideal to secure it from the bottom - though at the same time wouldn't be able to mount the brackets). Thanks in advance for any suggestions.
Answer: From your post, it's not clear whether the supporting wall is finished or not. That would be the ideal way to start securing it - by screwing up from the bottom. However, consider that your model will normally have her elbows resting on the bar, not under it, and that she's probably not the biggest guest who will ever belly up. Just a few screws from the bottom may not be sufficient to support the weight of Junior, the Utes' nose guard, when he comes to lean on it.
Really, you'll want some sort of brackets, attached to the bottom of the counter, then into studs in the half wall to securely attach this and support the weight of people leaning on it. You can cantilever a counter top like this, but it would need a much wider attachment area to counteract the weight of people leaning on the unsupported side.

Do be aware that generally it's frowned upon to make this type of permanent alteration to a rental. Of course, I'm making that assumption based on the Utes decoration on the wall, and it's entirely possible you're just a fan and that you own the place.
Also, that's not butcher block. But that's just a nit-pick.
Comment: Thanks for the reply. Agree about needing to support people leaning on it (we are actually just holding it up in place in the photo to show what it will look like). Planning to use some heavy-duty shelving brackets below, probably three of them, that claim to hold 300 lbs (attached to studs). The other option I was considering was attaching legs to the corners and connecting to the ground - obviously would be good support but a pain to navigate. And it is our house ha - the Utes decor is just covering up a hole in the wall where we started exposing the brick ;)
Comment: Yeah, I figured she was your temporary support. ;) Legs would be good but you'd be stubbing your toe on them. Just make sure you attach the shelf supports to studs and you should be good to go!
Comment: Also, spend a moment to take the [tour] to see the proper way to say "thanks" 'round here. ;)
Comment: Appreciate the advice - and to clarify for anyone else, the wall is indeed finished already, otherwise would definitely screw up into the block there as well (am considering cutting a hole in the drywall to do that still but don't know if it's necessary).


What are the best Together mode weapon sets?

Question: Everybody is extremely over-powered in Kid Icarus: Uprising. Therefore, I need some ideas on how to be on the same level of strength as them. Can anyone give me ideas on how to do that?
Answer: You'll want to have weapons that specialize in melee attacks and weapons that specialize in ranged attacks. For both types of weapons, you'll want as high of a rating for its given damage type as possible (6 stars if possible); don't worry about the other damage type. overall defense and health modifiers are always very helpful too. Remember that higher value weapons are not always more useful, and enemies will get more points for killing you when you have a higher value weapon, so you want to balance power and value.
For ranged weapons, most players prefer staffs. Staffs and clubs are good choices for sniping, while palms, orbitars, and bows are good choices if you want high homing ability.
Charged shot and continuous fire modifiers are great for ranged weapons. Full-health boosts can be good if you plan to shoot from afar. Shot homing and shot cancellation are extremely helpful, but remember that shot homing modifiers won't help weapons that have no inherent homing ability.
For melee weapons, most players choose claws. Claws are great for melee because they hit faster than any other weapon type, and also give you a speed boost. Arms and clubs can be good for dealing a lot of damage in a short time, but won't give you the speed boost and constant hits that claws will.
Obviously, you'll want melee combo +4 and melee dash attack +4 modifiers. Other especially useful modifiers include freezing, petrification, stamina, and speed bonuses.
See Icarus Wiki's weapons pages for individual weapons. There's a lot of useful information there for deciding which weapon you want to use, but it's not complete.

As for powers, you'll want to pick ones that work well with your weapon, but also ones that you like playing. I personally love destructive powers such as Mega Laser or Explosive Flame.
For ranged weapons, Homing Boost, Quick Charge, and Slip Shot are very useful. If you're using a club for ranged attacks you should try Invisible Shots too, so your enemies don't see your shots coming.
For melee weapons, Black Hole is great for holding your enemies in place while you wail on them, as are Paralyze Attack and Petrify Attack. Interference, Darkness, and Transparency can help you sneak up on them without being seen. Tirelessness is invaluable when it comes to engaging and disengaging combat. Playing Dead is especially fun to use when fighting another melee player.
Comment: What if I had a club with Trade-Off and Energy Charge? Is that strong?
Comment: @IcarusNerd Both are powerful abilities and have similar weaknesses. Both take up a fairly large piece of the power grid. Also both are powers that you only want to use if you don't think you'll be hit soon afterward, since Energy Charge ends when you're hit, and Trade-Off leaves you very vulnerable. You could combine them with Transparency to help combat that. To get a similar effect in a more flexible way, try getting a high ranged damage club with full-health boost and forward-dash ch. shot modifiers, and bring health recovery to get back to full health after being hit.
Comment: Or just use Spite in an area with a bunch of people?
Comment: I wouldn't suggest trying to make a suicide bomber build for together mode. If you're looking for AoE attacks, a cannon and the Explosive Flame work well. Note that AoE isn't particularly useful in Light vs Dark because there are only 3 enemies on the entire map.
Comment: What cannon exactly? Would Doom Cannon work for that? And what does AoE mean?
Comment: @IcarusNerd AoE means "area of effect", which is simply damage (or other effects) that hit an area rather than a single target. The Doom Cannon does have good AoE damage, but keep in mind that it has a long charge time and its shots travel slowly. Any cannon should be good for hitting an area aside from the Ball Cannon and Cragalanche Cannon. It's good to try them all out and see which suits you best, since they all have different effects. See http://www.kidicaruswiki.org/Cannon for some basic info.
Comment: Does Doom Cannon have the biggest AoE? Is the Lancer Staff a balanced weapon? I'm looking mostly for sets that are the most powerful, but don't leave you open. So I'm looking for shot cancellation, & power.
Comment: I don't know which cannon has the biggest blast radius, although the Dynamo Cannon is coming to mind for having a large blast (but less damage than most cannons). The Lancer Staff is fairly well balanced since it has strong ranged attacks and also strong melee for a staff. I often use a Lancer Staff in solo mode. It has fast moving charged shots but little (if any) homing ability. Cannons, clubs, and arms generally have good shot cancellation and high power.
Comment: I meant its Together performance. And what cannons have cancellation? What sets would be very sneaky?
Comment: All weapons have a certain cancellation value. I think the Ball Cannon has the highest cancellation value, but its shots don't explode like other cannons. If you're trying to make a sneaky set, I recommend the Transparency and Invisible Shots, but Slip Shot, Darkness, Interference, Tirelessness, Playing Dead, and Spin Attack would work well too. Claws are good for short range sneaky sets, while staffs are good for long range. Either way, you should use a weapon with a speed modifier to help you sneak around faster.
Comment: What's the second highest?
Comment: I'm not sure, but you might want to try out the Rail, Doom, Cragalanche, and Leo Cannons. Those are the ones that I have a feeling also have high cancellation, but that's just a hunch. If you have a friend that you can play against in local together mode, you can test it out by shooting charged shots at each other at the same time with different cannons and seeing which shot powers through.
Comment: Ok thanks but what overall weapon has highest cancellation? (other than Guardian Orbitars)
Comment: I'm not sure which is the highest, but other ones with high cancellation are the Black Club, Aurum Club, Hawkeye Bow, Divine Bow, Centurion Orbitars, Palutena Blade, Burst Blade, Crusader Blade, and Midnight Palm.
Comment: And how do you unlock Centurion Orbitars and Aurum Club?
Comment: Centurion Orbitars are unlocked by defeating the Chariot Master while in Crisis Mode, and the Aurum Club is unlocked by completing chapter 15 in less than 17 minutes. By the way, I noticed that you haven't accepted answers to any of your questions yet. If you want to accept an answer to one of your questions, you can click on the check mark to the left of it. See http://gaming.stackexchange.com/help/someone-answers for details.
Comment: What about powers to counter other powers and items?
Comment: If you name the powers or items that you're looking to counter, I can advise you on what I think would work best against them. If it's going to be extensive, you should probably make it a new question though.
Comment: Just O.P. powers and items I want to counter.
Comment: Having a Status Resistance modifier on your weapon or the Effect Recovery power can be very helpful for countering many items and powers, particularly ones that petrify or freeze you. With some practice, Reflect Barrier can be effective against thrown items or projectiles. Using a weapon with Speed or Running Speed boosts is helpful for picking up items before your opponents, especially if you're trying to prevent them from completing Daybreak. If all else fails, the Brief Invincibility power can be used as a "panic button" in case you get into a particularly bad situation.
Comment: What about Cyclone item & Blsck Hole power?
Comment: There isn't much you can do once you're sucked into one of those, but Brief Invincibility can be used to negate whatever damage they were planning to hit you with while you were stuck or Warp can be used to escape. Also, weapons with higher speed can help you run out of the pull so you don't get caught in the first place.
Comment: What do I do when fighting Japanese players? They're number one when it comes to overpoweredness.
Comment: Practice? Play when they're asleep? Don't know what to tell you there.
Comment: Whenever I fight Japanese players they kill me in EXACTLY one hit.
Comment: It sounds like you're getting sniped. Try bringing weapons with Health, Defense, or Shot Defense modifiers. If they're sniping you with staffs, find their favorite sniping spots and keep an eye on them. Forcing them into melee combat should give you an advantage against any sniping build, even if you aren't running a melee focused build. And if it's someone named Brian killing you in one hit with an Ore Club and Invisible Shots, you should definitely not attack him in melee. ;)
Comment: Well you see, people also use Brawler Claws and I think they're hacking because they can basically move as fast as the power Warp, and can practically fly, and my attacks NEVER land.
Comment: Those players are probably using the Brawler Claws that you get from Treasure Hunt with +8 Defense, +4 Speed, and +1 Stamina. They might have also added powers to help them run faster just for fun. The catch is that they have 0 stars of damage, so they should be mostly harmless.
Comment: Well what I meant by fly is sometimes they go super high on the map Lava Basin
Comment: There are jump pads in Lava Basin, but if they're staying in the air, they're probably using the Jump Glide power. That shouldn't be much of a problem for any weapon with decent homing ability.
Comment: But they go like, 150 ft into the air. Also, in the cave arena, they somehow walljump off the pillars
Comment: There definitely isn't wall-jumping in KIU. The only legitimate ways to "fly" are via powers, jump pads or cyclones, but I can't say for certain that there isn't some sort of flight hack.
Comment: Once in the Solo mode, Palutena said you can reflect shots with clubs. Is this true in Together? If so, how?
Comment: Clubs' continuous fire doesn't actually shoot anything, but instead can be used to bat back incoming projectiles. It's a lot more useful/reliable in Air Battles than on land.
Comment: But does it work against PvP shots is what I'm asking.
Comment: Yes. Wow, it was more than a year since my previous comment.
Comment: Ok cool. What's the best way to do it? Do you use a dash?
Comment: No, just hold down the button to shoot while standing or walking. Bigger and slower shots are easier to reflect, and not all projectiles can be reflected (the Flintlock Staff comes to mind). Shots from orbitars, cannons, and arms are probably the easiest to reflect.


Polynomial equal to polynomial of lower degree

Question: I am studying Linear Algebra Done Right, chapter 2 problem 6 states:

Prove that the real vector space consisting of all continuous real valued functions on the interval $[0,1]$ is infinite dimensional.

My solution:
Consider the sequence of functions $x, x^2, x^3, \dots$
This is a linearly independent infinite sequence of functions so clearly this space cannot have a finite basis.
However this prove relies on the fact that no $x^n$ is a linear combination of the previous terms. In other words, is it possible for a polynomial of degree $n$ to be equal to a polynomial of degree less than $n$. I believe this is not possible, but does anyone know how to prove this? More specifically, could the following equation ever be true for all $x$?
$x^n = \sum\limits_{k=1}^{n-1} a_kx^k$ where each $a_k \in \mathbb R$
Answer: Then the polynomial $\displaystyle x^n-\sum_{k=0}^{n-1}a_kx^k$ would have infinitely many roots, but it can have $n$, at most.

Another way of dealing with this problem is based upon defining polynomials (in one variable $x$) as expressions of the type $a_0+a_1x+a_2x^2+\cdots+a_nx^n$, where $n\in\{0,1,2,\dots\}$ and each $a_n$ is real. Under this definition, the polynomial $a_0+a_1x+a_2x^2+\cdots+a_nx^n$ is equal to the polynomial $b_0+b_1x+a_2x^2+\cdots+b_nx^n$ if and only if the coefficients are equal, that is, if and only if $a_0=b_0$, $a_1=b_1$, and so on. Under this definition, the problem discussed here is trivial.
What did I prove above then? Well, for each $P(x)\in\mathbb{R}[x]$, there is a corresponding polynomial function from $\mathbb R$ into $\mathbb R$. What I proved above is that this correspondence is one-to-one — when we are dealing with $\mathbb R$. It is still one-to-one if we are dealing with any field with charactristic $0$, such as $\mathbb Q$ or $\mathbb C$. But this is not true in general. For instance, if our field is $\mathbb{F}_2$, then $x$ and $x^2$ are distinct polynomials. But they correspond to the same polynomial function.
Comment: @ZubinMukerjee Jokes aside, I really do mean what I wrote. We should expect *statements* of results to be precise, but not *names* of results (else we'd be stuck with monstrous names like "the root bound for nonzero formal univariate polynomials over a commutative integral domain").
Comment: "Equations" can have infinitely many solutions, but *nonzero polynomials* cannot.
Comment: @Joe A reference? Why? Isn't my proof clear?
Comment: @Joe See [this answer](https://math.stackexchange.com/a/2049882/242) for a proof of the root bound for polynomials.
Comment: @Joe You can find several proofs of the [Fundamental theorem of algebra](https://en.wikipedia.org/wiki/Fundamental_theorem_of_algebra).
Comment: @BillDubuque I think you mean "a proof for the root bound for *nonzero* polynomials" :P
Comment: @Joe If you know about unique factorization of polynomials over fields then a [slick proof](https://math.stackexchange.com/a/37519/242) is that if a nonzero polynomial has infinitely many roots $r_i$ then it has infinitely many nonassociate prime factors $\,x - r_i,\,$ contra unique factorization.
Comment: In Linear Algebra Done Right, Sheldon Axler states on page 24 that the fact that a polynomial of degree m has at most m roots will be proved in chapter 4. I think maybe I should just wait until chapter 4. Are there other ways to prove the original question without this fact about polynomials?
Comment: @Joe I just wanted to make you aware of the distinction between *polynomial* and *polynomial function*. Perhaps that Axler assumed that his readers knew that a poynomial with degree $n$ has, at most, $n$ roots. Or perhaps that he had in mind a solution without poynomials. For instance, he might have been thinking about functions of the type $f_n(x)=(x-n)(1-x+n)$, which are zero outside the interval $(n,n+1)$ and non-zero inside. Therefore, they are linearly independent.
Comment: Thank you I just need to find a proof of that fact. If you have any good references that would be great.
Comment: A proof of the fact that a polynomial of degree n has at most n solutions.
Comment: @BillDubuque I have edited my answer.
Comment: @Joe See [here](https://math.stackexchange.com/questions/25822/how-to-prove-that-a-polynomial-of-degree-n-has-at-most-n-roots).
Comment: @Joe Please read my expanded answer.
Comment: @JoséCarlosSantos But it seems like you are going around the problem by changing the definition of a polynomial?
Comment: @BillDubuque That makes sense! I hadn't thought about that distinction before.
Answer: By definition, $x^n + \sum\limits_{k=0}^{n-1}a_k x^k$ is a nonzero polynomial of degree $n$.  A nonzero polynomial of degree $n$ can have at most $n$ zeros in any field, and $[0,1]$ has more than $n$ elements.
Answer: Two identical functions have identical derivatives. Differentiate your equality $n$ times and you will see the two sides cannot be identical.
Comment: Good point, but I have not studied derivatives on a rigorous level yet... so I can't really use that as part of my proof.
Answer: Suppose $x^n = \sum\limits_{k=1}^{n-1} a_kx^k$. Consider what happens when $x$ is much larger than  $|a_1|+\ldots+|a_{n-1}|$. By the triangle inequality, you will get a contradiction. Essentially, you are showing that $x^n$ grows faster than any degree $n-1$ polynomial...


Calling a method that only prints out a "loan statement"

Question: I am doing an assignment for class and we just started making our own methods and what I thought seemed easy enough has become extremely frustration and hoping you can help me wrap my head around it.
First things first and the assignment I am trying to complete is this: make a modular program to calculate monthly payments, seems easy but the few restrictions on this question is as follows
The main method should:
Ask the user for

the loan amount
the annual interest rate ( as a decimal,   7.5% is 0.075 )
the number of months

And

call a method to calculate and return the monthly interest rate  (annual rate/12)
call a method to calculate and return the monthly payment
call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment.

I have gotten to the end of just printing out the loan statement but cant for the life of me the proper way to call it, and make it show up once I run the program :/  so if you can help me understand how its done I would greatly appreciate it.
(I realize that there are probably other mistakes in my code but for right now I would rather just focus on what I need to get done)
import java.util.Scanner;
public class LoanPayment {
/**
 * The main method declares the variables in program while getting the user
 * info of amount loaned, interest rate of the loan, and the loans duration.
 *
 * The main method also calls other methods to calculate monthly interest
 * monthly payments and the output of the loan statement
 */
public static void main(String[] args)
{
   // declare variables
    double interest; // interest attributed to the loan
    double mInterest; // loans interest  divided by 12
    int time; // how long the loan was taken out for
    double principle; // the amount borrowed
    double mPayment; // how much is to be paid each month
    double loan;

   // initate new scanner class
    Scanner keyboard = new Scanner(System.in);

   // get user input/information
    System.out.println("Hi, Please enter the loan amount here:");
    principle = keyboard.nextDouble();

    System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
            "(example: 7.5% is 0.075:");
    interest = keyboard.nextDouble();

    System.out.println("now please put in the number of months the loan was taken out for");
    time = keyboard.nextInt();

   // call method to calculate and return monthly interest rate
    mInterest = calcMInterest( interest );

   // call method to calculate and return the monthly payment
    mPayment = calcMPayment (mInterest, principle, time);

    // call method to print loan statement

} // end main ()
/******************************************************************************/

// this class calculates and returns the monthly interest on the loan
public static double calcMInterest(  double interest )
{
    double mInterest;

    mInterest = (interest / 12);

    return mInterest;

} // end calcMInterest
/******************************************************************************/

// this class calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
    double mPayment;
    mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));

    return mPayment;
} // end calcMPayment
/******************************************************************************/

// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
   System.out.println(" principle is" + principle);

Comment: Okay... I posted an answer then deleted it because you're not actually using multiple classes here.  Can you clarify what exactly your program is doing and what you expect it to be doing?
Comment: @nhgrif this is supposed to be an exercise in creating methods. I needed to get user input for loan information, then make a method to calculate monthly interest, another method to calculate monthly payments, and the final method needs to print out a loan statement that includes all information
Comment: It looks like you already have methods for calculating interest and payments (`calcMPayment()`) that you're calling correctly. You should be able to call the `loanStatement()` method in the same way, just passing in all the arguments you read in.
Comment: See my posted answer.  If you still have questions, you need to clarify where exactly you have issues.
Answer: If // call method to print loan statement is all you have left to do, then this is what you need on the line below it:
loanStatement(principle, interest, time, mPayment);

And it should work fine.
Your other methods have non-void return types, so you put someVariable = yourMethod(yourArguments) in order to accept the return value.  However, loanStatement has a void return type.  You don't need to do this.  You can call it simply as I showed above and it will execute the code in the method.
Though, my personal preference would be to change loanStatement to a String return type and put the print statement in main and print the return of loanStatement.  Methods that return Strings almost as easily and are more flexible for future use (for example, if you wanted to allow your program to also write to file, you need two loanStatement methods, or to completely rework loanStatement).
Comment: You sir are awesome! I knew it was something simple but just couldn't get it >.< I am going to go through my text to see if something like that is mentioned but I don't think it was.
Comment: And yes, I originally made it a string and was going to have it return the value so the main method would print it out (as all the examples in my text did) but the wording of the assignment clearly stated to call a method that did the actual printing so I cant :/
Comment: @JeffreyQuinn Yea, I understand.  Homework is homework.  The final paragraph of my answer is more of a food-for-thought.  When I turn in assignments and have a thought like that, I'll usually offer two solutions (one commented completely out) and direct the teacher's attention to the alternate method that I feel is better.
Answer: Check out this solution ;)
public class LoanStatement{

    public static void main(String []args){
        // declare variables
        double interest; // interest attributed to the loan
        double mInterest; // loans interest  divided by 12
        int time; // how long the loan was taken out for
        double principle; // the amount borrowed
        double mPayment; // how much is to be paid each month
        double loan;

       // initate new scanner class
        Scanner keyboard = new Scanner(System.in);

       // get user input/information
        System.out.println("Hi, Please enter the loan amount here:");
        principle = keyboard.nextDouble();

        System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
            "(example: 7.5% is 0.075:");
        interest = keyboard.nextDouble();

        System.out.println("now please put in the number of months the loan was taken out for");
        time = keyboard.nextInt();

        // call method to calculate and return monthly interest rate
        mInterest = calcMInterest( interest );

       // call method to calculate and return the monthly payment
        mPayment = calcMPayment (mInterest, principle, time);

        // call method to print loan statement
        loanStatement(principle,interest,time,mPayment);
    }

    // this method calculates and returns the monthly interest on the loan
    public static double calcMInterest(  double interest )
    {
        double mInterest;

        mInterest = (interest / 12);

        return mInterest;

    } // end calcMInterest

    // this method calculates and returns the monthly payment
    public static double calcMPayment (double mInterest, double principle, int time)
    {
        double mPayment;
        mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));

        return mPayment;
    } // end calcMPayment

    // this class prints a loan statement showing the amount borrowed
    // and the amount borrowed, the annual interest rate, the number of months
    // and the monthly payment
    public static void loanStatement(double principle, double interest, int time, double mPayment)
    {
       System.out.println(" principle is" + principle);
    }
}


getting the path of a file from its grandparent folder

Question: I have a php file which has the following path
Shubhmangalam/admin/welcome_image_edition/delete_image.php

and an image file with the following path
Shubhmangalam/welcome_images/image_1.jpg

I want to delete the image_1.jpg file which I know can be done by using unlink() method..
but the prob is that the parent folder of the .php  file and .jpg file is different, and so is their level of file-system...and I cant find the proper way to get the path to delete the image_1.jpg file.
Now the code on the delete_image.php is accordingly
<?php
$image=$_REQUEST['image'];
if(unlink("./../welcome_images/".$image))
   echo "Successfully Deleted";
else
   echo "Wrong";
?>

Now the above is server-scripting code, I want to delete the image by getting appropriate path.. I dont want the actual path, but the path from the project folder that is Shubhmangalam
thanks in advance
Comment: ok, i got my answer, i need to find the parent of grand-parent of the file delete_image.php

so i used the code

    "../../welcome_images/".$image
Answer: Be VERY careful with this type of code. You're not filtering the $_REQUEST value AT ALL, which allows a malicious user to specify ANY file on your server, e.g:
http://example.com/delete_image.php?image=../../../../../../../../../etc/passwd

You can fix your pathing problem by using an absolute path:
unlink('/path/leading/to/your/welcome_images/' . $image);

which relives you of the burden of having to figure out the appropriate relative path.
Comment: ok, i got my answer, i need to find the parent of grand-parent of the file delete_image.php

so i used the code

    "../../welcome_images/".$image
Answer:  Shubhmangalam/admin/welcome_image_edition/delete_image.php

That is:
 __FILE__

and an image file with the follwing path
 Shubhmangalam/welcome_images/image_1.jpg

That is:
 dirname(dirname(__DIR__)) . '/welcome_images/image_1.jp';

in the first file. Use the magic constants __FILE__ and __DIR__ for your own good, e.g.:
if (unlink(__DIR__."/../../welcome_images/".$image))
{
    ...


Dealing with an API with a lot of data

Question: I am looking for advice on how best to approach this. I am grabbing data from a third party API that doesn't allow me to query/filter the data in the way I want.
That means I am required to pull every single row of the data and then I cycle through the rows through my own custom endpoint returning the data that meets the criteria. This isn't feasible on load of the site as it is around a million rows of data.
I figured that I could pull all the data daily and store it in my own database so I can query it however I like might be the best bet. Storing in a CSV would be a security risk and it's too large I presume.
Is a database the best method of doing this?
My custom endpoints would query this database however I like as it gives me the flexibility to do so.
The source data via the API is returned as csv format and am using PHP.
Comment: Yes, that is the exact use case for a database.
Answer: in your case database will be better than csv, you can write query that match any criteria like sorting, paginate or adding filter.
its so hard to do all this operations in csv file. this will cause you load whole data in memory then add this filter so this operation cost will be high based on data size and not good performance comparing with database.

Dealing with an API with a lot of data


Store max substring value

Question: $exmp = DB::table('cr_tblcomplaintregistration')
            ->select(DB::raw('MAX(CAST(SUBSTRING(complaintRegNo,16,length(complaintRegNo))+1 AS int))'))->first();
        dd($exmp);

I get:
{#337 ▼
  +"MAX(CAST(SUBSTRING(complaintRegNo,16,length(complaintRegNo))+1 AS int))": 51
}

How do i store the just the value 51 in another variable?.
Answer: I'm assuming the issue is the varable name?  If so, you can add an SQL alias:
->select(
DB::raw('MAX(CAST(SUBSTRING(complaintRegNo,16,length(complaintRegNo))+1 AS int)) AS maximum')
)

If you want $exmp to be the column value, just add that property to the end of your chain:
$exmp = DB::table('cr_tblcomplaintregistration')
->select(DB::raw('MAX(CAST(SUBSTRING(complaintRegNo,16,length(complaintRegNo))+1 AS int)) as maximum'))
->first()
->maximum;

Of course, you may want to get if first() is not null before hand.
Comment: when i do dd($exmp), i want the result to be just { 15 } so that i can increment or manipulate the integer value. Is there any other way i can do it?..
Comment: Using this code, you could just use `$exmp->maximum++` to increment, or you could assign `$exmp` in my updated example.

Store max substring value


Implementing inner operator for derived class

Question: Assume I have a general Matrix class, for which I have already implemented the operator * which performs the usual matrix multiplication.
Such an operator has the following signature :
Matrix operator*(const Matrix & ) const;

I now wish to implement another * operator for an inherited class Matrix3 that represents 3x3 matrices.
It would have the following signature :
Matrix3 operator*(const Matrix3 &) const;

I am looking for the proper way of implementing this operator in order to re-use the code already written for the base class, and to minimize cost (i.e. copying).
Answer: This should work just fine:
// Either return base class
Matrix operator*(const Matrix3& other) const
{
    return Matrix::operator*(other);
}

// Or construct from a Matrix
Matrix3 operator*(const Matrix3& other) const
{
    return Matrix3(Matrix::operator*(other));
}

// Either construct the Matrix data in the Matrix3
Matrix3(const Matrix& other)
{
    // Initialize Matrix specifics
    // Initialize Matrix3 specifics
}

// Or pass the Matrix to it's base class so it can take care of the copy
Matrix3(const Matrix& other) : Matrix(other)
{
    // Initialize Matrix3 specifics
}

Comment: Good point, if it was me I'd have the Matrix3 class to be able to be constructed from a Matrix class, I'll adjust the code a bit because I just wrote that without having access to an IDE atm.


Why is my two year old A/C compressor cycling every 10 seconds?

Question: My central A/C compressor is coming on and off every 10 seconds or so.   It's only about two years old.
I'm familiar with short-cycling, but that's usually in cycles of 1 to 5 minutes.  I've experienced that with my previous system that had a slow leak.  But I have never experienced or heard of short cycling so frequent, every 10 seconds.
What are possible causes and are there any DIY diagnostics I can do while I wait for the installer to come out?
The fan is running fine while this happens.
Edit
As noted in comments the compressor has diagnostic lights.  I should have known that.   Sadly this is the diagnosis: "Yellow Alert 4".  Which I believe is not a DIY job and hopefully a warranty job.  :(
It's not fault 2 - low voltage or bad connections.  The contactor is clean and functional and the cooling fan is starting and spinning nicely.  So it must be condition 4.1, 4.3 or 4.4
Comment: After the issue is resolved you should write your own answer below so that future Googler's can stumble upon this problem and solution :-)
Comment: Did you install a new thermostat? Did you wire it correctly? If you set the temperature 5 degrees lower than ambient then does it short cycle still? Does it do this even when the desired temp is 5 degree above ambient? If you have a newer furnace which displays status codes on the control board then you should check those out. My new furnace will show either AC1/AC2 followed by A01-A10 to let me know the furnace is requesting 1st/2nd stage cooling along with the fan speed percentage; A01 being 10%.
Comment: This sounds more like a loose connection where the motor is trying to start.
Comment: Check the compressor contactor.
Comment: @MonkeyZeus it's not a thermostat problem, but your reminding me that my (newer) compressor may have status lights was productive.   I added info to the question.
Comment: @EdBeal and at-JACK I wish either of you was right.  I so do.  :(. But the code says "locked rotor".
Comment: Well, hopefully the tech can resolve the issue quickly! It's starting to warm up outside; at least in Central NY anyways.
Comment: Locked rotor will go back to an overload condition much like a loose connection or bad starting cap can be the cause. I would not expect a bad cap or contactor at 2 years old but would expect a loose connection especially at the disconnect I have found this more than a few times, loose connection results in low voltage low voltage requires higher current to start so it may look like a locked rotor, I would pull the disconnect verify connections then Meg the motor to ground on both legs, if all the moisture was not removed the oil could have gone acidic and eaten the varnish off the motor wires
Comment: + for adding the info to your question, few do, I saw the comment flagged with my name.  A fan motor is a very small motor and may start fine with a low voltage. You don't list the brand and model but don't try to convince the tech on what you think it is. Diagnostics only point to a possibility, megging the motor was the last part I did not explain a high voltage ohm meter is used to test the windings to ground. I would use at least 500v but probably 1000v to verify motor integrity a vfd may detect a ground fault but we don't know the model. Loose connections or fried windings would be my cks
Comment: Does your multimeter have a capacitance function on it?
Comment: @ThreePhaseEel no.   I'm always amenable to buying more toys.  But this is one of those situations where 1) the most likely faults are ones I'm not capable of fixing (I can swap a blown capacitor but I can't fix seized motor bearings or do anything with the liquid/gas system) and 2) my using this as a learning experience comes at the expense of my family's comfort.  It could take me days or weeks.  It's getting hot.  The system is under warranty.   So I put in a call.
Answer: The technicians found low refrigerant and a slow leak at the fill valve.  They replaced the valve, refilled and tested the system and all seems well.
This leaves annoying open questions that can no longer be answered including:

Why did the self-diagnostic
detect Locked Rotor (4) and not Low Charge (1)?
How did a "slow leak" spontaneously develop after the end of last summer that progressed as far as immediate low-pressure-shutdown for the beginning of this summer?

The technicians were not interested in contemplating these things so I'll just have to move on without answers but with a working system.
Comment: _Don't forget to give yourself a check mark_
Comment: Nice, glad things are working! As for "Why code 4 and not 1?" It's anybody's guess but one theory is that low refrigerant (1) caused a downstream issue (4) which gets detected first by the system. Either that or the low refrigerant detection system is not working right so you'd have to replace some sensor. If you read the circuit board schematic then it might give you some clues. If you call the manufacturer then they might provide some insight into the board's logic but they are more likely to avoid talking to you and will tell you to speak with a licensed professional.
Comment: As for "How did a "slow leak" spontaneously develop in the fill valve?" Well, HVAC systems are subject to thousands if not millions of micro-vibrations during a heating/cooling season. Don't forget about expansion/contraction and accidental bumps. Things get loose and I'm not sure how much spare money you have lying around to research whether this happened to you :-)


Integral of a function which has different derivative from left and right direction at a point on an interval

Question: If $f(x)=|x|$, then we know $f(x)$ has a sharp point at $x=0$, and now I want to calculate the derivative of $f(x)$ on interval $[0,1]$, i.e.,
$$\int_{0}^{1} f '(x)\,dx$$
but $f'(x)$ is not defined on $0$, so I want to know whether the function of $f'(x)$ has been restricted on domain $[0,1]$ as we write down the definite integral, so the derivative of $f'(x)$ at zero just has to consider its derivative from right direction limit, thanks for answers~!
Comment: Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: You mean "I want to calculate the area under the graph of $f'(x)$ on the interval [0.1]" instead of  "I want to calculate the derivative of f(x) on interval [0,1]"
Comment: By the way, I not sure whether I understand your question.Could you be more clear about what exactly you are asking ?
Answer: If we let $f(x) = |x|$, we have that $$f'(x)  = \begin{cases} - 1 & x<0 \\ c & x =0 \\ 1 & x>0\end{cases}$$
Note that the value of $c$ here doesn't matter. You can say that it's undefined at $0$ just as well.
It's known that the Riemann integral doesn't change when finitely many points are changed (this is formalized better through measure theory). This is the case here, so $$\int_0^1 f'(x) \mathrm{d} x = 1$$
Answer: If the integral is not defined at a point in the interval then a limit approach needs to be taken as the integral approaches that value. If the limit exists then the value can be obtained. In this case the limit is x -> 0 from the right.


+% life vs +% resistance

Question: This is regarding the invigorate and Impunity runes of Barbarian's warcry. In short, impunity gives +50% to resistance, while invigorate gives +10% life (+ some regeneration).
Many people come to rely on this EHP (Effective Health Pool) calculator to compare the effect of these two runes. According to this calculator, impunity is the clear winner.
However, I started doing some calculations myself from the information and links taken from [this question], specifically the Diablo III formula list.
Here is the effective health fomula:
Effective Health = Health Pool * Total Damage Reduction,
i.e. Health * (1 - ((1 - DR from Armor) × (1 - DR from Resistance) × (1 - other DR)))

DR means "damage reduction"

Let's simplify the formula:
A = DR from Armor (for example 75%, but we are not using numbers)
R = DR from Resistance (for example 66%, but we are not using numbers)
O = DR from Other

For the sake of this example, let's say "DR from Other" is zero. This means that only health, armor and resistance is being taken into account.
So the effective health becomes:
x = Effective Health = Health * (1 - ((1 - A) × (1 - R)))
                     = Health * (A + R - AR)

Also, this is how damage reduction from resistance is calculated:
Elemental damage reduction = Resistance / (5 × Monster Level + Resistance)

Due to the hyperbolic shape of the resistance formula, +50% in the Resistance when converted to damage reduction doesn't increase as the resistance goes up, but actually the increase in damage reduction decreases. For example with monster level 63 (taken from this answer):
Resistance = 600 --> Reduction = 65.6%
+ 50% = 900 --> Reduction = 74.1% (which is 65.6% + 8.5%)
Resistance = 1200 --> Reduction = 79.2%
+ 50% = 1800 --> Reduction = 85.1% (which is 79.2% + 5.9% (less increase))

This means that while invigorate adds 10% to health, impunity adds a smaller value to the damage reduction. This means that in the formula for effective health, invigorate replaces Health by 1.1 * Health while impunity replaces R by (R + y) where y is the increase in damage reduction (in the two examples above, 8.5% 5.9% respectively).

Adding 10% to Health:
Invigorate Health = (1.1 * Health) * (A + R - AR)
                  = 1.1 * (Health * (A + R - AR))
                  = 110% x

which means 10% increase in health is equal to 10% increase in effective health.
Adding y to the value of reduction from resistance:
Impunity Health = Health * (1 - (1 - A) × (1 - (R + y)))
                = Health * (1 - (1 - A) * (1 - R - y))
                = Health * (1 - (1 - R - y - A + AR + yA))
                = Health * (A + R - AR + y (1 - A))
                = x + y * Health * (1 - A)

So with invigorate, you get 10% * x bonus, while with impunity you get y * Health * (1 - A).
To get an idea which one is better, let's put numbers from my build in to see which is worth what. My base life is 50k. Resistances are at 56% reduction. Armor is at 78% reduction. 50% increase in my resistance gives about 65% reduction. This means y is 9%.
Bonus from invigorate:
10% x = 10% * Health * (A + R - AR)
      = 0.1 * 50k * (0.75 + 0.56 - 0.75 * 0.56)
      = 0.089 * 50k

Bonus from impunity:
y * Health * (1 - A)
      = 0.09 * 50k * (1 - 0.75)
      = 0.0225 * 50k

As you can see, the bonus from impunity is about one fourth of that of invigorate.
My question is then, in what way is impunity superior to invigorate? How does the other calculator calculate effective health that the numbers are different?
Comment: I think your your calculations are wrong, even though resistance % is not linear, EHP from resistance is.  at level 60, [every 300 resistance points is equivalent to 100% EHP](http://gaming.stackexchange.com/a/73141/3917).
Comment: I would think the onyl time 10% health bonus out weighs the 50% resistance is if your EHP is already over 1000% and impunity only gives 300 resistance (an impossible situation since to get 1000% EHP your resistance is probably much higher in the first place.)
Comment: @yx, the link to battle.net forum from the other post was really interesting. It seems like the website I got my formula from has a different fromula than the one in that post (note that, my website is up-to-date while that post is from 3 months ago). Nevertheless, playing with impunity definitely "feels" easier, so I guess the other formula is more accurate.
Comment: **EHP = Health * (A + R - AR)**. So, if you'd theoretically have 0 armor and 0 resistance, your EHP would be 0, even if you have 42 billion hp... In other words, you'd be dead, even if you do not get hit by a monster.
Answer: I am afraid to say the EHP formula you quoted is very wrong. EHP should be HP divided by combined damage taken rate, not multiplied by damage reduction rate. For example if you have 10k HP and 60% combined DR, which means you're only taking 40% damage, it is equivalent to having 25k HP without any damage reduction, so your EHP is 10k / (1 - 60%) = 25k.
Using your simplified model and numbers, base EHP is 50k / ((1 - 56%)(1 - 78%)) = 516529.
With Invigorate, total EHP is 1.1 * 50k / ((1 - 56%)(1 - 78%))= 568182, or a 10% increase.
With Impunity, total EHP is 50k / ((1 - 65%)(1 - 78%)) = 649351, or a 26% increase.
As @yx pointed out, every 300 resistance equals to 100% EHP*, so the only case Invigorate will beat Impunity in terms of EHP increase is when 50% of your resistance is less than 30. Invigorate unlocks at lv41 and usually a character don't have much resistance (or HP) at that time, and the 310 regen could be something. However when a character reaches lv60 and enters Inferno, Impunity is the clear winner.
*Based on assumption of mLvl=60, while your DR numbers were calculated based on mLvl=63, so there might be a small gap but doesn't change the big picture.
Comment: It's also worth noting that lower health but lower intake of damage means that Life on Hit weapons are more effective.
Comment: Thanks. And for future reference, [this battle.net forum post](http://us.battle.net/d3/en/forum/topic/5149150485) helps a lot.

+% life vs +% resistance


Why was my question about Stockfish levels off-topic?

Question: How do Stockfish 13 Levels (Lichess) work?

This question does not appear to be about chess within the scope defined in the help center.

So, what does the help center say?

Chess-specific questions about programming a chess engine or other chess software are welcome.

I don't feel very welcome at all. Other questions about how an engine works, not just using the program, were not considered off-topic:

Do Stockfish and the tablebase work together or independently?
Lichess' Stockfish's tuning
Stockfish blunders away a piece
How does Stockfish ensure an incremental change made is beneficial?
Did AlphaZero also have to learn that each piece has a value?
etc.
Answer: Your original question read (to me) like a general user complaint about how this was working on Lichess. Apologies for my misunderstanding and now that you have made it clear that you primary interest is a chess programming one I have reopened.


Add text annotation to plot from a pandas dataframe

Question: My Code:
import matplotlib.pyplot as plt
import pandas as pd
import os, glob

path = r'C:/Users/New folder'
all_files = glob.glob(os.path.join(path, "*.txt"))
df = pd.DataFrame()
for file_ in all_files:
    file_df = pd.read_csv(file_,sep=',', parse_dates=[0], infer_datetime_format=True,header=None, usecols=[0,1,2,3,4,5,6], names=['Date','Time','open', 'high', 'low', 'close','volume','tradingsymbol'])

df = df[['Date','Time','close','volume','tradingsymbol']]
df["Time"] = pd.to_datetime(df['Time'])
df.set_index('Time', inplace=True)
print(df)

fig, axes = plt.subplots(nrows=2, ncols=1)
################### Volume ###########################
df.groupby('tradingsymbol')['volume'].plot(legend=True, rot=0, grid=True, ax=axes[0])
################### PRICE ###########################
df.groupby('tradingsymbol')['close'].plot(legend=True, rot=0, grid=True, ax=axes[1])

plt.show()

My Current Output is like:

I need add text annotation to matplotlib plot. My desired output similar to below image:
Comment: At one point you will need to decide: Do you want to have working solutions to your questions? Then provide a [mcve]. If not, feel free to continue asking questions without runnable code.
Answer: It's hard to answer this question without access to your dataset, or a simpler example. However, I'll try my best.
Let's begin by setting up a dataframe which may or may resemble your data:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 3)),
                    columns=['a', 'b', 'c'])

With the dataset we'll now proceed to plot it with
fig, ax = plt.subplots(1, 1)
df.plot(legend=True, ax=ax)

Finally, we'll loop over the columns and annotate each datapoint as
for col in df.columns:
    for id, val in enumerate(df[col]):
        ax.text(id, val, str(val))

This gave me the plot following plot, which resembles your desired figure.
Comment: Sir, How to convert df.groupby('tradingsymbol')['volume'] data to x1 (I mean numpay array)
Comment: You can convert with the [pandas.DataFrame.to_numpy](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy) function. I.e. ```df.groupby('tradingsymbol')['volume'].to_numpy()```.
Comment: I'm not very confident with ```pandas```, but i suspect you can loop over the values as ```for i, x in enumerate(df.groupby('tradingsymbol')['volume'])```
Comment: Not Working. Something is missing. AttributeError: 'numpy.ndarray' object has no attribute 'text'
Comment: Please see my edit --- I've altered the example to plot from a pandas dataframe.


What determines the devices that google play will offer apps to?

Question: I had assumed that if your manifest contains a line <uses-sdk android:minSdkVersion="X" /> then google play automatically knows to only show your app in the play store to people whose devices have android X or higher.... But I just recently tried out uploading an app (as beta) which contains <uses-sdk android:minSdkVersion="8" /> but upon looking at the app in the store on a PC (visible only to invited beta testers), it says in the store listing "Requires android 1.6 and up". This has confused me because I thought that SDK8 corresponded to Android 2.2.
Comment: I have the same issue (showing as 1.6+ in app store). However I am using a minSDK of 11...
Comment: @MuhammadA: Is that with a beta release? I guess it could just be a google bug that only shows up for beta apps.
Comment: My app is in Alpha at the moment.
Answer: Here is the official documentation of filtering criteria, and this is a list of all API levels.
The specific issue you have seems to be a bug with Google Play, see this question (and a few more unanswered ones here or here).
Comment: But that documentation would indicate that my line  is correct, but why does the listing say  "Requires android 1.6 and up"?
Answer: A the Goolge play store looks after our androidmaifest.com
<uses-sdk android:minSdkVersion="X"
          android:targetSdkVersion="X"
          android:maxSdkVersion="X"/>

as the min sdk tells that it will support from the api level and max sdk tell that it will support for that high level of devices.version. by looking after in the manifest files the Google play store will decide


SQL 1064 - You have an error in your SQL syntax when deleting across multiple tables

Question: I'm trying to delete specific rows in multiple log tables, for activity that is > 5 days old. but want to keep the log activity if the visitor_id is found in log_customer.
the following returns over 42 K rows:
SELECT *
FROM `log_url` , `log_url_info`, `log_visitor_info`, `log_visitor`
WHERE `log_url`.`visit_time` <= NOW( ) - INTERVAL 5
DAY
AND `log_url`.`url_id` = `log_url_info`.`url_id`
AND `log_url`.`visitor_id` = `log_visitor`.`visitor_id`
AND `log_url`.`visitor_id` = `log_visitor_info`.`visitor_id`
AND `log_url`.`visitor_id` NOT IN ( select `log_customer`.`visitor_id` from `log_customer` )

However, this returns the sql 1064 error:
DELETE
FROM `log_url` , `log_url_info`, `log_visitor_info`, `log_visitor`
WHERE `log_url`.`visit_time` <= NOW( ) - INTERVAL 5
DAY
AND `log_url`.`url_id` = `log_url_info`.`url_id`
AND `log_url`.`visitor_id` = `log_visitor`.`visitor_id`
AND `log_url`.`visitor_id` = `log_visitor_info`.`visitor_id`
AND `log_url`.`visitor_id` NOT IN ( select `log_customer`.`visitor_id` from `log_customer` )

Error messages:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'WHERE log_url.visit_time
<= NOW( ) - INTERVAL 5 DAY AND log_url.url_id' at line 3

I also get ...
#1064 - You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'WHERE log_url.visit_time
<= STR_TO_DATE('2014-08-21 10:00:00', '%Y-%m-%d %H:' at line 3

...if I replace NOW() ... with <= STR_TO_DATE( '2014-08-21 10:00:00', '%Y-%m-%d %H:%i:%s' )
Comment: What's the specific error message? That's likely to help you figure out where your MySQL syntax error lies.
Comment: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `log_url`.`visit_time` <= NOW( ) - INTERVAL 5 DAY AND `log_url`.`url_id`' at line 3

I also get

      #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `log_url`.`visit_time` <= STR_TO_DATE('2014-08-21 10:00:00', '%Y-%m-%d %H:' at line 3

if I replace NOW() ... with
    <= STR_TO_DATE( '2014-08-21 10:00:00', '%Y-%m-%d %H:%i:%s' )
Answer: Shouldn't that be...
DELETE `log_url` , `log_url_info`, `log_visitor_info`, `log_visitor`
FROM `log_url` , `log_url_info`, `log_visitor_info`, `log_visitor`
WHERE `log_url`.`visit_time` <= NOW( ) - INTERVAL 5 DAY
AND `log_url`.`url_id` = `log_url_info`.`url_id`
AND `log_url`.`visitor_id` = `log_visitor`.`visitor_id`
AND `log_url`.`visitor_id` = `log_visitor_info`.`visitor_id`
AND `log_url`.`visitor_id` NOT IN ( select `log_customer`.`visitor_id` from log_customer` )

or even...
DELETE u
     , ui
     , vi
     , v
  FROM log_url u
  JOIN log_url_info ui
    ON ui.url_id = u.url_id
  JOIN log_visitor_info vi
    ON vi.visitor_id = u.visitor_id
  JOIN log_visitor v
    ON v.visitor_id = u.visitor_id
 WHERE u.visit_time <= NOW( ) - INTERVAL 5 DAY
   AND u.visitor_id NOT IN ( SELECT visitor_id FROM log_customer)

Comment: of course! delete `log_url` , `log_url_info`, `log_visitor_info`, `log_visitor` from .. .

Thanks for the much more elegant option with the join!


Single pole relay on a 240VAC split phase circuit?

Question: I'm installing an EV charger but my panel is only big enough to run either the dryer or the EV charger at the same time. So I have a current sensor on the dryer line so that when the dryer is running the EV charger circuit opens.
The EV charger is 240VAC, 24A, on a split phase circuit. I have a crydom SSR (rated to 50A) and heat sink but it's single pole. Is it safe for me to just break a single phase on the EV circuit when I want to disconnect the charger? (It's currently working with a standard dual pole power relay, but the panel is in my bedroom and the click on/off is really loud and keeps waking the baby).
Here is the only info I have on the EV charger circuit:
Comment: While what you are doing is *conceptually* 100% fine, whether the implementation is proper or not is unknown. If you ever have an electrical fire or similar problem, the insurance company may invalidate your coverage based on this unlisted equipment *even if the equipment is not the cause of the fire*. There are commercial listed/certified/tested systems of this type available, and the cost may be worth it even if your homebrew solution is functionally identical.
Comment: @WiseShepherd -- the issue isn't the amp rating, it's that it's only UL Component Recognized (RU = Rather Useless to us) for use in a larger UL-Listed product vs being fully UL Listed for direct installation in the field
Comment: Note that you _cannot_ use a random SSR or relay for this -- you'll need something like a RIB or a general-purpose contactor that's listed to UL 508 and rated for the load in question.
Comment: @ThreePhaseEel the one I have is rated to 50A (https://www.sensata.com/sites/default/files/media/documents/2018-04-25/ourproducts_series-1-240-ac-panel-mount_datasheet.pdf)
Answer: Instead of dealing with turning on and off the car charger you can opt for a smart EVSE with current probes that go onto the feed of the panel.
That way the EVSE can throttle charging when other loads are taking up capacity.
Answer: Ah, the things people do to charge EVs.  If you actually run through your NEC 220.82 Load Calculation, you'll see that dryers come in only at 40%. EV loads come in at 125% (ask your municipality) so knocking out a dryer doesn't quite create the headroom needed to charge an EV.
However, your project would be much better served by an EVEMS system made specifically for this purpose, such as the Wallbox Pulsar Plus with Power Boost, or Emporia Load Management bundle. Trying to hork something together with electronics parts is tempting, but you will have a lot of explaining to do when it has a safety problem.  This work is already done for you, and done well.
Answer: Assuming you are also using a receptacle because it's the usual for this sort of weird DIY style charging setup, it's not particularly dangerous to break just one side of the circuit, but it's not particularly safe either. If you have one side open, the EVSE or the outlet for it can potentially appear to be dead and off due to not operating while also being live thanks to having 120V on one side. It's not an accident that equipment hooked to 240V almost always has a two pole contactor. Consider spending the $100 on a proper DPST SSR for your application.


Wrong keyboard layout on client PC when using synergy

Question: I just installed ubuntu 11.10 in my new computer, the old one (still main computer) is ubuntu 10.04. Both PCs use "Spanish LAm" keyboard layout, the only difference is that the new PC keyboard has some multimedia keys but the configs are the same and the work well each one on each PC.
But when I use synergy to use the main keyboard in the client PC (11.10), the keyboard layout seems to be the "Enlglish (US)" layout, or other but not "Spanish LAm", while settings on both PCs remain as "Spanish LAm". The other keyboard connected by cable to the client PC does work well with the spanish layout even when using synergy.
Any idea how to fix this?
Comment: I removed 11.10 and installed 11.04, I don't have the problem with this version.
Comment: "The issue is actually not fixed, but was instead closed because it's too broad." https://github.com/symless/synergy-core/issues/6005#issuecomment-426570946
Answer: In my case synergy seams simply to ignore actual keyboard layout but it helps if I set it after starting synergyc.
synergyc myhost
setxkbmap us -option grp:alt_shift_toggle

You will find correct values for setxkbmap arguments in file /etc/default/keyboard. Instead of us place value of XKBLAYOUT and pass value of XKBOPTIONS to -options.
You can use this simple script to do this automatically:
#!/bin/sh

. /etc/default/keyboard
synergyc $1
setxkbmap $XKBLAYOUT -option "$XKBOPTIONS" -model "$XKBMODEL" \
                     -variant "$XKBVARIANT"

Save it as mysynergyc, set correct permissions (chmod 755 mysynergyc) and then run as usual instead of synergyc.
Answer:
Search for "Keyboard Layout" and open it.
Use the plus sign on the
bottom left of the screen to add the keyboard layout "English(US)".
Restart synergy

This worked for me. (Ubuntu 11.10 64-bit)
Comment: I have the same problem in 12.04, though with Norwegian keymap and Windows 7 on the server side. It used to work flawlessly for me in 11.10 with the same setup. The suggestion in this answer does not work for me.
Answer: I had the same problem with my Windows server / Ubuntu client configuration.
At work I had the setup the other way around and it worked like a dream.
As a workaround a added an another keymap to the Ubuntu client. Then while using Synergy switched the keymap from en to de and it started working.
Answer: Stop the synergy server, reset keyboard layout in server, then restart synergy seems to solve the problem in my situtation. Original reference is here:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=580504#15
Answer: In my case, running Ubuntu 22-04, I open the synergy window (on the machine I had the problem), went on Keyboard & Mouse, and turned off "Alt G for PC keyboards only" in the advanced section. That solved the problem.


GNU Triplet, GCC and Linux kernel compiling

Question: My native gcc says, that its triplet is the following.
> gcc -dumpmachine
x86_64-suse-linux

Where cpu-vendor-os are correspondingly x86_64, suse, linux. The latter means that glibs is in use(?). When I am doing cross-compiling busybux-based system the compiler triplet is something like avr32-linux-uclibc, where os is 'linux-uclibc', meaning that uclibc is used.
The difference between 'linux-glibc' and 'linux-uclibc' is (AFAIU) in collect2 behavior and libgcc.a content. Either glibc or uclibs are silently linked to the target binary.
The questions is that how is the linux kernel been compiled by the same compilers? As soon as the kernel runs on bare-metal it must not been linked with any kind of user-space libc, and should use appropriate libgcc.a
Comment: Some compilers use a *quadruplet*.  The form is *architechure*-*vendor*-*os*-*library*.  But even this is not sufficient as *FPU*, *object format* and other conventions may apply.  At the root, `gcc` just supports a prefix that is free form.  People come up with names and there is no unifying body to make them unique.  `-dumpspecs`, etc can be used to help identify the compiler.
Answer: gcc has all kind of options to control how it works.
Here's a few relevant ones:

-nostdlib to omit linking to the standard libraries and startup code
-nostdinc to omit searching for header files in the standard locations.
-ffreestanding to compile for a freestanding environment (such as a kernel)

You also do not need to use gcc for linking. You can invoke the linker directly, supply it with your own linker map, startup object code, and anything else you need.
The linux kernel build seems, for arbitrary reasons not to use -ffreestanding , it does control the linking stage though, and ensures the kernel gets linked without pulling in any userspace code.
Comment: Linux has some built-in functionality normally provided by *libgcc*.  I hope this is the same independent of the *libc* used.  For the ARM, you can still mess up the kernel if you use a compiler with different register conventions.  For identical compiler options, except for the library (glibc/eglibc vs uclibc vs newlib), your answer might be correct.  Here is [an example](http://stackoverflow.com/questions/12174247/android-ndk-8b-cannot-load-library) libgcc function generated by the compiler, but not available in the system.  Linux has many internal *libgcc* functions in it's source.
Comment: In this case would it be possible to use x86_64-suse-linux-uclibc instead of x86_64-suse-linux-glibc by just specifying '-nostdlib -nostdinc -I ... -L ... -l ...'? This means that specifying linux-uclibc is redundant.
Comment: For compiling a kernel it shouldn't matter which of the two you use, for user space applications it should be possible, but quite cumbersome as you'd have to manually pull in the proper startup code and libraries, and possibly a different linker map, as well as supplying or overriding preprocessor macros if there's any code that relies on e.g. a #define being present for telling the difference between glibc and uClibc.


RXJS data manipulation

Question: I am trying to find the reactive way of manipulating data in an array of objects.  In the array below, I want to determine the low score in groups of four and add a low and diff property to the item.
<code>arr = [
    { name: 'Cliff', score: 44 },
    { name: 'Bob', score: 55 },
    { name: 'Jack', score: 404 },
    { name: 'John', score: 50 },
    { name: 'Doug', score: 22 },
    { name: 'EZ', score: 550 },
    { name: 'Bill', score: 404 },
    { name: 'Dan', score: 5 },
    { name: 'Rich', score: 404 },
    { name: 'Steve', score: 565 },
  ];
  arr$: Observable<Arr[]> = of(this.arr);

  getData() {
    const scores = this.arr$.pipe(
      map((result) =>
        result.map((data) => {
          return {
            x: data.score,
          };
        })
      )
      // reduce((acc, x) => (acc = acc > x.score ? acc :x.score), 0)
    );

    return scores;
  }
}

/*
Desired result
arr = [
  { name: 'Cliff', score: 44, low: 44, diff 0 },
  { name: 'Bob', score: 55, low: 44, diff: 9 },
  { name: 'Jack', score: 404, low 44, diff: 360 },
  { name: 'John', score: 50, low: 44, diff: 6 },
  { name: 'Doug', score: 22, low 5, diff: 17 },
  { name: 'EZ', score: 550, low 5, diff: 545 },
  { name: 'Bill', score: 404, low 5, diff: 399 },
  { name: 'Dan', score: 5, low 5, diff: 0 },
  { name: 'Rich', score: 404, low: 404, diff: 0 },
  { name: 'Steve', score: 565. low 404, diff: 121 },
];
*/
</code>
I can't seem to get past the few lines of code that I've written.  A StackBlitz is here.
Comment: don't the data need to be sorted by score first?
Answer: This could be a reactive way to get what you want. The comments in the code explain the logic.
<code>// the from rxjs function takes an array and returns an
// Observable that emits each item in the array
from(arr)
  .pipe(
    // bufferCount will emit an array of arrays of items,
    // therefore creates the groups of four items
    bufferCount(4),
    // for each group we find the low and create
    // the new items with the low value and the diff
    map((buff) => {
      const low = buff.reduce((acc, curr) => {
        return acc < curr.score ? acc : curr.score;
      }, Infinity);
      return buff.map((v) => ({ ...v, low, diff: v.score - low }));
    }),
    // with mergeMap we flatten the groups of items
    // and emit each item
    mergeMap((buffEnriched) => buffEnriched),
   // if you want to emit an array rather than each single
   // object you add toArray
   toArray()
  )
</code>
Comment: Thank you.  I have updated the StackBlitz to your answer.  Do you have a good source to learn reactive design patterns?  What I find online rarely goes much beyond the use of each operator.
Answer: it makes more sense to sort, then generate your data. otherwise, your output data in your question makes little sense to me.
<code>// DATA IN
arr = [
    { name: 'Cliff', score: 44 },
    { name: 'Bob', score: 55 },
    { name: 'Jack', score: 404 },
    { name: 'John', score: 50 },
    { name: 'Doug', score: 22 },
    { name: 'EZ', score: 550 },
    { name: 'Bill', score: 404 },
    { name: 'Dan', score: 5 },
    { name: 'Rich', score: 404 },
    { name: 'Steve', score: 565 },
  ];

// PROCESSING and OUTPUT
let lowest = arr[0].score;
let output_arr = arr.sort((a, b)=>{
    if(a.score < b.score) return -1;
    if(a.score > b.score) return 1;
  return 0;
}).map((a)=>{
    if(a.score < lowest) lowest = a.score;
        return {
        name: 'Steve',
      score: 565,
      low: lowest,
      diff: a.score - lowest
     };
});

// use output array output
console.log(output_arr);
</code>
DEMO
Example
INPUT
<code>[
    { name: 'Cliff', score: 44 },
    { name: 'Bob', score: 55 },
    { name: 'Jack', score: 404 },
    { name: 'John', score: 50 },
    { name: 'Doug', score: 22 },
    { name: 'EZ', score: 550 },
    { name: 'Bill', score: 404 },
    { name: 'Dan', score: 5 },
    { name: 'Rich', score: 404 },
    { name: 'Steve', score: 565 },
  ]
</code>
OUTPUT
<code>[{
  diff: 0,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 17,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 39,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 45,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 50,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 399,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 399,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 399,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 545,
  low: 5,
  name: "Steve",
  score: 565
}, {
  diff: 560,
  low: 5,
  name: "Steve",
  score: 565
}]
</code>
Comment: The input array reflects two groups of four players and one group of two.  Assume that I want to balance/handicap the next competition among these players.  Sorting the entire array does not work.  Also, I'm trying to learn how to perform the manipulation using Observables.  Your concise declarative answer works, but I don't want to subscribe the the Observable array at this point and thus need a reactive approach similar to @Picci  above.

RXJS data manipulation


How to handle shouldInterceptRequest parameter change in API21?

Question: In API21 Google modified shouldInterceptRequest method to use WebResourceRequest request instead of String url.
Is there any way I could write a generic class extending WebViewClient and handle both methods?
My minimum API version is 18.
Thanks
Krystian
Answer:
Google modified shouldInterceptRequest method to use WebResourceRequest request instead of String url

No, they added a second shouldInterceptRequest() method. Both are available in API Level 21+; the String variant is available on API Level 11+. While the String one is marked as deprecated, the String variant should be supported for quite some time, for backwards compatibility.

Is there any way I could write a generic class extending WebViewClient and handle both methods?

The built-in implementation of the WebResourceRequest version of shouldInterceptRequest() simply calls the String implementation of shouldInterceptRequest():
public WebResourceResponse shouldInterceptRequest(WebView view,
        WebResourceRequest request) {
    return shouldInterceptRequest(view, request.getUrl().toString());
}

(from the source code as of right now)
So, you have two choices:

Just override the String edition, if you do not need the WebResourceRequest, and it will be used on all relevant API levels.
Override both, knowing that the WebResourceRequest one will be used on API Level 21+ and the String edition will be used on API Levels 11-20.
Comment: Thank you CommonsWare, in fact what I did was implementing both methods and using `@TargetApi(Build.VERSION_CODES.LOLLIPOP)` on the one from API21.
Comment: I think overriding string version should be just fine.


HeadlessException with java.awt.Robot with Jenkins on a Mac Mini

Question: We've a Mac Mini that does some automated testing from a brew Jenkins install, on a Mac Mini in our office, which we're using a test tool called "Genie", which at it's lower level, creates a java.awt.Robot, but at sun.awt.HToolkit.createRobot, a java.awt.HeadlessException occurs.
java.awt.HeadlessException
at sun.awt.HToolkit.createRobot(HToolkit.java:160)
at java.awt.Robot.init(Robot.java:138)
at java.awt.Robot.<init>(Robot.java:96)
at com.adobe.genie.genieUIRobot.UIFunctions.<init>(Unknown Source)
at com.adobe.genie.executor.uiEvents.UIImage.<init>(Unknown Source)

Funny thing is that the exact same job works completely fine on my own MacBook Pro, from the exact same brew Jenkins install.
Really confused about it, and have tried some of the workaround answers that have popped on here,  the launch script is:
java -Djava.awt.headless=false -jar /Developer/Genie/GenieScripts/Executor.jar --logFolder /tmp /Developer/Genie/GenieScripts/bin/scripts/TestScript.class

And then in the TestScript.java, there's
System.setProperty("java.awt.headless", "false");
System.setProperty("javafx.macosx.embedded", "true");

in a static {} block, in the constructor and in the start() function.
Both machines are fully up to date Mavericks OS machines.
Answer: So, for this particular instance, the way to get it working was to ensure that the Jenkins session was started as the real, logged in, head-full user.
With Genie, and obviously createRobot though, they did.
So, to get things back up and running, we changed the user Jenkins was running as to the real account on the Mac Mini, and then after that, we changed the way it was starting from a system service, starting before login, to a user service, starting after login, by that logged in user.
That was how I had, by accident and default, installed it on my laptop and hence why it had worked without incident for me.


Expo App not updating on iOS physical device (Expo Go)

Question: I'm trying to run my app on my phone with Expo Go but changes I make to the code are not being updated. Both my devices are on the same wifi network and Fast Refresh is enabled. When I reload the app on the Terminal, it says the bundling with my phone is complete, so it doesn't seem to be a connection error...
Any thoughts ?
Thanks!
Comment: try to clear cache with `expo r -c`
Comment: It says my JavaScript transform cache is empty but nothing changes... Not updating.
Answer: Problem solved. If you're using Visual Studio Code, make sure you click on "Trust" the files you're coding on...
Comment: Where do you see that you can click on "Trust" the files?


BATCH: set a systemvariable with a path form another txt file

Question: I would like set a systemvariable in batch with a path which is written in a txt file. I already have the syntax but I don't know how can I read one line in the txt file and use the read line as variable path.
Can anyone help please?
setx -m thul type C:\Temp\pfade.txt

Answer: for /f "usebackq delims=" %%a in ("c:\temp\pfade.txt") do setx -m thul "%%a"

Or
set /p "value="<"c:\temp\pfade.txt"
setx -m thul "%value%"


Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted

Question: I'm studying for an exam and this is on my practice test. The question is "Which type of error does the following code fragment cause?"
I was pretty sure there would be no errors, but I also can't get it to compile in VS13, I get the error:

Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted.

    const int MAX = 500;
    int main(void)
    {
        int foo[MAX];
        for (int i = 0; i <= MAX; i++)
        {
            foo[i] = i * 2;
            cout << foo[i] << endl;
        }

    cout << "Press any key to exit." << endl;
    cin.ignore(2);

    return 0;
    }

Comment: You introduce undefined behaviour since you access out of bounds (i.e,. you access `foo[500]`).
Answer: Valid indexes for foo are from 0 to MAX-1 inclusive. MAX is past the end of the array.
Your loop runs up to, and including, MAX. This writes beyond the end of the array, corrupting the stack.
Either increase the array size to MAX+1 so that MAX is in range; or change the loop condition to i < MAX to stop before reaching MAX.
Answer: This problem is caused when you try to write too much data to a particular memory address. Typical causes are writing more to a string buffer than you have room for.
ie
void myfun()

{

    char mybuf[10];

    strcpy(mybuf, "This is definitely more than 10 characters long, it will also cause a Run-Time Check");

}

Another cause of this is when you are using memset/ZeroMemory to initialise a structure or array with the wrong size.
struct MyStruct

{

    int var;

};

void myfun2()

{

    MyStruct ms;

    ZeroMemory(&ms, 20); //since MyStruct is only one variable in the struct this will cause problems

}

A third possible problem is if you are accidentaly moving a pointer.
void myfun3()

{

    int a;

    int*b = &a;

    a++;

    *a = 20;

}

Of course, these problems are not so easy as above to find out, but I hope this will get you on the right track. But this happens and will break at the end of the function that the stack is corrupted in while it is returning. So the best place to look would be in the function that your LoggerThread variable is in.
Answer: It's usually allocating an array member past the max. I made a little password cracker with a large source array and no probs. I found I was calling an extra cycle past the max array size due to a loop condition mistake.
Comment: This doesn't add a lot (if any) information. Rather than discussing possible causes of stack corruption, it would be better to discuss what's wrong with the code in question.


Connecting SharePoint to Database as a service like AWS RDS or Azure SQL Databases

Question: Having a SharePoint on an instance [EC2 - AWS / Azure VM - Azure ] is the way we take SharePoint on Cloud (leaving the SharePoint Online with Office365). It would really great if we can connect the SharePoint instance with the Database as a Service like AWS RDS or Azure SQL Databases.
Is it possible in the first place? This is for both the cloud vendors AWS and Azure. I guess the main hurdle would be to bring the Database end point under the Subnet.
Answer: SharePoint does not support using a Database as a service as its store.  That said there are other integration points between SPS2k13 & Azure (e.g. Azure Web Sites, Auth Service, etc.).
http://msdn.microsoft.com/en-us/library/fp179922.aspx


PHP: Show 3 td's of data per table row

Question: I am wanting to use 8 images from my database and load them into a HTML Table. I would like to display 4 images per table row, but however when i run my code below, i seem to get all images in one table row. Any help would be great. Thank you in advance.
$count = $get->rowCount();

        if ($count > 0)
        {
            echo '
';

            $i = 0;

            while ($r = $get->fetch(\PDO::FETCH_OBJ))
            {
                $globals = new \Libraries\Helpers\Views\Globals;

                if ($i == 0)
                {
                    echo '
';
                }

                echo '

                        data_id.'">

                                data_image_name($r->data_id).'">

                     ';

                if ($i > 4)
                {
                    $i = 0;
                    echo '
';
                };

                $i++;

                echo '

                     ';
            }

            echo '
';

Comment: remove the semi-colon from the if($i > 4) and make the $i++ happen in an else after the if
Answer: In your current code, you're verifying if the $i variable is == 0 in order to add a row. But you're always increasing it's value at the end, even after you set it to zero in the if($i > 4)
Change these lines
if ($i > 4)
{
    $i = 0;
    echo '
';
};

$i++;

To this:
if ($i > 4)
{
    $i = 0;
    echo '
';
}
else
$i++;

Comment: Did you get different results? Try adding an = symbol on the if: `$i >= 4`
Comment: I changed $i = 1, instead of how it was $i = 0 and it worked
Comment: Cool! That was because when you say if $i > 4, it's when it's value is 5. And from 0 to 5 there are 6 values. What you did will work :)
Comment: Thanks for ur assistance. New to PHP and hoping to make it a primary language. Enjoy the day
Comment: Thank you, don't forget to pick the accepted answer ;)
Answer: put this code directly it will works...
echo '
';
    $i = 0;
    while ($r = $get->fetch(\PDO::FETCH_OBJ))
    {
        $globals = new \Libraries\Helpers\Views\Globals;
        $i++;
        if ($i == 1)
        {
            echo '
';
        }
        echo '

                data_id.'">

                        data_image_name($r->data_id).'">

             ';
        if ($i >= 4)
        {
            echo '
';
            $i = 0;
        };
        echo '

             ';
    }
    echo '
';

PHP: Show 3 td's of data per table row