How can I most effectively farm Pixels?

Question: I need a lot of Pixels to craft the various shiny weapons and armor that I have my eye on. However, the only ways that I can find to acquire Pixels are by killing enemies repeatedly, and by finding capsules underground. Neither method seems particularly quick, and frequent combat has its own associated risks.
Is there a better way? What is the fastest way to earn Pixels?
Comment: Once you do get higher level armor and weapons, I've noticed higher level monsters generally drop way more pixels than on the starting planet.
Answer: You can use the refinery to turn excess ore into pixels fairly effectively.  To get this, you will need the tier 2 crafting station, which you can only access after defeating the first boss.  This is, however, a very effective way to get extra bits out of excess ore.
Comment: Could you elaborate on what the processor is and how you use it?
Comment: @Sterno the refinery is a tier 2 product, you need to defeat the first boss and make the t2 crafting station from the item it drops before you can make the refinery. If you don't have that, the refinery isn't available to you yet.
Comment: @sterno Sorry Refinery. It converts ores into pixels.
Answer: Exploring the surface for large buildings can prove quite fruitful, as many of the chests and containers therein will contain large caches of pixels.  Take them.  All of them.  As of right now (shortly after the Frustrated Koala update), NPCs don't even get mad if you take their stuff from their containers.
If you cant' find such structures easily, there's another way to find large pixel caches.
Dig deeper down.
The world I am on has a huge underground cavern that has tons and TONS of capsules full of pixels.  dig down deep enough, and you'll start running into them all over the place.
This area is dangerous though, so be prepared.
For extra bits, make sure you kill monsters with a strong Melee weapon, which provides a high chance of them dropping bits (with ranged weapons, the chance for bits to drop is lower due to a higher chance to drop meat and leather instead).
Comment: AFAIK it's only more likely to drop leather or meat then you use Bow in particular, not any ranged weapon.
Comment: This isn't quite true. I quite often have monsters drop pixels when killed with a ranged weapon.
Comment: @SaintWacko I've noticed this too, but only after the most recent update.  Changing my answer to reflect this.
Answer: Search for a Sewer, but don't kill the po golems , search the whole sewer and lead all the po golems to one spot.
If the po golems can't hit you, they will start throwing small versions of The po
Dig a 4/6 wide gab between you and the po golems so the small po's fall in.
The small po's can be killed easy and you can collect the pixels quite easy!
Make sure the range attacks of the golems can't hit you by placing one block in front of their face
Answer: If you don't mind slaughtering NPC - killing guards yelds quite a lot of pixels. Kill everyone you see. Guards with sniper rifles can be dangerous.
Answer: Kill everything you see and pick all the ores that you find, and then turn the ores into pixels in the refinery and voila!
Answer: Head to the highest sector you can currently access, then look for a group of planets that are all desert. Pull out your pickaxe, and start looking for large sections of either soft sand, or gravel.
Dig straight down, and as the sand and gravels falls, any ore that was trapped inside it will fall down and be collected, it's like your sitting at the bottom of a funnel collecting all the ore that falls. When you run out of sand/gravel, find a new place.
When you get bored, go and put the crazy amounts of ores that you've collected into your refinery/refineries, and watch the pixels pour in.
Answer: An effective way of passively gathering pixels is to build a structure with a bunch of turrets on it in an untamed area. For best results, the turret weapons should outclass the planet you're on. Hang around nearby and attract monsters periodically, then lead them back to your turret firing squad and pick up the remains.
Disclaimer: this is based on my experience of creating an apartment complex for NPCs on a relatively dangerous planet. I'm not sure whether the proximity of civilian NPCs has an influence on this equation. Also, in my case the tiers of the planet and of the turret weapons are pretty close, which requires me and the civilian NPCs to take a hand in the defense. My guess is that on a lower-tier planet, turrets killing monsters by themselves will make for an overall more efficient process, but the higher your level relative to the monsters, the less rewarding it will be, obviously.
Using this setup, in ten minutes I gather over a thousand pixels. However, the turrets themselves obviously represent a significant initial investment, and turrets can't be re-positioned.
Comment: In ten minutes of gameplay, I earn 1k pixels just by looting chests, selling stuff or doing quests without focusing on gaining pixels. I'd probably rather use this method to farm monster loot like RAM sticks.
Comment: @TomášZato Psst ... check the date, this was way pre-1.0.
Comment: Okey, and? Afaik answers on SE are supposed to solve problem as good as possible. This one does not. Do you expect every visitor to compare dates before he starts reading every answer?
Comment: This is still an answer, the pixel amounts just differ these days.
Comment: You should really avoid being so defensive in reactions to a comment. I never said this is not an answer, if I thought so I would downvote and flag this post. I said that this method is (no longer) effective, which is true. I also said that on Stack Exchange, it is irrelevant when was the answer posted - that's also true. And I only commented that, because you for some reason needed to point the date-time out.
Answer: The current best way to make pixels is by selling space station transponders. Their value is 150000 pixels and they sell for 30000.
You need ores to acquire them. So the strategy is going to a asteroid field and mine copper, silver, gold in abundance.
Then you need to mine titanium but you can buy half of the bars from the outpost and still be profitable
Answer: All these ways of taking ores have a risk of dying. I have a better way that COULD kill you but only if you're about to die.
Make a large (30 x 10 is good) room, make sure there's no light and monsters will spawn. And you know they're coming! In 1 hour I got 1,450 pixels!
Answer: Farm. I mean Actually farm crops. They give you tons of money of little effort. Especially crops that grow more of it self(like pearlpeas). Hope this helps!
Answer: For the best gain over time, I focused on farming this two products:

Rice - sels for 24/pc
Silk (crafted from 4 Silk Fibre at Sewing Machine) - sels for 40/pc which is 10 per one Silk Fibre item.

Both those can be sold using Terramart Shipments which gives you twice the normal price. Both are very convenient for farming.

Rice does not need replanting, so all you need is one sprinkler for about 40 plants
Silk fibre just needs you to place Moth Trap. You can even place them in your ship.

Of course, since I already have Terramart Shipments I also throw in any excess produces of my farm.
This probably isn't fastest method to gain lot of pixels but by the time you have build Heating EPP upgrade, you will no longer worry about pixels.
Answer: Just retry the Great Sovereign Temple mission. You can find a Valkyrie Helm inside a box that you can sell at the Outpost for 1000 pixels. This object always reappears each time you do the mission.  You just need five minutes to find the helmet, so it's a relatively fast way of farming pixels
Answer: There are a lot of ways actually. Not dying being one of the most important ones.
You will have to grind your way. Go to the Alpha Sector and kill everything you see. That's one way. Put your spare ore in the refinery.
Comment: Hi NinjaBoffin, you haven't added a great deal more than what people have already contributed. You did mention the Alpha Sector as being good for farming Pixels though. Maybe you can go into more detail why that is the case?
Comment: Yeah, sure!
I said the Alpha sector because there a lo of NPC/Monsters for you to kill and they are a doddle. (if you have beta sector weapons+). Then you also get micro dungeons and normal dungeons.
Answer: 3 steps to fortune.

mine cobblestone
make rock bricks
make dark smooth stone

each 400 cobblestone earns around 20k pixels
Answer: My method is to make a farm with wheat, bananas, potatoes, ect. Then you will want to  get a terramart shipping device. Then, get a refinery. You'll also eventually need an oven. You can also start an animal farm if you want. Selling weapons and blocks that you don't need can aid in this process.
Here's the strategy:

Tenants sometimes have quests. Completing these is an easy way to earn money.
Your main source of income will come from producing and selling products. Namely, food using your oven, and crops from your farm; you should also produce weapons and armor using your refinery, and use or sell these as you wish.
If you water your crops frequently and sell off the crops/seeds you don't need, you'll have so much money the game becomes unfun.

I play in frackin universe and some other mods. That shouldn't matter with farming or other things.
Comment: I did not know that what crafting station do you make the stone in?

How can I most effectively farm Pixels?


limit set of a bounded solution

Question: Going over my lecture notes I have noticed that my professor uses poincare bendixson theorem whenever we have a solution x(t) that remain bounded for all time, but shouldn't we also know that the limit set for for x(t) is non empty to use poincare bendixson theorem?
Or does the following proposition hols?
Lets consider a solution x(t) of a planar differential equation and assume that x(t) remains bounded for all time then the limit set of x(t) is non empty
Thank you
Answer: Indeed, for any sequence $t_n\to\infty$ the sequence $x(t_n)$ contains a convergent subsequence; its limit belongs to the limit set of $x$.
Comment: cheers, good to finally clarify that

limit set of a bounded solution


Uniqueness of complex tori

Question: In the abelian case compact abelian Lie groups  are unique up to  diffeomorphism i.e. $(S^1)^n$.
How about  the complex case? Are complex tori unique up to holomorphism i.e $(T)^n$ where $T=S^1\times S^1$?
Comment: I mean if $G$ is a compact abelian Lie group of dimension $n$, then $G\cong(S^1)^n$.
Comment: For a lattice $\Lambda_1 = u\Bbb{Z}+v\Bbb{Z}$ then $\Bbb{C}/\Lambda_1\cong \Bbb{C}/\Lambda_2$ iff $\Lambda_1 = c \Lambda_2$, then $\Lambda_1=(au+bv)\Bbb{Z}+(cu+dv)\Bbb{Z}$ for any $a,b,c,d\in \Bbb{Z},ad-bc = \pm 1$. Letting $t = u/v$ we obtain the moduli space of complex tori is $(\Bbb{C-R}) /PGL_2(\Bbb{Z})= \mathcal{H}/SL_2(\Bbb{Z})$ the first modular curve https://en.wikipedia.org/wiki/Modular_curve
Comment: What does "compact abelian Lie groups are unique up to diffeomorphism" mean?
Comment: Ah. Probably you should have said that.
Answer: No.  There is a one-dimensional moduli of elliptic curves, for example.
Comment: See [this](/questions/316181) for example.  For higher dimension you also have complex tori that are nonprojective.
Comment: Can you please say more on this example. Thanks!

Uniqueness of complex tori


merge statement issue(mainly for update ) incase block

Question: i was trying to insert certain data from one table(table1) to another table(table2) in a way like if data is existing just update the data or insert the data .But the problem now i am facing is,when i added a last condition like if first_name like 'mss%' i have to do insert SERVICE_TYPE_ID 10 else 20.But it is not happening for this case condition and rest all case condition in success.So i would like to know what is wrong with the last case condtion
trim(b.first_name) like 'mss%'
                                      THEN 10
                                      ELSE 20

this is mainly failing for Merge update section and inserting 20 instead of 10
Here is my full oracle query
MERGE INTO table2 a
USING table1 b ON (a.second_name = b.first_name)

WHEN MATCHED THEN
  UPDATE
  SET a.friendly_name = TRIM(b.friendly_name),
    a.account_number  = TRIM(b.account_no),
    a.ne_type         = TRIM(b.ci_type),
    a.service_type_id = CASE
                        WHEN upper(trim(b.company_name)) LIKE '%MWAN%'
                             OR upper(trim(b.company_name)) LIKE '%MGWAN%'
                             OR upper(trim(b.company_name)) LIKE '%MWLAN%'
                             OR upper(trim(b.company_name)) LIKE '%MLAN%'
                             OR upper(trim(b.company_name)) LIKE '%DDOS%'
                             OR trim(b.first_name) LIKE 'mss%'
                          THEN 10 ELSE 20 END,
    a.to_locate_in_gis ='Y'
  WHERE a.account_number <> b.account_no

WHEN NOT MATCHED THEN
  INSERT (ne_slno, second_name, company_id, ne_type, ne_status, service_type_id)
  VALUES (s_node_seq_nextval,
          TRIM(b.first_name), TRIM(b.company_id),
          TRIM(b.ci_type), TRIM(b.ci_status),
      CASE
      WHEN upper(trim(b.company_name)) LIKE '%MWAN%'
           OR upper(trim(b.company_name)) LIKE '%MGWAN%'
           OR upper(trim(b.company_name)) LIKE '%MWLAN%'
           OR upper(trim(b.company_name)) LIKE '%MLAN%'
           OR upper(trim(b.company_name)) LIKE '%DDOS%'
           OR trim(b.first_name) LIKE 'mss%'
        THEN 10 ELSE 20 END)
  WHERE SUBSTR(b.first_name, 1, 1) != ' '

All case condition is success except the one which pointed trim(b.first_name) like 'mss%'
Comment: What result do you get if you do: `select count(*) from table1 where trim(b.first_name) like 'mss%';`?
Comment: What about `select count(*) from table1 where first_name like 'mss%';`?
Comment: Do you have data in your table1.first_name column that starts with "mss" (in lower case)?
Comment: @Boneist Yes it has data like mss-testeronet-mai-rb etc datas
Comment: @Boneist 11000 records are there
Comment: @ Boneist 56 records less ,is that the issue??if then what is the issue?
Answer: In your insert, the last expression in your case statement is trim(b.first_name) like 'mss%'.
However, then insert part of your merge statement has a predicate of: WHERE SUBSTR(b.first_name, 1, 1) != ' ') which excludes all the rows where there are spaces before the mss.
That is likely to be the cause of your issue. I would suggest you either remove that predicate from the insert part or add or trim(b.first_name) like 'mss%' into the where clause.
Comment: `WHERE SUBSTR ( b.first_name, 1,1 ) != ' '` is saying "where the first character of the first_name column is not a space". Your case statement trims the spaces off both the front and end of the first_name column **before** checking whether the resultant string starts with `mss`. This means that even though you have rows matching that expression the case statement, your where clause is excluding most of them, as they have at least one space at the beginning of the first_name.
Comment: i am confuse now,can you clear it. WHERE SUBSTR
                                    (
                                      b.first_name,
                                      1,1
                                    )
                                    != ' ' will not add any spaces then how it will add it up


Take over all links -- except certain class (.not?)

Question: I'm currently taking over any links on the page that begin with "users":
$('a[href^="/users/"]').live('click', function(event) {

...however, this is a little greedy.  I want to exclude any links to "stuff" that are NOT with the "versions" class.  I tried:
$('a[href^="/users/"]').not('div.versions a').live('click', function(event) {

...but this breaks the whole block.  My next guess it is breaking because of "live" -- with the way events trickle up.
Any ideas?  Is there a better way to do this?
Comment: Breaks the whole block as in the event never fires when you click any of them?
Comment: The reason for this is that jQuery relies on the correct selector for `.live()` to work. When a click event is received, it compares the elements to the selector. When you use `.not('div.versions a')`, the selector ends up looking like `a[href^="/users/"].not(div.versions a)`, which doesn't match anything.
Answer: try merging not in the main selector:
$('a[href^="/users/"]:not(div.versions a)').live('click', function(event) {

Check here as well: .not() with .live() not working, seems to be the same problem.


3 phase MWBC - 2 pole breaker with shared neutral

Question: I've searched around and can't quite find an answer to my question.
I understand that you can share a neutral on a 3 phase panel if you use a 3 pole breaker. But can you still share a neutral on a 3 phase panel with a 2 pole breaker?
I wanted to create 2 separate 20amp outlets using 12/3 wiring. Black for outlet A and Red for outlet B, and share the neutral. Will this work as long as use a 2 pole 20amp breaker? Or will I run the risk of overloading the shared neutral?
Comment: Is this in a house or a commercial setting, and what make and model is your breaker box?
Comment: This is a commercial setting, but I don't know the exact make and model of the breaker box. I can check in the next day or two. I do know that the breakers are Square D.
Comment: Carry on then -- were this residential, then AFCIs would be an issue because Square D 2-pole AFCIs aren't compatible with 208V power, but since you don't have AFCIs to worry about, you're good to go
Answer: Think of it this way. What is the difference between a 2-phase MWBC on a 3-phase panel and a 3-phase MWBC with no load on one phase? Nothing.
I'd say that it is no problem.
Answer: yes, you can still share neutral. the worst case neutral current is still the same.
Comment: Just double checking… using 2 pole breaker on 3 phase/shared neutral should result in equal amps on both hots and shared neutral? (Assuming both hots are running the exact same amps)
Comment: You mean in a worst case scenario, both hots maxed, neutral current = hot current but won't exceed it.
Comment: Yes it will do that.


How do I track progress for individual achievements on Steam?

Question: I've seen it on a TF2 video that I can't find anymore, but I found another occasion of someone doing this here:

At the bottom right, it shows "Achievement progress" and it appears multiple times throughout the video as he activates more radios.
Comment: I don't have a source for this, but to the best of my knowledge this is entirely game-dependent. Valve's games likely try to show off what the steam achievements tracker is capable of. And, in my experience, most other developers just don't bother - they track the achievement progress internally and send the unlock code at once.
Answer: You don't track the progress, it's up to each developer to implement progress for each achievement. Here is for example Euro Truck Simulator 2 with partial progress for 3 of it's achievements:

And here is Beat Saber not implementing progress for the Drum Kit and No Mistakes achievements:


3 Sets of Wires Confusion

Question: There was an old junction box in our family room with a metal cover over it. It looks like there was probably a wall sconce there at one point and I thought I'd install a new one. However, the wires inside are really confusing and I'm not sure how to proceed. There are two white wires capped together, two black wires and a white wire covered in black sharpie capped together, and a single black wire with black tape on it capped by itself. I am guessing this is some sort of 3 way switch wiring, but I'm not sure what to connect with the wires on the light fixture. Any ideas? See my picture for reference. Thank you
Answer: This appears to be a classic switch loop with the white wire marked black. With your power turned off, connect your white fixture wire to the group of white wires in the box. Connect your black fixture wire to the single black wire in the box. The box doesn't appear to be grounded so just leave the copper wire from the fixture, if there is one, unhooked and tucked into the box.
Comment: Thank you! I've never seen this before and was starting to scare myself!

3 Sets of Wires Confusion


What is the practical reason of having two terms tier and layer in applications architecture?

Question: According to this answer layers and tiers are different things.
I see a practical reason of using the term layer i.e. it logically divides code so it becomes more maintainable. It's just helps ti
But I don't see any practical reason of using the term tier. Following this conclusion I understand why people tend to use tier and layer interchangeably
I still have a hope that the word tier has its own meaning not for nothing. So, could you give me any practical example it use
 in development?
Comment: @DaveNewton While I was writing the question I found one probable example, maybe it can help understand my question's logic. When developers are asked to create 3-tier applications it literally means that the app should be run on 3 different machines i.e. the app should have monolith architecture with distributed load (hope it makes sense)
Comment: I don't know what you're asking or what kind of answer you expect. The linked answer explains one possible differentiation, the "practical reason" is implicit in that  explanation, regardless if anyone agrees with it or not. IMO this question isn't a good fit for SO.
Comment: That's an interpretation of the linked definition, yes (although you're assuming the monolithic part). But didn't really make the question any more suitable.
Answer: In Mythical Man Month, packaging is identified as an early sin.  Tiers are part of packaging.
You have designed your system well.  Your components have nice interface boundaries, and each component could be deployed upon a different computer, with a different architecture, in a different location, and your system would work just fine.  If you followed this far enough, many of these components could be deployed not just remotely, but also redundantly and concurrently to permit greater scalability and resiliency.
The micro-service architecture actually demands this.  Your system needs to decompose into in(ter)?dependent services that can be deployed outside your layer of control to permit scaling, etc.  A modern version of JCL(*) is employed in ugly named things like k8s and faas to grant scaling and redundancy to your system.
Regardless of these clever configuration mechanisms; some basics from traditional systems theory reign.  For example, if two modules inordinately communicate/share, they need to be relatively co-located.  The JCL needs to be able to express this, and the assertions of the component linkage becomes a definition of the tiers.
(*)Job Control Language; a rightly maligned mechanism used by IBM to allocate and deploy resources on mainframes in the 1970-2014; when it was suddenly replaced by an even harder to understand set of json & yaml files under the banner of k8s.  Those that don't learn from the past are doomed to repeat it; badly.


Can corrupted items (gems) be upgraded with GCP or other quality-increasing currency?

Question: It is known that corrupted items cannot be altered with currency items. Does this apply also to quality?
Can I upgrade quality of a corrupted gem with a GCP?
Can I upgrade quality of a weapon with a whetstone?
Answer: Yes, you cannot alter a Corrupted Gem with GCP (Gemcutter's Prism).
Because an item's quality is an alternation that boosts the damage/armor/etc. of an item, it cannot be used on Corrupted Gems.


List stored functions that reference a table in PostgreSQL

Question: Just a quick and simple question: in PostgreSQL, how do you list the names of all stored functions/stored procedures using a table using just a SELECT statement, if possible? If a simple SELECT is insufficient, I can make do with a stored function.
My question, I think, is somewhat similar to this other question, but this other question is for SQL Server 2005:
List of Stored Procedure from Table
(optional) For that matter, how do you also list the triggers and constraints that use the same table in the same manner?
Comment: [List stored functions **using a table** in PostgreSQL](http://stackoverflow.com/questions/31166303/how-to-get-a-list-of-stored-procedures-using-a-specific-table-in-postgresql/31168357#31168357)
Answer: SELECT  p.proname
FROM    pg_catalog.pg_namespace n
JOIN    pg_catalog.pg_proc p
ON      p.pronamespace = n.oid
WHERE   n.nspname = 'public';

Comment: As Lukáš Lalinský pointed out in his answer, PostgreSQL supports standard `information_schema.routines` -- useful for all that like standard things.
Answer: SELECT  proname, prosrc
FROM    pg_catalog.pg_namespace n
JOIN    pg_catalog.pg_proc p
ON      pronamespace = n.oid
WHERE   nspname = 'public';

Comment: Maybe next time simply edit the post above your own rather than change a small thing
Comment: Daniel L. VanDenBosch:  He pretty much got his whole karma with the upvotes from this answer, so I don't see him doing that anytime soon.
Answer: If you are using psql, try \df
From the man page:
Tip
To look up functions taking arguments or returning values of a specific type, use your pager's search capability to scroll through the \df output.

Running \set ECHO_HIDDEN will reveal what \df is running behind the scenes.
Answer: Same as @quassnoi and @davidwhthomas, except I added the argument names in there:
SELECT  proname, proargnames, prosrc
FROM    pg_catalog.pg_namespace n
JOIN    pg_catalog.pg_proc p
ON      pronamespace = n.oid
WHERE   nspname = 'public';

If the purpose behind listing the functions is to clean them up or iterate a new function with a changing params list, you will frequently need to drop functions:
DROP FUNCTION <name>(<args>);

By adding proargnames, I am able to construct the applicable function name for the drop.
Additionally, it's nice to see a more complete picture when evaluating the functions.
Answer: You can use the standard information_schema schema to get metadata about your database (it's in the SQL standard, so it should work the same way in different database systems). In this case you want information_schema.routines.
Comment: Useful, but doesn't really answer the question.
Answer: Excluding the system stuff:
select proname from pg_proc where proowner <> 1;

Comment: Why <> 1? On my Postgresql installation, system procedures have a proowner of 10, not 1.
Comment: I didn't know that. The solution is of course to change the "1" accordingly.
Answer: Have a look at my recipe. It reads functions and triggers. It is based on informations from: Extracting META information from PostgreSQL (INFORMATION_SCHEMA)
Comment: Second link is dead.  :-(  Please incorporate the contents of the first link into this answer so we're not left in the dark when that one dies.  Thanks.
Comment: Thanks, this worked. Combined with SELECT pg_catalog.pg_get_functiondef('functionName'::regproc) you can get the create statements as well.
Comment: The Extracting META... link was what worked for me I didn't see the "recipe" link till now.
Answer: Please change the schema_name and table_name in the below query:
SELECT n.nspname AS schema_name
     , p.proname AS function_name
     , pg_get_function_arguments(p.oid) AS args
     , pg_get_functiondef(p.oid) AS func_def
FROM   pg_proc p
JOIN   pg_namespace n ON n.oid = p.pronamespace
AND    n.nspname = 'schema_name'
AND    p.prosrc like '%table_name%'

Since the table name is case sensitive, so need to define the exact table name.
Comment: Note that PostgreSQL does have the `ILIKE` keyword and the `~~*` operator, both of which can be used for case-insesitive matching.
Answer: For retrieving the argument types of the functions, which are required when referencing the function in ALTER --  using oldevectortypes worked well for me.
See How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?


Need help creating a Azure Bot service

Question: Click Create new resource link found on the upper left-hand corner of the Azure portal, then select AI + Machine Learning > Web App bot. After filling all the details, I get an error message stating 'the service id is not available' and the create button disappears.
Comment: The exact error message is: 'The requested bot ID is not available.'
Comment: It means that you have already created a bot with the same name. Try creating a new bot with a different bot name and you won't get the error.
Answer: Sign out and re-login to the Azure portal and then re-try the operation has mentioned in the below article
https://learn.microsoft.com/en-us/azure/bot-service/bot-service-quickstart?view=azure-bot-service-4.0
Make sure you have enough amount in your Azure subscription (or) your subscription is Active.Like(changing "consumption plan" to "app service plan.)
However Azure Portal is a simple GUI to create any resources easily. But it doesn't mean to stop you from using other ways like Azure CLI, Powershell, ARM templates, Other SDK's
Azure CLI to create a WebApp Bot
Dot Net SDK to create a WebApp Bot
Node.js SDK to create a webApp Bot
Additional information: After you've registered your client with Azure, you need to create the Web App. Be sure to use the following in the body:kind "webapp"
location Geographic location used to create the bot service resources. For example, eastus, westus, westus2, and so on.
You won't be able to test this due to Azure subscription limitations.
Answer: This error is because the service name has already been assigned within Azure. That name must be unique across all Azure services, not only the ones in your group or resource groups. This is a common error new comers may experience.

Need help creating a Azure Bot service


Splicing 6 AWG Wire

Question: In my heater installation I need to connect two sets of 6 awg wire and a ground on a 50 amp circuit.
Whatever I use to splice is going to have to fit thru the hole and go into the wiring compartment. My initial thought is to use a blue nut and tape, but I also see butt connectors, Polaris Taps and other options.
My other thought is to take off the back of the unit and connect the wires directly to whatever the pigtails are attached to, removing the pigtails.
What would you do?
Thanks in advance for any advice.
EDIT: I ended up getting two of these:
Morris Products Insulated 2 Conductor Splice Connector
Comment: The wires for the power supply should stick out from the conduit by ~6 inches.  Wires from the heater are as long.  That big window should be plenty to attach your favourite connectors in.
Comment: Thanks, what would you recommend to connect the wires?
Comment: Wire nuts of the right size should be okay.  You want a size of nut with two 6 gauge wire around the centre of range of sizes.
Answer: The picture is misleading. The text is comparatively clear.
The hole the wires come out through in the picture is the knock-out where the cable or conduit goes into the device. The wires get shoved back in there before that happens (or are not ever pulled out through it, more likely.) A suitable clamp or fitting is used to secure the cable or conduit.
The large rectangular hole ("watch window for wiring") to the left and above that is where you pull the supply wires and the device wires to be joined out to actually make the connection and put the connected wires back inside the device, before restoring the cover (not shown in picture.) That hole will easily fit any listed and approved splicing device you choose to use, in triplicate.
Comment: If you **need** tape to keep a wire-nut/Marrette ("cap") on the wires, **don't** use wire-nuts/Marrettes at all. If they fall off otherwise, they are not correctly tightened. If bare wire is sticking out, the strip length is incorrect. If you use the correct size, applied correctly, they work fine for 50A and 6 AWG. If your past experience leads you to reach for the tape, Polaris or Mac-block connectors and a torque driver might be well worth the extra cost, given the savings on "electrical fires not started"
Comment: Thanks again, I ended up getting the Morris Products Connectors I linked in my OP. Seems safe and simple, and was only 25 bucks.
Comment: Thanks, that helps a ton...what would you connect the wires with? Is a cap and tape sufficient for 6 awg / 50 amps?

Splicing 6 AWG Wire


html5shiv doesn't seem to be working

Question: Here is the current working site...
http://www.cheltenham-nursery.co.uk/building/index.html
It displays fine in IE10, but anything previous to this and the display is all over the place.
I'm loading html5shiv in the head...

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Cheltenham Nursery</title>
    <link rel="stylesheet" type="text/css" href="css/screen_styles.css" />
    <link rel="stylesheet" type="text/css" href="css/screen_layout_large.css" />

Any advice or comments would be massively appreciated.
Cheers
Adam
Answer: Use:
<!DOCTYPE html>

Instead of:
<! DOCTYPE html>

The shiv script is being recognized, but your doctype is malformed because of the white space. While newer browsers won't care, older versions of IE will render your page in Quirks Mode.

html5shiv doesn't seem to be working


Contribute to the Docky Project

Question: I've recently installed Docky and it seems to be a great app to have and I'd like to contribute, or set up custom applets. Is there any guide regarding this? Especially the language used and the format that needs to be followed.
Answer: Check out Docky's LaunchPad here :
https://launchpad.net/docky
Seems the best way forward for you would to be either join #docky on irc.freenode.net or speak to one of the developers directly.

Contribute to the Docky Project


Python Parse JSON objects in Different Way

Question: I'm working on a python project In which we are getting some inputs from the user.
We are working on microservice deployments actually. Where user needs to provide the following things:
1): User will provide a GitHub repo which will include all of his microservices he wants to deploy inside a specific directory.
For example, we have a directory structure in GitHub repo  like this:
mysvcs
 |----nodeservice
 |----pyservice
2): User will provide a JSON object in which he will mention the URL for this repo and some other information for these microservices, like this:
{
  "repo_url": "https://github.com/arycloud/mysvcs.git",

  "services":[
        {
        "name": "pyservice",
        "routing": {
          "path": "/",
          "service": "pyservice",
          "port": "5000"
        }
      },
      {
        "name": "nodeservice",
        "routing": {
          "path": "/",
          "service": "nodeservice",
          "port": "8080"
        }
      }
        ]
}

Then we are reading all the services from GitHub repo and using their directories to read the source code., and along with that, we are parsing the JSON object to get some information regarding these services.
We are reading the repo like this:
tempdir = tempfile.mkdtemp()
saved_unmask = os.umask(0o077)
out_dir = os.path.join(tempdir)
Repo.clone_from(data['repo_url'], out_dir)
list_dir = os.listdir(out_dir)
print(list_dir)
services = []
for svc in range(0, len(data['services'])):
    services.append(list_dir[svc])

print(services)

According to our example above, it will return:
['nodesvc', 'pyservice']

But when we are reading the JSON object there user have mentioned the services in different order instead of alphabetically, so when we are the loop through the services using the above array we are trying to use the same index for JSON object services and the list of directories after cloning the GitHub repo but due to different orders it interchange the data.
Here's a sample code:
def my_deployment(data):
    # data is JSON object
    # Clone github repo and grab Dockerfiles
    tempdir = tempfile.mkdtemp()
    saved_unmask = os.umask(0o077)
    out_dir = os.path.join(tempdir)
    Repo.clone_from(data['repo_url'], out_dir)
    list_dir = os.listdir(out_dir)
    print(list_dir)
    services = []
    for svc in range(0, len(data['services'])):
        services.append(list_dir[svc])
    print(services)
    for service in range(len(services)):
        # Here i need to use the data from JSON object for current service
        data['services'][service]['routing']['port']
        # Here it's using the data of **pyservice** instead of **nodeservice** and vice versa.

Important:  Ther order of services in GitHub is ['nodeservices', 'nodeservices'] but in the JSON object user can mention his services in a different order like pyservices, nodeservices. So when we are looping through how can we sync the order of both of these sources? This is the main issue.

I have tried it by changing the structure of my JSON object in this way:
"services":[
    "pyservice": {
      "routing": {
        "path": "/",
        "service": "pyservice",
        "port": "5000"
      }
    },
    "nodeservice": {
      "routing": {
        "path": "/node",
        "service": "nodeservice",
        "port": "8080"
      }
    }
]

But it says syntax is not correct.
How can I overcome this issue?
Thanks in advance!
Comment: You forgot to change the `[]` to `{}` in the json
Comment: Hi @shadowtalker, it' s JSON array of objects.
Comment: If you run your code in  [JSON validator](https://jsonformatter.org/) you'll see it's not valid.
Comment: Hi @VilleKoo, Which one? I have posted 2 version of JSON object, first, one valid and second one is not as I mentioned in the question.
Comment: @AbdulRehman The bottom one
Comment: Yup, it is, I have mentioned, I was just showing that if we can overcome this issue by changing our JSON object.
Comment: Why can't Services be an object instead of array? From what I see, you are just iterating through the Services array and then grabbing the name of the service. So  instead, if you keep Services a key-value map, it will allow you to iterate as well as will save you from the issues of index number and order. Something like this:
"services" : {
    "pyservice": {"something":"something},
    "nodeservice" : {"x" : "y"}
}
You can iterate over all key value pairs of services as well!
Comment: Actually, we are also getting the no of services the user wants to host from the length of this array, without this array how can we get the number of services user will provide?
Comment: @AbdulRehman count the number of keys? this is trivial in Javascript and Python. You can't name elements of an array.
Answer: You are thinking too complicated.
for svc in data['services']:
    print(svc['name'], svc['routing']['port'])

Done.
General observation: You seem to cling to loop indexes. Don't. It's a good thing that Python loops have no indexes.
Whenever you are tempted to write
for thing in range(len(some_list)):

stop, and write
for thing in some_list:

instead.
Comment: Hi @Tomalak, the issue is the order of services in the two places are different. Can we re-order the services array in JSON object into alphabetically? it will be matched with the order in GitHub repo.
Comment: Which two places? Don't build a `svc_list` variable in the first place and you're good. `data['services']` is your service list.
Comment: One place is Github repo and the other is JSON object array.
Comment: I don't get it. You have a `svc` object with all the relevant information. Name, port, whatever. The service `name` exactly matches a directory name in the repo. What *else* do you need?
Answer: The reason the JSON is not valid, is that you can't have name value pairs in a JSON array. This page tells you an array can be:

A comma-delimited list of unnamed values, either simple or complex, enclosed in brackets

Is the below JSON any use?
{
  "repo_url": "https://github.com/arycloud/mysvcs.git",

  "services":[
    {
      "pyservice": {
        "routing": {
          "path": "/",
          "service": "pyservice",
          "port": "5000"
        }
      }
    },
    {
      "nodeservice": {
        "routing": {
          "path": "/node",
          "service": "nodeservice",
          "port": "8080"
        }
      }
    }
  ]
}

If you want services sorted alphabetically, you can do the following:
services = data["services"]

b = {}
for node in services:
  b.update(dict(node))

alphabetical_list = sorted(b)

Note:
This gives you a list ['nodeservice', 'pyservice'] which you can then use to get the object in b.
Comment: Hi @NeRa, but how can we sync the order of this JSON array to the order of directories list `['nodesvc', 'pyservice']` from Github repo? That's the main issue. Because even in this way we need to use the index to loop through the services array.
Comment: I've updated my answer with how to do it alphabetically.
Answer: Here an approach we can use to overcome this order-sync issue:
First, the order of directories in GitHub repo is by default alphabetically, so if we sort the order for the array of services in JSON objects we will be able to get the same index for both sources. Even to make sure we can sort both of these sources alphabetically.
Here's the code:
First sort the services array of JSON object as:
data['services'] = sorted(data["services"], key=lambda d: d["name"])

By considering the example in the question, it will give us:
services = [
   {"nodeservice": {
     "A": "B"
     }
   },
   {"pyservice":{
     "X": "Y"
    }
   }
]

Then we will sort the list of directories from GitHub repo like this:
Repo.clone_from(data['repo_url'], out_dir)
list_dir = os.listdir(out_dir)
print(list_dir)
services = []
for svc in range(0, len(data['services'])):
    services.append(list_dir[svc])

services.sort()
print(services)

It will give us: ['nodeservice', 'pyservice'] according to the example above in the question.
So, In both cases we have the nodeservice first the pyservice, mean the same order.


Bird sleeping and eating soffit. How to make sure it is not coming back?

Question: I found this morning a bird (Northern Flicker?) sleeping and eating my house (see picture). The bird is able to hang there and put his head in one of the hole. I suppose the bird do that to get some warm air.
The problem is that the bird has caused significant damage. How can I make sure that bird doesn't come back?
Comment: Is it actually pecking at the wood or is the damage caused by its claws? If the latter, it might prefer a round peg to perch on. That way the bird gets a comfy place and you get someone to remove any insects in that area.
Comment: We don't see the wood damage from the angle I took the picture. I just updated the post. We can clearly see that the bird is having fun pecking at the wood...
Comment: You're right about the bird ID, anyway :-) .
Answer: The slightly scruffy plumage and a flash of red on the tail but not on the head makes me think it is a juvenile red-shafted flicker - do you happen to be in the west of North America? - so it may not have quite figured out what a tree is yet.
First, you'll want to repair the damage and re-paint. Take the opportunity to check for insect boreholes as that will need to be taken care of too.
Then, various sites, e.g. www.birds.cornell.edu and There is a woodpecker pecking on my house! Why is it doing that? How can I make it stop?, recommend plastic netting to cover the area in question.
Other methods are suggested, but I would think that black netting would be aesthetically the least intrusive unless you want to go to the effort of applying aluminium sheet and painting that to match.
It might be that scaring it off every time you see it would suffice to put it off returning, but you're going to have to get up there to repair the damage anyway, if only to deter carpenter bees and such.
Comment: Red-shafted & yellow-shafted are subspecies.  I think you know that but didn't want other readers to be misled.
Comment: @CarlWitthoft I am no ornithologist, but yes, I found that in my research. However, I didn't think it all that necessary to make the distinction in my answer :) Am I likely to be correct in my assesment of it being a juvenile?
Comment: That's harder to tell - photos often fool us a bit about overall coloration.
Comment: @AndrewMorton - Yes, I live in the Pacific Northwest (Seattle, WA). What I don't understand is why the bird has done damage in that area? I looked closely and couldn't see any insect. I wonder if the bird could "sleep" there just because it is warm (no/little wind and heat coming from the roof). I just installed bird spikes in the area. I hope this discourage the bird from coming back.


JSF action vs actionListener

Question: I am not clear on the difference between these two methods.  I see that the actionListener takes an ActionEvent as a parameter, but both may be tied to a method in the backing bean.
Is the only functional difference the ActionEvent parameter?   So if I need ActionEvent use the listener method, if not, either will work?
Comment: I think the title of this question should be "Action vs actionListener" since this seems to have nothing to do with ICEFaces. Thanks for the info.
Answer: actionListener takes an ActionEvent as the Parameter and returns void.  Action takes no parameters and returns a String which can be used for navigation.
If you don't need the ActionEvent, and don't need to navigate, you can generally do either one.  If you do need the ActionEvent, you need actionListener.  If you do need to navigate, then you need the action.

JSF action vs actionListener


XPath Get Upper Node Value With Provided Lower Node Value

Question: I have node values where SData Event is different between the 2 elements below and need to return the Event value "WK1" when only providing the FormData "PEMD" and ItemData "2019-12-18"
I can't provide the Subject value as this will not be known, only ItemData Value.
<Data>
<Data1 Study="R1979" MetaDataVersionOID="6713">
    <Data2 Subject="4100">
        <SData Event="SCN" key="WK1[1]">
            <FormData Form="PEMD" FormKey="1">
                <ItemData Item="PM" Value="1"/>
                <ItemData Item="PE" Value="1"/>
                <ItemData Item="DATE" Value="2020-01-01"/>
            </FormData>
        </SData>
    </Data2>
</Data1>
<Data1 Study="R1979" MetaDataVersionOID="6713">
    <Data2 Subject="4200">
        <SData Event="WK1" key="WK1[1]">
        <FormData Form="PEMD" Formkey="1">
        <ItemData Item="PM" Value="1"/>
        <ItemData Item="PE" Value="1"/>
        <ItemData Item="DATE" Value="2019-12-18"/>
        </FormData>
        </SData>
    </Data2>
</Data1>

I have tried
/Data/Data1/Data2/SData[@Event]/FormData[@Form='PEMD']

Answer: This XPath,
//SData[FormData[@Form="PEMD"]/ItemData[@Item="DATE"]/@Value="2019-12-18"]/@Event

will return the Event="WK1" attribute as requested.
Answer: Alternative :
//FormData[@Form="PEMD"][./ItemData[@Value="2019-12-18"]]/../@Event

Look for a FormData element with specific attribute (attribute : PEMD) and a specific ItemData child (attribute : 2019-12-18). Then get the attribute (@Event) of the parent element (..).
Output : WK1


Getting "No SteamUser" error on Garry's Mod

Question: I'm getting an error on Garry's Mod that's preventing me from playing.

Steam Error: No SteamUser.

What should I do? I've done everything the error suggested but the game still won't work.
Answer: Open task manager (cntrl + alt + delete) or search for it via the start menu. Look for the Steam process, select it, and then click "End process".
After that open Steam/Gmod again and you should not get this error.
Comment: End all Steam processes, and then without opening Steam first, launch Gmod using the desktop/start menu shortcut.
Comment: Still doesn't work, any other ideas?
Comment: Which steam process? There's loads.
Comment: The Steam processes just re-open themselves as soon as I quit them. (Sorry for being annoying)
Answer: I had the same problem as you and most of the solutions I found online didn't work for me. But I can still fix it by:
1.Open steam
2. Run Garry mod (as adminstrator) but not in steam but run the game in its file
I hope it helps you


How to Redirect on Session End

Question: I am trying to redirect user to another page when session ends.
This code will result "Object reference not set to an instance of an object." exception
void Session_End(Object sender, EventArgs E)
{
    HttpContext.Current.Response.Redirect("/");
}

any idea how to do it ?
Comment: Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints.
Comment: When you get that trigger, you do not have any contact with the user page and so the Reponse is null. Try to make some kind of javascript call to check if the user is not loose their session. Its tricky tho, because each call can trigger again the session update.
Comment: You're hooking into an event that has nothing to do with a page request, which is why your HttpContext.Current is (likely) the null reference here. What specifically do you want? Do you want to implement a logout function, or possibly detect when a user is outside of a session? Those are each different situations with different answers, each of which being different from the code above.
Comment: http://stackoverflow.com/questions/4453365/session-end-in-global-asax-cs-not-firing-using-forms-authentication ...check like forum
Comment: i want to redirect the user to the logout page
Comment: @JohnSaunders I'm pretty sure that this Null reference is pretty different from the duplicated question. You can't fix the null reference in this case !!!
Comment: Fixed with another duplicate that answers the question.
Answer: Session_End is fired internally by the server, based on an internal timer. Because of that, there is no HttpRequest associated when that happens. That is why Response.Redirect or Server.Transfer does not make sense and will not work.
I see in the past workarounds about this but never tried, you should make Base class which every page inherit. OnInit in the base class add this. Base Class inherit UI.Page. If you don't use base class logic you should add this logic to every page which is not nice.
    protected override void OnInit(System.EventArgs e)
    {
         Response.AddHeader("Refresh",Convert.ToString((Session.Timeout * 60) + 5));

         if(Session.IsNewSession)
            Response.Redirect("Logout.aspx");// or another page which you want.
    }

The page should be refreshed after 5 seconds once the Session is expired, with the if you will catch that the session is new and you will redirect.

How to Redirect on Session End


Redirecting custom button URL based on User Role/User Public Group membership

Question: I need to add some URL parameters in the Send Email button in Email related list in Case detail page.
I have added a custom detail page button with execute javascript. Below is the button code.
<code>     var loc;
     var uRoleId = UserInfo.getUserRoleId();

     if(
       "{uRoleId}" == "General Permissions Team"){
         loc = "/firstname.lastname@example.com";
         }
     else{
        loc = "/email@example.com";
         }
         window.top.location.href = loc;
</code>
Now when I click on the button , I get a javascript error that user info is not defined.
Can you help me point out whats the issue with the button code.
Answer: UserInfo is not available in JavaScript. Instead you need to use {!$UserRole.Name} to get the role.
Try this:
<code>var loc;
var uRoleName = "{!$UserRole.Name}";

if( uRoleName == "General Permissions Team"){
    loc = "/email@example.com";
}
else {
    loc = "/firstname.lastname@example.com";
}
window.top.location.href = loc;
</code>


Custom comments template in wp theme

Question: I am trying to make a custom comments template for my WordPress theme. I made a copy of the original comments template and put it in my theme folder. Then I changed the
<?php comments_template(); ?>

to
<?php comments_template( '/custom-comments.php'); ?>

Just like the codex says. But when I use the custom comments template it doesn't show up and everything after that line in the code disappears.
Is there something I've missed?
My full code:
    <?php get_header(); ?>

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php the_title(); ?>

<?php the_time('F jS, Y') ?> by <?php the_author() ?>

                <?php the_content(); ?>

                <?php wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>

<?php the_tags( 'Tags: ', ', ', ''); ?>

    <?php comments_template( '/custom-comments.php'); ?>

    <?php endwhile; endif; ?>

    <?php get_sidebar(); ?>

<?php get_footer(); ?>

Comment: I hate to ask, but is your comments file named "custom_comments.php"? Also, is the file in the root of your theme folder, or in a subdirectory?
Comment: Yes that's its name, and yes it is in the root of my theme folder.
Comment: Which template are you calling the function in?
Comment: I am calling it in single.php
Comment: Can you include the surrounding few lines of code in your question (before and after)? Your usage is correct, with the information that has been given.
Comment: There could also be some kind of syntax error in the custom comments template itself.
Comment: Not at the moment as I'm afk. Maybe I should add that I'm only testing it locally with mamp, if that makes any difference..
Comment: No I haven't changed anything in it. It is identical to the original. Maybe there's a reference to some file which is now wrong?
Comment: Please include the lines of code before and after your `comments_template( '/custom_comments.php');` call.
Comment: They are the same whether I use the original template (which works) or the custom one. could it matter anyway? I'll include them as soon as I can.
Comment: added my full code of single.php
Comment: How about the code in your *custom_comments.php*?
Comment: it's identical to the original.
Answer: If you just copy the original comments-template.php it contains
Thus tries to redeclare the same php functions.
That creates a fatal error and aborts the processing as the template is included.

Custom comments template in wp theme


BeautifulSoup consecutive blocks

Question: I am using BeautifulSoup to parse my crawled html data,
The pattern I am looking at is

....

...

The content I care about is always enclosed with div followed by a p clause. Of course there are other stand-alone  div and p tags in the html, but the p followed by div are unique patterns that I want
Help know how to achieve query consecutive tags in beautifulSoup is very appreciated
Comment: Answered by for example http://stackoverflow.com/questions/22122307/beautifulsoup-parse-span-title and many others
Answer: There are relevant .next_sibling, .next_siblings, .find_next_sibling() and .find_next_siblings() methods that can help you to locate the div and p siblings:
div = soup.find("div", id="test")
p = div.find_next_sibling("p")

You can also use the "adjacent" CSS selector:
soup.select("div#test + p")

BeautifulSoup consecutive blocks


Is my garage safe with a 30amp breaker and some odd wiring

Question: I recently bought a house and have found several things wrong and I'm trying to prioritize which to fix first. I have some very limited electrical knowledge but not enough to know if this needs to be fixed immediately or can wait. I live in Texas. I'll try to use correct terminology but no gaurantees
I went into my attic to see about adding a recepticle in my (attached) garage. I find the junction box and see that the romex is just running straight from the direction of the main breaker box over insulation and whatever else is up there no staples. This is very thick 10gauge romex.
Inside the junction box it is wire nutted to three other cables one 10gauge, and two 14gauge cables. The 10gauge is then ran to a ceiling cicle box which holds the recepticle my garage door opener is plugged into, then continues on to be spliced (using only wire nuts and electrical tape). One (14gauge) leads to a switch and the other (10 maybe 12gauge different color romex) to an outside light controlled by the switch.
Back to first junction box. The two 14 gauge romex cables are ran to 15amp recepticals on two different walls (I was wanting a recepticle on the third wall). One of these recepticles has a single red very thickly insulated regency wire ran from it to a switch and continue on to the overhead light fixture. A single white common wire (same type very thick insulated wire) is ran to the fixture from the other receptical for some reason, and no ground wire.
At the main breaker box I find the 10 gauge cable is attached to a 30amp breaker and is just ran out of a hole punched out of the bottom of the box, ran up the side of box, and into the soffit.
I need to know if there are any immediate hazards I should fix this weekend. Then what is going to need to be switched out to get to/near code. I know the electrical taped splice needs to be boxed, but the 30amp breaker i haven't a clue if it's a hazard or if its fine since only 15amp recepticals are attached. The 30amp breaker is not ground or ark fault.
Comment: Are there _any_ other loads on this circuit? Is there something that may _require_ the 30amp draw? If not, it's a simple breaker replacement to keep your wiring safe - you'll get more detailed answers as they roll in. Also, if you could indicate the color of the NM-B sheath, that'll ID the wire gauge for us. Also what is a "single red ... 'regency' wire"? Maybe include a picture of it and, in particular, any writing that may be on the wire.
Comment: Can you post a photo of the labeling on that white cable running to the garage, and also of the labeling on the inside of your breaker box's door please?
Comment: For electrical work, especially where safety is concerned, you should have an electrician inspect the wiring and tell you what needs to be done. There are a lot of little things only someone with the proper training will know about. In the mean time, I wouldn't go up into the attic (touch the outside of the roof it it's metal) unless the power is off.
Comment: @AbhiBeckert On the other hand, there's nothing wrong with learning how to DIY, which is why this site's URL is _diy_.stackexchange.com. Yes, caution needs to be used when working on electrical, but there's nothing wrong with getting good advice and doing it yourself. Without that, this site would have no reason for being. Probably the best advice is "when in doubt, ask" especially when working on electrical, and that's exactly what the OP did.
Comment: What make and model is your breaker box? (Photos help.) Also, can you provide photos of those red and white wires that are running off by themselves?
Comment: @FreeMan I didn't say hire an electrician to do the work, just have one inspect your newly purchased home and give advice on what work should be done. They will likely find things Daniel wouldn't even think to ask about.
Answer: Good diagnostic post!  You have a number of safety issues, chief of which is all those receptacles and 12/14awg wiring should not be fed by a 30A circuit breaker.  How fast you decide to fix them is up to you, but you're right that it is a fire hazard.
For example, a 14awg NM-B cable can carry 15A without exceeding a 60C design temperature (someone will surly correct me if I'm remembering the values wrong.)  The requirements for installing this type of cable (no conduit needed, okay to be in contact with insulation, etc.) are specified with that 15A in mind.  When you exceed it by using a 30A breaker, some person could plug two big space heaters into a receptacle, cause the 14awg cable to overheat, and it could start a fire, all without tripping the circuit breaker.
My suggestion is to start by replacing the 30A breaker.  If you change it to 15A the wiring you have currently (aside from the improper splices) is basically safe.  If you change to a 20A breaker you will need to upgrade the 14awg wire to 12awg.
Book recommendation
By the way, you may want a book to help you get started.  As @ThreePhase explains, there are plenty of other things you want to do to make all this safe and up to code; and it's hard to cover them all in Q&A form.  I like the Black & Decker Complete Guide to Wiring, which is available at home improvement stores and many libraries.  It's heavily-illustrated and aimed right at DIY homeowners.
Comment: I would _turn off_ the breaker immediately. Sure, it's been fine so far, but _things happen_ - that's why the breaker is there. That would be the #1 thing to do and it would be a top priority to replace it with a properly sized one immediately.
Comment: No, each pole of a two pole breaker is rated for it's marked amperage, not half for each pole. It also appears at least the top right breaker may not be a breaker UL/CSA/ETL Listed for use in that panel. The neutral (common) wire must also be the same size for most circuits, there are limited conditions for some equipment that does allow smaller neutral, but not normally found in residential buildings. Also the NM cable needs a clamp where it enters the box.
Comment: You still need to change the circuit breaker.  Half of a 30A **two-pole breaker** is 30A 120V.  A circuit connected to two poles of a double-30A breaker is a 240V 30A.  A circuit with two poles *and* a neutral is a 120V/240V 30A, meaning loads on it can use either voltage; a common configuration for clothes washers which may use 240V for the motor/heater but 120V for circuit boards to control the machine.
Comment: No other loads on this circuit. Upon closer inspection I see that the cable is only connected to one side of the breaker. Does that mean it's working as a 15amp breaker and I am in the clear there? Or do I still need to replace? Cable appears to be white. Also it looks like they extended the common wire to reach with a wire nut and smaller gauge wire. Is this ok?
Comment: Referring to the top right breaker: it is a siemens breaker, a quick search led me to believe a Siemens breaker can go in a g.e. box, is this wrong? That actually makes (a little) sense, that also being a 30 amp breaker it looks like they just moved it from the top to the bottom and wired the garage with it. Why? I havent a clue but it explains why the garage wiring is different from the rest of the house. The top right breaker goes to the dryer which is located right behind the breaker box and not in or adjacent to the garage...
Answer: That breaker needs to be 15A, for starters
Since there's 14AWG wire in the circuits, you'll have to replace that 30A breaker with a 15A breaker to give this situation any hope of being safe.  This would be the first thing I'd do, even, before fixing any other issues with the circuit.  The good news is that for most panels, a 15A breaker is readily available at the home store, although you will need to match up the labels on the breaker to the labeling on the inside front of your breaker box.  If you are having trouble matching the labeling up, the labeling on your box is missing, or your breaker box has breakers that have single tabs on the back instead of pairs of "jaws", post back and we can help you here.
Working our way along the circuit...
The easiest way to approach this once you have the breaker swapped is to work your way along the circuit from start to finish, fixing issues as you go.  We start by replacing the existing outdoor run of 10-2 NM with 10-2 or 12-2 UF, depending on if you think the garage will need more power in the future or not. This is because running NM outside isn't allowed by the NEC as ordinary NM cable isn't rated to be shone or rained on, and will wick water up its paper separator, leading to failures indoors even.  You'll also need to use a cable clamp (one of the plastic button clamps will do) where the UF run exits the bottom of the breaker box to keep the cable's jacket from being damaged by the hole as well as to provide strain relief for the cable as it enters the box.
Moving on, you'll then need to box up the open splices, as you indicate; single gang plastic old work boxes installed into the garage ceiling will work just fine for this job, although you'll want to redo the splices with fresh wire nuts of the appropriate size.  Make sure to write down which wires are connected to which before undoing the splices, though!
Finally, we get to the red and white wires standing alone, which violate several sections of the NEC.  You'll want to rip them out and replace the red wire with a proper NM-B cable, as wires by themselves need to be in a conduit or other sort of raceway to be used legally under the NEC.  At the switch box, the black wire in the new cable goes to the screw on the switch that the red wire went to, while the white wire in the new cable goes to the spare neutral screw on the receptacle, and the bare wire in the new cable gets connected to any and all existing bare wires in the box.  Don't forget to make sure the cable is clamped when running out of the box!
As you run the cable, you'll also need to make sure it's at least 1.25" back from the edge of the stud so it doesn't get nailed into by accident, and secured with a staple or clip every 4.5' as well as within 12" of the boxes at each end.  You'll also need to enlarge the hole in the top plate the old wire ran thru so that it will fit the new cable, of course.
Finally, when you reach the light box and run the cable into it (use a new cable clamp if needed), you can wire the black wire to the hot terminal or wire on the fixture, the white wire to the neutral terminal or wire on the fixture, and the bare wire to any green or bare wires from the fixture if present, as well as to a pigtail to a grounding screw into the back of the box if the box is made from metal.  Last but not least, the holes that the old white wire went through will need to be plugged with knockout plugs, replacing any cable clamps that once held the white wire in.
If you want more power to the garage...
If you want to upgrade the garage power arrangement at this point, my bet would be to run a fatter /3 cable up to a subpanel in the garage since the existing 10/2 NM run isn't salvageable anyway, then run replacement 14/2 NM off a 15A breaker from the subpanel to the existing complex.  You'll need to make sure that the bond screw is pulled, a ground bar is fitted, and neutrals and grounds are separated in the subpanel if you do this, of course.
Comment: @DanielSherwood -- what color is the jacket of the cable that runs outside? Can you provide us with any writing on that jacket, for that matter?
Comment: Ok I need to get cable clamps especially for exit of sharp breaker box. So other than that is it OK for this to be exposed to the elements and ran through the soffit like this? And across the attic like this? It has settled more into insulation then I remember. It seems like alot of the cable up there is similarly ran every which direction, not stapled... so that is acceptable if It gets stapled every 4.5 feet? This is the only instance of the white cable the rest of the house appears to be ran with a black 12 or 14awg.

I have removed the stand alone wires that say "regency wire".
Comment: Guard strips are required where cable runs over studs when permanent access exists or within 6 ft. of  scuttle access holes.
Comment: Would another option, depending upon what else one might want to do in the garage, be to move or extend the 10ga wire to a subpanel, which could then feed multiple 15A or 20A circuits?  If the panel had fed two double-receptacle yokes, each with a 15A or 20A breaker, that would make it possible for the 30A circuit to run two space heaters in the garage safely provided they were plugged into separate sub-circuits.
Comment: @supercat -- yeah, thing is, that'd require a major reroute of the existing 10AWG cable, although I'm not sure what type of cable it is (NM or UF), and that might determine whether this is a feasible option or not
Comment: The jacket color looks off white to me. The only writing I can find says "Capex 10/2 with ground".
Comment: @DanielSherwood -- can you continue to follow that writing, or does it go off somewhere inaccessible after "ground"? (I'm trying to see if it's marked as "Type ..." somewhere on it, in particular)
Comment: It repeats the same thing Capex 10/2 with ground twice then disappears. I will try to find it on a different part of the wire. Its hard to see because its lightly stamped or imprinted no ink.
Comment: Type NM-B 600 volts (UL)
Comment: @ThreePhaseEel: It might also be possible leave the existing 10ga cable going to the box where it presently splits into smaller cables, but replace those smaller cables with a 10ga cable to a new subpanel.  I'm not sure how far from the box one would have to go in order to find a place where one could put a new subpanel that was deemed adequately accessible, but having breakers near the devices they supply would seem useful, especially if there were a classification of breakers which were intended for loads that would feed subpanels, and would be designed to avoid tripping except in cases...
Comment: @supercat -- not really, since the homerun needs to be replaced anyway (due to it being NM that was improperly run outdoors, and exposed to the weather at that)
Comment: ... where the subpanel's protection failed (e.g. have it avoid tripping on any overload that lasts less than 1/60 of a second).  With regard to this particular cable, I gotcha.  Still, even if one is replacing the home run, I think it may be worth considering the possibility of a subpanel.  I know I've sometimes wished my current kitchen had a subpanel to avoid the hassle of having to go to the basement to reset the breakers, and would think someone using high-power equipment in a garage might feel similarly depending upon where their main breaker box is located.
Comment: Ok I installed a 15amp breaker under the 30 amp and moved the wire down to it leaving the 30 amp breaker there in the off position for now. Replaced first junction box and installed a gfci receptical as the first thing power runs through (getting those 10gauge wires around the terminals was a nightmare). Replaced all standalone wires with 14/2 romex. Checked all the recepticals with plug in tester and everything reads correct and gfci trips when tested. That's all I had time for this weekend but at least I can sleep a little better at night, and use a space heater if needed.
Comment: @DanielSherwood -- yeah, that corrected the most imminent hazards (overbreakering, lack of GFCI for garage receptacles, improper wiring methods, and I presume you boxed up that open splice too?).  With that done, you can start working on longer-term plans to get that exposed-to-the-elements NM homerun swapped out, and consider a subpanel for the garage while you're at it
Comment: Yes I made sure everything got boxed up, educating myself on box fill limits at the same time. W


What is the best way to measure total context switches in a C/C++ application?

Question: This is simple way I am trying to get the resource usage, specially total context switches that happen in the execution of the program.
#include<stdio.h>
#include <sys/resource.h>

int appgetrusage(struct rusage *);
int appgetdiffrusage(struct rusage *, struct rusage *);

int main() {
    struct rusage begin, end;

    appgetrusage(&begin);

/*
* core of the program goes here
* where lot of system threads are spawned and joined
*
*/

    appgetrusage(&end);
    appgetdiffrusage(&begin, &end);

    return 0;
}

int appgetrusage(struct rusage *usage){
    int who = RUSAGE_SELF;
    struct timeval start, end;
    getrusage(RUSAGE_SELF, usage);
    return 1;
}

int appgetdiffrusage(struct rusage *oldr, struct rusage *newr){

    printf("\n");
    printf("user time (ms): %llu\n",1000 * ((newr->ru_utime).tv_sec - (oldr->ru_utime).tv_sec) +
            ((newr->ru_utime).tv_usec - (oldr->ru_utime).tv_usec) / 1000);

    printf("system time (ms): %ld\n", 1000 * ((newr->ru_stime).tv_sec - (oldr->ru_stime).tv_sec) +
            ((newr->ru_stime).tv_usec - (oldr->ru_stime).tv_usec) / 1000);

    printf("voluntary context switches : %ld\n", newr->ru_nvcsw - oldr->ru_nvcsw);
    printf("involuntary context switches : %ld\n", newr->ru_nivcsw - oldr->ru_nivcsw);

    return 1;
}

Is this the right approach?
Can anybody suggest an alternative? or Corrections? :-)
Comment: Why do you care about context switches? Isn't measure the real and CPU time enough for you?
Comment: Several context switches degrades performance of the system. Involuntary context switches, for example, more in number is always bad. That means there is something terribly wrong in the underlying system or the libraries depending on
Comment: Of course, but what matters is ultimately time.... And context switches depend also of the rest of the system (not only of the application...)....
Comment: I agree! context switches depend on whole system. Since i have an issue with degraded performance of an application. I am interested to know the cause :-) http://stackoverflow.com/q/21777430/815812
Comment: What do you think about the way I am calculating the difference of context switches? Will that do to research on the issue where resource usage is more? :-)
Answer:
Can anybody suggest an alternative?

Use perf (https://perf.wiki.kernel.org/index.php/Tutorial#Counting_with_perf_stat):
perf stat your-program

Like this:
>perf stat ./my_test 2
Thread 139828421826304:
Thread 139828411336448:
^[[A./my_test: Terminated

 Performance counter stats for './my_test 2':

      74333.536760 task-clock                #    1.999 CPUs utilized
               627 context-switches          #    0.008 K/sec
                26 cpu-migrations            #    0.000 K/sec
               282 page-faults               #    0.004 K/sec
      182727508914 cycles                    #    2.458 GHz                     [50.00%]
   <not supported> stalled-cycles-frontend
   <not supported> stalled-cycles-backend
      121168605770 instructions              #    0.66  insns per cycle         [75.00%]
       30262379463 branches                  #  407.116 M/sec                   [74.99%]
           1635031 branch-misses             #    0.01% of all branches         [75.01%]

      37.181359478 seconds time elapsed

Comment: Actually I usually start comparing different versions of a library using higher level metrics. For example I send lots of requests so that my application fully utilizes CPU and then measure Req/sec. If then I see that one of them is worse than another I use perf to find where it works worse.
Comment: Thanks. Where can I find what each line mean? For example, what does 'task-clock', 'branches' mean? Any man page reference?
Comment: Task-clock - As far as I know it is execution time of all threads in your application if it is multithreaded. So if your applicaton has 2 threads running all the time and it finishes after 10 seconds then task-clock will be around 20 secs (or 20000 msec)
Comment: Ok.. Thanks! I have two apps working on different versions of library. With same number of threads spawned (5k threads). What parameters should I consider to compare the best among them? Is it the branches, or branch-misses, or instructions, or cycles? Any online resource, a detailed man page maybe, you can refer me to?
Comment: As for branches. There are two useful links: https://stackoverflow.com/questions/9820319/why-is-a-cpu-branch-instruction-slow and  https://en.wikipedia.org/wiki/Branch_%28computer_science%29
Comment: One more observation! `context-switches` in `perf stat` is the total of "voluntary" and "non-voluntary" context switches made by app. Double checked with output of getrusage().
Answer: Systemtap provides excellent facility to profile/debug user space as well as kernel codes.
https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/SystemTap_Beginners_Guide/
systemtap script for finding context switches
https://sourceware.org/systemtap/examples/process/chng_cpu.stp
In ARM, user space profiling is not yet available, because of uprobes(https://blueprints.launchpad.net/linux-linaro/+spec/arm-uprobes).  But X86, it works fine.
Answer: You guys already shared the best resources like perf and systemtap, but if anyone just don't want to look into that much depth then sysstat package coming with RHEL6 or kernels 2.6.23 and later have something called pidstat. Use pidstat with -w and it will give you total number of voluntary as well as non-voluntary context switches.


How to convert forms to xpages programatically?

Question: I need to convert Notes Form to Xpage programatically ?
If anyone knows , please help me .
Thanks in advance..
Comment: if my answer helped you can you mark it as top answer so other developers will know what to do when facing the same issue. if not can you add more details and I or others may be able to offer help
Answer: There is a transformer from GBS that does this:
http://www.gbs.com/en/GBS-Xcelerator-Suite
Or an article (not programmatic) on how to do it:
http://www-10.lotus.com/ldd/ddwiki.nsf/dx/XPages_with_large_notes_forms
However i'd look at articles like the following which are arguing whether doing something like this is missing the point of XPages or not and whether it would be a benefit to re write and gain the full advantages of XPages instead of a hybrid.
http://www.geniisoft.com/showcase.nsf/archive/20090101-0857
Comment: The primary advantage of programmatic conversion applies when you want to modernize thousands of apps rapidly without losing the existing business logic. On a per-form basis, it's always better to design the XPage manually.
Comment: +1 XPages should NOT copy forms to leverage their full potential
Comment: Thank you for your response. I will try and let you know whether it will be done or not.


Passing in a function to another function?

Question: Is it better practice to pass in a function to another function that uses it to reduce the scope look up. I am getting quite confused about this stuff.
Without passing it in;
function loadSuccess(a, b, c) {

};

function image(url, name, info) {

   var asset = new Image();
   asset.addEventListener("load", function(name, info) {
       return function() {
           loadSuccess(this, name, info);
       };
   }(name, info), false);
   asset.src = url;
};

image(a, b, c);

And passing it in;
function loadSuccess(a, b, c) {

};

function image(url, name, info, loadSuccess) {

   var asset = new Image();
   asset.addEventListener("load", function(name, info, func) {
       return function() {
           func(this, name, info);
       };
   }(name, info, loadSuccess), false);
   asset.src = url;
};

image(a, b, c, loadSuccess);

Answer: The performance benefit is probably neglegible, but passing the callback makes your function more flexible, allowing you to pass a different callback in an different situation, if needed.
However, I see a problem in your code: tt makes no sense to return anything from an asynchronous callback. It's not your image function that will be returning it, but the inner anonymous function you passed to addEventListener.
Considering those problems, I'd change the code as follows:
function loadSuccess(a, b, c) {

};

function image(url, name, info, func) {
   var asset = new Image();
   asset.addEventListener("load", function(e) {
       func(this, name, info);
   }, false);
   asset.src = url;
};

image(a, b, c, loadSuccess);

I also removed the immediately invoked function you had, as I don't see any good reason to use it there.
Comment: `function(...){...}(...)` should be wrapped in parentheses, so that the developers know it's an IIFE rather than a callback.
Comment: I didn't even notice the IIFE (which makes my previous revision wrong). Fixed both now.
Comment: Thanks for this, I had an anonymous return function in there because I was rewriting the code, it previously was in one function call in a for loop, so I had to maintain a closure so that name, and info were kept in there for each loop iteration, thanks for spotting it though as I didn't!
Comment: @user2251919 I also had the wrong parameter name in the function image, just fixed it.
Answer: Both works fine but I think it is good practice to send a callback function as an argument.
Comment: Cool, I knew both were ok, but I like to code in the standard way, thanks.
Answer: The first option is to use when the image function always  needs call this loadSucces function.
The second option is to use when you need to choose which callback function you want to execute.
There is also third option in which the fourth parameter is optionnal :
function image(url, name, info, loadSuccessParameter) {
    loadSuccessParameter= loadSuccessParameter || loadSuccess;
    [...]

}

So you can call this way : image(a, b, c) or this way : image(a, b, c, otherLoadSuccess);
I hope it helps.


Wiring ceiling light fixture with 4 wires

Question: I previously had a fan installed here. There are 4 wires in the ceiling: red; white, black, and copper.
I don't have a pic of the wiring going to the switch, but black wire connects to one switch and the red connects to the other switch. It is a regular on/off switch without a dimmer or anything
My new LED light fixture also has 4 wires: White (N); Silver (L); green ; and copper. I'm not sure what is the purpose of the green wire and whether it should be connected to Red or not? Can someone help me with how to go about this? Thank you!
Comment: Can you post photos of both the wiring in the ceiling box and at the lightswitch controlling this fixture please?
Comment: I don't have a pic of the wiring going to the switch, but black wire connects to one switch and the red connects to the other switch.  It is a regular on/off switch without a dimmer or anything
Comment: Green, Green/Yellow, or Bare is _always_ a ground wire. DO NOT attach that to any hot wiring (Black, Red, etc.)
Answer: Choose either the black or red wire (cap the other) and connect that to the wire labeled "L" (line). Connect the white wire to the wire labeled "N" (neutral). Connect the green wire from the house to both the green and bare wire from the fixture.
It looks like the bare wire is the ground to the actual lamp while the bare wire is the ground to the canopy.
Comment: Makes sense! Thank you!!!


setting must be in the form "name=value" in vs 2017

Question: I have been learning the bot framework from microsoft and have been following a tutorial on pluralsight. I have made the changes to my Global.asax.cs and for some reason I keep on getting the error setting must be in the form name=value. I have no idea what to do and how to get rid of these errors. Any help would be highly appreciated.
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {

        // This code chunk below will allow us to use table bot data store instead of
        // in memory data store
        Conversation.UpdateContainer(
            builder =>
            {
                builder.RegisterModule(new AzureModule(Assembly.GetExecutingAssembly()));
                // here we grab the storage container string from our web config and connecting
                var store = new TableBotDataStore(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                builder.Register(c => store).
                Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore).
                AsSelf().
                SingleInstance();
            });

        GlobalConfiguration.Configure(WebApiConfig.Register);

Answer: TableBotDataStore is for Azure Table Storage, and it seems you are using some sql connectionstring. You would usually have that connection string in the AppSettings section, not the ConnectionStrings section (yes, the names are a bit misguiding here).


Which icons are the easiest to read, solid or hollow?

Question: With io7, Apple made a switch in the tabbars to icons that for the most part are line based. In other places, such as their app icons they are using mostly solid icons. That made me wonder if there is any evidence on if one icon style is more readable than the other.
Answer: Evidence says there's not a significant difference between the speed of recognition for 'line-based' vs. 'filled' icons.
When it comes to icon readability (interpreting 'readability' as inverse to 'time it takes to understand') other factors are more important than style differences.
Here's an excellent, annotated article from boxesandarrows.com covering how to optimize icons for faster recognition, which covers an actual experiment done on lined-vs-filled icons. It's also got great references that include published papers in visual theory, semiotics and linguistics.
Relevant quote:

There was no noticeable difference in speed of recognition for the two
  styles. So we could suggest that, if an icon is well designed and
  represents a particular recognizable shape clearly, its style doesn't
  have a significant effect on the speed of recognition. The more
  notable difference, however, was in how individual signs relate to the
  concepts they represent–the relation of signifier to signified in
  particular signs. The icons that performed faster in both sets were
  iconic signs–'calculator,' 'camera,' 'mail.' On the other hand, the
  icons that seemed to have required a short pause were symbolic:
  'download,' 'back,' 'copy.' Even the 'delete' icon caused a slight
  delay in participants' response.

Hope that helps!


Value Error when render used (django 1.7.1)

Question: I've an error
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/accounter/apps/accounter/views.py" in unit_view
  24.     return render(request, 'accounter/unit.html', context)
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render
  48.     return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
  177.     with context_instance.push(dictionary):
File "/usr/local/lib/python2.7/dist-packages/django/template/context.py" in push
  54.         return ContextDict(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/context.py" in __init__
  19.         super(ContextDict, self).__init__(*args, **kwargs)

Exception Type: ValueError at /accounter/1/
Exception Value: dictionary update sequence element #0 has length 3; 2 is required

Also my view source code:
class ProductListView(generic.ListView):
    model = Product

    def get_queryset(self):
            return Product.objects.all()

def unit_view(request, product_id):
    context = Context({
        'product': Product.objects.get(pk=product_id).name,
        'ship_units': ShipUnit.objects.filter(product = product_id),
        'shop_units': ShopUnit.objects.filter(product = product_id),
    })
    return render(request, 'accounter/unit.html', context)

I can't figure out what the problem. I've read documentation about using of render and context, also all the examples. But cant find where is my mistake.
Answer: render is a shortcut; it doesn't take a Context object, it takes a plain dict.
context = {
    'product': Product.objects.get(pk=product_id).name,
    'ship_units': ShipUnit.objects.filter(product = product_id),
    'shop_units': ShopUnit.objects.filter(product = product_id),
}


Not use URL redirect with ForbidResult or Pass Data to Acccount AccessDenied View from ASP.NET Core and Identity

Question: 'ForbidResult' below is used, which causes a url redirect. Thus,  Context.Items["data"] is lost for the redirected page, which is /MicrosoftIdentity/Account/AccessDenied?ReturnUrl=SomeSite.
 public class PermissionAttribute : TypeFilterAttribute
    {

        private class PermissionFilter : IAsyncActionFilter
        {

            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                context.HttpContext.Items["data"] = "some data";

                var authorized = check_if_it_has_permissions();
                if (authorized)
                {
                    await next();
                }
                else
                {
                    context.Result = new ForbidResult();  //this is a url redirect using /MicrosoftIdentity/Account/AccessDenied?ReturnUrl=SomeSite
                }
            }
        }
    }

partial_view_header.cshtml

    @{
                Context.Items["data"]
     }

Is it possible to keep the current url, and not change the url to '/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=xxx', or a way to pass data to Acccount AccessDenied view?
Answer: You can try to use Session,or you can pass data with querystring,here is a demo with session:
PermissionFilter:
public class PermissionFilter : Attribute,IAsyncActionFilter
    {

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            context.HttpContext.Session.SetString("data", "some data");
            context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Account",
                    controller = "Home",
                    //data = "some data"
                }));
            return;

        }
    }

HomeController:
 [PermissionFilter]
        public IActionResult Index()
        {
            return View();
        }
public IActionResult Account() {
            TempData["data"] = HttpContext.Session.GetString("data");
            return View();
        }

Comment: you are right. But we don't want to use session and querystring. The reason is security for querystring, and for session, it is not bening used. We want to avoid session if possible.
Comment: What about use cookie?you can refer to [this](https://stackoverflow.com/questions/14956027/how-to-pass-values-across-the-pages-in-asp-net-without-using-session)?
Comment: cookie is also not safe.


Remove the limit clause from MySQL Workbench

Question: I'm running this query: select * from schema.table
but i'm only getting the first 1000 rows
i see in the output window that there was a LIMIT clause appended to my select statement. Is there a way to turn off the default limit?
Comment: What tool are you using? (i.e.: What's adding the LIMIT clause?)
Comment: It seems like you are not running the query in direct mysql prompt. Is there any tool between?
Comment: ah, i see. there's also a button to toggle the limiting. Thanks!
Comment: by the way, post an answer if you want credit.
Answer: You can toggle the LIMIT clause added by MySQL Workbench via the SQL Editor tab within the application preferences (Edit menu -> Preferences...).
Simply un-check the "Limit Rows" option within the Query Results section as pictured below.

EDIT:
In Workbench 6.0, the "Limit Rows" checkbox stands in "SQL Queries" tab (new tab of the same form).
Answer: MySQL Workbench 6.3
Option 1
Query > Limit Rows > Don't Limit

If you change the value here, it will also be updated in the path achievable via the second option.
Option 2
Edit > Preferences...

SQL Editor > SQL Execution > uncheck Limit Rows

If you change the value here, it won't be updated in the path achievable via the first option, but the new value will be considered.
Answer: In MySql Workbench 6.3 this option can be selected from the actual query window:
Answer: In MYSQL Workbench 6.0 the option can be found at Edit->Preferences->SQL Queries tab.
Answer: You can use limit all at the end of the query
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


how to test for partial continuity of a multivariable function. Also, can a partial derivative of a function be $\infty$?

Question: So, let there be a scalar function $f(x,y)$. We know that the partial derivatives exist for every $(x,y)$. In the following example we know that the function is not continuous:
$$
f(x,y) = \begin{cases}
  \dfrac{2xy}{x^2+y^2} &\text{if } (x,y) \neq (0,0), \\[2pt]
  0 &\text{if } (x,y)=(0,0).
\end{cases}
$$
How can we test for example if the partial derivative of this function with respect to $x$ is continuous?
And generally on any function how is this tested?
If we assume that a partial derivative on a multivariable function exists, can it be $\infty$?
Are there any repercussion for this statement, if true?
Comment: If it were continuous, you would have that the relation $(x_n,y_n) \to (x,y)$ implies $f(x_n,y_n) \to f(x,y)$ for every $(x,y)$ and every sequence converging to this point. Consider the origin and sequences like $x_n=y_n=1/n.$
Answer: As $f(x,0)=0$ $${\partial f\over \partial x}(0,0)={d\over dx}f(x,0)\mid_{x=0}=0$$  For $(x,y)\neq (0,0)$ we get $${\partial f\over \partial x}(x,y)= {\partial \over dx} {2xy\over x^2+y^2}=2{y^3-x^2y\over (x^2+y^2)^2}$$ Thus
$${\partial f\over \partial x}(x,y)=\begin{cases} 0 & x=y=0\\ 2{y(y^2-x^2)\over (x^2+y^2)^2} & (x,y)\neq (0,0) \end{cases}$$
Thus ${\partial f\over \partial x}$ is continuous at every point $(x,y)\neq (0,0).$ But it is not continuous at $(0,0).$ Indeed for  for $a>0$ and $y\neq 0$ we get $${\partial f\over \partial x}(ay,y)={2\over y}{1-a^2\over (1+a^2)^2}$$ Thus for $a=2$ there holds $$\lim_{y\to 0^-}{\partial f\over \partial x}(ay,y)=\infty $$ Hence ${\partial f\over \partial x}$ is not continuous at $(0,0).$


Is there a way to edit data on a text file without having to create another temporary file in Java?

Question: Suppose I've a couple of objects' values stored on a text file. In the beginning, there will be some values which will have the same value, for instance, all students by default will have 0 age. Now if I want to make an edit in the age of one student using the conventional file handling approach, I'll end up making changes to all other students who have 0 age, while writing my data onto the temporary file. Thus, I was hoping that if there is a better way to make changes to a file using file handling in java. Just to give an example of the issue at hand consider the following text file
Edsger
Dijkstra
123
72 years

Ruth
Dijkstra
12345
29 years
The line indicates a space between the age and the name. Now, my task is to construct a program where a user can change any detail, such as the First Name, surname, roll_number or the age. As you can see from the example given above, two people can share some data that is common. In this case, it is the surname. However, the roll number (123,12345) will always be unique. The problem comes when you have to change similar data. Suppose the user wants to edit the surname. Then by I would create a temporary file which would hold this data and later I would read this data with some conditions to it. So the code might look like this:
Note: This data is stored at a known location "abc.txt".
            BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
            BufferedWriter bw=new BufferedWriter(new FileWriter("Temp.txt"));
            String a=br.readLine();
             while(a!=null)
            { bw.write(a);
              bw.newLine();
              a=br.readLine();
            }
            br.close();
            bw.close();
            BufferedReader br1=new BufferedReader(new FileReader("Temp.txt"));
            BufferedWriter bw1=new BufferedWriter(new FileWriter("temp.txt"));
            String b=br1.readLine();
            while(b!=null)
                    {
            if(b.equals(requested_surname))
                        bw1.write(w);//w is the String that holds the altered surname as desired by the User, for the sake of an example say it is Euler
                        else
                        bw1.write(b);
            bw1.newLine();
            b=br1.readLine();
            }
            bw1.close();
            br1.close();
            f.delete();

As a result the Original text file "abc.txt" will show something like this:-
Edsger
Euler
123
72 years

Ruth
Euler
12345
29 years
Now this will be a bungling problem as I intend to change only Ruth's surname! I know that this is slightly different from what I initially asked, but I think that if I could target the line below "Ruth", I can make the desired changes.
Please Help...
Comment: Possible duplicate of [Modifying existing file content in Java](http://stackoverflow.com/questions/8563294/modifying-existing-file-content-in-java). Simple answer: no, unless the edit is appending data to the end of the file, or overwriting existing data.
Comment: Yes, of course you can edit in place, BUT (as @andy-turner said above) only if you are not changing the size of the file. For example, if you need to change 0 to 15, you may overwrite " 0" with "15", but you may not overwrite "0" with "15". So for this kind of edit you want your fields to have constant, not variable width. It is also possible to append to a file. Look into random access files.
Answer: File can be thought as a character array.
  char[] file    = ... // file (on disk)
  char[] newData = ... // data to be written
  int pos = ...        // the position in the file to write to
  for (i=0; i<newData.; i++) {
     file[pos+i] = newData[i];
  }

You can particularly make use of seek().
Check this out as well:
http://docs.oracle.com/javase/tutorial/essential/io/rafs.html
Answer: There are several approaches to do this.
You could store the data in a csv file, 1 line for each object:
123,Edsger,Dijkstra,72
12345,Ruth,Dijkstra,29
4567,Ruth,Euler,27

Then, on program start-up read all the objects in memory (in a structure) for easy access. On program exit or save, write everything back to the file (assuming the number of objects isn't really big - i.e. not millions).
Another way is to store every field of the object as a fixed width value:
123    Edsger      Dijkstra    72
12345  Ruth        Dijkstra    29
4567   Ruth        Euler       27

That way changes to the data can easily be written 'in place' in the file. You only have to make sure the fields don't exceed the maximum size. The number fields could even be in binary format if needed.
With fixed width, or an exact size for each object, it is easy (and faster) to look up a certain object or roll number: since the size of the objects is known, file seek can be used to jump directly to the beginning of each object - no parsing is needed.
Note: the objects don't need to be on a separate line in this case (I've done it for clarity) - but if they are, newlines (could be \r or \r\n or \n) will have to be added to the size of the objects.
Of course, searches for a certain person/object should always be done on a unique ID, in this case roll number, never on the name.