AD B2C compareClaims throws internal server error

Question: I am trying to compare 2 claim (one from id_token_hint and one from AD B2C) . My requirement is to throw an Error Page that the 2 do not match and re-direct to login page.
For the same I have added the following steps :

Added ClaimType (boolean for comparison)
<ClaimType Id="agencyClaimMatch">
<DisplayName>Verify if input Agency and agency in AD B2C match</DisplayName>
<DataType>boolean</DataType>
<UserHelpText>Verify if input Agency and agency in AD B2C match</UserHelpText>
</ClaimType>

Create a ClaimTransformation (based on post to compare the 2 claims (extension_agency from AD B2C and agency from input claim of id_token_hint)
   <ClaimsTransformation Id="checkSameAgency" TransformationMethod="CompareClaims">
  <InputClaims>
   <InputClaim ClaimTypeReferenceId="extension_agency" TransformationClaimType="inputClaim1"/>
   <InputClaim ClaimTypeReferenceId="agency" TransformationClaimType="inputClaim2"/>
  </InputClaims>
  <InputParameters>
    <InputParameter Id="operator" DataType="string" Value="EQUAL"/>
    <InputParameter Id="ignoreCase" DataType="string" Value="true"/>
  </InputParameters>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="agencyClaimMatch" TransformationClaimType="outputClaim"/>
  </OutputClaims>

3.Added a Technical Profile to invoke the transformation (I am expecting the agencyClaimMatch boolean to get a true or false value based on the transformation, if false bot do not match need to throw the error page else allow access)
        <TechnicalProfile Id="CheckAgencyMatch">
       <DisplayName>Check Agency Match</DisplayName>
       <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=126.96.36.199, Culture=neutral, PublicKeyToken=null" />
       <Metadata>
          <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
       </Metadata>
       <IncludeInSso>false</IncludeInSso>
       <InputClaims>
         <InputClaim ClaimTypeReferenceId="agency" Required="true" />
         <InputClaim ClaimTypeReferenceId="extension_agency" Required="true" />
       </InputClaims>
       <OutputClaims>
         <OutputClaim ClaimTypeReferenceId="agency"/>
         <OutputClaim ClaimTypeReferenceId="extension_agency" />
         <OutputClaim ClaimTypeReferenceId="agencyClaimMatch"/>
       </OutputClaims>

      <OutputClaimsTransformations>
         <OutputClaimsTransformation ReferenceId="checkSameAgency"/>
      </OutputClaimsTransformations>
    </TechnicalProfile>

In UserJourney I added a ClaimExchange to get the value of checkSameAgency.

 <OrchestrationStep Order="6" Type="ClaimsExchange">
   <ClaimsExchanges>
     <ClaimsExchange Id="CheckAgencyMatch" TechnicalProfileReferenceId="CheckAgencyMatch"/>
   </ClaimsExchanges>
 </OrchestrationStep>

If boolean output checkSameAgency is not "True" that is both agencies do not match then throw an error else move to next step to issue jwt token .

 <OrchestrationStep Order="7" Type="ClaimsExchange">
   <Preconditions>
     <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
       <Value>agencyClaimMatch</Value>
       <Value>True</Value>
       <Action>SkipThisOrchestrationStep</Action>
     </Precondition>
   </Preconditions>
   <ClaimsExchanges>
     <ClaimsExchange Id="SelfAssertedAgencyNotMatched" TechnicalProfileReferenceId="SelfAssertedAgencyNotMatched" />
   </ClaimsExchanges>
 </OrchestrationStep>

But I am getting an error "The page cannot be displayed because an internal server error has occurred." even if the agency matches or if they don't.
Comment: As suggested by @rbrayb updated from

A SelfAssertedAttributeProvider is only used to display a screen, but you are only comparing claims. It should be

https://learn.microsoft.com/en-us/azure/active-directory-b2c/claims-transformation-technical-profile
Answer: <TechnicalProfile Id="CheckAgencyMatch">
           <DisplayName>Check Agency Match</DisplayName>
           <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=126.96.36.199, Culture=neutral, PublicKeyToken=null" />
           <Metadata>

A SelfAssertedAttributeProvider is only used to display a screen, but you are only comparing claims. It should be
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.ClaimsTransformationProtocolProvider, Web.TPEngine, Version=22.214.171.124, Culture=neutral, PublicKeyToken=null" />

Refer this.


Inputting stock tickers into Pandas and producing a table of returns

Question: Complete beginner here.
I'm trying to write a program in Python which takes a user input and plugs it into a Panda block of code to produce a table of stock prices in a date range.
So far, my input block looks like this:
StockCount = input ('Input the number of stocks in the portfolio: ')

StockTickerArray = list()

for i in range(1,StockCount+1):
   StockTicker = raw_input ('Enter Stock Ticker '+str(i)+': ')
   StockTickerArray.append(str(StockTicker))
   """
   print "you entered", StockTicker
   """

print 'ARRAY: ', StockTickerArray

So, let's say you enter just 1 stock: AAPL. That's the input. I want to be able to take AAPL and plug it in DataReader where it says "Stock Goes Here". Is that possible?
from pandas.io.data import DataReader
from datetime import datetime

stock = DataReader("STOCK GOES HERE",  "yahoo", datetime(2009,1,1))
print stock ["Adj Close"]

Thanks
Answer: StockTicker = raw_input ('Enter Stock Ticker '+str(i)+': ')
stock = DataReader(StockTicker,  "yahoo", datetime(2009,1,1))


How should I install a chimney for a wood stove in my garage?

Question: I have a new construction 24' x 48' garage that is two stories.  It is partial block construction (to middle of 2nd floor) and finished on the top with wood (trusses etc). The floor plan is very open.  I plan on installing a wood stove listed below:
SKU Number: 1015370
Manufacturers Number: B2350B
Brand: United States Stove
Fuel Type: Wood/Coal
Hopper Capacity: 50 lb.
Log Size: 23 in.
BTUs: 106,000
I want to install it on the first floor (concrete floor).  My question is where should I run my chimney?
Should I plan on going up through the ceiling of the first floor, into the second floor and through that ceiling into the attic, then through the roof? (the garage is something like 22+ feet tall to the eaves) I could build a steel grate to be around the pipe to prevent anyone from touching it etc on the second floor.  I would obviously use double wall pipe for the length between the floors, and preferable single wall in the first and second floor in the "open air" spaces to get the most form the heat, followed by double wall for attic/roof. I have heard of people going through closets, etc, does that seem ok?
My other option is to go through the block wall on the first floor, but then have an ugly, and expensive run of about 20ft insulated chimney pipe to get the desired height above the roof to ensure proper draft.
I am doing this on as tight of a budget as possible. I have considered pellet stoves, but have a steady unlimited local supply of wood available.  I realize it may not heat the second floor completely, so I will supplement with another type of heater up there when needed.  I do not have hvac installed in the garage, and would rather not install any. The garage is a very basic rectangle shape. I plan on insulating it very well.
Comment: Just a heads up that there may be code issues installing wood stoves in garages in your region.
Answer: Assuming open flame heaters are allowed in a garage in your area, carefully check all clearance requirements for the stove and flue.  I would encourage you to adapt to triple wall insulated flue pipe at the ceiling of the first floor and stay with insulated pipe the rest of the way. Do not attempt to change back to single wall pipe.
You may want to install a couple of floor registers to help take some of the warm air from the first floor to the second floor. Remember, heat rises, and depending on how long you run the stove, the heat will eventually fill the second floor.  Some simple electric fans can also be placed strategically to move the warm air around and even out the temp in the building.
Answer: To ensure maximum heat usage I would run it up through the second floor and out the roof there using a single skin flue ( if this is allowable by code and manufactures specs) and a decorative (perforated/decro) flue cover
You can then get ceiling rings to cover the necessary gap around the flue to combustible floor surfaces which will match the decro you choose.
One advantage of running it out the wall is for cleaning of the flue if you use wood that tends to soot the flue up as you can put an access tee out side the house.  But you do waste a lot of heat this way.


Looped update SQL stored procedure

Question: I need to define a stored procedure inSQL Server with a loop to create a bridge table between old and newest product codes. I am not an expert in SQL and I'm having some trouble...
I already have a source table that contains all product codes changes, However, I need to create the table that contains the relation of all OLD product codes with the NEWEST product code.
The source table is like:
PRD_OLD   ----   PRD_NEW
00001         ----    00003
00002         ----    00003
00003         ----    00004
00004         ----    00005
00006         ----    00007

It can be seen that products 1 and 2 correspond to product 3. Then 3 corresponds to 4 and then 4 corresponds to 5, so the newest product ID for 1, 2, 3 and 4 should be 5.
The output table then should be:
PRD_OLD   ----   PRD_NEW
00001         ----    00005
00002         ----    00005
00003         ----    00005
00004         ----    00005
00006         ----    00007

Note: in my table the Codes are codes with both letters and numbers (GUIDS) so using maximums won't work...
Can anyone help?
Thanks!
Answer: You can do this with a recursive CTE:
with cte as (
      select prd_old, prd_new, 1 as lev
      from source
      union all
      select cte.prd_old, s.prd_new, lev + 1
      from cte join
           source s
           on cte.prd_new = s.prd_old
     )
select t.*
from (select cte.*, max(lev) over (partition by prd_old) as max_lev
      from cte
     ) t
where lev = max_lev;

Looped update SQL stored procedure


Show that there exists a basis

Question: Let $g$ be an idempotent endomorphism. Show that there exists a basis $B$ for $V$ such that for some $v_i\in B$: $g(v_i) = v_i$ for $1 \leq i \leq r$ and $g(v_i) = 0$ for $r+1\leq i \leq n$, where $r = \text{rank}(g)$ and $n = \text{dim}(V)$.
I know $g: V \to V$ as an idempotent endomorphism means $g(g(v)) = g(v)$, but not sure how to proceed with this problem.
Answer: The fact that $\text{rank}(g) = r$ means that the image of $g$ will be an $r$-dimensional vector subspace of $V$. Therefore, it can be spanned by $r$ linearly independent vectors of $V$. Let $v_1,\dots,v_r$ be such vectors. Then, as they lay in the image of $g$, there are $w_1,\dots,w_r$ in $V$ such that $v_i =g(w_i)$ for $i=1,\dots,r$. Thus
$g(v_i) = g(g(w_i)) = g(w_i) = v_i$ for $i=1,\dots,r$.
The dimension theorem also shows that the kernel of $g$ has to be $n-r$ dimensional, and therefore can be spanned by $n-r$ linearly independent vectors of $V$, say $v_{r+1},\dots,v_n$. Then by definition,
$g(v_i) = 0$ for $i=r+1,\dots,n$.
Since $\text{im} (g) \cap \text{ker}(g) = {0}$, the set $v_i$ for $i=1,\dots, n$ then also is linearly independent, and therefore form a basis of $V$ with the claimed properties.

Show that there exists a basis


Leaving gold and elixir uncollected to prevent losing when raided

Question: In Clash of the Clans, to minimize loss of resources when your base is attacked is it better to store loot in clan castle and not collect it? Also is it better to leave resources in elixir collectors/mines for as long as possible before collecting it (at what point is it necessary)?
Answer: Without question, the best place to keep your resources is in the Clan Castle and Storage buildings.
All information can be referenced from the Clash of Clans Wiki Raid article. Here are the percentages of loot that can be stolen during a raid. Keep in mind that there are also loot caps, which differ depending on what building is storing the resources and what Town Hall level you are at.
Collectors/mines: 50% - no cap beyond the capacity of the mine/collector

Gold/Elixir Storages — Percentage depends on Town Hall Level
Level Percentage Cap
1-5   20%        200,000
6     18%        200,000
7     16%        250,000
8     14%        300,000
9     12%        350,000
10    10%        400,000

Clan Castle Treasury — Flat 3% at all Town Hall levels on destruction

For completeness, I'll include information for Dark Elixir as well.
DE Drills: 75% - no cap beyond the capacity of the drill

Dark Elixir Storage — Percentage depends on Town Hall Level
Level   Percentage  Cap
7       6%          1,200
8       6%          2,000
9       5%          2,500
10      4%          3,000

There's one or two other things that can affect how much resources are available during a raid, but they are broad and apply to all resource buildings equally. As you can see for gold/elixir, the Clan Castle offers the lowest percentage of available loot, followed by the storage buildings. The Dark Elixir storage is just slightly better than the clan castle when it comes to protecting Dark Elixir, but it is probably still optimal to keep the resources in the Clan Castle to protect gold/elixir and the benefit of not keeping all your DE in one "basket", so to speak. But keeping resources uncollected in the mines/collectors/drills is certainly the the worst place to leave them.
Answer: It's better to collect.  You can defend your stores much easier than you can all your collectors.
And of course, spend it as soon as possible.  Queue up troops etc.
Also, an advantage of having a side town hall ( in a corner with no defenses ) is quite often it will get sniped ( someone will just drop a few archers and destroy just the town hall )  and you will get a shield for 12 hours which will protect your resources.
Comment: This isn't the case anymore. Since the most recent update getting "sniped" is not as fruitful as it used to be. You won't get a full shield anymore so you probably don't want to keep your townhall outside to get sniped anymore.


Using Highcharts with IE 11 from ES5 folder but it crashes

Question: I try to run Highcharts with IE11 but it crashes
I load Highcharts from ES5 folder as told in the documentation.
IE11 devtool console indicates that the Highcharts es5 code not seem to be valid ES5.
Is there a bug or am I doing something wrong?
Comment: It's difficult to say what is wrong without seeing your code or any example. Make sure the issue is not caused by Internet Explorer 11 itself, as it is no longer supported. Please provide some additional information, such as the version of Highcharts, whether you are using any wrappers, and if you are encountering any errors. If possible, please try to reproduce your issue in an online demo. Regards
Comment: We've found the error. The ES5 code has been constructed wrong using a ES6 type of object {d} instead of {d:d}.
Answer: We've found the error. The ES5 code has been constructed wrong using a ES6 type of object {d} instead of {d:d}.
It has been addressed by the library owners. In the meanwhile we've corrected the code in the lib in our app, runs fine now.


When and why to use mind spike

Question: I am unsure of when to use mind spike.
I've noticed that my shadow priest rotation often boils down to the following:

shadow word: pain
vampiric touch
mind blast
devouring plague
vampiric embrace
mindbender
shadow word: death

I'm not sure where mind spike should fit, I do know that it cancels all damage over time abilities so I can't think of when to use it.
Also, is there anything I can do to improve my rotation.
Is there any difference in the approach I should take for solo, raid and dungeon play?
Comment: Should it be just before the DOTs (damage over time) expire?
Comment: I often begin with vampiric touch for one on one fights.
Answer: Mind Spike is primarily for enemies which will die soon so that dots will not tick longer.
Here is a shadow priest guide for the actual game version with more informations. The best rotation depends a lot of factors like enemies, buffs, talents and glyphs. Some Examples:

The Talent Surge of Darkness lets you cast Mind Spike withour removing dots from the target when it procs. This means you should cast it always when the talent procs.
The Talent Clarity of Power lets you play with a rotation without dots.
Glyph of Mind Spike makes your Mind Blast casts instant after casting two Mind Spikes. This is useful if you're using Mind Spike on lots of low health adds.
Comment: Yeah, when Mind Spike was originally introduced to the game (WotLK?), it was billed as a spell for quick kills.  Like when you're out questing and don't want to dot up enemies and wait forever for them to die.

When and why to use mind spike


(Bucket Not Deleted) Amazon S3 error- A conflicting conditional operation is currently in progress against this resource

Question: Why I got this error when I try to create a bucket in amazon S3? My buck still exists and is not deleted but I'm just trying to attach SNS topic to my bucket
Bucket error pictured
Answer: I was seeing similar issues. There was an AWS service interruption for S3 in us-east-1.
https://status.aws.amazon.com/
Everything looks OK on my end now.


gcc internals: calculating instruction costs

Question: I'm working on a gcc backend for an architecture. The architecture has instructions for indexed array access; so, ld r0, (r1, r2) is equivalent to r0 = r1[r2] where r1 is a int32_t*.
I'm representing this in the .md file with the following pattern:
(define_insn "*si_load_indexed"
  [
    (set
      (match_operand:SI 0 "register_operand" "=r")
      (mem:SI
        (plus:SI
          (mult:SI
            (match_operand:SI 1 "register_operand" "%r")
            (const_int 4))
          (match_operand:SI 2 "register_operand" "r"))))
  ]
  ""
  "ld %0, (%2, %1)"
  [(set_attr "length" "4")]
)

However, the instruction is never actually being emitted. Looking at the debug output from the instruction combining stage, I see this:
Trying 8, 9 -> 10:
Successfully matched this instruction:
(set (reg:SI 47 [ *_5 ])
    (mem:SI (plus:SI (mult:SI (reg/v:SI 43 [ b ])
                (const_int 4 [0x4]))
            (reg:SI 0 r0 [ a ])) [2 *_5+0 S4 A32]))
rejecting combination of insns 8, 9 and 10
original costs 8 + 4 + 4 = 16
replacement cost 32

If I've read this correctly, it indicates that the instruction pattern has been matched, but the instruction has been rejected due to being more expensive than the original instructions.
So, how is it calculating the cost of my instruction? Where's it getting that 32 from (which seems weirdly high)? How do I persuade gcc to actually use this instruction?
Comment: How did you resolve this? I have the same issue and need to
define cost for a new instruction with a similar pattern above
Comment: I didn't. I gave up and used LLVM. Sorry.
Answer: The proper place to asked questions like this is email@example.com. They're very helpful if you ask intelligent questions. :)
You should read the Internals Manual first, of course. The relevant section is here: http://gcc.gnu.org/onlinedocs/gccint/Costs.html#Costs
I believe you need to look at TARGET_RTX_COSTS, but I could be wrong. The default behaviour is to estimate the cost by stepping through the RTL recursively and adding up the operations, I think, but it's convoluted and a while since I looked at it (look at rtx_costs).
Other ports add instruction attributes to help them judge costs.
Comment: Yes, I've been reading that, but I've found it very puzzling --- surely the cost of an instruction depends on the instruction selected, and not the RTL that the instruction represents? Right now I have all the costing infrastructure set to the default, but _something_ isn't working right... what I'd really like is to be able to set the cost for each instruction manually in the `define_insn` clause, the way I do for lengths, but haven't found a way to do this yet.
Comment: Bear in mind that some define_insn are meta-instructions that get split later.
Comment: Look at other ports. They typically have an attribute to split the instructions into groups or classes or whatever. They then use those attributes in the costs calculation. They prefer not to use absolute numbers because costs vary between processor variants.


What tools are available to collect statistics on user behavioral patterns?

Question: I have an application with a relatively large user base. I would like to collect statistics on user behavior, analyze patterns etc. I expect that statistics to answer questions like:

How many female users vs. male users clicked button ABC?
How many 20-30 years old users followed XYZ behavioral pattern?
What sequence of actions users take when they work with window DEF?

And so on...
In my opinion Google Analytics is not a good choice as they focus on traffic patterns, rather than application logic.
Are there tracking tools collecting statistics on users and then helping to analyze the data?
Answer: I haven't heard of a tool that gives you demographic information as you specified. And I'm not sure that's possible. The only think you can do is track specific users by using Mixpanel or Universal Analytics logging in from different devices (PC, mobile, smartwatch), With the normal analytics if a user logs in with a different device it will be displayed as a separate session. However, to be able to use this kind of analytics you need to support user registration.
Comment: Thanks. I have all data on user demographic etc., I just need a tool which would be capable of collecting and slicing and dicing this info. I'll check Mixpanel. What is Universal Analytics?
Comment: Its the same as Mixpanel, but from Google. Basically its Google analytics but with the option to track logins of individual users, see if they are logging in with different devices. The normal analytics cannot track if one user has logged in with different device.


Get NDEF-Messages from block data

Question: I have an android NFC solution based in NDEF-Messages where I read parcelable extra tags from android intent. The data in NFC card is text plane and not key protected.
I need run my app on a personalized hardware, the owner brings to me an SDK for that purpose, but not support NDEF-Messages as native android do.
The owner sdk have authenticate(int block, int keyType, byte[] key) method, and read_block(int block). So, I try to read all information from blocks and convert that to NDEF-Messages but I was not successful.
How I can convert read data to NDEF-Messages? Or extract only the payload data?
my source code is:
StringBuilder result = new StringBuilder();
for(int i=0;i<64;i+=4){
   if(util.authenticate(i, 0, key)){
      for(int j=i;j<i+4;j++){
         byte[] readData = util.read_block(i);
         if(readData != null){
            result.append(NfcUtil.toHexString(readData));
         }
      }
   }
}

I need get "hello world" text data
Answer: NDEF data format can take a number of forms depending on the NFC Tag standard used to store it.
You don't tell us how the Ndef data was encoded and stored on the tag which makes it is difficult to answer as the are many different ways it could be done.
BUT as a guess and that you have Tagged mifare then it might follow the NXP's proprietary method of storing Ndef Data on Mifare Classic Tags which is defined in the doc AN1305
Update based on new data
So that data more looks like the standard Type2 Ndef format.
The spec is available here
But basically you would read block 04 to get 03h,12h,D1h,01h
03h is the Ndef Tag of the NDEF TLV and 12h (18 in Decimal) so you need to read 18 bytes after the 12h to get the Ndef message and should then read another byte to get the FEh Terminator TLV
You have the first 2 bytes in the block 04, so you need to read another (18 - 2) / 4 = 4 blocks.
This matches the data shown.
These 18 bytes are the complete Ndef message as you wanted (You would then need to extract the Ndef Record containing your data and then parse the Ndef Record to get your text, this can be done using standard Android class) If not the NDef message structure is here and then how to decode the records are here
For decoding the Record payload, if you look at block 05 0Eh,54h,02h,65h the 54h means its a RTD_TEXT Record and 02h is 2 bytes of the language type definition which gives you "en" for english, then your message "hello world" begins.
Comment: I update my question with extra info. Like i said the data is plane text, I just need extract it from the blocks structure.
Comment: thank for your answer, you showed me the way. Please help me with this new problem: https://stackoverflow.com/questions/73953835/i-cant-read-the-same-bytes-from-nfc-cards

Get NDEF-Messages from block data


Rewiring European Chandelier

Question: I have a chandelier that was bought in Europe in early 1990s, and I would like to hang it in my house in the US on a standard 120V AC circuit. There is nothing in the box or in the manual stating that the wiring is appropriate for the US, the wires follow European coloring scheme and "250V" is prominently stamped on the inside of the ceiling canopy, so I assume that the safest option is to rewire it. Below is my plan, and I appreciate if you could point out any obvious safety or code compliance issues and answer the questions at the end.

The chandelier has 8 arms, each labelled "40W". I plan to replace the European socket in each arm with a candelabra socket. The ones I consider buying are rated up to 75W, so the max total wattage of the chandelier would be 75W * 8 = 600W (*)
Replace the black/blue wires in each arm with 18/2 SVT or SJT stranded lamp cord and connect it to the new sockets
Replace the black/blue/green-yellow wires in the rod with 18/3 SVT or SJT stranded lamp cord. Connect the ground wire of the new 18/3 lamp cord to the original grounding screw at the bottom of the rod.
Connect the hot and neutral wire in each arm to the hot and neutral wires in the rod, respectively

My questions are:

Is 18 AWG wire appropriate for this load (600W) or do I need a heavier gauge?
Is SVT or SJT wire type important here?
In the last step, I need to connect nine wires together (one from each arm + the main one). Is there a wire connector that is designed to handle 9 18 AWG wires? Could the red wire nut handle it? If there is no single connector that can handle all 9, what would be the best option to minimize pigtails, and what connectors should I use? For example, I could connect 4 wires from arms + 1 pigtail and then connect the two resulting pigtails to the main wire. Which wire connectors should I use in that case?

(*) In reality, I will probably use LED candelabra bulbs equivalent to either 25W or 40W, but I do not see any significant cost or time savings in cutting corners here in terms of max wattage, even if safety is not an issue.
Comment: What is the size (mm2) of the existing European wire in the fixture?  Does it have a TUV, CE or UL listing?
Comment: CE doesn't count as a listing mark, but yes -- what is the wire size of the existing fixture wiring?
Answer: The 18-gauge wire for the arms is fine. You could even go a bit smaller safely if you wanted. The code, Table 400.5 (A) & (B) says that the 18-guage can also handle the entire fixture, although I would like to see 16-guage for the entire fixture.
I would definitely use fixture wire, SVT & SJT would be good.
I would use a pre-insulated crimp connector. Use the smallest one that will handle all the wires.  Get and use the right tool.
Spice once only for each lead.
Comment: SVT and SJT are cordage types, not fixture wire types...
Answer: NEC 240.5(B)(2) indicates that fixture wires of either 18 or 16 AWG can be tapped to a branch protected at 20A, but that presumes they are of a type shown in Table 402.3, not "flexible cords". 400.7 authorizes use of "flexible cord" for wiring of luminaires.
Note also that Article 410 includes numerous sections regarding wiring of luminaires, including 410.52 requiring insulation suitable for the temperature and 410.90 related to wiring of screw shell lampholders.
In particular however, 410.6 requires that

All luminaires, lampholders, and retrofit kits shall be listed.

Therefore, in theory, it would be a violation of the Code to connect a retro-fitted luminaire that is not listed, unless (perhaps) the retrofit kit is listed.

Rewiring European Chandelier


How do I break rotten boulders?

Question: I have a lot of rocks around my house. Generally, I drill holes with a rotary hammer and then use wedges and feathers to split them. There are some that are rotten, however, and the wedge and feathers just blow out. They are massive, and breaking then with a jackhammer would take a long time. Is there another option? I think that if I could saw them or something, it would be easier.
Comment: What does rotten mean in this context?
Comment: I really want the answer to be something about explosives...  Obvious answer is to rent a bigger jack hammer.  Are you looking for any certain method?  Trying to use basic tools that you have already?
Comment: Crumbly. Disintegrating.
Comment: How bigger is bigger?
Answer: Rent a mini hoe or skid loader with a hammer attachment for a day. Git 'r done.
Answer: I found this video from PBS' "This Old House"
It appears that the OP tried the feather and wedge approach, however, they could try larger ones and more powerful hammer.... Basically drill holes, put the feather in, drive the wedge until it splits. The larger the boulder, the larger the feather and wedge and hammer force needed.
Comment: You may wish to describe the techniques used in the video you linked. Links go bad over time and can make this answer useless.
Comment: Tools for How to Remove a Boulder: - pointed shovel, used to dig around rock - electric rotary hammer and 1/2-inch-diameter masonry bit, used to drive screws and drill screw holes - bulb-type syringe, for blowing dust out of holes - feathers and wedges, used to split the rock - 3-pound sledgehammer, for pounding in the wedges - long-handled pry bar, used to break off split pieces of rock - diesel-powered air compressor and rotary rock hammer, for drilling and splitting large rocks

How do I break rotten boulders?


Reduce spacing between input text and bottom border

Question: I'd like to reduce the space between the bottom border of the input text field and the text so that they're closer together.

#a {
    padding: 1px 3px;
    background: transparent;
    border: 0;
    outline: 0;
    border-bottom: 0.8px solid #D3D3D3;
    width: 300px;
}

<input type="text" id="a" style="font-family: open-sans, sans-serif; font-style: normal; font-weight: 300; color: black; font-size: 16px; text-align: left;">

Answer: Give #a a height of 10px (less than size of the font)
(Edit - 13 px would be best, consider visibility of characters like small case q,p,y.. etc)
Fiddle - https://jsfiddle.net/xpvt214o/735385/
#a
{
  padding: 1px 3px;
  background: transparent;
  border: 0;
  outline: 0;
  border-bottom: 2px solid #D3D3D3;
  width: 300px;
  height: 10px;
}

Comment: That seems to do the job. Thanks!
Comment: Even 13px is a bit too little to be clear in usability. I would also suggest using `em` units so that the font size can grow and the height will scale with it.
Answer: If you change your padding to:
padding: 1px 3px 0px;
It'll save you a pixel of space at least. The first value is the top and bottom border by default, and the 2nd is right and left. A third value when specified refers to the bottom specifically, and a 4th refers to left specifically.
Alternatively, you could use a 1-pixel image with a repeat as a background instead of a border and position it 1px from the bottom so save another pixel or two, but I think sticking with a simple border is probably cleaner.
If you want to go the image route, here's how to do it:
create a 1px x 1px image in the color you want, and do something like this:
border-bottom: 0px;
background-image: url('insert-imageURL');
background-repeat: repeat-x;
background-position-y: -2px;

The repeat will turn it into a line, and the position will bump it up from the bottom edge of your field by however many pixels you like. Put in your image link inside the URL field.
You'll have full control over exactly where the line goes in relation to the field.
Comment: Thanks for the idea but ideally I'd try and get a few more pixels shaved off as there's a rather significant gap between the border and text on my website (it doesn't seem to be too much of an issue when your run the code on here).


Cannot load Xdebug, as PHP was built with API NTS debug

Question: I installed php70 and php70-xdebug using brew.
brew install php70
brew install php70-xdebug

php -v returns this error:

Cannot load Xdebug - it was built with configuration API320151012,NTS,
  whereas running engine is API320151012,NTS,debug

I can't figure out how to pass --disable-debug to the compiler, brew uses preconfigured formula (https://github.com/Homebrew/homebrew-php), and doesn't allow to set this option.
The problem is: xdebug formula has --disable-debug, and php70 formula has an option --with-debug, but even if you don't use this argument, it appends --enable-debug to the configure command.
Answer: I found a workaround, it isn't perfect to do that, but it works!

Edit the Formula with brew edit php70-xdebug and add --enable-debug to the configure command :
system "./configure", "--prefix=#{prefix}",
                  phpconfig,
                  "--disable-dependency-tracking",
                  "--enable-xdebug",
                  "--enable-debug"

Recompile the library
brew reinstall php70-xdebug --build-from-source

Same thing works with php70-opcache as well.


solving $3\sin(x)^3 - 5\sin(x)\cos(x) + 2\cos(x)^2 = 0$

Question: I need help solving this equation:
$$3\sin(x)^3   -   5\sin(x)\cos(x) +   2\cos(x)^2 =  0$$
I didn't find any place with this exact question.
Comment: "I didn't find any place with this exact question" That's not how problems are solved in general.
Comment: Well, I tried to solve this alone for a long time
Comment: Was the first term $3\sin(x)^3$, or $3\sin(x)^2$?
Comment: I think there might be a mistake in the book.... but lets say it is ^3 (:
Answer: use that $$\sin(x)=2\,{\frac {\tan \left( x/2 \right) }{1+ \left( \tan \left( x/2
 \right)  \right) ^{2}}}
$$
 and
 $$\cos(x)={\frac {1- \left( \tan \left( x/2 \right)  \right) ^{2}}{1+ \left(
\tan \left( x/2 \right)  \right) ^{2}}}$$
Comment: Thank you very much ! However, I still can't get it right ):
Answer: it looks like $$3\sin^3 t -5 \sin t \cos t + 2\cos^2 t = 0 \tag 1$$ has four solutions in the closed interval $[0, 2\pi].$  one way to see this is to see $(1)$ as a quadratic equation in $x$ with the change of variables $x \cos t, y = \sin t.$ we now have $$2x^2 - 5y x + 3y^3 = 0 \text{ and } x^2 + y^2 = 1. $$  draw the graphs of $$x = \frac{5y \pm \sqrt{25y^2 - 24y^3 }} 4 \text{ and } x = \pm \sqrt{1-y^2}.$$
Comment: Thank you very much, helped a lot.
Comment: @tanto30, you are welcome.


ListFragments infinite scroll don't work after switching tabs to and fro

Question: I have a application which has a main activity hosting 2 list fragments controlled by tabs (courtesy of actionbarsherlock).
Both fragments are more less same in code and load data from server dynamically. One shows latest content second shows all the content in database with endless scrolling implemented.
All works well if if use only in the following order:
latestFragment -> allFragment
But when i comeback from latestFragment to allFragment
allFragment -> latestFragment
Endless scroll stops working!!
I am new to android development, having studied some bits and pieces did manage to put it all together but its stuck here. I simply cant get around. then no matter what i do scroll wont work until i close app and start again.
MainActivity.java

                public class MainActivity extends SlidingFragmentActivity implements OnQueryTextListener
                {
                protected static DisplayImageOptions options;
                protected static ImageLoader imageLoader;
                ArrayList latest;
                ArrayList generes;
            ActionBar.Tab latestTab;
            ActionBar.Tab AllTab;

            LatestNewsFragment latestNews;
            AllNewsFragment allNews;

            MenuItem search;
            SearchView searchView;
            ProgressBar pBar;
            SharedPreferences settings;

            protected CategoryListFragment mFrag;

            @Override
            public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.setContentView(R.layout.activity_main);

            pBar = (ProgressBar) this.findViewById(R.id.pBar);
            pBar.setVisibility(View.GONE);

            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.getApplicationContext())
            .build();

            imageLoader = ImageLoader.getInstance();
            imageLoader.init(config);

            options = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.poster)
            .delayBeforeLoading(2000)
            .showImageForEmptyUri(R.drawable.poster)
            .showImageOnFail(R.drawable.poster)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .imageScaleType(ImageScaleType.NONE)
            .cacheOnDisc()
            .cacheInMemory()
            .build();

            Bundle extras = getIntent().getExtras();
            latest = extras.getParcelableArrayList("latest");
            generes = extras.getParcelableArrayList("generes");
            disclaimer = extras.getString("disclaimer");

            /* Tabs */
            getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

            /* Latest list fragment */
            latestNews = new LatestNewsFragment();
            latestNews.setImagLoader(imageLoader);
            latestNews.setImageDisplayOptions(options);
            latestNews.setData(latest);
            latestTab = getSupportActionBar().newTab().setText("Latest");
            latestTab.setTabListener(new TabListener(latestNews));
            getSupportActionBar().addTab(latestTab);

            /* All news list fragment */
            allNews = new AllNewsFragment();
            allNews.setImagLoader(imageLoader);
            allNews.setImageDisplayOptions(options);
            AllTab = getSupportActionBar().newTab().setText("Browse All");
            AllTab.setTabListener(new TabListener(allNews));
            getSupportActionBar().addTab(AllTab);

            /* Sliding menu */

            // set the Behind View
            setBehindContentView(R.layout.menu_frame);
            if (savedInstanceState == null) {
            FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
            mFrag = new CategoryListFragment();
            mFrag.setData(generes);
            t.replace(R.id.menu_frame, mFrag);
            t.commit();
            } else {
            mFrag = (CategoryListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
            }

            // customize the SlidingMenu
            SlidingMenu sm = getSlidingMenu();
            sm.setShadowWidthRes(R.dimen.shadow_width);
            sm.setShadowDrawable(R.drawable.shadow);
            sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
            sm.setFadeDegree(0.35f);
            sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);

            settings = getSharedPreferences("com.newsspace.mobile.android", Context.MODE_PRIVATE);
            boolean hasAcceptedPolicy = settings.getBoolean("disclaimeraccept", false);

            if(!hasAcceptedPolicy)
            showDisclaimer(this, disclaimer);
            }

            void showDisclaimer(final Activity context, String message)
            {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

            // Setting Dialog Title
            alertDialog.setTitle(getText(R.string.disclaimer));

            // Setting Dialog Message
            alertDialog.setMessage(message);

            // Setting Icon to Dialog
            //alertDialog.setIcon(R.drawable.delete);

            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton(getText(R.string.disclaimer_agree), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            Editor editor = settings.edit();
            editor.putBoolean("disclaimeraccept", true);
            editor.commit();
            }
            });

            // Setting Negative "NO" Button
            alertDialog.setNegativeButton(getText(R.string.disclaimer_disagree), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            Editor editor = settings.edit();
            editor.putBoolean("disclaimeraccept", false);
            editor.commit();
            context.finish();
            }
            });

            // Showing Alert Message
            alertDialog.show();
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
            getSupportMenuInflater().inflate(R.menu.action_menu, menu);
            search = menu.findItem(R.id.search);
            SearchView searchView = (SearchView) search.getActionView();
            searchView.setOnQueryTextListener(this);
            SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            searchView.setSearchableInfo(info);

            return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
            toggle();
            return true;

            case R.id.refresh:
            refreshCurrentFragment();
            return true;
            }

            return super.onOptionsItemSelected(item);
            }

            @Override
            public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
            {
            // NO OP
            }

            void refreshCurrentFragment()
            {

            }

            @Override
            public void hideProgressbar() {
            // TODO Auto-generated method stub
            pBar.setVisibility(View.GONE);
            }

            @Override
            public void showProgressbar() {
            // TODO Auto-generated method stub
            pBar.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
            // TODO Auto-generated method stub
            search.collapseActionView();
            return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
            // TODO Auto-generated method stub
            return false;
            }

            @Override
            protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            handleIntent(intent);
            }

            private void handleIntent(Intent intent){
            if(Intent.ACTION_SEARCH.equals(intent.getAction())){
            String searchQuery = intent.getStringExtra(SearchManager.QUERY);
            }
            }

            }

TabListener.java

public class TabListener implements ActionBar.TabListener {
Fragment fragment;

public TabListener(Fragment fragment) {
  this.fragment = fragment;
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub
    ft.replace(R.id.fragment_container, fragment);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub
    ft.remove(fragment);
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
    // TODO Auto-generated method stub
}

}

AllNewsFragment.java

public class AllNewsFragment extends ListFragment implements OnRefreshListener, OnConnectivityHandler, OnScrollListener {

ArrayList<News> news;
OnNewsSelectedListener listener;
DisplayImageOptions options;
ImageLoader imageLoader;
LazyAdapter adapter;

NewsListQueryData data;
boolean canLoadNewss = true;

int page = 1;
int total = 0;
int category = 0;
String searchterm = "";
View rootview;

int mVisibleThreshold = 5;
int mPreviousTotal = 0;
boolean mLoading = true;
boolean mLastPage = false;

ConnectionManager connectionManager;
boolean isConnected;
boolean failedCall = false;
boolean activityReady = false;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.list, null);
    Log.d("APP", "createView");
    return rootview;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    Log.d("APP", "onCreate");
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

public void setImageDisplayOptions(DisplayImageOptions options){
    this.options = options;
}

public void setImagLoader(ImageLoader imageLoader){
    this.imageLoader = imageLoader;
}

public void setData(ArrayList<News> news){
    this.news = news;
}

public ArrayList<News> getData(){
    return this.news;
}

void init()
{
    if(news == null)
    this.news = new ArrayList<News>();

    adapter = new LazyAdapter(news, getActivity(), options, imageLoader);
    setListAdapter(adapter);

    ListView list = (ListView) this.rootview;
    list.setOnScrollListener(this);

    this.category = 0;
    this.page = 1;
    this.searchterm = "";

    this.total = 0;
    this.mPreviousTotal = 0;
    this.mLoading = true;
    this.mLastPage = false;

    connectionManager = new ConnectionManager(this.getActivity(), this);
    isConnected = connectionManager.isConnectedToInternet();
    connectionManager.regsiterForNetworkChanges();

    loadMoreNewss(category, page, searchterm);
}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if(!activityReady) init();
    activityReady = true;
}

@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
    News selectedNews =  (News) getListAdapter().getItem(position);
    if (selectedNews != null)
    showNewsDetails(selectedNews);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
    listener = (OnNewsSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }

}

void showNewsDetails(News news)
{
    listener.newsSelected(news);
}

@Override
public void result(Object args) {
    listener.hideProgressbar();

    // TODO Auto-generated method stub
    if(args instanceof NewsListQueryData){
    data = (NewsListQueryData) args;
    page = data.page;
    category = data.category;
    searchterm = data.searchterm;
    total = data.total;
    appendData(data.news);
    canLoadNewss = true;
    }
}

@Override
public void fault(Object args) {
    // TODO Auto-generated method stub
    listener.hideProgressbar();
    canLoadNewss = true;
    Toast.makeText(this.getActivity(), R.string.loading_reported_failed, Toast.LENGTH_LONG).show();
}

@Override
public void started(Object args) {
    // TODO Auto-generated method stub
    listener.showProgressbar();
}

@SuppressWarnings("unchecked")
void loadMoreNewss(int category, int page, String searchterm)
{
    if(canLoadNewss){
        if(isConnected){
        new LoadNewsTask(this).execute(Constants.SEARCH_SCRIPT, category, searchterm, page);
        canLoadNewss = false;
        failedCall = false;
        }
        else{
        failedCall = true;
        connectionManager.showProgressDialog();
        }
    }
}

void appendData(ArrayList<News> news)
{
    for(int i=0;i<news.size();i++)
    adapter.add(news.get(i));
    adapter.notifyDataSetChanged();
}

@Override
public void onScroll(AbsListView view, int firstVisible, int visibleCount, int totalCount) {
    if (mLoading) {
        if (totalCount > mPreviousTotal) {
            mLoading = false;
            mPreviousTotal = totalCount;
            page++;

            // Find your own condition in order to know when you have finished displaying all items
            if (page + 1 > total) {
            mLastPage = true;
            }
        }
    }
    if (!mLastPage && !mLoading && (totalCount - visibleCount) <= (firstVisible + mVisibleThreshold)) {
        loadMoreNewss(category, page, searchterm);
        mLoading = true;
    }
}

@Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
    // TODO Auto-generated method stub

}

@Override
public void connectToInternet() {
    // TODO Auto-generated method stub

}

@Override
public void doNotConnectToInternet() {
    // TODO Auto-generated method stub

}

@Override
public void connectionStatusChanged() {
    /*
    // TODO Auto-generated method stub
    isConnected = connectionManager.isConnectedToInternet();
    if(isConnected){
    connectionManager.hideProgressDialog();
    if(failedCall) loadMoreNewss(category, page, searchterm);
    }else{
    connectionManager.showProgressDialog();
    }
    */
}

void emptyAdapter()
{
    adapter.clear();
    adapter.notifyDataSetChanged();
}

@Override
public void refresh()
{
    this.page = 1;
    this.total = 0;
    this.mPreviousTotal = 0;
    this.mLoading = true;
    this.mLastPage = false;

    if(adapter != null)
    emptyAdapter();

    loadMoreNewss(category, page, searchterm);
}

}
Furthermore latestNews Fragment is exactly the same as AllNewsFragment except for the endless scroll. I can post here is needed. but i thing this much is good. Please help me find a answer to this problem.
Answer: Hopefully you got your solution by now. But anyway, I got it working by moving following lines from init to outside if(!activityReady) block in  onActivityCreated
ListView list = (ListView) this.rootview;
list.setOnScrollListener(this);


Avoid looping MySQL query with constrained INSERT

Question: I understand why we should not loop MySQL queries and I am trying to avoid it. I have an array $names which contains a list of keywords to insert into someTable, with a UNIQUE constraint on the MySQL field name:
mysql> select * from someTable where name='stress';
+-----+--------+
| id  | name   |
+-----+--------+
| 143 | stress |
+-----+--------+
1 row in set (0.00 sec)

mysql> insert into someTable (name) values ('stress');
ERROR 1062 (23000): Duplicate entry 'stress' for key 'name'
mysql>

I would prefer a query of the following type to avoid a loop:
$result = mysql_query("insert into someTable (name) values ('firstName'), ('secondName'), ('thirdName')");

However, if any of the names already exist then none of the values get inserted. Furthermore, the value of $result will be FALSE. How can I construct a single query to insert the values, which will not fail if any of them exist, and which will return TRUE if any of them were inserted?
I know that I could write a stored procedure for this, but that would just move the loop from PHP to MySQL. Other than bandwidth (not critical as this is on localhost) that doesn't seem to save anything.
Answer: INSERT IGNORE INTO someTable (name) values ('firstName'), ('secondName'), ('thirdName')

If there is a duplicate, it will ignore and continue.
Comment: Thanks, but that will return `TRUE` even if _all_ the names are dupes. I need something that will insert as much as it can, but will return `FALSE` only if all the names were dupes.
Comment: You've gotten me on the right track at least. I might be able to use `mysql_affected_rows` to see if any inserts were made. I'm trying that now.
Comment: Ya, that could work, do a count of how many values you are updating, just compare against.  Did loops beat you as a child?
Comment: Beat me as a child? No, that was my father. But I have seen loops beat other adult devs. In any case, mysql_affected_rows() did what I need after you got me on the right track. Thanks.
Comment: Sheesh, keep it light, glad I could help ;)
Answer: use ignore.
example:
insert ignore into someTable (name)...
Comment: Haha :) There can be a badge - "fast sender" :)
Comment: Thanks Oleg, for trying. I'll be following you around SO looking for helpful posts to learn from!


JQuery datepicker not rendering a calendar image after it is added dynamically as part of a partial view

Question: I have a MVC Razor page in C# .Net Framework 3.5.
The page calls for the user to be able to add (flight) items dynamically when a "Add Fare" button is clicked.  The items are stored in a list in the overall model for the entire page.  When the button is clicked, I call some javascript that serializes the form (so I have access to the model), add a new item to the list in the model, and the item is represented in a partial which I then append to a div in the main page.
I have a problem, however, as I am making use of the JQuery datepicker, and whilst this functionally works ok (i.e. when you click into it, a calendar pops up and you can select a date), the actual calendar button is not being rendered next to my inputs?
Here is the form I am trying to add the partial view into..
    @using (Html.BeginForm("ManualFlight", "ShoppingBasket", FormMethod.Post, new {@class="manualFlightForm" }))
    {

                    Add Fare

     }

This is the javascript I am calling from the onclick:
 $.ajax({
        type: "POST",
        data: $('form.manualFlightForm').serialize(),
        url: "/ShoppingBasket/ShoppingBasketAddFare",
        cache: false,
        traditional: true
    }).done(function (responseHtml) {
        $(".ManualFlightFareContainer").append(responseHtml);

        $('.t2Datepicker').datepicker({
            minDate: '+1d',
            defaultDate: '+1d',
            changeMonth: true,
            buttonImage: '/App_Themes/Travel2/Images/calendar_icon.png',
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            maxDate: '+3y'
        });
        });

Note I am calling datepicker after I have rendered the response I receive back from my call to the controller..
This is the partial that is being added (please ignore the use of tables, I am trying to recreate something that already exists in another part of the site..
@model Travel2.WebUI.ViewModels.ShoppingBasket.ShoppingBasketManualFlightViewModel

                Passenger Type
                Departure Details
                Arrival Details
                Flight No.
                Class
                Cost
                Sale Price
                Commission
                PEX

                IATA
                Date & Time
                IATA
                Date & Time

                @Html.DropDownListFor(m => m.Fares[Model.Fares.Count - 1].PassengerType, ViewBag.PassengerTypes as IEnumerable<SelectListItem>)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].DepartureIATA)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].DepartureDate, new { Class="t2Datepicker" })
                @Html.DropDownListFor(m => m.Fares[Model.Fares.Count - 1].DepartureHour, ViewBag.Hours as IEnumerable<SelectListItem>)
                @Html.DropDownListFor(m => m.Fares[Model.Fares.Count - 1].DepartureMinute, ViewBag.Minutes as IEnumerable<SelectListItem>)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].DestinationIATA)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].DestinationDate, new { Class = "t2Datepicker" })
                @Html.DropDownListFor(m => m.Fares[Model.Fares.Count - 1].DestinationHour, ViewBag.Hours as IEnumerable<SelectListItem>)
                @Html.DropDownListFor(m => m.Fares[Model.Fares.Count - 1].DestinationMinute, ViewBag.Minutes as IEnumerable<SelectListItem>)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].FlightNumber)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].FlightClass)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].Cost)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].SalePrice)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].Commission)

                @Html.TextBoxFor(m => m.Fares[Model.Fares.Count - 1].PEX)

Just for completion, here is the method in the controller that handles adding a new instance to the model and returning back the partial view.
[HttpPost, STPAuthorize]
public ActionResult ShoppingBasketAddFare(ShoppingBasketManualFlightViewModel model)
{
    if (model.Fares == null)
    {
        model.Fares = new List<ShoppingBasketManualFlightFareViewModel>();
    }

    ViewBag.PassengerTypes = GetPassengerTypes();
    ViewBag.Hours = GetHours();
    ViewBag.Minutes = GetMinutes();
    model.Fares.Add(new ShoppingBasketManualFlightFareViewModel());
    return PartialView("ShoppingBasketAddFare", model);
}

Any ideas as to why the calendar image isn't rendering?
Thanks in advance
Answer: Your missing the showOn option.
From buttonImage docs

A URL of an image to use to display the datepicker when the showOn
  option is set to "button" or "both".

showOn docs
$('.t2Datepicker').datepicker({
            minDate: '+1d',
            defaultDate: '+1d',
            changeMonth: true,
            buttonImage: '/App_Themes/Travel2/Images/calendar_icon.png',
            changeYear: true,
            dateFormat: 'dd/mm/yy',
            maxDate: '+3y',,
            showOn:'both'
        });

Comment: Yup! Thanks! That seemed to do the trick, just need to style the button it renders within an inch of its life!


Comparing sums of fractions.

Question: Consider a number n.
Out of all the fractions arising from the scenario by reducing some x from n and adding the ratio of the removed to the current n till n becomes 1, why does the sum be maximum if x = 1.
Lets say n = 5.
Why is 1/5+1/4+1/3+1/2 +1 = 2.28 always more than, alternative examples like. (Here x is always 1)
x = 2 , 1
2/5 + 1/3 + 1 = 1.73
or x =  3 , 1
3/5 + 1/2 + 1 = 2.1
or x = 4 ,  1
4/5 + 1 =  1.8.
Inductively I can say this is true. How can I prove this ?
Comment: Your first example should be $2,1,1$ leading to $2/5 + 1/3 + 1/2 +1 = 2.23$.
Answer: Notice that in every example, a sequence of fractions from the 'maximal' series is being replaced with a single fraction. In example 1, the sum $\frac{1}{5} + \frac{1}{4}$ is being replaced by the single fraction $\frac{2}{5}$. Similarly, in example 2, the sum $\frac{1}{5} + \frac{1}{4} + \frac{1}{3}$ is replaced by $\frac{3}{5}$, and in example 3, the sum $\frac{1}{5} + \frac{1}{4} + \frac{1}{3} + \frac{1}{2} $ is replaced by $\frac{4}{5}$.
But clearly in each case, the replacement lowers the sum, because
$$\frac{2}{5} = \frac{1}{5}+\frac{1}{5}<\frac{1}{5}+\frac{1}{4} \\
\frac{3}{5} = \frac{1}{5}+\frac{1}{5}+\frac{1}{5}<\frac{1}{5}+\frac{1}{4}+\frac{1}{3} \\
\frac{4}{5} = \frac{1}{5}+\frac{1}{5}+\frac{1}{5}+\frac{1}{5}<\frac{1}{5}+\frac{1}{4}+\frac{1}{3}+\frac{1}{2}$$
This would be the case even if the reductions were out of order, e.g. 1,2,1 would lead to the series $\frac{1}{5}+\frac{2}{4}+\frac{1}{2}+1=2.2$; here the sum $\frac{1}{4}+\frac{1}{3}$ is being replaced by $\frac{2}{4}$, which will again lower the sum.

Comparing sums of fractions.


MySQL Error: This command is not supported in the prepared statement protocol yet

Question: I am getting the following error when I use START TRANSACTION and COMMIT to the start and end of my MySQL queries.
SQLSTATE[HY000]: General error: 2030 This command is not supported in the prepared statement protocol yet

SQL: START TRANSACTION

Bindings: array (
)

In Larvel, I did:
DB::query('START TRANSACTION');

I am using the PHP framework Laravel, which uses PDO to access MySQL. What should I do?
Comment: Need version numbers for PHP and MySQL
Comment: @mblaettermann You don't mark a post as solved. You choose the best answer. In this case there is no provided answer that solves the solution so the OP should make one - not edit the post
Comment: The post below that I chose solved the problem, along with an upgrade of MySQL. Why the downvote? :(
Comment: I had an old version of mysql running, thanks! Upgrading..
Comment: Please mark question as solved and edit your post with the solution!
Answer: Laravel already has a support for transaction query.
DB::transaction(function ()
{
    // query goes here.
    DB::table('foo')->insert(array('foo' => 'bar'));
});

Comment: Please also answer the question.


Keyboard ALT + SHIFT doesn't work

Question: Pressing ALT + SHIFT is registered as only ALT, and commands with ALT + SHIFT don't work. When using xkbwatch I see that ALT takes one column, SHIFT takes another, but pressed together it's only registered as ALT. Doing the same with ALT + CTRL I see two columns highlighted.
I know there are a lot of similar questions but they don't fix my issue.
I'm on Ubuntu 22.04, upgraded from Ubuntu 20.04.
Answer: I've met the same issue
This solution helps me
gsettings set org.gnome.desktop.wm.keybindings switch-input-source "['<Alt>Shift_L', 'XF86Keyboard']"
Answer: Got it working.
I've installed Tweaks via apt install gnome-tweaks and saw that under Keyboard & Mouse -> Additional Layout Options -> Switching to another layout was set differently than global. Gnome Tweaks had ALT+SHIFT whereas global was ALT+SPACE. Changing in Tweaks to ALT+SPACE resolved my issue.

Keyboard ALT + SHIFT doesn't work


What is the reward for defeating all 17 Cyberpsychos?

Question: After traversing every region in Night City and engaging in a series of difficult fights I've defeated and incapacitated all 17 Cyberpsychos. Afterwards, I was called to Regina's location and she congratulated me for vanquishing the psychos without outright killing them - and then nothing happened. The 'Psycho Killer' side gig finished but I didn't seem to get a reward, and Regina didn't mention any bonus payout.
Am I missing something? Will she contact me later to offer a payout when her research has concluded? I anticipated a reward for defeating all of the Cyberpsychos but nothing seems to have happened.
Answer: There is no in game reward beyond the eddies you make while completing these missions for Regina. There is also no follow up mission once you have completed all of them like there are with some of the missions in game. You will get between 1000 and 3000 eddies per mission you complete.
Once all of the cyber psycho sighting missions have been completed you will earn the achievement "I am the law".
Answer: Not sure if this in new to patch 1.23 (I had to wait for "Where the Bodies Hit the Floor" to be fixed), you get a couple pieces of legendary clothing: Trauma Team Armor Weave Tactical Vest and a Decadencia Verde Tactical Armor-Weave Pants. They are easy to miss, on the floor of her office in a flat case.
Comment: It's been a while since I've played Cyberpunk. To confirm, this is a quest reward - not just a loot box that happens to be near Regina?
Comment: @PausePause, To confirm, I just finished the mission. I did it without killing a single cyber psycho and I did indeed get the legendary gear upon completion.
Answer: You got handed some Eddies. It's easy to miss when that happens.
As with most missions, the cash is the only direct reward.
Comment: Do you know approximately how many Eddies I was awarded? I noticed that my wallet amount didn't seem to change, or it maybe changed very, very little. Likewise, the wikia article for Psycho Killer votes that a reward may be bugged.
Comment: Psycho Killer claims* don't know why it autocorrected to votes
Answer: If you do not kill one single cyberpsycho after finishing the 17th one it will prompt you to "wait until Ragina contacts you." Just skip 24hrs and she will call. She will tell you to meet up with her. Go to her location and ask about the situation. She will thank you and the chest with the legendary orange marker will be unlocked. You should get two legendary class clothing items from the chest. Maybe you glithed out and they fixed this later IDK.


Is there a way to specify JavaScript dependencies for git submodules?

Question: I've been working on a website which is a collection of single-page applications. I have a monorepo consisting of my applications in separate directories, and each app has it's own package.json.
In addition to this, each application contains one or more git submodules, where I place my core libraries (ex. one for the "common" lib, one for SVG, etc.). I'm overall happy with this setup. It works well with tooling, since the submodule is directly within the app directory, and makes it easy to version the code.
EDIT: An example directory structure, where "common" is the git submodule:

frontend/app1/common
frontend/app2/common

That said, the biggest flaw has been dealing with dependencies, as sometimes there are dependencies I would like to have across all applications. Since every app has its own package.json, this means that I have to manually install that dependency across all my apps, should I ever use that dependency in my common lib.
What I'm looking for is a way to split a package.json, such that I could (for example), point the app's package.json at the common lib's (hypothetical) package.json, and inherit its dependencies. I'm aware that this is not possible with package.json, but I can't help but feel this is common enough an alternative might exist.
I know Yarn workspaces provides the ability to create local packages, but this wreaks havoc with the project tooling and makes it more difficult to make quick code changes.
Are there any good workarounds that don't involve building some hacky templating system?
My stack is:

Vite
Svelte
Yarn (with workspaces)
Answer: Let's say you have these folders:
- app1
- app2
- common

And in common folder you have package.json with node-fetch package, for example.
Also, in common you have index.js with something like this:
import fetch from "node-fetch";

export const getPage = async (page) => await fetch(page);

Then in app1 you have app.js with:
import { getPage } from "../common"

const data = await getPage("http://x.com");

Now all you have to do is to run npm install inside of your common folder.
It can also be a git submodule, doesn't matter. You don't need to add node-fetch into your app1 to get this working.
You might also face another issue: too many package.jsons. For which I wrote a script based on listr that finds all of them recursively and runs npm install or npm test for all of them in parallel. It's not published yet, but I can share some snippets if you're interested.
Comment: Ah I should specify, the git submodule is WITHIN the app (ex. app1/common and app2/common). This has a couple advantages:

1) The tooling sees it as a regular subdirectory, so nothing breaks.
2) You can be on a different commit of the common lib in different apps, which makes updates safer in a single app (doesn't affect other apps).
Comment: Mm, can you add `package.json` into the `common` and run `npm install` there? You'll have to do it twice tho in your example.
Comment: Most likely, though I was really hoping to avoid this. It wouldn't play nice with my automated Heroku deployment, might cause weirdness with PNP and workspaces, and I would probably prefer to write a tool to just insert the data into JSON.
Comment: Also, I don't understand what kind of havoc would there be if you make `common` a package. And it'll probably be the best thing to do... Otherwise, you might want to check out Deno - you can import specific dependencies by URL, so you don't need pacakge.json, instead the code in `common` itself will describe what it needs, like `import "https://email@example.com/dist/lodash.js";` etc.
Comment: Thank you, I don't recall the specifics but I gave it a solid try, and ran into all sorts of issues with svelte-check not working right, the IDE being incapable of picking up TypeScript types, and more I forgot. Eventually I tried the submodule approach and honestly do like it, since during development it's right in the app directory, so it's quick to make changes without having to constantly bump version numbers.  I'll check out Deno.


What is the Mr. Grizz statue supposed to be? (Spoilers)

Question: After beating the main game, the Grizz statue in the Salmon Run lobby changes.

So what is it supposed to be? A narwal? It's definitely not a bear anymore but I can't figure out what it is.
Answer: The normal Mr. Grizz statue is a bear eating a fish. The post-game statue is a fish eating a bear, presumably meant to evoke the image of Hugefry from the final boss sequence.
Comment: Think its the antenna in the middle that really threw me off lol


What is the name of this pipe and can I replace with with a flex hose?

Question: I am installing a new kitchen faucet and have this odd copper hard piping coming out from my water supply line.
My goal is to remove it and then add this (which comes with the faucet onto the water line, but the right size):

https://www.homedepot.com/p/BrassCraft-3-8-in-Compression-x-1-2-in-FIP-x-20-in-Braided-Polymer-Faucet-Connector-B1-20A-F/100459572
My question is what is the name of this hard copper pipe? Why would they use this rather than a flex cable (this home was built about 20 years ago if that changes it)? Am I doing something wrong by removing it and trying to replace it with a new cable?
Comment: It is called copper water supply tubing that usually came with the older faucet.
Comment: If you're in a high rise, there may be fire code rules that prohibit braided connectors.  I know this to be the case in Toronto. -- It's got to be copper all the way.
Comment: You'll have fun trying to fit a new *cable*..!
Comment: Wouldn't you have to install new shut-off valves to attach the flexible supply lines? Or are there flexible lines with terminations that would fit the body of a compression fitting?
Answer: Actually, that's soft copper, not hard copper (which can't be easily bent.) It has a thicker wall than hard copper pipe, and is annealed. Normally supplied in a coil and bent to fit.
"Soft copper line (or pipe, or tubing) with compression fittings" is about as precise a name as you'll get.
It's simple and reliable if installed correctly, but if you don't want to use it or it won't fit your new faucet, you can remove it. If it will fit your new faucet it will probably outlast the polymer one you'd prefer to use.
Comment: though depending on how old the copper is it might have hardened over time and you need to re-anneal it if you want to work with it
Comment: How would you re-anneal it?
Comment: The surface corrosion on the outside of the old soft copper lines does not look good but AFIK it does not affect its performance.
Answer: That looks like 3/8" copper tubing and it was a standard way to install the faucets. Many faucets would come with copper tubing and a fitting with a compression sleeve and nut. The shutoff valve would also have a compression sleeve and nut so all that was needed to hook up the faucet was a piece of copper tubing which every plumber carried on his truck. This was the best connection available.  Times changed and the copper tubing was replaced with PVC tubing and then came the flexible hose. The faucet designers and manufacturer modified their faucets to accommodate these new, user friendly installation procedures.
You can replace it but I have had to replace some of those hoses because they failed in service and ruptured.
Comment: OTOH, I've had braided supply hoses under my bathroom sink and to my toilet for significantly _more_ than 5 years and haven't had a hit of trouble, @TooTea.
Comment: @TooTea that seems a little exaggerated to me. Do you have any references for this claim? I would agree that braided hoses would seem likely to fail before a copper pipe, but I have never heard of braided hoses regularly failing in only 5 years.
Comment: Braided hoses are only good for maybe 5 years (even less if mishandled: twisted or subjected to some cleaning agents). Really, their only advantage is low cost and trivial installation (thus lower installation cost). Copper or stainless tubing is still the way to go if you care about reliability and don't want to replace the hoses regularly.
Comment: @FreeMan Sure, I don't think they are going to fail right after passing the 5 year mark. Most will likely be good for quarter a century, but the risk of the hose bursting definitely increases with its age. It only takes one burst hose to flood half of your house and deal $$$ in damage, so 5 years is IMHO just a very conservative estimate of the potential safe lifespan.
Comment: @TooTea I'm guessing that 5 years is for legal/insurance CYA.  Copper will not handle twisting, mishandling well either an there are many ways they can corrode (see OP's pic.)  My experience with a copper supply line for a refrigerator ice-maker tells me it's an inferior choice for that purpose, given that there's no way to move the fridge without putting stress on the line and it's connections and no way to access it without moving the fridge.  I've had many braided connections installed well over 10 years without issue.
Comment: @PhilippNagel I don't have any real stats on this, but googling "flexible water hose lifespan" gives me lots of results that seem to use "5 years" as the magic value.
Comment: @TooTea are any of those sites claiming 5 years manufacturer sites that have a vested interest in selling hoses? Serious question - I was recently researching hard drive temperature issues and almost everything I came across stating that temps above 40°C were bad were from companies selling cooling solutions. I had to look hard to find independent, impartial data (which turned out to be somewhat inconclusive).
Comment: @ All, yes the 5 year recommendation is simply to line up with the warranty. They recommend replacing them every 5 years because that's how long they'll warranty them for, and of course replacing them immediately is the best way to maximize profit without shortchanging your reputation on the warranty. However, I would consider replacing them once you hit the 10 year mark, regardless.
Comment: If the hose never moves (and it's likely you aren't moving the ones behind your toilet or bathroom sink very often), it's likely to last longer.  If, say, it's attached to your kitchen sink sprayer nozzle, and you move and flex that thing all the time in regular use, it's more likely to need replacement on a regular basis.
Answer: That copper tubing is called 1/4" ID soft copper by plumbers and 3/8" OD soft copper by HVAC people. Both identifiers are the same, It just depends on who is using it. It was used by plumbers until those flexible hoses became available. The copper tubing will last a lifetime but the flex will not. In some areas you can only use the soft copper tubing due to the building code that is in force. This soft copper hardens with age and will also harden when worked (bent). I prefer the copper to the flex hoses since it doesn't wear out or break as the flex stuff does. Hope this helps.
Comment: @RonJohn The inside of the hose is rubber, which can dry out and crack. The metal can also rust (even stainless) due to exposure to water treated with chemicals over time, and wear down in kink/twist spots.
Comment: How does the braided polymer hose wear out if not exposed to light, friction, chemicals other than water, etc?


How do you complete the Golden Egg level with all the sounds?

Question: One of the first Golden Egg levels you unlock is a level that has buttons with various birds, pigs and items on them.  When you press the buttons, the appropriate sound effect from the game is played.
Generating the sound effects is fun, but is there something you can do to complete this level?
Answer: As usual Angry Bird's Nest has a guide

Golden Egg #4 is unlocked when you obtain 3 stars on all levels of Poached Eggs. The Angry Birds Soundboard is the first of the puzzle levels. Here's what you need to do to unlock the star. Press the group of birds, slingshot, TNT, any top bird, and finally any bottom pig.

There's also two similar levels you could be referring to:

 Golden Egg #12 is unlocked when you obtain 3 stars on all levels of Danger Above. The second soundboard puzzle level is all about the birds and their beautiful harmonies. To get the star press blue bird, red bird, black bird (with eyes closed), blue bird, then finally the green bird.
 Golden Egg #17 is unlocked when you obtain 3 stars on all levels of The Big Setup. To get the star first fill in all the pigs then tap Big Brother so he opens his eyes. Now drag him to all the way to the right.

No. 17 was originally broken on the Android version, I believe, but doing the above has worked for a while now.
Comment: Thanks - it was egg #4 that I was referring to.  One of my kids managed to get the star while I was not watching, and could not recreate what they had done.


function gets stuck / freezes in the return statement

Question: I have a function which is supposed to return an object of arraylists but for some reason it gets stuck in the return statement. Everything before the return statement is working. I had an error where the ArrayLists only contained a single value which makes the function work, but of course returns the wrong data.
package com.burninglobster.TP;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;

public class Chart2Activity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Object graphdata[] = graphsetup();
            Log.d("This message is NOT shown", "");

    List<Double> distances = (List<Double>) graphdata[0];
    List<Double> accall = (List<Double>) graphdata[1];
    List<Double> accdir = (List<Double>) graphdata[2];
    List<Double> accdist = (List<Double>) graphdata[3];
    List<Double> meandir = (List<Double>) graphdata[4];
    List<Double> meandist = (List<Double>) graphdata[5];
    linegraph lgraph = new linegraph();

    setContentView(R.layout.splot);

    LinearLayout layout1 = (LinearLayout) findViewById(R.id.splot2);
    layout1.addView(lgraph.getView1(this, distances, accall));

    LinearLayout layout2 = (LinearLayout) findViewById(R.id.splot3);
    layout2.addView(lgraph.getView2(this, distances, accdir, meandir));

    LinearLayout layout3 = (LinearLayout) findViewById(R.id.splot4);
    layout3.addView(lgraph.getView2(this, distances, accdist, meandist));
}

public Object[] graphsetup() {

    SharedPreferences rprefs;
    rprefs = getSharedPreferences("com.burninglobster.TP.tprefs",
            Context.MODE_WORLD_READABLE);
    double setdist = rprefs.getFloat("setdist", 0);

    String[] sourcesarray = rprefs.getString("sourcesarray", "Standarddef")
            .split(",");
    String setdisc = sourcesarray[rprefs.getInt("spindiscpos", 0)];
    DBHelper dbHelper = new DBHelper(Chart2Activity.this);
    SQLiteDatabase db;
    db = dbHelper.getReadableDatabase();
    String graphquery = "SELECT " + DBHelper.SHOOTER + "," + DBHelper.WDIR
            + "," + DBHelper.WSTR + "," + DBHelper.SMOD + ","
            + DBHelper.DIST + "," + DBHelper.R_DIST + ","
            + DBHelper.OS_DIST + " FROM " + DBHelper.TABLE + " WHERE "
            + DBHelper.SHOOTER + "='" + setdisc + "'" + " ORDER BY "
            + DBHelper.DIST;
    Cursor graphcursor = db.rawQuery(graphquery, null);
    int rows = graphcursor.getCount();

    int ishooter = graphcursor.getColumnIndex(DBHelper.SHOOTER);
    int iwdir = graphcursor.getColumnIndex(DBHelper.WDIR);
    int iwstr = graphcursor.getColumnIndex(DBHelper.WSTR);
    int ismod = graphcursor.getColumnIndex(DBHelper.SMOD);
    int idist = graphcursor.getColumnIndex(DBHelper.DIST);
    int irdist = graphcursor.getColumnIndex(DBHelper.R_DIST);
    int iosdist = graphcursor.getColumnIndex(DBHelper.OS_DIST);

    List<Double> accall = new ArrayList<Double>();
    List<Double> accdir = new ArrayList<Double>();
    List<Double> meandir = new ArrayList<Double>();
    List<Double> accdist = new ArrayList<Double>();
    List<Double> meandist = new ArrayList<Double>();
    List<Double> accdirtemp = new ArrayList<Double>();
    List<Double> accdisttemp = new ArrayList<Double>();
    List<Double> distances = new ArrayList<Double>();

    double dalla = 0;
    double ddira = 0;
    double ddista = 0;
    double ddirm = 0;
    double ddistm = 0;
    double currentdist = 0;

    graphcursor.moveToFirst();
    if (rows > 0) {
        currentdist = graphcursor.getDouble(idist);
    }

    for (int i = 0; i < rows; i++) {
                    // REMOVED ERROR CAUSING SINGLE VALUE IN ARRAYLISTS:
                    // currentdist=graphcursor.getDouble(idist);
        if (graphcursor.getDouble(idist) < (currentdist + 5)) {

            accdirtemp.add(graphcursor.getDouble(irdist));
            accdisttemp.add(graphcursor.getDouble(iosdist));

        } else {

            for (int u = 0; u < accdirtemp.size(); u++) {

                ddira += Math.pow(accdirtemp.get(u), 2);
                ddista += Math.pow(accdisttemp.get(u), 2);
                dalla += Math.pow(accdirtemp.get(u), 2)
                        + Math.pow(accdisttemp.get(u), 2);
                ddirm += accdirtemp.get(u);
                ddistm += accdisttemp.get(u);

            }

            accall.add(Math.sqrt(dalla / accdirtemp.size()));
                    Double.toString(Math.sqrt(dalla / accdirtemp.size())));
            accdir.add(Math.sqrt(ddira / accdirtemp.size()));
            accdist.add(Math.sqrt(ddista / accdirtemp.size()));
            meandir.add(ddirm / accdirtemp.size());
            meandist.add(ddistm / accdirtemp.size());
            distances.add(currentdist);
            dalla = 0;
            ddira = 0;
            ddirm = 0;
            ddista = 0;
            ddistm = 0;

            currentdist = graphcursor.getDouble(idist) + 5;
            accdirtemp.clear();
            accdisttemp.clear();
            accdirtemp.add(graphcursor.getDouble(irdist));
            accdisttemp.add(graphcursor.getDouble(iosdist));

        }

        graphcursor.moveToNext();
    }

    for (int u = 0; u < accdirtemp.size(); u++) {

        ddira += Math.pow(accdirtemp.get(u), 2);
        ddista += Math.pow(accdisttemp.get(u), 2);
        dalla += Math.pow(accdirtemp.get(u), 2)
                + Math.pow(accdisttemp.get(u), 2);
        ddirm += accdirtemp.get(u);
        ddistm += accdisttemp.get(u);

    }

    accall.add(Math.sqrt(dalla / accdirtemp.size()));
    accdir.add(Math.sqrt(ddira / accdirtemp.size()));
    accdist.add(Math.sqrt(ddista / accdirtemp.size()));
    meandir.add(ddirm / accdirtemp.size());
    meandist.add(ddistm / accdirtemp.size());
    distances.add(currentdist);

    db.close();
    dbHelper.close();

            Log.d("This message", " is shown");
    return new Object[] { distances, accall, accdir, accdist, meandir,
            meandist };

}

}

I have a similar function that works just fine and I can't see the difference:
package com.burninglobster.TP;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;

public class ChartActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    Object plotdata[] = plotsetup();
            Log.d("This message", " is also shown");

    List<Double> rd1 = (List<Double>) plotdata[0];
    List<Double> osd1 = (List<Double>) plotdata[1];
    List<Double> rd2 = (List<Double>) plotdata[2];
    List<Double> osd2 = (List<Double>) plotdata[3];
    List<Double> rd3 = (List<Double>) plotdata[4];
    List<Double> osd3 = (List<Double>) plotdata[5];
    scatterplot plot = new scatterplot();
    setContentView(R.layout.tplot);
    LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
    layout.addView(plot.getView(this, rd1, osd1, rd2, osd2, rd3, osd3));
}

public Object[] plotsetup() {

    SharedPreferences rprefs;
    rprefs = getSharedPreferences("com.burninglobster.TP.tprefs",
            Context.MODE_WORLD_READABLE);

    double setdist = rprefs.getFloat("setdist", 0);
    String[] sourcesarray = rprefs.getString("sourcesarray", "Standarddef")
            .split(",");
    String setdisc = sourcesarray[rprefs.getInt("spindiscpos", 0)];

    DBHelper dbHelper = new DBHelper(ChartActivity.this);
    SQLiteDatabase db;
    db = dbHelper.getReadableDatabase();

    String plotquery = "SELECT " + DBHelper.SHOOTER + "," + DBHelper.WDIR
            + "," + DBHelper.WSTR + "," + DBHelper.SMOD + ","
            + DBHelper.DIST + "," + DBHelper.R_DIST + ","
            + DBHelper.OS_DIST + " FROM " + DBHelper.TABLE;
    Cursor plotcursor = db.rawQuery(plotquery, null);
    int ishooter = plotcursor.getColumnIndex(DBHelper.SHOOTER);
    int iwdir = plotcursor.getColumnIndex(DBHelper.WDIR);
    int iwstr = plotcursor.getColumnIndex(DBHelper.WSTR);
    int ismod = plotcursor.getColumnIndex(DBHelper.SMOD);
    int idist = plotcursor.getColumnIndex(DBHelper.DIST);
    int irdist = plotcursor.getColumnIndex(DBHelper.R_DIST);
    int iosdist = plotcursor.getColumnIndex(DBHelper.OS_DIST);

    int rows = plotcursor.getCount();

    List<Double> rd1 = new ArrayList<Double>();
    List<Double> osd1 = new ArrayList<Double>();
    List<Double> rd2 = new ArrayList<Double>();
    List<Double> osd2 = new ArrayList<Double>();
    List<Double> rd3 = new ArrayList<Double>();
    List<Double> osd3 = new ArrayList<Double>();

    plotcursor.moveToFirst();
    int disccount = 0;
    int array1 = 0;
    int array2 = 0;
    int array3 = 0;
    double cursordist;

    for (int i = 0; i < rows; i++) {
        if (plotcursor.getString(0).equals(setdisc)) {
            cursordist = plotcursor.getDouble(idist);
            if (cursordist > (setdist - 5) && cursordist < (setdist + 5)) {
                rd1.add(plotcursor.getDouble(irdist));
                osd1.add(plotcursor.getDouble(iosdist));
                array1++;
            } else if (cursordist > (setdist)
                    && cursordist < (setdist + 10)) {
                rd2.add(plotcursor.getDouble(irdist));
                osd2.add(plotcursor.getDouble(iosdist));
                array2++;
            } else if (cursordist > (setdist - 10)
                    && cursordist < (setdist)) {
                rd3.add(plotcursor.getDouble(irdist));
                osd3.add(plotcursor.getDouble(iosdist));
                array3++;
            }
            disccount++;
        }
        plotcursor.moveToNext();
    }
    db.close();
    dbHelper.close();

            Log.d("This message", " is shown");
    return new Object[] { rd1, osd1, rd2, osd2, rd3, osd3 };
}
}

I added a 'Log.d' just before the return statement and then another just after the function call in the activity and only the first one is shown. It freezes for ½-1 minute and then shows the dialogue to wait or kill. I don't know how to get more info on the problem. Suggestions?
Comment: I just realised, that I forgot to close the db and dbHelper, but the problem persists.
Answer: Don't know what the problem is, and you will have to explain "stuck in the return statement".  Code does not simply get "stuck".
But you will help yourself a lot of you break the problem up.
For example, if you created a class and handled instances of the class rather than untyped arrays of objects, your code would be much easier to write, much easier to debug and much easier to maintain.  Doing so will also enable the compiler to catch a lot of errors before you need to ask for help :)
Whenever you are tempted to use 'Object', you should stop and question yourself.  Of course, there are times when Object is useful and times when you have no choice but they are exceptional and should only be done for good reason - not because you haven't taken the time to think of a correct solution.
You should also choose better names for your variables and use proper Java naming conventions.  Here, I've named the object Thing because your code does not give proper clues as to what dalla, ddira, ddista etc are and how the relate to each other, either in comments or code (which is a bad thing - this code might only ever be seen by you but when you come back in a year, you will wish that you'd done these things).
For example:
class Thing{

    double dalla = 0;
    double ddira = 0;
    double ddista = 0;
    double ddirm = 0;
    double ddistm = 0;
    double currentdist = 0;

}

Then, in your loops or methods or whatever,
ArrayList<Thing> things = new ArrayList<Thing>();

...

Thing thing = new Thing();
for (int u = 0; u < accdirtemp.size(); u++) {

    thing.ddira += Math.pow(accdirtemp.get(u), 2);
    thing.ddista += Math.pow(accdisttemp.get(u), 2);
    thing.dalla += Math.pow(accdirtemp.get(u), 2)
            + Math.pow(accdisttemp.get(u), 2);
    thing.ddirm += accdirtemp.get(u);
    thing.ddistm += accdisttemp.get(u);
}

things.add(thing);

...

And so on.  Take the time now to refactor your code before it becomes even more of a nightmare to read.
Comment: Very good advise. I know it is important and I have actually improved on my coding sanitation, but I was hoping to smooth out this "bump" and then do a bit of cleaning.

I added a 'Log.d' just before the return statement and then another just after the function call in the activity and only the first one is shown. It freezes for ½-1 minute and then shows the dialogue to wait or kill. I don't know how to get more info on the problem. Suggestions?
Comment: Why smooth out the bump if you plan to refactor it?  Sounds like double work to me.  It won't take you long and I promise you will feel more satisfied afterwards.  Your coding going forward will then speed up considerably.
Comment: OK, so I'm feeling quite stupid for posting this and wasting coders' time!! My problem was to be found elsewhere. The real problem was, that I was using `Log.d` wrong. If the text string is empty, it seems that it doesn't get sent to the log:
`Log.d("This return","something")` ; `Log.d("This returns nothing","")` :S
[tag:Log.d]
Answer: OK, so I'm feeling quite stupid for posting this and wasting coders' time!!
My problem was to be found elsewhere. The real problem was, that I was using Log.d wrong. If the text string is empty, it seems that it doesn't get sent to the log:
Log.d("This return","something") ; Log.d("This returns nothing","") :S log.d


Can i have drag and drop from jquery treeview to jquery full calendar

Question: I want that i should be able to drag items from jquery treeview that supports drag and drop.Drop item onto jquery full calendar with database interaction
Comment: what kind of code do you have so far?
Answer: I answered a similar question here... basically you'll have to use a custom version of fullCalendar.
Or, maybe you could adapt this plugin I put together for use with any version of fullCalendar, until fullCalendar officially releases the drag and drop version.


Routing not working with dynamic URL

Question: See my code in Plunker: https://plnkr.co/edit/knuf4Z64Kla2vPQRociv?p=info
I am trying to get the routing part working with a dynamic URL.
my Component.js (only metadata, full code is in plnkr.co)
sap.ui.core.UIComponent.extend("com.myapp.Component", {
    metadata: {
        rootView: "myapp.main",
        routing: {
            config: {
                routerClass: "sap.m.routing.Router",
                viewType: "JS",
                viewPath: "myapp",
                controlId: "mainapp",
                controlAggregation: "pages",
                transition: "slide"
            },
            routes: [{
                pattern: "main",
                name: "main",
                target: "main"
            }, {
                pattern: "agent",
                name: "agent",
                target: "agent"
            }],
            targets: {
                main: {
                    viewName: "main",
                    viewLevel: 1
                },
                agent: {
                    viewName: "agent",
                    viewLevel: 2
                }
            }
        }
    }
});

Answer: Check this: https://sapui5.hana.ondemand.com/sdk/#docs/guide/cf3c57c89ef0491793d1ce327ab4f9b2.html
You need to specify a routerClass in your config. That is most probably why router is undefined in your scenario.
Furthermore you will need to specify a rootView as well as a controlId and a controlAggregation in your routing config.
Comment: Hi @cschuff, can you please explain more, regarding my updated question. Thank you
Comment: Could you create a new rootView, place the App control in there and remove the createContent from the Component.js? I'm not totally sure if createContent and addPAges works well together with routing...

Routing not working with dynamic URL


Can a 100 amp sub panel be mounted directly to a metal building frame?

Question: My main 200 amp panel has the neutral bus bar and the equipment ground bus bonded. I am running 2/2/2/4 al wire to the 100 amp sub panel. The neutral bus and the equipment ground bus are not bonded on the sub panel. Can the equipment ground bus bar be mounted directly to the metal panel box? Also, can the panel box be mounted directly to the metal building frame? The main panel and sub panel are on two seperste buildings.
Comment: Do you already have the 2/2/2/4 cable, or have you yet to buy it?
Comment: Are you really attached to 100A?
Comment: I have not bought the 2/2/2/4 yet.
I plan to install a 100 amp breaker in the main panel, to feed the sub panel.
Comment: The only NEC section that allows greater than 90A is Section and Table 310.12, where it clearly says "supplying the entire load associated with a single-family residence". Otherwise you need to use the rating from 310.16, 75 or 60 degree columns.
Answer: If an inspector is particularly picky he can insist that only the ground bars listed on the panel instructions be used, mounted as instructions say.
The panel can be mounted on a metal building frame. You must create a grounding electrode system at the detached building and bond the metal structure to the electrode system.
At best #2 aluminum is only good for 90A, and only 75A if you have 60°C conditions. You can use a 100A (or larger) panel, but you will need to feed it with a smaller breaker.


Can I play Pokémon Sun and Moon purchased in another country?

Question: I want to play Pokémon Sun and Moon, which has been just released, but when I tried to download it, I found that my 3DS didn't have enough disk space, so I'm going to purchase a physical disk.
Unfortunately however, I'm now traveling. So I must purchase a copy of Pokémon Sun and Moon that is purchased in another country...
Can I still play it on a 3DS that was purchased in a different country? If the countries are relevant, my 3DS was purchased in Japan and I'm going to buy a copy of Pokémon in China or Taiwan.
Comment: You can ask for US version of games at stores.  Some stores will import games from different regions.
Answer: From the Nintendo Support Forums, this same question was asked and this answer was chosen by the moderator as the best answer:

No. Nintendo 3DS games and systems are both region-locked, so a German copy of Pokémon Sun would only work on a Nintendo 3DS system from that same region. Similarly, a NTSC Nintendo 3DS system would only be able to play a Pokémon Sun game from the NTSC region.

Therefore, Pokemon Sun and Moon are region-locked and you will not be able to play a Chinese or Taiwanese copy on your Japanese 3DS.
For a map of the regions that Nintendo locks according to, see here.
Comment: @Blaszard While this answer is absolutely true, the fact that the countries involved are China/Taiwan gives you more options. Imported games are common in these countries and I would expect you to be able to find Japanese-region copies of the game fairly easily, at a slight price premium of course.
Comment: @Setsu Good catch. But it would take a few weeks, at least. Since I was insufferably desperate for playing the Pokemon, I already decided to delete my Pokemon X data and am now downloading it... Thanks guys!
Comment: Ohhh it is so bad. Thanks. What is NTSC by the way?
Comment: @Blaszard I had to google, but [here](https://en.wikipedia.org/wiki/NTSC) is the wikipedia page for it.
Comment: Hmmmm now I'm not sure what the answer means, then. Because Japan and Taiwan (and US) are in the same NTSC region, can I play Pokemon purchased at Taiwan? It seems that the OP on the linked page cannot play Pokemon because he/she tries to use a Germany copy of it, which is in different region called PAL, right?
Comment: @Blaszard Ah, you're right. I looked up how they divy up the regions and apparently Japan is its own region entirely! See the map I just added.
Comment: OMG! Now I'm seriously considering buying a new 3DS... Thank you so much, anyway.
Comment: @Blaszard For future reference, you can move the data using a file manager instead. It works on my machine, but afaik this is undefined behaviour and the data might not go back on again on future updates.
Answer: According to the region locking wikipedia page the 3DS is region locked for 3DS specific software. So I think you may be out of luck until you get a Japanese copy of the game.
Source: https://en.wikipedia.org/wiki/Regional_lockout#Nintendo

The Game Boy and Nintendo DS product lines do not use regional lockouts for physically distributed games; however, software specific to the Nintendo DSi are region-locked, and cartridges released by iQue in China can only be played on DS models produced by iQue (although they remain compatible with other DS cartridges). The Nintendo 3DS line however, does enforce region locking for 3DS-specific software,[2] with the exception of Nintendo 3DS Guide: Louvre, which is region-free.